File: sysinfo.c

package info (click to toggle)
cfengine3 3.24.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,552 kB
  • sloc: ansic: 163,161; sh: 10,296; python: 2,950; makefile: 1,744; lex: 784; yacc: 633; perl: 211; pascal: 157; xml: 21; sed: 13
file content (3640 lines) | stat: -rw-r--r-- 124,706 bytes parent folder | download | duplicates (2)
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
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
/*
  Copyright 2024 Northern.tech AS

  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the
  Free Software Foundation; version 3.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

  To the extent this program is licensed as part of the Enterprise
  versions of CFEngine, the applicable Commercial Open Source License
  (COSL) may apply to this file if you as a licensee so wish it. See
  included file COSL.txt.
*/

#include <platform.h>

#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
#include <sysinfo.h>
#include <sysinfo_priv.h>
#include <cf3.extern.h>
#include <eval_context.h>
#include <files_names.h>
#include <files_interfaces.h>
#include <hash.h>
#include <scope.h>
#include <item_lib.h>
#include <matching.h>
#include <systype.h>
#include <unix.h>
#include <string_lib.h>
#include <regex.h>                                       /* StringMatchFull */
#include <misc_lib.h>
#include <file_lib.h>
#include <rlist.h>
#include <audit.h>
#include <pipes.h>
#include <known_dirs.h>
#include <files_lib.h>
#include <printsize.h>
#include <cf-windows-functions.h>
#include <ornaments.h>
#include <feature.h>
#include <evalfunction.h>
#include <json-utils.h>
#include <unix.h>               /* GetCurrentUserName() */

#ifdef HAVE_ZONE_H
# include <zone.h>
#endif

// HP-UX mpctl() for $(sys.cpus) on HP-UX - Mantis #1069
#ifdef HAVE_SYS_MPCTL_H
# include <sys/mpctl.h>
#endif

/* Linux.
   WARNING keep this before the #include <sys/sysctl.h> because of glibc bug:
   https://sourceware.org/bugzilla/show_bug.cgi?id=140 */
#ifdef HAVE_STRUCT_SYSINFO_UPTIME
# include <sys/sysinfo.h>
#endif

/* BSD, MAC OS X uptime calculation use KERN_BOOTTIME sysctl. */
#ifdef HAVE_SYS_SYSCTL_H
# ifdef HAVE_SYS_PARAM_H
#  include <sys/param.h>
# endif
# ifdef __linux__
#  include <linux/sysctl.h>
# else
# include <sys/sysctl.h>
# endif
#endif


/*****************************************************/
// Uptime calculation settings for GetUptimeSeconds() - Mantis #1134

/* Listed here in priority order, i.e. first come the platform-specific
 * ways. If nothing works, one of the last, most generic ways should. */

#ifndef __MINGW32__                 /* Windows is implemented in Enterprise */

// HP-UX: pstat_getproc(2) on init (pid 1)
#if defined(__hpux)
# include <sys/param.h>
# include <sys/pstat.h>
# define BOOT_TIME_WITH_PSTAT_GETPROC

// Solaris: kstat() for kernel statistics
// See http://dsc.sun.com/solaris/articles/kstatc.html
// BSD also has a kstat.h (albeit in sys), so check __sun just to be paranoid

/**
 * @WARNING: Commented out because inside a Solaris 10 zone this gives the
 *           uptime of the host machine (the hypervisor). We thus choose to
 *           use UTMP for Solaris.
 */
/*
#elif defined(__sun) && defined(HAVE_KSTAT_H)
# include <kstat.h>
# define BOOT_TIME_WITH_KSTAT
*/

// BSD: sysctl(3) to get kern.boottime, CPU count, etc.
// See http://www.unix.com/man-page/FreeBSD/3/sysctl/
// Linux also has sys/sysctl.h, so we check KERN_BOOTTIME to make sure it's BSD
#elif defined(HAVE_SYS_SYSCTL_H) && defined(KERN_BOOTTIME)
# define BOOT_TIME_WITH_SYSCTL

// GNU/Linux: struct sysinfo.uptime
#elif defined(HAVE_STRUCT_SYSINFO_UPTIME)
# define BOOT_TIME_WITH_SYSINFO

/* Generic System V way, available in most platforms. */
#elif defined(HAVE_UTMP_H)
# include <utmp.h>
# define BOOT_TIME_WITH_UTMP

/* POSIX alternative (utmp.h does not exist on BSDs). */
#elif defined(HAVE_UTMPX_H)
# include <utmpx.h>
# define BOOT_TIME_WITH_UTMPX

#else
// Most generic way: {stat("/proc/1")}.st_ctime
// TODO in Solaris zones init is not guaranteed to be PID 1!
#define BOOT_TIME_WITH_PROCFS

#endif

/* Fallback uptime calculation: Parse the "uptime" command in case the
 * platform-specific way fails or returns absurd number. */
static time_t GetBootTimeFromUptimeCommand(time_t now);

#endif  /* ifndef __MINGW32__ */

#define LSB_RELEASE_FILENAME "/etc/lsb-release"
#define DEBIAN_VERSION_FILENAME "/etc/debian_version"
#define DEBIAN_ISSUE_FILENAME "/etc/issue"


/*****************************************************/

static char *FindNextInteger(char *str, char **num);

void CalculateDomainName(const char *nodename, const char *dnsname,
                         char *fqname, size_t fqname_size,
                         char *uqname, size_t uqname_size,
                         char *domain, size_t domain_size);

#ifdef __linux__
static int Linux_Fedora_Version(EvalContext *ctx);
static int Linux_Redhat_Version(EvalContext *ctx);
static void Linux_Amazon_Version(EvalContext *ctx);
static void Linux_Alpine_Version(EvalContext *ctx);
static void Linux_Oracle_VM_Server_Version(EvalContext *ctx);
static void Linux_Oracle_Version(EvalContext *ctx);
static int Linux_Suse_Version(EvalContext *ctx);
static int Linux_Slackware_Version(EvalContext *ctx, char *filename);
static int Linux_Debian_Version(EvalContext *ctx);
static int Linux_Misc_Version(EvalContext *ctx);
static int Linux_Mandrake_Version(EvalContext *ctx);
static int Linux_Mandriva_Version(EvalContext *ctx);
static int Linux_Mandriva_Version_Real(EvalContext *ctx, char *filename, char *relstring, char *vendor);
static int VM_Version(EvalContext *ctx);
static int Xen_Domain(EvalContext *ctx);
static int EOS_Version(EvalContext *ctx);
static int MiscOS(EvalContext *ctx);
static void OpenVZ_Detect(EvalContext *ctx);

static bool ReadLine(const char *filename, char *buf, int bufsize);
static FILE *ReadFirstLine(const char *filename, char *buf, int bufsize);
#endif

#ifdef XEN_CPUID_SUPPORT
static void Xen_Cpuid(uint32_t idx, uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx);
static bool Xen_Hv_Check(void);
#endif

static void GetCPUInfo(EvalContext *ctx);

static const char *const CLASSATTRIBUTES[][3] =
{
    [PLATFORM_CONTEXT_UNKNOWN] = {"-", "-", "-"},       /* as appear here are matched. The fields are sysname and machine */
    [PLATFORM_CONTEXT_OPENVZ] = {"virt_host_vz_vzps", ".*", ".*"}, /* VZ with vzps */
    [PLATFORM_CONTEXT_HP] = {"hp-ux", ".*", ".*"},      /* hpux */
    [PLATFORM_CONTEXT_AIX] = {"aix", ".*", ".*"},       /* aix */
    [PLATFORM_CONTEXT_LINUX] = {"linux", ".*", ".*"},   /* linux */
    [PLATFORM_CONTEXT_BUSYBOX] = {"busybox", ".*", ".*"}, /* linux w/ busybox - warning uname returns linux */
    [PLATFORM_CONTEXT_SOLARIS] = {"sunos", ".*",
                                  "5\\.1[1-9].*"},      /* new solaris, SunOS >= 5.11 */
    [PLATFORM_CONTEXT_SUN_SOLARIS] = {"sunos", ".*",
                                      "5\\.([2-9]|10)(\\..*)?"}, /* old solaris, SunOS < 5.11 */
    [PLATFORM_CONTEXT_FREEBSD] = {"freebsd", ".*", ".*"}, /* freebsd */
    [PLATFORM_CONTEXT_NETBSD] = {"netbsd", ".*", ".*"},   /* NetBSD */
    [PLATFORM_CONTEXT_CRAYOS] = {"sn.*", "cray*", ".*"},  /* cray */
    [PLATFORM_CONTEXT_WINDOWS_NT] = {"cygwin_nt.*", ".*", ".*"}, /* NT (cygwin) */
    [PLATFORM_CONTEXT_SYSTEMV] = {"unix_sv", ".*", ".*"}, /* Unixware */
    [PLATFORM_CONTEXT_OPENBSD] = {"openbsd", ".*", ".*"}, /* OpenBSD */
    [PLATFORM_CONTEXT_CFSCO] = {"sco_sv", ".*", ".*"},    /* SCO */
    [PLATFORM_CONTEXT_DARWIN] = {"darwin", ".*", ".*"},   /* Darwin, aka MacOS X */
    [PLATFORM_CONTEXT_QNX] = {"qnx", ".*", ".*"},         /* qnx  */
    [PLATFORM_CONTEXT_DRAGONFLY] = {"dragonfly", ".*", ".*"}, /* dragonfly */
    [PLATFORM_CONTEXT_MINGW] = {"windows_nt.*", ".*", ".*"},  /* NT (native) */
    [PLATFORM_CONTEXT_VMWARE] = {"vmkernel", ".*", ".*"}, /* VMWARE / ESX */
    [PLATFORM_CONTEXT_ANDROID] = {"android", ".*", ".*"}, /* android: Warning uname returns linux */
};

static const char *const VRESOLVCONF[] =
{
    [PLATFORM_CONTEXT_UNKNOWN] = "-",
    [PLATFORM_CONTEXT_OPENVZ] = "/etc/resolv.conf",      /* virt_host_vz_vzps */
    [PLATFORM_CONTEXT_HP] = "/etc/resolv.conf",          /* hpux */
    [PLATFORM_CONTEXT_AIX] = "/etc/resolv.conf",         /* aix */
    [PLATFORM_CONTEXT_LINUX] = "/etc/resolv.conf",       /* linux */
    [PLATFORM_CONTEXT_BUSYBOX] = "/etc/resolv.conf",     /* linux */
    [PLATFORM_CONTEXT_SOLARIS] = "/etc/resolv.conf",     /* new solaris */
    [PLATFORM_CONTEXT_SUN_SOLARIS] = "/etc/resolv.conf", /* old solaris */
    [PLATFORM_CONTEXT_FREEBSD] = "/etc/resolv.conf",     /* freebsd */
    [PLATFORM_CONTEXT_NETBSD] = "/etc/resolv.conf",      /* netbsd */
    [PLATFORM_CONTEXT_CRAYOS] = "/etc/resolv.conf",      /* cray */
    [PLATFORM_CONTEXT_WINDOWS_NT] = "/etc/resolv.conf",  /* NT */
    [PLATFORM_CONTEXT_SYSTEMV] = "/etc/resolv.conf",     /* Unixware */
    [PLATFORM_CONTEXT_OPENBSD] = "/etc/resolv.conf",     /* openbsd */
    [PLATFORM_CONTEXT_CFSCO] = "/etc/resolv.conf",       /* sco */
    [PLATFORM_CONTEXT_DARWIN] = "/etc/resolv.conf",      /* darwin */
    [PLATFORM_CONTEXT_QNX] = "/etc/resolv.conf",         /* qnx */
    [PLATFORM_CONTEXT_DRAGONFLY] = "/etc/resolv.conf",   /* dragonfly */
    [PLATFORM_CONTEXT_MINGW] = "",                       /* mingw */
    [PLATFORM_CONTEXT_VMWARE] = "/etc/resolv.conf",      /* vmware */
    [PLATFORM_CONTEXT_ANDROID] = "",                     /* android */
};

static const char *const VMAILDIR[] =
{
    [PLATFORM_CONTEXT_UNKNOWN] = "-",
    [PLATFORM_CONTEXT_OPENVZ] = "/var/spool/mail", /* virt_host_vz_vzps */
    [PLATFORM_CONTEXT_HP] = "/var/mail",           /* hpux */
    [PLATFORM_CONTEXT_AIX] = "/var/spool/mail",    /* aix */
    [PLATFORM_CONTEXT_LINUX] = "/var/spool/mail",  /* linux */
    [PLATFORM_CONTEXT_BUSYBOX] = "",               /* linux */
    [PLATFORM_CONTEXT_SOLARIS] = "/var/mail",      /* new solaris */
    [PLATFORM_CONTEXT_SUN_SOLARIS] = "/var/mail",  /* old solaris */
    [PLATFORM_CONTEXT_FREEBSD] = "/var/mail",      /* freebsd */
    [PLATFORM_CONTEXT_NETBSD] = "/var/mail",       /* netbsd */
    [PLATFORM_CONTEXT_CRAYOS] = "/usr/mail",       /* cray */
    [PLATFORM_CONTEXT_WINDOWS_NT] = "N/A",         /* NT */
    [PLATFORM_CONTEXT_SYSTEMV] = "/var/mail",      /* Unixware */
    [PLATFORM_CONTEXT_OPENBSD] = "/var/mail",      /* openbsd */
    [PLATFORM_CONTEXT_CFSCO] = "/var/spool/mail",  /* sco */
    [PLATFORM_CONTEXT_DARWIN] = "/var/mail",       /* darwin */
    [PLATFORM_CONTEXT_QNX] = "/var/spool/mail",    /* qnx */
    [PLATFORM_CONTEXT_DRAGONFLY] = "/var/mail",    /* dragonfly */
    [PLATFORM_CONTEXT_MINGW] = "",                 /* mingw */
    [PLATFORM_CONTEXT_VMWARE] = "/var/spool/mail", /* vmware */
    [PLATFORM_CONTEXT_ANDROID] = "",               /* android */
};

static const char *const VEXPORTS[] =
{
    [PLATFORM_CONTEXT_UNKNOWN] = "-",
    [PLATFORM_CONTEXT_OPENVZ] = "/etc/exports",         /* virt_host_vz_vzps */
    [PLATFORM_CONTEXT_HP] = "/etc/exports",             /* hpux */
    [PLATFORM_CONTEXT_AIX] = "/etc/exports",            /* aix */
    [PLATFORM_CONTEXT_LINUX] = "/etc/exports",          /* linux */
    [PLATFORM_CONTEXT_BUSYBOX] = "",                    /* linux */
    [PLATFORM_CONTEXT_SOLARIS] = "/etc/dfs/dfstab",     /* new solaris */
    [PLATFORM_CONTEXT_SUN_SOLARIS] = "/etc/dfs/dfstab", /* old solaris */
    [PLATFORM_CONTEXT_FREEBSD] = "/etc/exports",        /* freebsd */
    [PLATFORM_CONTEXT_NETBSD] = "/etc/exports",         /* netbsd */
    [PLATFORM_CONTEXT_CRAYOS] = "/etc/exports",         /* cray */
    [PLATFORM_CONTEXT_WINDOWS_NT] = "/etc/exports",     /* NT */
    [PLATFORM_CONTEXT_SYSTEMV] = "/etc/dfs/dfstab",     /* Unixware */
    [PLATFORM_CONTEXT_OPENBSD] = "/etc/exports",        /* openbsd */
    [PLATFORM_CONTEXT_CFSCO] = "/etc/dfs/dfstab",       /* sco */
    [PLATFORM_CONTEXT_DARWIN] = "/etc/exports",         /* darwin */
    [PLATFORM_CONTEXT_QNX] = "/etc/exports",            /* qnx */
    [PLATFORM_CONTEXT_DRAGONFLY] = "/etc/exports",      /* dragonfly */
    [PLATFORM_CONTEXT_MINGW] = "",                      /* mingw */
    [PLATFORM_CONTEXT_VMWARE] = "none",                 /* vmware */
    [PLATFORM_CONTEXT_ANDROID] = ""  ,                  /* android */
};


