summaryrefslogtreecommitdiffstats
path: root/src/VBox/Additions/common/VBoxService/VBoxServiceVMInfo.cpp
blob: 308bd90ec26a417e6a697ed166fde4160eebf797 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
/* $Id: VBoxServiceVMInfo.cpp $ */
/** @file
 * VBoxService - Virtual Machine Information for the Host.
 */

/*
 * Copyright (C) 2009-2019 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

/** @page pg_vgsvc_vminfo VBoxService - VM Information
 *
 * The VM Information subservice provides heaps of useful information about the
 * VM via guest properties.
 *
 * Guest properties is a limited database maintained by the HGCM GuestProperties
 * service in cooperation with the Main API (VBoxSVC).  Properties have a name
 * (ours are path like), a string value, and a nanosecond timestamp (unix
 * epoch).  The timestamp lets the user see how recent the information is.  As
 * an laternative to polling on changes, it is also possible to wait on changes
 * via the Main API or VBoxManage on the host side and VBoxControl in the guest.
 *
 * The namespace "/VirtualBox/" is reserved for value provided by VirtualBox.
 * This service provides all the information under "/VirtualBox/GuestInfo/".
 *
 *
 * @section sec_vgsvc_vminfo_beacons    Beacons
 *
 * The subservice does not write properties unless there are changes.  So, in
 * order for the host side to know that information is up to date despite an
 * oldish timestamp we define a couple of values that are always updated and can
 * reliably used to figure how old the information actually is.
 *
 * For the networking part "/VirtualBox/GuestInfo/Net/Count" is the value to
 * watch out for.
 *
 * For the login part, it's possible that we intended to use
 * "/VirtualBox/GuestInfo/OS/LoggedInUsers" for this, however it is not defined
 * correctly and current does NOT work as a beacon.
 *
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#ifdef RT_OS_WINDOWS
# include <iprt/win/winsock2.h>
# include <iprt/win/iphlpapi.h>
# include <iprt/win/ws2tcpip.h>
# include <iprt/win/windows.h>
# include <Ntsecapi.h>
#else
# define __STDC_LIMIT_MACROS
# include <arpa/inet.h>
# include <errno.h>
# include <netinet/in.h>
# include <sys/ioctl.h>
# include <sys/socket.h>
# include <net/if.h>
# include <pwd.h> /* getpwuid */
# include <unistd.h>
# if !defined(RT_OS_OS2) && !defined(RT_OS_FREEBSD) && !defined(RT_OS_HAIKU)
#  include <utmpx.h> /** @todo FreeBSD 9 should have this. */
# endif
# ifdef RT_OS_OS2
#  include <net/if_dl.h>
# endif
# ifdef RT_OS_SOLARIS
#  include <sys/sockio.h>
#  include <net/if_arp.h>
# endif
# if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD)
#  include <ifaddrs.h> /* getifaddrs, freeifaddrs */
#  include <net/if_dl.h> /* LLADDR */
#  include <netdb.h> /* getnameinfo */
# endif
# ifdef VBOX_WITH_DBUS
#  include <VBox/dbus.h>
# endif
#endif

#include <iprt/mem.h>
#include <iprt/thread.h>
#include <iprt/string.h>
#include <iprt/semaphore.h>
#include <iprt/system.h>
#include <iprt/time.h>
#include <iprt/assert.h>
#include <VBox/err.h>
#include <VBox/version.h>
#include <VBox/VBoxGuestLib.h>
#include "VBoxServiceInternal.h"
#include "VBoxServiceUtils.h"
#include "VBoxServicePropCache.h"


/** Structure containing information about a location awarness
 *  client provided by the host. */
/** @todo Move this (and functions) into VbglR3. */
typedef struct VBOXSERVICELACLIENTINFO
{
    uint32_t    uID;
    char       *pszName;
    char       *pszLocation;
    char       *pszDomain;
    bool        fAttached;
    uint64_t    uAttachedTS;
} VBOXSERVICELACLIENTINFO, *PVBOXSERVICELACLIENTINFO;


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** The vminfo interval (milliseconds). */
static uint32_t                 g_cMsVMInfoInterval = 0;
/** The semaphore we're blocking on. */
static RTSEMEVENTMULTI          g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
/** The guest property service client ID. */
static uint32_t                 g_uVMInfoGuestPropSvcClientID = 0;
/** Number of currently logged in users in OS. */
static uint32_t                 g_cVMInfoLoggedInUsers = 0;
/** The guest property cache. */
static VBOXSERVICEVEPROPCACHE   g_VMInfoPropCache;
static const char              *g_pszPropCacheValLoggedInUsersList = "/VirtualBox/GuestInfo/OS/LoggedInUsersList";
static const char              *g_pszPropCacheValLoggedInUsers = "/VirtualBox/GuestInfo/OS/LoggedInUsers";
static const char              *g_pszPropCacheValNoLoggedInUsers = "/VirtualBox/GuestInfo/OS/NoLoggedInUsers";
static const char              *g_pszPropCacheValNetCount = "/VirtualBox/GuestInfo/Net/Count";
/** A guest user's guest property root key. */
static const char              *g_pszPropCacheValUser = "/VirtualBox/GuestInfo/User/";
/** The VM session ID. Changes whenever the VM is restored or reset. */
static uint64_t                 g_idVMInfoSession;
/** The last attached locartion awareness (LA) client timestamp. */
static uint64_t                 g_LAClientAttachedTS = 0;
/** The current LA client info. */
static VBOXSERVICELACLIENTINFO  g_LAClientInfo;
/** User idle threshold (in ms). This specifies the minimum time a user is considered
 *  as being idle and then will be reported to the host. Default is 5s. */
uint32_t                        g_uVMInfoUserIdleThresholdMS = 5 * 1000;


/*********************************************************************************************************************************
*   Defines                                                                                                                      *
*********************************************************************************************************************************/
static const char *g_pszLAActiveClient = "/VirtualBox/HostInfo/VRDP/ActiveClient";

#ifdef VBOX_WITH_DBUS
/** @name ConsoleKit defines (taken from 0.4.5).
 * @{ */
# define CK_NAME                "org.freedesktop.ConsoleKit"
# define CK_PATH                "/org/freedesktop/ConsoleKit"
# define CK_INTERFACE           "org.freedesktop.ConsoleKit"
# define CK_MANAGER_PATH        "/org/freedesktop/ConsoleKit/Manager"
# define CK_MANAGER_INTERFACE   "org.freedesktop.ConsoleKit.Manager"
# define CK_SEAT_INTERFACE      "org.freedesktop.ConsoleKit.Seat"
# define CK_SESSION_INTERFACE   "org.freedesktop.ConsoleKit.Session"
/** @} */
#endif



/**
 * Signals the event so that a re-enumeration of VM-specific
 * information (like logged in users) can happen.
 *
 * @return  IPRT status code.
 */
