VirtualBox

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

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

VBoxService/VMInfo: Skip interface if no IP-address assigned on Solaris.

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