VirtualBox

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

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

VBoxService: close socket on error

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.1 KB
Line 
1/* $Id: VBoxServiceVMInfo.cpp 33554 2010-10-28 11:59: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, NULL /* Delete on exit */);
150 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsers",
151 VBOXSERVICEPROPCACHEFLAG_TEMPORARY, "0");
152 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
153 VBOXSERVICEPROPCACHEFLAG_TEMPORARY, "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 *pszAddRev;
193 rc = VbglR3GetAdditionsVersion(&pszAddVer, &pszAddRev);
194 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Version",
195 "%s", RT_FAILURE(rc) ? "" : pszAddVer);
196 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Revision",
197 "%s", RT_FAILURE(rc) ? "" : pszAddRev);
198 if (RT_SUCCESS(rc))
199 {
200 RTStrFree(pszAddVer);
201 RTStrFree(pszAddRev);
202 }
203
204#ifdef RT_OS_WINDOWS
205 /*
206 * Do windows specific properties.
207 */
208 char *pszInstDir;
209 rc = VbglR3GetAdditionsInstallationPath(&pszInstDir);
210 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/InstallDir",
211 "%s", RT_FAILURE(rc) ? "" : pszInstDir);
212 if (RT_SUCCESS(rc))
213 RTStrFree(pszInstDir);
214
215 VBoxServiceWinGetComponentVersions(g_uVMInfoGuestPropSvcClientID);
216#endif
217}
218
219
220/**
221 * Provide information about active users.
222 */
223static int vboxserviceVMInfoWriteUsers(void)
224{
225 int rc = VINF_SUCCESS;
226 char *pszUserList = NULL;
227 uint32_t cUsersInList = 0;
228
229#ifdef RT_OS_WINDOWS
230# ifndef TARGET_NT4
231 rc = VBoxServiceVMInfoWinWriteUsers(&pszUserList, &cUsersInList);
232# else
233 rc = VERR_NOT_IMPLEMENTED;
234# endif
235
236#elif defined(RT_OS_FREEBSD)
237 /** @todo FreeBSD: Port logged on user info retrieval.
238 * However, FreeBSD 9 supports utmpx, so we could use the code
239 * block below (?). */
240 rc = VERR_NOT_IMPLEMENTED;
241
242#elif defined(RT_OS_OS2)
243 /** @todo OS/2: Port logged on (LAN/local/whatever) user info retrieval. */
244 rc = VERR_NOT_IMPLEMENTED;
245
246#else
247 setutxent();
248 utmpx *ut_user;
249 uint32_t cListSize = 32;
250
251 /* Allocate a first array to hold 32 users max. */
252 char **papszUsers = (char **)RTMemAllocZ(cListSize * sizeof(char *));
253 if (papszUsers == NULL)
254 rc = VERR_NO_MEMORY;
255
256 /* Process all entries in the utmp file. */
257 while ( (ut_user = getutxent())
258 && RT_SUCCESS(rc))
259 {
260 VBoxServiceVerbose(4, "VMInfo: Found logged in user \"%s\"\n", ut_user->ut_user);
261
262 if (cUsersInList > cListSize)
263 {
264 cListSize += 32;
265 void *pvNew = RTMemRealloc(papszUsers, cListSize * sizeof(char*));
266 AssertPtrBreakStmt(pvNew, cListSize -= 32);
267 papszUsers = (char **)pvNew;
268 }
269
270 /* Make sure we don't add user names which are not
271 * part of type USER_PROCESS. */
272 if (ut_user->ut_type == USER_PROCESS)
273 {
274 bool fFound = false;
275 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
276 fFound = strcmp(papszUsers[i], ut_user->ut_user) == 0;
277
278 if (!fFound)
279 {
280 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ut_user->ut_user);
281 if (RT_FAILURE(rc))
282 break;
283 cUsersInList++;
284 }
285 }
286 }
287
288 /* Calc the string length. */
289 size_t cchUserList = 0;
290 for (uint32_t i = 0; i < cUsersInList; i++)
291 cchUserList += (i != 0) + strlen(papszUsers[i]);
292
293 /* Build the user list. */
294 rc = RTStrAllocEx(&pszUserList, cchUserList + 1);
295 if (RT_SUCCESS(rc))
296 {
297 char *psz = pszUserList;
298 for (uint32_t i = 0; i < cUsersInList; i++)
299 {
300 if (i != 0)
301 *psz++ = ',';
302 size_t cch = strlen(papszUsers[i]);
303 memcpy(psz, papszUsers[i], cch);
304 psz += cch;
305 }
306 *psz = '\0';
307 }
308
309 /* Cleanup. */
310 for (uint32_t i = 0; i < cUsersInList; i++)
311 RTStrFree(papszUsers[i]);
312 RTMemFree(papszUsers);
313
314 endutxent(); /* Close utmpx file. */
315#endif
316 Assert(RT_FAILURE(rc) || cUsersInList == 0 || (pszUserList && *pszUserList));
317 if (RT_FAILURE(rc))
318 cUsersInList = 0;
319
320 VBoxServiceVerbose(4, "VMInfo: cUsersInList: %u, pszUserList: %s, rc=%Rrc\n",
321 cUsersInList, pszUserList ? pszUserList : "<NULL>", rc);
322
323 if (pszUserList && cUsersInList > 0)
324 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", "%s", pszUserList);
325 else
326 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", NULL);
327 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsers", "%u", cUsersInList);
328 if (g_cVMInfoLoggedInUsers != cUsersInList)
329 {
330 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
331 cUsersInList == 0 ? "true" : "false");
332 g_cVMInfoLoggedInUsers = cUsersInList;
333 }
334 if (RT_SUCCESS(rc) && pszUserList)
335 RTStrFree(pszUserList);
336 return rc;
337}
338
339
340/**
341 * Provide information about the guest network.
342 */
343static int vboxserviceVMInfoWriteNetwork(void)
344{
345 int rc = VINF_SUCCESS;
346 uint32_t cIfacesReport = 0;
347 char szPropPath[256];
348
349#ifdef RT_OS_WINDOWS
350 IP_ADAPTER_INFO *pAdpInfo = NULL;
351
352# ifndef TARGET_NT4
353 ULONG cbAdpInfo = sizeof(*pAdpInfo);
354 pAdpInfo = (IP_ADAPTER_INFO *)RTMemAlloc(cbAdpInfo);
355 if (!pAdpInfo)
356 {
357 VBoxServiceError("VMInfo/Network: Failed to allocate IP_ADAPTER_INFO\n");
358 return VERR_NO_MEMORY;
359 }
360 DWORD dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
361 if (dwRet == ERROR_BUFFER_OVERFLOW)
362 {
363 IP_ADAPTER_INFO *pAdpInfoNew = (IP_ADAPTER_INFO*)RTMemRealloc(pAdpInfo, cbAdpInfo);
364 if (pAdpInfoNew)
365 {
366 pAdpInfo = pAdpInfoNew;
367 dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
368 }
369 }
370 if (dwRet != ERROR_SUCCESS)
371 {
372 if (pAdpInfo)
373 RTMemFree(pAdpInfo);
374 VBoxServiceError("VMInfo/Network: Failed to get adapter info: Error %d\n", dwRet);
375 return RTErrConvertFromWin32(dwRet);
376 }
377# endif /* !TARGET_NT4 */
378
379 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
380 if (sd == SOCKET_ERROR) /* Socket invalid. */
381 {
382 int wsaErr = WSAGetLastError();
383 /* Don't complain/bail out with an error if network stack is not up; can happen
384 * on NT4 due to start up when not connected shares dialogs pop up. */
385 if (WSAENETDOWN == wsaErr)
386 {
387 VBoxServiceVerbose(0, "VMInfo/Network: Network is not up yet.\n");
388 wsaErr = VINF_SUCCESS;
389 }
390 else
391 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %d\n", wsaErr);
392 if (pAdpInfo)
393 RTMemFree(pAdpInfo);
394 return RTErrConvertFromWin32(wsaErr);
395 }
396
397 INTERFACE_INFO InterfaceList[20] = {0};
398 unsigned long nBytesReturned = 0;
399 if (WSAIoctl(sd,
400 SIO_GET_INTERFACE_LIST,
401 0,
402 0,
403 &InterfaceList,
404 sizeof(InterfaceList),
405 &nBytesReturned,
406 0,
407 0) == SOCKET_ERROR)
408 {
409 VBoxServiceError("VMInfo/Network: Failed to WSAIoctl() on socket: Error: %d\n", WSAGetLastError());
410 if (pAdpInfo)
411 RTMemFree(pAdpInfo);
412 return RTErrConvertFromWin32(WSAGetLastError());
413 }
414 int cIfacesSystem = nBytesReturned / sizeof(INTERFACE_INFO);
415
416 /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
417 for (int i = 0; i < cIfacesSystem; ++i)
418 {
419 sockaddr_in *pAddress;
420 u_long nFlags = 0;
421 if (InterfaceList[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
422 continue;
423 nFlags = InterfaceList[i].iiFlags;
424 pAddress = (sockaddr_in *)&(InterfaceList[i].iiAddress);
425 Assert(pAddress);
426 char szIp[32];
427 RTStrPrintf(szIp, sizeof(szIp), "%s", inet_ntoa(pAddress->sin_addr));
428 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
429 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szIp);
430
431 pAddress = (sockaddr_in *) & (InterfaceList[i].iiBroadcastAddress);
432 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
433 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
434
435 pAddress = (sockaddr_in *)&(InterfaceList[i].iiNetmask);
436 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
437 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
438
439 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
440 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, nFlags & IFF_UP ? "Up" : "Down");
441
442# ifndef TARGET_NT4
443 IP_ADAPTER_INFO *pAdp;
444 for (pAdp = pAdpInfo; pAdp; pAdp = pAdp->Next)
445 if (!strcmp(pAdp->IpAddressList.IpAddress.String, szIp))
446 break;
447
448 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
449 if (pAdp)
450 {
451 char szMac[32];
452 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
453 pAdp->Address[0], pAdp->Address[1], pAdp->Address[2],
454 pAdp->Address[3], pAdp->Address[4], pAdp->Address[5]);
455 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
456 }
457 else
458 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, NULL);
459# endif /* !TARGET_NT4 */
460
461 cIfacesReport++;
462 }
463 if (pAdpInfo)
464 RTMemFree(pAdpInfo);
465 if (sd >= 0)
466 closesocket(sd);
467
468#elif defined(RT_OS_FREEBSD)
469 struct ifaddrs *pIfHead = NULL;
470
471 /* Get all available interfaces */
472 rc = getifaddrs(&pIfHead);
473 if (rc < 0)
474 {
475 rc = RTErrConvertFromErrno(errno);
476 VBoxServiceError("VMInfo/Network: Failed to get all interfaces: Error %Rrc\n");
477 return rc;
478 }
479
480 /* Loop through all interfaces and set the data. */
481 for (struct ifaddrs *pIfCurr = pIfHead; pIfCurr; pIfCurr = pIfCurr->ifa_next)
482 {
483 /*
484 * Only AF_INET and no loopback interfaces
485 * @todo: IPv6 interfaces
486 */
487 if ( pIfCurr->ifa_addr->sa_family == AF_INET
488 && !(pIfCurr->ifa_flags & IFF_LOOPBACK))
489 {
490 char szInetAddr[NI_MAXHOST];
491
492 memset(szInetAddr, 0, NI_MAXHOST);
493 getnameinfo(pIfCurr->ifa_addr, sizeof(struct sockaddr_in),
494 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
495 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
496 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
497
498 memset(szInetAddr, 0, NI_MAXHOST);
499 getnameinfo(pIfCurr->ifa_broadaddr, sizeof(struct sockaddr_in),
500 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
501 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
502 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
503
504 memset(szInetAddr, 0, NI_MAXHOST);
505 getnameinfo(pIfCurr->ifa_netmask, sizeof(struct sockaddr_in),
506 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
507 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
508 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
509
510 /* Search for the AF_LINK interface of the current AF_INET one and get the mac. */
511 for (struct ifaddrs *pIfLinkCurr = pIfHead; pIfLinkCurr; pIfLinkCurr = pIfLinkCurr->ifa_next)
512 {
513 if ( pIfLinkCurr->ifa_addr->sa_family == AF_LINK
514 && !strcmp(pIfCurr->ifa_name, pIfLinkCurr->ifa_name))
515 {
516 char szMac[32];
517 uint8_t *pu8Mac = NULL;
518 struct sockaddr_dl *pLinkAddress = (struct sockaddr_dl *)pIfLinkCurr->ifa_addr;
519
520 AssertPtr(pLinkAddress);
521 pu8Mac = (uint8_t *)LLADDR(pLinkAddress);
522 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
523 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
524 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
525 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
526 break;
527 }
528 }
529
530 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
531 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");
532
533 cIfacesReport++;
534 }
535 }
536
537 /* Free allocated resources. */
538 freeifaddrs(pIfHead);
539
540#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
541 int sd = socket(AF_INET, SOCK_DGRAM, 0);
542 if (sd < 0)
543 {
544 rc = RTErrConvertFromErrno(errno);
545 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
546 return rc;
547 }
548
549 ifconf ifcfg;
550 char buffer[1024] = {0};
551 ifcfg.ifc_len = sizeof(buffer);
552 ifcfg.ifc_buf = buffer;
553 if (ioctl(sd, SIOCGIFCONF, &ifcfg) < 0)
554 {
555 close(sd);
556 rc = RTErrConvertFromErrno(errno);
557 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFCONF) on socket: Error %Rrc\n", rc);
558 return rc;
559 }
560
561 ifreq* ifrequest = ifcfg.ifc_req;
562 int cIfacesSystem = ifcfg.ifc_len / sizeof(ifreq);
563
564 for (int i = 0; i < cIfacesSystem; ++i)
565 {
566 sockaddr_in *pAddress;
567 if (ioctl(sd, SIOCGIFFLAGS, &ifrequest[i]) < 0)
568 {
569 rc = RTErrConvertFromErrno(errno);
570 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS) on socket: Error %Rrc\n", rc);
571 break;
572 }
573 if (ifrequest[i].ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
574 continue;
575
576 bool fIfUp = !!(ifrequest[i].ifr_flags & IFF_UP);
577 pAddress = ((sockaddr_in *)&ifrequest[i].ifr_addr);
578 Assert(pAddress);
579 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
580 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
581
582 if (ioctl(sd, SIOCGIFBRDADDR, &ifrequest[i]) < 0)
583 {
584 rc = RTErrConvertFromErrno(errno);
585 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
586 break;
587 }
588 pAddress = (sockaddr_in *)&ifrequest[i].ifr_broadaddr;
589 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
590 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
591
592 if (ioctl(sd, SIOCGIFNETMASK, &ifrequest[i]) < 0)
593 {
594 rc = RTErrConvertFromErrno(errno);
595 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
596 break;
597 }
598# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
599 pAddress = (sockaddr_in *)&ifrequest[i].ifr_addr;
600# else
601 pAddress = (sockaddr_in *)&ifrequest[i].ifr_netmask;
602# endif
603
604 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
605 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
606
607# if defined(RT_OS_SOLARIS)
608 /*
609 * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
610 * We might fail if the interface has not been assigned an IP address.
611 * That doesn't matter; as long as it's plumbed we can pick it up.
612 * But, if it has not acquired an IP address we cannot obtain it's MAC
613 * address this way, so we just use all zeros there.
614 */
615 RTMAC IfMac;
616 RT_ZERO(IfMac);
617 struct lifreq IfReq;
618 RT_ZERO(IfReq);
619 AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(ifrequest[i].ifr_name));
620 strncpy(IfReq.lifr_name, ifrequest[i].ifr_name, sizeof(ifrequest[i].ifr_name));
621 if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
622 {
623 struct arpreq ArpReq;
624 RT_ZERO(ArpReq);
625 memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));
626
627 if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
628 memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
629 else
630 {
631 rc = RTErrConvertFromErrno(errno);
632 VBoxServiceError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
633 break;
634 }
635 }
636 else
637 {
638 VBoxServiceVerbose(2, "VMInfo/Network: Interface %d has no assigned IP address, skipping ...\n", i);
639 continue;
640 }
641# else
642# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
643 if (ioctl(sd, SIOCGIFHWADDR, &ifrequest[i]) < 0)
644 {
645 rc = RTErrConvertFromErrno(errno);
646 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
647 break;
648 }
649# endif
650# endif
651
652# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
653 char szMac[32];
654# if defined(RT_OS_SOLARIS)
655 uint8_t *pu8Mac = IfMac.au8;
656# else
657 uint8_t *pu8Mac = (uint8_t*)&ifrequest[i].ifr_hwaddr.sa_data[0]; /* @todo see above */
658# endif
659 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
660 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
661 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
662 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
663# endif /* !OS/2*/
664
665 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
666 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");
667 cIfacesReport++;
668 }
669
670 close(sd);
671 if (RT_FAILURE(rc))
672 VBoxServiceError("VMInfo/Network: Network enumeration for interface %u failed with error %Rrc\n", cIfacesReport, rc);
673
674#endif /* !RT_OS_WINDOWS */
675
676#if 0 /* Zapping not enabled yet, needs more testing first. */
677 /*
678 * Zap all stale network interface data if the former (saved) network ifaces count
679 * is bigger than the current one.
680 */
681
682 /* Get former count. */
683 uint32_t cIfacesReportOld;
684 rc = VBoxServiceReadPropUInt32(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/Net/Count", &cIfacesReportOld,
685 0 /* Min */, UINT32_MAX /* Max */);
686 if ( RT_SUCCESS(rc)
687 && cIfacesReportOld > cIfacesReport) /* Are some ifaces not around anymore? */
688 {
689 VBoxServiceVerbose(3, "VMInfo/Network: Stale interface data detected (%u old vs. %u current)\n",
690 cIfacesReportOld, cIfacesReport);
691
692 uint32_t uIfaceDeleteIdx = cIfacesReport;
693 do
694 {
695 VBoxServiceVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
696 rc = VBoxServicePropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%u", uIfaceDeleteIdx++);
697 } while (RT_SUCCESS(rc));
698 }
699 else if ( RT_FAILURE(rc)
700 && rc != VERR_NOT_FOUND)
701 {
702 VBoxServiceError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
703 }
704#endif
705
706 /*
707 * This property is a beacon which is _always_ written, even if the network configuration
708 * does not change. If this property is missing, the host assumes that all other GuestInfo
709 * properties are no longer valid.
710 */
711 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/Net/Count", "%d",
712 cIfacesReport);
713
714 /* Don't fail here; just report everything we got. */
715 return VINF_SUCCESS;
716}
717
718
719/** @copydoc VBOXSERVICE::pfnWorker */
720DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
721{
722 int rc;
723
724 /*
725 * Tell the control thread that it can continue
726 * spawning services.
727 */
728 RTThreadUserSignal(RTThreadSelf());
729
730#ifdef RT_OS_WINDOWS
731 /* Required for network information (must be called per thread). */
732 WSADATA wsaData;
733 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
734 VBoxServiceError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
735#endif /* RT_OS_WINDOWS */
736
737 /*
738 * Write the fixed properties first.
739 */
740 vboxserviceVMInfoWriteFixedProperties();
741
742 /*
743 * Now enter the loop retrieving runtime data continuously.
744 */
745 for (;;)
746 {
747 rc = vboxserviceVMInfoWriteUsers();
748 if (RT_FAILURE(rc))
749 break;
750
751 rc = vboxserviceVMInfoWriteNetwork();
752 if (RT_FAILURE(rc))
753 break;
754
755 /*
756 * Flush all properties if we were restored.
757 */
758 uint64_t idNewSession = g_idVMInfoSession;
759 VbglR3GetSessionId(&idNewSession);
760 if (idNewSession != g_idVMInfoSession)
761 {
762 VBoxServiceVerbose(3, "VMInfo: The VM session ID changed, flushing all properties.\n");
763 vboxserviceVMInfoWriteFixedProperties();
764 VBoxServicePropCacheFlush(&g_VMInfoPropCache);
765 g_idVMInfoSession = idNewSession;
766 }
767
768 /*
769 * Block for a while.
770 *
771 * The event semaphore takes care of ignoring interruptions and it
772 * allows us to implement service wakeup later.
773 */
774 if (*pfShutdown)
775 break;
776 int rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
777 if (*pfShutdown)
778 break;
779 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
780 {
781 VBoxServiceError("VMInfo: RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
782 rc = rc2;
783 break;
784 }
785 }
786
787#ifdef RT_OS_WINDOWS
788 WSACleanup();
789#endif
790
791 return rc;
792}
793
794
795/** @copydoc VBOXSERVICE::pfnStop */
796static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
797{
798 RTSemEventMultiSignal(g_hVMInfoEvent);
799}
800
801
802/** @copydoc VBOXSERVICE::pfnTerm */
803static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
804{
805 int rc;
806
807 if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
808 {
809 /** @todo temporary solution: Zap all values which are not valid
810 * anymore when VM goes down (reboot/shutdown ). Needs to
811 * be replaced with "temporary properties" later.
812 *
813 * One idea is to introduce a (HGCM-)session guest property
814 * flag meaning that a guest property is only valid as long
815 * as the HGCM session isn't closed (e.g. guest application
816 * terminates). [don't remove till implemented]
817 */
818 /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
819 * since it remembers what we've written. */
820 /* Delete the "../Net" branch. */
821 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
822 rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
823
824 /* Destroy property cache. */
825 VBoxServicePropCacheDestroy(&g_VMInfoPropCache);
826
827 /* Disconnect from guest properties service. */
828 rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
829 if (RT_FAILURE(rc))
830 VBoxServiceError("VMInfo: Failed to disconnect from guest property service! Error: %Rrc\n", rc);
831 g_uVMInfoGuestPropSvcClientID = 0;
832
833 RTSemEventMultiDestroy(g_hVMInfoEvent);
834 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
835 }
836}
837
838
839/**
840 * The 'vminfo' service description.
841 */
842VBOXSERVICE g_VMInfo =
843{
844 /* pszName. */
845 "vminfo",
846 /* pszDescription. */
847 "Virtual Machine Information",
848 /* pszUsage. */
849 " [--vminfo-interval <ms>]"
850 ,
851 /* pszOptions. */
852 " --vminfo-interval Specifies the interval at which to retrieve the\n"
853 " VM information. The default is 10000 ms.\n"
854 ,
855 /* methods */
856 VBoxServiceVMInfoPreInit,
857 VBoxServiceVMInfoOption,
858 VBoxServiceVMInfoInit,
859 VBoxServiceVMInfoWorker,
860 VBoxServiceVMInfoStop,
861 VBoxServiceVMInfoTerm
862};
863
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use