int VGSvcVMInfoSignal(void)
{
    /* Trigger a re-enumeration of all logged-in users by unblocking
     * the multi event semaphore of the VMInfo thread. */
    if (g_hVMInfoEvent)
        return RTSemEventMultiSignal(g_hVMInfoEvent);

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{VBOXSERVICE,pfnPreInit}
 */
static DECLCALLBACK(int) vbsvcVMInfoPreInit(void)
{
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{VBOXSERVICE,pfnOption}
 */
static DECLCALLBACK(int) vbsvcVMInfoOption(const char **ppszShort, int argc, char **argv, int *pi)
{
    /** @todo Use RTGetOpt here. */

    int rc = -1;
    if (ppszShort)
        /* no short options */;
    else if (!strcmp(argv[*pi], "--vminfo-interval"))
        rc = VGSvcArgUInt32(argc, argv, "", pi, &g_cMsVMInfoInterval, 1, UINT32_MAX - 1);
    else if (!strcmp(argv[*pi], "--vminfo-user-idle-threshold"))
        rc = VGSvcArgUInt32(argc, argv, "", pi, &g_uVMInfoUserIdleThresholdMS, 1, UINT32_MAX - 1);
    return rc;
}


/**
 * @interface_method_impl{VBOXSERVICE,pfnInit}
 */
static DECLCALLBACK(int) vbsvcVMInfoInit(void)
{
    /*
     * If not specified, find the right interval default.
     * Then create the event sem to block on.
     */
    if (!g_cMsVMInfoInterval)
        g_cMsVMInfoInterval = g_DefaultInterval * 1000;
    if (!g_cMsVMInfoInterval)
    {
        /* Set it to 5s by default for location awareness checks. */
        g_cMsVMInfoInterval = 5 * 1000;
    }

    int rc = RTSemEventMultiCreate(&g_hVMInfoEvent);
    AssertRCReturn(rc, rc);

    VbglR3GetSessionId(&g_idVMInfoSession);
    /* The status code is ignored as this information is not available with VBox < 3.2.10. */

    /* Initialize the LA client object. */
    RT_ZERO(g_LAClientInfo);

    rc = VbglR3GuestPropConnect(&g_uVMInfoGuestPropSvcClientID);
    if (RT_SUCCESS(rc))
        VGSvcVerbose(3, "Property Service Client ID: %#x\n", g_uVMInfoGuestPropSvcClientID);
    else
    {
        /* If the service was not found, we disable this service without
           causing VBoxService to fail. */
        if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
        {
            VGSvcVerbose(0, "Guest property service is not available, disabling the service\n");
            rc = VERR_SERVICE_DISABLED;
        }
        else
            VGSvcError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
        RTSemEventMultiDestroy(g_hVMInfoEvent);
        g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
    }

    if (RT_SUCCESS(rc))
    {
        VGSvcPropCacheCreate(&g_VMInfoPropCache, g_uVMInfoGuestPropSvcClientID);

        /*
         * Declare some guest properties with flags and reset values.
         */
        int rc2 = VGSvcPropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsersList,
                                            VGSVCPROPCACHE_FLAGS_TEMPORARY | VGSVCPROPCACHE_FLAGS_TRANSIENT,
                                            NULL /* Delete on exit */);
        if (RT_FAILURE(rc2))
            VGSvcError("Failed to init property cache value '%s', rc=%Rrc\n", g_pszPropCacheValLoggedInUsersList, rc2);

        rc2 = VGSvcPropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsers,
                                        VGSVCPROPCACHE_FLAGS_TEMPORARY | VGSVCPROPCACHE_FLAGS_TRANSIENT, "0");
        if (RT_FAILURE(rc2))
            VGSvcError("Failed to init property cache value '%s', rc=%Rrc\n", g_pszPropCacheValLoggedInUsers, rc2);

        rc2 = VGSvcPropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValNoLoggedInUsers,
                                        VGSVCPROPCACHE_FLAGS_TEMPORARY | VGSVCPROPCACHE_FLAGS_TRANSIENT, "true");
        if (RT_FAILURE(rc2))
            VGSvcError("Failed to init property cache value '%s', rc=%Rrc\n", g_pszPropCacheValNoLoggedInUsers, rc2);

        rc2 = VGSvcPropCacheUpdateEntry(&g_VMInfoPropCache, g_pszPropCacheValNetCount,
                                        VGSVCPROPCACHE_FLAGS_TEMPORARY | VGSVCPROPCACHE_FLAGS_ALWAYS_UPDATE,
                                        NULL /* Delete on exit */);
        if (RT_FAILURE(rc2))
            VGSvcError("Failed to init property cache value '%s', rc=%Rrc\n", g_pszPropCacheValNetCount, rc2);

        /*
         * Get configuration guest properties from the host.
         * Note: All properties should have sensible defaults in case the lookup here fails.
         */
        char *pszValue;
        rc2 = VGSvcReadHostProp(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--vminfo-user-idle-threshold",
                                true /* Read only */, &pszValue, NULL /* Flags */, NULL /* Timestamp */);
        if (RT_SUCCESS(rc2))
        {
            AssertPtr(pszValue);
            g_uVMInfoUserIdleThresholdMS = RT_CLAMP(RTStrToUInt32(pszValue), 1000, UINT32_MAX - 1);
            RTStrFree(pszValue);
        }
    }
    return rc;
}


/**
 * Retrieves a specifiy client LA property.
 *
 * @return  IPRT status code.
 * @param   uClientID               LA client ID to retrieve property for.
 * @param   pszProperty             Property (without path) to retrieve.
 * @param   ppszValue               Where to store value of property.
 * @param   puTimestamp             Timestamp of property to retrieve. Optional.
 */
static int vgsvcGetLAClientValue(uint32_t uClientID, const char *pszProperty, char **ppszValue, uint64_t *puTimestamp)
{
    AssertReturn(uClientID, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pszProperty, VERR_INVALID_POINTER);

    int rc;

    char pszClientPath[255];
/** @todo r=bird: Another pointless RTStrPrintf test with wrong status code to boot. */
    if (RTStrPrintf(pszClientPath, sizeof(pszClientPath),
                    "/VirtualBox/HostInfo/VRDP/Client/%RU32/%s", uClientID, pszProperty))
    {
        rc = VGSvcReadHostProp(g_uVMInfoGuestPropSvcClientID, pszClientPath, true /* Read only */,
                               ppszValue, NULL /* Flags */, puTimestamp);
    }
    else
        rc = VERR_NO_MEMORY;

    return rc;
}


/**
 * Retrieves LA client information. On success the returned structure will have allocated
 * objects which need to be free'd with vboxServiceFreeLAClientInfo.
 *
 * @return  IPRT status code.
 * @param   uClientID               Client ID to retrieve information for.
 * @param   pClient                 Pointer where to store the client information.
 */
static int vgsvcGetLAClientInfo(uint32_t uClientID, PVBOXSERVICELACLIENTINFO pClient)
{
    AssertReturn(uClientID, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pClient, VERR_INVALID_POINTER);

    int rc = vgsvcGetLAClientValue(uClientID, "Name", &pClient->pszName,
                                         NULL /* Timestamp */);
    if (RT_SUCCESS(rc))
    {
        char *pszAttach;
        rc = vgsvcGetLAClientValue(uClientID, "Attach", &pszAttach, &pClient->uAttachedTS);
        if (RT_SUCCESS(rc))
        {
            AssertPtr(pszAttach);
            pClient->fAttached = RTStrICmp(pszAttach, "1") == 0;

            RTStrFree(pszAttach);
        }
    }
    if (RT_SUCCESS(rc))
        rc = vgsvcGetLAClientValue(uClientID, "Location", &pClient->pszLocation, NULL /* Timestamp */);
    if (RT_SUCCESS(rc))
        rc = vgsvcGetLAClientValue(uClientID, "Domain", &pClient->pszDomain, NULL /* Timestamp */);
    if (RT_SUCCESS(rc))
        pClient->uID = uClientID;

    return rc;
}


/**
 * Frees all allocated LA client information of a structure.
 *
 * @param   pClient                 Pointer to client information structure to free.
 */
static void vgsvcFreeLAClientInfo(PVBOXSERVICELACLIENTINFO pClient)
{
    if (pClient)
    {
        if (pClient->pszName)
        {
            RTStrFree(pClient->pszName);
            pClient->pszName = NULL;
        }
        if (pClient->pszLocation)
        {
            RTStrFree(pClient->pszLocation);
            pClient->pszLocation = NULL;
        }
        if (pClient->pszDomain)
        {
            RTStrFree(pClient->pszDomain);
            pClient->pszDomain = NULL;
        }
    }
}


/**
 * Updates a per-guest user guest property inside the given property cache.
 *
 * @return  IPRT status code.
 * @param   pCache                  Pointer to guest property cache to update user in.
 * @param   pszUser                 Name of guest user to update.
 * @param   pszDomain               Domain of guest user to update. Optional.
 * @param   pszKey                  Key name of guest property to update.
 * @param   pszValueFormat          Guest property value to set. Pass NULL for deleting
 *                                  the property.
 */
int VGSvcUserUpdateF(PVBOXSERVICEVEPROPCACHE pCache, const char *pszUser, const char *pszDomain,
                     const char *pszKey, const char *pszValueFormat, ...)
{
    AssertPtrReturn(pCache, VERR_INVALID_POINTER);
    AssertPtrReturn(pszUser, VERR_INVALID_POINTER);
    /* pszDomain is optional. */
    AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
    /* pszValueFormat is optional. */

    int rc = VINF_SUCCESS;

    char *pszName;
    if (pszDomain)
    {
/** @todo r=bird: RTStrAPrintf returns -1, not zero on failure!   */
        if (!RTStrAPrintf(&pszName, "%s%s@%s/%s", g_pszPropCacheValUser, pszUser, pszDomain, pszKey))
            rc = VERR_NO_MEMORY;
    }
    else
    {
/** @todo r=bird: RTStrAPrintf returns -1, not zero on failure! You got it
 *        right 5 lines further down... */
        if (!RTStrAPrintf(&pszName, "%s%s/%s", g_pszPropCacheValUser, pszUser, pszKey))
            rc = VERR_NO_MEMORY;
    }

    char *pszValue = NULL;
    if (   RT_SUCCESS(rc)
        && pszValueFormat)
    {
        va_list va;
        va_start(va, pszValueFormat);
        if (RTStrAPrintfV(&pszValue, pszValueFormat, va) < 0)
            rc = VERR_NO_MEMORY;
        va_end(va);
        if (   RT_SUCCESS(rc)
            && !pszValue)
            rc = VERR_NO_STR_MEMORY;
    }

    if (RT_SUCCESS(rc))
        rc = VGSvcPropCacheUpdate(pCache, pszName, pszValue);
    if (rc == VINF_SUCCESS) /* VGSvcPropCacheUpdate will also return VINF_NO_CHANGE. */
    {
        /** @todo Combine updating flags w/ updating the actual value. */
        rc = VGSvcPropCacheUpdateEntry(pCache, pszName,
                                       VGSVCPROPCACHE_FLAGS_TEMPORARY | VGSVCPROPCACHE_FLAGS_TRANSIENT,
                                       NULL /* Delete on exit */);
    }

    RTStrFree(pszValue);
    RTStrFree(pszName);
    return rc;
}


/**
 * Writes the properties that won't change while the service is running.
 *
 * Errors are ignored.
 */
static void vgsvcVMInfoWriteFixedProperties(void)
{
    /*
     * First get OS information that won't change.
     */
    char szInfo[256];
    int rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szInfo, sizeof(szInfo));
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Product",
                    "%s", RT_FAILURE(rc) ? "" : szInfo);

    rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szInfo, sizeof(szInfo));
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Release",
                    "%s", RT_FAILURE(rc) ? "" : szInfo);

    rc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szInfo, sizeof(szInfo));
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/Version",
                    "%s", RT_FAILURE(rc) ? "" : szInfo);

    rc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szInfo, sizeof(szInfo));
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestInfo/OS/ServicePack",
                    "%s", RT_FAILURE(rc) ? "" : szInfo);

    /*
     * Retrieve version information about Guest Additions and installed files (components).
     */
    char *pszAddVer;
    char *pszAddVerExt;
    char *pszAddRev;
    rc = VbglR3GetAdditionsVersion(&pszAddVer, &pszAddVerExt, &pszAddRev);
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Version",
                    "%s", RT_FAILURE(rc) ? "" : pszAddVer);
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/VersionExt",
                    "%s", RT_FAILURE(rc) ? "" : pszAddVerExt);
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/Revision",
                    "%s", RT_FAILURE(rc) ? "" : pszAddRev);
    if (RT_SUCCESS(rc))
    {
        RTStrFree(pszAddVer);
        RTStrFree(pszAddVerExt);
        RTStrFree(pszAddRev);
    }

#ifdef RT_OS_WINDOWS
    /*
     * Do windows specific properties.
     */
    char *pszInstDir;
    rc = VbglR3GetAdditionsInstallationPath(&pszInstDir);
    VGSvcWritePropF(g_uVMInfoGuestPropSvcClientID, "/VirtualBox/GuestAdd/InstallDir",
                    "%s", RT_FAILURE(rc) ? "" :  pszInstDir);
    if (RT_SUCCESS(rc))
        RTStrFree(pszInstDir);

    VGSvcVMInfoWinGetComponentVersions(g_uVMInfoGuestPropSvcClientID);
#endif
}


#if defined(VBOX_WITH_DBUS) && defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
/*
 * Simple wrapper to work around compiler-specific va_list madness.
 */
static dbus_bool_t vboxService_dbus_message_get_args(DBusMessage *message, DBusError *error, int first_arg_type, ...)
{
    va_list va;
    va_start(va, first_arg_type);
    dbus_bool_t ret = dbus_message_get_args_valist(message, error, first_arg_type, va);
    va_end(va);
    return ret;
}
#endif


/**
 * Provide information about active users.
 */
static int vgsvcVMInfoWriteUsers(void)
{
    int rc;
    char *pszUserList = NULL;
    uint32_t cUsersInList = 0;

#ifdef RT_OS_WINDOWS
    rc = VGSvcVMInfoWinWriteUsers(&g_VMInfoPropCache, &pszUserList, &cUsersInList);

#elif defined(RT_OS_FREEBSD)
    /** @todo FreeBSD: Port logged on user info retrieval.
     *                 However, FreeBSD 9 supports utmpx, so we could use the code
     *                 block below (?). */
    rc = VERR_NOT_IMPLEMENTED;

#elif defined(RT_OS_HAIKU)
    /** @todo Haiku: Port logged on user info retrieval. */
    rc = VERR_NOT_IMPLEMENTED;

#elif defined(RT_OS_OS2)
    /** @todo OS/2: Port logged on (LAN/local/whatever) user info retrieval. */
    rc = VERR_NOT_IMPLEMENTED;

#else
    setutxent();
    utmpx *ut_user;
    uint32_t cListSize = 32;

    /* Allocate a first array to hold 32 users max. */
    char **papszUsers = (char **)RTMemAllocZ(cListSize * sizeof(char *));
    if (papszUsers)
        rc = VINF_SUCCESS;
    else
        rc = VERR_NO_MEMORY;

    /* Process all entries in the utmp file.
     * Note: This only handles */
    while (   (ut_user = getutxent())
           && RT_SUCCESS(rc))
    {
# ifdef RT_OS_DARWIN /* No ut_user->ut_session on Darwin */
        VGSvcVerbose(4, "Found entry '%s' (type: %d, PID: %RU32)\n", ut_user->ut_user, ut_user->ut_type, ut_user->ut_pid);
# else
        VGSvcVerbose(4, "Found entry '%s' (type: %d, PID: %RU32, session: %RU32)\n",
                     ut_user->ut_user, ut_user->ut_type, ut_user->ut_pid, ut_user->ut_session);
# endif
        if (cUsersInList > cListSize)
        {
            cListSize += 32;
            void *pvNew = RTMemRealloc(papszUsers, cListSize * sizeof(char*));
            AssertBreakStmt(pvNew, cListSize -= 32);
            papszUsers = (char **)pvNew;
        }

        /* Make sure we don't add user names which are not
         * part of type USER_PROCES. */
        if (ut_user->ut_type == USER_PROCESS) /* Regular user process. */
        {
            bool fFound = false;
            for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
                fFound = strcmp(papszUsers[i], ut_user->ut_user) == 0;

            if (!fFound)
            {
                VGSvcVerbose(4, "Adding user '%s' (type: %d) to list\n", ut_user->ut_user, ut_user->ut_type);

                rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ut_user->ut_user);
                if (RT_FAILURE(rc))
                    break;
                cUsersInList++;
            }
        }
    }