/*******************************************************************/

void CalculateDomainName(const char *nodename, const char *dnsname,
                         char *fqname, size_t fqname_size,
                         char *uqname, size_t uqname_size,
                         char *domain, size_t domain_size)
{
    if (strstr(dnsname, "."))
    {
        strlcpy(fqname, dnsname, fqname_size);
    }
    else
    {
        strlcpy(fqname, nodename, fqname_size);
    }

    if ((strncmp(nodename, fqname, strlen(nodename)) == 0) && (fqname[strlen(nodename)] == '.'))
    {
        /* If hostname is not qualified */
        strlcpy(domain, fqname + strlen(nodename) + 1, domain_size);
        strlcpy(uqname, nodename, uqname_size);
    }
    else
    {
        /* If hostname is qualified */

        char *p = strchr(nodename, '.');

        if (p != NULL)
        {
            strlcpy(uqname, nodename, MIN(uqname_size, p - nodename + 1));
            strlcpy(domain, p + 1, domain_size);
        }
        else
        {
            strlcpy(uqname, nodename, uqname_size);
            strlcpy(domain, "", domain_size);
        }
    }
}

/*******************************************************************/

void DetectDomainName(EvalContext *ctx, const char *orig_nodename)
{
    char nodename[CF_BUFSIZE];

    strlcpy(nodename, orig_nodename, sizeof(nodename));
    ToLowerStrInplace(nodename);

    char dnsname[CF_BUFSIZE] = "";
    char fqn[CF_BUFSIZE];

    if (gethostname(fqn, sizeof(fqn)) != -1)
    {
        struct hostent *hp;

        if ((hp = gethostbyname(fqn)))
        {
            strlcpy(dnsname, hp->h_name, sizeof(dnsname));
            ToLowerStrInplace(dnsname);
        }
    }

    nt_static_assert(sizeof(VFQNAME) > 255);
    nt_static_assert(sizeof(VUQNAME) > 255);
    nt_static_assert(sizeof(VDOMAIN) > 255);
    CalculateDomainName(nodename, dnsname, VFQNAME, sizeof(VFQNAME),
                        VUQNAME, sizeof(VUQNAME), VDOMAIN, sizeof(VDOMAIN));

    // Note: We don't expect hostnames or domain names above 255
    // Not supported by DNS:
    // https://tools.ietf.org/html/rfc2181#section-11
    // So let's print some warnings:
    if (strlen(VUQNAME) > 255)
    {
        Log(LOG_LEVEL_WARNING,
            "Long host name '%s' (%zu bytes) will may cause issues",
            VUQNAME,
            strlen(VUQNAME));
    }
    if (strlen(VDOMAIN) > 255)
    {
        Log(LOG_LEVEL_WARNING,
            "Long domain name '%s' (%zu bytes) will may cause issues",
            VDOMAIN,
            strlen(VDOMAIN));
    }

/*
 * VFQNAME = a.b.c.d ->
 * NewClass("a.b.c.d")
 * NewClass("b.c.d")
 * NewClass("c.d")
 * NewClass("d")
 */
    char *ptr = VFQNAME;

    do
    {
        EvalContextClassPutHard(ctx, ptr, "inventory,attribute_name=none,source=agent,derived-from=sys.fqhost");

        ptr = strchr(ptr, '.');
        if (ptr != NULL)
        {
            ptr++;
        }
    } while (ptr != NULL);

    EvalContextClassPutHard(ctx, VUQNAME, "source=agent,derived-from=sys.uqhost");
    EvalContextClassPutHard(ctx, VDOMAIN, "source=agent,derived-from=sys.domain");

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "host", nodename, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=none");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "uqhost", VUQNAME, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=none");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "fqhost", VFQNAME, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=Host name");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "domain", VDOMAIN, CF_DATA_TYPE_STRING, "source=agent");
}

/*******************************************************************/

void DiscoverVersion(EvalContext *ctx)
{
    int major = 0;
    int minor = 0;
    int patch = 0;
    char workbuf[CF_BUFSIZE];
    if (sscanf(Version(), "%d.%d.%d", &major, &minor, &patch) == 3)
    {
        snprintf(workbuf, CF_MAXVARSIZE, "%d", major);
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version_major", workbuf, CF_DATA_TYPE_STRING, "source=agent");
        snprintf(workbuf, CF_MAXVARSIZE, "%d", minor);
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version_minor", workbuf, CF_DATA_TYPE_STRING, "source=agent");
        snprintf(workbuf, CF_MAXVARSIZE, "%d", patch);
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version_patch", workbuf, CF_DATA_TYPE_STRING, "source=agent");
    }
    else
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version_major", "BAD VERSION " VERSION, CF_DATA_TYPE_STRING, "source=agent");
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version_minor", "BAD VERSION " VERSION, CF_DATA_TYPE_STRING, "source=agent");
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version_patch", "BAD VERSION " VERSION, CF_DATA_TYPE_STRING, "source=agent");
    }

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version_release", RELEASE, CF_DATA_TYPE_STRING, "source=agent");

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "local_libdir", "lib", CF_DATA_TYPE_STRING, "source=agent");

    snprintf(workbuf, CF_BUFSIZE, "%s%cinputs%clib", GetWorkDir(), FILE_SEPARATOR, FILE_SEPARATOR);
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "libdir", workbuf, CF_DATA_TYPE_STRING, "source=agent");
}

static void GetNameInfo3(EvalContext *ctx)
{
    int i;
    char *sp, workbuf[CF_BUFSIZE];
    time_t tloc;
    struct hostent *hp;
    struct sockaddr_in cin;
    unsigned char digest[EVP_MAX_MD_SIZE + 1];
    const char* const workdir = GetWorkDir();
    const char* const bindir = GetBinDir();

#ifdef _AIX
    char real_version[_SYS_NMLN];
#endif
#if defined(HAVE_SYSINFO) && (defined(SI_ARCHITECTURE) || defined(SI_PLATFORM))
    long sz;
#endif

#define COMPONENTS_SIZE 17
    // This is used for $(sys.cf_agent), $(sys.cf_serverd) ... :
    char *components[COMPONENTS_SIZE] = { "cf-twin", "cf-agent", "cf-serverd", "cf-monitord", "cf-know",
        "cf-report", "cf-key", "cf-runagent", "cf-execd", "cf-hub", "cf-reactor",
        "cf-promises", "cf-upgrade", "cf-net", "cf-check", "cf-secret",
        NULL
    };
    int have_component[COMPONENTS_SIZE] = {0};
    struct stat sb;
    char name[CF_MAXVARSIZE], quoteName[CF_MAXVARSIZE + 2], shortname[CF_MAXVARSIZE];

    if (uname(&VSYSNAME) == -1)
    {
        Log(LOG_LEVEL_ERR, "Couldn't get kernel name info!. (uname: %s)", GetErrorStr());
        memset(&VSYSNAME, 0, sizeof(VSYSNAME));
    }

#ifdef _AIX
    snprintf(real_version, _SYS_NMLN, "%.80s.%.80s", VSYSNAME.version, VSYSNAME.release);
    strlcpy(VSYSNAME.release, real_version, _SYS_NMLN);
#endif
#if defined(__ANDROID__) && !defined(__TERMUX__)
    /*
     * uname cannot differentiate android from linux
     */
    strcpy(VSYSNAME.sysname, "android");
#endif
#ifdef __BUSYBOX__
    /*
     * uname cannot differentiate a busybox toolset from a normal GNU linux toolset
     */
     strcpy(VSYSNAME.sysname, "busybox");
#endif

    ToLowerStrInplace(VSYSNAME.sysname);
    ToLowerStrInplace(VSYSNAME.machine);

#ifdef _AIX
    switch (_system_configuration.architecture)
    {
    case POWER_RS:
        strlcpy(VSYSNAME.machine, "power", _SYS_NMLN);
        break;
    case POWER_PC:
        strlcpy(VSYSNAME.machine, "powerpc", _SYS_NMLN);
        break;
    case IA64:
        strlcpy(VSYSNAME.machine, "ia64", _SYS_NMLN);
        break;
    }
#endif

/*
 * solarisx86 is a historically defined class for Solaris on x86. We have to
 * define it manually now.
 */
#ifdef __sun
    if (strcmp(VSYSNAME.machine, "i86pc") == 0)
    {
        EvalContextClassPutHard(ctx, "solarisx86", "inventory,attribute_name=none,source=agent");
    }
#endif

    DetectDomainName(ctx, VSYSNAME.nodename);

    if ((tloc = time((time_t *) NULL)) == -1)
    {
        Log(LOG_LEVEL_ERR, "Couldn't read system clock");
    }
    else
    {
        snprintf(workbuf, CF_BUFSIZE, "%jd", (intmax_t) tloc);
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "systime", workbuf, CF_DATA_TYPE_INT, "time_based,source=agent");
        snprintf(workbuf, CF_BUFSIZE, "%jd", (intmax_t) tloc / SECONDS_PER_DAY);
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "sysday", workbuf, CF_DATA_TYPE_INT, "time_based,source=agent");
        i = GetUptimeMinutes(tloc);
        if (i != -1)
        {
            snprintf(workbuf, CF_BUFSIZE, "%d", i);
            EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "uptime", workbuf, CF_DATA_TYPE_INT, "inventory,time_based,source=agent,attribute_name=Uptime minutes");
        }
    }

    bool found = false;
    for (i = 0; !found && (i < PLATFORM_CONTEXT_MAX); i++)
    {
        char sysname[CF_BUFSIZE];
        strlcpy(sysname, VSYSNAME.sysname, CF_BUFSIZE);
        ToLowerStrInplace(sysname);

        /* FIXME: review those strcmps. Moved out from StringMatch */
        if (!strcmp(CLASSATTRIBUTES[i][0], sysname)
            || StringMatchFull(CLASSATTRIBUTES[i][0], sysname))
        {
            if (!strcmp(CLASSATTRIBUTES[i][1], VSYSNAME.machine)
                || StringMatchFull(CLASSATTRIBUTES[i][1], VSYSNAME.machine))
            {
                if (!strcmp(CLASSATTRIBUTES[i][2], VSYSNAME.release)
                    || StringMatchFull(CLASSATTRIBUTES[i][2], VSYSNAME.release))
                {
                    EvalContextClassPutHard(ctx, CLASSTEXT[i], "inventory,attribute_name=none,source=agent,derived-from=sys.class");

                    found = true;

                    VSYSTEMHARDCLASS = (PlatformContext) i;
                    VPSHARDCLASS = (PlatformContext) i; /* this one can be overriden at vz detection */
                    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "class", CLASSTEXT[i], CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=Kernel");
                }
            }
            else
            {
                Log(LOG_LEVEL_DEBUG, "I recognize '%s' but not '%s'", VSYSNAME.sysname, VSYSNAME.machine);
                continue;
            }
        }
    }

    if (!found)
    {
        i = 0;
    }

    Log(LOG_LEVEL_VERBOSE, "%s - ready", NameVersion());
    Banner("Environment discovery");

    snprintf(workbuf, CF_BUFSIZE, "%s", CLASSTEXT[i]); // See: cppcheck_suppressions.txt


    Log(LOG_LEVEL_VERBOSE, "Host name is: %s", VSYSNAME.nodename);
    Log(LOG_LEVEL_VERBOSE, "Operating System Type is %s", VSYSNAME.sysname);
    Log(LOG_LEVEL_VERBOSE, "Operating System Release is %s", VSYSNAME.release);
    Log(LOG_LEVEL_VERBOSE, "Architecture = %s", VSYSNAME.machine);
    Log(LOG_LEVEL_VERBOSE, "CFEngine detected operating system description is %s", workbuf);
    Log(LOG_LEVEL_VERBOSE, "The time is now %s", ctime(&tloc));

    snprintf(workbuf, CF_MAXVARSIZE, "%s", ctime(&tloc));
    Chop(workbuf, CF_EXPANDSIZE);

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "date", workbuf, CF_DATA_TYPE_STRING, "time_based,source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cdate", CanonifyName(workbuf), CF_DATA_TYPE_STRING, "time_based,source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "os", VSYSNAME.sysname, CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "release", VSYSNAME.release, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=Kernel Release");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "version", VSYSNAME.version, CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "arch", VSYSNAME.machine, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=Architecture");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "workdir", workdir, CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "fstab", VFSTAB[VSYSTEMHARDCLASS], CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "resolv", VRESOLVCONF[VSYSTEMHARDCLASS], CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "maildir", VMAILDIR[VSYSTEMHARDCLASS], CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "exports", VEXPORTS[VSYSTEMHARDCLASS], CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "logdir", GetLogDir(), CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "piddir", GetPidDir(), CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "statedir", GetStateDir(), CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "masterdir", GetMasterDir(), CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "inputdir", GetInputDir(), CF_DATA_TYPE_STRING, "source=agent");

    snprintf(workbuf, CF_BUFSIZE, "%s", bindir);
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "bindir", workbuf, CF_DATA_TYPE_STRING, "source=agent");

    snprintf(workbuf, CF_BUFSIZE, "%s%cpromises.cf", GetInputDir(), FILE_SEPARATOR);
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "default_policy_path", workbuf, CF_DATA_TYPE_STRING, "source=agent");

    snprintf(workbuf, CF_BUFSIZE, "%s%cfailsafe.cf", GetInputDir(), FILE_SEPARATOR);
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "failsafe_policy_path", workbuf, CF_DATA_TYPE_STRING, "source=agent");

    snprintf(workbuf, CF_BUFSIZE, "%s%cupdate.cf", GetInputDir(), FILE_SEPARATOR);
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "update_policy_path", workbuf, CF_DATA_TYPE_STRING, "source=agent");

/* FIXME: type conversion */
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cf_version", (char *) Version(), CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=CFEngine version");

    DiscoverVersion(ctx);

    if (PUBKEY)
    {
        char pubkey_digest[CF_HOSTKEY_STRING_SIZE] = { 0 };

        HashPubKey(PUBKEY, digest, CF_DEFAULT_DIGEST);
        HashPrintSafe(pubkey_digest, sizeof(pubkey_digest), digest,
                      CF_DEFAULT_DIGEST, true);

        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "key_digest", pubkey_digest, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=CFEngine ID");

        snprintf(workbuf, CF_MAXVARSIZE - 1, "PK_%s", pubkey_digest);
        CanonifyNameInPlace(workbuf);
        EvalContextClassPutHard(ctx, workbuf, "inventory,attribute_name=none,source=agent,derived-from=sys.key_digest");
    }

    for (i = 0; components[i] != NULL; i++)
    {
        snprintf(shortname, CF_MAXVARSIZE - 1, "%s", CanonifyName(components[i]));

#if defined(_WIN32)
        // twin has own dir, and is named agent
        if (i == 0)
        {
            snprintf(name, CF_MAXVARSIZE - 1, "%s-twin%ccf-agent.exe", bindir, FILE_SEPARATOR);
        }
        else
        {
            snprintf(name, CF_MAXVARSIZE - 1, "%s%c%s.exe", bindir, FILE_SEPARATOR, components[i]);
        }
#else
        snprintf(name, CF_MAXVARSIZE - 1, "%s%c%s", bindir, FILE_SEPARATOR, components[i]);
#endif

        have_component[i] = false;

        if (stat(name, &sb) != -1)
        {
            snprintf(quoteName, sizeof(quoteName), "\"%s\"", name);
            // Sets $(sys.cf_agent), $(sys.cf_serverd) $(sys.cf_execd) etc.
            // to their respective /bin paths
            EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, shortname, quoteName, CF_DATA_TYPE_STRING, "cfe_internal,source=agent");
            have_component[i] = true;
        }
    }

// If no twin, fail over the agent

    if (!have_component[0])
    {
        snprintf(shortname, CF_MAXVARSIZE - 1, "%s", CanonifyName(components[0]));

#if defined(_WIN32)
        snprintf(name, CF_MAXVARSIZE - 1, "%s%c%s.exe", bindir, FILE_SEPARATOR,
                 components[1]);
#else
        snprintf(name, CF_MAXVARSIZE - 1, "%s%c%s", bindir, FILE_SEPARATOR, components[1]);
#endif

        if (stat(name, &sb) != -1)
        {
            snprintf(quoteName, sizeof(quoteName), "\"%s\"", name);
            EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, shortname, quoteName, CF_DATA_TYPE_STRING, "cfe_internal,source=agent");
        }
    }

