VirtualBox

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

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

VBoxService/VMInfo-win: Don't bail out if there are no network interfaces present.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.5 KB
Line 
1/* $Id: VBoxServiceVMInfo.cpp 38224 2011-07-28 14:53:13Z 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 else if (dwRet == ERROR_NO_DATA)
391 {
392 VBoxServiceVerbose(3, "VMInfo/Network: No network adapters available\n");
393
394 /* If no network adapters available / present in the
395 * system we pretend success to not bail out too early. */
396 dwRet = ERROR_SUCCESS;
397 }
398
399 if (dwRet != ERROR_SUCCESS)
400 {
401 if (pAdpInfo)
402 RTMemFree(pAdpInfo);
403 VBoxServiceError("VMInfo/Network: Failed to get adapter info: Error %d\n", dwRet);
404 return RTErrConvertFromWin32(dwRet);
405 }
406# endif /* !TARGET_NT4 */
407
408 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
409 if (sd == SOCKET_ERROR) /* Socket invalid. */
410 {
411 int wsaErr = WSAGetLastError();
412 /* Don't complain/bail out with an error if network stack is not up; can happen
413 * on NT4 due to start up when not connected shares dialogs pop up. */
414 if (WSAENETDOWN == wsaErr)
415 {
416 VBoxServiceVerbose(0, "VMInfo/Network: Network is not up yet.\n");
417 wsaErr = VINF_SUCCESS;
418 }
419 else
420 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %d\n", wsaErr);
421 if (pAdpInfo)
422 RTMemFree(pAdpInfo);
423 return RTErrConvertFromWin32(wsaErr);
424 }
425
426 INTERFACE_INFO InterfaceList[20] = {0};
427 unsigned long nBytesReturned = 0;
428 if (WSAIoctl(sd,
429 SIO_GET_INTERFACE_LIST,
430 0,
431 0,
432 &InterfaceList,
433 sizeof(InterfaceList),
434 &nBytesReturned,
435 0,
436 0) == SOCKET_ERROR)
437 {
438 VBoxServiceError("VMInfo/Network: Failed to WSAIoctl() on socket: Error: %d\n", WSAGetLastError());
439 if (pAdpInfo)
440 RTMemFree(pAdpInfo);
441 return RTErrConvertFromWin32(WSAGetLastError());
442 }
443 int cIfacesSystem = nBytesReturned / sizeof(INTERFACE_INFO);
444
445 /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
446 for (int i = 0; i < cIfacesSystem; ++i)
447 {
448 sockaddr_in *pAddress;
449 u_long nFlags = 0;
450 if (InterfaceList[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
451 continue;
452 nFlags = InterfaceList[i].iiFlags;
453 pAddress = (sockaddr_in *)&(InterfaceList[i].iiAddress);
454 Assert(pAddress);
455 char szIp[32];
456 RTStrPrintf(szIp, sizeof(szIp), "%s", inet_ntoa(pAddress->sin_addr));
457 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
458 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szIp);
459
460 pAddress = (sockaddr_in *) & (InterfaceList[i].iiBroadcastAddress);
461 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
462 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
463
464 pAddress = (sockaddr_in *)&(InterfaceList[i].iiNetmask);
465 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
466 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
467
468 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
469 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, nFlags & IFF_UP ? "Up" : "Down");
470
471# ifndef TARGET_NT4
472 IP_ADAPTER_INFO *pAdp;
473 for (pAdp = pAdpInfo; pAdp; pAdp = pAdp->Next)
474 if (!strcmp(pAdp->IpAddressList.IpAddress.String, szIp))
475 break;
476
477 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
478 if (pAdp)
479 {
480 char szMac[32];
481 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
482 pAdp->Address[0], pAdp->Address[1], pAdp->Address[2],
483 pAdp->Address[3], pAdp->Address[4], pAdp->Address[5]);
484 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
485 }
486 else
487 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, NULL);
488# endif /* !TARGET_NT4 */
489
490 cIfacesReport++;
491 }
492 if (pAdpInfo)
493 RTMemFree(pAdpInfo);
494 if (sd >= 0)
495 closesocket(sd);
496
497#elif defined(RT_OS_FREEBSD)
498 struct ifaddrs *pIfHead = NULL;
499
500 /* Get all available interfaces */
501 rc = getifaddrs(&pIfHead);
502 if (rc < 0)
503 {
504 rc = RTErrConvertFromErrno(errno);
505 VBoxServiceError("VMInfo/Network: Failed to get all interfaces: Error %Rrc\n");
506 return rc;
507 }
508
509 /* Loop through all interfaces and set the data. */
510 for (struct ifaddrs *pIfCurr = pIfHead; pIfCurr; pIfCurr = pIfCurr->ifa_next)
511 {
512 /*
513 * Only AF_INET and no loopback interfaces
514 * @todo: IPv6 interfaces
515 */
516 if ( pIfCurr->ifa_addr->sa_family == AF_INET
517 && !(pIfCurr->ifa_flags & IFF_LOOPBACK))
518 {
519 char szInetAddr[NI_MAXHOST];
520
521 memset(szInetAddr, 0, NI_MAXHOST);
522 getnameinfo(pIfCurr->ifa_addr, sizeof(struct sockaddr_in),
523 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
524 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
525 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
526
527 memset(szInetAddr, 0, NI_MAXHOST);
528 getnameinfo(pIfCurr->ifa_broadaddr, sizeof(struct sockaddr_in),
529 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
530 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
531 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
532
533 memset(szInetAddr, 0, NI_MAXHOST);
534 getnameinfo(pIfCurr->ifa_netmask, sizeof(struct sockaddr_in),
535 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
536 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
537 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
538
539 /* Search for the AF_LINK interface of the current AF_INET one and get the mac. */
540 for (struct ifaddrs *pIfLinkCurr = pIfHead; pIfLinkCurr; pIfLinkCurr = pIfLinkCurr->ifa_next)
541 {
542 if ( pIfLinkCurr->ifa_addr->sa_family == AF_LINK
543 && !strcmp(pIfCurr->ifa_name, pIfLinkCurr->ifa_name))
544 {
545 char szMac[32];
546 uint8_t *pu8Mac = NULL;
547 struct sockaddr_dl *pLinkAddress = (struct sockaddr_dl *)pIfLinkCurr->ifa_addr;
548
549 AssertPtr(pLinkAddress);
550 pu8Mac = (uint8_t *)LLADDR(pLinkAddress);
551 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
552 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
553 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
554 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
555 break;
556 }
557 }
558
559 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
560 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");
561
562 cIfacesReport++;
563 }
564 }
565
566 /* Free allocated resources. */
567 freeifaddrs(pIfHead);
568
569#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
570 int sd = socket(AF_INET, SOCK_DGRAM, 0);
571 if (sd < 0)
572 {
573 rc = RTErrConvertFromErrno(errno);
574 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
575 return rc;
576 }
577
578 ifconf ifcfg;
579 char buffer[1024] = {0};
580 ifcfg.ifc_len = sizeof(buffer);
581 ifcfg.ifc_buf = buffer;
582 if (ioctl(sd, SIOCGIFCONF, &ifcfg) < 0)
583 {
584 close(sd);
585 rc = RTErrConvertFromErrno(errno);
586 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFCONF) on socket: Error %Rrc\n", rc);
587 return rc;
588 }
589
590 ifreq* ifrequest = ifcfg.ifc_req;
591 int cIfacesSystem = ifcfg.ifc_len / sizeof(ifreq);
592
593 for (int i = 0; i < cIfacesSystem; ++i)
594 {
595 sockaddr_in *pAddress;
596 if (ioctl(sd, SIOCGIFFLAGS, &ifrequest[i]) < 0)
597 {
598 rc = RTErrConvertFromErrno(errno);
599 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS) on socket: Error %Rrc\n", rc);
600 break;
601 }
602 if (ifrequest[i].ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
603 continue;
604
605 bool fIfUp = !!(ifrequest[i].ifr_flags & IFF_UP);
606 pAddress = ((sockaddr_in *)&ifrequest[i].ifr_addr);
607 Assert(pAddress);
608 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
609 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
610
611 if (ioctl(sd, SIOCGIFBRDADDR, &ifrequest[i]) < 0)
612 {
613 rc = RTErrConvertFromErrno(errno);
614 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
615 break;
616 }
617 pAddress = (sockaddr_in *)&ifrequest[i].ifr_broadaddr;
618 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
619 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
620
621 if (ioctl(sd, SIOCGIFNETMASK, &ifrequest[i]) < 0)
622 {
623 rc = RTErrConvertFromErrno(errno);
624 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
625 break;
626 }
627# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
628 pAddress = (sockaddr_in *)&ifrequest[i].ifr_addr;
629# else
630 pAddress = (sockaddr_in *)&ifrequest[i].ifr_netmask;
631# endif
632
633 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
634 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
635
636# if defined(RT_OS_SOLARIS)
637 /*
638 * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
639 * We might fail if the interface has not been assigned an IP address.
640 * That doesn't matter; as long as it's plumbed we can pick it up.
641 * But, if it has not acquired an IP address we cannot obtain it's MAC
642 * address this way, so we just use all zeros there.
643 */
644 RTMAC IfMac;
645 RT_ZERO(IfMac);
646 struct lifreq IfReq;
647 RT_ZERO(IfReq);
648 AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(ifrequest[i].ifr_name));
649 strncpy(IfReq.lifr_name, ifrequest[i].ifr_name, sizeof(ifrequest[i].ifr_name));
650 if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
651 {
652 struct arpreq ArpReq;
653 RT_ZERO(ArpReq);
654 memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));
655
656 if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
657 memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
658 else
659 {
660 rc = RTErrConvertFromErrno(errno);
661 VBoxServiceError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
662 break;
663 }
664 }
665 else
666 {
667 VBoxServiceVerbose(2, "VMInfo/Network: Interface %d has no assigned IP address, skipping ...\n", i);
668 continue;
669 }
670# else
671# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
672 if (ioctl(sd, SIOCGIFHWADDR, &ifrequest[i]) < 0)
673 {
674 rc = RTErrConvertFromErrno(errno);
675 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
676 break;
677 }
678# endif
679# endif
680
681# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
682 char szMac[32];
683# if defined(RT_OS_SOLARIS)
684 uint8_t *pu8Mac = IfMac.au8;
685# else
686 uint8_t *pu8Mac = (uint8_t*)&ifrequest[i].ifr_hwaddr.sa_data[0]; /* @todo see above */
687# endif
688 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
689 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
690 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
691 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
692# endif /* !OS/2*/
693
694 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
695 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");
696 cIfacesReport++;
697 } /* For all interfaces */
698
699 close(sd);
700 if (RT_FAILURE(rc))
701 VBoxServiceError("VMInfo/Network: Network enumeration for interface %u failed with error %Rrc\n", cIfacesReport, rc);
702
703#endif /* !RT_OS_WINDOWS */
704
705#if 0 /* Zapping not enabled yet, needs more testing first. */
706 /*
707 * Zap all stale network interface data if the former (saved) network ifaces count
708 * is bigger than the current one.
709 */
710
711 /* Get former count. */
712 uint32_t cIfacesReportOld;
713 rc = VBoxServiceReadPropUInt32(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/Net/Count", &cIfacesReportOld,
714 0 /* Min */, UINT32_MAX /* Max */);
715 if ( RT_SUCCESS(rc)
716 && cIfacesReportOld > cIfacesReport) /* Are some ifaces not around anymore? */
717 {
718 VBoxServiceVerbose(3, "VMInfo/Network: Stale interface data detected (%u old vs. %u current)\n",
719 cIfacesReportOld, cIfacesReport);
720
721 uint32_t uIfaceDeleteIdx = cIfacesReport;
722 do
723 {
724 VBoxServiceVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
725 rc = VBoxServicePropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%u", uIfaceDeleteIdx++);
726 } while (RT_SUCCESS(rc));
727 }
728 else if ( RT_FAILURE(rc)
729 && rc != VERR_NOT_FOUND)
730 {
731 VBoxServiceError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
732 }
733#endif
734
735 /*
736 * This property is a beacon which is _always_ written, even if the network configuration
737 * does not change. If this property is missing, the host assumes that all other GuestInfo
738 * properties are no longer valid.
739 */
740 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/Net/Count", "%d",
741 cIfacesReport);
742
743 /* Don't fail here; just report everything we got. */
744 return VINF_SUCCESS;
745}
746
747
748/** @copydoc VBOXSERVICE::pfnWorker */
749DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
750{
751 int rc;
752
753 /*
754 * Tell the control thread that it can continue
755 * spawning services.
756 */
757 RTThreadUserSignal(RTThreadSelf());
758
759#ifdef RT_OS_WINDOWS
760 /* Required for network information (must be called per thread). */
761 WSADATA wsaData;
762 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
763 VBoxServiceError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
764#endif /* RT_OS_WINDOWS */
765
766 /*
767 * Write the fixed properties first.
768 */
769 vboxserviceVMInfoWriteFixedProperties();
770
771 /*
772 * Now enter the loop retrieving runtime data continuously.
773 */
774 for (;;)
775 {
776 rc = vboxserviceVMInfoWriteUsers();
777 if (RT_FAILURE(rc))
778 break;
779
780 rc = vboxserviceVMInfoWriteNetwork();
781 if (RT_FAILURE(rc))
782 break;
783
784 /*
785 * Flush all properties if we were restored.
786 */
787 uint64_t idNewSession = g_idVMInfoSession;
788 VbglR3GetSessionId(&idNewSession);
789 if (idNewSession != g_idVMInfoSession)
790 {
791 VBoxServiceVerbose(3, "VMInfo: The VM session ID changed, flushing all properties\n");
792 vboxserviceVMInfoWriteFixedProperties();
793 VBoxServicePropCacheFlush(&g_VMInfoPropCache);
794 g_idVMInfoSession = idNewSession;
795 }
796
797 /*
798 * Block for a while.
799 *
800 * The event semaphore takes care of ignoring interruptions and it
801 * allows us to implement service wakeup later.
802 */
803 if (*pfShutdown)
804 break;
805 int rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
806 if (*pfShutdown)
807 break;
808 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
809 {
810 VBoxServiceError("VMInfo: RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
811 rc = rc2;
812 break;
813 }
814 }
815
816#ifdef RT_OS_WINDOWS
817 WSACleanup();
818#endif
819
820 return rc;
821}
822
823
824/** @copydoc VBOXSERVICE::pfnStop */
825static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
826{
827 RTSemEventMultiSignal(g_hVMInfoEvent);
828}
829
830
831/** @copydoc VBOXSERVICE::pfnTerm */
832static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
833{
834 int rc;
835
836 if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
837 {
838 /** @todo temporary solution: Zap all values which are not valid
839 * anymore when VM goes down (reboot/shutdown ). Needs to
840 * be replaced with "temporary properties" later.
841 *
842 * One idea is to introduce a (HGCM-)session guest property
843 * flag meaning that a guest property is only valid as long
844 * as the HGCM session isn't closed (e.g. guest application
845 * terminates). [don't remove till implemented]
846 */
847 /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
848 * since it remembers what we've written. */
849 /* Delete the "../Net" branch. */
850 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
851 rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
852
853 /* Destroy property cache. */
854 VBoxServicePropCacheDestroy(&g_VMInfoPropCache);
855
856 /* Disconnect from guest properties service. */
857 rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
858 if (RT_FAILURE(rc))
859 VBoxServiceError("VMInfo: Failed to disconnect from guest property service! Error: %Rrc\n", rc);
860 g_uVMInfoGuestPropSvcClientID = 0;
861
862 RTSemEventMultiDestroy(g_hVMInfoEvent);
863 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
864 }
865}
866
867
868/**
869 * The 'vminfo' service description.
870 */
871VBOXSERVICE g_VMInfo =
872{
873 /* pszName. */
874 "vminfo",
875 /* pszDescription. */
876 "Virtual Machine Information",
877 /* pszUsage. */
878 " [--vminfo-interval <ms>]"
879 ,
880 /* pszOptions. */
881 " --vminfo-interval Specifies the interval at which to retrieve the\n"
882 " VM information. The default is 10000 ms.\n"
883 ,
884 /* methods */
885 VBoxServiceVMInfoPreInit,
886 VBoxServiceVMInfoOption,
887 VBoxServiceVMInfoInit,
888 VBoxServiceVMInfoWorker,
889 VBoxServiceVMInfoStop,
890 VBoxServiceVMInfoTerm
891};
892
Note: See TracBrowser for help on using the repository browser.

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