# ifdef VBOX_WITH_DBUS
#  if defined(RT_OS_LINUX) /* Not yet for Solaris/FreeBSB. */
    DBusError dbErr;
    DBusConnection *pConnection = NULL;
    int rc2 = RTDBusLoadLib();
    bool fHaveLibDbus = false;
    if (RT_SUCCESS(rc2))
    {
        /* Handle desktop sessions using ConsoleKit. */
        VGSvcVerbose(4, "Checking ConsoleKit sessions ...\n");
        fHaveLibDbus = true;
        dbus_error_init(&dbErr);
        pConnection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbErr);
    }

    if (   pConnection
        && !dbus_error_is_set(&dbErr))
    {
        /* Get all available sessions. */
/** @todo r=bird: What's the point of hardcoding things here when we've taken the pain of defining CK_XXX constants at the top of the file (or vice versa)? */
        DBusMessage *pMsgSessions = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
                                                                 "/org/freedesktop/ConsoleKit/Manager",
                                                                 "org.freedesktop.ConsoleKit.Manager",
                                                                 "GetSessions");
        if (   pMsgSessions
            && dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL)
        {
            DBusMessage *pReplySessions = dbus_connection_send_with_reply_and_block(pConnection,
                                                                                    pMsgSessions, 30 * 1000 /* 30s timeout */,
                                                                                    &dbErr);
            if (   pReplySessions
                && !dbus_error_is_set(&dbErr))
            {
                char **ppszSessions;
                int cSessions;
                if (   dbus_message_get_type(pMsgSessions) == DBUS_MESSAGE_TYPE_METHOD_CALL
                    && vboxService_dbus_message_get_args(pReplySessions, &dbErr, DBUS_TYPE_ARRAY,
                                                         DBUS_TYPE_OBJECT_PATH, &ppszSessions, &cSessions,
                                                         DBUS_TYPE_INVALID /* Termination */))
                {
                    VGSvcVerbose(4, "ConsoleKit: retrieved %RU16 session(s)\n", cSessions);

                    char **ppszCurSession = ppszSessions;
                    for (ppszCurSession; ppszCurSession && *ppszCurSession; ppszCurSession++)
                    {
                        VGSvcVerbose(4, "ConsoleKit: processing session '%s' ...\n", *ppszCurSession);

                        /* Only respect active sessions .*/
                        bool fActive = false;
                        DBusMessage *pMsgSessionActive = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
                                                                                      *ppszCurSession,
                                                                                      "org.freedesktop.ConsoleKit.Session",
                                                                                      "IsActive");
                        if (   pMsgSessionActive
                            && dbus_message_get_type(pMsgSessionActive) == DBUS_MESSAGE_TYPE_METHOD_CALL)
                        {
                            DBusMessage *pReplySessionActive = dbus_connection_send_with_reply_and_block(pConnection,
                                                                                                         pMsgSessionActive,
                                                                                                         30 * 1000 /*sec*/,
                                                                                                         &dbErr);
                            if (   pReplySessionActive
                                && !dbus_error_is_set(&dbErr))
                            {
                                DBusMessageIter itMsg;
                                if (   dbus_message_iter_init(pReplySessionActive, &itMsg)
                                    && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_BOOLEAN)
                                {
                                    /* Get uid from message. */
                                    int val;
                                    dbus_message_iter_get_basic(&itMsg, &val);
                                    fActive = val >= 1;
                                }

                                if (pReplySessionActive)
                                    dbus_message_unref(pReplySessionActive);
                            }

                            if (pMsgSessionActive)
                                dbus_message_unref(pMsgSessionActive);
                        }

                        VGSvcVerbose(4, "ConsoleKit: session '%s' is %s\n",
                                           *ppszCurSession, fActive ? "active" : "not active");

                        /* *ppszCurSession now contains the object path
                         * (e.g. "/org/freedesktop/ConsoleKit/Session1"). */
                        DBusMessage *pMsgUnixUser = dbus_message_new_method_call("org.freedesktop.ConsoleKit",
                                                                                 *ppszCurSession,
                                                                                 "org.freedesktop.ConsoleKit.Session",
                                                                                 "GetUnixUser");
                        if (   fActive
                            && pMsgUnixUser
                            && dbus_message_get_type(pMsgUnixUser) == DBUS_MESSAGE_TYPE_METHOD_CALL)
                        {
                            DBusMessage *pReplyUnixUser = dbus_connection_send_with_reply_and_block(pConnection,
                                                                                                    pMsgUnixUser,
                                                                                                    30 * 1000 /* 30s timeout */,
                                                                                                    &dbErr);
                            if (   pReplyUnixUser
                                && !dbus_error_is_set(&dbErr))
                            {
                                DBusMessageIter itMsg;
                                if (   dbus_message_iter_init(pReplyUnixUser, &itMsg)
                                    && dbus_message_iter_get_arg_type(&itMsg) == DBUS_TYPE_UINT32)
                                {
                                    /* Get uid from message. */
                                    uint32_t uid;
                                    dbus_message_iter_get_basic(&itMsg, &uid);

                                    /** @todo Add support for getting UID_MIN (/etc/login.defs on
                                     *        Debian). */
                                    uint32_t uid_min = 1000;

                                    /* Look up user name (realname) from uid. */
                                    setpwent();
                                    struct passwd *ppwEntry = getpwuid(uid);
                                    if (   ppwEntry
                                        && ppwEntry->pw_name)
                                    {
                                        if (ppwEntry->pw_uid >= uid_min /* Only respect users, not daemons etc. */)
                                        {
                                            VGSvcVerbose(4, "ConsoleKit: session '%s' -> %s (uid: %RU32)\n",
                                                         *ppszCurSession, ppwEntry->pw_name, uid);

                                            bool fFound = false;
                                            for (uint32_t i = 0; i < cUsersInList && !fFound; i++)
                                                fFound = strcmp(papszUsers[i], ppwEntry->pw_name) == 0;

                                            if (!fFound)
                                            {
                                                VGSvcVerbose(4, "ConsoleKit: adding user '%s' to list\n", ppwEntry->pw_name);

                                                rc = RTStrDupEx(&papszUsers[cUsersInList], (const char *)ppwEntry->pw_name);
                                                if (RT_FAILURE(rc))
                                                    break;
                                                cUsersInList++;
                                            }
                                        }
                                        /* else silently ignore the user */
                                    }
                                    else
                                        VGSvcError("ConsoleKit: unable to lookup user name for uid=%RU32\n", uid);
                                }
                                else
                                    AssertMsgFailed(("ConsoleKit: GetUnixUser returned a wrong argument type\n"));
                            }

                            if (pReplyUnixUser)
                                dbus_message_unref(pReplyUnixUser);
                        }
                        else if (fActive) /* don't bitch about inactive users */
                        {
                            static int s_iBitchedAboutConsoleKit = 0;
                            if (s_iBitchedAboutConsoleKit < 1)
                            {
                                s_iBitchedAboutConsoleKit++;
                                VGSvcError("ConsoleKit: unable to retrieve user for session '%s' (msg type=%d): %s\n",
                                           *ppszCurSession, dbus_message_get_type(pMsgUnixUser),
                                           dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
                            }
                        }

                        if (pMsgUnixUser)
                            dbus_message_unref(pMsgUnixUser);
                    }

                    dbus_free_string_array(ppszSessions);
                }
                else
                    VGSvcError("ConsoleKit: unable to retrieve session parameters (msg type=%d): %s\n",
                               dbus_message_get_type(pMsgSessions),
                               dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
                dbus_message_unref(pReplySessions);
            }

            if (pMsgSessions)
            {
                dbus_message_unref(pMsgSessions);
                pMsgSessions = NULL;
            }
        }
        else
        {
            static int s_iBitchedAboutConsoleKit = 0;
            if (s_iBitchedAboutConsoleKit < 3)
            {
                s_iBitchedAboutConsoleKit++;
                VGSvcError("Unable to invoke ConsoleKit (%d/3) -- maybe not installed / used? Error: %s\n",
                           s_iBitchedAboutConsoleKit,
                           dbus_error_is_set(&dbErr) ? dbErr.message : "No error information available");
            }
        }

        if (pMsgSessions)
            dbus_message_unref(pMsgSessions);
    }
    else
    {
        static int s_iBitchedAboutDBus = 0;
        if (s_iBitchedAboutDBus < 3)
        {
            s_iBitchedAboutDBus++;
            VGSvcError("Unable to connect to system D-Bus (%d/3): %s\n", s_iBitchedAboutDBus,
                       fHaveLibDbus && dbus_error_is_set(&dbErr) ? dbErr.message : "D-Bus not installed");
        }
    }

    if (   fHaveLibDbus
        && dbus_error_is_set(&dbErr))
        dbus_error_free(&dbErr);
#  endif /* RT_OS_LINUX */
# endif /* VBOX_WITH_DBUS */

    /** @todo Fedora/others: Handle systemd-loginctl. */

    /* Calc the string length. */
    size_t cchUserList = 0;
    if (RT_SUCCESS(rc))
        for (uint32_t i = 0; i < cUsersInList; i++)
            cchUserList += (i != 0) + strlen(papszUsers[i]);

    /* Build the user list. */
    if (cchUserList > 0)
    {
        if (RT_SUCCESS(rc))
            rc = RTStrAllocEx(&pszUserList, cchUserList + 1);
        if (RT_SUCCESS(rc))
        {
            char *psz = pszUserList;
            for (uint32_t i = 0; i < cUsersInList; i++)
            {
                if (i != 0)
                    *psz++ = ',';
                size_t cch = strlen(papszUsers[i]);
                memcpy(psz, papszUsers[i], cch);
                psz += cch;
            }
            *psz = '\0';
        }
    }

    /* Cleanup. */
    for (uint32_t i = 0; i < cUsersInList; i++)
        RTStrFree(papszUsers[i]);
    RTMemFree(papszUsers);

    endutxent(); /* Close utmpx file. */