/* Windows special directories and tools */

#ifdef __MINGW32__
    if (NovaWin_GetWinDir(workbuf, sizeof(workbuf)))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "windir", workbuf, CF_DATA_TYPE_STRING, "source=agent");
    }

    if (NovaWin_GetSysDir(workbuf, sizeof(workbuf)))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "winsysdir", workbuf, CF_DATA_TYPE_STRING, "source=agent");

        char filename[CF_BUFSIZE];
        if (snprintf(filename, sizeof(filename), "%s%s", workbuf, "\\WindowsPowerShell\\v1.0\\powershell.exe") < sizeof(filename))
        {
            if (NovaWin_FileExists(filename))
            {
                EvalContextClassPutHard(ctx, "powershell", "inventory,attribute_name=none,source=agent");
                Log(LOG_LEVEL_VERBOSE, "Additional hard class defined as: %s", "powershell");
            }
        }
    }

    if (NovaWin_GetProgDir(workbuf, sizeof(workbuf)))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "winprogdir", workbuf, CF_DATA_TYPE_STRING, "source=agent");
    }

# ifdef _WIN64
// only available on 64 bit windows systems
    if (NovaWin_GetEnv("PROGRAMFILES(x86)", workbuf, sizeof(workbuf)))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "winprogdir86", workbuf, CF_DATA_TYPE_STRING, "source=agent");
    }

# else/* NOT _WIN64 */

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "winprogdir86", "", CF_DATA_TYPE_STRING, "source=agent");

# endif
#endif /* !__MINGW32__ */

    EnterpriseContext(ctx);

    snprintf(workbuf, sizeof(workbuf), "%u_bit", (unsigned) sizeof(void*) * 8);
    EvalContextClassPutHard(ctx, workbuf, "source=agent");
    Log(LOG_LEVEL_VERBOSE, "Additional hard class defined as: %s", CanonifyName(workbuf));

    snprintf(workbuf, CF_BUFSIZE, "%s_%s", VSYSNAME.sysname, VSYSNAME.release);
    EvalContextClassPutHard(ctx, workbuf, "inventory,attribute_name=none,source=agent,derived-from=sys.sysname,derived-from=sys.release");

    EvalContextClassPutHard(ctx, VSYSNAME.machine, "source=agent,derived-from=sys.machine");
    Log(LOG_LEVEL_VERBOSE, "Additional hard class defined as: %s", CanonifyName(workbuf));

    snprintf(workbuf, CF_BUFSIZE, "%s_%s", VSYSNAME.sysname, VSYSNAME.machine);
    EvalContextClassPutHard(ctx, workbuf, "source=agent,derived-from=sys.sysname,derived-from=sys.machine");
    Log(LOG_LEVEL_VERBOSE, "Additional hard class defined as: %s", CanonifyName(workbuf));

    snprintf(workbuf, CF_BUFSIZE, "%s_%s_%s", VSYSNAME.sysname, VSYSNAME.machine, VSYSNAME.release);
    EvalContextClassPutHard(ctx, workbuf, "source=agent,derived-from=sys.sysname,derived-from=sys.machine,derived-from=sys.release");
    Log(LOG_LEVEL_VERBOSE, "Additional hard class defined as: %s", CanonifyName(workbuf));

#ifdef HAVE_SYSINFO
# ifdef SI_ARCHITECTURE
    sz = sysinfo(SI_ARCHITECTURE, workbuf, CF_BUFSIZE);
    if (sz == -1)
    {
        Log(LOG_LEVEL_VERBOSE, "cfengine internal: sysinfo returned -1");
    }
    else
    {
        EvalContextClassPutHard(ctx, workbuf, "inventory,attribute_name=none,source=agent");
        Log(LOG_LEVEL_VERBOSE, "Additional hard class defined as: %s", workbuf);
    }
# endif
# ifdef SI_PLATFORM
    sz = sysinfo(SI_PLATFORM, workbuf, CF_BUFSIZE);
    if (sz == -1)
    {
        Log(LOG_LEVEL_VERBOSE, "cfengine internal: sysinfo returned -1");
    }
    else
    {
        EvalContextClassPutHard(ctx, workbuf, "inventory,attribute_name=none,source=agent");
        Log(LOG_LEVEL_VERBOSE, "Additional hard class defined as: %s", workbuf);
    }
# endif
#endif

    snprintf(workbuf, CF_BUFSIZE, "%s_%s_%s_%s", VSYSNAME.sysname, VSYSNAME.machine, VSYSNAME.release,
             VSYSNAME.version);

    if (strlen(workbuf) > CF_MAXVARSIZE - 2)
    {
        Log(LOG_LEVEL_VERBOSE, "cfengine internal: $(arch) overflows CF_MAXVARSIZE! Truncating");
    }

    sp = xstrdup(CanonifyName(workbuf));
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "long_arch", sp, CF_DATA_TYPE_STRING, "source=agent");
    EvalContextClassPutHard(ctx, sp, "source=agent,derived-from=sys.long_arch");
    free(sp);

    snprintf(workbuf, CF_BUFSIZE, "%s_%s", VSYSNAME.sysname, VSYSNAME.machine);
    sp = xstrdup(CanonifyName(workbuf));
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "ostype", sp, CF_DATA_TYPE_STRING, "source=agent");
    EvalContextClassPutHard(ctx, sp, "inventory,attribute_name=none,source=agent,derived-from=sys.ostype");
    free(sp);

    if (!found)
    {
        Log(LOG_LEVEL_ERR, "I don't understand what architecture this is");
    }

    char compile_str[] = "compiled_on_";
    size_t compile_str_len = sizeof(compile_str);
    strcpy(workbuf, compile_str);

    strlcat(workbuf, CanonifyName(AUTOCONF_SYSNAME),
            CF_BUFSIZE - compile_str_len);
    EvalContextClassPutHard(ctx, workbuf, "source=agent");
    Log(LOG_LEVEL_VERBOSE, "GNU autoconf class from compile time: %s", workbuf);

/* Get IP address from nameserver */

    if ((hp = gethostbyname(VFQNAME)) == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Hostname lookup failed on node name '%s'", VSYSNAME.nodename);
        return;
    }
    else
    {
        memset(&cin, 0, sizeof(cin));
        cin.sin_addr.s_addr = ((struct in_addr *) (hp->h_addr))->s_addr;
        Log(LOG_LEVEL_VERBOSE, "Address given by nameserver: %s", inet_ntoa(cin.sin_addr));
        strcpy(VIPADDRESS, inet_ntoa(cin.sin_addr));

        for (i = 0; hp->h_aliases[i] != NULL; i++)
        {
            Log(LOG_LEVEL_DEBUG, "Adding alias '%s'", hp->h_aliases[i]);
            EvalContextClassPutHard(ctx, hp->h_aliases[i], "inventory,attribute_name=none,source=agent,based-on=sys.fqhost");
        }
    }

#ifdef HAVE_GETZONEID
    zoneid_t zid;
    char zone[ZONENAME_MAX];
    char vbuff[CF_BUFSIZE];

    zid = getzoneid();
    getzonenamebyid(zid, zone, ZONENAME_MAX);

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "zone", zone, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=Solaris zone");
    snprintf(vbuff, CF_BUFSIZE - 1, "zone_%s", zone);
    EvalContextClassPutHard(ctx, vbuff, "source=agent,derived-from=sys.zone");

    if (strcmp(zone, "global") == 0)
    {
        Log(LOG_LEVEL_VERBOSE, "CFEngine seems to be running inside a global solaris zone of name '%s'", zone);
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "CFEngine seems to be running inside a local solaris zone of name '%s'", zone);
    }
#endif
}

/*******************************************************************/

void LoadSlowlyVaryingObservations(EvalContext *ctx)
{
    CF_DB *dbp;
    CF_DBC *dbcp;
    char *key;
    void *stored;
    int ksize, vsize;

    if (!OpenDB(&dbp, dbid_static))
    {
        return;
    }

    /* Acquire a cursor for the database. */
    if (!NewDBCursor(dbp, &dbcp))
    {
        Log(LOG_LEVEL_INFO, "Unable to scan class db");
        CloseDB(dbp);
        return;
    }

    while (NextDB(dbcp, &key, &ksize, &stored, &vsize))
    {
        if (key == NULL  ||  stored == NULL)
        {
            continue;
        }

        char lval[1024];
        int type_i;
        int ret = sscanf(key, "%1023[^:]:%d", lval, &type_i);
        if (ret == 2)
        {
            DataType type = type_i;
            switch (type)
            {
            case CF_DATA_TYPE_STRING:
            case CF_DATA_TYPE_INT:
            case CF_DATA_TYPE_REAL:
                EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_MON,
                                              lval, stored, type,
                                              "monitoring,source=observation");
                break;

            case CF_DATA_TYPE_STRING_LIST:
            {
                Rlist *list = RlistFromSplitString(stored, ',');
                EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_MON,
                                              lval, list, CF_DATA_TYPE_STRING_LIST,
                                              "monitoring,source=observation");
                RlistDestroy(list);
                break;
            }
            case CF_DATA_TYPE_COUNTER:
                EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_MON,
                                              lval, stored, CF_DATA_TYPE_STRING,
                                              "monitoring,source=observation");
                break;

            default:
                Log(LOG_LEVEL_ERR,
                    "Unexpected monitoring type %d found in dbid_static database",
                    (int) type);
            }
        }
    }

    DeleteDBCursor(dbcp);
    CloseDB(dbp);
}

static void Get3Environment(EvalContext *ctx)
{
    char env[CF_BUFSIZE], context[CF_BUFSIZE], name[CF_MAXVARSIZE], value[CF_BUFSIZE];
    struct stat statbuf;
    time_t now = time(NULL);

    Log(LOG_LEVEL_VERBOSE, "Looking for environment from cf-monitord...");

    snprintf(env, CF_BUFSIZE, "%s/%s", GetStateDir(), CF_ENV_FILE);
    MapName(env);

    FILE *fp = safe_fopen(env, "r");
    if (fp == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Unable to detect environment from cf-monitord");
        return;
    }

    int fd = fileno(fp);
    if (fstat(fd, &statbuf) == -1)
    {
        Log(LOG_LEVEL_VERBOSE, "Unable to detect environment from cf-monitord");
        fclose(fp);
        return;
    }

    if (statbuf.st_mtime < (now - 60 * 60))
    {
        Log(LOG_LEVEL_VERBOSE, "Environment data are too old - discarding");
        unlink(env);
        fclose(fp);
        return;
    }

    snprintf(value, CF_MAXVARSIZE - 1, "%s", ctime(&statbuf.st_mtime));
    if (Chop(value, CF_EXPANDSIZE) == -1)
    {
        Log(LOG_LEVEL_ERR, "Chop was called on a string that seemed to have no terminator");
    }

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_MON, "env_time", value, CF_DATA_TYPE_STRING, "time_based,source=agent");

    Log(LOG_LEVEL_VERBOSE, "Loading environment...");

    for(;;)
    {
        name[0] = '\0';
        value[0] = '\0';

        if (fgets(context, sizeof(context), fp) == NULL)
        {
            if (ferror(fp))
            {
                UnexpectedError("Failed to read line from stream");
                break;
            }
            else /* feof */
            {
                break;
            }
        }


        if (*context == '@')
        {
            nt_static_assert((sizeof(name)) > 255);
            nt_static_assert((sizeof(value)) > 255);
            if (sscanf(context + 1, "%255[^=]=%255[^\n]", name, value) == 2)
            {
                Log(LOG_LEVEL_DEBUG,
                    "Setting new monitoring list '%s' => '%s'",
                    name, value);
                Rlist *list = RlistParseShown(value);
                EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_MON,
                                              name, list,
                                              CF_DATA_TYPE_STRING_LIST,
                                              "monitoring,source=environment");

                RlistDestroy(list);
            }
            else
            {
                Log(LOG_LEVEL_ERR,
                    "Failed to parse '%s' as '@variable=list' monitoring list",
                    context);
            }
        }
        else if (strchr(context, '='))
        {
            nt_static_assert((sizeof(name)) > 255);
            nt_static_assert((sizeof(value)) > 255);
            if (sscanf(context, "%255[^=]=%255[^\n]", name, value) == 2)
            {
                EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_MON,
                                              name, value,
                                              CF_DATA_TYPE_STRING,
                                              "monitoring,source=environment");
                Log(LOG_LEVEL_DEBUG,
                    "Setting new monitoring scalar '%s' => '%s'",
                    name, value);
            }
            else
            {
                Log(LOG_LEVEL_ERR,
                    "Failed to parse '%s' as 'variable=value' monitoring scalar",
                    context);
            }
        }
        else
        {
            StripTrailingNewline(context, CF_BUFSIZE);
            EvalContextClassPutHard(ctx, context, "monitoring,source=environment");
        }
    }

    fclose(fp);
    Log(LOG_LEVEL_VERBOSE, "Environment data loaded");

    LoadSlowlyVaryingObservations(ctx);
}

static void BuiltinClasses(EvalContext *ctx)
{
    char vbuff[CF_BUFSIZE];

    EvalContextClassPutHard(ctx, "any", "source=agent");            /* This is a reserved word / wildcard */

    snprintf(vbuff, CF_BUFSIZE, "cfengine_%s", CanonifyName(Version()));
    CreateHardClassesFromCanonification(ctx, vbuff, "inventory,attribute_name=none,source=agent");

    CreateHardClassesFromFeatures(ctx, "source=agent");
}

/*******************************************************************/

void CreateHardClassesFromCanonification(EvalContext *ctx, const char *canonified, char *tags)
{
    char buf[CF_MAXVARSIZE];

    strlcpy(buf, canonified, sizeof(buf));

    EvalContextClassPutHard(ctx, buf, tags);

    char *sp;

    while ((sp = strrchr(buf, '_')))
    {
        *sp = 0;
        EvalContextClassPutHard(ctx, buf, tags);
    }
}

static void SetFlavor(EvalContext *ctx, const char *flavor)
{
    EvalContextClassPutHard(ctx, flavor, "inventory,attribute_name=none,source=agent,derived-from=sys.flavor");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "flavour", flavor, CF_DATA_TYPE_STRING, "source=agent");
    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "flavor", flavor, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=none");
}

#if defined __linux__ || __MINGW32__

/**
 * @brief Combines OS and version string to define flavor variable and class
 *
 * @note Input strings should be canonified before calling
 */
static void SetFlavor2(
    EvalContext *const ctx,
    const char *const id,
    const char *const major_version)
{
    assert(ctx != NULL);
    assert(id != NULL);
    assert(major_version != NULL);

    char *flavor;
    xasprintf(&flavor, "%s_%s", id, major_version);
    SetFlavor(ctx, flavor);
    free(flavor);
}

#endif

#ifdef __linux__

/**
 * @brief Combines OS and version string to define multiple hard classes
 *
 * @note Input strings should be canonified before calling
 */
static void DefineVersionedHardClasses(
    EvalContext *const ctx,
    const char *const tags,
    const char *const id,
    const char *const version)
{
    assert(ctx != NULL);
    assert(id != NULL);
    assert(version != NULL);

    char *class;
    xasprintf(&class, "%s_%s", id, version);

    // Strip away version number to define multiple hard classes
    // Example: coreos_1185_3_0 -> coreos_1185_3 -> coreos_1185 -> coreos
    char *last_underscore = strrchr(class, '_');
    while ( last_underscore != NULL )
    {
        EvalContextClassPutHard(ctx, class, tags);
        *last_underscore = '\0';
        last_underscore = strrchr(class, '_');
    }
    EvalContextClassPutHard(ctx, class, tags);
    free(class);
}

