VirtualBox

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

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

Additions/VBoxService: save a few \n in error messages

  • 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 44912 2013-03-04 14:45:14Z 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");
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");
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");
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 pConnection && dbus_error_is_set(&dbErr) ? dbErr.message : "D-Bus not installed");
671 }
672
673 if ( pConnection
674 && dbus_error_is_set(&dbErr))
675 dbus_error_free(&dbErr);
676# endif /* RT_OS_LINUX */
677#endif /* VBOX_WITH_DBUS */
678
679 /** @todo Fedora/others: Handle systemd-loginctl. */
680
681 /* Calc the string length. */
682 size_t cchUserList = 0;
683 if (RT_SUCCESS(rc))
684 {
685 for (uint32_t i = 0; i < cUsersInList; i++)
686 cchUserList += (i != 0) + strlen(papszUsers[i]);
687 }
688
689 /* Build the user list. */
690 if (RT_SUCCESS(rc))
691 rc = RTStrAllocEx(&pszUserList, cchUserList + 1);
692 if (RT_SUCCESS(rc))
693 {
694 char *psz = pszUserList;
695 for (uint32_t i = 0; i < cUsersInList; i++)
696 {
697 if (i != 0)
698 *psz++ = ',';
699 size_t cch = strlen(papszUsers[i]);
700 memcpy(psz, papszUsers[i], cch);
701 psz += cch;
702 }
703 *psz = '\0';
704 }
705
706 /* Cleanup. */
707 for (uint32_t i = 0; i < cUsersInList; i++)
708 RTStrFree(papszUsers[i]);
709 RTMemFree(papszUsers);
710
711 endutxent(); /* Close utmpx file. */
712#endif
713 Assert(RT_FAILURE(rc) || cUsersInList == 0 || (pszUserList && *pszUserList));
714
715 /* If the user enumeration above failed, reset the user count to 0 except
716 * we didn't have enough memory anymore. In that case we want to preserve
717 * the previous user count in order to not confuse third party tools which
718 * rely on that count. */
719 if (RT_FAILURE(rc))
720 {
721 if (rc == VERR_NO_MEMORY)
722 {
723 static int s_iVMInfoBitchedOOM = 0;
724 if (s_iVMInfoBitchedOOM++ < 3)
725 VBoxServiceVerbose(0, "Warning: Not enough memory available to enumerate users! Keeping old value (%u)\n",
726 g_cVMInfoLoggedInUsers);
727 cUsersInList = g_cVMInfoLoggedInUsers;
728 }
729 else
730 cUsersInList = 0;
731 }
732
733 VBoxServiceVerbose(4, "cUsersInList=%RU32, pszUserList=%s, rc=%Rrc\n",
734 cUsersInList, pszUserList ? pszUserList : "<NULL>", rc);
735
736 if (pszUserList && cUsersInList > 0)
737 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", "%s", pszUserList);
738 else
739 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsersList", NULL);
740 if (RT_FAILURE(rc))
741 {
742 VBoxServiceError("Error writing logged on users list, rc=%Rrc\n", rc);
743 cUsersInList = 0; /* Reset user count on error. */
744 }
745
746 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/LoggedInUsers", "%u", cUsersInList);
747 if (RT_FAILURE(rc))
748 {
749 VBoxServiceError("Error writing logged on users count, rc=%Rrc\n", rc);
750 cUsersInList = 0; /* Reset user count on error. */
751 }
752
753 if (g_cVMInfoLoggedInUsers != cUsersInList)
754 {
755 rc = VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
756 cUsersInList == 0 ? "true" : "false");
757 if (RT_FAILURE(rc))
758 VBoxServiceError("Error writing no logged in users beacon, rc=%Rrc\n", rc);
759 g_cVMInfoLoggedInUsers = cUsersInList;
760 }
761 if (pszUserList)
762 RTStrFree(pszUserList);
763
764 VBoxServiceVerbose(4, "Writing users returned with rc=%Rrc\n", rc);
765 return rc;
766}
767
768
769/**
770 * Provide information about the guest network.
771 */
772static int vboxserviceVMInfoWriteNetwork(void)
773{
774 int rc = VINF_SUCCESS;
775 uint32_t cIfacesReport = 0;
776 char szPropPath[256];
777
778#ifdef RT_OS_WINDOWS
779 IP_ADAPTER_INFO *pAdpInfo = NULL;
780
781# ifndef TARGET_NT4
782 ULONG cbAdpInfo = sizeof(*pAdpInfo);
783 pAdpInfo = (IP_ADAPTER_INFO *)RTMemAlloc(cbAdpInfo);
784 if (!pAdpInfo)
785 {
786 VBoxServiceError("VMInfo/Network: Failed to allocate IP_ADAPTER_INFO\n");
787 return VERR_NO_MEMORY;
788 }
789 DWORD dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
790 if (dwRet == ERROR_BUFFER_OVERFLOW)
791 {
792 IP_ADAPTER_INFO *pAdpInfoNew = (IP_ADAPTER_INFO*)RTMemRealloc(pAdpInfo, cbAdpInfo);
793 if (pAdpInfoNew)
794 {
795 pAdpInfo = pAdpInfoNew;
796 dwRet = GetAdaptersInfo(pAdpInfo, &cbAdpInfo);
797 }
798 }
799 else if (dwRet == ERROR_NO_DATA)
800 {
801 VBoxServiceVerbose(3, "VMInfo/Network: No network adapters available\n");
802
803 /* If no network adapters available / present in the
804 * system we pretend success to not bail out too early. */
805 dwRet = ERROR_SUCCESS;
806 }
807
808 if (dwRet != ERROR_SUCCESS)
809 {
810 if (pAdpInfo)
811 RTMemFree(pAdpInfo);
812 VBoxServiceError("VMInfo/Network: Failed to get adapter info: Error %d\n", dwRet);
813 return RTErrConvertFromWin32(dwRet);
814 }
815# endif /* !TARGET_NT4 */
816
817 SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
818 if (sd == SOCKET_ERROR) /* Socket invalid. */
819 {
820 int wsaErr = WSAGetLastError();
821 /* Don't complain/bail out with an error if network stack is not up; can happen
822 * on NT4 due to start up when not connected shares dialogs pop up. */
823 if (WSAENETDOWN == wsaErr)
824 {
825 VBoxServiceVerbose(0, "VMInfo/Network: Network is not up yet.\n");
826 wsaErr = VINF_SUCCESS;
827 }
828 else
829 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %d\n", wsaErr);
830 if (pAdpInfo)
831 RTMemFree(pAdpInfo);
832 return RTErrConvertFromWin32(wsaErr);
833 }
834
835 INTERFACE_INFO InterfaceList[20] = {0};
836 unsigned long nBytesReturned = 0;
837 if (WSAIoctl(sd,
838 SIO_GET_INTERFACE_LIST,
839 0,
840 0,
841 &InterfaceList,
842 sizeof(InterfaceList),
843 &nBytesReturned,
844 0,
845 0) == SOCKET_ERROR)
846 {
847 VBoxServiceError("VMInfo/Network: Failed to WSAIoctl() on socket: Error: %d\n", WSAGetLastError());
848 if (pAdpInfo)
849 RTMemFree(pAdpInfo);
850 return RTErrConvertFromWin32(WSAGetLastError());
851 }
852 int cIfacesSystem = nBytesReturned / sizeof(INTERFACE_INFO);
853
854 /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
855 for (int i = 0; i < cIfacesSystem; ++i)
856 {
857 sockaddr_in *pAddress;
858 u_long nFlags = 0;
859 if (InterfaceList[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
860 continue;
861 nFlags = InterfaceList[i].iiFlags;
862 pAddress = (sockaddr_in *)&(InterfaceList[i].iiAddress);
863 Assert(pAddress);
864 char szIp[32];
865 RTStrPrintf(szIp, sizeof(szIp), "%s", inet_ntoa(pAddress->sin_addr));
866 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
867 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szIp);
868
869 pAddress = (sockaddr_in *) & (InterfaceList[i].iiBroadcastAddress);
870 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
871 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
872
873 pAddress = (sockaddr_in *)&(InterfaceList[i].iiNetmask);
874 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
875 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
876
877 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
878 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, nFlags & IFF_UP ? "Up" : "Down");
879
880# ifndef TARGET_NT4
881 IP_ADAPTER_INFO *pAdp;
882 for (pAdp = pAdpInfo; pAdp; pAdp = pAdp->Next)
883 if (!strcmp(pAdp->IpAddressList.IpAddress.String, szIp))
884 break;
885
886 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
887 if (pAdp)
888 {
889 char szMac[32];
890 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
891 pAdp->Address[0], pAdp->Address[1], pAdp->Address[2],
892 pAdp->Address[3], pAdp->Address[4], pAdp->Address[5]);
893 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
894 }
895 else
896 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, NULL);
897# endif /* !TARGET_NT4 */
898
899 cIfacesReport++;
900 }
901 if (pAdpInfo)
902 RTMemFree(pAdpInfo);
903 if (sd >= 0)
904 closesocket(sd);
905
906#elif defined(RT_OS_HAIKU)
907 /** @todo Haiku: implement network info. retreival */
908 return VERR_NOT_IMPLEMENTED;
909
910#elif defined(RT_OS_FREEBSD)
911 struct ifaddrs *pIfHead = NULL;
912
913 /* Get all available interfaces */
914 rc = getifaddrs(&pIfHead);
915 if (rc < 0)
916 {
917 rc = RTErrConvertFromErrno(errno);
918 VBoxServiceError("VMInfo/Network: Failed to get all interfaces: Error %Rrc\n");
919 return rc;
920 }
921
922 /* Loop through all interfaces and set the data. */
923 for (struct ifaddrs *pIfCurr = pIfHead; pIfCurr; pIfCurr = pIfCurr->ifa_next)
924 {
925 /*
926 * Only AF_INET and no loopback interfaces
927 * @todo: IPv6 interfaces
928 */
929 if ( pIfCurr->ifa_addr->sa_family == AF_INET
930 && !(pIfCurr->ifa_flags & IFF_LOOPBACK))
931 {
932 char szInetAddr[NI_MAXHOST];
933
934 memset(szInetAddr, 0, NI_MAXHOST);
935 getnameinfo(pIfCurr->ifa_addr, sizeof(struct sockaddr_in),
936 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
937 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
938 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
939
940 memset(szInetAddr, 0, NI_MAXHOST);
941 getnameinfo(pIfCurr->ifa_broadaddr, sizeof(struct sockaddr_in),
942 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
943 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
944 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
945
946 memset(szInetAddr, 0, NI_MAXHOST);
947 getnameinfo(pIfCurr->ifa_netmask, sizeof(struct sockaddr_in),
948 szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
949 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
950 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);
951
952 /* Search for the AF_LINK interface of the current AF_INET one and get the mac. */
953 for (struct ifaddrs *pIfLinkCurr = pIfHead; pIfLinkCurr; pIfLinkCurr = pIfLinkCurr->ifa_next)
954 {
955 if ( pIfLinkCurr->ifa_addr->sa_family == AF_LINK
956 && !strcmp(pIfCurr->ifa_name, pIfLinkCurr->ifa_name))
957 {
958 char szMac[32];
959 uint8_t *pu8Mac = NULL;
960 struct sockaddr_dl *pLinkAddress = (struct sockaddr_dl *)pIfLinkCurr->ifa_addr;
961
962 AssertPtr(pLinkAddress);
963 pu8Mac = (uint8_t *)LLADDR(pLinkAddress);
964 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
965 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
966 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
967 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
968 break;
969 }
970 }
971
972 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
973 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");
974
975 cIfacesReport++;
976 }
977 }
978
979 /* Free allocated resources. */
980 freeifaddrs(pIfHead);
981
982#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
983 int sd = socket(AF_INET, SOCK_DGRAM, 0);
984 if (sd < 0)
985 {
986 rc = RTErrConvertFromErrno(errno);
987 VBoxServiceError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
988 return rc;
989 }
990
991 ifconf ifcfg;
992 char buffer[1024] = {0};
993 ifcfg.ifc_len = sizeof(buffer);
994 ifcfg.ifc_buf = buffer;
995 if (ioctl(sd, SIOCGIFCONF, &ifcfg) < 0)
996 {
997 close(sd);
998 rc = RTErrConvertFromErrno(errno);
999 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFCONF) on socket: Error %Rrc\n", rc);
1000 return rc;
1001 }
1002
1003 ifreq* ifrequest = ifcfg.ifc_req;
1004 int cIfacesSystem = ifcfg.ifc_len / sizeof(ifreq);
1005
1006 for (int i = 0; i < cIfacesSystem; ++i)
1007 {
1008 sockaddr_in *pAddress;
1009 if (ioctl(sd, SIOCGIFFLAGS, &ifrequest[i]) < 0)
1010 {
1011 rc = RTErrConvertFromErrno(errno);
1012 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS) on socket: Error %Rrc\n", rc);
1013 break;
1014 }
1015 if (ifrequest[i].ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
1016 continue;
1017
1018 bool fIfUp = !!(ifrequest[i].ifr_flags & IFF_UP);
1019 pAddress = ((sockaddr_in *)&ifrequest[i].ifr_addr);
1020 Assert(pAddress);
1021 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/IP", cIfacesReport);
1022 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1023
1024 if (ioctl(sd, SIOCGIFBRDADDR, &ifrequest[i]) < 0)
1025 {
1026 rc = RTErrConvertFromErrno(errno);
1027 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
1028 break;
1029 }
1030 pAddress = (sockaddr_in *)&ifrequest[i].ifr_broadaddr;
1031 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Broadcast", cIfacesReport);
1032 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1033
1034 if (ioctl(sd, SIOCGIFNETMASK, &ifrequest[i]) < 0)
1035 {
1036 rc = RTErrConvertFromErrno(errno);
1037 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
1038 break;
1039 }
1040# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
1041 pAddress = (sockaddr_in *)&ifrequest[i].ifr_addr;
1042# else
1043 pAddress = (sockaddr_in *)&ifrequest[i].ifr_netmask;
1044# endif
1045
1046 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/V4/Netmask", cIfacesReport);
1047 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));
1048
1049# if defined(RT_OS_SOLARIS)
1050 /*
1051 * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
1052 * We might fail if the interface has not been assigned an IP address.
1053 * That doesn't matter; as long as it's plumbed we can pick it up.
1054 * But, if it has not acquired an IP address we cannot obtain it's MAC
1055 * address this way, so we just use all zeros there.
1056 */
1057 RTMAC IfMac;
1058 RT_ZERO(IfMac);
1059 struct lifreq IfReq;
1060 RT_ZERO(IfReq);
1061 AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(ifrequest[i].ifr_name));
1062 strncpy(IfReq.lifr_name, ifrequest[i].ifr_name, sizeof(ifrequest[i].ifr_name));
1063 if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
1064 {
1065 struct arpreq ArpReq;
1066 RT_ZERO(ArpReq);
1067 memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));
1068
1069 if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
1070 memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
1071 else
1072 {
1073 rc = RTErrConvertFromErrno(errno);
1074 VBoxServiceError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
1075 break;
1076 }
1077 }
1078 else
1079 {
1080 VBoxServiceVerbose(2, "VMInfo/Network: Interface %d has no assigned IP address, skipping ...\n", i);
1081 continue;
1082 }
1083# else
1084# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
1085 if (ioctl(sd, SIOCGIFHWADDR, &ifrequest[i]) < 0)
1086 {
1087 rc = RTErrConvertFromErrno(errno);
1088 VBoxServiceError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
1089 break;
1090 }
1091# endif
1092# endif
1093
1094# ifndef RT_OS_OS2 /** @todo port this to OS/2 */
1095 char szMac[32];
1096# if defined(RT_OS_SOLARIS)
1097 uint8_t *pu8Mac = IfMac.au8;
1098# else
1099 uint8_t *pu8Mac = (uint8_t*)&ifrequest[i].ifr_hwaddr.sa_data[0]; /* @todo see above */
1100# endif
1101 RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
1102 pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3], pu8Mac[4], pu8Mac[5]);
1103 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/MAC", cIfacesReport);
1104 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
1105# endif /* !OS/2*/
1106
1107 RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%u/Status", cIfacesReport);
1108 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");
1109 cIfacesReport++;
1110 } /* For all interfaces */
1111
1112 close(sd);
1113 if (RT_FAILURE(rc))
1114 VBoxServiceError("VMInfo/Network: Network enumeration for interface %u failed with error %Rrc\n", cIfacesReport, rc);
1115
1116#endif /* !RT_OS_WINDOWS */
1117
1118#if 0 /* Zapping not enabled yet, needs more testing first. */
1119 /*
1120 * Zap all stale network interface data if the former (saved) network ifaces count
1121 * is bigger than the current one.
1122 */
1123
1124 /* Get former count. */
1125 uint32_t cIfacesReportOld;
1126 rc = VBoxServiceReadPropUInt32(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/Net/Count", &cIfacesReportOld,
1127 0 /* Min */, UINT32_MAX /* Max */);
1128 if ( RT_SUCCESS(rc)
1129 && cIfacesReportOld > cIfacesReport) /* Are some ifaces not around anymore? */
1130 {
1131 VBoxServiceVerbose(3, "VMInfo/Network: Stale interface data detected (%u old vs. %u current)\n",
1132 cIfacesReportOld, cIfacesReport);
1133
1134 uint32_t uIfaceDeleteIdx = cIfacesReport;
1135 do
1136 {
1137 VBoxServiceVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
1138 rc = VBoxServicePropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%u", uIfaceDeleteIdx++);
1139 } while (RT_SUCCESS(rc));
1140 }
1141 else if ( RT_FAILURE(rc)
1142 && rc != VERR_NOT_FOUND)
1143 {
1144 VBoxServiceError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
1145 }
1146#endif
1147
1148 /*
1149 * This property is a beacon which is _always_ written, even if the network configuration
1150 * does not change. If this property is missing, the host assumes that all other GuestInfo
1151 * properties are no longer valid.
1152 */
1153 VBoxServicePropCacheUpdate(&g_VMInfoPropCache, "/VirtualBox/GuestInfo/Net/Count", "%d",
1154 cIfacesReport);
1155
1156 /* Don't fail here; just report everything we got. */
1157 return VINF_SUCCESS;
1158}
1159
1160
1161/** @copydoc VBOXSERVICE::pfnWorker */
1162DECLCALLBACK(int) VBoxServiceVMInfoWorker(bool volatile *pfShutdown)
1163{
1164 int rc;
1165
1166 /*
1167 * Tell the control thread that it can continue
1168 * spawning services.
1169 */
1170 RTThreadUserSignal(RTThreadSelf());
1171
1172#ifdef RT_OS_WINDOWS
1173 /* Required for network information (must be called per thread). */
1174 WSADATA wsaData;
1175 if (WSAStartup(MAKEWORD(2, 2), &wsaData))
1176 VBoxServiceError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(WSAGetLastError()));
1177#endif /* RT_OS_WINDOWS */
1178
1179 /*
1180 * Write the fixed properties first.
1181 */
1182 vboxserviceVMInfoWriteFixedProperties();
1183
1184 /*
1185 * Now enter the loop retrieving runtime data continuously.
1186 */
1187 for (;;)
1188 {
1189 rc = vboxserviceVMInfoWriteUsers();
1190 if (RT_FAILURE(rc))
1191 break;
1192
1193 rc = vboxserviceVMInfoWriteNetwork();
1194 if (RT_FAILURE(rc))
1195 break;
1196
1197 /* Whether to wait for event semaphore or not. */
1198 bool fWait = true;
1199
1200 /* Check for location awareness. This most likely only
1201 * works with VBox (latest) 4.1 and up. */
1202
1203 /* Check for new connection. */
1204 char *pszLAClientID = NULL;
1205 int rc2 = VBoxServiceReadHostProp(g_uVMInfoGuestPropSvcClientID, g_pszLAActiveClient, true /* Read only */,
1206 &pszLAClientID, NULL /* Flags */, NULL /* Timestamp */);
1207 if (RT_SUCCESS(rc2))
1208 {
1209 AssertPtr(pszLAClientID);
1210 if (RTStrICmp(pszLAClientID, "0")) /* Is a client connected? */
1211 {
1212 uint32_t uLAClientID = RTStrToInt32(pszLAClientID);
1213 uint64_t uLAClientAttachedTS;
1214
1215 /* Peek at "Attach" value to figure out if hotdesking happened. */
1216 char *pszAttach = NULL;
1217 rc2 = vboxServiceGetLAClientValue(uLAClientID, "Attach", &pszAttach,
1218 &uLAClientAttachedTS);
1219
1220 if ( RT_SUCCESS(rc2)
1221 && ( !g_LAClientAttachedTS
1222 || (g_LAClientAttachedTS != uLAClientAttachedTS)))
1223 {
1224 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1225
1226 /* Note: There is a race between setting the guest properties by the host and getting them by
1227 * the guest. */
1228 rc2 = vboxServiceGetLAClientInfo(uLAClientID, &g_LAClientInfo);
1229 if (RT_SUCCESS(rc2))
1230 {
1231 VBoxServiceVerbose(1, "VRDP: Hotdesk client %s with ID=%RU32, Name=%s, Domain=%s\n",
1232 /* If g_LAClientAttachedTS is 0 this means there already was an active
1233 * hotdesk session when VBoxService started. */
1234 !g_LAClientAttachedTS ? "already active" : g_LAClientInfo.fAttached ? "connected" : "disconnected",
1235 uLAClientID, g_LAClientInfo.pszName, g_LAClientInfo.pszDomain);
1236
1237 g_LAClientAttachedTS = g_LAClientInfo.uAttachedTS;
1238
1239 /* Don't wait for event semaphore below anymore because we now know that the client
1240 * changed. This means we need to iterate all VM information again immediately. */
1241 fWait = false;
1242 }
1243 else
1244 {
1245 static int s_iBitchedAboutLAClientInfo = 0;
1246 if (s_iBitchedAboutLAClientInfo++ < 10)
1247 VBoxServiceError("Error getting active location awareness client info, rc=%Rrc\n", rc2);
1248 }
1249 }
1250 else if (RT_FAILURE(rc2))
1251 VBoxServiceError("Error getting attached value of location awareness client %RU32, rc=%Rrc\n",
1252 uLAClientID, rc2);
1253 if (pszAttach)
1254 RTStrFree(pszAttach);
1255 }
1256 else
1257 {
1258 VBoxServiceVerbose(1, "VRDP: UTTSC disconnected from VRDP server\n");
1259 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1260 }
1261
1262 RTStrFree(pszLAClientID);
1263 }
1264 else
1265 {
1266 static int s_iBitchedAboutLAClient = 0;
1267 if ( (rc2 != VERR_NOT_FOUND) /* No location awareness installed, skip. */
1268 && s_iBitchedAboutLAClient++ < 3)
1269 VBoxServiceError("VRDP: Querying connected location awareness client failed with rc=%Rrc\n", rc2);
1270 }
1271
1272 VBoxServiceVerbose(3, "VRDP: Handling location awareness done\n");
1273
1274 /*
1275 * Flush all properties if we were restored.
1276 */
1277 uint64_t idNewSession = g_idVMInfoSession;
1278 VbglR3GetSessionId(&idNewSession);
1279 if (idNewSession != g_idVMInfoSession)
1280 {
1281 VBoxServiceVerbose(3, "The VM session ID changed, flushing all properties\n");
1282 vboxserviceVMInfoWriteFixedProperties();
1283 VBoxServicePropCacheFlush(&g_VMInfoPropCache);
1284 g_idVMInfoSession = idNewSession;
1285 }
1286
1287 /*
1288 * Block for a while.
1289 *
1290 * The event semaphore takes care of ignoring interruptions and it
1291 * allows us to implement service wakeup later.
1292 */
1293 if (*pfShutdown)
1294 break;
1295 if (fWait)
1296 rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
1297 if (*pfShutdown)
1298 break;
1299 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
1300 {
1301 VBoxServiceError("RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
1302 rc = rc2;
1303 break;
1304 }
1305 else if (RT_LIKELY(RT_SUCCESS(rc2)))
1306 {
1307 /* Reset event semaphore if it got triggered. */
1308 rc2 = RTSemEventMultiReset(g_hVMInfoEvent);
1309 if (RT_FAILURE(rc2))
1310 rc2 = VBoxServiceError("RTSemEventMultiReset failed; rc2=%Rrc\n", rc2);
1311 }
1312 }
1313
1314#ifdef RT_OS_WINDOWS
1315 WSACleanup();
1316#endif
1317
1318 return rc;
1319}
1320
1321
1322/** @copydoc VBOXSERVICE::pfnStop */
1323static DECLCALLBACK(void) VBoxServiceVMInfoStop(void)
1324{
1325 RTSemEventMultiSignal(g_hVMInfoEvent);
1326}
1327
1328
1329/** @copydoc VBOXSERVICE::pfnTerm */
1330static DECLCALLBACK(void) VBoxServiceVMInfoTerm(void)
1331{
1332 if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
1333 {
1334 /** @todo temporary solution: Zap all values which are not valid
1335 * anymore when VM goes down (reboot/shutdown ). Needs to
1336 * be replaced with "temporary properties" later.
1337 *
1338 * One idea is to introduce a (HGCM-)session guest property
1339 * flag meaning that a guest property is only valid as long
1340 * as the HGCM session isn't closed (e.g. guest application
1341 * terminates). [don't remove till implemented]
1342 */
1343 /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
1344 * since it remembers what we've written. */
1345 /* Delete the "../Net" branch. */
1346 const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
1347 int rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));
1348
1349 /* Destroy LA client info. */
1350 vboxServiceFreeLAClientInfo(&g_LAClientInfo);
1351
1352 /* Destroy property cache. */
1353 VBoxServicePropCacheDestroy(&g_VMInfoPropCache);
1354
1355 /* Disconnect from guest properties service. */
1356 rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
1357 if (RT_FAILURE(rc))
1358 VBoxServiceError("Failed to disconnect from guest property service! Error: %Rrc\n", rc);
1359 g_uVMInfoGuestPropSvcClientID = 0;
1360
1361 RTSemEventMultiDestroy(g_hVMInfoEvent);
1362 g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
1363 }
1364}
1365
1366
1367/**
1368 * The 'vminfo' service description.
1369 */
1370VBOXSERVICE g_VMInfo =
1371{
1372 /* pszName. */
1373 "vminfo",
1374 /* pszDescription. */
1375 "Virtual Machine Information",
1376 /* pszUsage. */
1377 " [--vminfo-interval <ms>]"
1378 ,
1379 /* pszOptions. */
1380 " --vminfo-interval Specifies the interval at which to retrieve the\n"
1381 " VM information. The default is 10000 ms.\n"
1382 ,
1383 /* methods */
1384 VBoxServiceVMInfoPreInit,
1385 VBoxServiceVMInfoOption,
1386 VBoxServiceVMInfoInit,
1387 VBoxServiceVMInfoWorker,
1388 VBoxServiceVMInfoStop,
1389 VBoxServiceVMInfoTerm
1390};
1391
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