#endif /* !RT_OS_WINDOWS && !RT_OS_FREEBSD && !RT_OS_HAIKU && !RT_OS_OS2 */

    Assert(RT_FAILURE(rc) || cUsersInList == 0 || (pszUserList && *pszUserList));

    /*
     * If the user enumeration above failed, reset the user count to 0 except
     * we didn't have enough memory anymore. In that case we want to preserve
     * the previous user count in order to not confuse third party tools which
     * rely on that count.
     */
    if (RT_FAILURE(rc))
    {
        if (rc == VERR_NO_MEMORY)
        {
            static int s_iVMInfoBitchedOOM = 0;
            if (s_iVMInfoBitchedOOM++ < 3)
                VGSvcVerbose(0, "Warning: Not enough memory available to enumerate users! Keeping old value (%RU32)\n",
                             g_cVMInfoLoggedInUsers);
            cUsersInList = g_cVMInfoLoggedInUsers;
        }
        else
            cUsersInList = 0;
    }
    else /* Preserve logged in users count. */
        g_cVMInfoLoggedInUsers = cUsersInList;

    VGSvcVerbose(4, "cUsersInList=%RU32, pszUserList=%s, rc=%Rrc\n", cUsersInList, pszUserList ? pszUserList : "<NULL>", rc);

    if (pszUserList)
    {
        AssertMsg(cUsersInList, ("pszUserList contains users whereas cUsersInList is 0\n"));
        rc = VGSvcPropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsersList, "%s", pszUserList);
    }
    else
        rc = VGSvcPropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsersList, NULL);
    if (RT_FAILURE(rc))
        VGSvcError("Error writing logged in users list, rc=%Rrc\n", rc);

    rc = VGSvcPropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValLoggedInUsers, "%RU32", cUsersInList);
    if (RT_FAILURE(rc))
        VGSvcError("Error writing logged in users count, rc=%Rrc\n", rc);

/** @todo r=bird: What's this 'beacon' nonsense here?  It's _not_ defined with
 *        the VGSVCPROPCACHE_FLAGS_ALWAYS_UPDATE flag set!!  */
    rc = VGSvcPropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValNoLoggedInUsers, cUsersInList == 0 ? "true" : "false");
    if (RT_FAILURE(rc))
        VGSvcError("Error writing no logged in users beacon, rc=%Rrc\n", rc);

    if (pszUserList)
        RTStrFree(pszUserList);

    VGSvcVerbose(4, "Writing users returned with rc=%Rrc\n", rc);
    return rc;
}


/**
 * Provide information about the guest network.
 */
static int vgsvcVMInfoWriteNetwork(void)
{
    uint32_t    cIfsReported = 0;
    char        szPropPath[256];

#ifdef RT_OS_WINDOWS
    /* */
    if (   !g_pfnGetAdaptersInfo
        && (   !g_pfnWSAIoctl
            || !g_pfnWSASocketA
            || !g_pfnWSAGetLastError
            || !g_pfninet_ntoa
            || !g_pfnclosesocket) )
           return VINF_SUCCESS;

    ULONG            cbAdpInfo = sizeof(IP_ADAPTER_INFO);
    IP_ADAPTER_INFO *pAdpInfo  = (IP_ADAPTER_INFO *)RTMemAlloc(cbAdpInfo);
    if (!pAdpInfo)
    {
        VGSvcError("VMInfo/Network: Failed to allocate IP_ADAPTER_INFO\n");
        return VERR_NO_MEMORY;
    }
    DWORD dwRet = g_pfnGetAdaptersInfo ? g_pfnGetAdaptersInfo(pAdpInfo, &cbAdpInfo) : ERROR_NO_DATA;
    if (dwRet == ERROR_BUFFER_OVERFLOW)
    {
        IP_ADAPTER_INFO *pAdpInfoNew = (IP_ADAPTER_INFO*)RTMemRealloc(pAdpInfo, cbAdpInfo);
        if (pAdpInfoNew)
        {
            pAdpInfo = pAdpInfoNew;
            dwRet = g_pfnGetAdaptersInfo(pAdpInfo, &cbAdpInfo);
        }
    }
    else if (dwRet == ERROR_NO_DATA)
    {
        VGSvcVerbose(3, "VMInfo/Network: No network adapters available\n");

        /* If no network adapters available / present in the
         * system we pretend success to not bail out too early. */
        dwRet = ERROR_SUCCESS;
    }
    if (dwRet != ERROR_SUCCESS)
    {
        RTMemFree(pAdpInfo);
        VGSvcError("VMInfo/Network: Failed to get adapter info: Error %d\n", dwRet);
        return RTErrConvertFromWin32(dwRet);
    }

    SOCKET sd = g_pfnWSASocketA(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
    if (sd == SOCKET_ERROR) /* Socket invalid. */
    {
        int wsaErr = g_pfnWSAGetLastError();
        /* Don't complain/bail out with an error if network stack is not up; can happen
         * on NT4 due to start up when not connected shares dialogs pop up. */
        if (WSAENETDOWN == wsaErr)
        {
            VGSvcVerbose(0, "VMInfo/Network: Network is not up yet.\n");
            wsaErr = VINF_SUCCESS;
        }
        else
            VGSvcError("VMInfo/Network: Failed to get a socket: Error %d\n", wsaErr);
        if (pAdpInfo)
            RTMemFree(pAdpInfo);
        return RTErrConvertFromWin32(wsaErr);
    }

    INTERFACE_INFO  aInterfaces[20] = {0};
    DWORD           cbReturned      = 0;
# ifdef RT_ARCH_x86
    /* Workaround for uninitialized variable used in memcpy in GetTcpipInterfaceList
       (NT4SP1 at least).  It seems to be happy enough with garbages, no failure
       returns so far, so we just need to prevent it from crashing by filling the
       stack with valid pointer values prior to the API call. */
    _asm
    {
        mov     edx, edi
        lea     eax, aInterfaces
        mov     [esp - 0x1000], eax
        mov     [esp - 0x2000], eax
        mov     ecx, 0x2000/4 - 1
        cld
        lea     edi, [esp - 0x2000]
        rep stosd
        mov     edi, edx
    }
# endif
    int rc = g_pfnWSAIoctl(sd,
                           SIO_GET_INTERFACE_LIST,
                           NULL,                /* pvInBuffer */
                           0,                   /* cbInBuffer */
                           &aInterfaces[0],     /* pvOutBuffer */
                           sizeof(aInterfaces), /* cbOutBuffer */
                           &cbReturned,
                           NULL,                /* pOverlapped */
                           NULL);               /* pCompletionRoutine */
    if (rc == SOCKET_ERROR)
    {
        VGSvcError("VMInfo/Network: Failed to WSAIoctl() on socket: Error: %d\n", g_pfnWSAGetLastError());
        if (pAdpInfo)
            RTMemFree(pAdpInfo);
        g_pfnclosesocket(sd);
        return RTErrConvertFromWin32(g_pfnWSAGetLastError());
    }
    g_pfnclosesocket(sd);
    int cIfacesSystem = cbReturned / sizeof(INTERFACE_INFO);

    /** @todo Use GetAdaptersInfo() and GetAdapterAddresses (IPv4 + IPv6) for more information. */
    for (int i = 0; i < cIfacesSystem; ++i)
    {
        sockaddr_in *pAddress;
        u_long nFlags = 0;
        if (aInterfaces[i].iiFlags & IFF_LOOPBACK) /* Skip loopback device. */
            continue;
        nFlags = aInterfaces[i].iiFlags;
        pAddress = (sockaddr_in *)&(aInterfaces[i].iiAddress);
        Assert(pAddress);
        char szIp[32];
        RTStrPrintf(szIp, sizeof(szIp), "%s", g_pfninet_ntoa(pAddress->sin_addr));
        RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/IP", cIfsReported);
        VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szIp);

        pAddress = (sockaddr_in *) & (aInterfaces[i].iiBroadcastAddress);
        RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Broadcast", cIfsReported);
        VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", g_pfninet_ntoa(pAddress->sin_addr));

        pAddress = (sockaddr_in *)&(aInterfaces[i].iiNetmask);
        RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Netmask", cIfsReported);
        VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", g_pfninet_ntoa(pAddress->sin_addr));

        RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/Status", cIfsReported);
        VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, nFlags & IFF_UP ? "Up" : "Down");

        if (pAdpInfo)
        {
            IP_ADAPTER_INFO *pAdp;
            for (pAdp = pAdpInfo; pAdp; pAdp = pAdp->Next)
                if (!strcmp(pAdp->IpAddressList.IpAddress.String, szIp))
                    break;

            RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/MAC", cIfsReported);
            if (pAdp)
            {
                char szMac[32];
                RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
                            pAdp->Address[0], pAdp->Address[1], pAdp->Address[2],
                            pAdp->Address[3], pAdp->Address[4], pAdp->Address[5]);
                VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
            }
            else
                VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, NULL);
        }

        cIfsReported++;
    }
    if (pAdpInfo)
        RTMemFree(pAdpInfo);