static void OSReleaseParse(EvalContext *ctx, const char *file_path)
{
    JsonElement *os_release_json = JsonReadDataFile("system info discovery",
                                                    file_path, DATAFILETYPE_ENV,
                                                    100 * 1024);
    if (os_release_json != NULL)
    {
        char *tags;
        xasprintf(&tags,
                  "inventory,attribute_name=none,source=agent,derived-from-file=%s",
                  file_path);
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "os_release",
                                      os_release_json, CF_DATA_TYPE_CONTAINER,
                                      tags);
        const char *const_os_release_id = JsonObjectGetAsString(os_release_json, "ID");
        const char *const_os_release_version_id = JsonObjectGetAsString(os_release_json, "VERSION_ID");
        char *os_release_id = SafeStringDuplicate(const_os_release_id);
        char *os_release_version_id = SafeStringDuplicate(const_os_release_version_id);

        if (os_release_id != NULL)
        {
            CanonifyNameInPlace(os_release_id);

            const char *alias = NULL;
            if (StringEqual(os_release_id, "rhel"))
            {
                alias = "redhat";
            }
            else if (StringEqual(os_release_id, "opensuse") || 
                     StringEqual(os_release_id, "sles"))
            {
                alias = "suse";
            }

            if (os_release_version_id == NULL)
            {
                // if VERSION_ID doesn't exist, define only one hard class:
                EvalContextClassPutHard(ctx, os_release_id, tags);
                if (alias != NULL)
                {
                    EvalContextClassPutHard(ctx, alias, tags);
                }
            }
            else // if VERSION_ID exists set flavor and multiple hard classes:
            {
                CanonifyNameInPlace(os_release_version_id);

                // Set the flavor to be ID + major version (derived from VERSION_ID)
                char *first_underscore = strchr(os_release_version_id, '_');
                if (first_underscore != NULL)
                {
                    // Temporarily modify os_release_version_id to be major version
                    *first_underscore = '\0';
                    SetFlavor2(ctx, os_release_id, os_release_version_id);
                    *first_underscore = '_';
                }
                else
                {
                    SetFlavor2(ctx, os_release_id, os_release_version_id);
                }

                // One of the hard classes is already set by SetFlavor
                // but it seems excessive to try to skip this:
                DefineVersionedHardClasses(ctx, tags, os_release_id, os_release_version_id);
                if (alias != NULL)
                {
                    DefineVersionedHardClasses(ctx, tags, alias, os_release_version_id);
                }
            }
        }
        free(os_release_version_id);
        free(os_release_id);
        free(tags);
        JsonDestroy(os_release_json);
    }
}
#endif

static void OSClasses(EvalContext *ctx)
{
#ifdef __linux__

/* First we check if init process is systemd, and set "systemd" hard class. */

    {
        char init_path[CF_BUFSIZE];
        if (ReadLine("/proc/1/cmdline", init_path, sizeof(init_path)))
        {
            /* Follow possible symlinks. */

            char resolved_path[PATH_MAX];      /* realpath() needs PATH_MAX */
            if (realpath(init_path, resolved_path) != NULL &&
                strlen(resolved_path) < sizeof(init_path))
            {
                strcpy(init_path, resolved_path);
            }

            /* Check if string ends with "/systemd". */
            char *p;
            char *next_p = NULL;
            const char *term = "/systemd";
            do
            {
                p = next_p;
                next_p = strstr(next_p ? next_p+strlen(term) : init_path, term);
            }
            while (next_p);

            if (p != NULL &&
                p[strlen("/systemd")] == '\0')
            {
                EvalContextClassPutHard(ctx, "systemd",
                                        "inventory,attribute_name=none,source=agent");
            }
        }
    }


    struct stat statbuf;

    // os-release is used to set sys.os_release, sys.flavor and hard classes
    if (access("/etc/os-release", R_OK) != -1)
    {
        OSReleaseParse(ctx, "/etc/os-release");
    }
    else if (access("/usr/lib/os-release", R_OK) != -1)
    {
        OSReleaseParse(ctx, "/usr/lib/os-release");
    }

/* Mandrake/Mandriva, Fedora and Oracle VM Server supply /etc/redhat-release, so
   we test for those distributions first */

    if (stat("/etc/mandriva-release", &statbuf) != -1)
    {
        Linux_Mandriva_Version(ctx);
    }
    else if (stat("/etc/mandrake-release", &statbuf) != -1)
    {
        Linux_Mandrake_Version(ctx);
    }
    else if (stat("/etc/fedora-release", &statbuf) != -1)
    {
        Linux_Fedora_Version(ctx);
    }
    else if (stat("/etc/ovs-release", &statbuf) != -1)
    {
        Linux_Oracle_VM_Server_Version(ctx);
    }
    else if (stat("/etc/redhat-release", &statbuf) != -1)
    {
        Linux_Redhat_Version(ctx);
    }

/* Oracle Linux >= 6 supplies separate /etc/oracle-release alongside
   /etc/redhat-release, use it to precisely identify version */

    if (stat("/etc/oracle-release", &statbuf) != -1)
    {
        Linux_Oracle_Version(ctx);
    }

    if (stat("/etc/generic-release", &statbuf) != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "This appears to be a sun cobalt system.");
        SetFlavor(ctx, "SunCobalt");
    }

    if (stat("/etc/SuSE-release", &statbuf) != -1)
    {
        Linux_Suse_Version(ctx);
    }

    if (stat("/etc/system-release", &statbuf) != -1)
    {
        Linux_Amazon_Version(ctx);
    }

# define SLACKWARE_ANCIENT_VERSION_FILENAME "/etc/slackware-release"
# define SLACKWARE_VERSION_FILENAME "/etc/slackware-version"
    if (stat(SLACKWARE_VERSION_FILENAME, &statbuf) != -1)
    {
        Linux_Slackware_Version(ctx, SLACKWARE_VERSION_FILENAME);
    }
    else if (stat(SLACKWARE_ANCIENT_VERSION_FILENAME, &statbuf) != -1)
    {
        Linux_Slackware_Version(ctx, SLACKWARE_ANCIENT_VERSION_FILENAME);
    }

    if (stat(DEBIAN_VERSION_FILENAME, &statbuf) != -1)
    {
        Linux_Debian_Version(ctx);
    }

    if (stat(LSB_RELEASE_FILENAME, &statbuf) != -1)
    {
        Linux_Misc_Version(ctx);
    }

    if (stat("/usr/bin/aptitude", &statbuf) != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "This system seems to have the aptitude package system");
        EvalContextClassPutHard(ctx, "have_aptitude", "inventory,attribute_name=none,source=agent");
    }

    if (stat("/etc/UnitedLinux-release", &statbuf) != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "This appears to be a UnitedLinux system.");
        SetFlavor(ctx, "UnitedLinux");
    }

    if (stat("/etc/alpine-release", &statbuf) != -1)
    {
        Linux_Alpine_Version(ctx);
    }

    if (stat("/etc/gentoo-release", &statbuf) != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "This appears to be a gentoo system.");
        SetFlavor(ctx, "gentoo");
    }

    if (stat("/etc/arch-release", &statbuf) != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "This appears to be an Arch Linux system.");
        SetFlavor(ctx, "archlinux");
    }

    if (stat("/proc/vmware/version", &statbuf) != -1 || stat("/etc/vmware-release", &statbuf) != -1)
    {
        VM_Version(ctx);
    }
    else if (stat("/etc/vmware", &statbuf) != -1 && S_ISDIR(statbuf.st_mode))
    {
        VM_Version(ctx);
    }

    if (stat("/proc/xen/capabilities", &statbuf) != -1)
    {
        Xen_Domain(ctx);
    }
    if (stat("/etc/Eos-release", &statbuf) != -1)
    {
        EOS_Version(ctx);
        SetFlavor(ctx, "Eos");
    }

    if (stat("/etc/issue", &statbuf) != -1)
    {
        MiscOS(ctx);
    }

    if (stat("/proc/self/status", &statbuf) != -1)
    {
        OpenVZ_Detect(ctx);
    }

#else

    char vbuff[CF_MAXVARSIZE];

#ifdef _AIX
    strlcpy(vbuff, VSYSNAME.version, CF_MAXVARSIZE);
#else
    strlcpy(vbuff, VSYSNAME.release, CF_MAXVARSIZE);
#endif


    for (char *sp = vbuff; *sp != '\0'; sp++)
    {
        if (*sp == '-')
        {
            *sp = '\0';
            break;
        }
    }

    char context[CF_BUFSIZE];
    snprintf(context, CF_BUFSIZE, "%s_%s", VSYSNAME.sysname, vbuff);
    SetFlavor(ctx, context);


#ifdef __hpux
    /*
     * Define a hard class with just the version major number of HP-UX
     *
     * For example, when being run on HP-UX B.11.23 the following class will
     * be defined: hpux_11
     */

    // Extract major version number
    char *major = NULL;
    for (char *sp = vbuff; *sp != '\0'; sp++)
    {
        if (major == NULL && isdigit(*sp))
        {
            major = sp;
        }
        else if (!isdigit(*sp))
        {
            *sp = '\0';
        }
    }

    if (major != NULL)
    {
        snprintf(context, CF_BUFSIZE, "hpux_%s", major);
        EvalContextClassPutHard(ctx, context, "source=agent,derived-from=sys.flavor");
    }
#endif

#ifdef __FreeBSD__
    /*
     * Define a hard class with just the version major number on FreeBSD
     *
     * For example, when being run on either FreeBSD 10.0 or 10.1 a class
     * called freebsd_10 will be defined
     */
    for (char *sp = vbuff; *sp != '\0'; sp++)
    {
        if (*sp == '.')
        {
            *sp = '\0';
            break;
        }
    }

    snprintf(context, CF_BUFSIZE, "%s_%s", VSYSNAME.sysname, vbuff);
    EvalContextClassPutHard(ctx, context, "source=agent,derived-from=sys.flavor");
#endif

#endif

#ifdef XEN_CPUID_SUPPORT
    if (Xen_Hv_Check())
    {
        Log(LOG_LEVEL_VERBOSE, "This appears to be a xen hv system.");
        EvalContextClassPutHard(ctx, "xen", "inventory,attribute_name=Virtual host,source=agent");
        EvalContextClassPutHard(ctx, "xen_domu_hv", "source=agent");
    }
#endif /* XEN_CPUID_SUPPORT */

    GetCPUInfo(ctx);

#ifdef __CYGWIN__

    for (char *sp = VSYSNAME.sysname; *sp != '\0'; sp++)
    {
        if (*sp == '-')
        {
            sp++;
            if (strncmp(sp, "5.0", 3) == 0)
            {
                Log(LOG_LEVEL_VERBOSE, "This appears to be Windows 2000");
                EvalContextClassPutHard(ctx, "Win2000", "inventory,attribute_name=none,source=agent");
            }

            if (strncmp(sp, "5.1", 3) == 0)
            {
                Log(LOG_LEVEL_VERBOSE, "This appears to be Windows XP");
                EvalContextClassPutHard(ctx, "WinXP", "inventory,attribute_name=none,source=agent");
            }

            if (strncmp(sp, "5.2", 3) == 0)
            {
                Log(LOG_LEVEL_VERBOSE, "This appears to be Windows Server 2003");
                EvalContextClassPutHard(ctx, "WinServer2003", "inventory,attribute_name=none,source=agent");
            }

            if (strncmp(sp, "6.1", 3) == 0)
            {
                Log(LOG_LEVEL_VERBOSE, "This appears to be Windows Vista");
                EvalContextClassPutHard(ctx, "WinVista", "inventory,attribute_name=none,source=agent");
            }

            if (strncmp(sp, "6.3", 3) == 0)
            {
                Log(LOG_LEVEL_VERBOSE, "This appears to be Windows Server 2008");
                EvalContextClassPutHard(ctx, "WinServer2008", "inventory,attribute_name=none,source=agent");
            }
        }
    }

    EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "crontab", "", CF_DATA_TYPE_STRING, "source=agent");

#endif /* __CYGWIN__ */

#ifdef __MINGW32__
    EvalContextClassPutHard(ctx, VSYSNAME.release, "inventory,attribute_name=none,source=agent,derived-from=sys.release"); // code name - e.g. Windows Vista
    EvalContextClassPutHard(ctx, VSYSNAME.version, "inventory,attribute_name=none,source=agent,derived-from=sys.version"); // service pack number - e.g. Service Pack 3

    if (strstr(VSYSNAME.sysname, "workstation"))
    {
        EvalContextClassPutHard(ctx, "WinWorkstation", "inventory,attribute_name=Windows roles,source=agent,derived-from=sys.sysname");
    }
    else if (strstr(VSYSNAME.sysname, "server"))
    {
        EvalContextClassPutHard(ctx, "WinServer", "inventory,attribute_name=Windows roles,source=agent,derived-from=sys.sysname");
    }
    else if (strstr(VSYSNAME.sysname, "domain controller"))
    {
        EvalContextClassPutHard(ctx, "DomainController", "inventory,attribute_name=Windows roles,source=agent,derived-from=sys.sysname");
        EvalContextClassPutHard(ctx, "WinServer", "inventory,attribute_name=Windows roles,source=agent,derived-from=sys.sysname");
    }
    else
    {
        EvalContextClassPutHard(ctx, "unknown_ostype", "source=agent,derived-from=sys.sysname");
    }

    char *release = SafeStringDuplicate(VSYSNAME.release);
    char *major = NULL;
    FindNextInteger(release, &major);
    if (NULL_OR_EMPTY(major))
    {
        SetFlavor(ctx, "windows");
    }
    else
    {
        SetFlavor2(ctx, "windows", major);
    }
    free(release);

#endif /* __MINGW32__ */

#ifndef _WIN32
    char user_name[CF_SMALLBUF];
    if (GetCurrentUserName(user_name, sizeof(user_name)))
    {
        char vbuff[CF_BUFSIZE];

        if (EvalContextClassGet(ctx, NULL, "SUSE"))
        {
            snprintf(vbuff, CF_BUFSIZE, "/var/spool/cron/tabs/%s", user_name);
        }
        else if (EvalContextClassGet(ctx, NULL, "redhat"))
        {
            snprintf(vbuff, CF_BUFSIZE, "/var/spool/cron/%s", user_name);
        }
        else if (EvalContextClassGet(ctx, NULL, "freebsd"))
        {
            snprintf(vbuff, CF_BUFSIZE, "/var/cron/tabs/%s", user_name);
        }
        else
        {
            snprintf(vbuff, CF_BUFSIZE, "/var/spool/cron/crontabs/%s", user_name);
        }

        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "crontab", vbuff, CF_DATA_TYPE_STRING, "source=agent");
    }

#endif

#if defined(__ANDROID__)
    SetFlavor(ctx, "android");
#endif

/* termux flavor should over-ride android flavor */
#if defined(__TERMUX__)
    SetFlavor(ctx, "termux");
#endif

#ifdef __sun
    if (StringMatchFull("joyent.*", VSYSNAME.version))
    {
        EvalContextClassPutHard(ctx, "smartos", "inventory,attribute_name=none,source=agent,derived-from=sys.version");
        EvalContextClassPutHard(ctx, "smartmachine", "source=agent,derived-from=sys.version");
    }
#endif

    /* FIXME: this variable needs redhat/SUSE/debian classes to be defined and
     * hence can't be initialized earlier */

    if (EvalContextClassGet(ctx, NULL, "redhat"))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "doc_root", "/var/www/html", CF_DATA_TYPE_STRING, "source=agent");
    }

    if (EvalContextClassGet(ctx, NULL, "SUSE"))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "doc_root", "/srv/www/htdocs", CF_DATA_TYPE_STRING, "source=agent");
    }

    if (EvalContextClassGet(ctx, NULL, "debian"))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "doc_root", "/var/www", CF_DATA_TYPE_STRING, "source=agent");
    }
}

/*********************************************************************************/

