VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceVMInfo.cpp@ 28926

Last change on this file since 28926 was 28800, checked in by vboxsync, 15 years ago

Automated rebranding to Oracle copyright/license strings via filemuncher

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.4 KB
Line 
1/* $Id: VBoxServiceVMInfo.cpp 28800 2010-04-27 08:22:32Z vboxsync $ */
2/** @file
3 * VBoxService - Virtual Machine Information for the Host.
4 */
5
6/*
7 * Copyright (C) 2009-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23#ifdef RT_OS_WINDOWS
24#include <winsock2.h>
25#include <ws2tcpip.h>
26#include <windows.h>
27#include <Ntsecapi.h>
28#else
29# define __STDC_LIMIT_MACROS
30# include <arpa/inet.h>
31# include <errno.h>
32# include <netinet/in.h>
33# include <sys/ioctl.h>
34# include <sys/socket.h>
35# include <net/if.h>
36# include <unistd.h>
37# ifndef RT_OS_FREEBSD /* The header does not exist anymore since FreeBSD 9-current */
38# include <utmp.h>
39# endif
40# ifdef RT_OS_SOLARIS
41# include <sys/sockio.h>
42# endif
43#endif
44
45#include <iprt/mem.h>
46#include <iprt/thread.h>
47#include <iprt/string.h>
48#include <iprt/semaphore.h>
49#include <iprt/system.h>
50#include <iprt/time.h>
51#include <iprt/assert.h>
52#include <VBox/version.h>
53#include <VBox/VBoxGuestLib.h>
54#include "VBoxServiceInternal.h"
55#include "VBoxServiceUtils.h"
56
57
58/*******************************************************************************
59* Global Variables *
60*******************************************************************************/
61/** The vminfo interval (millseconds). */
62uint32_t g_VMInfoInterval = 0;
63/** The semaphore we're blocking on. */
64static RTSEMEVENTMULTI g_VMInfoEvent = NIL_RTSEMEVENTMULTI;
65/** The guest property service client ID. */
66static uint32_t g_VMInfoGuestPropSvcClientID = 0;
67/** Number of logged in users in OS. */
68static uint32_t g_cVMInfoLoggedInUsers = UINT32_MAX;
69
70
71/** @copydoc VBOXSERVICE::pfnPreInit */
72static DECLCALLBACK(int) VBoxServiceVMInfoPreInit(void)
73{
74 return VINF_SUCCESS;
75}
76
77
78/** @copydoc VBOXSERVICE::pfnOption */
79static DECLCALLBACK(int) VBoxServiceVMInfoOption(const char **ppszShort, int argc, char **argv, int *pi)
80{
81 int rc = -1;
82 if (ppszShort)
83 /* no short options */;
84 else if (!strcmp(argv[*pi], "--vminfo-interval"))
85 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
86 &g_VMInfoInterval, 1, UINT32_MAX - 1);
87 return rc;
88}
89
90
91/** @copydoc VBOXSERVICE::pfnInit */
92static DECLCALLBACK(int) VBoxServiceVMInfoInit(void)
93{
94 /*
95 * If not specified, find the right interval default.
96 * Then create the event sem to block on.
97 */
98 if (!g_VMInfoInterval)
99 g_VMInfoInterval = g_DefaultInterval * 1000;
100 if (!g_VMInfoInterval)
101 g_VMInfoInterval = 10 * 1000;
102
103 int rc = RTSemEventMultiCreate(&g_VMInfoEvent);
104 AssertRCReturn(rc, rc);
105
106#ifdef RT_OS_WINDOWS
107 /* Get function pointers. */
108 HMODULE hKernel32 = LoadLibrary("kernel32");
109 if (hKernel32 != NULL)
110 {
111 g_pfnWTSGetActiveConsoleSessionId = (PFNWTSGETACTIVECONSOLESESSIONID)GetProcAddress(hKernel32, "WTSGetActiveConsoleSessionId");
112 FreeLibrary(hKernel32);
113 }
114#endif
115
116 rc = VbglR3GuestPropConnect(&g_VMInfoGuestPropSvcClientID);
117 if (RT_SUCCESS(rc))
118 VBoxServiceVerbose(3, "Property Service Client ID: %#x\n", g_VMInfoGuestPropSvcClientID);
119 else
120 {
121 VBoxServiceError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
122 RTSemEventMultiDestroy(g_VMInfoEvent);
123 g_VMInfoEvent = NIL_RTSEMEVENTMULTI;
124 }
125
126 return rc;
127}
128
129
130/**
131 * Writes the properties that won't change while the service is running.
132 *
133 * Errors are ignored.
134 */
135static void VBoxServiceVMInfoWriteFixedProperties(void)
136{
137 /*
138 * First get OS information that won't change.
139 */
140 char szInfo[256];
141 int rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szInfo, sizeof(szInfo));
142 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Product",
143 "%s", RT_FAILURE(rc) ? "" : szInfo);
144
145 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szInfo, sizeof(szInfo));
146 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Release",
147 "%s", RT_FAILURE(rc) ? "" : szInfo);
148
149 rc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szInfo, sizeof(szInfo));
150 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Version",
151 "%s", RT_FAILURE(rc) ? "" : szInfo);
152
153 rc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szInfo, sizeof(szInfo));
154 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/ServicePack",
155 "%s", RT_FAILURE(rc) ? "" : szInfo);
156
157 /*
158 * Retrieve version information about Guest Additions and installed files (components).
159 */
160 char *pszAddVer;
161 char *pszAddRev;
162 rc = VbglR3GetAdditionsVersion(&pszAddVer, &pszAddRev);
163 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Version",
164 "%s", RT_FAILURE(rc) ? "" : pszAddVer);
165 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Revision",
166 "%s", RT_FAILURE(rc) ? "" : pszAddRev);
167 if (RT_SUCCESS(rc))
168 {
169 RTStrFree(pszAddVer);
170 RTStrFree(pszAddRev);
171 }
172
173#ifdef RT_OS_WINDOWS
174 /*
175 * Do windows specific properties.
176 */
177 char *pszInstDir;
178 rc = VbglR3GetAdditionsInstallationPath(&pszInstDir);
179 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/InstallDir",
180 "%s", RT_FAILURE(rc) ? "" : pszInstDir);
181 if (RT_SUCCESS(rc))
182 RTStrFree(pszInstDir);
183
184 VBoxServiceWinGetComponentVersions(g_VMInfoGuestPropSvcClientID);
185#endif
186}
187
188
189/** @copydoc VBOXSERVICE::pfnWorker */
190DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
191{
192 int rc = VINF_SUCCESS;
193
194 /*
195 * Tell the control thread that it can continue
196 * spawning services.
197 */
198 RTThreadUserSignal(RTThreadSelf());
199
200#ifdef RT_OS_WINDOWS
201 /* Required for network information (must be called per thread). */
202 WSADATA wsaData;
203 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
204 VBoxServiceError("WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
205#endif /* RT_OS_WINDOWS */
206
207 /*
208 * Write the fixed properties first.
209 */
210 VBoxServiceVMInfoWriteFixedProperties();
211
212 /*
213 * Now enter the loop retrieving runtime data continuously.
214 */
215 unsigned cErrors = 0;
216 for (;;)
217 {
218/** @todo r=bird: split this code up into functions!! */
219 /* Enumerate logged in users. */
220 uint32_t cUsersInList = 0;
221 char szUserList[4096] = {0};
222
223#ifdef RT_OS_WINDOWS
224# ifndef TARGET_NT4
225 PLUID paSessions = NULL;
226 ULONG cSession = 0;
227 NTSTATUS r = 0;
228
229 /* This function can report stale or orphaned interactive logon sessions
230 of already logged off users (especially in Windows 2000). */
231 r = ::LsaEnumerateLogonSessions(&cSession, &paSessions);
232 VBoxServiceVerbose(3, "Users: Found %ld users.\n", cSession);
233 if (r != STATUS_SUCCESS)
234 {
235 VBoxServiceError("LsaEnumerate failed %lu\n", LsaNtStatusToWinError(r));
236 return 1;
237 }
238
239 PVBOXSERVICEVMINFOPROC paProcs;
240 DWORD cProcs;
241 rc = VBoxServiceVMInfoWinProcessesEnumerate(&paProcs, &cProcs);
242 if (RT_SUCCESS(rc))
243 {
244 for (ULONG i = 0; i < cSession; i++)
245 {
246 VBOXSERVICEVMINFOUSER UserInfo;
247 if ( VBoxServiceVMInfoWinIsLoggedIn(&UserInfo, &paSessions[i])
248 && VBoxServiceVMInfoWinSessionHasProcesses(&paSessions[i], paProcs, cProcs))
249 {
250 if (cUsersInList > 0)
251 strcat(szUserList, ",");
252
253 cUsersInList++;
254
255 char *pszTemp;
256 int rc2 = RTUtf16ToUtf8(UserInfo.wszUser, &pszTemp);
257 if (RT_SUCCESS(rc2))
258 {
259 strcat(szUserList, pszTemp);
260 RTMemFree(pszTemp);
261 }
262 else
263 strcat(szUserList, "<string-convertion-error>");
264 }
265 }
266 VBoxServiceVMInfoWinProcessesFree(paProcs);
267 }
268
269 ::LsaFreeReturnBuffer(paSessions);
270# endif /* TARGET_NT4 */
271#elif defined(RT_OS_FREEBSD)
272 /** @todo FreeBSD: Port logged on user info retrival. */
273#elif defined(RT_OS_OS2)
274 /** @todo OS/2: Port logged on (LAN/local/whatever) user info retrival. */
275#else
276 rc = utmpname(UTMP_FILE);
277# ifdef RT_OS_SOLARIS
278 if (rc != 1)
279# else
280 if (rc != 0)
281# endif
282 {
283 VBoxServiceError("Could not set UTMP file! Error: %ld\n", errno);
284 }
285 setutent();
286 utmp *ut_user;
287 while ((ut_user = getutent()))
288 {
289 /* Make sure we don't add user names which are not
290 * part of type USER_PROCESS and don't add same users twice. */
291 if ( ut_user->ut_type == USER_PROCESS
292 && strstr(szUserList, ut_user->ut_user) == NULL)
293 {
294 /** @todo Do we really want to filter out double user names? (Same user logged in twice)
295 * bird: If we do, then we must add checks for buffer overflows here! */
296 /** @todo r=bird: strstr will filtering out users with similar names. For
297 * example: smith, smithson, joesmith and bobsmith */
298 if (cUsersInList > 0)
299 strcat(szUserList, ",");
300 strcat(szUserList, ut_user->ut_user);
301 cUsersInList++;
302 }
303 }
304 endutent();
305#endif /* !RT_OS_WINDOWS */
306
307 if (cUsersInList > 0)
308 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", "%s", szUserList);
309 else
310 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", NULL);
311 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/LoggedInUsers", "%u", cUsersInList);
312 if ( g_cVMInfoLoggedInUsers != cUsersInList
313 || g_cVMInfoLoggedInUsers == UINT32_MAX)
314 {
315 /* Update this property ONLY if there is a real change from no users to
316 * users or vice versa. The only exception is that the initialization
317 * forces an update, but only once. This ensures consistent property
318 * settings even if the VM aborted previously. */
319 if (cUsersInList == 0)
320 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers", "true");
321 else if (g_cVMInfoLoggedInUsers == 0)
322 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers", "false");
323 }
324 g_cVMInfoLoggedInUsers = cUsersInList;
325
326 /*
327 * Get network configuration.
328 */
329 /** @todo Throw this code into a separate function/module? */
330 int nNumInterfaces = 0;
331#ifdef RT_OS_WINDOWS
332 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
333 if (sd == SOCKET_ERROR) /* Socket invalid. */
334 {
335 VBoxServiceError("Failed to get a socket: Error %d\n", WSAGetLastError());
336 return -1;
337 }
338
339 INTERFACE_INFO InterfaceList[20] = {0};
340 unsigned long nBytesReturned = 0;
341 if (WSAIoctl(sd,
342 SIO_GET_INTERFACE_LIST,
343 0,
344 0,
345 &InterfaceList,
346 sizeof(InterfaceList),
347 &nBytesReturned,
348 0,
349 0) == SOCKET_ERROR)
350 {
351 VBoxServiceError("Failed to WSAIoctl() on socket: Error: %d\n", WSAGetLastError());
352 return -1;
353 }
354 nNumInterfaces = nBytesReturned / sizeof(INTERFACE_INFO);
355#else
356 int sd = socket(AF_INET, SOCK_DGRAM, 0);
357 if (sd < 0) /* Socket invalid. */
358 {
359 VBoxServiceError("Failed to get a socket: Error %d\n", errno);
360 return -1;
361 }
362
363 ifconf ifcfg;
364 char buffer[1024] = {0};
365 ifcfg.ifc_len = sizeof(buffer);
366 ifcfg.ifc_buf = buffer;
367 if (ioctl(sd, SIOCGIFCONF, &ifcfg) < 0)
368 {
369 VBoxServiceError("Failed to ioctl(SIOCGIFCONF) on socket: Error %d\n", errno);
370 return -1;
371 }
372
373 ifreq* ifrequest = ifcfg.ifc_req;
374 ifreq *ifreqitem = NULL;
375 nNumInterfaces = ifcfg.ifc_len / sizeof(ifreq);
376#endif
377 char szPropPath [FILENAME_MAX];
378 int iCurIface = 0;
379
380 /*
381 * This property is a beacon which is _always_ written, even if the network configuration
382 * does not change. If this property is missing, the host assumes that all other GuestInfo
383 * properties are no longer valid.
384 */
385 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/Net/Count", "%d",
386 nNumInterfaces > 1 ? nNumInterfaces-1 : 0);
387
388 /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
389 for (int i = 0; i < nNumInterfaces; ++i)
390 {
391 sockaddr_in *pAddress;
392 u_long nFlags = 0;
393#ifdef RT_OS_WINDOWS
394 if (InterfaceList[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
395 continue;
396 nFlags = InterfaceList[i].iiFlags;
397 pAddress = (sockaddr_in *)&(InterfaceList[i].iiAddress);
398#else
399 if (ioctl(sd, SIOCGIFFLAGS, &ifrequest[i]) < 0)
400 {
401 VBoxServiceError("Failed to ioctl(SIOCGIFFLAGS) on socket: Error %d\n", errno);
402 return -1;
403 }
404 if (ifrequest[i].ifr_flags & IFF_LOOPBACK) /* Skip loopback device. */
405 continue;
406 nFlags = ifrequest[i].ifr_flags;
407 pAddress = ((sockaddr_in *)&ifrequest[i].ifr_addr);
408#endif
409 Assert(pAddress);
410 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%d/V4/IP", iCurIface);
411 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
412
413#ifdef RT_OS_WINDOWS
414 pAddress = (sockaddr_in *) & (InterfaceList[i].iiBroadcastAddress);
415#else
416 if (ioctl(sd, SIOCGIFBRDADDR, &ifrequest[i]) < 0)
417 {
418 VBoxServiceError("Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %d\n", errno);
419 return -1;
420 }
421 pAddress = (sockaddr_in *)&ifrequest[i].ifr_broadaddr;
422#endif
423 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%d/V4/Broadcast", iCurIface);
424 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
425
426#ifdef RT_OS_WINDOWS
427 pAddress = (sockaddr_in *)&(InterfaceList[i].iiNetmask);
428#else
429 if (ioctl(sd, SIOCGIFNETMASK, &ifrequest[i]) < 0)
430 {
431 VBoxServiceError("Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %d\n", errno);
432 return -1;
433 }
434 #if defined(RT_OS_FREEBSD) || defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
435 pAddress = (sockaddr_in *)&ifrequest[i].ifr_addr;
436 #else
437 pAddress = (sockaddr_in *)&ifrequest[i].ifr_netmask;
438 #endif
439
440#endif
441 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%d/V4/Netmask", iCurIface);
442 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
443
444 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%d/Status", iCurIface);
445 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, szPropPath,
446 nFlags & IFF_UP ? "Up" : "Down");
447
448 iCurIface++;
449 }
450 if (sd >= 0)
451#ifdef RT_OS_WINDOWS
452 closesocket(sd);
453#else
454 close(sd);
455#endif
456
457 /*
458 * Block for a while.
459 *
460 * The event semaphore takes care of ignoring interruptions and it
461 * allows us to implement service wakeup later.
462 */
463 if (*pfShutdown)
464 break;
465 int rc2 = RTSemEventMultiWait(g_VMInfoEvent, g_VMInfoInterval);
466 if (*pfShutdown)
467 break;
468 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
469 {
470 VBoxServiceError("RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
471 rc = rc2;
472 break;
473 }
474 }
475
476#ifdef RT_OS_WINDOWS
477 WSACleanup();
478#endif
479
480 return rc;
481}
482
483
484/** @copydoc VBOXSERVICE::pfnStop */
485static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
486{
487 RTSemEventMultiSignal(g_VMInfoEvent);
488}
489
490
491/** @copydoc VBOXSERVICE::pfnTerm */
492static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
493{
494 int rc;
495
496 if (g_VMInfoEvent != NIL_RTSEMEVENTMULTI)
497 {
498 /** @todo temporary solution: Zap all values which are not valid
499 * anymore when VM goes down (reboot/shutdown ). Needs to
500 * be replaced with "temporary properties" later.
501 *
502 * One idea is to introduce a (HGCM-)session guest property
503 * flag meaning that a guest property is only valid as long
504 * as the HGCM session isn't closed (e.g. guest application
505 * terminates).
506 */
507 rc = VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", NULL);
508 rc = VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/LoggedInUsers", "%d", 0);
509 if (g_cVMInfoLoggedInUsers > 0)
510 VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers", "true");
511
512 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
513 rc = VbglR3GuestPropDelSet(g_VMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
514 rc = VBoxServiceWritePropF(g_VMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/Net/Count", "%d", 0);
515
516 /* Disconnect from guest properties service. */
517 rc = VbglR3GuestPropDisconnect(g_VMInfoGuestPropSvcClientID);
518 if (RT_FAILURE(rc))
519 VBoxServiceError("Failed to disconnect from guest property service! Error: %Rrc\n", rc);
520 g_VMInfoGuestPropSvcClientID = 0;
521
522
523 RTSemEventMultiDestroy(g_VMInfoEvent);
524 g_VMInfoEvent = NIL_RTSEMEVENTMULTI;
525 }
526}
527
528
529/**
530 * The 'vminfo' service description.
531 */
532VBOXSERVICE g_VMInfo =
533{
534 /* pszName. */
535 "vminfo",
536 /* pszDescription. */
537 "Virtual Machine Information",
538 /* pszUsage. */
539 "[--vminfo-interval <ms>]"
540 ,
541 /* pszOptions. */
542 " --vminfo-interval Specifies the interval at which to retrieve the\n"
543 " VM information. The default is 10000 ms.\n"
544 ,
545 /* methods */
546 VBoxServiceVMInfoPreInit,
547 VBoxServiceVMInfoOption,
548 VBoxServiceVMInfoInit,
549 VBoxServiceVMInfoWorker,
550 VBoxServiceVMInfoStop,
551 VBoxServiceVMInfoTerm
552};
553
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette