VirtualBox

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

Last change on this file since 51504 was 51503, checked in by vboxsync, 11 years ago

Additions/common/VBoxService: make most service call-back functions optional.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.0 KB
Line 
1/* $Id: VBoxServiceVMInfo.cpp 51503 2014-06-03 07:24:46Z vboxsync $ */
2/** @file
3 * VBoxService - Virtual Machine Information for the Host.
4 */
5
6/*
7 * Copyright (C) 2009-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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_OS2
47# include <net/if_dl.h>
48# endif
49# ifdef RT_OS_SOLARIS
50# include <sys/sockio.h>
51# include <net/if_arp.h>
52# endif
53# if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
54# include <ifaddrs.h> /* getifaddrs, freeifaddrs */
55# include <net/if_dl.h> /* LLADDR */
56# include <netdb.h> /* getnameinfo */
57# endif
58# ifdef VBOX_WITH_DBUS
59# include <VBox/dbus.h>
60# endif
61#endif
62
63#include <iprt/mem.h>
64#include <iprt/thread.h>
65#include <iprt/string.h>
66#include <iprt/semaphore.h>
67#include <iprt/system.h>
68#include <iprt/time.h>
69#include <iprt/assert.h>
70#include <VBox/version.h>
71#include <VBox/VBoxGuestLib.h>
72#include "VBoxServiceInternal.h"
73#include "VBoxServiceUtils.h"
74#include "VBoxServicePropCache.h"
75
76
77/** Structure containing information about a location awarness
78 * client provided by the host. */
79/** @todo Move this (and functions) into VbglR3. */
80typedef struct VBOXSERVICELACLIENTINFO
81{
82 uint32_t uID;
83 char *pszName;
84 char *pszLocation;
85 char *pszDomain;
86 bool fAttached;
87 uint64_t uAttachedTS;
88} VBOXSERVICELACLIENTINFO, *PVBOXSERVICELACLIENTINFO;
89
90
91/*******************************************************************************
92* Global Variables *
93*******************************************************************************/
94/** The vminfo interval (milliseconds). */
95static uint32_t g_cMsVMInfoInterval = 0;
96/** The semaphore we're blocking on. */
97static RTSEMEVENTMULTI g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
98/** The guest property service client ID. */
99static uint32_t g_uVMInfoGuestPropSvcClientID = 0;
100/** Number of currently logged in users in OS. */
101static uint32_t g_cVMInfoLoggedInUsers = 0;
102/** The guest property cache. */
103static VBOXSERVICEVEPROPCACHE g_VMInfoPropCache;
104static const char *g_pszPropCacheValLoggedInUsersList = "/VirtualBox/GuestInfo/OS/LoggedInUsersList";
105static const char *g_pszPropCacheValLoggedInUsers = "/VirtualBox/GuestInfo/OS/LoggedInUsers";
106static const char *g_pszPropCacheValNoLoggedInUsers = "/VirtualBox/GuestInfo/OS/NoLoggedInUsers";
107static const char *g_pszPropCacheValNetCount = "/VirtualBox/GuestInfo/Net/Count";
108/** A guest user's guest property root key. */
109static const char *g_pszPropCacheValUser = "/VirtualBox/GuestInfo/User/";
110/** The VM session ID. Changes whenever the VM is restored or reset. */
111static uint64_t g_idVMInfoSession;
112/** The last attached locartion awareness (LA) client timestamp. */
113static uint64_t g_LAClientAttachedTS = 0;
114/** The current LA client info. */
115static VBOXSERVICELACLIENTINFO g_LAClientInfo;
116/** User idle threshold (in ms). This specifies the minimum time a user is considered
117 * as being idle and then will be reported to the host. Default is 5s. */
118uint32_t g_uVMInfoUserIdleThresholdMS = 5 * 1000;
119
120
121/*******************************************************************************
122* Defines *
123*******************************************************************************/
124static const char *g_pszLAActiveClient = "/VirtualBox/HostInfo/VRDP/ActiveClient";
125
126#ifdef VBOX_WITH_DBUS
127/** ConsoleKit defines (taken from 0.4.5). */
128#define CK_NAME "org.freedesktop.ConsoleKit"
129#define CK_PATH "/org/freedesktop/ConsoleKit"
130#define CK_INTERFACE "org.freedesktop.ConsoleKit"
131
132#define CK_MANAGER_PATH "/org/freedesktop/ConsoleKit/Manager"
133#define CK_MANAGER_INTERFACE "org.freedesktop.ConsoleKit.Manager"
134#define CK_SEAT_INTERFACE "org.freedesktop.ConsoleKit.Seat"
135#define CK_SESSION_INTERFACE "org.freedesktop.ConsoleKit.Session"
136#endif
137
138
139
140/**
141 * Signals the event so that a re-enumeration of VM-specific
142 * information (like logged in users) can happen.
143 *
144 * @return IPRT status code.
145 */
146int VBoxServiceVMInfoSignal(void)
147{
148 /* Trigger a re-enumeration of all logged-in users by unblocking
149 * the multi event semaphore of the VMInfo thread. */
150 if (g_hVMInfoEvent)
151 return RTSemEventMultiSignal(g_hVMInfoEvent);
152
153 return VINF_SUCCESS;
154}
155
156
157/** @copydoc VBOXSERVICE::pfnOption */
158static DECLCALLBACK(int) VBoxServiceVMInfoOption(const char **ppszShort, int argc, char **argv, int *pi)
159{
160 /** @todo Use RTGetOpt here. */
161
162 int rc = -1;
163 if (ppszShort)
164 /* no short options */;
165 else if (!strcmp(argv[*pi], "--vminfo-interval"))
166 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
167 &g_cMsVMInfoInterval, 1, UINT32_MAX - 1);
168 else if (!strcmp(argv[*pi], "--vminfo-user-idle-threshold"))
169 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
170 &g_uVMInfoUserIdleThresholdMS, 1, UINT32_MAX - 1);
171 return rc;
172}
173
174
175/** @copydoc VBOXSERVICE::pfnInit */
176static DECLCALLBACK(int) VBoxServiceVMInfoInit(void)
177{
178 /*
179 * If not specified, find the right interval default.
180 * Then create the event sem to block on.
181 */
182 if (!g_cMsVMInfoInterval)
183 g_cMsVMInfoInterval = g_DefaultInterval * 1000;
184 if (!g_cMsVMInfoInterval)
185 {
186 /* Set it to 5s by default for location awareness checks. */
187 g_cMsVMInfoInterval = 5 * 1000;
188 }
189
190 int rc = RTSemEventMultiCreate(&g_hVMInfoEvent);
191 AssertRCReturn(rc, rc);
192
193 VbglR3GetSessionId(&g_idVMInfoSession);
194 /* The status code is ignored as this information is not available with VBox < 3.2.10. */
195
196 /* Initialize the LA client object. */
197 RT_ZERO(g_LAClientInfo);
198
199 rc = VbglR3GuestPropConnect(&g_uVMInfoGuestPropSvcClientID);
200 if (RT_SUCCESS(rc))
201 VBoxServiceVerbose(3, "Property Service Client ID: %#x\n", g_uVMInfoGuestPropSvcClientID);
202 else
203 {
204 /* If the service was not found, we disable this service without
205 causing VBoxService to fail. */
206 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
207 {
208 VBoxServiceVerbose(0, "Guest property service is not available, disabling the service\n");
209 rc = VERR_SERVICE_DISABLED;
210 }
211 else
212 VBoxServiceError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
213 RTSemEventMultiDestroy(g_hVMInfoEvent);
214 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
215 }
216
217 if (RT_SUCCESS(rc))
218 {
219 VBoxServicePropCacheCreate(&g_VMInfoPropCache, g_uVMInfoGuestPropSvcClientID);
220
221 /*
222 * Declare some guest properties with flags and reset values.
223 */
224 int rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsersList,
225 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, NULL /* Delete on exit */);
226 if (RT_FAILURE(rc2))
227 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValLoggedInUsersList, rc2);
228
229 rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsers,
230 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "0");
231 if (RT_FAILURE(rc2))
232 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValLoggedInUsers, rc2);
233
234 rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValNoLoggedInUsers,
235 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "true");
236 if (RT_FAILURE(rc2))
237 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValNoLoggedInUsers, rc2);
238
239 rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValNetCount,
240 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_ALWAYS_UPDATE, NULL /* Delete on exit */);
241 if (RT_FAILURE(rc2))
242 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValNetCount, rc2);
243
244 /*
245 * Get configuration guest properties from the host.
246 * Note: All properties should have sensible defaults in case the lookup here fails.
247 */
248 char *pszValue;
249 rc2 = VBoxServiceReadHostProp(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--vminfo-user-idle-threshold", true /* Read only */,
250 &pszValue, NULL /* Flags */, NULL /* Timestamp */);
251 if (RT_SUCCESS(rc2))
252 {
253 AssertPtr(pszValue);
254 g_uVMInfoUserIdleThresholdMS = RT_CLAMP(RTStrToUInt32(pszValue), 1000, UINT32_MAX - 1);
255 RTStrFree(pszValue);
256 }
257 }
258 return rc;
259}
260
261
262/**
263 * Retrieves a specifiy client LA property.
264 *
265 * @return IPRT status code.
266 * @param uClientID LA client ID to retrieve property for.
267 * @param pszProperty Property (without path) to retrieve.
268 * @param ppszValue Where to store value of property.
269 * @param puTimestamp Timestamp of property to retrieve. Optional.
270 */
271static int vboxServiceGetLAClientValue(uint32_t uClientID, const char *pszProperty,
272 char **ppszValue, uint64_t *puTimestamp)
273{
274 AssertReturn(uClientID, VERR_INVALID_PARAMETER);
275 AssertPtrReturn(pszProperty, VERR_INVALID_POINTER);
276
277 int rc;
278
279 char pszClientPath[255];
280 if (RTStrPrintf(pszClientPath, sizeof(pszClientPath),
281 "/VirtualBox/HostInfo/VRDP/Client/%RU32/%s", uClientID, pszProperty))
282 {
283 rc = VBoxServiceReadHostProp(g_uVMInfoGuestPropSvcClientID, pszClientPath, true /* Read only */,
284 ppszValue, NULL /* Flags */, puTimestamp);
285 }
286 else
287 rc = VERR_NO_MEMORY;
288
289 return rc;
290}
291
292
293/**
294 * Retrieves LA client information. On success the returned structure will have allocated
295 * objects which need to be free'd with vboxServiceFreeLAClientInfo.
296 *
297 * @return IPRT status code.
298 * @param uClientID Client ID to retrieve information for.
299 * @param pClient Pointer where to store the client information.
300 */
301static int vboxServiceGetLAClientInfo(uint32_t uClientID, PVBOXSERVICELACLIENTINFO pClient)
302{
303 AssertReturn(uClientID, VERR_INVALID_PARAMETER);
304 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
305
306 int rc = vboxServiceGetLAClientValue(uClientID, "Name", &pClient->pszName,
307 NULL /* Timestamp */);
308 if (RT_SUCCESS(rc))
309 {
310 char *pszAttach;
311 rc = vboxServiceGetLAClientValue(uClientID, "Attach", &pszAttach,
312 &pClient->uAttachedTS);
313 if (RT_SUCCESS(rc))
314 {
315 AssertPtr(pszAttach);
316 pClient->fAttached = !RTStrICmp(pszAttach, "1") ? true : false;
317
318 RTStrFree(pszAttach);
319 }
320 }
321 if (RT_SUCCESS(rc))
322 rc = vboxServiceGetLAClientValue(uClientID, "Location", &pClient->pszLocation,
323 NULL /* Timestamp */);
324 if (RT_SUCCESS(rc))
325 rc = vboxServiceGetLAClientValue(uClientID, "Domain", &pClient->pszDomain,
326 NULL /* Timestamp */);
327 if (RT_SUCCESS(rc))
328 pClient->uID = uClientID;
329
330 return rc;
331}
332
333
334/**
335 * Frees all allocated LA client information of a structure.
336 *
337 * @param pClient Pointer to client information structure to free.
338 */
339static void vboxServiceFreeLAClientInfo(PVBOXSERVICELACLIENTINFO pClient)
340{
341 if (pClient)
342 {
343 if (pClient->pszName)
344 {
345 RTStrFree(pClient->pszName);
346 pClient->pszName = NULL;
347 }
348 if (pClient->pszLocation)
349 {
350 RTStrFree(pClient->pszLocation);
351 pClient->pszLocation = NULL;
352 }
353 if (pClient->pszDomain)
354 {
355 RTStrFree(pClient->pszDomain);
356 pClient->pszDomain = NULL;
357 }
358 }
359}
360
361
362/**
363 * Updates a per-guest user guest property inside the given property cache.
364 *
365 * @return IPRT status code.
366 * @param pCache Pointer to guest property cache to update user in.
367 * @param pszUser Name of guest user to update.
368 * @param pszDomain Domain of guest user to update. Optional.
369 * @param pszKey Key name of guest property to update.
370 * @param pszValueFormat Guest property value to set. Pass NULL for deleting
371 * the property.
372 */
373int vboxServiceUserUpdateF(PVBOXSERVICEVEPROPCACHE pCache, const char *pszUser, const char *pszDomain,
374 const char *pszKey, const char *pszValueFormat, ...)
375{
376 AssertPtrReturn(pCache, VERR_INVALID_POINTER);
377 AssertPtrReturn(pszUser, VERR_INVALID_POINTER);
378 /* pszDomain is optional. */
379 AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
380 /* pszValueFormat is optional. */
381
382 int rc = VINF_SUCCESS;
383
384 char *pszName;
385 if (pszDomain)
386 {
387 if (!RTStrAPrintf(&pszName, "%s%s@%s/%s", g_pszPropCacheValUser, pszUser, pszDomain, pszKey))
388 rc = VERR_NO_MEMORY;
389 }
390 else
391 {
392 if (!RTStrAPrintf(&pszName, "%s%s/%s", g_pszPropCacheValUser, pszUser, pszKey))
393 rc = VERR_NO_MEMORY;
394 }
395
396 char *pszValue = NULL;
397 if ( RT_SUCCESS(rc)
398 && pszValueFormat)
399 {
400 va_list va;
401 va_start(va, pszValueFormat);
402 if (RTStrAPrintfV(&pszValue, pszValueFormat, va) < 0)
403 rc = VERR_NO_MEMORY;
404 va_end(va);
405 if ( RT_SUCCESS(rc)
406 && !pszValue)
407 rc = VERR_NO_STR_MEMORY;
408 }
409
410 if (RT_SUCCESS(rc))
411 rc = VBoxServicePropCacheUpdate(pCache, pszName, pszValue);
412 if (rc == VINF_SUCCESS) /* VBoxServicePropCacheUpdate will also return VINF_NO_CHANGE. */
413 {
414 /** @todo Combine updating flags w/ updating the actual value. */
415 rc = VBoxServicePropCacheUpdateEntry(pCache, pszName,
416 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT,
417 NULL /* Delete on exit */);
418 }
419
420 RTStrFree(pszValue);
421 RTStrFree(pszName);
422 return rc;
423}
424
425
426/**
427 * Writes the properties that won't change while the service is running.
428 *
429 * Errors are ignored.
430 */
431static void vboxserviceVMInfoWriteFixedProperties(void)
432{
433 /*
434 * First get OS information that won't change.
435 */
436 char szInfo[256];
437 int rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szInfo, sizeof(szInfo));
438 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Product",
439 "%s", RT_FAILURE(rc) ? "" : szInfo);
440
441 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szInfo, sizeof(szInfo));
442 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Release",
443 "%s", RT_FAILURE(rc) ? "" : szInfo);
444
445 rc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szInfo, sizeof(szInfo));
446 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Version",
447 "%s", RT_FAILURE(rc) ? "" : szInfo);
448
449 rc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szInfo, sizeof(szInfo));
450 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/ServicePack",
451 "%s", RT_FAILURE(rc) ? "" : szInfo);
452
453 /*
454 * Retrieve version information about Guest Additions and installed files (components).
455 */
456 char *pszAddVer;
457 char *pszAddVerExt;
458 char *pszAddRev;
459 rc = VbglR3GetAdditionsVersion(&pszAddVer, &pszAddVerExt, &pszAddRev);
460 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Version",
461 "%s", RT_FAILURE(rc) ? "" : pszAddVer);
462 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VersionExt",
463 "%s", RT_FAILURE(rc) ? "" : pszAddVerExt);
464 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Revision",
465 "%s", RT_FAILURE(rc) ? "" : pszAddRev);
466 if (RT_SUCCESS(rc))
467 {
468 RTStrFree(pszAddVer);
469 RTStrFree(pszAddVerExt);
470 RTStrFree(pszAddRev);
471 }
472
473#ifdef RT_OS_WINDOWS
474 /*
475 * Do windows specific properties.
476 */
477 char *pszInstDir;
478 rc = VbglR3GetAdditionsInstallationPath(&pszInstDir);
479 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/InstallDir",
480 "%s", RT_FAILURE(rc) ? "" : pszInstDir);
481 if (RT_SUCCESS(rc))
482 RTStrFree(pszInstDir);
483
484 VBoxServiceWinGetComponentVersions(g_uVMInfoGuestPropSvcClientID);
485#endif
486}
487
488#if defined(VBOX_WITH_DBUS) && defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
489/*
490 * Simple wrapper to work around compiler-specific va_list madness.
491 */
492static dbus_bool_t vboxService_dbus_message_get_args(DBusMessage *message,
493 DBusError *error,
494 int first_arg_type,
495 ...)
496{
497 va_list va;
498 va_start(va, first_arg_type);
499 dbus_bool_t ret = dbus_message_get_args_valist(message, error,
500 first_arg_type, va);
501 va_end(va);
502 return ret;
503}
504#endif
505
506/**
507 * Provide information about active users.
508 */
509static int vboxserviceVMInfoWriteUsers(void)
510{
511 int rc = VINF_SUCCESS;
512 char *pszUserList = NULL;
513 uint32_t cUsersInList = 0;
514
515#ifdef RT_OS_WINDOWS
516# ifndef TARGET_NT4
517 rc = VBoxServiceVMInfoWinWriteUsers(&g_VMInfoPropCache,
518 &pszUserList, &cUsersInList);
519# else
520 rc = VERR_NOT_IMPLEMENTED;
521# endif
522
523#elif defined(RT_OS_FREEBSD)
524 /** @todo FreeBSD: Port logged on user info retrieval.
525 * However, FreeBSD 9 supports utmpx, so we could use the code
526 * block below (?). */
527 rc = VERR_NOT_IMPLEMENTED;
528
529#elif defined(RT_OS_HAIKU)
530 /** @todo Haiku: Port logged on user info retrieval. */
531 rc = VERR_NOT_IMPLEMENTED;
532
533#elif defined(RT_OS_OS2)
534 /** @todo OS/2: Port logged on (LAN/local/whatever) user info retrieval. */
535 rc = VERR_NOT_IMPLEMENTED;
536
537#else
538 setutxent();
539 utmpx *ut_user;
540 uint32_t cListSize = 32;
541
542 /* Allocate a first array to hold 32 users max. */
543 char **papszUsers = (char **)RTMemAllocZ(cListSize * sizeof(char *));
544 if (papszUsers == NULL)
545 rc = VERR_NO_MEMORY;
546
547 /* Process all entries in the utmp file.
548 * Note: This only handles */
549 while ( (ut_user = getutxent())
550 && RT_SUCCESS(rc))
551 {
552# ifdef RT_OS_DARWIN /* No ut_user->ut_session on Darwin */
553 VBoxServiceVerbose(4, "Found entry \"%s\" (type: %d, PID: %RU32)\n",
554 ut_user->ut_user, ut_user->ut_type, ut_user->ut_pid);
555# else
556 VBoxServiceVerbose(4, "Found entry \"%s\" (type: %d, PID: %RU32, session: %RU32)\n",
557 ut_user->ut_user, ut_user->ut_type, ut_user->ut_pid, ut_user->ut_session);
558# endif
559 if (cUsersInList > cListSize)
560 {
561 cListSize += 32;
562 void *pvNew = RTMemRealloc(papszUsers, cListSize * sizeof(char*));
563 AssertPtrBreakStmt(pvNew, cListSize -= 32);
564 papszUsers = (char **)pvNew;
565 }
566
567 /* Make sure we don't add user names which are not
568 * part of type USER_PROCES. */
569 if (ut_user->ut_type == USER_PROCESS) /* Regular user process. */
570 {
571 bool fFound = false;
572 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
573 fFound = strcmp(papszUsers[i], ut_user->ut_user) == 0;
574
575 if (!fFound)
576 {
577 VBoxServiceVerbose(4, "Adding user \"%s\" (type: %d) to list\n",
578 ut_user->ut_user, ut_user->ut_type);
579
580 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ut_user->ut_user);
581 if (RT_FAILURE(rc))
582 break;
583 cUsersInList++;
584 }
585 }
586 }
587
588# ifdef VBOX_WITH_DBUS
589# if defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
590 DBusError dbErr;
591 DBusConnection *pConnection = NULL;
592 int rc2 = RTDBusLoadLib();
593 if (RT_SUCCESS(rc2))
594 {
595 /* Handle desktop sessions using ConsoleKit. */
596 VBoxServiceVerbose(4, "Checking ConsoleKit sessions ...\n");
597
598 dbus_error_init(&dbErr);
599 pConnection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbErr);
600 }
601
602 if ( pConnection
603 && !dbus_error_is_set(&dbErr))
604 {
605 /* Get all available sessions. */
606 DBusMessage *pMsgSessions = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
607 "/org/freedesktop/ConsoleKit/Manager",
608 "org.freedesktop.ConsoleKit.Manager",
609 "GetSessions");
610 if ( pMsgSessions
611 && (dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL))
612 {
613 DBusMessage *pReplySessions = dbus_connection_send_with_reply_and_block(pConnection,
614 pMsgSessions, 30 * 1000 /* 30s timeout */,
615 &dbErr);
616 if ( pReplySessions
617 && !dbus_error_is_set(&dbErr))
618 {
619 char **ppszSessions; int cSessions;
620 if ( (dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL)
621 && vboxService_dbus_message_get_args(pReplySessions, &dbErr, DBUS_TYPE_ARRAY,
622 DBUS_TYPE_OBJECT_PATH, &ppszSessions, &cSessions,
623 DBUS_TYPE_INVALID /* Termination */))
624 {
625 VBoxServiceVerbose(4, "ConsoleKit: retrieved %RU16 session(s)\n", cSessions);
626
627 char **ppszCurSession = ppszSessions;
628 for (ppszCurSession;
629 ppszCurSession && *ppszCurSession; ppszCurSession++)
630 {
631 VBoxServiceVerbose(4, "ConsoleKit: processing session '%s' ...\n", *ppszCurSession);
632
633 /* Only respect active sessions .*/
634 bool fActive = false;
635 DBusMessage *pMsgSessionActive = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
636 *ppszCurSession,
637 "org.freedesktop.ConsoleKit.Session",
638 "IsActive");
639 if ( pMsgSessionActive
640 && dbus_message_get_type(pMsgSessionActive) == DBUS_MESSAGE_TYPE_METHOD_CALL)
641 {
642 DBusMessage *pReplySessionActive = dbus_connection_send_with_reply_and_block(pConnection,
643 pMsgSessionActive, 30 * 1000 /* 30s timeout */,
644 &dbErr);
645 if ( pReplySessionActive
646 && !dbus_error_is_set(&dbErr))
647 {
648 DBusMessageIter itMsg;
649 if ( dbus_message_iter_init(pReplySessionActive, &itMsg)
650 && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_BOOLEAN)
651 {
652 /* Get uid from message. */
653 int val;
654 dbus_message_iter_get_basic(&itMsg, &val);
655 fActive = val >= 1;
656 }
657
658 if (pReplySessionActive)
659 dbus_message_unref(pReplySessionActive);
660 }
661
662 if (pMsgSessionActive)
663 dbus_message_unref(pMsgSessionActive);
664 }
665
666 VBoxServiceVerbose(4, "ConsoleKit: session '%s' is %s\n",
667 *ppszCurSession, fActive ? "active" : "not active");
668
669 /* *ppszCurSession now contains the object path
670 * (e.g. "/org/freedesktop/ConsoleKit/Session1"). */
671 DBusMessage *pMsgUnixUser = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
672 *ppszCurSession,
673 "org.freedesktop.ConsoleKit.Session",
674 "GetUnixUser");
675 if ( fActive
676 && pMsgUnixUser
677 && dbus_message_get_type(pMsgUnixUser) == DBUS_MESSAGE_TYPE_METHOD_CALL)
678 {
679 DBusMessage *pReplyUnixUser = dbus_connection_send_with_reply_and_block(pConnection,
680 pMsgUnixUser, 30 * 1000 /* 30s timeout */,
681 &dbErr);
682 if ( pReplyUnixUser
683 && !dbus_error_is_set(&dbErr))
684 {
685 DBusMessageIter itMsg;
686 if ( dbus_message_iter_init(pReplyUnixUser, &itMsg)
687 && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_UINT32)
688 {
689 /* Get uid from message. */
690 uint32_t uid;
691 dbus_message_iter_get_basic(&itMsg, &uid);
692
693 /** @todo Add support for getting UID_MIN (/etc/login.defs on
694 * Debian). */
695 uint32_t uid_min = 1000;
696
697 /* Look up user name (realname) from uid. */
698 setpwent();
699 struct passwd *ppwEntry = getpwuid(uid);
700 if ( ppwEntry
701 && ppwEntry->pw_uid >= uid_min /* Only respect users, not daemons etc. */
702 && ppwEntry->pw_name)
703 {
704 VBoxServiceVerbose(4, "ConsoleKit: session '%s' -> %s (uid: %RU32)\n",
705 *ppszCurSession, ppwEntry->pw_name, uid);
706
707 bool fFound = false;
708 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
709 fFound = strcmp(papszUsers[i], ppwEntry->pw_name) == 0;
710
711 if (!fFound)
712 {
713 VBoxServiceVerbose(4, "ConsoleKit: adding user \"%s\" to list\n",
714 ppwEntry->pw_name);
715
716 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ppwEntry->pw_name);
717 if (RT_FAILURE(rc))
718 break;
719 cUsersInList++;
720 }
721 }
722 else
723 VBoxServiceError("ConsoleKit: unable to lookup user name for uid=%RU32\n", uid);
724 }
725 else
726 AssertMsgFailed(("ConsoleKit: GetUnixUser returned a wrong argument type\n"));
727 }
728
729 if (pReplyUnixUser)
730 dbus_message_unref(pReplyUnixUser);
731 }
732 else
733 VBoxServiceError("ConsoleKit: unable to retrieve user for session '%s' (msg type=%d): %s",
734 *ppszCurSession, dbus_message_get_type(pMsgUnixUser),
735 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
736
737 if (pMsgUnixUser)
738 dbus_message_unref(pMsgUnixUser);
739 }
740
741 dbus_free_string_array(ppszSessions);
742 }
743 else
744 {
745 VBoxServiceError("ConsoleKit: unable to retrieve session parameters (msg type=%d): %s",
746 dbus_message_get_type(pMsgSessions),
747 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
748 }
749 dbus_message_unref(pReplySessions);
750 }
751
752 if (pMsgSessions)
753 {
754 dbus_message_unref(pMsgSessions);
755 pMsgSessions = NULL;
756 }
757 }
758 else
759 {
760 static int s_iBitchedAboutConsoleKit = 0;
761 if (s_iBitchedAboutConsoleKit++ < 3)
762 VBoxServiceError("Unable to invoke ConsoleKit (%d/3) -- maybe not installed / used? Error: %s\n",
763 s_iBitchedAboutConsoleKit,
764 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
765 }
766
767 if (pMsgSessions)
768 dbus_message_unref(pMsgSessions);
769 }
770 else
771 {
772 static int s_iBitchedAboutDBus = 0;
773 if (s_iBitchedAboutDBus++ < 3)
774 VBoxServiceError("Unable to connect to system D-Bus (%d/3): %s\n", s_iBitchedAboutDBus,
775 pConnection && dbus_error_is_set(&dbErr) ? dbErr.message : "D-Bus not installed");
776 }
777
778 if ( pConnection
779 && dbus_error_is_set(&dbErr))
780 dbus_error_free(&dbErr);
781# endif /* RT_OS_LINUX */
782# endif /* VBOX_WITH_DBUS */
783
784 /** @todo Fedora/others: Handle systemd-loginctl. */
785
786 /* Calc the string length. */
787 size_t cchUserList = 0;
788 if (RT_SUCCESS(rc))
789 {
790 for (uint32_t i = 0; i < cUsersInList; i++)
791 cchUserList += (i != 0) + strlen(papszUsers[i]);
792 }
793
794 /* Build the user list. */
795 if (cchUserList > 0)
796 {
797 if (RT_SUCCESS(rc))
798 rc = RTStrAllocEx(&pszUserList, cchUserList + 1);
799 if (RT_SUCCESS(rc))
800 {
801 char *psz = pszUserList;
802 for (uint32_t i = 0; i < cUsersInList; i++)
803 {
804 if (i != 0)
805 *psz++ = ',';
806 size_t cch = strlen(papszUsers[i]);
807 memcpy(psz, papszUsers[i], cch);
808 psz += cch;
809 }
810 *psz = '\0';
811 }
812 }
813
814 /* Cleanup. */
815 for (uint32_t i = 0; i < cUsersInList; i++)
816 RTStrFree(papszUsers[i]);
817 RTMemFree(papszUsers);
818
819 endutxent(); /* Close utmpx file. */
820#endif /* !RT_OS_WINDOWS && !RT_OS_FREEBSD && !RT_OS_HAIKU && !RT_OS_OS2 */
821
822 Assert(RT_FAILURE(rc) || cUsersInList == 0 || (pszUserList && *pszUserList));
823
824 /* If the user enumeration above failed, reset the user count to 0 except
825 * we didn't have enough memory anymore. In that case we want to preserve
826 * the previous user count in order to not confuse third party tools which
827 * rely on that count. */
828 if (RT_FAILURE(rc))
829 {
830 if (rc == VERR_NO_MEMORY)
831 {
832 static int s_iVMInfoBitchedOOM = 0;
833 if (s_iVMInfoBitchedOOM++ < 3)
834 VBoxServiceVerbose(0, "Warning: Not enough memory available to enumerate users! Keeping old value (%RU32)\n",
835 g_cVMInfoLoggedInUsers);
836 cUsersInList = g_cVMInfoLoggedInUsers;
837 }
838 else
839 cUsersInList = 0;
840 }
841 else /* Preserve logged in users count. */
842 g_cVMInfoLoggedInUsers = cUsersInList;
843
844 VBoxServiceVerbose(4, "cUsersInList=%RU32, pszUserList=%s, rc=%Rrc\n",
845 cUsersInList, pszUserList ? pszUserList : "<NULL>", rc);
846
847 if (pszUserList)
848 {
849 AssertMsg(cUsersInList, ("pszUserList contains users whereas cUsersInList is 0\n"));
850 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsersList, "%s", pszUserList);
851 }
852 else
853 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsersList, NULL);
854 if (RT_FAILURE(rc))
855 VBoxServiceError("Error writing logged in users list, rc=%Rrc\n", rc);
856
857 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsers, "%RU32", cUsersInList);
858 if (RT_FAILURE(rc))
859 VBoxServiceError("Error writing logged in users count, rc=%Rrc\n", rc);
860
861 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValNoLoggedInUsers,
862 cUsersInList == 0 ? "true" : "false");
863 if (RT_FAILURE(rc))
864 VBoxServiceError("Error writing no logged in users beacon, rc=%Rrc\n", rc);
865
866 if (pszUserList)
867 RTStrFree(pszUserList);
868
869 VBoxServiceVerbose(4, "Writing users returned with rc=%Rrc\n", rc);
870 return rc;
871}
872
873
874/**
875 * Provide information about the guest network.
876 */
877static int vboxserviceVMInfoWriteNetwork(void)
878{
879 int rc = VINF_SUCCESS;
880 uint32_t cIfsReported = 0;
881 char szPropPath[256];
882
883#ifdef RT_OS_WINDOWS
884 IP_ADAPTER_INFO *pAdpInfo = NULL;
885
886# ifndef TARGET_NT4
887 ULONG cbAdpInfo = sizeof(*pAdpInfo);
888 pAdpInfo = (IP_ADAPTER_INFO *)RTMemAlloc(cbAdpInfo);
889 if (!pAdpInfo)
890 {
891 VBoxServiceError("VMInfo/Network: Failed to allocate IP_ADAPTER_INFO\n");
892 return VERR_NO_MEMORY;
893 }
894 DWORD dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
895 if (dwRet == ERROR_BUFFER_OVERFLOW)
896 {
897 IP_ADAPTER_INFO *pAdpInfoNew = (IP_ADAPTER_INFO*)RTMemRealloc(pAdpInfo, cbAdpInfo);
898 if (pAdpInfoNew)
899 {
900 pAdpInfo = pAdpInfoNew;
901 dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
902 }
903 }
904 else if (dwRet == ERROR_NO_DATA)
905 {
906 VBoxServiceVerbose(3, "VMInfo/Network: No network adapters available\n");
907
908 /* If no network adapters available / present in the
909 * system we pretend success to not bail out too early. */
910 dwRet = ERROR_SUCCESS;
911 }
912
913 if (dwRet != ERROR_SUCCESS)
914 {
915 if (pAdpInfo)
916 RTMemFree(pAdpInfo);
917 VBoxServiceError("VMInfo/Network: Failed to get adapter info: Error %d\n", dwRet);
918 return RTErrConvertFromWin32(dwRet);
919 }
920# endif /* !TARGET_NT4 */
921
922 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
923 if (sd == SOCKET_ERROR) /* Socket invalid. */
924 {
925 int wsaErr = WSAGetLastError();
926 /* Don't complain/bail out with an error if network stack is not up; can happen
927 * on NT4 due to start up when not connected shares dialogs pop up. */
928 if (WSAENETDOWN == wsaErr)
929 {
930 VBoxServiceVerbose(0, "VMInfo/Network: Network is not up yet.\n");
931 wsaErr = VINF_SUCCESS;
932 }
933 else
934 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %d\n", wsaErr);
935 if (pAdpInfo)
936 RTMemFree(pAdpInfo);
937 return RTErrConvertFromWin32(wsaErr);
938 }
939
940 INTERFACE_INFO InterfaceList[20] = {0};
941 unsigned long nBytesReturned = 0;
942 if (WSAIoctl(sd,
943 SIO_GET_INTERFACE_LIST,
944 0,
945 0,
946 &InterfaceList,
947 sizeof(InterfaceList),
948 &nBytesReturned,
949 0,
950 0) == SOCKET_ERROR)
951 {
952 VBoxServiceError("VMInfo/Network: Failed to WSAIoctl() on socket: Error: %d\n", WSAGetLastError());
953 if (pAdpInfo)
954 RTMemFree(pAdpInfo);
955 return RTErrConvertFromWin32(WSAGetLastError());
956 }
957 int cIfacesSystem = nBytesReturned / sizeof(INTERFACE_INFO);
958
959 /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
960 for (int i = 0; i < cIfacesSystem; ++i)
961 {
962 sockaddr_in *pAddress;
963 u_long nFlags = 0;
964 if (InterfaceList[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
965 continue;
966 nFlags = InterfaceList[i].iiFlags;
967 pAddress = (sockaddr_in *)&(InterfaceList[i].iiAddress);
968 Assert(pAddress);
969 char szIp[32];
970 RTStrPrintf(szIp, sizeof(szIp), "%s", inet_ntoa(pAddress->sin_addr));
971 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/IP", cIfsReported);
972 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szIp);
973
974 pAddress = (sockaddr_in *) & (InterfaceList[i].iiBroadcastAddress);
975 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Broadcast", cIfsReported);
976 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
977
978 pAddress = (sockaddr_in *)&(InterfaceList[i].iiNetmask);
979 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Netmask", cIfsReported);
980 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
981
982 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/Status", cIfsReported);
983 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, nFlags & IFF_UP ? "Up" : "Down");
984
985# ifndef TARGET_NT4
986 IP_ADAPTER_INFO *pAdp;
987 for (pAdp = pAdpInfo; pAdp; pAdp = pAdp->Next)
988 if (!strcmp(pAdp->IpAddressList.IpAddress.String, szIp))
989 break;
990
991 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/MAC", cIfsReported);
992 if (pAdp)
993 {
994 char szMac[32];
995 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
996 pAdp->Address[0], pAdp->Address[1], pAdp->Address[2],
997 pAdp->Address[3], pAdp->Address[4], pAdp->Address[5]);
998 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
999 }
1000 else
1001 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, NULL);
1002# endif /* !TARGET_NT4 */
1003
1004 cIfsReported++;
1005 }
1006 if (pAdpInfo)
1007 RTMemFree(pAdpInfo);
1008 if (sd >= 0)
1009 closesocket(sd);
1010
1011#elif defined(RT_OS_HAIKU)
1012 /** @todo Haiku: implement network info. retreival */
1013 return VERR_NOT_IMPLEMENTED;
1014
1015#elif defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
1016 struct ifaddrs *pIfHead = NULL;
1017
1018 /* Get all available interfaces */
1019 rc = getifaddrs(&pIfHead);
1020 if (rc < 0)
1021 {
1022 rc = RTErrConvertFromErrno(errno);
1023 VBoxServiceError("VMInfo/Network: Failed to get all interfaces: Error %Rrc\n");
1024 return rc;
1025 }
1026
1027 /* Loop through all interfaces and set the data. */
1028 for (struct ifaddrs *pIfCurr = pIfHead; pIfCurr; pIfCurr = pIfCurr->ifa_next)
1029 {
1030 /*
1031 * Only AF_INET and no loopback interfaces
1032 */
1033 /** @todo: IPv6 interfaces */
1034 if ( pIfCurr->ifa_addr->sa_family == AF_INET
1035 && !(pIfCurr->ifa_flags & IFF_LOOPBACK))
1036 {
1037 char szInetAddr[NI_MAXHOST];
1038
1039 memset(szInetAddr, 0, NI_MAXHOST);
1040 getnameinfo(pIfCurr->ifa_addr, sizeof(struct sockaddr_in),
1041 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1042 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/IP", cIfsReported);
1043 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
1044
1045 memset(szInetAddr, 0, NI_MAXHOST);
1046 getnameinfo(pIfCurr->ifa_broadaddr, sizeof(struct sockaddr_in),
1047 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1048 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Broadcast", cIfsReported);
1049 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
1050
1051 memset(szInetAddr, 0, NI_MAXHOST);
1052 getnameinfo(pIfCurr->ifa_netmask, sizeof(struct sockaddr_in),
1053 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1054 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Netmask", cIfsReported);
1055 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
1056
1057 /* Search for the AF_LINK interface of the current AF_INET one and get the mac. */
1058 for (struct ifaddrs *pIfLinkCurr = pIfHead; pIfLinkCurr; pIfLinkCurr = pIfLinkCurr->ifa_next)
1059 {
1060 if ( pIfLinkCurr->ifa_addr->sa_family == AF_LINK
1061 && !strcmp(pIfCurr->ifa_name, pIfLinkCurr->ifa_name))
1062 {
1063 char szMac[32];
1064 uint8_t *pu8Mac = NULL;
1065 struct sockaddr_dl *pLinkAddress = (struct sockaddr_dl *)pIfLinkCurr->ifa_addr;
1066
1067 AssertPtr(pLinkAddress);
1068 pu8Mac = (uint8_t *)LLADDR(pLinkAddress);
1069 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
1070 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
1071 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/MAC", cIfsReported);
1072 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
1073 break;
1074 }
1075 }
1076
1077 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/Status", cIfsReported);
1078 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");
1079
1080 cIfsReported++;
1081 }
1082 }
1083
1084 /* Free allocated resources. */
1085 freeifaddrs(pIfHead);
1086
1087#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
1088 /*
1089 * Use SIOCGIFCONF to get a list of interface/protocol configurations.
1090 *
1091 * See "UNIX Network Programming Volume 1" by W. R. Stevens, section 17.6
1092 * for details on this ioctl.
1093 */
1094 int sd = socket(AF_INET, SOCK_DGRAM, 0);
1095 if (sd < 0)
1096 {
1097 rc = RTErrConvertFromErrno(errno);
1098 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
1099 return rc;
1100 }
1101
1102 /* Call SIOCGIFCONF with the right sized buffer (remember the size). */
1103 static int s_cbBuf = 256; // 1024
1104 int cbBuf = s_cbBuf;
1105 char *pchBuf;
1106 struct ifconf IfConf;
1107 rc = VINF_SUCCESS;
1108 for (;;)
1109 {
1110 pchBuf = (char *)RTMemTmpAllocZ(cbBuf);
1111 if (!pchBuf)
1112 {
1113 rc = VERR_NO_TMP_MEMORY;
1114 break;
1115 }
1116
1117 IfConf.ifc_len = cbBuf;
1118 IfConf.ifc_buf = pchBuf;
1119 if (ioctl(sd, SIOCGIFCONF, &IfConf) >= 0)
1120 {
1121 /* Hard to anticipate how space an address might possibly take, so
1122 making some generous assumptions here to avoid performing the
1123 query twice with different buffer sizes. */
1124 if (IfConf.ifc_len + 128 < cbBuf)
1125 break;
1126 }
1127 else if (errno != EOVERFLOW)
1128 {
1129 rc = RTErrConvertFromErrno(errno);
1130 break;
1131 }
1132
1133 /* grow the buffer */
1134 s_cbBuf = cbBuf *= 2;
1135 RTMemFree(pchBuf);
1136 }
1137 if (RT_FAILURE(rc))
1138 {
1139 close(sd);
1140 RTMemTmpFree(pchBuf);
1141 VBoxServiceError("VMInfo/Network: Error doing SIOCGIFCONF (cbBuf=%d): %Rrc\n", cbBuf, rc);
1142 return rc;
1143 }
1144
1145 /*
1146 * Iterate the interface/protocol configurations.
1147 *
1148 * Note! The current code naively assumes one IPv4 address per interface.
1149 * This means that guest assigning more than one address to an
1150 * interface will get multiple entries for one physical interface.
1151 */
1152# ifdef RT_OS_OS2
1153 struct ifreq *pPrevLinkAddr = NULL;
1154# endif
1155 struct ifreq *pCur = IfConf.ifc_req;
1156 size_t cbLeft = IfConf.ifc_len;
1157 while (cbLeft >= sizeof(*pCur))
1158 {
1159 /* Figure the size of the current request. */
1160 size_t cbCur = RT_OFFSETOF(struct ifreq, ifr_addr);
1161# if defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) /* No sa_len on this platforms. */
1162 Assert(pCur->ifr_addr.sa_family == AF_INET);
1163 cbCur += sizeof(struct sockaddr);
1164# else
1165 cbCur += RT_MAX(sizeof(struct sockaddr), pCur->ifr_addr.sa_len);
1166# endif
1167 AssertBreak(cbCur <= cbLeft);
1168
1169# ifdef RT_OS_OS2
1170 /* On OS/2 we get the MAC address in the AF_LINK that the BSD 4.4 stack
1171 emits. We boldly ASSUME these always comes first. */
1172 if ( pCur->ifr_addr.sa_family == AF_LINK
1173 && ((struct sockaddr_dl *)&pCur->ifr_addr)->sdl_alen == 6)
1174 pPrevLinkAddr = pCur;
1175# endif
1176
1177 /* Skip it if it's not the kind of address we're looking for. */
1178 struct ifreq IfReqTmp;
1179 bool fIfUp = false;
1180 bool fSkip = false;
1181 if (pCur->ifr_addr.sa_family != AF_INET)
1182 fSkip = true;
1183 else
1184 {
1185 /* Get the interface flags so we can detect loopback and check if it's up. */
1186 IfReqTmp = *pCur;
1187 if (ioctl(sd, SIOCGIFFLAGS, &IfReqTmp) < 0)
1188 {
1189 rc = RTErrConvertFromErrno(errno);
1190 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS,%s) on socket: Error %Rrc\n", pCur->ifr_name, rc);
1191 break;
1192 }
1193 fIfUp = !!(IfReqTmp.ifr_flags & IFF_UP);
1194 if (IfReqTmp.ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
1195 fSkip = true;
1196 }
1197 if (!fSkip)
1198 {
1199 size_t offSubProp = RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32", cIfsReported);
1200
1201 sockaddr_in *pAddress = (sockaddr_in *)&pCur->ifr_addr;
1202 strcpy(&szPropPath[offSubProp], "/V4/IP");
1203 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1204
1205 /* Get the broadcast address. */
1206 IfReqTmp = *pCur;
1207 if (ioctl(sd, SIOCGIFBRDADDR, &IfReqTmp) < 0)
1208 {
1209 rc = RTErrConvertFromErrno(errno);
1210 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
1211 break;
1212 }
1213 pAddress = (sockaddr_in *)&IfReqTmp.ifr_broadaddr;
1214 strcpy(&szPropPath[offSubProp], "/V4/Broadcast");
1215 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1216
1217 /* Get the net mask. */
1218 IfReqTmp = *pCur;
1219 if (ioctl(sd, SIOCGIFNETMASK, &IfReqTmp) < 0)
1220 {
1221 rc = RTErrConvertFromErrno(errno);
1222 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
1223 break;
1224 }
1225# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
1226 pAddress = (sockaddr_in *)&IfReqTmp.ifr_addr;
1227# else
1228 pAddress = (sockaddr_in *)&IfReqTmp.ifr_netmask;
1229# endif
1230 strcpy(&szPropPath[offSubProp], "/V4/Netmask");
1231 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1232
1233# if defined(RT_OS_SOLARIS)
1234 /*
1235 * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
1236 * We might fail if the interface has not been assigned an IP address.
1237 * That doesn't matter; as long as it's plumbed we can pick it up.
1238 * But, if it has not acquired an IP address we cannot obtain it's MAC
1239 * address this way, so we just use all zeros there.
1240 */
1241 RTMAC IfMac;
1242 struct lifreq IfReq;
1243 RT_ZERO(IfReq);
1244 AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(pCur->ifr_name));
1245 strncpy(IfReq.lifr_name, pCur->ifr_name, sizeof(pCur->ifr_name));
1246 if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
1247 {
1248 struct arpreq ArpReq;
1249 RT_ZERO(ArpReq);
1250 memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));
1251
1252 if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
1253 memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
1254 else
1255 {
1256 rc = RTErrConvertFromErrno(errno);
1257 VBoxServiceError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
1258 break;
1259 }
1260 }
1261 else
1262 {
1263 VBoxServiceVerbose(2, "VMInfo/Network: Interface \"%s\" has no assigned IP address, skipping ...\n", pCur->ifr_name);
1264 continue;
1265 }
1266# elif defined(RT_OS_OS2)
1267 RTMAC IfMac;
1268 if ( pPrevLinkAddr
1269 && strncmp(pCur->ifr_name, pPrevLinkAddr->ifr_name, sizeof(pCur->ifr_name)) == 0)
1270 {
1271 struct sockaddr_dl *pDlAddr = (struct sockaddr_dl *)&pPrevLinkAddr->ifr_addr;
1272 IfMac = *(PRTMAC)&pDlAddr->sdl_data[pDlAddr->sdl_nlen];
1273 }
1274 else
1275 RT_ZERO(IfMac);
1276#else
1277 if (ioctl(sd, SIOCGIFHWADDR, &IfReqTmp) < 0)
1278 {
1279 rc = RTErrConvertFromErrno(errno);
1280 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
1281 break;
1282 }
1283 RTMAC IfMac = *(PRTMAC)&IfReqTmp.ifr_hwaddr.sa_data[0];
1284# endif
1285 strcpy(&szPropPath[offSubProp], "/MAC");
1286 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%02X%02X%02X%02X%02X%02X",
1287 IfMac.au8[0], IfMac.au8[1], IfMac.au8[2], IfMac.au8[3], IfMac.au8[4], IfMac.au8[5]);
1288
1289 strcpy(&szPropPath[offSubProp], "/Status");
1290 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");
1291
1292 /* The name. */
1293 int rc2 = RTStrValidateEncodingEx(pCur->ifr_name, sizeof(pCur->ifr_name), 0);
1294 if (RT_SUCCESS(rc2))
1295 {
1296 strcpy(&szPropPath[offSubProp], "/Name");
1297 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%.*s", sizeof(pCur->ifr_name), pCur->ifr_name);
1298 }
1299
1300 cIfsReported++;
1301 }
1302
1303 /*
1304 * Next interface/protocol configuration.
1305 */
1306 pCur = (struct ifreq *)((uintptr_t)pCur + cbCur);
1307 cbLeft -= cbCur;
1308 }
1309
1310 RTMemTmpFree(pchBuf);
1311 close(sd);
1312 if (RT_FAILURE(rc))
1313 VBoxServiceError("VMInfo/Network: Network enumeration for interface %RU32 failed with error %Rrc\n", cIfsReported, rc);
1314
1315#endif /* !RT_OS_WINDOWS */
1316
1317#if 0 /* Zapping not enabled yet, needs more testing first. */
1318 /*
1319 * Zap all stale network interface data if the former (saved) network ifaces count
1320 * is bigger than the current one.
1321 */
1322
1323 /* Get former count. */
1324 uint32_t cIfsReportedOld;
1325 rc = VBoxServiceReadPropUInt32(g_uVMInfoGuestPropSvcClientID, g_pszPropCacheValNetCount, &cIfsReportedOld,
1326 0 /* Min */, UINT32_MAX /* Max */);
1327 if ( RT_SUCCESS(rc)
1328 && cIfsReportedOld > cIfsReported) /* Are some ifaces not around anymore? */
1329 {
1330 VBoxServiceVerbose(3, "VMInfo/Network: Stale interface data detected (%RU32 old vs. %RU32 current)\n",
1331 cIfsReportedOld, cIfsReported);
1332
1333 uint32_t uIfaceDeleteIdx = cIfsReported;
1334 do
1335 {
1336 VBoxServiceVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
1337 rc = VBoxServicePropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%RU32", uIfaceDeleteIdx++);
1338 } while (RT_SUCCESS(rc));
1339 }
1340 else if ( RT_FAILURE(rc)
1341 && rc != VERR_NOT_FOUND)
1342 {
1343 VBoxServiceError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
1344 }
1345#endif
1346
1347 /*
1348 * This property is a beacon which is _always_ written, even if the network configuration
1349 * does not change. If this property is missing, the host assumes that all other GuestInfo
1350 * properties are no longer valid.
1351 */
1352 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValNetCount, "%RU32",
1353 cIfsReported);
1354
1355 /* Don't fail here; just report everything we got. */
1356 return VINF_SUCCESS;
1357}
1358
1359
1360/** @copydoc VBOXSERVICE::pfnWorker */
1361DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
1362{
1363 int rc;
1364
1365 /*
1366 * Tell the control thread that it can continue
1367 * spawning services.
1368 */
1369 RTThreadUserSignal(RTThreadSelf());
1370
1371#ifdef RT_OS_WINDOWS
1372 /* Required for network information (must be called per thread). */
1373 WSADATA wsaData;
1374 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
1375 VBoxServiceError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
1376#endif /* RT_OS_WINDOWS */
1377
1378 /*
1379 * Write the fixed properties first.
1380 */
1381 vboxserviceVMInfoWriteFixedProperties();
1382
1383 /*
1384 * Now enter the loop retrieving runtime data continuously.
1385 */
1386 for (;;)
1387 {
1388 rc = vboxserviceVMInfoWriteUsers();
1389 if (RT_FAILURE(rc))
1390 break;
1391
1392 rc = vboxserviceVMInfoWriteNetwork();
1393 if (RT_FAILURE(rc))
1394 break;
1395
1396 /* Whether to wait for event semaphore or not. */
1397 bool fWait = true;
1398
1399 /* Check for location awareness. This most likely only
1400 * works with VBox (latest) 4.1 and up. */
1401
1402 /* Check for new connection. */
1403 char *pszLAClientID = NULL;
1404 int rc2 = VBoxServiceReadHostProp(g_uVMInfoGuestPropSvcClientID, g_pszLAActiveClient, true /* Read only */,
1405 &pszLAClientID, NULL /* Flags */, NULL /* Timestamp */);
1406 if (RT_SUCCESS(rc2))
1407 {
1408 AssertPtr(pszLAClientID);
1409 if (RTStrICmp(pszLAClientID, "0")) /* Is a client connected? */
1410 {
1411 uint32_t uLAClientID = RTStrToInt32(pszLAClientID);
1412 uint64_t uLAClientAttachedTS;
1413
1414 /* Peek at "Attach" value to figure out if hotdesking happened. */
1415 char *pszAttach = NULL;
1416 rc2 = vboxServiceGetLAClientValue(uLAClientID, "Attach", &pszAttach,
1417 &uLAClientAttachedTS);
1418
1419 if ( RT_SUCCESS(rc2)
1420 && ( !g_LAClientAttachedTS
1421 || (g_LAClientAttachedTS != uLAClientAttachedTS)))
1422 {
1423 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1424
1425 /* Note: There is a race between setting the guest properties by the host and getting them by
1426 * the guest. */
1427 rc2 = vboxServiceGetLAClientInfo(uLAClientID, &g_LAClientInfo);
1428 if (RT_SUCCESS(rc2))
1429 {
1430 VBoxServiceVerbose(1, "VRDP: Hotdesk client %s with ID=%RU32, Name=%s, Domain=%s\n",
1431 /* If g_LAClientAttachedTS is 0 this means there already was an active
1432 * hotdesk session when VBoxService started. */
1433 !g_LAClientAttachedTS ? "already active" : g_LAClientInfo.fAttached ? "connected" : "disconnected",
1434 uLAClientID, g_LAClientInfo.pszName, g_LAClientInfo.pszDomain);
1435
1436 g_LAClientAttachedTS = g_LAClientInfo.uAttachedTS;
1437
1438 /* Don't wait for event semaphore below anymore because we now know that the client
1439 * changed. This means we need to iterate all VM information again immediately. */
1440 fWait = false;
1441 }
1442 else
1443 {
1444 static int s_iBitchedAboutLAClientInfo = 0;
1445 if (s_iBitchedAboutLAClientInfo++ < 10)
1446 VBoxServiceError("Error getting active location awareness client info, rc=%Rrc\n", rc2);
1447 }
1448 }
1449 else if (RT_FAILURE(rc2))
1450 VBoxServiceError("Error getting attached value of location awareness client %RU32, rc=%Rrc\n",
1451 uLAClientID, rc2);
1452 if (pszAttach)
1453 RTStrFree(pszAttach);
1454 }
1455 else
1456 {
1457 VBoxServiceVerbose(1, "VRDP: UTTSC disconnected from VRDP server\n");
1458 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1459 }
1460
1461 RTStrFree(pszLAClientID);
1462 }
1463 else
1464 {
1465 static int s_iBitchedAboutLAClient = 0;
1466 if ( (rc2 != VERR_NOT_FOUND) /* No location awareness installed, skip. */
1467 && s_iBitchedAboutLAClient++ < 3)
1468 VBoxServiceError("VRDP: Querying connected location awareness client failed with rc=%Rrc\n", rc2);
1469 }
1470
1471 VBoxServiceVerbose(3, "VRDP: Handling location awareness done\n");
1472
1473 /*
1474 * Flush all properties if we were restored.
1475 */
1476 uint64_t idNewSession = g_idVMInfoSession;
1477 VbglR3GetSessionId(&idNewSession);
1478 if (idNewSession != g_idVMInfoSession)
1479 {
1480 VBoxServiceVerbose(3, "The VM session ID changed, flushing all properties\n");
1481 vboxserviceVMInfoWriteFixedProperties();
1482 VBoxServicePropCacheFlush(&g_VMInfoPropCache);
1483 g_idVMInfoSession = idNewSession;
1484 }
1485
1486 /*
1487 * Block for a while.
1488 *
1489 * The event semaphore takes care of ignoring interruptions and it
1490 * allows us to implement service wakeup later.
1491 */
1492 if (*pfShutdown)
1493 break;
1494 if (fWait)
1495 rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
1496 if (*pfShutdown)
1497 break;
1498 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
1499 {
1500 VBoxServiceError("RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
1501 rc = rc2;
1502 break;
1503 }
1504 else if (RT_LIKELY(RT_SUCCESS(rc2)))
1505 {
1506 /* Reset event semaphore if it got triggered. */
1507 rc2 = RTSemEventMultiReset(g_hVMInfoEvent);
1508 if (RT_FAILURE(rc2))
1509 rc2 = VBoxServiceError("RTSemEventMultiReset failed; rc2=%Rrc\n", rc2);
1510 }
1511 }
1512
1513#ifdef RT_OS_WINDOWS
1514 WSACleanup();
1515#endif
1516
1517 return rc;
1518}
1519
1520
1521/** @copydoc VBOXSERVICE::pfnStop */
1522static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
1523{
1524 RTSemEventMultiSignal(g_hVMInfoEvent);
1525}
1526
1527
1528/** @copydoc VBOXSERVICE::pfnTerm */
1529static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
1530{
1531 if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
1532 {
1533 /** @todo temporary solution: Zap all values which are not valid
1534 * anymore when VM goes down (reboot/shutdown ). Needs to
1535 * be replaced with "temporary properties" later.
1536 *
1537 * One idea is to introduce a (HGCM-)session guest property
1538 * flag meaning that a guest property is only valid as long
1539 * as the HGCM session isn't closed (e.g. guest application
1540 * terminates). [don't remove till implemented]
1541 */
1542 /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
1543 * since it remembers what we've written. */
1544 /* Delete the "../Net" branch. */
1545 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
1546 int rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
1547
1548 /* Destroy LA client info. */
1549 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1550
1551 /* Destroy property cache. */
1552 VBoxServicePropCacheDestroy(&g_VMInfoPropCache);
1553
1554 /* Disconnect from guest properties service. */
1555 rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
1556 if (RT_FAILURE(rc))
1557 VBoxServiceError("Failed to disconnect from guest property service! Error: %Rrc\n", rc);
1558 g_uVMInfoGuestPropSvcClientID = 0;
1559
1560 RTSemEventMultiDestroy(g_hVMInfoEvent);
1561 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
1562 }
1563}
1564
1565
1566/**
1567 * The 'vminfo' service description.
1568 */
1569VBOXSERVICE g_VMInfo =
1570{
1571 /* pszName. */
1572 "vminfo",
1573 /* pszDescription. */
1574 "Virtual Machine Information",
1575 /* pszUsage. */
1576 " [--vminfo-interval <ms>] [--vminfo-user-idle-threshold <ms>]"
1577 ,
1578 /* pszOptions. */
1579 " --vminfo-interval Specifies the interval at which to retrieve the\n"
1580 " VM information. The default is 10000 ms.\n"
1581 " --vminfo-user-idle-threshold <ms>\n"
1582 " Specifies the user idle threshold (in ms) for\n"
1583 " considering a guest user as being idle. The default\n"
1584 " is 5000 (5 seconds).\n"
1585 ,
1586 /* methods */
1587 /* pfnPreInit */
1588 NULL,
1589 VBoxServiceVMInfoOption,
1590 VBoxServiceVMInfoInit,
1591 VBoxServiceVMInfoWorker,
1592 VBoxServiceVMInfoStop,
1593 VBoxServiceVMInfoTerm
1594};
1595
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