#ifdef __linux__
static void Linux_Oracle_VM_Server_Version(EvalContext *ctx)
{
    char relstring[CF_MAXVARSIZE];
    char *r;
    int major, minor, patch;
    int revcomps;

#define ORACLE_VM_SERVER_REL_FILENAME "/etc/ovs-release"
#define ORACLE_VM_SERVER_ID "Oracle VM server"

    Log(LOG_LEVEL_VERBOSE, "This appears to be Oracle VM Server");
    EvalContextClassPutHard(ctx, "redhat", "inventory,attribute_name=none,source=agent");
    EvalContextClassPutHard(ctx, "oraclevmserver", "inventory,attribute_name=Virtual host,source=agent");

    if (!ReadLine(ORACLE_VM_SERVER_REL_FILENAME, relstring, sizeof(relstring)))
    {
        return;
    }

    if (strncmp(relstring, ORACLE_VM_SERVER_ID, strlen(ORACLE_VM_SERVER_ID)))
    {
        Log(LOG_LEVEL_VERBOSE, "Could not identify distribution from %s", ORACLE_VM_SERVER_REL_FILENAME);
        return;
    }

    if ((r = strstr(relstring, "release ")) == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Could not find distribution version in %s", ORACLE_VM_SERVER_REL_FILENAME);
        return;
    }

    revcomps = sscanf(r + strlen("release "), "%d.%d.%d", &major, &minor, &patch);

    if (revcomps > 0)
    {
        char buf[CF_BUFSIZE];

        snprintf(buf, CF_BUFSIZE, "oraclevmserver_%d", major);
        SetFlavor(ctx, buf);
    }

    if (revcomps > 1)
    {
        char buf[CF_BUFSIZE];

        snprintf(buf, CF_BUFSIZE, "oraclevmserver_%d_%d", major, minor);
        EvalContextClassPutHard(ctx, buf, "inventory,attribute_name=none,source=agent");
    }

    if (revcomps > 2)
    {
        char buf[CF_BUFSIZE];

        snprintf(buf, CF_BUFSIZE, "oraclevmserver_%d_%d_%d", major, minor, patch);
        EvalContextClassPutHard(ctx, buf, "inventory,attribute_name=none,source=agent");
    }
}

/*********************************************************************************/

static void Linux_Oracle_Version(EvalContext *ctx)
{
    char relstring[CF_MAXVARSIZE];
    char *r;
    int major, minor;

#define ORACLE_REL_FILENAME "/etc/oracle-release"
#define ORACLE_ID "Oracle Linux Server"

    Log(LOG_LEVEL_VERBOSE, "This appears to be Oracle Linux");
    EvalContextClassPutHard(ctx, "oracle", "inventory,attribute_name=none,source=agent");

    if (!ReadLine(ORACLE_REL_FILENAME, relstring, sizeof(relstring)))
    {
        return;
    }

    if (strncmp(relstring, ORACLE_ID, strlen(ORACLE_ID)))
    {
        Log(LOG_LEVEL_VERBOSE, "Could not identify distribution from %s", ORACLE_REL_FILENAME);
        return;
    }

    if ((r = strstr(relstring, "release ")) == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Could not find distribution version in %s", ORACLE_REL_FILENAME);
        return;
    }

    if (sscanf(r + strlen("release "), "%d.%d", &major, &minor) == 2)
    {
        char buf[CF_BUFSIZE];

        snprintf(buf, CF_BUFSIZE, "oracle_%d", major);
        SetFlavor(ctx, buf);

        snprintf(buf, CF_BUFSIZE, "oracle_%d_%d", major, minor);
        EvalContextClassPutHard(ctx, buf, "inventory,attribute_name=none,source=agent");
    }
}

/*********************************************************************************/

static int Linux_Fedora_Version(EvalContext *ctx)
{
#define FEDORA_ID "Fedora"
#define RELEASE_FLAG "release "

/* We are looking for one of the following strings...
 *
 * Fedora Core release 1 (Yarrow)
 * Fedora release 7 (Zodfoobar)
 */

#define FEDORA_REL_FILENAME "/etc/fedora-release"

/* The full string read in from fedora-release */
    char relstring[CF_MAXVARSIZE];

    Log(LOG_LEVEL_VERBOSE, "This appears to be a fedora system.");
    EvalContextClassPutHard(ctx, "redhat", "inventory,attribute_name=none,source=agent");
    EvalContextClassPutHard(ctx, "fedora", "inventory,attribute_name=none,source=agent");

/* Grab the first line from the file and then close it. */

    if (!ReadLine(FEDORA_REL_FILENAME, relstring, sizeof(relstring)))
    {
        return 1;
    }

    Log(LOG_LEVEL_VERBOSE, "Looking for fedora core linux info...");

    char *vendor = "";
    if (!strncmp(relstring, FEDORA_ID, strlen(FEDORA_ID)))
    {
        vendor = "fedora";
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "Could not identify OS distro from %s", FEDORA_REL_FILENAME);
        return 2;
    }

/* Now, grok the release.  We assume that all the strings will
 * have the word 'release' before the numerical release.
 */
    int major = -1;
    char strmajor[PRINTSIZE(major)];
    char *release = strstr(relstring, RELEASE_FLAG);

    if (release == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Could not find a numeric OS release in %s", FEDORA_REL_FILENAME);
        return 2;
    }
    else
    {
        release += strlen(RELEASE_FLAG);

        strmajor[0] = '\0';
        if (sscanf(release, "%d", &major) != 0)
        {
            xsnprintf(strmajor, sizeof(strmajor), "%d", major);
        }
    }

    if (major != -1 && vendor[0] != '\0')
    {
        char classbuf[CF_MAXVARSIZE];
        classbuf[0] = '\0';
        strcat(classbuf, vendor);
        EvalContextClassPutHard(ctx,classbuf, "inventory,attribute_name=none,source=agent");
        strcat(classbuf, "_");
        strcat(classbuf, strmajor);
        SetFlavor(ctx, classbuf);
    }

    return 0;
}

/*********************************************************************************/

static int Linux_Redhat_Version(EvalContext *ctx)
{
#define REDHAT_ID "Red Hat Linux"
#define REDHAT_ENT_ID "Red Hat Enterprise Linux"
#define REDHAT_AS_ID "Red Hat Enterprise Linux AS"
#define REDHAT_AS21_ID "Red Hat Linux Advanced Server"
#define REDHAT_ES_ID "Red Hat Enterprise Linux ES"
#define REDHAT_WS_ID "Red Hat Enterprise Linux WS"
#define REDHAT_C_ID "Red Hat Enterprise Linux Client"
#define REDHAT_S_ID "Red Hat Enterprise Linux Server"
#define REDHAT_W_ID "Red Hat Enterprise Linux Workstation"
#define REDHAT_CN_ID "Red Hat Enterprise Linux ComputeNode"
#define MANDRAKE_ID "Linux Mandrake"
#define MANDRAKE_10_1_ID "Mandrakelinux"
#define WHITEBOX_ID "White Box Enterprise Linux"
#define CENTOS_ID "CentOS"
#define SCIENTIFIC_SL_ID "Scientific Linux SL"
#define SCIENTIFIC_SL6_ID "Scientific Linux"
#define SCIENTIFIC_CERN_ID "Scientific Linux CERN"
#define RELEASE_FLAG "release "
#define ORACLE_4_5_ID "Enterprise Linux Enterprise Linux Server"

/* We are looking for one of the following strings...
 *
 * Red Hat Linux release 6.2 (Zoot)
 * Red Hat Enterprise Linux release 8.0 (Ootpa)
 * Red Hat Linux Advanced Server release 2.1AS (Pensacola)
 * Red Hat Enterprise Linux AS release 3 (Taroon)
 * Red Hat Enterprise Linux WS release 3 (Taroon)
 * Red Hat Enterprise Linux Client release 5 (Tikanga)
 * Red Hat Enterprise Linux Server release 5 (Tikanga)
 * Linux Mandrake release 7.1 (helium)
 * Red Hat Enterprise Linux ES release 2.1 (Panama)
 * White Box Enterprise linux release 3.0 (Liberation)
 * Scientific Linux SL Release 4.0 (Beryllium)
 * CentOS release 4.0 (Final)
 */

#define RH_REL_FILENAME "/etc/redhat-release"

    Log(LOG_LEVEL_VERBOSE, "This appears to be a redhat (or redhat-based) system.");
    EvalContextClassPutHard(ctx, "redhat", "inventory,attribute_name=none,source=agent,derived-from-file="RH_REL_FILENAME);

    /* Grab the first line from the file and then close it. */
    char relstring[CF_MAXVARSIZE];
    if (!ReadLine(RH_REL_FILENAME, relstring, sizeof(relstring)))
    {
        return 1;
    }

    Log(LOG_LEVEL_VERBOSE, "Looking for redhat linux info in '%s'", relstring);

    /* First, try to grok the vendor and edition (if any) */
    char *edition = ""; /* as (Advanced Server, Enterprise) */
    char *vendor = ""; /* Red Hat, Mandrake */
    if (!strncmp(relstring, REDHAT_ES_ID, strlen(REDHAT_ES_ID)))
    {
        vendor = "redhat";
        edition = "es";
    }
    else if (!strncmp(relstring, REDHAT_WS_ID, strlen(REDHAT_WS_ID)))
    {
        vendor = "redhat";
        edition = "ws";
    }
    else if (!strncmp(relstring, REDHAT_WS_ID, strlen(REDHAT_WS_ID)))
    {
        vendor = "redhat";
        edition = "ws";
    }
    else if (!strncmp(relstring, REDHAT_AS_ID, strlen(REDHAT_AS_ID)) ||
             !strncmp(relstring, REDHAT_AS21_ID, strlen(REDHAT_AS21_ID)))
    {
        vendor = "redhat";
        edition = "as";
    }
    else if (!strncmp(relstring, REDHAT_S_ID, strlen(REDHAT_S_ID)))
    {
        vendor = "redhat";
        edition = "s";
    }
    else if (!strncmp(relstring, REDHAT_C_ID, strlen(REDHAT_C_ID))
             || !strncmp(relstring, REDHAT_W_ID, strlen(REDHAT_W_ID)))
    {
        vendor = "redhat";
        edition = "c";
    }
    else if (!strncmp(relstring, REDHAT_CN_ID, strlen(REDHAT_CN_ID)))
    {
        vendor = "redhat";
        edition = "cn";
    }
    else if (!strncmp(relstring, REDHAT_ID, strlen(REDHAT_ID)))
    {
        vendor = "redhat";
    }
    else if (!strncmp(relstring, REDHAT_ENT_ID, strlen(REDHAT_ENT_ID)))
    {
        vendor = "redhat";
    }
    else if (!strncmp(relstring, MANDRAKE_ID, strlen(MANDRAKE_ID)))
    {
        vendor = "mandrake";
    }
    else if (!strncmp(relstring, MANDRAKE_10_1_ID, strlen(MANDRAKE_10_1_ID)))
    {
        vendor = "mandrake";
    }
    else if (!strncmp(relstring, WHITEBOX_ID, strlen(WHITEBOX_ID)))
    {
        vendor = "whitebox";
    }
    else if (!strncmp(relstring, SCIENTIFIC_SL_ID, strlen(SCIENTIFIC_SL_ID)))
    {
        vendor = "scientific";
        edition = "sl";
    }
    else if (!strncmp(relstring, SCIENTIFIC_CERN_ID, strlen(SCIENTIFIC_CERN_ID)))
    {
        vendor = "scientific";
        edition = "cern";
    }
    else if (!strncmp(relstring, SCIENTIFIC_SL6_ID, strlen(SCIENTIFIC_SL6_ID)))
    {
        vendor = "scientific";
        edition = "sl";
    }
    else if (!strncmp(relstring, CENTOS_ID, strlen(CENTOS_ID)))
    {
        vendor = "centos";
    }
    else if (!strncmp(relstring, ORACLE_4_5_ID, strlen(ORACLE_4_5_ID)))
    {
        vendor = "oracle";
        edition = "s";
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "Could not identify OS distro from %s", RH_REL_FILENAME);
        return 2;
    }

/* Now, grok the release.  For AS, we neglect the AS at the end of the
 * numerical release because we already figured out that it *is* AS
 * from the information above.  We assume that all the strings will
 * have the word 'release' before the numerical release.
 */

/* Convert relstring to lowercase so that vendors like
   Scientific Linux don't fall through the cracks.
   */

    for (size_t i = 0; i < strlen(relstring); i++)
    {
        relstring[i] = tolower(relstring[i]);
    }

    /* Where the numerical release will be found */
    int major = -1, minor = -1;
    char strmajor[PRINTSIZE(major)], strminor[PRINTSIZE(minor)];

    char *release = strstr(relstring, RELEASE_FLAG);
    if (release == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Could not find a numeric OS release in %s", RH_REL_FILENAME);
        return 2;
    }
    else
    {
        release += strlen(RELEASE_FLAG);
        if (sscanf(release, "%d.%d", &major, &minor) == 2)
        {
            xsnprintf(strmajor, sizeof(strmajor), "%d", major);
            xsnprintf(strminor, sizeof(strminor), "%d", minor);
        }
        /* red hat 9 is *not* red hat 9.0.
         * and same thing with RHEL AS 3
         */
        else if (sscanf(release, "%d", &major) == 1)
        {
            xsnprintf(strmajor, sizeof(strmajor), "%d", major);
            minor = -2;
        }
    }

    char classbuf[CF_MAXVARSIZE];
    if (major != -1 && minor != -1 && (strcmp(vendor, "") != 0))
    {
        classbuf[0] = '\0';
        strcat(classbuf, vendor);
        EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent,derived-from-file="RH_REL_FILENAME);
        strcat(classbuf, "_");

        if (strcmp(edition, "") != 0)
        {
            strcat(classbuf, edition);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent,derived-from-file="RH_REL_FILENAME);
            strcat(classbuf, "_");
        }

        strcat(classbuf, strmajor);
        EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent,derived-from-file="RH_REL_FILENAME);

        if (minor != -2)
        {
            strcat(classbuf, "_");
            strcat(classbuf, strminor);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent,derived-from-file="RH_REL_FILENAME);
        }
    }

    // Now a version without the edition
    if (major != -1 && minor != -1 && vendor[0] != '\0')
    {
        classbuf[0] = '\0';
        strcat(classbuf, vendor);
        EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent,derived-from-file="RH_REL_FILENAME);
        strcat(classbuf, "_");

        strcat(classbuf, strmajor);

        SetFlavor(ctx, classbuf);

        if (minor != -2)
        {
            strcat(classbuf, "_");
            strcat(classbuf, strminor);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent,derived-from-file="RH_REL_FILENAME);
        }
    }

    return 0;
}

/******************************************************************/