#elif defined(RT_OS_HAIKU)
    /** @todo Haiku: implement network info. retreival */
    return VERR_NOT_IMPLEMENTED;

#elif defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD)
    struct ifaddrs *pIfHead = NULL;

    /* Get all available interfaces */
    int rc = getifaddrs(&pIfHead);
    if (rc < 0)
    {
        rc = RTErrConvertFromErrno(errno);
        VGSvcError("VMInfo/Network: Failed to get all interfaces: Error %Rrc\n");
        return rc;
    }

    /* Loop through all interfaces and set the data. */
    for (struct ifaddrs *pIfCurr = pIfHead; pIfCurr; pIfCurr = pIfCurr->ifa_next)
    {
        /*
         * Only AF_INET and no loopback interfaces
         */
        /** @todo IPv6 interfaces */
        if (   pIfCurr->ifa_addr->sa_family == AF_INET
            && !(pIfCurr->ifa_flags & IFF_LOOPBACK))
        {
            char szInetAddr[NI_MAXHOST];

            memset(szInetAddr, 0, NI_MAXHOST);
            getnameinfo(pIfCurr->ifa_addr, sizeof(struct sockaddr_in),
                        szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/IP", cIfsReported);
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);

            memset(szInetAddr, 0, NI_MAXHOST);
            getnameinfo(pIfCurr->ifa_broadaddr, sizeof(struct sockaddr_in),
                        szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Broadcast", cIfsReported);
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);

            memset(szInetAddr, 0, NI_MAXHOST);
            getnameinfo(pIfCurr->ifa_netmask, sizeof(struct sockaddr_in),
                        szInetAddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/V4/Netmask", cIfsReported);
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szInetAddr);

            /* Search for the AF_LINK interface of the current AF_INET one and get the mac. */
            for (struct ifaddrs *pIfLinkCurr = pIfHead; pIfLinkCurr; pIfLinkCurr = pIfLinkCurr->ifa_next)
            {
                if (   pIfLinkCurr->ifa_addr->sa_family == AF_LINK
                    && !strcmp(pIfCurr->ifa_name, pIfLinkCurr->ifa_name))
                {
                    char szMac[32];
                    uint8_t *pu8Mac = NULL;
                    struct sockaddr_dl *pLinkAddress = (struct sockaddr_dl *)pIfLinkCurr->ifa_addr;

                    AssertPtr(pLinkAddress);
                    pu8Mac = (uint8_t *)LLADDR(pLinkAddress);
                    RTStrPrintf(szMac, sizeof(szMac), "%02X%02X%02X%02X%02X%02X",
                                pu8Mac[0], pu8Mac[1], pu8Mac[2], pu8Mac[3],  pu8Mac[4], pu8Mac[5]);
                    RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/MAC", cIfsReported);
                    VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", szMac);
                    break;
                }
            }

            RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32/Status", cIfsReported);
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, pIfCurr->ifa_flags & IFF_UP ? "Up" : "Down");

            cIfsReported++;
        }
    }

    /* Free allocated resources. */
    freeifaddrs(pIfHead);

#else /* !RT_OS_WINDOWS && !RT_OS_FREEBSD */
    /*
     * Use SIOCGIFCONF to get a list of interface/protocol configurations.
     *
     * See "UNIX Network Programming Volume 1" by W. R. Stevens, section 17.6
     * for details on this ioctl.
     */
    int sd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sd < 0)
    {
        int rc = RTErrConvertFromErrno(errno);
        VGSvcError("VMInfo/Network: Failed to get a socket: Error %Rrc\n", rc);
        return rc;
    }

    /* Call SIOCGIFCONF with the right sized buffer (remember the size). */
    static int      s_cbBuf = 256; // 1024
    int             cbBuf   = s_cbBuf;
    char           *pchBuf;
    struct ifconf   IfConf;
    int rc = VINF_SUCCESS;
    for (;;)
    {
        pchBuf = (char *)RTMemTmpAllocZ(cbBuf);
        if (!pchBuf)
        {
            rc = VERR_NO_TMP_MEMORY;
            break;
        }

        IfConf.ifc_len = cbBuf;
        IfConf.ifc_buf = pchBuf;
        if (ioctl(sd, SIOCGIFCONF, &IfConf) >= 0)
        {
            /* Hard to anticipate how space an address might possibly take, so
               making some generous assumptions here to avoid performing the
               query twice with different buffer sizes. */
            if (IfConf.ifc_len + 128 < cbBuf)
                break;
        }
        else if (errno != EOVERFLOW)
        {
            rc = RTErrConvertFromErrno(errno);
            break;
        }

        /* grow the buffer */
        s_cbBuf = cbBuf *= 2;
        RTMemFree(pchBuf);
    }
    if (RT_FAILURE(rc))
    {
        close(sd);
        RTMemTmpFree(pchBuf);
        VGSvcError("VMInfo/Network: Error doing SIOCGIFCONF (cbBuf=%d): %Rrc\n", cbBuf, rc);
        return rc;
    }

    /*
     * Iterate the interface/protocol configurations.
     *
     * Note! The current code naively assumes one IPv4 address per interface.
     *       This means that guest assigning more than one address to an
     *       interface will get multiple entries for one physical interface.
     */
# ifdef RT_OS_OS2
    struct ifreq   *pPrevLinkAddr = NULL;
# endif
    struct ifreq   *pCur   = IfConf.ifc_req;
    size_t          cbLeft = IfConf.ifc_len;
    while (cbLeft >= sizeof(*pCur))
    {
# if defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX)
        /* These two do not provide the sa_len member but only support address
         * families which do not need extra bytes on the end. */
#  define SA_LEN(pAddr) sizeof(struct sockaddr)
# elif !defined(SA_LEN)
#  define SA_LEN(pAddr) (pAddr)->sa_len
# endif
        /* Figure the size of the current request. */
        size_t cbCur = RT_UOFFSETOF(struct ifreq, ifr_addr)
                     + SA_LEN(&pCur->ifr_addr);
        cbCur = RT_MAX(cbCur, sizeof(struct ifreq));
# if defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX)
        Assert(pCur->ifr_addr.sa_family == AF_INET);
# endif
        AssertBreak(cbCur <= cbLeft);

# ifdef RT_OS_OS2
        /* On OS/2 we get the MAC address in the AF_LINK that the BSD 4.4 stack
           emits.  We boldly ASSUME these always comes first. */
        if (   pCur->ifr_addr.sa_family == AF_LINK
            && ((struct sockaddr_dl *)&pCur->ifr_addr)->sdl_alen == 6)
            pPrevLinkAddr = pCur;
# endif

        /* Skip it if it's not the kind of address we're looking for. */
        struct ifreq IfReqTmp;
        bool         fIfUp = false;
        bool         fSkip = false;
        if (pCur->ifr_addr.sa_family != AF_INET)
            fSkip = true;
        else
        {
            /* Get the interface flags so we can detect loopback and check if it's up. */
            IfReqTmp = *pCur;
            if (ioctl(sd, SIOCGIFFLAGS, &IfReqTmp) < 0)
            {
                rc = RTErrConvertFromErrno(errno);
                VGSvcError("VMInfo/Network: Failed to ioctl(SIOCGIFFLAGS,%s) on socket: Error %Rrc\n", pCur->ifr_name, rc);
                break;
            }
            fIfUp = !!(IfReqTmp.ifr_flags & IFF_UP);
            if (IfReqTmp.ifr_flags & IFF_LOOPBACK) /* Skip the loopback device. */
                fSkip = true;
        }
        if (!fSkip)
        {
            size_t offSubProp = RTStrPrintf(szPropPath, sizeof(szPropPath), "/VirtualBox/GuestInfo/Net/%RU32", cIfsReported);

            sockaddr_in *pAddress = (sockaddr_in *)&pCur->ifr_addr;
            strcpy(&szPropPath[offSubProp], "/V4/IP");
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));

            /* Get the broadcast address. */
            IfReqTmp = *pCur;
            if (ioctl(sd, SIOCGIFBRDADDR, &IfReqTmp) < 0)
            {
                rc = RTErrConvertFromErrno(errno);
                VGSvcError("VMInfo/Network: Failed to ioctl(SIOCGIFBRDADDR) on socket: Error %Rrc\n", rc);
                break;
            }
            pAddress = (sockaddr_in *)&IfReqTmp.ifr_broadaddr;
            strcpy(&szPropPath[offSubProp], "/V4/Broadcast");
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));

            /* Get the net mask. */
            IfReqTmp = *pCur;
            if (ioctl(sd, SIOCGIFNETMASK, &IfReqTmp) < 0)
            {
                rc = RTErrConvertFromErrno(errno);
                VGSvcError("VMInfo/Network: Failed to ioctl(SIOCGIFNETMASK) on socket: Error %Rrc\n", rc);
                break;
            }
