VirtualBox

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

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

VBoxService/VMInfo: Implemented detecting hotdesk sessions through VRDP location awareness.

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