VirtualBox

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

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

VBoxGuestR3LibAdditions: VersionEx -> VersionExt, refacatored code.

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