# if defined(RT_OS_OS2) || defined(RT_OS_SOLARIS)
            pAddress = (sockaddr_in *)&IfReqTmp.ifr_addr;
# else
            pAddress = (sockaddr_in *)&IfReqTmp.ifr_netmask;
# endif
            strcpy(&szPropPath[offSubProp], "/V4/Netmask");
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%s", inet_ntoa(pAddress->sin_addr));

# if defined(RT_OS_SOLARIS)
            /*
             * "ifreq" is obsolete on Solaris. We use the recommended "lifreq".
             * We might fail if the interface has not been assigned an IP address.
             * That doesn't matter; as long as it's plumbed we can pick it up.
             * But, if it has not acquired an IP address we cannot obtain it's MAC
             * address this way, so we just use all zeros there.
             */
            RTMAC           IfMac;
            struct lifreq   IfReq;
            RT_ZERO(IfReq);
            AssertCompile(sizeof(IfReq.lifr_name) >= sizeof(pCur->ifr_name));
            strncpy(IfReq.lifr_name, pCur->ifr_name, sizeof(pCur->ifr_name));
            if (ioctl(sd, SIOCGLIFADDR, &IfReq) >= 0)
            {
                struct arpreq ArpReq;
                RT_ZERO(ArpReq);
                memcpy(&ArpReq.arp_pa, &IfReq.lifr_addr, sizeof(struct sockaddr_in));

                if (ioctl(sd, SIOCGARP, &ArpReq) >= 0)
                    memcpy(&IfMac, ArpReq.arp_ha.sa_data, sizeof(IfMac));
                else
                {
                    rc = RTErrConvertFromErrno(errno);
                    VGSvcError("VMInfo/Network: failed to ioctl(SIOCGARP) on socket: Error %Rrc\n", rc);
                    break;
                }
            }
            else
            {
                VGSvcVerbose(2, "VMInfo/Network: Interface '%s' has no assigned IP address, skipping ...\n", pCur->ifr_name);
                continue;
            }
# elif defined(RT_OS_OS2)
            RTMAC   IfMac;
            if (   pPrevLinkAddr
                && strncmp(pCur->ifr_name, pPrevLinkAddr->ifr_name, sizeof(pCur->ifr_name)) == 0)
            {
                struct sockaddr_dl *pDlAddr = (struct sockaddr_dl *)&pPrevLinkAddr->ifr_addr;
                IfMac = *(PRTMAC)&pDlAddr->sdl_data[pDlAddr->sdl_nlen];
            }
            else
                RT_ZERO(IfMac);
#else
            if (ioctl(sd, SIOCGIFHWADDR, &IfReqTmp) < 0)
            {
                rc = RTErrConvertFromErrno(errno);
                VGSvcError("VMInfo/Network: Failed to ioctl(SIOCGIFHWADDR) on socket: Error %Rrc\n", rc);
                break;
            }
            RTMAC IfMac = *(PRTMAC)&IfReqTmp.ifr_hwaddr.sa_data[0];
# endif
            strcpy(&szPropPath[offSubProp], "/MAC");
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%02X%02X%02X%02X%02X%02X",
                                       IfMac.au8[0], IfMac.au8[1], IfMac.au8[2], IfMac.au8[3], IfMac.au8[4], IfMac.au8[5]);

            strcpy(&szPropPath[offSubProp], "/Status");
            VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, fIfUp ? "Up" : "Down");

            /* The name. */
            int rc2 = RTStrValidateEncodingEx(pCur->ifr_name, sizeof(pCur->ifr_name), 0);
            if (RT_SUCCESS(rc2))
            {
                strcpy(&szPropPath[offSubProp], "/Name");
                VGSvcPropCacheUpdate(&g_VMInfoPropCache, szPropPath, "%.*s", sizeof(pCur->ifr_name), pCur->ifr_name);
            }

            cIfsReported++;
        }

        /*
         * Next interface/protocol configuration.
         */
        pCur = (struct ifreq *)((uintptr_t)pCur + cbCur);
        cbLeft -= cbCur;
    }

    RTMemTmpFree(pchBuf);
    close(sd);
    if (RT_FAILURE(rc))
        VGSvcError("VMInfo/Network: Network enumeration for interface %RU32 failed with error %Rrc\n", cIfsReported, rc);

#endif /* !RT_OS_WINDOWS */

#if 0 /* Zapping not enabled yet, needs more testing first. */
    /*
     * Zap all stale network interface data if the former (saved) network ifaces count
     * is bigger than the current one.
     */

    /* Get former count. */
    uint32_t cIfsReportedOld;
    rc = VGSvcReadPropUInt32(g_uVMInfoGuestPropSvcClientID, g_pszPropCacheValNetCount, &cIfsReportedOld,
                             0 /* Min */, UINT32_MAX /* Max */);
    if (   RT_SUCCESS(rc)
        && cIfsReportedOld > cIfsReported) /* Are some ifaces not around anymore? */
    {
        VGSvcVerbose(3, "VMInfo/Network: Stale interface data detected (%RU32 old vs. %RU32 current)\n",
                     cIfsReportedOld, cIfsReported);

        uint32_t uIfaceDeleteIdx = cIfsReported;
        do
        {
            VGSvcVerbose(3, "VMInfo/Network: Deleting stale data of interface %d ...\n", uIfaceDeleteIdx);
            rc = VGSvcPropCacheUpdateByPath(&g_VMInfoPropCache, NULL /* Value, delete */, 0 /* Flags */, "/VirtualBox/GuestInfo/Net/%RU32", uIfaceDeleteIdx++);
        } while (RT_SUCCESS(rc));
    }
    else if (   RT_FAILURE(rc)
             && rc != VERR_NOT_FOUND)
    {
        VGSvcError("VMInfo/Network: Failed retrieving old network interfaces count with error %Rrc\n", rc);
    }
#endif

    /*
     * This property is a beacon which is _always_ written, even if the network configuration
     * does not change. If this property is missing, the host assumes that all other GuestInfo
     * properties are no longer valid.
     */
    VGSvcPropCacheUpdate(&g_VMInfoPropCache, g_pszPropCacheValNetCount, "%RU32", cIfsReported);

    /* Don't fail here; just report everything we got. */
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{VBOXSERVICE,pfnWorker}
 */