static int Linux_Suse_Version(EvalContext *ctx)
{
#define SUSE_REL_FILENAME "/etc/SuSE-release"
/* Check if it's a SUSE Enterprise version (all in lowercase) */
#define SUSE_SLES8_ID "suse sles-8"
#define SUSE_SLES_ID  "suse linux enterprise server"
#define SUSE_SLED_ID  "suse linux enterprise desktop"
#define SUSE_RELEASE_FLAG "linux "

    char classbuf[CF_MAXVARSIZE];

    Log(LOG_LEVEL_VERBOSE, "This appears to be a SUSE system.");
    EvalContextClassPutHard(ctx, "SUSE", "inventory,attribute_name=none,source=agent");
    EvalContextClassPutHard(ctx, "suse", "inventory,attribute_name=none,source=agent");

    /* The correct spelling for SUSE is "SUSE" but CFEngine used to use "SuSE".
     * Keep this for backwards compatibility until CFEngine 3.7
     */
    EvalContextClassPutHard(ctx, "SuSE", "inventory,attribute_name=none,source=agent");

    /* Grab the first line from the SuSE-release file and then close it. */
    char relstring[CF_MAXVARSIZE];

    FILE *fp = ReadFirstLine(SUSE_REL_FILENAME, relstring, sizeof(relstring));
    if (fp == NULL)
    {
        return 1;
    }

    char vbuf[CF_BUFSIZE], strversion[CF_MAXVARSIZE], strpatch[CF_MAXVARSIZE];
    strversion[0] = '\0';
    strpatch[0] = '\0';

    int major = -1, minor = -1;
    while (fgets(vbuf, sizeof(vbuf), fp) != NULL)
    {
        if (strncmp(vbuf, "VERSION", strlen("version")) == 0)
        {
            strlcpy(strversion, vbuf, sizeof(strversion));
            sscanf(vbuf, "VERSION = %d", &major);
        }

        if (strncmp(vbuf, "PATCH", strlen("PATCH")) == 0)
        {
            strlcpy(strpatch, vbuf, sizeof(strpatch));
            sscanf(vbuf, "PATCHLEVEL = %d", &minor);
        }
    }
    if (ferror(fp))
    {
        UnexpectedError("Failed to read line from stream");
    }
    else
    {
        assert(feof(fp));
    }

    fclose(fp);

    /* Check if it's a SUSE Enterprise version  */

    Log(LOG_LEVEL_VERBOSE, "Looking for SUSE enterprise info in '%s'", relstring);

    /* Convert relstring to lowercase to handle rename of SuSE to
     * SUSE with SUSE 10.0.
     */

    for (size_t i = 0; i < strlen(relstring); i++)
    {
        relstring[i] = tolower(relstring[i]);
    }

    /* Check if it's a SUSE Enterprise version (all in lowercase) */

    if (!strncmp(relstring, SUSE_SLES8_ID, strlen(SUSE_SLES8_ID)))
    {
        classbuf[0] = '\0';
        strcat(classbuf, "SLES8");
        EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
    }
    else if (strncmp(relstring, "sles", 4) == 0)
    {
        Item *list, *ip;

        nt_static_assert((sizeof(vbuf)) > 255);
        sscanf(relstring, "%255[-_a-zA-Z0-9]", vbuf);
        EvalContextClassPutHard(ctx, vbuf, "inventory,attribute_name=none,source=agent");

        list = SplitString(vbuf, '-');

        for (ip = list; ip != NULL; ip = ip->next)
        {
            EvalContextClassPutHard(ctx, ip->name, "inventory,attribute_name=none,source=agent");
        }

        DeleteItemList(list);
    }
    else
    {
        for (int version = 9; version < 13; version++)
        {
            snprintf(vbuf, CF_BUFSIZE, "%s %d ", SUSE_SLES_ID, version);
            Log(LOG_LEVEL_DEBUG, "Checking for SUSE [%s]", vbuf);

            if (!strncmp(relstring, vbuf, strlen(vbuf)))
            {
                snprintf(classbuf, CF_MAXVARSIZE, "SLES%d", version);
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
            }
            else
            {
                snprintf(vbuf, CF_BUFSIZE, "%s %d ", SUSE_SLED_ID, version);
                Log(LOG_LEVEL_DEBUG, "Checking for SUSE [%s]", vbuf);

                if (!strncmp(relstring, vbuf, strlen(vbuf)))
                {
                    snprintf(classbuf, CF_MAXVARSIZE, "SLED%d", version);
                    EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
                }
            }
        }
    }

    /* Determine release version. We assume that the version follows
     * the string "SuSE Linux" or "SUSE LINUX".
     */

    char *release = strstr(relstring, SUSE_RELEASE_FLAG);
    if (release == NULL)
    {
        release = strstr(relstring, "opensuse");
        if (release == NULL)
        {
            release = strversion;
        }
    }

    if (release == NULL)
    {
        Log(LOG_LEVEL_VERBOSE,
            "Could not find a numeric OS release in %s",
            SUSE_REL_FILENAME);
        return 2;
    }
    else
    {
        char strmajor[CF_MAXVARSIZE], strminor[CF_MAXVARSIZE];
        if (strchr(release, '.'))
        {
            sscanf(release, "%*s %d.%d", &major, &minor);
            xsnprintf(strmajor, sizeof(strmajor), "%d", major);
            xsnprintf(strminor, sizeof(strminor), "%d", minor);

            if (major != -1 && minor != -1)
            {
                strcpy(classbuf, "SUSE");
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
                strcat(classbuf, "_");
                strcat(classbuf, strmajor);
                SetFlavor(ctx, classbuf);
                strcat(classbuf, "_");
                strcat(classbuf, strminor);
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");

                /* The correct spelling for SUSE is "SUSE" but CFEngine used to use "SuSE".
                 * Keep this for backwards compatibility until CFEngine 3.7
                 */
                strcpy(classbuf, "SuSE");
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
                strcat(classbuf, "_");
                strcat(classbuf, strmajor);
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
                strcat(classbuf, "_");
                strcat(classbuf, strminor);
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");

                Log(LOG_LEVEL_VERBOSE, "Discovered SUSE version %s", classbuf);
                return 0;
            }
        }
        else
        {
            nt_static_assert((sizeof(strmajor)) > 255);
            nt_static_assert((sizeof(strminor)) > 255);
            sscanf(strversion, "VERSION = %255s", strmajor);
            sscanf(strpatch, "PATCHLEVEL = %255s", strminor);

            if (major != -1 && minor != -1)
            {
                strcpy(classbuf, "SLES");
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
                strcat(classbuf, "_");
                strcat(classbuf, strmajor);
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
                strcat(classbuf, "_");
                strcat(classbuf, strminor);
                EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");

                snprintf(classbuf, CF_MAXVARSIZE, "SUSE_%d", major);
                SetFlavor(ctx, classbuf);

                /* The correct spelling for SUSE is "SUSE" but CFEngine used to use "SuSE".
                 * Keep this for backwards compatibility until CFEngine 3.7
                 */
                snprintf(classbuf, CF_MAXVARSIZE, "SuSE_%d", major);
                EvalContextClassPutHard(ctx, classbuf, "source=agent");

                Log(LOG_LEVEL_VERBOSE, "Discovered SUSE version %s", classbuf);
                return 0;
            }
        }
    }

    Log(LOG_LEVEL_VERBOSE, "Could not find a numeric OS release in %s", SUSE_REL_FILENAME);

    return 0;
}

/******************************************************************/

static int Linux_Slackware_Version(EvalContext *ctx, char *filename)
{
    int major = -1;
    int minor = -1;
    int release = -1;
    char classname[CF_MAXVARSIZE] = "";
    char buffer[CF_MAXVARSIZE];

    Log(LOG_LEVEL_VERBOSE, "This appears to be a slackware system.");
    EvalContextClassPutHard(ctx, "slackware", "inventory,attribute_name=none,source=agent");

    if (!ReadLine(filename, buffer, sizeof(buffer)))
    {
        return 1;
    }

    Log(LOG_LEVEL_VERBOSE, "Looking for Slackware version...");
    switch (sscanf(buffer, "Slackware %d.%d.%d", &major, &minor, &release))
    {
    case 3:
        Log(LOG_LEVEL_VERBOSE, "This appears to be a Slackware %u.%u.%u system.", major, minor, release);
        snprintf(classname, CF_MAXVARSIZE, "slackware_%u_%u_%u", major, minor, release);
        EvalContextClassPutHard(ctx, classname, "inventory,attribute_name=none,source=agent");
        /* Fall-through */
    case 2:
        Log(LOG_LEVEL_VERBOSE, "This appears to be a Slackware %u.%u system.", major, minor);
        snprintf(classname, CF_MAXVARSIZE, "slackware_%u_%u", major, minor);
        EvalContextClassPutHard(ctx, classname, "inventory,attribute_name=none,source=agent");
        /* Fall-through */
    case 1:
        Log(LOG_LEVEL_VERBOSE, "This appears to be a Slackware %u system.", major);
        snprintf(classname, CF_MAXVARSIZE, "slackware_%u", major);
        EvalContextClassPutHard(ctx, classname, "inventory,attribute_name=none,source=agent");
        break;
    case 0:
        Log(LOG_LEVEL_VERBOSE, "No Slackware version number found.");
        return 2;
    }
    return 0;
}

/*
 * @brief Purge /etc/issue escapes on debian
 *
 * On debian, /etc/issue can include special characters escaped with
 * '\\' or '@'. This function removes such escape sequences.
 *
 * @param[in,out] buffer: string to be sanitized
 */
static void LinuxDebianSanitizeIssue(char *buffer)
{
    bool escaped = false;
    char *dst = buffer, *src = buffer, *tail = dst;
    while (*src != '\0')
    {
        char here = *src;
        src++;
        if (here == '\\' || here == '@' || escaped)
        {
            /* Skip over escapes and the character each acts on. */
            escaped = !escaped;
        }
        else
        {
            /* Copy everything else verbatim: */
            *dst = here;
            dst++;
            /* Keep track of (just after) last non-space: */
            if (!isspace(here))
            {
                tail = dst;
            }
        }
    }

    assert(tail == dst || isspace(*tail));
    *tail = '\0';
}

/******************************************************************/

static int Linux_Misc_Version(EvalContext *ctx)
{
    char flavor[CF_MAXVARSIZE];
    char version[256];
    char buffer[CF_BUFSIZE];

    const char *os = NULL;
    version[0] = '\0';

    FILE *fp = safe_fopen(LSB_RELEASE_FILENAME, "r");
    if (fp != NULL)
    {
        while (!feof(fp))
        {
            if (fgets(buffer, CF_BUFSIZE, fp) == NULL)
            {
                if (ferror(fp))
                {
                    break;
                }
                continue;
            }

            if (strstr(buffer, "Cumulus"))
            {
                EvalContextClassPutHard(ctx, "cumulus", "inventory,attribute_name=none,source=agent");
                os = "cumulus";
            }

            char *sp = strstr(buffer, "DISTRIB_RELEASE=");
            if (sp)
            {
                version[0] = '\0';
                nt_static_assert((sizeof(version)) > 255);
                sscanf(sp + strlen("DISTRIB_RELEASE="), "%255[^\n]", version);
                CanonifyNameInPlace(version);
            }
        }
        fclose(fp);
    }

    if (os != NULL && version[0] != '\0')
    {
        snprintf(flavor, CF_MAXVARSIZE, "%s_%s", os, version);
        SetFlavor(ctx, flavor);
        return 1;
    }

    return 0;
}

/******************************************************************/

static int Linux_Debian_Version(EvalContext *ctx)
{
    int major = -1;
    int release = -1;
    int result;
    char classname[CF_MAXVARSIZE], buffer[CF_MAXVARSIZE], os[CF_MAXVARSIZE];
    char version[256]; // Size must agree with sscanfs below

    Log(LOG_LEVEL_VERBOSE, "This appears to be a debian system.");
    EvalContextClassPutHard(
        ctx,
        "debian",
        "inventory,attribute_name=none,source=agent,derived-from-file="DEBIAN_VERSION_FILENAME);

    buffer[0] = classname[0] = '\0';

    Log(LOG_LEVEL_VERBOSE, "Looking for Debian version...");

    if (!ReadLine(DEBIAN_VERSION_FILENAME, buffer, sizeof(buffer)))
    {
        return 1;
    }

    result = sscanf(buffer, "%d.%d", &major, &release);

    switch (result)
    {
    case 2:
        Log(LOG_LEVEL_VERBOSE, "This appears to be a Debian %u.%u system.", major, release);
        snprintf(classname, CF_MAXVARSIZE, "debian_%u_%u", major, release);
        EvalContextClassPutHard(
            ctx,
            classname,
            "inventory,attribute_name=none,source=agent,derived-from-file="DEBIAN_VERSION_FILENAME);
        snprintf(classname, CF_MAXVARSIZE, "debian_%u", major);
        SetFlavor(ctx, classname);
        break;

    case 1:
        Log(LOG_LEVEL_VERBOSE, "This appears to be a Debian %u system.", major);
        snprintf(classname, CF_MAXVARSIZE, "debian_%u", major);
        SetFlavor(ctx, classname);
        break;

    default:
        version[0] = '\0';
        nt_static_assert((sizeof(version)) > 25);
        sscanf(buffer, "%25[^/]", version);
        if (strlen(version) > 0)
        {
            snprintf(classname, CF_MAXVARSIZE, "debian_%s", version);
            EvalContextClassPutHard(
                ctx,
                classname,
                "inventory,attribute_name=none,source=agent,derived-from-file="DEBIAN_VERSION_FILENAME);
        }
        break;
    }

    if (!ReadLine(DEBIAN_ISSUE_FILENAME, buffer, sizeof(buffer)))
    {
        return 1;
    }

    os[0] = '\0';
    nt_static_assert((sizeof(os)) > 250);
    sscanf(buffer, "%250s", os);

    if (strcmp(os, "Debian") == 0)
    {
        LinuxDebianSanitizeIssue(buffer);
        nt_static_assert((sizeof(version)) > 255);
        sscanf(buffer, "%*s %*s %255[^./]", version);
        snprintf(buffer, CF_MAXVARSIZE, "debian_%s", version);
        EvalContextClassPutHard(
            ctx,
            "debian",
            "inventory,attribute_name=none,source=agent,derived-from-file="DEBIAN_ISSUE_FILENAME);
        SetFlavor(ctx, buffer);
    }
    else if (strcmp(os, "Ubuntu") == 0)
    {
        LinuxDebianSanitizeIssue(buffer);
        char minor[256] = {0};
        nt_static_assert((sizeof(version)) > 255);
        sscanf(buffer, "%*s %255[^.].%255s", version, minor);
        snprintf(buffer, CF_MAXVARSIZE, "ubuntu_%s", version);
        SetFlavor(ctx, buffer);
        EvalContextClassPutHard(
            ctx,
            "ubuntu",
            "inventory,attribute_name=none,source=agent,derived-from-file="DEBIAN_ISSUE_FILENAME);
        if (release >= 0)
        {
            snprintf(buffer, CF_MAXVARSIZE, "ubuntu_%s_%s", version, minor);
            EvalContextClassPutHard(
                ctx,
                buffer,
                "inventory,attribute_name=none,source=agent,derived-from-file="DEBIAN_ISSUE_FILENAME);
        }
    }

    return 0;
}

/******************************************************************/

static int Linux_Mandrake_Version(EvalContext *ctx)
{
/* We are looking for one of the following strings... */
#define MANDRAKE_ID "Linux Mandrake"
#define MANDRAKE_REV_ID "Mandrake Linux"
#define MANDRAKE_10_1_ID "Mandrakelinux"

#define MANDRAKE_REL_FILENAME "/etc/mandrake-release"

    char relstring[CF_MAXVARSIZE];
    char *vendor = NULL;

    Log(LOG_LEVEL_VERBOSE, "This appears to be a mandrake system.");
    EvalContextClassPutHard(ctx, "Mandrake", "inventory,attribute_name=none,source=agent");

    if (!ReadLine(MANDRAKE_REL_FILENAME, relstring, sizeof(relstring)))
    {
        return 1;
    }

    Log(LOG_LEVEL_VERBOSE, "Looking for Mandrake linux info in '%s'", relstring);

/* Older Mandrakes had the 'Mandrake Linux' string in reverse order */

    if (!strncmp(relstring, MANDRAKE_ID, strlen(MANDRAKE_ID)))
    {
        vendor = "mandrake";
    }
    else if (!strncmp(relstring, MANDRAKE_REV_ID, strlen(MANDRAKE_REV_ID)))
    {
        vendor = "mandrake";
    }

    else if (!strncmp(relstring, MANDRAKE_10_1_ID, strlen(MANDRAKE_10_1_ID)))
    {
        vendor = "mandrake";
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "Could not identify OS distro from %s", MANDRAKE_REL_FILENAME);
        return 2;
    }

    return Linux_Mandriva_Version_Real(ctx, MANDRAKE_REL_FILENAME, relstring, vendor);
}

/******************************************************************/

static int Linux_Mandriva_Version(EvalContext *ctx)
{
/* We are looking for the following strings... */
#define MANDRIVA_ID "Mandriva Linux"

#define MANDRIVA_REL_FILENAME "/etc/mandriva-release"

    char relstring[CF_MAXVARSIZE];
    char *vendor = NULL;

    Log(LOG_LEVEL_VERBOSE, "This appears to be a mandriva system.");
    EvalContextClassPutHard(ctx, "Mandrake", "inventory,attribute_name=none,source=agent");
    EvalContextClassPutHard(ctx, "Mandriva", "inventory,attribute_name=none,source=agent");

    if (!ReadLine(MANDRIVA_REL_FILENAME, relstring, sizeof(relstring)))
    {
        return 1;
    }

    Log(LOG_LEVEL_VERBOSE, "Looking for Mandriva linux info in '%s'", relstring);

    if (!strncmp(relstring, MANDRIVA_ID, strlen(MANDRIVA_ID)))
    {
        vendor = "mandriva";
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "Could not identify OS distro from '%s'", MANDRIVA_REL_FILENAME);
        return 2;
    }

    return Linux_Mandriva_Version_Real(ctx, MANDRIVA_REL_FILENAME, relstring, vendor);

}

