VirtualBox

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

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

Additions/VBoxService: solaris build fix

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