VirtualBox

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

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

Additions/VBoxServices: two warnings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 59.5 KB
Line 
1/* $Id: VBoxServiceVMInfo.cpp 47449 2013-07-29 08:06:14Z 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.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23#ifdef RT_OS_WINDOWS
24# ifdef TARGET_NT4 /* HACK ALERT! PMIB_IPSTATS undefined if 0x0400 with newer SDKs. */
25# undef _WIN32_WINNT
26# define _WIN32_WINNT 0x0500
27# endif
28# include <winsock2.h>
29# include <iphlpapi.h>
30# include <ws2tcpip.h>
31# include <windows.h>
32# include <Ntsecapi.h>
33#else
34# define __STDC_LIMIT_MACROS
35# include <arpa/inet.h>
36# include <errno.h>
37# include <netinet/in.h>
38# include <sys/ioctl.h>
39# include <sys/socket.h>
40# include <net/if.h>
41# include <pwd.h> /* getpwuid */
42# include <unistd.h>
43# if !defined(RT_OS_OS2) && !defined(RT_OS_FREEBSD) && !defined(RT_OS_HAIKU)
44# include <utmpx.h> /* @todo FreeBSD 9 should have this. */
45# endif
46# ifdef RT_OS_SOLARIS
47# include <sys/sockio.h>
48# include <net/if_arp.h>
49# endif
50# if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
51# include <ifaddrs.h> /* getifaddrs, freeifaddrs */
52# include <net/if_dl.h> /* LLADDR */
53# include <netdb.h> /* getnameinfo */
54# endif
55# ifdef VBOX_WITH_DBUS
56# include <VBox/dbus.h>
57# endif
58#endif
59
60#include <iprt/mem.h>
61#include <iprt/thread.h>
62#include <iprt/string.h>
63#include <iprt/semaphore.h>
64#include <iprt/system.h>
65#include <iprt/time.h>
66#include <iprt/assert.h>
67#include <VBox/version.h>
68#include <VBox/VBoxGuestLib.h>
69#include "VBoxServiceInternal.h"
70#include "VBoxServiceUtils.h"
71#include "VBoxServicePropCache.h"
72
73
74/** Structure containing information about a location awarness
75 * client provided by the host. */
76/** @todo Move this (and functions) into VbglR3. */
77typedef struct VBOXSERVICELACLIENTINFO
78{
79 uint32_t uID;
80 char *pszName;
81 char *pszLocation;
82 char *pszDomain;
83 bool fAttached;
84 uint64_t uAttachedTS;
85} VBOXSERVICELACLIENTINFO, *PVBOXSERVICELACLIENTINFO;
86
87
88/*******************************************************************************
89* Global Variables *
90*******************************************************************************/
91/** The vminfo interval (milliseconds). */
92static uint32_t g_cMsVMInfoInterval = 0;
93/** The semaphore we're blocking on. */
94static RTSEMEVENTMULTI g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
95/** The guest property service client ID. */
96static uint32_t g_uVMInfoGuestPropSvcClientID = 0;
97/** Number of currently logged in users in OS. */
98static uint32_t g_cVMInfoLoggedInUsers = 0;
99/** The guest property cache. */
100static VBOXSERVICEVEPROPCACHE g_VMInfoPropCache;
101static const char *g_pszPropCacheValLoggedInUsersList = "/VirtualBox/GuestInfo/OS/LoggedInUsersList";
102static const char *g_pszPropCacheValLoggedInUsers = "/VirtualBox/GuestInfo/OS/LoggedInUsers";
103static const char *g_pszPropCacheValNoLoggedInUsers = "/VirtualBox/GuestInfo/OS/NoLoggedInUsers";
104static const char *g_pszPropCacheValNetCount = "/VirtualBox/GuestInfo/Net/Count";
105/** A guest user's guest property root key. */
106static const char *g_pszPropCacheValUser = "/VirtualBox/GuestInfo/User/";
107/** The VM session ID. Changes whenever the VM is restored or reset. */
108static uint64_t g_idVMInfoSession;
109/** The last attached locartion awareness (LA) client timestamp. */
110static uint64_t g_LAClientAttachedTS = 0;
111/** The current LA client info. */
112static VBOXSERVICELACLIENTINFO g_LAClientInfo;
113/** User idle threshold. This specifies the minimum time a user is considered
114 * being idle and then will be reported to the host. Default is 5s. */
115uint32_t g_uVMInfoUserIdleThreshold = 5 * 1000;
116
117
118/*******************************************************************************
119* Defines *
120*******************************************************************************/
121static const char *g_pszLAActiveClient = "/VirtualBox/HostInfo/VRDP/ActiveClient";
122
123#ifdef VBOX_WITH_DBUS
124/** ConsoleKit defines (taken from 0.4.5). */
125#define CK_NAME "org.freedesktop.ConsoleKit"
126#define CK_PATH "/org/freedesktop/ConsoleKit"
127#define CK_INTERFACE "org.freedesktop.ConsoleKit"
128
129#define CK_MANAGER_PATH "/org/freedesktop/ConsoleKit/Manager"
130#define CK_MANAGER_INTERFACE "org.freedesktop.ConsoleKit.Manager"
131#define CK_SEAT_INTERFACE "org.freedesktop.ConsoleKit.Seat"
132#define CK_SESSION_INTERFACE "org.freedesktop.ConsoleKit.Session"
133#endif
134
135
136
137/**
138 * Signals the event so that a re-enumeration of VM-specific
139 * information (like logged in users) can happen.
140 *
141 * @return IPRT status code.
142 */
143int VBoxServiceVMInfoSignal(void)
144{
145 /* Trigger a re-enumeration of all logged-in users by unblocking
146 * the multi event semaphore of the VMInfo thread. */
147 if (g_hVMInfoEvent)
148 return RTSemEventMultiSignal(g_hVMInfoEvent);
149
150 return VINF_SUCCESS;
151}
152
153
154/** @copydoc VBOXSERVICE::pfnPreInit */
155static DECLCALLBACK(int) VBoxServiceVMInfoPreInit(void)
156{
157 return VINF_SUCCESS;
158}
159
160
161/** @copydoc VBOXSERVICE::pfnOption */
162static DECLCALLBACK(int) VBoxServiceVMInfoOption(const char **ppszShort, int argc, char **argv, int *pi)
163{
164 /** @todo Use RTGetOpt here. */
165
166 int rc = -1;
167 if (ppszShort)
168 /* no short options */;
169 else if (!strcmp(argv[*pi], "--vminfo-interval"))
170 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
171 &g_cMsVMInfoInterval, 1, UINT32_MAX - 1);
172 else if (!strcmp(argv[*pi], "--vminfo-user-idle-threshold"))
173 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
174 &g_uVMInfoUserIdleThreshold, 1, UINT32_MAX - 1);
175 return rc;
176}
177
178
179/** @copydoc VBOXSERVICE::pfnInit */
180static DECLCALLBACK(int) VBoxServiceVMInfoInit(void)
181{
182 /*
183 * If not specified, find the right interval default.
184 * Then create the event sem to block on.
185 */
186 if (!g_cMsVMInfoInterval)
187 g_cMsVMInfoInterval = g_DefaultInterval * 1000;
188 if (!g_cMsVMInfoInterval)
189 {
190 /* Set it to 5s by default for location awareness checks. */
191 g_cMsVMInfoInterval = 5 * 1000;
192 }
193
194 int rc = RTSemEventMultiCreate(&g_hVMInfoEvent);
195 AssertRCReturn(rc, rc);
196
197 VbglR3GetSessionId(&g_idVMInfoSession);
198 /* The status code is ignored as this information is not available with VBox < 3.2.10. */
199
200 /* Initialize the LA client object. */
201 RT_ZERO(g_LAClientInfo);
202
203 rc = VbglR3GuestPropConnect(&g_uVMInfoGuestPropSvcClientID);
204 if (RT_SUCCESS(rc))
205 VBoxServiceVerbose(3, "Property Service Client ID: %#x\n", g_uVMInfoGuestPropSvcClientID);
206 else
207 {
208 /* If the service was not found, we disable this service without
209 causing VBoxService to fail. */
210 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
211 {
212 VBoxServiceVerbose(0, "Guest property service is not available, disabling the service\n");
213 rc = VERR_SERVICE_DISABLED;
214 }
215 else
216 VBoxServiceError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
217 RTSemEventMultiDestroy(g_hVMInfoEvent);
218 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
219 }
220
221 if (RT_SUCCESS(rc))
222 {
223 VBoxServicePropCacheCreate(&g_VMInfoPropCache, g_uVMInfoGuestPropSvcClientID);
224
225 /*
226 * Declare some guest properties with flags and reset values.
227 */
228 int rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsersList,
229 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, NULL /* Delete on exit */);
230 if (RT_FAILURE(rc2))
231 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValLoggedInUsersList, rc2);
232
233 rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsers,
234 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "0");
235 if (RT_FAILURE(rc2))
236 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValLoggedInUsers, rc2);
237
238 rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValNoLoggedInUsers,
239 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT, "true");
240 if (RT_FAILURE(rc2))
241 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValNoLoggedInUsers, rc2);
242
243 rc2 = VBoxServicePropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValNetCount,
244 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_ALWAYS_UPDATE, NULL /* Delete on exit */);
245 if (RT_FAILURE(rc2))
246 VBoxServiceError("Failed to init property cache value \"%s\", rc=%Rrc\n", g_pszPropCacheValNetCount, rc2);
247
248 /*
249 * Get configuration guest properties from the host.
250 * Note: All properties should have sensible defaults in case the lookup here fails.
251 */
252 char *pszValue;
253 rc2 = VBoxServiceReadHostProp(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--vminfo-user-idle-threshold", true /* Read only */,
254 &pszValue, NULL /* Flags */, NULL /* Timestamp */);
255 if (RT_SUCCESS(rc2))
256 {
257 AssertPtr(pszValue);
258 g_uVMInfoUserIdleThreshold = RT_CLAMP(RTStrToUInt32(pszValue), 1000, UINT32_MAX - 1);
259 RTStrFree(pszValue);
260 }
261 }
262 return rc;
263}
264
265
266/**
267 * Retrieves a specifiy client LA property.
268 *
269 * @return IPRT status code.
270 * @param uClientID LA client ID to retrieve property for.
271 * @param pszProperty Property (without path) to retrieve.
272 * @param ppszValue Where to store value of property.
273 * @param puTimestamp Timestamp of property to retrieve. Optional.
274 */
275static int vboxServiceGetLAClientValue(uint32_t uClientID, const char *pszProperty,
276 char **ppszValue, uint64_t *puTimestamp)
277{
278 AssertReturn(uClientID, VERR_INVALID_PARAMETER);
279 AssertPtrReturn(pszProperty, VERR_INVALID_POINTER);
280
281 int rc;
282
283 char pszClientPath[255];
284 if (RTStrPrintf(pszClientPath, sizeof(pszClientPath),
285 "/VirtualBox/HostInfo/VRDP/Client/%RU32/%s", uClientID, pszProperty))
286 {
287 rc = VBoxServiceReadHostProp(g_uVMInfoGuestPropSvcClientID, pszClientPath, true /* Read only */,
288 ppszValue, NULL /* Flags */, puTimestamp);
289 }
290 else
291 rc = VERR_NO_MEMORY;
292
293 return rc;
294}
295
296
297/**
298 * Retrieves LA client information. On success the returned structure will have allocated
299 * objects which need to be free'd with vboxServiceFreeLAClientInfo.
300 *
301 * @return IPRT status code.
302 * @param uClientID Client ID to retrieve information for.
303 * @param pClient Pointer where to store the client information.
304 */
305static int vboxServiceGetLAClientInfo(uint32_t uClientID, PVBOXSERVICELACLIENTINFO pClient)
306{
307 AssertReturn(uClientID, VERR_INVALID_PARAMETER);
308 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
309
310 int rc = vboxServiceGetLAClientValue(uClientID, "Name", &pClient->pszName,
311 NULL /* Timestamp */);
312 if (RT_SUCCESS(rc))
313 {
314 char *pszAttach;
315 rc = vboxServiceGetLAClientValue(uClientID, "Attach", &pszAttach,
316 &pClient->uAttachedTS);
317 if (RT_SUCCESS(rc))
318 {
319 AssertPtr(pszAttach);
320 pClient->fAttached = !RTStrICmp(pszAttach, "1") ? true : false;
321
322 RTStrFree(pszAttach);
323 }
324 }
325 if (RT_SUCCESS(rc))
326 rc = vboxServiceGetLAClientValue(uClientID, "Location", &pClient->pszLocation,
327 NULL /* Timestamp */);
328 if (RT_SUCCESS(rc))
329 rc = vboxServiceGetLAClientValue(uClientID, "Domain", &pClient->pszDomain,
330 NULL /* Timestamp */);
331 if (RT_SUCCESS(rc))
332 pClient->uID = uClientID;
333
334 return rc;
335}
336
337
338/**
339 * Frees all allocated LA client information of a structure.
340 *
341 * @param pClient Pointer to client information structure to free.
342 */
343static void vboxServiceFreeLAClientInfo(PVBOXSERVICELACLIENTINFO pClient)
344{
345 if (pClient)
346 {
347 if (pClient->pszName)
348 {
349 RTStrFree(pClient->pszName);
350 pClient->pszName = NULL;
351 }
352 if (pClient->pszLocation)
353 {
354 RTStrFree(pClient->pszLocation);
355 pClient->pszLocation = NULL;
356 }
357 if (pClient->pszDomain)
358 {
359 RTStrFree(pClient->pszDomain);
360 pClient->pszDomain = NULL;
361 }
362 }
363}
364
365
366/**
367 * Updates a per-guest user guest property inside the given property cache.
368 *
369 * @return IPRT status code.
370 * @param pCache Pointer to guest property cache to update user in.
371 * @param pszUser Name of guest user to update.
372 * @param pszDomain Domain of guest user to update. Optional.
373 * @param pszKey Key name of guest property to update.
374 * @param pszValueFormat Guest property value to set. Pass NULL for deleting
375 * the property.
376 */
377int vboxServiceUserUpdateF(PVBOXSERVICEVEPROPCACHE pCache, const char *pszUser, const char *pszDomain,
378 const char *pszKey, const char *pszValueFormat, ...)
379{
380 AssertPtrReturn(pCache, VERR_INVALID_POINTER);
381 AssertPtrReturn(pszUser, VERR_INVALID_POINTER);
382 /* pszDomain is optional. */
383 AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
384 /* pszValueFormat is optional. */
385
386 int rc = VINF_SUCCESS;
387
388 char *pszName;
389 if (pszDomain)
390 {
391 if (!RTStrAPrintf(&pszName, "%s%s@%s/%s", g_pszPropCacheValUser, pszUser, pszDomain, pszKey))
392 rc = VERR_NO_MEMORY;
393 }
394 else
395 {
396 if (!RTStrAPrintf(&pszName, "%s%s/%s", g_pszPropCacheValUser, pszUser, pszKey))
397 rc = VERR_NO_MEMORY;
398 }
399
400 char *pszValue = NULL;
401 if ( RT_SUCCESS(rc)
402 && pszValueFormat)
403 {
404 va_list va;
405 va_start(va, pszValueFormat);
406 if (RTStrAPrintfV(&pszValue, pszValueFormat, va) < 0)
407 rc = VERR_NO_MEMORY;
408 va_end(va);
409 if ( RT_SUCCESS(rc)
410 && !pszValue)
411 rc = VERR_NO_STR_MEMORY;
412 }
413
414 if (RT_SUCCESS(rc))
415 rc = VBoxServicePropCacheUpdate(pCache, pszName, pszValue);
416 if (rc == VINF_SUCCESS) /* VBoxServicePropCacheUpdate will also return VINF_NO_CHANGE. */
417 {
418 /** @todo Combine updating flags w/ updating the actual value. */
419 rc = VBoxServicePropCacheUpdateEntry(pCache, pszName,
420 VBOXSERVICEPROPCACHEFLAG_TEMPORARY | VBOXSERVICEPROPCACHEFLAG_TRANSIENT,
421 NULL /* Delete on exit */);
422 }
423
424 RTStrFree(pszValue);
425 RTStrFree(pszName);
426 return rc;
427}
428
429
430/**
431 * Writes the properties that won't change while the service is running.
432 *
433 * Errors are ignored.
434 */
435static void vboxserviceVMInfoWriteFixedProperties(void)
436{
437 /*
438 * First get OS information that won't change.
439 */
440 char szInfo[256];
441 int rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szInfo, sizeof(szInfo));
442 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Product",
443 "%s", RT_FAILURE(rc) ? "" : szInfo);
444
445 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szInfo, sizeof(szInfo));
446 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Release",
447 "%s", RT_FAILURE(rc) ? "" : szInfo);
448
449 rc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szInfo, sizeof(szInfo));
450 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Version",
451 "%s", RT_FAILURE(rc) ? "" : szInfo);
452
453 rc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szInfo, sizeof(szInfo));
454 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/ServicePack",
455 "%s", RT_FAILURE(rc) ? "" : szInfo);
456
457 /*
458 * Retrieve version information about Guest Additions and installed files (components).
459 */
460 char *pszAddVer;
461 char *pszAddVerExt;
462 char *pszAddRev;
463 rc = VbglR3GetAdditionsVersion(&pszAddVer, &pszAddVerExt, &pszAddRev);
464 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Version",
465 "%s", RT_FAILURE(rc) ? "" : pszAddVer);
466 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VersionExt",
467 "%s", RT_FAILURE(rc) ? "" : pszAddVerExt);
468 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Revision",
469 "%s", RT_FAILURE(rc) ? "" : pszAddRev);
470 if (RT_SUCCESS(rc))
471 {
472 RTStrFree(pszAddVer);
473 RTStrFree(pszAddVerExt);
474 RTStrFree(pszAddRev);
475 }
476
477#ifdef RT_OS_WINDOWS
478 /*
479 * Do windows specific properties.
480 */
481 char *pszInstDir;
482 rc = VbglR3GetAdditionsInstallationPath(&pszInstDir);
483 VBoxServiceWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/InstallDir",
484 "%s", RT_FAILURE(rc) ? "" : pszInstDir);
485 if (RT_SUCCESS(rc))
486 RTStrFree(pszInstDir);
487
488 VBoxServiceWinGetComponentVersions(g_uVMInfoGuestPropSvcClientID);
489#endif
490}
491
492#if defined(VBOX_WITH_DBUS) && defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
493/*
494 * Simple wrapper to work around compiler-specific va_list madness.
495 */
496static dbus_bool_t vboxService_dbus_message_get_args(DBusMessage *message,
497 DBusError *error,
498 int first_arg_type,
499 ...)
500{
501 va_list va;
502 va_start(va, first_arg_type);
503 dbus_bool_t ret = dbus_message_get_args_valist(message, error,
504 first_arg_type, va);
505 va_end(va);
506 return ret;
507}
508#endif
509
510/**
511 * Provide information about active users.
512 */
513static int vboxserviceVMInfoWriteUsers(void)
514{
515 int rc = VINF_SUCCESS;
516 char *pszUserList = NULL;
517 uint32_t cUsersInList = 0;
518
519#ifdef RT_OS_WINDOWS
520# ifndef TARGET_NT4
521 rc = VBoxServiceVMInfoWinWriteUsers(&g_VMInfoPropCache,
522 &pszUserList, &cUsersInList);
523# else
524 rc = VERR_NOT_IMPLEMENTED;
525# endif
526
527#elif defined(RT_OS_FREEBSD)
528 /** @todo FreeBSD: Port logged on user info retrieval.
529 * However, FreeBSD 9 supports utmpx, so we could use the code
530 * block below (?). */
531 rc = VERR_NOT_IMPLEMENTED;
532
533#elif defined(RT_OS_HAIKU)
534 /** @todo Haiku: Port logged on user info retrieval. */
535 rc = VERR_NOT_IMPLEMENTED;
536
537#elif defined(RT_OS_OS2)
538 /** @todo OS/2: Port logged on (LAN/local/whatever) user info retrieval. */
539 rc = VERR_NOT_IMPLEMENTED;
540
541#else
542 setutxent();
543 utmpx *ut_user;
544 uint32_t cListSize = 32;
545
546 /* Allocate a first array to hold 32 users max. */
547 char **papszUsers = (char **)RTMemAllocZ(cListSize * sizeof(char *));
548 if (papszUsers == NULL)
549 rc = VERR_NO_MEMORY;
550
551 /* Process all entries in the utmp file.
552 * Note: This only handles */
553 while ( (ut_user = getutxent())
554 && RT_SUCCESS(rc))
555 {
556#ifdef RT_OS_DARWIN /* No ut_user->ut_session on Darwin */
557 VBoxServiceVerbose(4, "Found entry \"%s\" (type: %d, PID: %RU32)\n",
558 ut_user->ut_user, ut_user->ut_type, ut_user->ut_pid);
559#else
560 VBoxServiceVerbose(4, "Found entry \"%s\" (type: %d, PID: %RU32, session: %RU32)\n",
561 ut_user->ut_user, ut_user->ut_type, ut_user->ut_pid, ut_user->ut_session);
562#endif
563 if (cUsersInList > cListSize)
564 {
565 cListSize += 32;
566 void *pvNew = RTMemRealloc(papszUsers, cListSize * sizeof(char*));
567 AssertPtrBreakStmt(pvNew, cListSize -= 32);
568 papszUsers = (char **)pvNew;
569 }
570
571 /* Make sure we don't add user names which are not
572 * part of type USER_PROCES. */
573 if (ut_user->ut_type == USER_PROCESS) /* Regular user process. */
574 {
575 bool fFound = false;
576 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
577 fFound = strcmp(papszUsers[i], ut_user->ut_user) == 0;
578
579 if (!fFound)
580 {
581 VBoxServiceVerbose(4, "Adding user \"%s\" (type: %d) to list\n",
582 ut_user->ut_user, ut_user->ut_type);
583
584 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ut_user->ut_user);
585 if (RT_FAILURE(rc))
586 break;
587 cUsersInList++;
588 }
589 }
590 }
591
592#ifdef VBOX_WITH_DBUS
593# if defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
594 DBusError dbErr;
595 DBusConnection *pConnection = NULL;
596 int rc2 = RTDBusLoadLib();
597 if (RT_SUCCESS(rc2))
598 {
599 /* Handle desktop sessions using ConsoleKit. */
600 VBoxServiceVerbose(4, "Checking ConsoleKit sessions ...\n");
601
602 dbus_error_init(&dbErr);
603 pConnection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbErr);
604 }
605
606 if ( pConnection
607 && !dbus_error_is_set(&dbErr))
608 {
609 /* Get all available sessions. */
610 DBusMessage *pMsgSessions = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
611 "/org/freedesktop/ConsoleKit/Manager",
612 "org.freedesktop.ConsoleKit.Manager",
613 "GetSessions");
614 if ( pMsgSessions
615 && (dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL))
616 {
617 DBusMessage *pReplySessions = dbus_connection_send_with_reply_and_block(pConnection,
618 pMsgSessions, 30 * 1000 /* 30s timeout */,
619 &dbErr);
620 if ( pReplySessions
621 && !dbus_error_is_set(&dbErr))
622 {
623 char **ppszSessions; int cSessions;
624 if ( (dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL)
625 && vboxService_dbus_message_get_args(pReplySessions, &dbErr, DBUS_TYPE_ARRAY,
626 DBUS_TYPE_OBJECT_PATH, &ppszSessions, &cSessions,
627 DBUS_TYPE_INVALID /* Termination */))
628 {
629 VBoxServiceVerbose(4, "ConsoleKit: retrieved %RU16 session(s)\n", cSessions);
630
631 char **ppszCurSession = ppszSessions;
632 for (ppszCurSession;
633 ppszCurSession && *ppszCurSession; ppszCurSession++)
634 {
635 VBoxServiceVerbose(4, "ConsoleKit: processing session '%s' ...\n", *ppszCurSession);
636
637 /* Only respect active sessions .*/
638 bool fActive = false;
639 DBusMessage *pMsgSessionActive = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
640 *ppszCurSession,
641 "org.freedesktop.ConsoleKit.Session",
642 "IsActive");
643 if ( pMsgSessionActive
644 && dbus_message_get_type(pMsgSessionActive) == DBUS_MESSAGE_TYPE_METHOD_CALL)
645 {
646 DBusMessage *pReplySessionActive = dbus_connection_send_with_reply_and_block(pConnection,
647 pMsgSessionActive, 30 * 1000 /* 30s timeout */,
648 &dbErr);
649 if ( pReplySessionActive
650 && !dbus_error_is_set(&dbErr))
651 {
652 DBusMessageIter itMsg;
653 if ( dbus_message_iter_init(pReplySessionActive, &itMsg)
654 && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_BOOLEAN)
655 {
656 /* Get uid from message. */
657 int val;
658 dbus_message_iter_get_basic(&itMsg, &val);
659 fActive = val >= 1;
660 }
661
662 if (pReplySessionActive)
663 dbus_message_unref(pReplySessionActive);
664 }
665
666 if (pMsgSessionActive)
667 dbus_message_unref(pMsgSessionActive);
668 }
669
670 VBoxServiceVerbose(4, "ConsoleKit: session '%s' is %s\n",
671 *ppszCurSession, fActive ? "active" : "not active");
672
673 /* *ppszCurSession now contains the object path
674 * (e.g. "/org/freedesktop/ConsoleKit/Session1"). */
675 DBusMessage *pMsgUnixUser = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
676 *ppszCurSession,
677 "org.freedesktop.ConsoleKit.Session",
678 "GetUnixUser");
679 if ( fActive
680 && pMsgUnixUser
681 && dbus_message_get_type(pMsgUnixUser) == DBUS_MESSAGE_TYPE_METHOD_CALL)
682 {
683 DBusMessage *pReplyUnixUser = dbus_connection_send_with_reply_and_block(pConnection,
684 pMsgUnixUser, 30 * 1000 /* 30s timeout */,
685 &dbErr);
686 if ( pReplyUnixUser
687 && !dbus_error_is_set(&dbErr))
688 {
689 DBusMessageIter itMsg;
690 if ( dbus_message_iter_init(pReplyUnixUser, &itMsg)
691 && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_UINT32)
692 {
693 /* Get uid from message. */
694 uint32_t uid;
695 dbus_message_iter_get_basic(&itMsg, &uid);
696
697 /** @todo Add support for getting UID_MIN (/etc/login.defs on
698 * Debian). */
699 uint32_t uid_min = 1000;
700
701 /* Look up user name (realname) from uid. */
702 setpwent();
703 struct passwd *ppwEntry = getpwuid(uid);
704 if ( ppwEntry
705 && ppwEntry->pw_uid >= uid_min /* Only respect users, not daemons etc. */
706 && ppwEntry->pw_name)
707 {
708 VBoxServiceVerbose(4, "ConsoleKit: session '%s' -> %s (uid: %RU32)\n",
709 *ppszCurSession, ppwEntry->pw_name, uid);
710
711 bool fFound = false;
712 for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
713 fFound = strcmp(papszUsers[i], ppwEntry->pw_name) == 0;
714
715 if (!fFound)
716 {
717 VBoxServiceVerbose(4, "ConsoleKit: adding user \"%s\" to list\n",
718 ppwEntry->pw_name);
719
720 rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ppwEntry->pw_name);
721 if (RT_FAILURE(rc))
722 break;
723 cUsersInList++;
724 }
725 }
726 else
727 VBoxServiceError("ConsoleKit: unable to lookup user name for uid=%RU32\n", uid);
728 }
729 else
730 AssertMsgFailed(("ConsoleKit: GetUnixUser returned a wrong argument type\n"));
731 }
732
733 if (pReplyUnixUser)
734 dbus_message_unref(pReplyUnixUser);
735 }
736 else
737 VBoxServiceError("ConsoleKit: unable to retrieve user for session '%s' (msg type=%d): %s",
738 *ppszCurSession, dbus_message_get_type(pMsgUnixUser),
739 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
740
741 if (pMsgUnixUser)
742 dbus_message_unref(pMsgUnixUser);
743 }
744
745 dbus_free_string_array(ppszSessions);
746 }
747 else
748 {
749 VBoxServiceError("ConsoleKit: unable to retrieve session parameters (msg type=%d): %s",
750 dbus_message_get_type(pMsgSessions),
751 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
752 }
753 dbus_message_unref(pReplySessions);
754 }
755
756 if (pMsgSessions)
757 {
758 dbus_message_unref(pMsgSessions);
759 pMsgSessions = NULL;
760 }
761 }
762 else
763 {
764 static int s_iBitchedAboutConsoleKit = 0;
765 if (s_iBitchedAboutConsoleKit++ < 3)
766 VBoxServiceError("Unable to invoke ConsoleKit (%d/3) -- maybe not installed / used? Error: %s\n",
767 s_iBitchedAboutConsoleKit,
768 dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
769 }
770
771 if (pMsgSessions)
772 dbus_message_unref(pMsgSessions);
773 }
774 else
775 {
776 static int s_iBitchedAboutDBus = 0;
777 if (s_iBitchedAboutDBus++ < 3)
778 VBoxServiceError("Unable to connect to system D-Bus (%d/3): %s\n", s_iBitchedAboutDBus,
779 pConnection && dbus_error_is_set(&dbErr) ? dbErr.message : "D-Bus not installed");
780 }
781
782 if ( pConnection
783 && dbus_error_is_set(&dbErr))
784 dbus_error_free(&dbErr);
785# endif /* RT_OS_LINUX */
786#endif /* VBOX_WITH_DBUS */
787
788 /** @todo Fedora/others: Handle systemd-loginctl. */
789
790 /* Calc the string length. */
791 size_t cchUserList = 0;
792 if (RT_SUCCESS(rc))
793 {
794 for (uint32_t i = 0; i < cUsersInList; i++)
795 cchUserList += (i != 0) + strlen(papszUsers[i]);
796 }
797
798 /* Build the user list. */
799 if (RT_SUCCESS(rc))
800 rc = RTStrAllocEx(&pszUserList, cchUserList + 1);
801 if (RT_SUCCESS(rc))
802 {
803 char *psz = pszUserList;
804 for (uint32_t i = 0; i < cUsersInList; i++)
805 {
806 if (i != 0)
807 *psz++ = ',';
808 size_t cch = strlen(papszUsers[i]);
809 memcpy(psz, papszUsers[i], cch);
810 psz += cch;
811 }
812 *psz = '\0';
813 }
814
815 /* Cleanup. */
816 for (uint32_t i = 0; i < cUsersInList; i++)
817 RTStrFree(papszUsers[i]);
818 RTMemFree(papszUsers);
819
820 endutxent(); /* Close utmpx file. */
821#endif
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 cIfacesReport = 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", cIfacesReport);
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", cIfacesReport);
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", cIfacesReport);
980 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
981
982 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/Status", cIfacesReport);
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", cIfacesReport);
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 cIfacesReport++;
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 * @todo: IPv6 interfaces
1033 */
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", cIfacesReport);
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", cIfacesReport);
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", cIfacesReport);
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", cIfacesReport);
1072 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
1073 break;
1074 }
1075 }
1076
1077 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/Status", cIfacesReport);
1078 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");
1079
1080 cIfacesReport++;
1081 }
1082 }
1083
1084 /* Free allocated resources. */
1085 freeifaddrs(pIfHead);
1086
1087#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
1088 int sd = socket(AF_INET, SOCK_DGRAM, 0);
1089 if (sd < 0)
1090 {
1091 rc = RTErrConvertFromErrno(errno);
1092 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
1093 return rc;
1094 }
1095
1096 ifconf ifcfg;
1097 char buffer[1024] = {0};
1098 ifcfg.ifc_len = sizeof(buffer);
1099 ifcfg.ifc_buf = buffer;
1100 if (ioctl(sd, SIOCGIFCONF, &ifcfg) < 0)
1101 {
1102 close(sd);
1103 rc = RTErrConvertFromErrno(errno);
1104 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFCONF) on socket: Error %Rrc\n", rc);
1105 return rc;
1106 }
1107
1108 ifreq* ifrequest = ifcfg.ifc_req;
1109 int cIfacesSystem = ifcfg.ifc_len / sizeof(ifreq);
1110
1111 for (int i = 0; i < cIfacesSystem; ++i)
1112 {
1113 sockaddr_in *pAddress;
1114 if (ioctl(sd, SIOCGIFFLAGS, &ifrequest[i]) < 0)
1115 {
1116 rc = RTErrConvertFromErrno(errno);
1117 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS) on socket: Error %Rrc\n", rc);
1118 break;
1119 }
1120 if (ifrequest[i].ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
1121 continue;
1122
1123 bool fIfUp = !!(ifrequest[i].ifr_flags & IFF_UP);
1124 pAddress = ((sockaddr_in *)&ifrequest[i].ifr_addr);
1125 Assert(pAddress);
1126 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/IP", cIfacesReport);
1127 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1128
1129 if (ioctl(sd, SIOCGIFBRDADDR, &ifrequest[i]) < 0)
1130 {
1131 rc = RTErrConvertFromErrno(errno);
1132 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
1133 break;
1134 }
1135 pAddress = (sockaddr_in *)&ifrequest[i].ifr_broadaddr;
1136 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Broadcast", cIfacesReport);
1137 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1138
1139 if (ioctl(sd, SIOCGIFNETMASK, &ifrequest[i]) < 0)
1140 {
1141 rc = RTErrConvertFromErrno(errno);
1142 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
1143 break;
1144 }
1145# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
1146 pAddress = (sockaddr_in *)&ifrequest[i].ifr_addr;
1147# else
1148 pAddress = (sockaddr_in *)&ifrequest[i].ifr_netmask;
1149# endif
1150
1151 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Netmask", cIfacesReport);
1152 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1153
1154# if defined(RT_OS_SOLARIS)
1155 /*
1156 * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
1157 * We might fail if the interface has not been assigned an IP address.
1158 * That doesn't matter; as long as it's plumbed we can pick it up.
1159 * But, if it has not acquired an IP address we cannot obtain it's MAC
1160 * address this way, so we just use all zeros there.
1161 */
1162 RTMAC IfMac;
1163 RT_ZERO(IfMac);
1164 struct lifreq IfReq;
1165 RT_ZERO(IfReq);
1166 AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(ifrequest[i].ifr_name));
1167 strncpy(IfReq.lifr_name, ifrequest[i].ifr_name, sizeof(ifrequest[i].ifr_name));
1168 if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
1169 {
1170 struct arpreq ArpReq;
1171 RT_ZERO(ArpReq);
1172 memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));
1173
1174 if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
1175 memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
1176 else
1177 {
1178 rc = RTErrConvertFromErrno(errno);
1179 VBoxServiceError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
1180 break;
1181 }
1182 }
1183 else
1184 {
1185 VBoxServiceVerbose(2, "VMInfo/Network: Interface %d has no assigned IP address, skipping ...\n", i);
1186 continue;
1187 }
1188# else
1189# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
1190 if (ioctl(sd, SIOCGIFHWADDR, &ifrequest[i]) < 0)
1191 {
1192 rc = RTErrConvertFromErrno(errno);
1193 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
1194 break;
1195 }
1196# endif
1197# endif
1198
1199# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
1200 char szMac[32];
1201# if defined(RT_OS_SOLARIS)
1202 uint8_t *pu8Mac = IfMac.au8;
1203# else
1204 uint8_t *pu8Mac = (uint8_t*)&ifrequest[i].ifr_hwaddr.sa_data[0]; /* @todo see above */
1205# endif
1206 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
1207 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
1208 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/MAC", cIfacesReport);
1209 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
1210# endif /* !OS/2*/
1211
1212 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/Status", cIfacesReport);
1213 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");
1214 cIfacesReport++;
1215 } /* For all interfaces */
1216
1217 close(sd);
1218 if (RT_FAILURE(rc))
1219 VBoxServiceError("VMInfo/Network: Network enumeration for interface %RU32 failed with error %Rrc\n", cIfacesReport, rc);
1220
1221#endif /* !RT_OS_WINDOWS */
1222
1223#if 0 /* Zapping not enabled yet, needs more testing first. */
1224 /*
1225 * Zap all stale network interface data if the former (saved) network ifaces count
1226 * is bigger than the current one.
1227 */
1228
1229 /* Get former count. */
1230 uint32_t cIfacesReportOld;
1231 rc = VBoxServiceReadPropUInt32(g_uVMInfoGuestPropSvcClientID, g_pszPropCacheValNetCount, &cIfacesReportOld,
1232 0 /* Min */, UINT32_MAX /* Max */);
1233 if ( RT_SUCCESS(rc)
1234 && cIfacesReportOld > cIfacesReport) /* Are some ifaces not around anymore? */
1235 {
1236 VBoxServiceVerbose(3, "VMInfo/Network: Stale interface data detected (%RU32 old vs. %RU32 current)\n",
1237 cIfacesReportOld, cIfacesReport);
1238
1239 uint32_t uIfaceDeleteIdx = cIfacesReport;
1240 do
1241 {
1242 VBoxServiceVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
1243 rc = VBoxServicePropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%RU32", uIfaceDeleteIdx++);
1244 } while (RT_SUCCESS(rc));
1245 }
1246 else if ( RT_FAILURE(rc)
1247 && rc != VERR_NOT_FOUND)
1248 {
1249 VBoxServiceError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
1250 }
1251#endif
1252
1253 /*
1254 * This property is a beacon which is _always_ written, even if the network configuration
1255 * does not change. If this property is missing, the host assumes that all other GuestInfo
1256 * properties are no longer valid.
1257 */
1258 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValNetCount, "%RU32",
1259 cIfacesReport);
1260
1261 /* Don't fail here; just report everything we got. */
1262 return VINF_SUCCESS;
1263}
1264
1265
1266/** @copydoc VBOXSERVICE::pfnWorker */
1267DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
1268{
1269 int rc;
1270
1271 /*
1272 * Tell the control thread that it can continue
1273 * spawning services.
1274 */
1275 RTThreadUserSignal(RTThreadSelf());
1276
1277#ifdef RT_OS_WINDOWS
1278 /* Required for network information (must be called per thread). */
1279 WSADATA wsaData;
1280 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
1281 VBoxServiceError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
1282#endif /* RT_OS_WINDOWS */
1283
1284 /*
1285 * Write the fixed properties first.
1286 */
1287 vboxserviceVMInfoWriteFixedProperties();
1288
1289 /*
1290 * Now enter the loop retrieving runtime data continuously.
1291 */
1292 for (;;)
1293 {
1294 rc = vboxserviceVMInfoWriteUsers();
1295 if (RT_FAILURE(rc))
1296 break;
1297
1298 rc = vboxserviceVMInfoWriteNetwork();
1299 if (RT_FAILURE(rc))
1300 break;
1301
1302 /* Whether to wait for event semaphore or not. */
1303 bool fWait = true;
1304
1305 /* Check for location awareness. This most likely only
1306 * works with VBox (latest) 4.1 and up. */
1307
1308 /* Check for new connection. */
1309 char *pszLAClientID = NULL;
1310 int rc2 = VBoxServiceReadHostProp(g_uVMInfoGuestPropSvcClientID, g_pszLAActiveClient, true /* Read only */,
1311 &pszLAClientID, NULL /* Flags */, NULL /* Timestamp */);
1312 if (RT_SUCCESS(rc2))
1313 {
1314 AssertPtr(pszLAClientID);
1315 if (RTStrICmp(pszLAClientID, "0")) /* Is a client connected? */
1316 {
1317 uint32_t uLAClientID = RTStrToInt32(pszLAClientID);
1318 uint64_t uLAClientAttachedTS;
1319
1320 /* Peek at "Attach" value to figure out if hotdesking happened. */
1321 char *pszAttach = NULL;
1322 rc2 = vboxServiceGetLAClientValue(uLAClientID, "Attach", &pszAttach,
1323 &uLAClientAttachedTS);
1324
1325 if ( RT_SUCCESS(rc2)
1326 && ( !g_LAClientAttachedTS
1327 || (g_LAClientAttachedTS != uLAClientAttachedTS)))
1328 {
1329 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1330
1331 /* Note: There is a race between setting the guest properties by the host and getting them by
1332 * the guest. */
1333 rc2 = vboxServiceGetLAClientInfo(uLAClientID, &g_LAClientInfo);
1334 if (RT_SUCCESS(rc2))
1335 {
1336 VBoxServiceVerbose(1, "VRDP: Hotdesk client %s with ID=%RU32, Name=%s, Domain=%s\n",
1337 /* If g_LAClientAttachedTS is 0 this means there already was an active
1338 * hotdesk session when VBoxService started. */
1339 !g_LAClientAttachedTS ? "already active" : g_LAClientInfo.fAttached ? "connected" : "disconnected",
1340 uLAClientID, g_LAClientInfo.pszName, g_LAClientInfo.pszDomain);
1341
1342 g_LAClientAttachedTS = g_LAClientInfo.uAttachedTS;
1343
1344 /* Don't wait for event semaphore below anymore because we now know that the client
1345 * changed. This means we need to iterate all VM information again immediately. */
1346 fWait = false;
1347 }
1348 else
1349 {
1350 static int s_iBitchedAboutLAClientInfo = 0;
1351 if (s_iBitchedAboutLAClientInfo++ < 10)
1352 VBoxServiceError("Error getting active location awareness client info, rc=%Rrc\n", rc2);
1353 }
1354 }
1355 else if (RT_FAILURE(rc2))
1356 VBoxServiceError("Error getting attached value of location awareness client %RU32, rc=%Rrc\n",
1357 uLAClientID, rc2);
1358 if (pszAttach)
1359 RTStrFree(pszAttach);
1360 }
1361 else
1362 {
1363 VBoxServiceVerbose(1, "VRDP: UTTSC disconnected from VRDP server\n");
1364 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1365 }
1366
1367 RTStrFree(pszLAClientID);
1368 }
1369 else
1370 {
1371 static int s_iBitchedAboutLAClient = 0;
1372 if ( (rc2 != VERR_NOT_FOUND) /* No location awareness installed, skip. */
1373 && s_iBitchedAboutLAClient++ < 3)
1374 VBoxServiceError("VRDP: Querying connected location awareness client failed with rc=%Rrc\n", rc2);
1375 }
1376
1377 VBoxServiceVerbose(3, "VRDP: Handling location awareness done\n");
1378
1379 /*
1380 * Flush all properties if we were restored.
1381 */
1382 uint64_t idNewSession = g_idVMInfoSession;
1383 VbglR3GetSessionId(&idNewSession);
1384 if (idNewSession != g_idVMInfoSession)
1385 {
1386 VBoxServiceVerbose(3, "The VM session ID changed, flushing all properties\n");
1387 vboxserviceVMInfoWriteFixedProperties();
1388 VBoxServicePropCacheFlush(&g_VMInfoPropCache);
1389 g_idVMInfoSession = idNewSession;
1390 }
1391
1392 /*
1393 * Block for a while.
1394 *
1395 * The event semaphore takes care of ignoring interruptions and it
1396 * allows us to implement service wakeup later.
1397 */
1398 if (*pfShutdown)
1399 break;
1400 if (fWait)
1401 rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
1402 if (*pfShutdown)
1403 break;
1404 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
1405 {
1406 VBoxServiceError("RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
1407 rc = rc2;
1408 break;
1409 }
1410 else if (RT_LIKELY(RT_SUCCESS(rc2)))
1411 {
1412 /* Reset event semaphore if it got triggered. */
1413 rc2 = RTSemEventMultiReset(g_hVMInfoEvent);
1414 if (RT_FAILURE(rc2))
1415 rc2 = VBoxServiceError("RTSemEventMultiReset failed; rc2=%Rrc\n", rc2);
1416 }
1417 }
1418
1419#ifdef RT_OS_WINDOWS
1420 WSACleanup();
1421#endif
1422
1423 return rc;
1424}
1425
1426
1427/** @copydoc VBOXSERVICE::pfnStop */
1428static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
1429{
1430 RTSemEventMultiSignal(g_hVMInfoEvent);
1431}
1432
1433
1434/** @copydoc VBOXSERVICE::pfnTerm */
1435static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
1436{
1437 if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
1438 {
1439 /** @todo temporary solution: Zap all values which are not valid
1440 * anymore when VM goes down (reboot/shutdown ). Needs to
1441 * be replaced with "temporary properties" later.
1442 *
1443 * One idea is to introduce a (HGCM-)session guest property
1444 * flag meaning that a guest property is only valid as long
1445 * as the HGCM session isn't closed (e.g. guest application
1446 * terminates). [don't remove till implemented]
1447 */
1448 /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
1449 * since it remembers what we've written. */
1450 /* Delete the "../Net" branch. */
1451 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
1452 int rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
1453
1454 /* Destroy LA client info. */
1455 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1456
1457 /* Destroy property cache. */
1458 VBoxServicePropCacheDestroy(&g_VMInfoPropCache);
1459
1460 /* Disconnect from guest properties service. */
1461 rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
1462 if (RT_FAILURE(rc))
1463 VBoxServiceError("Failed to disconnect from guest property service! Error: %Rrc\n", rc);
1464 g_uVMInfoGuestPropSvcClientID = 0;
1465
1466 RTSemEventMultiDestroy(g_hVMInfoEvent);
1467 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
1468 }
1469}
1470
1471
1472/**
1473 * The 'vminfo' service description.
1474 */
1475VBOXSERVICE g_VMInfo =
1476{
1477 /* pszName. */
1478 "vminfo",
1479 /* pszDescription. */
1480 "Virtual Machine Information",
1481 /* pszUsage. */
1482 " [--vminfo-interval <ms>] [--vminfo-user-idle-threshold <ms>]"
1483 ,
1484 /* pszOptions. */
1485 " --vminfo-interval Specifies the interval at which to retrieve the\n"
1486 " VM information. The default is 10000 ms.\n"
1487 " --vminfo-user-idle-threshold <ms>\n"
1488 " Specifies the user idle threshold (in ms) for\n"
1489 " considering a guest user being as idle. The default\n"
1490 " is 5000 (5 seconds).\n"
1491 ,
1492 /* methods */
1493 VBoxServiceVMInfoPreInit,
1494 VBoxServiceVMInfoOption,
1495 VBoxServiceVMInfoInit,
1496 VBoxServiceVMInfoWorker,
1497 VBoxServiceVMInfoStop,
1498 VBoxServiceVMInfoTerm
1499};
1500
Note: See TracBrowser for help on using the repository browser.

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