/******************************************************************/

static int Linux_Mandriva_Version_Real(EvalContext *ctx, char *filename, char *relstring, char *vendor)
{
    int major = -1, minor = -1;
    char strmajor[PRINTSIZE(major)], strminor[PRINTSIZE(minor)];

#define RELEASE_FLAG "release "
    char *release = strstr(relstring, RELEASE_FLAG);
    if (release == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "Could not find a numeric OS release in %s", filename);
        return 2;
    }
    else
    {
        release += strlen(RELEASE_FLAG);
        if (sscanf(release, "%d.%d", &major, &minor) == 2)
        {
            xsnprintf(strmajor, sizeof(strmajor), "%d", major);
            xsnprintf(strminor, sizeof(strminor), "%d", minor);
        }
        else
        {
            Log(LOG_LEVEL_VERBOSE, "Could not break down release version numbers in %s", filename);
        }
    }

    if (major != -1 && minor != -1 && strcmp(vendor, ""))
    {
        char classbuf[CF_MAXVARSIZE];
        classbuf[0] = '\0';
        strcat(classbuf, vendor);
        EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
        strcat(classbuf, "_");
        strcat(classbuf, strmajor);
        EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
        if (minor != -2)
        {
            strcat(classbuf, "_");
            strcat(classbuf, strminor);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
        }
    }

    return 0;
}

/******************************************************************/

static void Linux_Amazon_Version(EvalContext *ctx)
{
    char buffer[CF_BUFSIZE];

    // Amazon Linux release 2 (Karoo)

    if (ReadLine("/etc/system-release", buffer, sizeof(buffer)))
    {
        if (strstr(buffer, "Amazon") != NULL)
        {
            EvalContextClassPutHard(ctx, "amazon_linux",
                "inventory,attribute_name=none,source=agent"
                ",derived-from-file=/etc/system-release");

            char version[128];
            if (sscanf(buffer, "%*s %*s %*s %127s", version) == 1)
            {
                char class[CF_MAXVARSIZE];

                CanonifyNameInPlace(version);
                snprintf(class, sizeof(class), "amazon_linux_%s", version);
                EvalContextClassPutHard(ctx, class,
                    "inventory,attribute_name=none,source=agent"
                    ",derived-from-file=/etc/system-release");
                SetFlavor(ctx, class);
            }
            else
            {
                SetFlavor(ctx, "amazon_linux");
            }
            // We set this class for backwards compatibility
            EvalContextClassPutHard(ctx, "AmazonLinux",
                    "inventory,attribute_name=none,source=agent,"
                    "derived-from=sys.flavor");
        }
    }
}

/******************************************************************/

static void Linux_Alpine_Version(EvalContext *ctx)
{
    char buffer[CF_BUFSIZE];

    Log(LOG_LEVEL_VERBOSE, "This appears to be an AlpineLinux system.");

    EvalContextClassPutHard(ctx, "alpine_linux",
        "inventory,attribute_name=none,source=agent"
        ",derived-from-file=/etc/alpine-release");

    if (ReadLine("/etc/alpine-release", buffer, sizeof(buffer)))
    {
        char version[128];
        if (sscanf(buffer, "%127s", version) == 1)
        {
            char class[CF_MAXVARSIZE];
            CanonifyNameInPlace(version);
            snprintf(class, sizeof(class), "alpine_linux_%s", version);
            EvalContextClassPutHard(ctx, class,
                "inventory,attribute_name=none,source=agent"
                ",derived-from-file=/etc/alpine-release");
        }
    }
    SetFlavor(ctx, "alpinelinux");
}

/******************************************************************/

static int EOS_Version(EvalContext *ctx)

{
    char buffer[CF_BUFSIZE];

 // e.g. Arista Networks EOS 4.10.2

    if (ReadLine("/etc/Eos-release", buffer, sizeof(buffer)))
    {
        if (strstr(buffer, "EOS"))
        {
            char version[256], class[CF_MAXVARSIZE];
            EvalContextClassPutHard(ctx, "eos", "inventory,attribute_name=none,source=agent");
            EvalContextClassPutHard(ctx, "arista", "source=agent");
            version[0] = '\0';
            sscanf(buffer, "%*s %*s %*s %255s", version);
            CanonifyNameInPlace(version);
            snprintf(class, CF_MAXVARSIZE, "eos_%s", version);
            EvalContextClassPutHard(ctx, class, "inventory,attribute_name=none,source=agent");
        }
    }

    return 0;
}

/******************************************************************/

static int MiscOS(EvalContext *ctx)

{ char buffer[CF_BUFSIZE];

 // e.g. BIG-IP 10.1.0 Build 3341.1084

    if (ReadLine("/etc/issue", buffer, sizeof(buffer)))
    {
       if (strstr(buffer, "BIG-IP"))
       {
           char version[256], build[256], class[CF_MAXVARSIZE];
           EvalContextClassPutHard(ctx, "big_ip", "inventory,attribute_name=none,source=agent");
           sscanf(buffer, "%*s %255s %*s %255s", version, build);
           CanonifyNameInPlace(version);
           CanonifyNameInPlace(build);
           snprintf(class, CF_MAXVARSIZE, "big_ip_%s", version);
           EvalContextClassPutHard(ctx, class, "inventory,attribute_name=none,source=agent");
           snprintf(class, CF_MAXVARSIZE, "big_ip_%s_%s", version, build);
           EvalContextClassPutHard(ctx, class, "inventory,attribute_name=none,source=agent");
           SetFlavor(ctx, "BIG-IP");
       }
    }

    return 0;
}

/******************************************************************/

static int VM_Version(EvalContext *ctx)
{
    char *sp, buffer[CF_BUFSIZE], classbuf[CF_BUFSIZE], version[256];
    int major, minor, bug;
    int sufficient = 0;

    Log(LOG_LEVEL_VERBOSE, "This appears to be a VMware Server ESX/xSX system.");
    EvalContextClassPutHard(ctx, "VMware", "inventory,attribute_name=Virtual host,source=agent");

/* VMware Server ESX >= 3 has version info in /proc */
    if (ReadLine("/proc/vmware/version", buffer, sizeof(buffer)))
    {
        if (sscanf(buffer, "VMware ESX Server %d.%d.%d", &major, &minor, &bug) > 0)
        {
            snprintf(classbuf, CF_BUFSIZE, "VMware ESX Server %d", major);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
            snprintf(classbuf, CF_BUFSIZE, "VMware ESX Server %d.%d", major, minor);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
            snprintf(classbuf, CF_BUFSIZE, "VMware ESX Server %d.%d.%d", major, minor, bug);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
            sufficient = 1;
        }
        else if (sscanf(buffer, "VMware ESX Server %255s", version) > 0)
        {
            snprintf(classbuf, CF_BUFSIZE, "VMware ESX Server %s", version);
            EvalContextClassPutHard(ctx, classbuf, "inventory,attribute_name=none,source=agent");
            sufficient = 1;
        }
    }

/* Fall back to checking for other files */

    if (sufficient < 1 && (ReadLine("/etc/vmware-release", buffer, sizeof(buffer))
                           || ReadLine("/etc/issue", buffer, sizeof(buffer))))
    {
        EvalContextClassPutHard(ctx, buffer, "inventory,attribute_name=none,source=agent");

        /* Strip off the release code name e.g. "(Dali)" */
        if ((sp = strchr(buffer, '(')) != NULL)
        {
            *sp = 0;
            Chop(buffer, CF_EXPANDSIZE);
            EvalContextClassPutHard(ctx, buffer, "inventory,attribute_name=none,source=agent");
        }
        sufficient = 1;
    }

    return sufficient < 1 ? 1 : 0;
}

/******************************************************************/

static int Xen_Domain(EvalContext *ctx)
{
    int sufficient = 0;

    Log(LOG_LEVEL_VERBOSE, "This appears to be a xen pv system.");
    EvalContextClassPutHard(ctx, "xen", "inventory,attribute_name=Virtual host,source=agent");

/* xen host will have "control_d" in /proc/xen/capabilities, xen guest will not */

    FILE *fp = safe_fopen("/proc/xen/capabilities", "r");
    if (fp != NULL)
    {
        size_t buffer_size = CF_BUFSIZE;
        char *buffer = xmalloc(buffer_size);

        for (;;)
        {
            ssize_t res = CfReadLine(&buffer, &buffer_size, fp);
            if (res == -1)
            {
                if (!feof(fp))
                {
                    /* Failure reading Xen capabilites. Do we care? */
                    fclose(fp);
                    free(buffer);
                    return 1;
                }
                else
                {
                    break;
                }
            }

            if (strstr(buffer, "control_d"))
            {
                EvalContextClassPutHard(ctx, "xen_dom0", "inventory,attribute_name=Virtual host,source=agent");
                sufficient = 1;
            }
        }

        if (!sufficient)
        {
            EvalContextClassPutHard(ctx, "xen_domu_pv", "inventory,attribute_name=Virtual host,source=agent");
            sufficient = 1;
        }

        fclose(fp);
        free(buffer);
    }

    return sufficient < 1 ? 1 : 0;
}

/******************************************************************/
static void OpenVZ_Detect(EvalContext *ctx)
{
/* paths to file defining the type of vm (guest or host) */
#define OPENVZ_HOST_FILENAME "/proc/bc/0"
#define OPENVZ_GUEST_FILENAME "/proc/vz"
/* path to the vzps binary */
#define OPENVZ_VZPS_FILE "/bin/vzps"
    struct stat statbuf;

    /* The file /proc/bc/0 is present on host
       The file /proc/vz is present on guest
       If the host has /bin/vzps, we should use it for checking processes
    */

    if (stat(OPENVZ_HOST_FILENAME, &statbuf) != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "This appears to be an OpenVZ/Virtuozzo/Parallels Cloud Server host system.\n");
        EvalContextClassPutHard(ctx, "virt_host_vz", "inventory,attribute_name=Virtual host,source=agent");
        /* if the file /bin/vzps is there, it is safe to use the processes promise type */
        if (stat(OPENVZ_VZPS_FILE, &statbuf) != -1)
        {
            EvalContextClassPutHard(ctx, "virt_host_vz_vzps", "inventory,attribute_name=Virtual host,source=agent");
            /* here we must redefine the value of VPSHARDCLASS */
            for (int i = 0; i < PLATFORM_CONTEXT_MAX; i++)
            {
                if (!strcmp(CLASSATTRIBUTES[i][0], "virt_host_vz_vzps"))
                {
                   VPSHARDCLASS = (PlatformContext) i;
                   break;
                }
            }
        }
        else
        {
            Log(LOG_LEVEL_NOTICE, "This OpenVZ/Virtuozzo/Parallels Cloud Server host system does not have vzps installed; the processes promise type may not work as expected.\n");
        }
    }
    else if (stat(OPENVZ_GUEST_FILENAME, &statbuf) != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "This appears to be an OpenVZ/Virtuozzo/Parallels Cloud Server guest system.\n");
        EvalContextClassPutHard(ctx, "virt_guest_vz", "inventory,attribute_name=Virtual host,source=agent");
    }
}

/******************************************************************/

static bool ReadLine(const char *filename, char *buf, int bufsize)
{
    FILE *fp = ReadFirstLine(filename, buf, bufsize);

    if (fp == NULL)
    {
        return false;
    }
    else
    {
        fclose(fp);
        return true;
    }
}

static FILE *ReadFirstLine(const char *filename, char *buf, int bufsize)
{
    FILE *fp = safe_fopen(filename, "r");

    if (fp == NULL)
    {
        return NULL;
    }

    if (fgets(buf, bufsize, fp) == NULL)
    {
        fclose(fp);
        return NULL;
    }

    StripTrailingNewline(buf, CF_EXPANDSIZE);

    return fp;
}
#endif /* __linux__ */

/******************************************************************/

#ifdef XEN_CPUID_SUPPORT

/* Borrowed and modified from Xen source/tools/libxc/xc_cpuid_x86.c */

static void Xen_Cpuid(uint32_t idx, uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx)
{
# ifdef __i386__
    /* On i386, %ebx register needs to be saved before usage and restored
     * thereafter for PIC-compliant code on i386. */
    asm("push %%ebx; cpuid; mov %%ebx,%1; pop %%ebx"
        : "=a"(*eax), "=r"(*ebx), "=c"(*ecx), "=d"(*edx)
        : "0" (idx),  "2" (0) );
# else
    asm("cpuid"
        : "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
        : "0" (idx),  "2" (0) );
# endif
}

/******************************************************************/

static bool Xen_Hv_Check(void)
{
    /* CPUID interface to Xen from arch-x86/cpuid.h:
     * Leaf 1 (0x40000000)
     * EAX: Largest Xen-information leaf. All leaves up to an including @EAX
     *   are supported by the Xen host.
     * EBX-EDX: "XenVMMXenVMM" signature, allowing positive identification
     *   of a Xen host.
     *
     * Additional information can be found in the Hypervisor CPUID
     * Interface Proposal (https://lkml.org/lkml/2008/10/1/246)
     */

    uint32_t eax, base;
    union
    {
        uint32_t u[3];
        char     s[13];
    } sig = {{0}};

    /*
     * For compatibility with other hypervisor interfaces, the Xen cpuid leaves
     * can be found at the first otherwise unused 0x100 aligned boundary starting
     * from 0x40000000.
     *
     * e.g If viridian extensions are enabled for an HVM domain, the Xen cpuid
     * leaves will start at 0x40000100
     */
    for (base = 0x40000000; base < 0x40010000; base += 0x100)
    {
        Xen_Cpuid(base, &eax, &sig.u[0], &sig.u[1], &sig.u[2]);

        if (memcmp("XenVMMXenVMM", &sig.s[0], 12) == 0)
        {
            /* The highest basic calling parameter (largest value that EAX can
             * be set to before calling CPUID) is returned in EAX. */
            if ((eax - base) < 2)
            {
                Log(LOG_LEVEL_DEBUG,
                    "Insufficient Xen CPUID Leaves (eax=%x at base %x)",
                    eax, base);
                return false;
            }
            Log(LOG_LEVEL_DEBUG,
                "Found Xen CPUID Leaf (eax=%x at base %x)", eax, base);
            return true;
        }
    }

    return false;
}

#endif /* XEN_CPUID_SUPPORT */

