VirtualBox

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

Last change on this file since 44073 was 44073, checked in by vboxsync, 12 years ago

VBoxService/VMInfo: Added a todo.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.5 KB
Line 
1/* $Id: VBoxServiceVMInfo.cpp 44073 2012-12-10 09:39:49Z vboxsync $ */
2/** @file
3 * VBoxService - Virtual Machine Information for the Host.
4 */
5
6/*
7 * Copyright (C) 2009-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23#ifdef RT_OS_WINDOWS
24# ifdef TARGET_NT4 /* HACK ALERT! PMIB_IPSTATS undefined if 0x0400 with newer SDKs. */
25# undef _WIN32_WINNT
26# define _WIN32_WINNT 0x0500
27# endif
28# include <winsock2.h>
29# include <iphlpapi.h>
30# include <ws2tcpip.h>
31# include <windows.h>
32# include <Ntsecapi.h>
33#else
34# define __STDC_LIMIT_MACROS
35# include <arpa/inet.h>
36# include <errno.h>
37# include <netinet/in.h>
38# include <sys/ioctl.h>
39# include <sys/socket.h>
40# include <net/if.h>
41# include <pwd.h> /* getpwuid */
42# include <unistd.h>
43# if !defined(RT_OS_OS2) && !defined(RT_OS_FREEBSD) && !defined(RT_OS_HAIKU)
44# include <utmpx.h> /* @todo FreeBSD 9 should have this. */
45# endif
46# ifdef RT_OS_SOLARIS
47# include <sys/sockio.h>
48# include <net/if_arp.h>
49# endif
50# ifdef RT_OS_FREEBSD
51# include <ifaddrs.h> /* getifaddrs, freeifaddrs */
52# include <net/if_dl.h> /* LLADDR */
53# include <netdb.h> /* getnameinfo */
54# endif
55# ifdef VBOX_WITH_DBUS
56# include <VBox/dbus.h>
57# endif
58#endif
59
60#include <iprt/mem.h>
61#include <iprt/thread.h>
62#include <iprt/string.h>
63#include <iprt/semaphore.h>
64#include <iprt/system.h>
65#include <iprt/time.h>
66#include <iprt/assert.h>
67#include <VBox/version.h>
68#include <VBox/VBoxGuestLib.h>
69#include "VBoxServiceInternal.h"
70#include "VBoxServiceUtils.h"
71#include "VBoxServicePropCache.h"
72
73
74/*******************************************************************************
75* Global Variables *
76*******************************************************************************/
77/** The vminfo interval (milliseconds). */
78static uint32_t g_cMsVMInfoInterval = 0;
79/** The semaphore we're blocking on. */
80static RTSEMEVENTMULTI g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
81/** The guest property service client ID. */
82static uint32_t g_uVMInfoGuestPropSvcClientID = 0;
83/** Number of logged in users in OS. */
84static uint32_t g_cVMInfoLoggedInUsers = UINT32_MAX;
85/** The guest property cache. */
86static VBOXSERVICEVEPROPCACHE g_VMInfoPropCache;
87/** The VM session ID. Changes whenever the VM is restored or reset. */
88static uint64_t g_idVMInfoSession;
89
90
91/*******************************************************************************
92* Defines *
93*******************************************************************************/
94#ifdef VBOX_WITH_DBUS
95/** ConsoleKit defines (taken from 0.4.5). */
96#define CK_NAME "org.freedesktop.ConsoleKit"
97#define CK_PATH "/org/freedesktop/ConsoleKit"
98#define CK_INTERFACE "org.freedesktop.ConsoleKit"
99
100#define CK_MANAGER_PATH "/org/freedesktop/ConsoleKit/Manager"
101#define CK_MANAGER_INTERFACE "org.freedesktop.ConsoleKit.Manager"
102#define CK_SEAT_INTERFACE "org.freedesktop.ConsoleKit.Seat"
103#define CK_SESSION_INTERFACE "org.freedesktop.ConsoleKit.Session"
104#endif
105
106
107
108/**
109 * Signals the event so that a re-enumeration of VM-specific
110 * information (like logged in users) can happen.
111 *
112 * @return IPRT status code.
113 */
114int VBoxServiceVMInfoSignal(void)
115{
116 /* Trigger a re-enumeration of all logged-in users by unblocking
117 * the multi event semaphore of the VMInfo thread. */
118 if (g_hVMInfoEvent)
119 return RTSemEventMultiSignal(g_hVMInfoEvent);
120
121 return VINF_SUCCESS;
122}
123
124
125/** @copydoc VBOXSERVICE::pfnPreInit */
126static DECLCALLBACK(int) VBoxServiceVMInfoPreInit(void)
127{
128 return VINF_SUCCESS;
129}
130
131
132/** @copydoc VBOXSERVICE::pfnOption */
133static DECLCALLBACK(int) VBoxServiceVMInfoOption(const char **ppszShort, int argc, char **argv, int *pi)
134{
135 int rc = -1;
136 if (ppszShort)
137 /* no short options */;
138 else if (!strcmp(argv[*pi], "--vminfo-interval"))
139 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
140 &g_cMsVMInfoInterval, 1, UINT32_MAX - 1);
141 return rc;
142}
143
144
145/** @copydoc VBOXSERVICE::pfnInit */
146static DECLCALLBACK(int) VBoxServiceVMInfoInit(void)
147{
148 /*
149 * If not specified, find the right interval default.
150 * Then create the event sem to block on.
151 */
152 if (!g_cMsVMInfoInterval)
153 g_cMsVMInfoInterval = g_DefaultInterval * 1000;
154 if (!g_cMsVMInfoInterval)
155 g_cMsVMInfoInterval = 10 * 1000;
156
157 int rc = RTSemEventMultiCreate(&g_hVMInfoEvent);
158 AssertRCReturn(rc, rc);
159
160 VbglR3GetSessionId(&g_idVMInfoSession);
161 /* The status code is ignored as this information is not available with VBox < 3.2.10. */
162
163 rc = VbglR3GuestPropConnect(&g_uVMInfoGuestPropSvcClientID);
164 if (RT_SUCCESS(rc))
165 VBoxServiceVerbose(3, "VMInfo: Property Service Client ID: %#x\n", g_uVMInfoGuestPropSvcClientID);
166 else
167 {
168 /* If the service was not found, we disable this service without
169 causing VBoxService to fail. */
170 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
171 {
172 VBoxServiceVerbose(0, "VMInfo: Guest property service is not available, disabling the service\n");
173 rc = VERR_SERVICE_DISABLED;
174 }
175 else
176 VBoxServiceError("VMInfo: Failed to connect to the guest property service! Error: %Rrc\n", rc);
177 RTSemEventMultiDestroy(g_hVMInfoEvent);
178 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
179 }
180
181 if (RT_SUCCESS(rc))
182 {
183 VBoxServicePropCacheCreate(&g_VMInfoPropCache, g_uVMInfoGuestPropSvcClientID);
184
185 /*
186 * Declare some guest properties with flags and reset values.
187 */
188 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList",
189 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, NULL /* Delete on exit */);
190 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsers",
191 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "0");
192 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
193 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "true");
194 VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/Net/Count",
195 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_ALWAYS_UPDATE, NULL /* Delete on exit */);
196 }
197 return rc;
198}
199
200
201/**
202 * Writes the properties that won't change while the service is running.
203 *
204 * Errors are ignored.
205 */
206static void vboxserviceVMInfoWriteFixedProperties(void)
207{
208 /*
209 * First get OS information that won't change.
210 */
211 char szInfo[256];
212 int rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szInfo, sizeof(szInfo));
213 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Product",
214 "%s", RT_FAILURE(rc) ? "" : szInfo);
215
216 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szInfo, sizeof(szInfo));
217 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Release",
218 "%s", RT_FAILURE(rc) ? "" : szInfo);
219
220 rc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szInfo, sizeof(szInfo));
221 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Version",
222 "%s", RT_FAILURE(rc) ? "" : szInfo);
223
224 rc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szInfo, sizeof(szInfo));
225 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/ServicePack",
226 "%s", RT_FAILURE(rc) ? "" : szInfo);
227
228 /*
229 * Retrieve version information about Guest Additions and installed files (components).
230 */
231 char *pszAddVer;
232 char *pszAddVerExt;
233 char *pszAddRev;
234 rc = VbglR3GetAdditionsVersion(&pszAddVer, &pszAddVerExt, &pszAddRev);
235 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Version",
236 "%s", RT_FAILURE(rc) ? "" : pszAddVer);
237 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VersionExt",
238 "%s", RT_FAILURE(rc) ? "" : pszAddVerExt);
239 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Revision",
240 "%s", RT_FAILURE(rc) ? "" : pszAddRev);
241 if (RT_SUCCESS(rc))
242 {
243 RTStrFree(pszAddVer);
244 RTStrFree(pszAddVerExt);
245 RTStrFree(pszAddRev);
246 }
247
248#ifdef RT_OS_WINDOWS
249 /*
250 * Do windows specific properties.
251 */
252 char *pszInstDir;
253 rc = VbglR3GetAdditionsInstallationPath(&pszInstDir);
254 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/InstallDir",
255 "%s", RT_FAILURE(rc) ? "" : pszInstDir);
256 if (RT_SUCCESS(rc))
257 RTStrFree(pszInstDir);
258
259 VBoxServiceWinGetComponentVersions(g_uVMInfoGuestPropSvcClientID);
260#endif
261}
262
263#if defined(VBOX_WITH_DBUS) && defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
264/*
265 * Simple wrapper to work around compiler-specific va_list madness.
266 */
267static dbus_bool_t vboxService_dbus_message_get_args(DBusMessage *message,
268 DBusError *error,
269 int first_arg_type,
270 ...)
271{
272 va_list va;
273 va_start(va, first_arg_type);
274 dbus_bool_t ret = dbus_message_get_args_valist(message, error,
275 first_arg_type, va);
276 va_end(va);
277 return ret;
278}
279#endif
280
281/**
282 * Provide information about active users.
283 */
284static int vboxserviceVMInfoWriteUsers(void)
285{
286 int rc = VINF_SUCCESS;
287 char *pszUserList = NULL;
288 uint32_t cUsersInList = 0;
289
290#ifdef RT_OS_WINDOWS
291# ifndef TARGET_NT4
292 rc = VBoxServiceVMInfoWinWriteUsers(&pszUserList, &cUsersInList);
293# else
294 rc = VERR_NOT_IMPLEMENTED;
295# endif
296
297#elif defined(RT_OS_FREEBSD)
298 /** @todo FreeBSD: Port logged on user info retrieval.
299 * However, FreeBSD 9 supports utmpx, so we could use the code
300 * block below (?). */
301 rc = VERR_NOT_IMPLEMENTED;
302
303#elif defined(RT_OS_HAIKU)
304 /** @todo Haiku: Port logged on user info retrieval. */
305 rc = VERR_NOT_IMPLEMENTED;
306
307#elif defined(RT_OS_OS2)
308 /** @todo OS/2: Port logged on (LAN/local/whatever) user info retrieval. */
309 rc = VERR_NOT_IMPLEMENTED;
310
311#else
312 setutxent();
313 utmpx *ut_user;
314 uint32_t cListSize = 32;
315
316 /* Allocate a first array to hold 32 users max. */
317 char **papszUsers = (char **)RTMemAllocZ(cListSize * sizeof(char *));
318 if (papszUsers == NULL)
319 rc = VERR_NO_MEMORY;
320
321 /* Process all entries in the utmp file.
322 * Note: This only handles */
323 while ( (ut_user = getutxent())
324 && RT_SUCCESS(rc))
325 {
326 VBoxServiceVerbose(4, "Found entry \"%s\" (type: %d, PID: %RU32, session: %RU32)\n",
327 ut_user->ut_user, ut_user->ut_type, ut_user->ut_pid, ut_user->ut_session);
328 if (cUsersInList > cListSize)
329 {
330 cListSize += 32;
331 void *pvNew = RTMemRealloc(papszUsers, cListSize * sizeof(char*));
332 AssertPtrBreakStmt(pvNew, cListSize -= 32);
333 papszUsers = (char **)pvNew;
334 }
335
336 /* Make sure we don't add user names which are not
337 * part of type USER_PROCES. */
338 if (ut_user->ut_type == USER_PROCESS) /* Regular user process. */
339 {
340 bool fFound = false;
341 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
342 fFound = strcmp(papszUsers[i], ut_user->ut_user) == 0;
343
344 if (!fFound)
345 {
346 VBoxServiceVerbose(4, "Adding user \"%s\" (type: %d) to list\n",
347 ut_user->ut_user, ut_user->ut_type);
348
349 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ut_user->ut_user);
350 if (RT_FAILURE(rc))
351 break;
352 cUsersInList++;
353 }
354 }
355 }
356
357#ifdef VBOX_WITH_DBUS
358# if defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
359 DBusError dbErr;
360 DBusConnection *pConnection = NULL;
361 int rc2 = RTDBusLoadLib();
362 if (RT_SUCCESS(rc2))
363 {
364 /* Handle desktop sessions using ConsoleKit. */
365 VBoxServiceVerbose(4, "Checking ConsoleKit sessions ...\n");
366
367 dbus_error_init(&dbErr);
368 pConnection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbErr);
369 }
370
371 if ( pConnection
372 && !dbus_error_is_set(&dbErr))
373 {
374 /* Get all available sessions. */
375 DBusMessage *pMsgSessions = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
376 "/org/freedesktop/ConsoleKit/Manager",
377 "org.freedesktop.ConsoleKit.Manager",
378 "GetSessions");
379 if ( pMsgSessions
380 && (dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL))
381 {
382 DBusMessage *pReplySessions = dbus_connection_send_with_reply_and_block(pConnection,
383 pMsgSessions, 30 * 1000 /* 30s timeout */,
384 &dbErr);
385 if ( pReplySessions
386 && !dbus_error_is_set(&dbErr))
387 {
388 char **ppszSessions; int cSessions;
389 if ( (dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL)
390 && vboxService_dbus_message_get_args(pReplySessions, &dbErr, DBUS_TYPE_ARRAY,
391 DBUS_TYPE_OBJECT_PATH, &ppszSessions, &cSessions,
392 DBUS_TYPE_INVALID /* Termination */))
393 {
394 VBoxServiceVerbose(4, "ConsoleKit: retrieved %RU16 session(s)\n", cSessions);
395
396 char **ppszCurSession = ppszSessions;
397 for (ppszCurSession;
398 ppszCurSession && *ppszCurSession; ppszCurSession++)
399 {
400 VBoxServiceVerbose(4, "ConsoleKit: processing session '%s' ...\n", *ppszCurSession);
401
402 /* Only respect active sessions .*/
403 bool fActive = false;
404 DBusMessage *pMsgSessionActive = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
405 *ppszCurSession,
406 "org.freedesktop.ConsoleKit.Session",
407 "IsActive");
408 if ( pMsgSessionActive
409 && dbus_message_get_type(pMsgSessionActive) == DBUS_MESSAGE_TYPE_METHOD_CALL)
410 {
411 DBusMessage *pReplySessionActive = dbus_connection_send_with_reply_and_block(pConnection,
412 pMsgSessionActive, 30 * 1000 /* 30s timeout */,
413 &dbErr);
414 if ( pReplySessionActive
415 && !dbus_error_is_set(&dbErr))
416 {
417 DBusMessageIter itMsg;
418 if ( dbus_message_iter_init(pReplySessionActive, &itMsg)
419 && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_BOOLEAN)
420 {
421 /* Get uid from message. */
422 int val;
423 dbus_message_iter_get_basic(&itMsg, &val);
424 fActive = val >= 1;
425 }
426
427 if (pReplySessionActive)
428 dbus_message_unref(pReplySessionActive);
429 }
430
431 if (pMsgSessionActive)
432 dbus_message_unref(pMsgSessionActive);
433 }
434
435 VBoxServiceVerbose(4, "ConsoleKit: session '%s' is %s\n",
436 *ppszCurSession, fActive ? "active" : "not active");
437
438 /* *ppszCurSession now contains the object path
439 * (e.g. "/org/freedesktop/ConsoleKit/Session1"). */
440 DBusMessage *pMsgUnixUser = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
441 *ppszCurSession,
442 "org.freedesktop.ConsoleKit.Session",
443 "GetUnixUser");
444 if ( fActive
445 && pMsgUnixUser
446 && dbus_message_get_type(pMsgUnixUser) == DBUS_MESSAGE_TYPE_METHOD_CALL)
447 {
448 DBusMessage *pReplyUnixUser = dbus_connection_send_with_reply_and_block(pConnection,
449 pMsgUnixUser, 30 * 1000 /* 30s timeout */,
450 &dbErr);
451 if ( pReplyUnixUser
452 && !dbus_error_is_set(&dbErr))
453 {
454 DBusMessageIter itMsg;
455 if ( dbus_message_iter_init(pReplyUnixUser, &itMsg)
456 && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_UINT32)
457 {
458 /* Get uid from message. */
459 uint32_t uid;
460 dbus_message_iter_get_basic(&itMsg, &uid);
461
462 /** @todo Add support for getting UID_MIN (/etc/login.defs on
463 * Debian). */
464 int uid_min = 1000;
465
466 /* Look up user name (realname) from uid. */
467 setpwent();
468 struct passwd *ppwEntry = getpwuid(uid);
469 if ( ppwEntry
470 && ppwEntry->pw_uid >= uid_min /* Only respect users, not daemons etc. */
471 && ppwEntry->pw_name)
472 {
473 VBoxServiceVerbose(4, "ConsoleKit: session '%s' -> %s (uid: %RU32)\n",
474 *ppszCurSession, ppwEntry->pw_name, uid);
475
476 bool fFound = false;
477 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
478 fFound = strcmp(papszUsers[i], ppwEntry->pw_name) == 0;
479
480 if (!fFound)
481 {
482 VBoxServiceVerbose(4, "ConsoleKit: adding user \"%s\" to list\n",
483 ppwEntry->pw_name);
484
485 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ppwEntry->pw_name);
486 if (RT_FAILURE(rc))
487 break;
488 cUsersInList++;
489 }
490 }
491 else
492 VBoxServiceError("ConsoleKit: unable to lookup user name for uid=%RU32\n", uid);
493 }
494 else
495 AssertMsgFailed(("ConsoleKit: GetUnixUser returned a wrong argument type\n"));
496 }
497
498 if (pReplyUnixUser)
499 dbus_message_unref(pReplyUnixUser);
500 }
501 else
502 VBoxServiceError("ConsoleKit: unable to retrieve user for session '%s' (msg type=%d): %s",
503 *ppszCurSession, dbus_message_get_type(pMsgUnixUser),
504 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available\n");
505
506 if (pMsgUnixUser)
507 dbus_message_unref(pMsgUnixUser);
508 }
509
510 dbus_free_string_array(ppszSessions);
511 }
512 else
513 {
514 VBoxServiceError("ConsoleKit: unable to retrieve session parameters (msg type=%d): %s",
515 dbus_message_get_type(pMsgSessions),
516 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available\n");
517 }
518 dbus_message_unref(pReplySessions);
519 }
520
521 if (pMsgSessions)
522 {
523 dbus_message_unref(pMsgSessions);
524 pMsgSessions = NULL;
525 }
526 }
527 else
528 {
529 static int s_iBitchedAboutConsoleKit = 0;
530 if (s_iBitchedAboutConsoleKit++ < 3)
531 VBoxServiceError("Unable to invoke ConsoleKit (%d/3) -- maybe not installed / used? Error: %s\n",
532 s_iBitchedAboutConsoleKit,
533 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available\n");
534 }
535
536 if (pMsgSessions)
537 dbus_message_unref(pMsgSessions);
538 }
539 else
540 {
541 static int s_iBitchedAboutDBus = 0;
542 if (s_iBitchedAboutDBus++ < 3)
543 VBoxServiceError("Unable to connect to system D-Bus (%d/3): %s\n", s_iBitchedAboutDBus,
544 dbus_error_is_set(&dbErr) ? dbErr.message : "D-Bus not installed\n");
545 }
546
547 if (dbus_error_is_set(&dbErr))
548 dbus_error_free(&dbErr);
549# endif /* RT_OS_LINUX */
550#endif /* VBOX_WITH_DBUS */
551
552 /** @todo Fedora/others: Handle systemd-loginctl. */
553
554 /* Calc the string length. */
555 size_t cchUserList = 0;
556 if (RT_SUCCESS(rc))
557 {
558 for (uint32_t i = 0; i < cUsersInList; i++)
559 cchUserList += (i != 0) + strlen(papszUsers[i]);
560 }
561
562 /* Build the user list. */
563 if (RT_SUCCESS(rc))
564 rc = RTStrAllocEx(&pszUserList, cchUserList + 1);
565 if (RT_SUCCESS(rc))
566 {
567 char *psz = pszUserList;
568 for (uint32_t i = 0; i < cUsersInList; i++)
569 {
570 if (i != 0)
571 *psz++ = ',';
572 size_t cch = strlen(papszUsers[i]);
573 memcpy(psz, papszUsers[i], cch);
574 psz += cch;
575 }
576 *psz = '\0';
577 }
578
579 /* Cleanup. */
580 for (uint32_t i = 0; i < cUsersInList; i++)
581 RTStrFree(papszUsers[i]);
582 RTMemFree(papszUsers);
583
584 endutxent(); /* Close utmpx file. */
585#endif
586 Assert(RT_FAILURE(rc) || cUsersInList == 0 || (pszUserList && *pszUserList));
587
588 /* If the user enumeration above failed, reset the user count to 0 except
589 * we didn't have enough memory anymore. In that case we want to preserve
590 * the previous user count in order to not confuse third party tools which
591 * rely on that count. */
592 if (RT_FAILURE(rc))
593 {
594 if (rc == VERR_NO_MEMORY)
595 {
596 static int s_iVMInfoBitchedOOM = 0;
597 if (s_iVMInfoBitchedOOM++ < 3)
598 VBoxServiceVerbose(0, "Warning: Not enough memory available to enumerate users! Keeping old value (%u)\n",
599 g_cVMInfoLoggedInUsers);
600 cUsersInList = g_cVMInfoLoggedInUsers;
601 }
602 else
603 cUsersInList = 0;
604 }
605
606 VBoxServiceVerbose(4, "cUsersInList=%RU32, pszUserList=%s, rc=%Rrc\n",
607 cUsersInList, pszUserList ? pszUserList : "<NULL>", rc);
608
609 if (pszUserList && cUsersInList > 0)
610 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", "%s", pszUserList);
611 else
612 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", NULL);
613 if (RT_FAILURE(rc))
614 {
615 VBoxServiceError("VMInfo: Error writing logged on users list, rc=%Rrc\n", rc);
616 cUsersInList = 0; /* Reset user count on error. */
617 }
618
619 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsers", "%u", cUsersInList);
620 if (RT_FAILURE(rc))
621 {
622 VBoxServiceError("VMInfo: Error writing logged on users count, rc=%Rrc\n", rc);
623 cUsersInList = 0; /* Reset user count on error. */
624 }
625
626 if (g_cVMInfoLoggedInUsers != cUsersInList)
627 {
628 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
629 cUsersInList == 0 ? "true" : "false");
630 if (RT_FAILURE(rc))
631 VBoxServiceError("VMInfo: Error writing no logged in users beacon, rc=%Rrc\n", rc);
632 g_cVMInfoLoggedInUsers = cUsersInList;
633 }
634 if (pszUserList)
635 RTStrFree(pszUserList);
636 return rc;
637}
638
639
640/**
641 * Provide information about the guest network.
642 */
643static int vboxserviceVMInfoWriteNetwork(void)
644{
645 int rc = VINF_SUCCESS;
646 uint32_t cIfacesReport = 0;
647 char szPropPath[256];
648
649#ifdef RT_OS_WINDOWS
650 IP_ADAPTER_INFO *pAdpInfo = NULL;
651
652# ifndef TARGET_NT4
653 ULONG cbAdpInfo = sizeof(*pAdpInfo);
654 pAdpInfo = (IP_ADAPTER_INFO *)RTMemAlloc(cbAdpInfo);
655 if (!pAdpInfo)
656 {
657 VBoxServiceError("VMInfo/Network: Failed to allocate IP_ADAPTER_INFO\n");
658 return VERR_NO_MEMORY;
659 }
660 DWORD dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
661 if (dwRet == ERROR_BUFFER_OVERFLOW)
662 {
663 IP_ADAPTER_INFO *pAdpInfoNew = (IP_ADAPTER_INFO*)RTMemRealloc(pAdpInfo, cbAdpInfo);
664 if (pAdpInfoNew)
665 {
666 pAdpInfo = pAdpInfoNew;
667 dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
668 }
669 }
670 else if (dwRet == ERROR_NO_DATA)
671 {
672 VBoxServiceVerbose(3, "VMInfo/Network: No network adapters available\n");
673
674 /* If no network adapters available / present in the
675 * system we pretend success to not bail out too early. */
676 dwRet = ERROR_SUCCESS;
677 }
678
679 if (dwRet != ERROR_SUCCESS)
680 {
681 if (pAdpInfo)
682 RTMemFree(pAdpInfo);
683 VBoxServiceError("VMInfo/Network: Failed to get adapter info: Error %d\n", dwRet);
684 return RTErrConvertFromWin32(dwRet);
685 }
686# endif /* !TARGET_NT4 */
687
688 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
689 if (sd == SOCKET_ERROR) /* Socket invalid. */
690 {
691 int wsaErr = WSAGetLastError();
692 /* Don't complain/bail out with an error if network stack is not up; can happen
693 * on NT4 due to start up when not connected shares dialogs pop up. */
694 if (WSAENETDOWN == wsaErr)
695 {
696 VBoxServiceVerbose(0, "VMInfo/Network: Network is not up yet.\n");
697 wsaErr = VINF_SUCCESS;
698 }
699 else
700 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %d\n", wsaErr);
701 if (pAdpInfo)
702 RTMemFree(pAdpInfo);
703 return RTErrConvertFromWin32(wsaErr);
704 }
705
706 INTERFACE_INFO InterfaceList[20] = {0};
707 unsigned long nBytesReturned = 0;
708 if (WSAIoctl(sd,
709 SIO_GET_INTERFACE_LIST,
710 0,
711 0,
712 &InterfaceList,
713 sizeof(InterfaceList),
714 &nBytesReturned,
715 0,
716 0) == SOCKET_ERROR)
717 {
718 VBoxServiceError("VMInfo/Network: Failed to WSAIoctl() on socket: Error: %d\n", WSAGetLastError());
719 if (pAdpInfo)
720 RTMemFree(pAdpInfo);
721 return RTErrConvertFromWin32(WSAGetLastError());
722 }
723 int cIfacesSystem = nBytesReturned / sizeof(INTERFACE_INFO);
724
725 /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
726 for (int i = 0; i < cIfacesSystem; ++i)
727 {
728 sockaddr_in *pAddress;
729 u_long nFlags = 0;
730 if (InterfaceList[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
731 continue;
732 nFlags = InterfaceList[i].iiFlags;
733 pAddress = (sockaddr_in *)&(InterfaceList[i].iiAddress);
734 Assert(pAddress);
735 char szIp[32];
736 RTStrPrintf(szIp, sizeof(szIp), "%s", inet_ntoa(pAddress->sin_addr));
737 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
738 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szIp);
739
740 pAddress = (sockaddr_in *) & (InterfaceList[i].iiBroadcastAddress);
741 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
742 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
743
744 pAddress = (sockaddr_in *)&(InterfaceList[i].iiNetmask);
745 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
746 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
747
748 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
749 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, nFlags & IFF_UP ? "Up" : "Down");
750
751# ifndef TARGET_NT4
752 IP_ADAPTER_INFO *pAdp;
753 for (pAdp = pAdpInfo; pAdp; pAdp = pAdp->Next)
754 if (!strcmp(pAdp->IpAddressList.IpAddress.String, szIp))
755 break;
756
757 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
758 if (pAdp)
759 {
760 char szMac[32];
761 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
762 pAdp->Address[0], pAdp->Address[1], pAdp->Address[2],
763 pAdp->Address[3], pAdp->Address[4], pAdp->Address[5]);
764 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
765 }
766 else
767 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, NULL);
768# endif /* !TARGET_NT4 */
769
770 cIfacesReport++;
771 }
772 if (pAdpInfo)
773 RTMemFree(pAdpInfo);
774 if (sd >= 0)
775 closesocket(sd);
776
777#elif defined(RT_OS_HAIKU)
778 /** @todo Haiku: implement network info. retreival */
779 return VERR_NOT_IMPLEMENTED;
780
781#elif defined(RT_OS_FREEBSD)
782 struct ifaddrs *pIfHead = NULL;
783
784 /* Get all available interfaces */
785 rc = getifaddrs(&pIfHead);
786 if (rc < 0)
787 {
788 rc = RTErrConvertFromErrno(errno);
789 VBoxServiceError("VMInfo/Network: Failed to get all interfaces: Error %Rrc\n");
790 return rc;
791 }
792
793 /* Loop through all interfaces and set the data. */
794 for (struct ifaddrs *pIfCurr = pIfHead; pIfCurr; pIfCurr = pIfCurr->ifa_next)
795 {
796 /*
797 * Only AF_INET and no loopback interfaces
798 * @todo: IPv6 interfaces
799 */
800 if ( pIfCurr->ifa_addr->sa_family == AF_INET
801 && !(pIfCurr->ifa_flags & IFF_LOOPBACK))
802 {
803 char szInetAddr[NI_MAXHOST];
804
805 memset(szInetAddr, 0, NI_MAXHOST);
806 getnameinfo(pIfCurr->ifa_addr, sizeof(struct sockaddr_in),
807 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
808 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
809 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
810
811 memset(szInetAddr, 0, NI_MAXHOST);
812 getnameinfo(pIfCurr->ifa_broadaddr, sizeof(struct sockaddr_in),
813 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
814 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
815 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
816
817 memset(szInetAddr, 0, NI_MAXHOST);
818 getnameinfo(pIfCurr->ifa_netmask, sizeof(struct sockaddr_in),
819 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
820 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
821 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
822
823 /* Search for the AF_LINK interface of the current AF_INET one and get the mac. */
824 for (struct ifaddrs *pIfLinkCurr = pIfHead; pIfLinkCurr; pIfLinkCurr = pIfLinkCurr->ifa_next)
825 {
826 if ( pIfLinkCurr->ifa_addr->sa_family == AF_LINK
827 && !strcmp(pIfCurr->ifa_name, pIfLinkCurr->ifa_name))
828 {
829 char szMac[32];
830 uint8_t *pu8Mac = NULL;
831 struct sockaddr_dl *pLinkAddress = (struct sockaddr_dl *)pIfLinkCurr->ifa_addr;
832
833 AssertPtr(pLinkAddress);
834 pu8Mac = (uint8_t *)LLADDR(pLinkAddress);
835 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
836 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
837 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
838 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
839 break;
840 }
841 }
842
843 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
844 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");
845
846 cIfacesReport++;
847 }
848 }
849
850 /* Free allocated resources. */
851 freeifaddrs(pIfHead);
852
853#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
854 int sd = socket(AF_INET, SOCK_DGRAM, 0);
855 if (sd < 0)
856 {
857 rc = RTErrConvertFromErrno(errno);
858 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
859 return rc;
860 }
861
862 ifconf ifcfg;
863 char buffer[1024] = {0};
864 ifcfg.ifc_len = sizeof(buffer);
865 ifcfg.ifc_buf = buffer;
866 if (ioctl(sd, SIOCGIFCONF, &ifcfg) < 0)
867 {
868 close(sd);
869 rc = RTErrConvertFromErrno(errno);
870 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFCONF) on socket: Error %Rrc\n", rc);
871 return rc;
872 }
873
874 ifreq* ifrequest = ifcfg.ifc_req;
875 int cIfacesSystem = ifcfg.ifc_len / sizeof(ifreq);
876
877 for (int i = 0; i < cIfacesSystem; ++i)
878 {
879 sockaddr_in *pAddress;
880 if (ioctl(sd, SIOCGIFFLAGS, &ifrequest[i]) < 0)
881 {
882 rc = RTErrConvertFromErrno(errno);
883 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS) on socket: Error %Rrc\n", rc);
884 break;
885 }
886 if (ifrequest[i].ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
887 continue;
888
889 bool fIfUp = !!(ifrequest[i].ifr_flags & IFF_UP);
890 pAddress = ((sockaddr_in *)&ifrequest[i].ifr_addr);
891 Assert(pAddress);
892 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
893 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
894
895 if (ioctl(sd, SIOCGIFBRDADDR, &ifrequest[i]) < 0)
896 {
897 rc = RTErrConvertFromErrno(errno);
898 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
899 break;
900 }
901 pAddress = (sockaddr_in *)&ifrequest[i].ifr_broadaddr;
902 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
903 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
904
905 if (ioctl(sd, SIOCGIFNETMASK, &ifrequest[i]) < 0)
906 {
907 rc = RTErrConvertFromErrno(errno);
908 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
909 break;
910 }
911# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
912 pAddress = (sockaddr_in *)&ifrequest[i].ifr_addr;
913# else
914 pAddress = (sockaddr_in *)&ifrequest[i].ifr_netmask;
915# endif
916
917 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
918 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
919
920# if defined(RT_OS_SOLARIS)
921 /*
922 * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
923 * We might fail if the interface has not been assigned an IP address.
924 * That doesn't matter; as long as it's plumbed we can pick it up.
925 * But, if it has not acquired an IP address we cannot obtain it's MAC
926 * address this way, so we just use all zeros there.
927 */
928 RTMAC IfMac;
929 RT_ZERO(IfMac);
930 struct lifreq IfReq;
931 RT_ZERO(IfReq);
932 AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(ifrequest[i].ifr_name));
933 strncpy(IfReq.lifr_name, ifrequest[i].ifr_name, sizeof(ifrequest[i].ifr_name));
934 if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
935 {
936 struct arpreq ArpReq;
937 RT_ZERO(ArpReq);
938 memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));
939
940 if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
941 memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
942 else
943 {
944 rc = RTErrConvertFromErrno(errno);
945 VBoxServiceError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
946 break;
947 }
948 }
949 else
950 {
951 VBoxServiceVerbose(2, "VMInfo/Network: Interface %d has no assigned IP address, skipping ...\n", i);
952 continue;
953 }
954# else
955# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
956 if (ioctl(sd, SIOCGIFHWADDR, &ifrequest[i]) < 0)
957 {
958 rc = RTErrConvertFromErrno(errno);
959 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
960 break;
961 }
962# endif
963# endif
964
965# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
966 char szMac[32];
967# if defined(RT_OS_SOLARIS)
968 uint8_t *pu8Mac = IfMac.au8;
969# else
970 uint8_t *pu8Mac = (uint8_t*)&ifrequest[i].ifr_hwaddr.sa_data[0]; /* @todo see above */
971# endif
972 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
973 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
974 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
975 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
976# endif /* !OS/2*/
977
978 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
979 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");
980 cIfacesReport++;
981 } /* For all interfaces */
982
983 close(sd);
984 if (RT_FAILURE(rc))
985 VBoxServiceError("VMInfo/Network: Network enumeration for interface %u failed with error %Rrc\n", cIfacesReport, rc);
986
987#endif /* !RT_OS_WINDOWS */
988
989#if 0 /* Zapping not enabled yet, needs more testing first. */
990 /*
991 * Zap all stale network interface data if the former (saved) network ifaces count
992 * is bigger than the current one.
993 */
994
995 /* Get former count. */
996 uint32_t cIfacesReportOld;
997 rc = VBoxServiceReadPropUInt32(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/Net/Count", &cIfacesReportOld,
998 0 /* Min */, UINT32_MAX /* Max */);
999 if ( RT_SUCCESS(rc)
1000 && cIfacesReportOld > cIfacesReport) /* Are some ifaces not around anymore? */
1001 {
1002 VBoxServiceVerbose(3, "VMInfo/Network: Stale interface data detected (%u old vs. %u current)\n",
1003 cIfacesReportOld, cIfacesReport);
1004
1005 uint32_t uIfaceDeleteIdx = cIfacesReport;
1006 do
1007 {
1008 VBoxServiceVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
1009 rc = VBoxServicePropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%u", uIfaceDeleteIdx++);
1010 } while (RT_SUCCESS(rc));
1011 }
1012 else if ( RT_FAILURE(rc)
1013 && rc != VERR_NOT_FOUND)
1014 {
1015 VBoxServiceError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
1016 }
1017#endif
1018
1019 /*
1020 * This property is a beacon which is _always_ written, even if the network configuration
1021 * does not change. If this property is missing, the host assumes that all other GuestInfo
1022 * properties are no longer valid.
1023 */
1024 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/Net/Count", "%d",
1025 cIfacesReport);
1026
1027 /* Don't fail here; just report everything we got. */
1028 return VINF_SUCCESS;
1029}
1030
1031
1032/** @copydoc VBOXSERVICE::pfnWorker */
1033DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
1034{
1035 int rc;
1036
1037 /*
1038 * Tell the control thread that it can continue
1039 * spawning services.
1040 */
1041 RTThreadUserSignal(RTThreadSelf());
1042
1043#ifdef RT_OS_WINDOWS
1044 /* Required for network information (must be called per thread). */
1045 WSADATA wsaData;
1046 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
1047 VBoxServiceError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
1048#endif /* RT_OS_WINDOWS */
1049
1050 /*
1051 * Write the fixed properties first.
1052 */
1053 vboxserviceVMInfoWriteFixedProperties();
1054
1055 /*
1056 * Now enter the loop retrieving runtime data continuously.
1057 */
1058 for (;;)
1059 {
1060 rc = vboxserviceVMInfoWriteUsers();
1061 if (RT_FAILURE(rc))
1062 break;
1063
1064 rc = vboxserviceVMInfoWriteNetwork();
1065 if (RT_FAILURE(rc))
1066 break;
1067
1068 /*
1069 * Flush all properties if we were restored.
1070 */
1071 uint64_t idNewSession = g_idVMInfoSession;
1072 VbglR3GetSessionId(&idNewSession);
1073 if (idNewSession != g_idVMInfoSession)
1074 {
1075 VBoxServiceVerbose(3, "VMInfo: The VM session ID changed, flushing all properties\n");
1076 vboxserviceVMInfoWriteFixedProperties();
1077 VBoxServicePropCacheFlush(&g_VMInfoPropCache);
1078 g_idVMInfoSession = idNewSession;
1079 }
1080
1081 /*
1082 * Block for a while.
1083 *
1084 * The event semaphore takes care of ignoring interruptions and it
1085 * allows us to implement service wakeup later.
1086 */
1087 if (*pfShutdown)
1088 break;
1089 int rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
1090 if (*pfShutdown)
1091 break;
1092 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
1093 {
1094 VBoxServiceError("VMInfo: RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
1095 rc = rc2;
1096 break;
1097 }
1098 else if (RT_LIKELY(RT_SUCCESS(rc2)))
1099 {
1100 /* Reset event semaphore if it got triggered. */
1101 rc2 = RTSemEventMultiReset(g_hVMInfoEvent);
1102 if (RT_FAILURE(rc2))
1103 rc2 = VBoxServiceError("VMInfo: RTSemEventMultiReset failed; rc2=%Rrc\n", rc2);
1104 }
1105 }
1106
1107#ifdef RT_OS_WINDOWS
1108 WSACleanup();
1109#endif
1110
1111 return rc;
1112}
1113
1114
1115/** @copydoc VBOXSERVICE::pfnStop */
1116static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
1117{
1118 RTSemEventMultiSignal(g_hVMInfoEvent);
1119}
1120
1121
1122/** @copydoc VBOXSERVICE::pfnTerm */
1123static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
1124{
1125 if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
1126 {
1127 /** @todo temporary solution: Zap all values which are not valid
1128 * anymore when VM goes down (reboot/shutdown ). Needs to
1129 * be replaced with "temporary properties" later.
1130 *
1131 * One idea is to introduce a (HGCM-)session guest property
1132 * flag meaning that a guest property is only valid as long
1133 * as the HGCM session isn't closed (e.g. guest application
1134 * terminates). [don't remove till implemented]
1135 */
1136 /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
1137 * since it remembers what we've written. */
1138 /* Delete the "../Net" branch. */
1139 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
1140 int rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
1141
1142 /* Destroy property cache. */
1143 VBoxServicePropCacheDestroy(&g_VMInfoPropCache);
1144
1145 /* Disconnect from guest properties service. */
1146 rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
1147 if (RT_FAILURE(rc))
1148 VBoxServiceError("VMInfo: Failed to disconnect from guest property service! Error: %Rrc\n", rc);
1149 g_uVMInfoGuestPropSvcClientID = 0;
1150
1151 RTSemEventMultiDestroy(g_hVMInfoEvent);
1152 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
1153 }
1154}
1155
1156
1157/**
1158 * The 'vminfo' service description.
1159 */
1160VBOXSERVICE g_VMInfo =
1161{
1162 /* pszName. */
1163 "vminfo",
1164 /* pszDescription. */
1165 "Virtual Machine Information",
1166 /* pszUsage. */
1167 " [--vminfo-interval <ms>]"
1168 ,
1169 /* pszOptions. */
1170 " --vminfo-interval Specifies the interval at which to retrieve the\n"
1171 " VM information. The default is 10000 ms.\n"
1172 ,
1173 /* methods */
1174 VBoxServiceVMInfoPreInit,
1175 VBoxServiceVMInfoOption,
1176 VBoxServiceVMInfoInit,
1177 VBoxServiceVMInfoWorker,
1178 VBoxServiceVMInfoStop,
1179 VBoxServiceVMInfoTerm
1180};
1181
Note: See TracBrowser for help on using the repository browser.

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