VirtualBox

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

Last change on this file since 42154 was 42154, checked in by vboxsync, 13 years ago

VS2010 preps.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.3 KB
Line 
1/* $Id: VBoxServiceVMInfo.cpp 42154 2012-07-13 23:00:53Z 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.215389.xyz. 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# ifdef TARGET_NT4 /* HACK ALERT! PMIB_IPSTATS undefined if 0x0400 with newer SDKs. */
25# undef _WIN32_WINNT
26# define _WIN32_WINNT 0x0500
27# endif
28# include <winsock2.h>
29# include <iphlpapi.h>
30# include <ws2tcpip.h>
31# include <windows.h>
32# include <Ntsecapi.h>
33#else
34# define __STDC_LIMIT_MACROS
35# include <arpa/inet.h>
36# include <errno.h>
37# include <netinet/in.h>
38# include <sys/ioctl.h>
39# include <sys/socket.h>
40# include <net/if.h>
41# include <unistd.h>
42# ifndef RT_OS_OS2
43# ifndef RT_OS_FREEBSD
44# include <utmpx.h> /* @todo FreeBSD 9 should have this. */
45# endif
46# endif
47# ifdef RT_OS_SOLARIS
48# include <sys/sockio.h>
49# include <net/if_arp.h>
50# endif
51# ifdef RT_OS_FREEBSD
52# include <ifaddrs.h> /* getifaddrs, freeifaddrs */
53# include <net/if_dl.h> /* LLADDR */
54# include <netdb.h> /* getnameinfo */
55# endif
56#endif
57
58#include <iprt/mem.h>
59#include <iprt/thread.h>
60#include <iprt/string.h>
61#include <iprt/semaphore.h>
62#include <iprt/system.h>
63#include <iprt/time.h>
64#include <iprt/assert.h>
65#include <VBox/version.h>
66#include <VBox/VBoxGuestLib.h>
67#include "VBoxServiceInternal.h"
68#include "VBoxServiceUtils.h"
69#include "VBoxServicePropCache.h"
70
71
72/*******************************************************************************
73* Global Variables *
74*******************************************************************************/
75/** The vminfo interval (milliseconds). */
76static uint32_t g_cMsVMInfoInterval = 0;
77/** The semaphore we're blocking on. */
78static RTSEMEVENTMULTI g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
79/** The guest property service client ID. */
80static uint32_t g_uVMInfoGuestPropSvcClientID = 0;
81/** Number of logged in users in OS. */
82static uint32_t g_cVMInfoLoggedInUsers = UINT32_MAX;
83/** The guest property cache. */
84static VBOXSERVICEVEPROPCACHE g_VMInfoPropCache;
85/** The VM session ID. Changes whenever the VM is restored or reset. */
86static uint64_t g_idVMInfoSession;
87
88
89
90/**
91 * Signals the event so that a re-enumeration of VM-specific
92 * information (like logged in users) can happen.
93 *
94 * @return IPRT status code.
95 */
96int VBoxServiceVMInfoSignal(void)
97{
98 /* Trigger a re-enumeration of all logged-in users by unblocking
99 * the multi event semaphore of the VMInfo thread. */
100 if (g_hVMInfoEvent)
101 return RTSemEventMultiSignal(g_hVMInfoEvent);
102
103 return VINF_SUCCESS;
104}
105
106
107/** @copydoc VBOXSERVICE::pfnPreInit */
108static DECLCALLBACK(int) VBoxServiceVMInfoPreInit(void)
109{
110 return VINF_SUCCESS;
111}
112
113
114/** @copydoc VBOXSERVICE::pfnOption */
115static DECLCALLBACK(int) VBoxServiceVMInfoOption(const char **ppszShort, int argc, char **argv, int *pi)
116{
117 int rc = -1;
118 if (ppszShort)
119 /* no short options */;
120 else if (!strcmp(argv[*pi], "--vminfo-interval"))
121 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
122 &g_cMsVMInfoInterval, 1, UINT32_MAX - 1);
123 return rc;
124}
125
126
127/** @copydoc VBOXSERVICE::pfnInit */
128static DECLCALLBACK(int) VBoxServiceVMInfoInit(void)
129{
130 /*
131 * If not specified, find the right interval default.
132 * Then create the event sem to block on.
133 */
134 if (!g_cMsVMInfoInterval)
135 g_cMsVMInfoInterval = g_DefaultInterval * 1000;
136 if (!g_cMsVMInfoInterval)
137 g_cMsVMInfoInterval = 10 * 1000;
138
139 int rc = RTSemEventMultiCreate(&g_hVMInfoEvent);
140 AssertRCReturn(rc, rc);
141
142 VbglR3GetSessionId(&g_idVMInfoSession);
143 /* The status code is ignored as this information is not available with VBox < 3.2.10. */
144
145 rc = VbglR3GuestPropConnect(&g_uVMInfoGuestPropSvcClientID);
146 if (RT_SUCCESS(rc))
147 VBoxServiceVerbose(3, "VMInfo: Property Service Client ID: %#x\n", g_uVMInfoGuestPropSvcClientID);
148 else
149 {
150 /* If the service was not found, we disable this service without
151 causing VBoxService to fail. */
152 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
153 {
154 VBoxServiceVerbose(0, "VMInfo: Guest property service is not available, disabling the service\n");
155 rc = VERR_SERVICE_DISABLED;
156 }
157 else
158 VBoxServiceError("VMInfo: Failed to connect to the guest property service! Error: %Rrc\n", rc);
159 RTSemEventMultiDestroy(g_hVMInfoEvent);
160 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
161 }
162
163 if (RT_SUCCESS(rc))
164 {
165 VBoxServicePropCacheCreate(&g_VMInfoPropCache, g_uVMInfoGuestPropSvcClientID);
166
167 /*
168 * Declare some guest properties with flags and reset values.
169 */
170 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList",
171 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, NULL /* Delete on exit */);
172 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsers",
173 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "0");
174 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
175 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "true");
176 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/Net/Count",
177 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_ALWAYS_UPDATE, NULL /* Delete on exit */);
178 }
179 return rc;
180}
181
182
183/**
184 * Writes the properties that won't change while the service is running.
185 *
186 * Errors are ignored.
187 */
188static void vboxserviceVMInfoWriteFixedProperties(void)
189{
190 /*
191 * First get OS information that won't change.
192 */
193 char szInfo[256];
194 int rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szInfo, sizeof(szInfo));
195 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Product",
196 "%s", RT_FAILURE(rc) ? "" : szInfo);
197
198 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szInfo, sizeof(szInfo));
199 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Release",
200 "%s", RT_FAILURE(rc) ? "" : szInfo);
201
202 rc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szInfo, sizeof(szInfo));
203 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Version",
204 "%s", RT_FAILURE(rc) ? "" : szInfo);
205
206 rc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szInfo, sizeof(szInfo));
207 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/ServicePack",
208 "%s", RT_FAILURE(rc) ? "" : szInfo);
209
210 /*
211 * Retrieve version information about Guest Additions and installed files (components).
212 */
213 char *pszAddVer;
214 char *pszAddVerExt;
215 char *pszAddRev;
216 rc = VbglR3GetAdditionsVersion(&pszAddVer, &pszAddVerExt, &pszAddRev);
217 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Version",
218 "%s", RT_FAILURE(rc) ? "" : pszAddVer);
219 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VersionExt",
220 "%s", RT_FAILURE(rc) ? "" : pszAddVerExt);
221 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Revision",
222 "%s", RT_FAILURE(rc) ? "" : pszAddRev);
223 if (RT_SUCCESS(rc))
224 {
225 RTStrFree(pszAddVer);
226 RTStrFree(pszAddVerExt);
227 RTStrFree(pszAddRev);
228 }
229
230#ifdef RT_OS_WINDOWS
231 /*
232 * Do windows specific properties.
233 */
234 char *pszInstDir;
235 rc = VbglR3GetAdditionsInstallationPath(&pszInstDir);
236 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/InstallDir",
237 "%s", RT_FAILURE(rc) ? "" : pszInstDir);
238 if (RT_SUCCESS(rc))
239 RTStrFree(pszInstDir);
240
241 VBoxServiceWinGetComponentVersions(g_uVMInfoGuestPropSvcClientID);
242#endif
243}
244
245
246/**
247 * Provide information about active users.
248 */
249static int vboxserviceVMInfoWriteUsers(void)
250{
251 int rc = VINF_SUCCESS;
252 char *pszUserList = NULL;
253 uint32_t cUsersInList = 0;
254
255#ifdef RT_OS_WINDOWS
256# ifndef TARGET_NT4
257 rc = VBoxServiceVMInfoWinWriteUsers(&pszUserList, &cUsersInList);
258# else
259 rc = VERR_NOT_IMPLEMENTED;
260# endif
261
262#elif defined(RT_OS_FREEBSD)
263 /** @todo FreeBSD: Port logged on user info retrieval.
264 * However, FreeBSD 9 supports utmpx, so we could use the code
265 * block below (?). */
266 rc = VERR_NOT_IMPLEMENTED;
267
268#elif defined(RT_OS_OS2)
269 /** @todo OS/2: Port logged on (LAN/local/whatever) user info retrieval. */
270 rc = VERR_NOT_IMPLEMENTED;
271
272#else
273 setutxent();
274 utmpx *ut_user;
275 uint32_t cListSize = 32;
276
277 /* Allocate a first array to hold 32 users max. */
278 char **papszUsers = (char **)RTMemAllocZ(cListSize * sizeof(char *));
279 if (papszUsers == NULL)
280 rc = VERR_NO_MEMORY;
281
282 /* Process all entries in the utmp file. */
283 while ( (ut_user = getutxent())
284 && RT_SUCCESS(rc))
285 {
286 VBoxServiceVerbose(4, "Found logged in user \"%s\"\n",
287 ut_user->ut_user);
288 if (cUsersInList > cListSize)
289 {
290 cListSize += 32;
291 void *pvNew = RTMemRealloc(papszUsers, cListSize * sizeof(char*));
292 AssertPtrBreakStmt(pvNew, cListSize -= 32);
293 papszUsers = (char **)pvNew;
294 }
295
296 /* Make sure we don't add user names which are not
297 * part of type USER_PROCESS. */
298 if (ut_user->ut_type == USER_PROCESS)
299 {
300 bool fFound = false;
301 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
302 fFound = strcmp(papszUsers[i], ut_user->ut_user) == 0;
303
304 if (!fFound)
305 {
306 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ut_user->ut_user);
307 if (RT_FAILURE(rc))
308 break;
309 cUsersInList++;
310 }
311 }
312 }
313
314 /* Calc the string length. */
315 size_t cchUserList = 0;
316 for (uint32_t i = 0; i < cUsersInList; i++)
317 cchUserList += (i != 0) + strlen(papszUsers[i]);
318
319 /* Build the user list. */
320 rc = RTStrAllocEx(&pszUserList, cchUserList + 1);
321 if (RT_SUCCESS(rc))
322 {
323 char *psz = pszUserList;
324 for (uint32_t i = 0; i < cUsersInList; i++)
325 {
326 if (i != 0)
327 *psz++ = ',';
328 size_t cch = strlen(papszUsers[i]);
329 memcpy(psz, papszUsers[i], cch);
330 psz += cch;
331 }
332 *psz = '\0';
333 }
334
335 /* Cleanup. */
336 for (uint32_t i = 0; i < cUsersInList; i++)
337 RTStrFree(papszUsers[i]);
338 RTMemFree(papszUsers);
339
340 endutxent(); /* Close utmpx file. */
341#endif
342 Assert(RT_FAILURE(rc) || cUsersInList == 0 || (pszUserList && *pszUserList));
343
344 /* If the user enumeration above failed, reset the user count to 0 except
345 * we didn't have enough memory anymore. In that case we want to preserve
346 * the previous user count in order to not confuse third party tools which
347 * rely on that count. */
348 if (RT_FAILURE(rc))
349 {
350 if (rc == VERR_NO_MEMORY)
351 {
352 static int s_iVMInfoBitchedOOM = 0;
353 if (s_iVMInfoBitchedOOM++ < 3)
354 VBoxServiceVerbose(0, "Warning: Not enough memory available to enumerate users! Keeping old value (%u)\n",
355 g_cVMInfoLoggedInUsers);
356 cUsersInList = g_cVMInfoLoggedInUsers;
357 }
358 else
359 cUsersInList = 0;
360 }
361
362 VBoxServiceVerbose(4, "cUsersInList: %u, pszUserList: %s, rc=%Rrc\n",
363 cUsersInList, pszUserList ? pszUserList : "<NULL>", rc);
364
365 if (pszUserList && cUsersInList > 0)
366 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", "%s", pszUserList);
367 else
368 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", NULL);
369 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsers", "%u", cUsersInList);
370 if (g_cVMInfoLoggedInUsers != cUsersInList)
371 {
372 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
373 cUsersInList == 0 ? "true" : "false");
374 g_cVMInfoLoggedInUsers = cUsersInList;
375 }
376 if (RT_SUCCESS(rc) && pszUserList)
377 RTStrFree(pszUserList);
378 return rc;
379}
380
381
382/**
383 * Provide information about the guest network.
384 */
385static int vboxserviceVMInfoWriteNetwork(void)
386{
387 int rc = VINF_SUCCESS;
388 uint32_t cIfacesReport = 0;
389 char szPropPath[256];
390
391#ifdef RT_OS_WINDOWS
392 IP_ADAPTER_INFO *pAdpInfo = NULL;
393
394# ifndef TARGET_NT4
395 ULONG cbAdpInfo = sizeof(*pAdpInfo);
396 pAdpInfo = (IP_ADAPTER_INFO *)RTMemAlloc(cbAdpInfo);
397 if (!pAdpInfo)
398 {
399 VBoxServiceError("VMInfo/Network: Failed to allocate IP_ADAPTER_INFO\n");
400 return VERR_NO_MEMORY;
401 }
402 DWORD dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
403 if (dwRet == ERROR_BUFFER_OVERFLOW)
404 {
405 IP_ADAPTER_INFO *pAdpInfoNew = (IP_ADAPTER_INFO*)RTMemRealloc(pAdpInfo, cbAdpInfo);
406 if (pAdpInfoNew)
407 {
408 pAdpInfo = pAdpInfoNew;
409 dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
410 }
411 }
412 else if (dwRet == ERROR_NO_DATA)
413 {
414 VBoxServiceVerbose(3, "VMInfo/Network: No network adapters available\n");
415
416 /* If no network adapters available / present in the
417 * system we pretend success to not bail out too early. */
418 dwRet = ERROR_SUCCESS;
419 }
420
421 if (dwRet != ERROR_SUCCESS)
422 {
423 if (pAdpInfo)
424 RTMemFree(pAdpInfo);
425 VBoxServiceError("VMInfo/Network: Failed to get adapter info: Error %d\n", dwRet);
426 return RTErrConvertFromWin32(dwRet);
427 }
428# endif /* !TARGET_NT4 */
429
430 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
431 if (sd == SOCKET_ERROR) /* Socket invalid. */
432 {
433 int wsaErr = WSAGetLastError();
434 /* Don't complain/bail out with an error if network stack is not up; can happen
435 * on NT4 due to start up when not connected shares dialogs pop up. */
436 if (WSAENETDOWN == wsaErr)
437 {
438 VBoxServiceVerbose(0, "VMInfo/Network: Network is not up yet.\n");
439 wsaErr = VINF_SUCCESS;
440 }
441 else
442 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %d\n", wsaErr);
443 if (pAdpInfo)
444 RTMemFree(pAdpInfo);
445 return RTErrConvertFromWin32(wsaErr);
446 }
447
448 INTERFACE_INFO InterfaceList[20] = {0};
449 unsigned long nBytesReturned = 0;
450 if (WSAIoctl(sd,
451 SIO_GET_INTERFACE_LIST,
452 0,
453 0,
454 &InterfaceList,
455 sizeof(InterfaceList),
456 &nBytesReturned,
457 0,
458 0) == SOCKET_ERROR)
459 {
460 VBoxServiceError("VMInfo/Network: Failed to WSAIoctl() on socket: Error: %d\n", WSAGetLastError());
461 if (pAdpInfo)
462 RTMemFree(pAdpInfo);
463 return RTErrConvertFromWin32(WSAGetLastError());
464 }
465 int cIfacesSystem = nBytesReturned / sizeof(INTERFACE_INFO);
466
467 /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
468 for (int i = 0; i < cIfacesSystem; ++i)
469 {
470 sockaddr_in *pAddress;
471 u_long nFlags = 0;
472 if (InterfaceList[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
473 continue;
474 nFlags = InterfaceList[i].iiFlags;
475 pAddress = (sockaddr_in *)&(InterfaceList[i].iiAddress);
476 Assert(pAddress);
477 char szIp[32];
478 RTStrPrintf(szIp, sizeof(szIp), "%s", inet_ntoa(pAddress->sin_addr));
479 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
480 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szIp);
481
482 pAddress = (sockaddr_in *) & (InterfaceList[i].iiBroadcastAddress);
483 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
484 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
485
486 pAddress = (sockaddr_in *)&(InterfaceList[i].iiNetmask);
487 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
488 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
489
490 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
491 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, nFlags & IFF_UP ? "Up" : "Down");
492
493# ifndef TARGET_NT4
494 IP_ADAPTER_INFO *pAdp;
495 for (pAdp = pAdpInfo; pAdp; pAdp = pAdp->Next)
496 if (!strcmp(pAdp->IpAddressList.IpAddress.String, szIp))
497 break;
498
499 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
500 if (pAdp)
501 {
502 char szMac[32];
503 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
504 pAdp->Address[0], pAdp->Address[1], pAdp->Address[2],
505 pAdp->Address[3], pAdp->Address[4], pAdp->Address[5]);
506 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
507 }
508 else
509 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, NULL);
510# endif /* !TARGET_NT4 */
511
512 cIfacesReport++;
513 }
514 if (pAdpInfo)
515 RTMemFree(pAdpInfo);
516 if (sd >= 0)
517 closesocket(sd);
518
519#elif defined(RT_OS_FREEBSD)
520 struct ifaddrs *pIfHead = NULL;
521
522 /* Get all available interfaces */
523 rc = getifaddrs(&pIfHead);
524 if (rc < 0)
525 {
526 rc = RTErrConvertFromErrno(errno);
527 VBoxServiceError("VMInfo/Network: Failed to get all interfaces: Error %Rrc\n");
528 return rc;
529 }
530
531 /* Loop through all interfaces and set the data. */
532 for (struct ifaddrs *pIfCurr = pIfHead; pIfCurr; pIfCurr = pIfCurr->ifa_next)
533 {
534 /*
535 * Only AF_INET and no loopback interfaces
536 * @todo: IPv6 interfaces
537 */
538 if ( pIfCurr->ifa_addr->sa_family == AF_INET
539 && !(pIfCurr->ifa_flags & IFF_LOOPBACK))
540 {
541 char szInetAddr[NI_MAXHOST];
542
543 memset(szInetAddr, 0, NI_MAXHOST);
544 getnameinfo(pIfCurr->ifa_addr, sizeof(struct sockaddr_in),
545 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
546 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
547 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
548
549 memset(szInetAddr, 0, NI_MAXHOST);
550 getnameinfo(pIfCurr->ifa_broadaddr, sizeof(struct sockaddr_in),
551 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
552 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
553 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
554
555 memset(szInetAddr, 0, NI_MAXHOST);
556 getnameinfo(pIfCurr->ifa_netmask, sizeof(struct sockaddr_in),
557 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
558 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
559 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
560
561 /* Search for the AF_LINK interface of the current AF_INET one and get the mac. */
562 for (struct ifaddrs *pIfLinkCurr = pIfHead; pIfLinkCurr; pIfLinkCurr = pIfLinkCurr->ifa_next)
563 {
564 if ( pIfLinkCurr->ifa_addr->sa_family == AF_LINK
565 && !strcmp(pIfCurr->ifa_name, pIfLinkCurr->ifa_name))
566 {
567 char szMac[32];
568 uint8_t *pu8Mac = NULL;
569 struct sockaddr_dl *pLinkAddress = (struct sockaddr_dl *)pIfLinkCurr->ifa_addr;
570
571 AssertPtr(pLinkAddress);
572 pu8Mac = (uint8_t *)LLADDR(pLinkAddress);
573 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
574 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
575 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
576 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
577 break;
578 }
579 }
580
581 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
582 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");
583
584 cIfacesReport++;
585 }
586 }
587
588 /* Free allocated resources. */
589 freeifaddrs(pIfHead);
590
591#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
592 int sd = socket(AF_INET, SOCK_DGRAM, 0);
593 if (sd < 0)
594 {
595 rc = RTErrConvertFromErrno(errno);
596 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
597 return rc;
598 }
599
600 ifconf ifcfg;
601 char buffer[1024] = {0};
602 ifcfg.ifc_len = sizeof(buffer);
603 ifcfg.ifc_buf = buffer;
604 if (ioctl(sd, SIOCGIFCONF, &ifcfg) < 0)
605 {
606 close(sd);
607 rc = RTErrConvertFromErrno(errno);
608 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFCONF) on socket: Error %Rrc\n", rc);
609 return rc;
610 }
611
612 ifreq* ifrequest = ifcfg.ifc_req;
613 int cIfacesSystem = ifcfg.ifc_len / sizeof(ifreq);
614
615 for (int i = 0; i < cIfacesSystem; ++i)
616 {
617 sockaddr_in *pAddress;
618 if (ioctl(sd, SIOCGIFFLAGS, &ifrequest[i]) < 0)
619 {
620 rc = RTErrConvertFromErrno(errno);
621 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS) on socket: Error %Rrc\n", rc);
622 break;
623 }
624 if (ifrequest[i].ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
625 continue;
626
627 bool fIfUp = !!(ifrequest[i].ifr_flags & IFF_UP);
628 pAddress = ((sockaddr_in *)&ifrequest[i].ifr_addr);
629 Assert(pAddress);
630 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
631 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
632
633 if (ioctl(sd, SIOCGIFBRDADDR, &ifrequest[i]) < 0)
634 {
635 rc = RTErrConvertFromErrno(errno);
636 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
637 break;
638 }
639 pAddress = (sockaddr_in *)&ifrequest[i].ifr_broadaddr;
640 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
641 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
642
643 if (ioctl(sd, SIOCGIFNETMASK, &ifrequest[i]) < 0)
644 {
645 rc = RTErrConvertFromErrno(errno);
646 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
647 break;
648 }
649# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
650 pAddress = (sockaddr_in *)&ifrequest[i].ifr_addr;
651# else
652 pAddress = (sockaddr_in *)&ifrequest[i].ifr_netmask;
653# endif
654
655 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
656 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
657
658# if defined(RT_OS_SOLARIS)
659 /*
660 * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
661 * We might fail if the interface has not been assigned an IP address.
662 * That doesn't matter; as long as it's plumbed we can pick it up.
663 * But, if it has not acquired an IP address we cannot obtain it's MAC
664 * address this way, so we just use all zeros there.
665 */
666 RTMAC IfMac;
667 RT_ZERO(IfMac);
668 struct lifreq IfReq;
669 RT_ZERO(IfReq);
670 AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(ifrequest[i].ifr_name));
671 strncpy(IfReq.lifr_name, ifrequest[i].ifr_name, sizeof(ifrequest[i].ifr_name));
672 if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
673 {
674 struct arpreq ArpReq;
675 RT_ZERO(ArpReq);
676 memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));
677
678 if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
679 memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
680 else
681 {
682 rc = RTErrConvertFromErrno(errno);
683 VBoxServiceError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
684 break;
685 }
686 }
687 else
688 {
689 VBoxServiceVerbose(2, "VMInfo/Network: Interface %d has no assigned IP address, skipping ...\n", i);
690 continue;
691 }
692# else
693# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
694 if (ioctl(sd, SIOCGIFHWADDR, &ifrequest[i]) < 0)
695 {
696 rc = RTErrConvertFromErrno(errno);
697 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
698 break;
699 }
700# endif
701# endif
702
703# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
704 char szMac[32];
705# if defined(RT_OS_SOLARIS)
706 uint8_t *pu8Mac = IfMac.au8;
707# else
708 uint8_t *pu8Mac = (uint8_t*)&ifrequest[i].ifr_hwaddr.sa_data[0]; /* @todo see above */
709# endif
710 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
711 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
712 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
713 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
714# endif /* !OS/2*/
715
716 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
717 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");
718 cIfacesReport++;
719 } /* For all interfaces */
720
721 close(sd);
722 if (RT_FAILURE(rc))
723 VBoxServiceError("VMInfo/Network: Network enumeration for interface %u failed with error %Rrc\n", cIfacesReport, rc);
724
725#endif /* !RT_OS_WINDOWS */
726
727#if 0 /* Zapping not enabled yet, needs more testing first. */
728 /*
729 * Zap all stale network interface data if the former (saved) network ifaces count
730 * is bigger than the current one.
731 */
732
733 /* Get former count. */
734 uint32_t cIfacesReportOld;
735 rc = VBoxServiceReadPropUInt32(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/Net/Count", &cIfacesReportOld,
736 0 /* Min */, UINT32_MAX /* Max */);
737 if ( RT_SUCCESS(rc)
738 && cIfacesReportOld > cIfacesReport) /* Are some ifaces not around anymore? */
739 {
740 VBoxServiceVerbose(3, "VMInfo/Network: Stale interface data detected (%u old vs. %u current)\n",
741 cIfacesReportOld, cIfacesReport);
742
743 uint32_t uIfaceDeleteIdx = cIfacesReport;
744 do
745 {
746 VBoxServiceVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
747 rc = VBoxServicePropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%u", uIfaceDeleteIdx++);
748 } while (RT_SUCCESS(rc));
749 }
750 else if ( RT_FAILURE(rc)
751 && rc != VERR_NOT_FOUND)
752 {
753 VBoxServiceError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
754 }
755#endif
756
757 /*
758 * This property is a beacon which is _always_ written, even if the network configuration
759 * does not change. If this property is missing, the host assumes that all other GuestInfo
760 * properties are no longer valid.
761 */
762 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/Net/Count", "%d",
763 cIfacesReport);
764
765 /* Don't fail here; just report everything we got. */
766 return VINF_SUCCESS;
767}
768
769
770/** @copydoc VBOXSERVICE::pfnWorker */
771DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
772{
773 int rc;
774
775 /*
776 * Tell the control thread that it can continue
777 * spawning services.
778 */
779 RTThreadUserSignal(RTThreadSelf());
780
781#ifdef RT_OS_WINDOWS
782 /* Required for network information (must be called per thread). */
783 WSADATA wsaData;
784 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
785 VBoxServiceError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
786#endif /* RT_OS_WINDOWS */
787
788 /*
789 * Write the fixed properties first.
790 */
791 vboxserviceVMInfoWriteFixedProperties();
792
793 /*
794 * Now enter the loop retrieving runtime data continuously.
795 */
796 for (;;)
797 {
798 rc = vboxserviceVMInfoWriteUsers();
799 if (RT_FAILURE(rc))
800 break;
801
802 rc = vboxserviceVMInfoWriteNetwork();
803 if (RT_FAILURE(rc))
804 break;
805
806 /*
807 * Flush all properties if we were restored.
808 */
809 uint64_t idNewSession = g_idVMInfoSession;
810 VbglR3GetSessionId(&idNewSession);
811 if (idNewSession != g_idVMInfoSession)
812 {
813 VBoxServiceVerbose(3, "VMInfo: The VM session ID changed, flushing all properties\n");
814 vboxserviceVMInfoWriteFixedProperties();
815 VBoxServicePropCacheFlush(&g_VMInfoPropCache);
816 g_idVMInfoSession = idNewSession;
817 }
818
819 /*
820 * Block for a while.
821 *
822 * The event semaphore takes care of ignoring interruptions and it
823 * allows us to implement service wakeup later.
824 */
825 if (*pfShutdown)
826 break;
827 int rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
828 if (*pfShutdown)
829 break;
830 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
831 {
832 VBoxServiceError("VMInfo: RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
833 rc = rc2;
834 break;
835 }
836 else if (RT_LIKELY(RT_SUCCESS(rc2)))
837 {
838 /* Reset event semaphore if it got triggered. */
839 rc2 = RTSemEventMultiReset(g_hVMInfoEvent);
840 if (RT_FAILURE(rc2))
841 rc2 = VBoxServiceError("VMInfo: RTSemEventMultiReset failed; rc2=%Rrc\n", rc2);
842 }
843 }
844
845#ifdef RT_OS_WINDOWS
846 WSACleanup();
847#endif
848
849 return rc;
850}
851
852
853/** @copydoc VBOXSERVICE::pfnStop */
854static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
855{
856 RTSemEventMultiSignal(g_hVMInfoEvent);
857}
858
859
860/** @copydoc VBOXSERVICE::pfnTerm */
861static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
862{
863 if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
864 {
865 /** @todo temporary solution: Zap all values which are not valid
866 * anymore when VM goes down (reboot/shutdown ). Needs to
867 * be replaced with "temporary properties" later.
868 *
869 * One idea is to introduce a (HGCM-)session guest property
870 * flag meaning that a guest property is only valid as long
871 * as the HGCM session isn't closed (e.g. guest application
872 * terminates). [don't remove till implemented]
873 */
874 /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
875 * since it remembers what we've written. */
876 /* Delete the "../Net" branch. */
877 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
878 int rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
879
880 /* Destroy property cache. */
881 VBoxServicePropCacheDestroy(&g_VMInfoPropCache);
882
883 /* Disconnect from guest properties service. */
884 rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
885 if (RT_FAILURE(rc))
886 VBoxServiceError("VMInfo: Failed to disconnect from guest property service! Error: %Rrc\n", rc);
887 g_uVMInfoGuestPropSvcClientID = 0;
888
889 RTSemEventMultiDestroy(g_hVMInfoEvent);
890 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
891 }
892}
893
894
895/**
896 * The 'vminfo' service description.
897 */
898VBOXSERVICE g_VMInfo =
899{
900 /* pszName. */
901 "vminfo",
902 /* pszDescription. */
903 "Virtual Machine Information",
904 /* pszUsage. */
905 " [--vminfo-interval <ms>]"
906 ,
907 /* pszOptions. */
908 " --vminfo-interval Specifies the interval at which to retrieve the\n"
909 " VM information. The default is 10000 ms.\n"
910 ,
911 /* methods */
912 VBoxServiceVMInfoPreInit,
913 VBoxServiceVMInfoOption,
914 VBoxServiceVMInfoInit,
915 VBoxServiceVMInfoWorker,
916 VBoxServiceVMInfoStop,
917 VBoxServiceVMInfoTerm
918};
919
Note: See TracBrowser for help on using the repository browser.

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