VirtualBox

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

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

BUGZ:4686 OS X guest: VBoxGuest device driver + VBoxService and VBoxControl now work.

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