static void GetCPUInfo(EvalContext *ctx)
{
#if defined(MINGW) || defined(NT)
    Log(LOG_LEVEL_VERBOSE, "!! cpu count not implemented on Windows platform");
    return;
#else
    int count = 0;

    // http://preview.tinyurl.com/c9l2sh - StackOverflow on cross-platform CPU counting
#if defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
    // Linux, AIX, Solaris, Darwin >= 10.4
    count = (int)sysconf(_SC_NPROCESSORS_ONLN);
#endif

#if defined(HAVE_SYS_SYSCTL_H) && defined(HW_NCPU)
    // BSD-derived platforms
    int mib[2] = { CTL_HW, HW_NCPU };
    size_t len;

    len = sizeof(count);
    if(sysctl(mib, 2, &count, &len, NULL, 0) < 0)
    {
        Log(LOG_LEVEL_ERR, "!! failed to get cpu count: %s", strerror(errno));
    }
#endif

#ifdef HAVE_SYS_MPCTL_H
// Itanium processors have Intel Hyper-Threading virtual-core capability,
// and the MPC_GETNUMCORES_SYS operation counts each HT virtual core,
// which is equivalent to what the /proc/stat scan delivers for Linux.
//
// A build on 11i v3 PA would have the GETNUMCORES define, but if run on an
// 11i v1 system it would fail since that OS release has only GETNUMSPUS.
// So in the presence of GETNUMCORES, we check for an invalid arg error
// and fall back to GETNUMSPUS if necessary. An 11i v1 build would work
// normally on 11i v3, because on PA-RISC cores == spus since there's no
// HT on PA-RISC, and 11i v1 only runs on PA-RISC.
# ifdef MPC_GETNUMCORES_SYS
    count = mpctl(MPC_GETNUMCORES_SYS, 0, 0);
    if (count == -1 && errno == EINVAL)
    {
        count = mpctl(MPC_GETNUMSPUS_SYS, 0, 0);
    }
# else
    count = mpctl(MPC_GETNUMSPUS_SYS, 0, 0);	// PA-RISC processor count
# endif
#endif /* HAVE_SYS_MPCTL_H */

    if (count < 1)
    {
        Log(LOG_LEVEL_VERBOSE, "invalid processor count: %d", count);
        return;
    }
    Log(LOG_LEVEL_VERBOSE, "Found %d processor%s", count, count > 1 ? "s" : "");

    char buf[CF_SMALLBUF] = "1_cpu";
    if (count == 1)
    {
        EvalContextClassPutHard(ctx, buf, "source=agent,derived-from=sys.cpus");  // "1_cpu" from init - change if buf is ever used above
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cpus", "1", CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=CPU logical cores");
    }
    else
    {
        snprintf(buf, CF_SMALLBUF, "%d_cpus", count);
        EvalContextClassPutHard(ctx, buf, "source=agent,derived-from=sys.cpus");
        snprintf(buf, CF_SMALLBUF, "%d", count);
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "cpus", buf, CF_DATA_TYPE_STRING, "inventory,source=agent,attribute_name=CPU logical cores");
    }
#endif /* MINGW || NT */
}

/******************************************************************/

// Implemented in Windows specific section.
#ifndef __MINGW32__

/**
   Return the number of seconds the system has been online given the current
   time() as an argument, or return -1 if unavailable or unimplemented.
*/
int GetUptimeSeconds(time_t now)
{
    time_t boot_time = 0;
    errno = 0;

#if defined(BOOT_TIME_WITH_SYSINFO)         // Most GNU, Linux platforms

    struct sysinfo s;
    if (sysinfo(&s) == 0)
    {
       // Don't return yet, sanity checking below
       boot_time = now - s.uptime;
    }

#elif defined(BOOT_TIME_WITH_KSTAT)         // Solaris platform

    /* From command line you can get this with:
       kstat -p unix:0:system_misc:boot_time */
    kstat_ctl_t *kc = kstat_open();
    if(kc != 0)
    {
        kstat_t *kp = kstat_lookup(kc, "unix", 0, "system_misc");
        if(kp != 0)
        {
            if (kstat_read(kc, kp, NULL) != -1)
            {
                kstat_named_t *knp = kstat_data_lookup(kp, "boot_time");
                if (knp != NULL)
                {
                    boot_time = knp->value.ui32;
                }
            }
        }
        kstat_close(kc);
    }

#elif defined(BOOT_TIME_WITH_PSTAT_GETPROC) // HP-UX platform only

    struct pst_status p;
    if (pstat_getproc(&p, sizeof(p), 0, 1) == 1)
    {
        boot_time = (time_t)p.pst_start;
    }

#elif defined(BOOT_TIME_WITH_SYSCTL)        // BSD-derived platforms

    int mib[2] = { CTL_KERN, KERN_BOOTTIME };
    struct timeval boot;
    size_t len = sizeof(boot);
    if (sysctl(mib, 2, &boot, &len, NULL, 0) == 0)
    {
        boot_time = boot.tv_sec;
    }

#elif defined(BOOT_TIME_WITH_PROCFS)

    struct stat p;
    if (stat("/proc/1", &p) == 0)
    {
        boot_time = p.st_ctime;
    }

#elif defined(BOOT_TIME_WITH_UTMP)          /* SystemV, highly portable way */

    struct utmp query = { .ut_type = BOOT_TIME };
    struct utmp *result;
    setutent();
    result = getutid(&query);
    if (result != NULL)
    {
        boot_time = result->ut_time;
    }
    endutent();

#elif defined(BOOT_TIME_WITH_UTMPX)                            /* POSIX way */

    struct utmpx query = { .ut_type = BOOT_TIME };
    struct utmpx *result;
    setutxent();
    result = getutxid(&query);
    if (result != NULL)
    {
        boot_time = result->ut_tv.tv_sec;
    }
    endutxent();

#endif

    if(errno)
    {
        Log(LOG_LEVEL_VERBOSE, "boot time discovery error: %s", GetErrorStr());
    }

    if(boot_time > now || boot_time <= 0)
    {
        Log(LOG_LEVEL_VERBOSE, "invalid boot time found; trying uptime command");
        boot_time = GetBootTimeFromUptimeCommand(now);
    }

    return boot_time > 0 ? now - boot_time : -1;
}
#endif // !__MINGW32__

int GetUptimeMinutes(time_t now)
{
    return GetUptimeSeconds(now) / SECONDS_PER_MINUTE;
}

/******************************************************************/

// Last resort: parse the output of the uptime command with a PCRE regexp
// and convert the uptime to boot time using "now" argument.
//
// The regexp needs to match all variants of the uptime command's output.
// Solaris 8/9/10:  10:45am up 109 day(s), 19:56, 1 user, load average:
// HP-UX 11.11:   9:24am  up 1 min,  1 user,  load average:
//                8:23am  up 23 hrs,  0 users,  load average:
//                9:33am  up 2 days, 10 mins,  0 users,  load average:
//                11:23am  up 2 days, 2 hrs,  0 users,  load average:
// Red Hat Linux: 10:51:23 up 5 days, 19:54, 1 user, load average:
//
// UPTIME_BACKREFS must be set to this regexp's maximum backreference
// index number (i.e., the count of left-parentheses):
#define UPTIME_REGEXP " up (\\d+ day[^,]*,|) *(\\d+( ho?u?r|:(\\d+))|(\\d+) min)"
#define UPTIME_BACKREFS 5

static time_t GetBootTimeFromUptimeCommand(time_t now)
{
    FILE *uptimecmd;
    char *backref = NULL;
    const char *uptimepath = "/usr/bin/uptime";
    time_t uptime = 0;

    int err_code;
    size_t err_offset;
    pcre2_code *regex = pcre2_compile((PCRE2_SPTR) UPTIME_REGEXP, PCRE2_ZERO_TERMINATED, 0,
                                      &err_code, &err_offset, NULL);
    if (regex == NULL)
    {
        Log(LOG_LEVEL_DEBUG, "failed to compile regexp to parse uptime command");
        return(-1);
    }

    // Try "/usr/bin/uptime" first, then "/bin/uptime"
    uptimecmd = cf_popen(uptimepath, "r", false);
    uptimecmd = uptimecmd ? uptimecmd : cf_popen((uptimepath + 4), "r", false);
    if (!uptimecmd)
    {
        Log(LOG_LEVEL_ERR, "uptime failed: (cf_popen: %s)", GetErrorStr());
        pcre2_code_free(regex);
        return -1;
    }

    size_t uptime_output_size = CF_SMALLBUF;
    char *uptime_output = xmalloc(uptime_output_size);
    ssize_t n_read = CfReadLine(&uptime_output, &uptime_output_size, uptimecmd);

    cf_pclose(uptimecmd);
    if (n_read == -1 && !feof(uptimecmd))
    {
        Log(LOG_LEVEL_ERR, "Reading uptime output failed. (getline: '%s')", GetErrorStr());
        pcre2_code_free(regex);
        return -1;
    }

    pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(regex, NULL);
    if ((n_read > 0) &&
        (pcre2_match(regex, (PCRE2_SPTR) uptime_output, PCRE2_ZERO_TERMINATED,
                     0, 0, match_data, NULL) > 1))
    {
        size_t *ovector = pcre2_get_ovector_pointer(match_data);
        for (int i = 1; i <= UPTIME_BACKREFS ; i++)
        {
            if (ovector[i * 2 + 1] - ovector[i * 2] == 0) // strlen(backref)
            {
                continue;
            }
            backref = uptime_output + ovector[i * 2];
            // atoi() ignores non-digits, so no need to null-terminate backref

            time_t seconds;
            switch(i)
            {
                case 1: // Day
                    seconds = SECONDS_PER_DAY;
                    break;
                case 2: // Hour
                    seconds = SECONDS_PER_HOUR;
                    break;
                case 4: // Minute
                case 5:
                    seconds = SECONDS_PER_MINUTE;
                    break;
                default:
                    seconds = 0;
             }
             uptime += ((time_t) atoi(backref)) * seconds;
        }
    }
    else
    {
        Log(LOG_LEVEL_ERR, "uptime PCRE match failed: regexp: '%s', uptime: '%s'", UPTIME_REGEXP, uptime_output);
    }
    pcre2_match_data_free(match_data);
    pcre2_code_free(regex);
    Log(LOG_LEVEL_VERBOSE, "Reading boot time from uptime command successful.");
    return(uptime ? (now - uptime) : -1);
}

/*****************************************************************************/

/* TODO accept a const char * and move the ifdefs away from
 *      evalfunction.c:FnCallGetUserInfo() to here. */
JsonElement* GetUserInfo(const void *passwd)
{
#ifdef __MINGW32__
    return NULL;

#else /* !__MINGW32__ */

    // we lose the const to set pw if passwd is NULL
    struct passwd *pw = (struct passwd*) passwd;

    if (pw == NULL)
    {
        pw = getpwuid(getuid());
    }

    if (pw == NULL)
    {
        return NULL;
    }

    JsonElement *result = JsonObjectCreate(10);
    JsonObjectAppendString(result, "username", pw->pw_name);
    JsonObjectAppendString(result, "description", pw->pw_gecos);
    JsonObjectAppendString(result, "home_dir", pw->pw_dir);
    JsonObjectAppendString(result, "shell", pw->pw_shell);
    JsonObjectAppendInteger(result, "uid", pw->pw_uid);
    JsonObjectAppendInteger(result, "gid", pw->pw_gid);
    //JsonObjectAppendBool(result, "locked", IsAccountLocked(pw->pw_name, pw));
    // TODO: password: { format: "hash", data: { ...GetPasswordHash()... } }
    // TODO: group_primary: name of group
    // TODO: groups_secondary: [ names of groups ]
    // TODO: gids_secondary: [ gids of groups ]

    return result;
#endif
}

/*****************************************************************************/

void GetSysVars(EvalContext *ctx)
{
    /* Get info for current user. */
    JsonElement *info = GetUserInfo(NULL);
    if (info != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, "user_data",
                                      info, CF_DATA_TYPE_CONTAINER,
                                      "source=agent,user_info");
        JsonDestroy(info);
    }
}

/*****************************************************************************/

void GetDefVars(EvalContext *ctx)
{
    EvalContextVariablePutSpecial(
        ctx, SPECIAL_SCOPE_DEF, "jq",
        "jq --compact-output --monochrome-output --ascii-output --unbuffered --sort-keys",
        CF_DATA_TYPE_STRING, "invocation,source=agent,command_name=jq");
}

/*****************************************************************************/

static void SysOSNameHuman(EvalContext *ctx)
{
    // This function sets the $(sys.os_name_human) variable
    assert(ctx != NULL);
    const char *const lval = "os_name_human";

    /**
     * Order is important. The first if-statement is more specific and wins.
     * E.g. prefer Ubuntu over Debian.
     */
    if (EvalContextClassGet(ctx, NULL, "ubuntu") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Ubuntu", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=ubuntu");
    }
    else if (EvalContextClassGet(ctx, NULL, "debian") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Debian", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=debian");
    }
    else if (EvalContextClassGet(ctx, NULL, "centos") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "CentOS", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=centos");
    }
    else if (EvalContextClassGet(ctx, NULL, "fedora") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Fedora", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=fedora");
    }
    else if (EvalContextClassGet(ctx, NULL, "redhat") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "RHEL", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=redhat");
    }
    else if (EvalContextClassGet(ctx, NULL, "aix") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "AIX", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=aix");
    }
    else if (EvalContextClassGet(ctx, NULL, "hpux") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "HP-UX", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=hpux");
    }
    else if (EvalContextClassGet(ctx, NULL, "opensuse") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "OpenSUSE", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=opensuse");
    }
    else if (EvalContextClassGet(ctx, NULL, "suse") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "SUSE", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=suse");
    }
    else if (EvalContextClassGet(ctx, NULL, "macos") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "macOS", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=macos");
    }
    else if (EvalContextClassGet(ctx, NULL, "windows") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Windows", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=windows");
    }
    else if (EvalContextClassGet(ctx, NULL, "freebsd") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "FreeBSD", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=freebsd");
    }
    else if (EvalContextClassGet(ctx, NULL, "openbsd") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "OpenBSD", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=openbsd");
    }
    else if (EvalContextClassGet(ctx, NULL, "netbsd") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "NetBSD", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=netbsd");
    }
    else if (EvalContextClassGet(ctx, NULL, "solaris") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Solaris", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=solaris");
    }
    else if (EvalContextClassGet(ctx, NULL, "amazon_linux") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Amazon", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=amazon_linux");
    }
    else if (EvalContextClassGet(ctx, NULL, "arch") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Arch", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=arch");
    }
    else if (EvalContextClassGet(ctx, NULL, "postmarketos") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "postmarketOS", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=postmarketos");
    }
    else if (EvalContextClassGet(ctx, NULL, "alpine") != NULL)
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Alpine", CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=alpine");
    }
    else
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval,
                                      "Unknown", CF_DATA_TYPE_STRING,
                                      "source=agent");
        Log(LOG_LEVEL_WARNING,
            "Operating System not properly recognized, setting sys.os_name_human to \"Unknown\", please submit a bug report for us to fix this");
    }
}

/*****************************************************************************/

/**
 * Find next integer from string in place. Leading zero's are included.
 * 
 * @param [in]  str string to extract next integer from
 * @param [out] num pointer to start of next integer or %NULL if no integer
 *                  number was found
 * 
 * @return pointer to the remaining string in `str` or %NULL if no remainder
 * 
 * @note `str` will be mutated
 */
static char *FindNextInteger(char *str, char **num)
{
    if (str == NULL)
    {
        *num = NULL;
        return NULL;
    }

    char *ptr = str;
    while (*ptr != '\0' && !isdigit(*ptr))
    {
        ++ptr;
    }
    if (*ptr == '\0')
    {
        /* no integer found */
        *num = NULL;
        return NULL;
    }
    *num = ptr++;

    while (*ptr != '\0' && isdigit(*ptr))
    {
        ++ptr;
    }
    if (*ptr == '\0')
    {
        /* no remainder */
        return NULL;
    }
    *ptr++ = '\0';

    return ptr;
}

static void SysOsVersionMajor(EvalContext *ctx)
{
    const char *const_flavor = EvalContextVariableGetSpecialString(
        ctx, SPECIAL_SCOPE_SYS, "flavor");
    char *flavor = SafeStringDuplicate(const_flavor);

    char *major;
    char *next = FindNextInteger(flavor, &major);

    if (flavor != NULL)
    {
        if (StringStartsWith(const_flavor, "solaris") ||
            StringStartsWith(const_flavor, "sunos"))
        {
            /* In this case the major version comes second.
             * E.g. SunOS 5.11 where 11 is the major release number.
             * Thus, we need to get the next number.
             */
            FindNextInteger(next, &major);
        }
    }

    if (NULL_OR_EMPTY(major))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS,
                                      "os_version_major", "Unknown",
                                      CF_DATA_TYPE_STRING, "source=agent");
    }
    else
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, 
                                      "os_version_major", major, 
                                      CF_DATA_TYPE_STRING,
                                      "source=agent,derived-from=flavor");
    }

    free(flavor);
}

/*****************************************************************************/

void DetectEnvironment(EvalContext *ctx)
{
    GetNameInfo3(ctx);
    GetInterfacesInfo(ctx);
    GetNetworkingInfo(ctx);
    Get3Environment(ctx);
    BuiltinClasses(ctx);
    OSClasses(ctx);
    GetSysVars(ctx);
    GetDefVars(ctx);
    SysOSNameHuman(ctx);
    SysOsVersionMajor(ctx);
}