VirtualBox

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

Last change on this file since 38129 was 38129, checked in by vboxsync, 14 years ago

VBoxService/VMInfo-win: Keep old user count when out of memory and warn about it.

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