static DECLCALLBACK(int) vbsvcVMInfoWorker(bool volatile *pfShutdown)
{
    int rc;

    /*
     * Tell the control thread that it can continue
     * spawning services.
     */
    RTThreadUserSignal(RTThreadSelf());

#ifdef RT_OS_WINDOWS
    /* Required for network information (must be called per thread). */
    if (g_pfnWSAStartup)
    {
        WSADATA wsaData;
        RT_ZERO(wsaData);
        if (g_pfnWSAStartup(MAKEWORD(2, 2), &wsaData))
            VGSvcError("VMInfo/Network: WSAStartup failed! Error: %Rrc\n", RTErrConvertFromWin32(g_pfnWSAGetLastError()));
    }
#endif

    /*
     * Write the fixed properties first.
     */
    vgsvcVMInfoWriteFixedProperties();

    /*
     * Now enter the loop retrieving runtime data continuously.
     */
    for (;;)
    {
        rc = vgsvcVMInfoWriteUsers();
        if (RT_FAILURE(rc))
            break;

        rc = vgsvcVMInfoWriteNetwork();
        if (RT_FAILURE(rc))
            break;

        /* Whether to wait for event semaphore or not. */
        bool fWait = true;

        /* Check for location awareness. This most likely only
         * works with VBox (latest) 4.1 and up. */

        /* Check for new connection. */
        char *pszLAClientID = NULL;
        int rc2 = VGSvcReadHostProp(g_uVMInfoGuestPropSvcClientID, g_pszLAActiveClient, true /* Read only */,
                                          &pszLAClientID, NULL /* Flags */, NULL /* Timestamp */);
        if (RT_SUCCESS(rc2))
        {
            AssertPtr(pszLAClientID);
            if (RTStrICmp(pszLAClientID, "0")) /* Is a client connected? */
            {
                uint32_t uLAClientID = RTStrToInt32(pszLAClientID);
                uint64_t uLAClientAttachedTS;

                /* Peek at "Attach" value to figure out if hotdesking happened. */
                char *pszAttach = NULL;
                rc2 = vgsvcGetLAClientValue(uLAClientID, "Attach", &pszAttach,
                                                 &uLAClientAttachedTS);

                if (   RT_SUCCESS(rc2)
                    && (   !g_LAClientAttachedTS
                        || (g_LAClientAttachedTS != uLAClientAttachedTS)))
                {
                    vgsvcFreeLAClientInfo(&g_LAClientInfo);

                    /* Note: There is a race between setting the guest properties by the host and getting them by
                     *       the guest. */
                    rc2 = vgsvcGetLAClientInfo(uLAClientID, &g_LAClientInfo);
                    if (RT_SUCCESS(rc2))
                    {
                        VGSvcVerbose(1, "VRDP: Hotdesk client %s with ID=%RU32, Name=%s, Domain=%s\n",
                                     /* If g_LAClientAttachedTS is 0 this means there already was an active
                                      * hotdesk session when VBoxService started. */
                                     !g_LAClientAttachedTS ? "already active" : g_LAClientInfo.fAttached ? "connected" : "disconnected",
                                     uLAClientID, g_LAClientInfo.pszName, g_LAClientInfo.pszDomain);

                        g_LAClientAttachedTS = g_LAClientInfo.uAttachedTS;

                        /* Don't wait for event semaphore below anymore because we now know that the client
                         * changed. This means we need to iterate all VM information again immediately. */
                        fWait = false;
                    }
                    else
                    {
                        static int s_iBitchedAboutLAClientInfo = 0;
                        if (s_iBitchedAboutLAClientInfo < 10)
                        {
                            s_iBitchedAboutLAClientInfo++;
                            VGSvcError("Error getting active location awareness client info, rc=%Rrc\n", rc2);
                        }
                    }
                }
                else if (RT_FAILURE(rc2))
                     VGSvcError("Error getting attached value of location awareness client %RU32, rc=%Rrc\n", uLAClientID, rc2);
                if (pszAttach)
                    RTStrFree(pszAttach);
            }
            else
            {
                VGSvcVerbose(1, "VRDP: UTTSC disconnected from VRDP server\n");
                vgsvcFreeLAClientInfo(&g_LAClientInfo);
            }

            RTStrFree(pszLAClientID);
        }
        else
        {
            static int s_iBitchedAboutLAClient = 0;
            if (   (rc2 != VERR_NOT_FOUND) /* No location awareness installed, skip. */
                && s_iBitchedAboutLAClient < 3)
            {
                s_iBitchedAboutLAClient++;
                VGSvcError("VRDP: Querying connected location awareness client failed with rc=%Rrc\n", rc2);
            }
        }

        VGSvcVerbose(3, "VRDP: Handling location awareness done\n");

        /*
         * Flush all properties if we were restored.
         */
        uint64_t idNewSession = g_idVMInfoSession;
        VbglR3GetSessionId(&idNewSession);
        if (idNewSession != g_idVMInfoSession)
        {
            VGSvcVerbose(3, "The VM session ID changed, flushing all properties\n");
            vgsvcVMInfoWriteFixedProperties();
            VGSvcPropCacheFlush(&g_VMInfoPropCache);
            g_idVMInfoSession = idNewSession;
        }

        /*
         * Block for a while.
         *
         * The event semaphore takes care of ignoring interruptions and it
         * allows us to implement service wakeup later.
         */
        if (*pfShutdown)
            break;
        if (fWait)
            rc2 = RTSemEventMultiWait(g_hVMInfoEvent, g_cMsVMInfoInterval);
        if (*pfShutdown)
            break;
        if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
        {
            VGSvcError("RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
            rc = rc2;
            break;
        }
        else if (RT_LIKELY(RT_SUCCESS(rc2)))
        {
            /* Reset event semaphore if it got triggered. */
            rc2 = RTSemEventMultiReset(g_hVMInfoEvent);
            if (RT_FAILURE(rc2))
                rc2 = VGSvcError("RTSemEventMultiReset failed; rc2=%Rrc\n", rc2);
        }
    }

#ifdef RT_OS_WINDOWS
    if (g_pfnWSACleanup)
        g_pfnWSACleanup();
#endif

    return rc;
}


/**
 * @interface_method_impl{VBOXSERVICE,pfnStop}
 */
static DECLCALLBACK(void) vbsvcVMInfoStop(void)
{
    RTSemEventMultiSignal(g_hVMInfoEvent);
}


/**
 * @interface_method_impl{VBOXSERVICE,pfnTerm}
 */
static DECLCALLBACK(void) vbsvcVMInfoTerm(void)
{
    if (g_hVMInfoEvent != NIL_RTSEMEVENTMULTI)
    {
        /** @todo temporary solution: Zap all values which are not valid
         *        anymore when VM goes down (reboot/shutdown ). Needs to
         *        be replaced with "temporary properties" later.
         *
         *        One idea is to introduce a (HGCM-)session guest property
         *        flag meaning that a guest property is only valid as long
         *        as the HGCM session isn't closed (e.g. guest application
         *        terminates). [don't remove till implemented]
         */
        /** @todo r=bird: Drop the VbglR3GuestPropDelSet call here and use the cache
         *        since it remembers what we've written. */
        /* Delete the "../Net" branch. */
        const char *apszPat[1] = { "/VirtualBox/GuestInfo/Net/*" };
        int rc = VbglR3GuestPropDelSet(g_uVMInfoGuestPropSvcClientID, &apszPat[0], RT_ELEMENTS(apszPat));

        /* Destroy LA client info. */
        vgsvcFreeLAClientInfo(&g_LAClientInfo);

        /* Destroy property cache. */
        VGSvcPropCacheDestroy(&g_VMInfoPropCache);

        /* Disconnect from guest properties service. */
        rc = VbglR3GuestPropDisconnect(g_uVMInfoGuestPropSvcClientID);
        if (RT_FAILURE(rc))
            VGSvcError("Failed to disconnect from guest property service! Error: %Rrc\n", rc);
        g_uVMInfoGuestPropSvcClientID = 0;

        RTSemEventMultiDestroy(g_hVMInfoEvent);
        g_hVMInfoEvent = NIL_RTSEMEVENTMULTI;
    }
}


/**
 * The 'vminfo' service description.
 */
VBOXSERVICE g_VMInfo =
{
    /* pszName. */
    "vminfo",
    /* pszDescription. */
    "Virtual Machine Information",
    /* pszUsage. */
    "              [--vminfo-interval <ms>] [--vminfo-user-idle-threshold <ms>]"
    ,
    /* pszOptions. */
    "    --vminfo-interval       Specifies the interval at which to retrieve the\n"
    "                            VM information. The default is 10000 ms.\n"
    "    --vminfo-user-idle-threshold <ms>\n"
    "                            Specifies the user idle threshold (in ms) for\n"
    "                            considering a guest user as being idle. The default\n"
    "                            is 5000 (5 seconds).\n"
    ,
    /* methods */
    vbsvcVMInfoPreInit,
    vbsvcVMInfoOption,
    vbsvcVMInfoInit,
    vbsvcVMInfoWorker,
    vbsvcVMInfoStop,
    vbsvcVMInfoTerm
};