VirtualBox

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

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

Additions/VBoxService: warning

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