VirtualBox

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

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

Haiku Additions.

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