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

#include "config.h"
#include "common.h"
#include "nrpe.h"
#include "utils.h"
#include "acl.h"

#ifdef HAVE_SSL
# ifdef USE_SSL_DH
#  include "../include/dh.h"
# endif
#endif
#ifndef HAVE_ASPRINTF
extern int asprintf(char **ptr, const char *format, ...);
#endif

#ifdef HAVE_LIBWRAP
int       allow_severity = LOG_INFO;
int       deny_severity = LOG_WARNING;
# ifndef HAVE_RFC931_TIMEOUT
int       rfc931_timeout=15;
# endif
#endif

#ifdef HAVE_SSL
# if (defined(__sun) && defined(SOLARIS_10)) || defined(_AIX) || defined(__hpux)
SSL_METHOD *meth;
# else
const SSL_METHOD *meth;
# endif
SSL_CTX  *ctx;
int       use_ssl = TRUE;
#else
int       use_ssl = FALSE;
#endif

#define DEFAULT_COMMAND_TIMEOUT			60	/* default timeout for execution of plugins */
#define MAXFD							64
#define NASTY_METACHARS					"|`&><'\\[]{};\r\n"
#define MAX_LISTEN_SOCKS				16
#define DEFAULT_LISTEN_QUEUE_SIZE		5
#define DEFAULT_SSL_SHUTDOWN_TIMEOUT	15

#define how_many(x,y) (((x)+((y)-1))/(y))

extern int errno;
struct addrinfo *listen_addrs = NULL;
int       listen_socks[MAX_LISTEN_SOCKS];
char      remote_host[MAX_HOST_ADDRESS_LENGTH];
char     *macro_argv[MAX_COMMAND_ARGUMENTS];
char      config_file[MAX_INPUT_BUFFER] = "nrpe.cfg";
char      server_address[NI_MAXHOST] = "";
char     *command_name = NULL;
int       log_facility = LOG_DAEMON;
int       server_port = DEFAULT_SERVER_PORT;
int       num_listen_socks = 0;
int       address_family = AF_UNSPEC;
int       socket_timeout = DEFAULT_SOCKET_TIMEOUT;
int       command_timeout = DEFAULT_COMMAND_TIMEOUT;
int       connection_timeout = DEFAULT_CONNECTION_TIMEOUT;
int       ssl_shutdown_timeout = DEFAULT_SSL_SHUTDOWN_TIMEOUT;
char     *command_prefix = NULL;
int       packet_ver = 0;
command  *command_list = NULL;
char     *nrpe_user = NULL;
char     *nrpe_group = NULL;
char     *allowed_hosts = NULL;
char     *keep_env_vars = NULL;
char     *pid_file = NULL;
int       wrote_pid_file = FALSE;
int       allow_arguments = FALSE;
int       allow_bash_cmd_subst = FALSE;
int       allow_weak_random_seed = FALSE;
int       sigrestart = FALSE;
int       sigshutdown = FALSE;
int       show_help = FALSE;
int       show_license = FALSE;
int       show_version = FALSE;
int       use_inetd = TRUE;
int 	  commands_running = 0;
int       max_commands = 0;
int       debug = FALSE;
int       use_src = FALSE;		/* Define parameter for SRC option */
int       no_forking = FALSE;
int       listen_queue_size = DEFAULT_LISTEN_QUEUE_SIZE;
char     *nasty_metachars = NULL;
extern char *log_file;

/* SSL/TLS parameters */
typedef enum _SSL_VER {
	SSLv2 = 1, SSLv2_plus, SSLv3, SSLv3_plus, TLSv1,
	TLSv1_plus, TLSv1_1, TLSv1_1_plus, TLSv1_2, TLSv1_2_plus, TLSv1_3, TLSv1_3_plus
} SslVer;

typedef enum _CLNT_CERTS {
	ClntCerts_Unknown = 0, Ask_For_Cert = 1, Require_Cert = 2
} ClntCerts;

typedef enum _SSL_LOGGING {
	SSL_NoLogging = 0, SSL_LogStartup = 1, SSL_LogIpAddr = 2,
	SSL_LogVersion = 4, SSL_LogCipher = 8, SSL_LogIfClientCert = 16,
	SSL_LogCertDetails = 32
} SslLogging;

struct _SSL_PARMS {
	char     *cert_file;
	char     *cacert_file;
	char     *privatekey_file;
	char      cipher_list[MAX_FILENAME_LENGTH];
	SslVer    ssl_proto_ver;
	int       allowDH;
	ClntCerts client_certs;
	SslLogging log_opts;
} sslprm = {
#if OPENSSL_VERSION_NUMBER >= 0x10100000
NULL, NULL, NULL, "ALL:!MD5:@STRENGTH:@SECLEVEL=0", TLSv1_plus, TRUE, 0, SSL_NoLogging
#else
NULL, NULL, NULL, "ALL:!MD5:@STRENGTH", TLSv1_plus, TRUE, 0, SSL_NoLogging
#endif
};

#ifdef HAVE_SSL
static int verify_callback(int ok, X509_STORE_CTX * ctx);
static void my_disconnect_sighandler(int sig);
static void complete_SSL_shutdown(SSL *);
#endif

int disable_syslog = FALSE;

int main(int argc, char **argv)
{
	int       result = OK;
	int       x;
	uint32_t  y;
	char      buffer[MAX_INPUT_BUFFER];

	init();

	/* process command-line args */
	result = process_arguments(argc, argv);
	if (result != OK || show_help == TRUE || show_license == TRUE || show_version == TRUE)
		usage(result);

	/* make sure the config file uses an absolute path */
	if (config_file[0] != '/') {

		/* save the name of the config file */
		strncpy(buffer, config_file, sizeof(buffer));
		buffer[sizeof(buffer) - 1] = '\x0';

		/* get absolute path of current working directory */
		strcpy(config_file, "");
		if (getcwd(config_file, sizeof(config_file)) == NULL) {
			printf("ERROR: getcwd(): %s, bailing out...\n", strerror(errno));
			exit(STATE_CRITICAL);
		}

		/* append a forward slash */
		strncat(config_file, "/", sizeof(config_file) - 2);
		config_file[sizeof(config_file) - 1] = '\x0';

		/* append the config file to the path */
		strncat(config_file, buffer, sizeof(config_file) - strlen(config_file) - 1);
		config_file[sizeof(config_file) - 1] = '\x0';
	}

	/* read the config file */
	result = read_config_file(config_file);
	/* exit if there are errors... */
	if (result == ERROR) {
		logit(LOG_ERR, "Config file '%s' contained errors, aborting...", config_file);
		return STATE_CRITICAL;
	}

	if (!nasty_metachars)
		nasty_metachars = strdup(NASTY_METACHARS);

	/* initialize macros */
	for (x = 0; x < MAX_COMMAND_ARGUMENTS; x++)
		macro_argv[x] = NULL;

	init_ssl();

	/* if we're running under inetd... */
	if (use_inetd == TRUE)
		run_inetd();

	else if (use_src == TRUE || no_forking == TRUE)
		run_src();

	else
		run_daemon();

#ifdef HAVE_SSL
	if (use_ssl == TRUE)
		SSL_CTX_free(ctx);
#endif

	/* We are now running in daemon mode, or the connection handed over by inetd has
	   been completed, so the parent process exits */
	return STATE_OK;
}

int init(void)
{
	char     *env_string = NULL;
	int       result = OK;

	/* set some environment variables */
	asprintf(&env_string, "NRPE_MULTILINESUPPORT=1");
	putenv(env_string);
	asprintf(&env_string, "NRPE_PROGRAMVERSION=%s", PROGRAM_VERSION);
	putenv(env_string);

	/* open a connection to the syslog facility */
	/* facility name may be overridden later */
	get_log_facility(NRPE_LOG_FACILITY);
	openlog("nrpe", LOG_PID, log_facility);

	/* generate the CRC 32 table */
	generate_crc32_table();

	return result;
}

void init_ssl(void)
{
#ifdef HAVE_SSL
	DH            *dh;
	char          seedfile[FILENAME_MAX];
	char          errstr[120] = { "" };
	int           i, c, x, vrfy;
	unsigned long ssl_opts = SSL_OP_ALL | SSL_OP_SINGLE_DH_USE;

	if (use_ssl == FALSE) {
		if (debug == TRUE)
			logit(LOG_INFO, "INFO: SSL/TLS NOT initialized. Network encryption DISABLED.");
		return;
	}

#ifndef USE_SSL_DH
	ssl_opts = SSL_OP_ALL;
	sslprm.allowDH = 0;
#endif

	if (sslprm.log_opts & SSL_LogStartup)
		log_ssl_startup();

	/* initialize SSL */
	SSL_load_error_strings();
	SSL_library_init();
	ENGINE_load_builtin_engines();
	RAND_set_rand_engine(NULL);
 	ENGINE_register_all_complete();

	meth = SSLv23_server_method();

	/* use week random seed if necessary */
	if (allow_weak_random_seed && (RAND_status() == 0)) {
		if (RAND_file_name(seedfile, sizeof(seedfile) - 1))
			if (RAND_load_file(seedfile, -1))
				RAND_write_file(seedfile);

		if (RAND_status() == 0) {
			logit(LOG_ERR,
				   "Warning: SSL/TLS uses a weak random seed which is highly discouraged");
			srand(time(NULL));
			for (i = 0; i < 500 && RAND_status() == 0; i++) {
				for (c = 0; c < sizeof(seedfile); c += sizeof(int)) {
					*((int *)(seedfile + c)) = rand();
				}
				RAND_seed(seedfile, sizeof(seedfile));
			}
		}
	}

#if OPENSSL_VERSION_NUMBER >= 0x10100000

	meth = TLS_method();

#else		/* OPENSSL_VERSION_NUMBER >= 0x10100000 */

# ifndef OPENSSL_NO_SSL2
	if (sslprm.ssl_proto_ver == SSLv2)
		meth = SSLv2_server_method();
# endif
# ifndef OPENSSL_NO_SSL3
	if (sslprm.ssl_proto_ver == SSLv3)
		meth = SSLv3_server_method();
# endif
	if (sslprm.ssl_proto_ver == TLSv1)
		meth = TLSv1_server_method();
# ifdef SSL_TXT_TLSV1_1
	if (sslprm.ssl_proto_ver == TLSv1_1)
		meth = TLSv1_1_server_method();
#  ifdef SSL_TXT_TLSV1_2
	if (sslprm.ssl_proto_ver == TLSv1_2)
		meth = TLSv1_2_server_method();
#  ifdef SSL_TXT_TLSV1_3
	if (sslprm.ssl_proto_ver == TLSv1_3)
		meth = TLSv1_3_server_method();
#  endif	/* ifdef SSL_TXT_TLSV1_3 */
#  endif	/* ifdef SSL_TXT_TLSV1_2 */
# endif		/* SSL_TXT_TLSV1_1 */

#endif		/* OPENSSL_VERSION_NUMBER >= 0x10100000 */

	ctx = SSL_CTX_new(meth);
	if (ctx == NULL) {
		while ((x = ERR_get_error()) != 0) {
			ERR_error_string(x, errstr);
			logit(LOG_ERR, "Error: could not create SSL context : %s", errstr);
		}
		SSL_CTX_free(ctx);
		exit(STATE_CRITICAL);
	}

#if OPENSSL_VERSION_NUMBER >= 0x10100000

	SSL_CTX_set_max_proto_version(ctx, 0);

	switch(sslprm.ssl_proto_ver) {
		case TLSv1_3:
#if OPENSSL_VERSION_NUMBER >= 0x10101000
			SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
#endif
		case TLSv1_3_plus:
#if OPENSSL_VERSION_NUMBER >= 0x10101000
			SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
			break;
#endif

		case TLSv1_2:
			SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
		case TLSv1_2_plus:
			SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
			break;

		case TLSv1_1:
			SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION);
		case TLSv1_1_plus:
			SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
			break;

		case TLSv1:
			SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION);
		case TLSv1_plus:
			SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
			break;

		case SSLv3:
			SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION);
		case SSLv3_plus:
			SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
			break;
	}

#else		/* OPENSSL_VERSION_NUMBER >= 0x10100000 */

	switch(sslprm.ssl_proto_ver) {
		case SSLv2:
		case SSLv2_plus:
			break;
		case TLSv1_3:
		case TLSv1_3_plus:
#ifdef SSL_OP_NO_TLSv1_2
			ssl_opts |= SSL_OP_NO_TLSv1_2;
#endif
		case TLSv1_2:
		case TLSv1_2_plus:
			ssl_opts |= SSL_OP_NO_TLSv1_1;
		case TLSv1_1:
		case TLSv1_1_plus:
			ssl_opts |= SSL_OP_NO_TLSv1;
		case TLSv1:
		case TLSv1_plus:
			ssl_opts |= SSL_OP_NO_SSLv3;
		case SSLv3:
		case SSLv3_plus:
			ssl_opts |= SSL_OP_NO_SSLv2;
			break;
	}

#endif		/* OPENSSL_VERSION_NUMBER >= 0x10100000 */

	SSL_CTX_set_options(ctx, ssl_opts);

	if (sslprm.cert_file != NULL) {
		if (!SSL_CTX_use_certificate_file(ctx, sslprm.cert_file, SSL_FILETYPE_PEM)) {
			SSL_CTX_free(ctx);
			while ((x = ERR_get_error()) != 0) {
				ERR_error_string(x, errstr);
				logit(LOG_ERR, "Error: could not use certificate file %s : %s",
					   sslprm.cert_file, errstr);
			}
			exit(STATE_CRITICAL);
		}
		if (!SSL_CTX_use_PrivateKey_file(ctx, sslprm.privatekey_file, SSL_FILETYPE_PEM)) {
			while ((x = ERR_get_error()) != 0) {
				ERR_error_string(x, errstr);
				logit(LOG_ERR, "Error: could not use private key file '%s' : %s",
					 sslprm.privatekey_file, errstr);
			}
			SSL_CTX_free(ctx);
			exit(STATE_CRITICAL);
		}
	}

	if (sslprm.client_certs != 0) {
		vrfy = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
		if ((sslprm.client_certs & Require_Cert) != 0)
			vrfy |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
		SSL_CTX_set_verify(ctx, vrfy, verify_callback);
		if (!SSL_CTX_load_verify_locations(ctx, sslprm.cacert_file, NULL)) {
			while ((x = ERR_get_error_line_data(NULL, NULL, NULL, NULL)) != 0) {
				logit(LOG_ERR, "Error: could not use CA certificate file '%s': %s\n",
					   sslprm.cacert_file, ERR_reason_error_string(x));
			}
			SSL_CTX_free(ctx);
			logit(LOG_ERR, "Error: could not use CA certificate '%s'", sslprm.cacert_file);
			exit(STATE_CRITICAL);
		}
	}

	if (!sslprm.allowDH) {
		if (strlen(sslprm.cipher_list) < sizeof(sslprm.cipher_list) - 6)
			strcat(sslprm.cipher_list, ":!ADH");
	} else {
		/* use anonymous DH ciphers */
		if (sslprm.allowDH == 2) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000
			strncpy(sslprm.cipher_list, "ADH@SECLEVEL=0", MAX_FILENAME_LENGTH - 1);
#else
			strncpy(sslprm.cipher_list, "ADH", MAX_FILENAME_LENGTH - 1);
#endif
		}

#ifdef USE_SSL_DH
		dh = get_dh2048();
		SSL_CTX_set_tmp_dh(ctx, dh);
		DH_free(dh);
#endif
	}

	if (SSL_CTX_set_cipher_list(ctx, sslprm.cipher_list) == 0) {
		SSL_CTX_free(ctx);
		logit(LOG_ERR, "Error: Could not set SSL/TLS cipher list");
		exit(STATE_CRITICAL);
	}

	if (debug == TRUE)
		logit(LOG_INFO, "INFO: SSL/TLS initialized. All network traffic will be encrypted.");
#endif
}

void log_ssl_startup(void)
{
#ifdef HAVE_SSL
	char     *vers;

	logit(LOG_INFO, "SSL Certificate File: %s", sslprm.cert_file ? sslprm.cert_file : "None");
	logit(LOG_INFO, "SSL Private Key File: %s",
		   sslprm.privatekey_file ? sslprm.privatekey_file : "None");
	logit(LOG_INFO, "SSL CA Certificate File: %s",
		   sslprm.cacert_file ? sslprm.cacert_file : "None");
	logit(LOG_INFO, "SSL Cipher List: %s", sslprm.cipher_list);
	logit(LOG_INFO, "SSL Allow ADH: %d", sslprm.allowDH == 0);
	logit(LOG_INFO, "SSL Client Certs: %s",
		   sslprm.client_certs == 0 ? "Don't Ask" : (sslprm.client_certs ==
													 1 ? "Accept" : "Require"));
	logit(LOG_INFO, "SSL Log Options: 0x%02x", sslprm.log_opts);
	switch (sslprm.ssl_proto_ver) {
	case SSLv2:
		vers = "SSLv2";
		break;
	case SSLv2_plus:
		vers = "SSLv2 And Above";
		break;
	case SSLv3:
		vers = "SSLv3";
		break;
	case SSLv3_plus:
		vers = "SSLv3 And Above";
		break;
	case TLSv1:
		vers = "TLSv1";
		break;
	case TLSv1_plus:
		vers = "TLSv1 And Above";
		break;
	case TLSv1_1:
		vers = "TLSv1_1";
		break;
	case TLSv1_1_plus:
		vers = "TLSv1_1 And Above";
		break;
	case TLSv1_2:
		vers = "TLSv1_2";
		break;
	case TLSv1_2_plus:
		vers = "TLSv1_2 And Above";
		break;
	case TLSv1_3:
		vers = "TLSv1_3";
		break;
	case TLSv1_3_plus:
		vers = "TLSv1_3 And Above";
		break;
	default:
		vers = "INVALID VALUE!";
		break;
	}
	logit(LOG_INFO, "SSL Version: %s", vers);
#endif
}

void usage(int result)
{
	if (result != OK) {
		printf("\n");
		printf("Incorrect command line arguments supplied\n");
		printf("\n");
	}
	printf("NRPE - Nagios Remote Plugin Executor\n");
	printf("Version: %s\n", PROGRAM_VERSION);
	printf("\n");
	if (result != OK || show_help == TRUE) {
		printf("Copyright (c) 2009-2017 Nagios Enterprises\n");
		printf("              1999-2008 Ethan Galstad (nagios@nagios.org)\n");
		printf("\n");
		printf("Last Modified: %s\n", MODIFICATION_DATE);
		printf("\n");
		printf("License: GPL v2 with exemptions (-l for more info)\n");
		printf("\n");
#ifdef HAVE_SSL
		printf("SSL/TLS Available, OpenSSL 0.9.6 or higher required\n");
		printf("\n");
#endif
#ifdef HAVE_LIBWRAP
		printf("TCP Wrappers Available\n");
		printf("\n");
#endif
#ifdef ENABLE_COMMAND_ARGUMENTS
		printf("***************************************************************\n");
		printf("** POSSIBLE SECURITY RISK - COMMAND ARGUMENTS ARE SUPPORTED! **\n");
		printf("**      Read the NRPE SECURITY file for more information     **\n");
		printf("***************************************************************\n");
		printf("\n");
#endif
#ifndef HAVE_LIBWRAP
		printf("***************************************************************\n");
		printf("** POSSIBLE SECURITY RISK - TCP WRAPPERS ARE NOT AVAILABLE!  **\n");
		printf("**      Read the NRPE SECURITY file for more information     **\n");
		printf("***************************************************************\n");
		printf("\n");
#endif
		printf("Usage: nrpe [-V] [-n] -c <config_file> [-4|-6] <mode>\n");
		printf("\n");
		printf("Options:\n");
		printf(" -V, --version         Print version info and quit\n");
		printf(" -n, --no-ssl          Do not use SSL\n");
		printf(" -c, --config=FILE     Name of config file to use\n");
		printf(" -4, --ipv4            Use ipv4 only\n");
		printf(" -6, --ipv6            Use ipv6 only\n");
		printf(" <mode> (One of the following operating modes)\n");
		printf("   -i, --inetd         Run as a service under inetd or xinetd\n");
		printf("   -d, --daemon        Run as a standalone daemon\n");
		printf("   -s, --src           Run as a subsystem under AIX\n");
		printf("   -f, --no-forking    Don't fork() (for systemd, launchd, etc.)\n");
		printf("\n");
		printf("Notes:\n");
		printf("This program is designed to process requests from the check_nrpe\n");
		printf("plugin on the host(s) running Nagios.  It can run as a service\n");
		printf("under inetd or xinetd (read the docs for info on this), or as a\n");
		printf("standalone daemon. Once a request is received from an authorized\n");
		printf("host, NRPE will execute the command/plugin (as defined in the\n");
		printf("config file) and return the plugin output and return code to the\n");
		printf("check_nrpe plugin.\n");
		printf("\n");
	}

	if (show_license == TRUE)
		display_license();

	exit(STATE_UNKNOWN);
}

void run_inetd(void)
{
	check_privileges();			/* make sure we're not root */
	close(2);					/* redirect STDERR to /dev/null */
	open("/dev/null", O_WRONLY);
	handle_connection(0);		/* handle the connection */
}

void run_src(void)
{
	/* if we're running under SRC we don't fork but does drop-privileges */

	set_stdio_sigs();

	do {
		/* reset flags */
		sigrestart = FALSE;
		sigshutdown = FALSE;

		wait_for_connections();	/* wait for connections */
		cleanup();
	} while (sigrestart == TRUE && sigshutdown == FALSE);
}

/* daemonize and start listening for requests... */
void run_daemon(void)
{
	pid_t     pid;

	pid = fork();

	if (pid != 0) {
		if (pid == -1) {
			logit(LOG_ERR, "fork() failed with error %d, bailing out...", errno);
			exit(STATE_CRITICAL);
		}

		return;
	}

	setsid();					/* we're a daemon - set up a new process group */
	set_stdio_sigs();

	do {
		/* reset flags */
		sigrestart = FALSE;
		sigshutdown = FALSE;

		wait_for_connections();	/* wait for connections */
		cleanup();
	} while (sigrestart == TRUE && sigshutdown == FALSE);
}

void set_stdio_sigs(void)
{
#ifdef HAVE_SIGACTION
	struct sigaction sig_action;
#endif

	if (chdir("/") == -1) {
		printf("ERROR: chdir(): %s, bailing out...\n", strerror(errno));
		exit(STATE_CRITICAL);
	}

	close(0);					/* close standard file descriptors */
	close(1);
	close(2);
	open("/dev/null", O_RDONLY);	/* redirect standard descriptors to /dev/null */
	open("/dev/null", O_WRONLY);
	open("/dev/null", O_WRONLY);

	/* handle signals */
#ifdef HAVE_SIGACTION
	sig_action.sa_sigaction = NULL;
	sig_action.sa_handler = sighandler;
	sigfillset(&sig_action.sa_mask);
	sig_action.sa_flags = SA_NODEFER | SA_RESTART;
	sigaction(SIGQUIT, &sig_action, NULL);
	sigaction(SIGTERM, &sig_action, NULL);
	sigaction(SIGHUP, &sig_action, NULL);
#else	 /* HAVE_SIGACTION */
	signal(SIGQUIT, sighandler);
	signal(SIGTERM, sighandler);
	signal(SIGHUP, sighandler);
#endif	 /* HAVE_SIGACTION */

	logit(LOG_NOTICE, "Starting up daemon");	/* log info */
	if (write_pid_file() == ERROR)	/* write pid file */
		exit(STATE_CRITICAL);

	clean_environ(keep_env_vars, nrpe_user);

	/* drop and then check privileges */
	drop_privileges(nrpe_user, nrpe_group, 0);
	check_privileges();
}

void cleanup(void)
{
	int       result;

	free_memory();				/* free all memory we allocated */

	if (sigrestart == TRUE && sigshutdown == FALSE) {
		close_log_file();
		result = read_config_file(config_file);	/* read the config file */

		if (result == ERROR) {	/* exit if there are errors... */
			logit(LOG_ERR, "Config file '%s' contained errors, bailing out...", config_file);
			exit(STATE_CRITICAL);
		}
		return;
	}

	remove_pid_file();			/* remove pid file */
	logit(LOG_NOTICE, "Daemon shutdown\n");

	close_log_file();			/* close the log file */
}

#ifdef HAVE_SSL
int verify_callback(int preverify_ok, X509_STORE_CTX * ctx)
{
	char      name[256], issuer[256];
	X509     *err_cert;
	int       err;
	SSL      *ssl;

	if (preverify_ok || ((sslprm.log_opts & SSL_LogCertDetails) == 0))
		return preverify_ok;

	err_cert = X509_STORE_CTX_get_current_cert(ctx);
	err = X509_STORE_CTX_get_error(ctx);

	/* Get the pointer to the SSL of the current connection */
	ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());

	X509_NAME_oneline(X509_get_subject_name(err_cert), name, 256);
	X509_NAME_oneline(X509_get_issuer_name(err_cert), issuer, 256);

	if (!preverify_ok && (sslprm.log_opts & SSL_LogCertDetails)) {
		logit(LOG_ERR, "SSL Client has an invalid certificate: %s (issuer=%s) err=%d:%s",
			   name, issuer, err, X509_verify_cert_error_string(err));
	}

	return preverify_ok;
}
#endif

/*
 * Given a string, convert any byte pairs representing an escape sequence (e.g. "\\r" into 
 * the single-byte metacharacter (e.g. '\r')
 * Currently, this doesn't support octal/hex numbers or unicode code points (\n, \x, \u, \U)
 */
char* process_metachars(const char* input)
{
	char* copy = strdup(input);
	int i,j;
	int length = strlen(input);
	for (i = 0, j = 0; i < length, j < length; i++, j++) {
		if (copy[j] != '\\') {
			copy[i] = copy[j];
			continue;
		}

		j += 1;
		switch (copy[j]) {
			case 'a':
				copy[i] = '\a';
				break;
			case 'b':
				copy[i] = '\b';
				break;
			case 'f':
				copy[i] = '\f';
				break;
			case 'n':
				copy[i] = '\n';
				break;
			case 'r':
				copy[i] = '\r';
				break;
			case 't':
				copy[i] = '\t';
				break;
			case 'v':
				copy[i] = '\v';
				break;
			case '\\':
				copy[i] = '\\';
				break;
			case '\'':
				copy[i] = '\'';
				break;
			case '"':
				copy[i] = '\"';
				break;
			case '?':
				copy[i] = '\?';
				break;
		}
	}
	copy[i] = '\0';

	return copy;
}

/* read in the configuration file */
int read_config_file(char *filename)
{
	struct stat st;
	FILE     *fp;
	char      config_file[MAX_FILENAME_LENGTH];
	char      input_buffer[MAX_INPUT_BUFFER];
	char     *input_line;
	char     *temp_buffer;
	char     *varname;
	char     *varvalue;
	int       line = 0;
	int       len = 0;
	int       x = 0;

	fp = fopen(filename, "r");	/* open the config file for reading */

	/* exit if we couldn't open the config file */
	if (fp == NULL) {
		logit(LOG_ERR, "Unable to open config file '%s' for reading\n", filename);
		return ERROR;
	}

	while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
		line++;
		input_line = input_buffer;

		/* skip leading whitespace */
		while (isspace(*input_line))
			++input_line;

		/* trim trailing whitespace */
		len = strlen(input_line);
		for (x = len - 1; x >= 0; x--) {
			if (isspace(input_line[x]))
				input_line[x] = '\x0';
			else
				break;
		}

		/* skip comments and blank lines */
		if (input_line[0] == '#' || input_line[0] == '\x0' || input_line[0] == '\n')
			continue;

		/* get the variable name */
		varname = strtok(input_line, "=");
		if (varname == NULL) {
			logit(LOG_ERR, "No variable name specified in config file '%s' - Line %d\n",
				   filename, line);
			return ERROR;
		}

		/* get the variable value */
		varvalue = strtok(NULL, "\n");
		if (varvalue == NULL) {
			logit(LOG_ERR, "No variable value specified in config file '%s' - Line %d\n",
				   filename, line);
			return ERROR;

		} else if (!strcmp(varname, "include_dir")) {
			/* allow users to specify directories to recurse into for config files */

			strncpy(config_file, varvalue, sizeof(config_file) - 1);
			config_file[sizeof(config_file) - 1] = '\x0';

			/* strip trailing / if necessary */
			if (config_file[strlen(config_file) - 1] == '/')
				config_file[strlen(config_file) - 1] = '\x0';

			/* process the config directory... */
			if (read_config_dir(config_file) == ERROR)
				logit(LOG_ERR, "Continuing with errors...");

		} else if (!strcmp(varname, "include") || !strcmp(varname, "include_file")) {
			/* allow users to specify individual config files to include */

			/* process the config file... */
			if (read_config_file(varvalue) == ERROR)
				logit(LOG_ERR, "Continuing with errors...");

		} else if (!strcmp(varname, "max_commands")) {

			max_commands = atoi(varvalue);
			if (max_commands < 0) {
				logit(LOG_WARNING, "max_commands set too low, setting to 0\n");
				max_commands = 0;
			}

		} else if (!strcmp(varname, "server_port")) {
			server_port = atoi(varvalue);
			if (server_port < 1024) {
				logit(LOG_ERR,
					   "Invalid port number specified in config file '%s' - Line %d\n",
					   filename, line);
				return ERROR;
			}

		} else if (!strcmp(varname, "command_prefix"))
			command_prefix = strdup(varvalue);

		else if (!strcmp(varname, "server_address")) {
			strncpy(server_address, varvalue, sizeof(server_address) - 1);
			server_address[sizeof(server_address) - 1] = '\0';

		} else if (!strcmp(varname, "allowed_hosts")) {
			allowed_hosts = strdup(varvalue);
			parse_allowed_hosts(allowed_hosts);
			if (debug == TRUE)
				show_acl_lists();

		} else if (strstr(input_line, "command[")) {
			temp_buffer = strtok(varname, "[");
			temp_buffer = strtok(NULL, "]");
			if (temp_buffer == NULL) {
				logit(LOG_ERR, "Invalid command specified in config file '%s' - Line %d\n",
					   filename, line);
				return ERROR;
			}
			add_command(temp_buffer, varvalue);

		} else if (strstr(input_buffer, "debug")) {
			debug = atoi(varvalue);
			if (debug > 0)
				debug = TRUE;
			else
				debug = FALSE;

		} else if (!strcmp(varname, "nrpe_user"))
			nrpe_user = strdup(varvalue);

		else if (!strcmp(varname, "nrpe_group"))
			nrpe_group = strdup(varvalue);

		else if (!strcmp(varname, "dont_blame_nrpe"))
			allow_arguments = (atoi(varvalue) == 1) ? TRUE : FALSE;

		else if (!strcmp(varname, "disable_syslog"))
			disable_syslog = (atoi(varvalue) == 1) ? TRUE : FALSE;

		else if (!strcmp(varname, "allow_bash_command_substitution"))
			allow_bash_cmd_subst = (atoi(varvalue) == 1) ? TRUE : FALSE;

		else if (!strcmp(varname, "command_timeout")) {
			command_timeout = atoi(varvalue);
			if (command_timeout < 1) {
				logit(LOG_ERR,
					   "Invalid command_timeout specified in config file '%s' - Line %d\n",
					   filename, line);
				return ERROR;
			}
		} else if (!strcmp(varname, "connection_timeout")) {
			connection_timeout = atoi(varvalue);
			if (connection_timeout < 1) {
				logit(LOG_ERR,
					   "Invalid connection_timeout specified in config file '%s' - Line %d\n",
					   filename, line);
				return ERROR;
			}

		} else if (!strcmp(varname, "ssl_shutdown_timeout")) {
			ssl_shutdown_timeout = atoi(varvalue);
			if (ssl_shutdown_timeout < 1) {
				logit(LOG_ERR,
					   "Invalid ssl_shutdown_timeout specified in config file '%s' - Line %d\n",
					   filename, line);
				return ERROR;
			}

		} else if (!strcmp(varname, "allow_weak_random_seed"))
			allow_weak_random_seed = (atoi(varvalue) == 1) ? TRUE : FALSE;

		else if (!strcmp(varname, "pid_file"))
			pid_file = strdup(varvalue);

		else if (!strcmp(varname, "listen_queue_size")) {
			listen_queue_size = atoi(varvalue);
			if (listen_queue_size == 0) {
				logit(LOG_ERR,
					   "Invalid listen queue size specified in config file '%s' - Line %d\n",
					   filename, line);
				return ERROR;
			}

		} else if (!strcmp(varname, "ssl_version")) {
			if (!strcmp(varvalue, "TLSv1.3"))
				sslprm.ssl_proto_ver = TLSv1_3;
			else if (!strcmp(varvalue, "TLSv1.3+"))
				sslprm.ssl_proto_ver = TLSv1_3_plus;
			else if (!strcmp(varvalue, "TLSv1.2"))
				sslprm.ssl_proto_ver = TLSv1_2;
			else if (!strcmp(varvalue, "TLSv1.2+"))
				sslprm.ssl_proto_ver = TLSv1_2_plus;
			else if (!strcmp(varvalue, "TLSv1.1"))
				sslprm.ssl_proto_ver = TLSv1_1;
			else if (!strcmp(varvalue, "TLSv1.1+"))
				sslprm.ssl_proto_ver = TLSv1_1_plus;
			else if (!strcmp(varvalue, "TLSv1"))
				sslprm.ssl_proto_ver = TLSv1;
			else if (!strcmp(varvalue, "TLSv1+"))
				sslprm.ssl_proto_ver = TLSv1_plus;
			else if (!strcmp(varvalue, "SSLv3"))
				sslprm.ssl_proto_ver = SSLv3;
			else if (!strcmp(varvalue, "SSLv3+"))
				sslprm.ssl_proto_ver = SSLv3_plus;
#if OPENSSL_VERSION_NUMBER < 0x10100000
			else if (!strcmp(varvalue, "SSLv2"))
				sslprm.ssl_proto_ver = SSLv2;
			else if (!strcmp(varvalue, "SSLv2+"))
				sslprm.ssl_proto_ver = SSLv2_plus;
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */
			else {
				logit(LOG_ERR, "Invalid ssl version specified in config file '%s' - Line %d",
					   filename, line);
				return ERROR;
			}

		} else if (!strcmp(varname, "ssl_use_adh")) {
			sslprm.allowDH = atoi(varvalue);
			if (sslprm.allowDH < 0 || sslprm.allowDH > 2) {
				logit(LOG_ERR,
					   "Invalid use adh value specified in config file '%s' - Line %d",
					   filename, line);
				return ERROR;
			}

		} else if (!strcmp(varname, "ssl_logging"))
			sslprm.log_opts = strtoul(varvalue, NULL, 0);

		else if (!strcmp(varname, "ssl_cipher_list")) {
			strncpy(sslprm.cipher_list, varvalue, sizeof(sslprm.cipher_list) - 1);
			sslprm.cipher_list[sizeof(sslprm.cipher_list) - 1] = '\0';

		} else if (!strcmp(varname, "ssl_cert_file"))
			sslprm.cert_file = strdup(varvalue);

		else if (!strcmp(varname, "ssl_cacert_file"))
			sslprm.cacert_file = strdup(varvalue);

		else if (!strcmp(varname, "ssl_privatekey_file"))
			sslprm.privatekey_file = strdup(varvalue);

		else if (!strcmp(varname, "ssl_client_certs")) {
			sslprm.client_certs = atoi(varvalue);
			if ((int)sslprm.client_certs < 0 || sslprm.client_certs > Require_Cert) {
				logit(LOG_ERR,
					   "Invalid client certs value specified in config file '%s' - Line %d",
					   filename, line);
				return ERROR;
			}
			/* if requiring or logging client certs, make sure "Ask" is turned on */
			if (sslprm.client_certs & Require_Cert)
				sslprm.client_certs |= Ask_For_Cert;

		} else if (!strcmp(varname, "log_facility")) {
			if ((get_log_facility(varvalue)) == OK) {
				/* re-open log using new facility */
				closelog();
				openlog("nrpe", LOG_PID, log_facility);
			} else
				logit(LOG_WARNING,
					   "Invalid log_facility specified in config file '%s' - Line %d\n",
					   filename, line);

		} else if (!strcmp(varname, "keep_env_vars"))
			keep_env_vars = strdup(varvalue);

		else if (!strcmp(varname, "nasty_metachars"))
			nasty_metachars = process_metachars(varvalue);

		else if (!strcmp(varname, "log_file")) {
			log_file = strdup(varvalue);
			open_log_file();

		} else {
			logit(LOG_WARNING, "Unknown option specified in config file '%s' - Line %d\n",
				   filename, line);
			continue;
		}
	}

	fclose(fp);					/* close the config file */
	return OK;
}

/* process all config files in a specific config directory (with directory recursion) */
int read_config_dir(char *dirname)
{
	struct dirent *dirfile;
#ifdef HAVE_SCANDIR
	struct dirent **dirfiles;
	int       x, i, n;
#else
	DIR      *dirp;
	int       x;
#endif
	struct stat buf;
	char      config_file[MAX_FILENAME_LENGTH];
	int       result = OK;

#ifdef HAVE_SCANDIR
	/* read and sort the directory contents */
	n = scandir(dirname, &dirfiles, 0, alphasort);
	if (n < 0) {
		logit(LOG_ERR, "Could not open config directory '%s' for reading.\n", dirname);
		return ERROR;
	}

	for (i = 0; i < n; i++) {
		dirfile = dirfiles[i];
#else
	/* open the directory for reading */
	dirp = opendir(dirname);
	if (dirp == NULL) {
		logit(LOG_ERR, "Could not open config directory '%s' for reading.\n", dirname);
		return ERROR;
	}

	while ((dirfile = readdir(dirp)) != NULL) {
#endif

		/* process all files in the directory... */

		/* create the full path to the config file or subdirectory */
		snprintf(config_file, sizeof(config_file) - 1, "%s/%s", dirname, dirfile->d_name);
		config_file[sizeof(config_file) - 1] = '\x0';
		stat(config_file, &buf);

		/* process this if it's a config file... */
		x = strlen(dirfile->d_name);
		if (x > 4 && !strcmp(dirfile->d_name + (x - 4), ".cfg")) {

			/* only process normal files */
			if (!S_ISREG(buf.st_mode))
				continue;

			/* process the config file */
			result |= read_config_file(config_file);
		}

		/* recurse into subdirectories... */
		if (S_ISDIR(buf.st_mode)) {

			/* ignore current, parent and hidden directory entries */
			if (dirfile->d_name[0] == '.')
				continue;

			/* process the config directory */
			result |= read_config_dir(config_file);
		}
	}

#ifdef HAVE_SCANDIR
	for (i = 0; i < n; i++)
		free(dirfiles[i]);
	free(dirfiles);
#else
	closedir(dirp);
#endif

	return result;
}

/* determines facility to use with syslog */
int get_log_facility(char *varvalue)
{
	if (!strcmp(varvalue, "kern"))
		log_facility = LOG_KERN;
	else if (!strcmp(varvalue, "user"))
		log_facility = LOG_USER;
	else if (!strcmp(varvalue, "mail"))
		log_facility = LOG_MAIL;
	else if (!strcmp(varvalue, "daemon"))
		log_facility = LOG_DAEMON;
	else if (!strcmp(varvalue, "auth"))
		log_facility = LOG_AUTH;
	else if (!strcmp(varvalue, "syslog"))
		log_facility = LOG_SYSLOG;
	else if (!strcmp(varvalue, "lrp"))
		log_facility = LOG_LPR;
	else if (!strcmp(varvalue, "news"))
		log_facility = LOG_NEWS;
	else if (!strcmp(varvalue, "uucp"))
		log_facility = LOG_UUCP;
	else if (!strcmp(varvalue, "cron"))
		log_facility = LOG_CRON;
	else if (!strcmp(varvalue, "authpriv"))
		log_facility = LOG_AUTHPRIV;
	else if (!strcmp(varvalue, "ftp"))
		log_facility = LOG_FTP;
	else if (!strcmp(varvalue, "local0"))
		log_facility = LOG_LOCAL0;
	else if (!strcmp(varvalue, "local1"))
		log_facility = LOG_LOCAL1;
	else if (!strcmp(varvalue, "local2"))
		log_facility = LOG_LOCAL2;
	else if (!strcmp(varvalue, "local3"))
		log_facility = LOG_LOCAL3;
	else if (!strcmp(varvalue, "local4"))
		log_facility = LOG_LOCAL4;
	else if (!strcmp(varvalue, "local5"))
		log_facility = LOG_LOCAL5;
	else if (!strcmp(varvalue, "local6"))
		log_facility = LOG_LOCAL6;
	else if (!strcmp(varvalue, "local7"))
		log_facility = LOG_LOCAL7;
	else {
		log_facility = LOG_DAEMON;
		return ERROR;
	}

	return OK;
}

/* adds a new command definition from the config file to the list in memory */
int add_command(char *command_name, char *command_line)
{
	command  *new_command;

	if (command_name == NULL || command_line == NULL)
		return ERROR;

	/* allocate memory for the new command */
	new_command = (command *) malloc(sizeof(command));
	if (new_command == NULL)
		return ERROR;

	new_command->command_name = strdup(command_name);
	if (new_command->command_name == NULL) {
		free(new_command);
		return ERROR;
	}
	new_command->command_line = strdup(command_line);
	if (new_command->command_line == NULL) {
		free(new_command->command_name);
		free(new_command);
		return ERROR;
	}

	/* add new command to head of list in memory */
	new_command->next = command_list;
	command_list = new_command;

	if (debug == TRUE)
		logit(LOG_DEBUG, "Added command[%s]=%s\n", command_name, command_line);

	return OK;
}

/* given a command name, find the structure in memory */
command  *find_command(char *command_name)
{
	command  *temp_command;

	for (temp_command = command_list; temp_command != NULL; temp_command = temp_command->next)
		if (!strcmp(command_name, temp_command->command_name))
			return temp_command;

	return NULL;
}

/* Start listen on a particular port */
void create_listener(struct addrinfo *ai)
{
	int       ret;
	char      ntop[NI_MAXHOST], strport[NI_MAXSERV];
	int       listen_sock;
	int       flag = 1;

	if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
		return;

	if (num_listen_socks >= MAX_LISTEN_SOCKS) {
		logit(LOG_ERR, "Too many listen sockets. Enlarge MAX_LISTEN_SOCKS");
		exit(1);
	}

	if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
						   strport, sizeof(strport), NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
		logit(LOG_ERR, "getnameinfo failed: %.100s", gai_strerror(ret));
		return;
	}

	/* Create socket for listening. */
	listen_sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
	if (listen_sock < 0) {
		/* kernel may not support ipv6 */
		logit(LOG_ERR, "socket: %.100s", strerror(errno));
		return;
	}

	/* socket should be non-blocking */
	fcntl(listen_sock, F_SETFL, O_NONBLOCK);

	/* set the reuse address flag so we don't get errors when restarting */
	if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) < 0) {
		logit(LOG_ERR, "setsockopt SO_REUSEADDR: %s", strerror(errno));
		return;
	}
#ifdef IPV6_V6ONLY
	/* Only communicate in IPv6 over AF_INET6 sockets. */
	if (ai->ai_family == AF_INET6) {
		if (setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &flag, sizeof(flag)) == -1) {
			fprintf(stderr, "setsockopt IPV6_V6ONLY: %s", strerror(errno));
		}
	}
#endif

	/* Bind the socket to the desired port. */
	if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
		logit(LOG_ERR, "Bind to port %s on %s failed: %.200s.",
			   strport, ntop, strerror(errno));
		close(listen_sock);
		return;
	}
	listen_socks[num_listen_socks] = listen_sock;
	num_listen_socks++;

	/* Start listening on the port. */
	if (listen(listen_sock, listen_queue_size) < 0) {
		logit(LOG_ERR, "listen on [%s]:%s: %.100s", ntop, strport, strerror(errno));
		exit(1);
	}

	logit(LOG_INFO, "Server listening on %s port %s.", ntop, strport);
}

/* Close all listening sockets */
static void close_listen_socks(void)
{
	int       i;

	for (i = 0; i <= num_listen_socks; i++) {
		close(listen_socks[i]);
		num_listen_socks--;
	}
}

/* wait for incoming connection requests */
void wait_for_connections(void)
{
#ifdef HAVE_STRUCT_SOCKADDR_STORAGE
	struct sockaddr_storage from;
#else
	struct sockaddr from;
#endif
	socklen_t fromlen;
	fd_set   *fdset = NULL;
	int       maxfd = 0, new_sd = 0, i, rc, retval;

	setup_wait_conn();

	/* listen for connection requests - fork() if we get one */
	while (1) {
		/* bail out if necessary */
		if (sigrestart == TRUE || sigshutdown == TRUE)
			break;

		for (i = 0; i < num_listen_socks; i++) {
			if (listen_socks[i] > maxfd)
				maxfd = listen_socks[i];
		}

		if (fdset != NULL)
			free(fdset);
		fdset = (fd_set *) calloc(how_many(maxfd + 1, NFDBITS), sizeof(fd_mask));

		for (i = 0; i < num_listen_socks; i++)
			FD_SET(listen_socks[i], fdset);

		/* Wait in select until there is a connection. */
		retval = select(maxfd + 1, fdset, NULL, NULL, NULL);

		/* bail out if necessary */
		if (sigrestart == TRUE || sigshutdown == TRUE)
			break;

		/* error */
		if (retval < 0)
			continue;

		for (i = 0; i < num_listen_socks; i++) {
			if (!FD_ISSET(listen_socks[i], fdset))
				continue;
			fromlen = (socklen_t)sizeof(from);

			/* accept a new connection request */
			new_sd = accept(listen_socks[i], (struct sockaddr *)&from, &fromlen);

			/* some kind of error occurred... */
			if (new_sd < 0) {
				/* bail out if necessary */
				if (sigrestart == TRUE || sigshutdown == TRUE)
					break;
				if (errno == EWOULDBLOCK || errno == EINTR)	/* retry */
					continue;
				/* socket is nonblocking and we don't have a connection yet */
				if (errno == EAGAIN)
					continue;
				if (errno == ENOBUFS)	/* fix for HP-UX 11.0 - just retry */
					continue;

				break;			/* else handle the error later */
			}


			rc = wait_conn_fork(new_sd);
			if (rc == TRUE)
				continue;		/* Continue if this is the parent returning */

			/* grandchild running here */
			conn_check_peer(new_sd);

			/* handle the client connection */
			handle_connection(new_sd);

			/* log info */
			if (debug == TRUE)
				logit(LOG_DEBUG, "Connection from %s closed.", remote_host);

			/* close socket prior to exiting */
			close(new_sd);

			exit(STATE_OK);

		}
	}

	/* close the sockets we're listening on */
	close_listen_socks();
	freeaddrinfo(listen_addrs);
	listen_addrs = NULL;

	return;
}

void setup_wait_conn(void)
{
	struct addrinfo *ai;
	char	addrstr[100];
	void	*ptr;

	add_listen_addr(&listen_addrs, address_family,
					(strcmp(server_address, "") == 0) ? NULL : server_address, server_port);

	for (ai = listen_addrs; ai; ai = ai->ai_next) {
		if (debug == TRUE) {
			inet_ntop (ai->ai_family, ai->ai_addr->sa_data, addrstr, 100);
			ptr = &((struct sockaddr_in *) ai->ai_addr)->sin_addr;
			inet_ntop (ai->ai_family, ptr, addrstr, 100);
			logit(LOG_INFO, "SETUP_WAIT_CONN FOR: IPv4 address: %s (%s)\n", addrstr, ai->ai_canonname);
		}
		create_listener(ai);
	}

	if (!num_listen_socks) {
		logit(LOG_ERR, "Cannot bind to any address.");
		exit(1);
	}

	/* log warning about command arguments */
#ifdef ENABLE_COMMAND_ARGUMENTS
	if (allow_arguments == TRUE)
		logit(LOG_NOTICE,
			   "Warning: Daemon is configured to accept command arguments from clients!");
# ifdef ENABLE_BASH_COMMAND_SUBSTITUTION
	if (TRUE == allow_bash_cmd_subst) {
		if (TRUE == allow_arguments)
			logit(LOG_NOTICE,
				   "Warning: Daemon is configured to accept command arguments with bash command substitutions!");
		else
			logit(LOG_NOTICE,
				   "Warning: Daemon is configured to accept command arguments with bash command substitutions, but is not configured to accept command arguments from clients. Enable command arguments if you wish to allow command arguments with bash command substitutions.");
	}
# endif
#endif

	logit(LOG_INFO, "Listening for connections on port %d", server_port);

	if (allowed_hosts)
		logit(LOG_INFO, "Allowing connections from: %s\n", allowed_hosts);
}

int wait_conn_fork(int sock)
{
#ifdef HAVE_SIGACTION
	struct sigaction sig_action;
#endif
	pid_t     pid;

	/* child process should handle the connection */
	pid = fork();

	if (pid > 0) {
		close(sock);			/* parent doesn't need the new connection */
		waitpid(pid, NULL, 0);	/* parent waits for first child to exit */
		return TRUE;			/* tell caller this is the parent process */
	}

	if (pid < 0) {
		logit(LOG_ERR, "fork() failed with error %d, bailing out...", errno);
		exit(STATE_CRITICAL);
	}

	/* fork again so we don't create zombies */
	pid = fork();

	if (pid < 0) {
		logit(LOG_ERR, "Second fork() failed with error %d, bailing out...", errno);
		exit(STATE_CRITICAL);
	}

	if (pid > 0) {
		/* first child returns immediately, grandchild is inherited by
		   INIT process -> no zombies... */
		exit(STATE_OK);
	}

	/* hey, there was an error... */
	if (sock < 0) {
		/* log error */
		logit(LOG_ERR, "Network server accept failure (%d: %s)",
			   errno, strerror(errno));
		exit(STATE_OK);
	}

	/* all good - handle signals */
#ifdef HAVE_SIGACTION
	sig_action.sa_sigaction = NULL;
	sig_action.sa_handler = child_sighandler;
	sigfillset(&sig_action.sa_mask);
	sig_action.sa_flags = SA_NODEFER | SA_RESTART;
	sigaction(SIGQUIT, &sig_action, NULL);
	sigaction(SIGTERM, &sig_action, NULL);
	sigaction(SIGHUP, &sig_action, NULL);
#else	 /* HAVE_SIGACTION */
	signal(SIGQUIT, child_sighandler);
	signal(SIGTERM, child_sighandler);
	signal(SIGHUP, child_sighandler);
#endif	 /* HAVE_SIGACTION */

	close_listen_socks();		/* grandchild does not need to listen */

	return FALSE;				/* tell caller this isn't the parent process */
}

void conn_check_peer(int sock)
{
#ifdef HAVE_LIBWRAP
	struct request_info     req;
#endif
#ifdef HAVE_STRUCT_SOCKADDR_STORAGE
	struct sockaddr_storage addr;
#else
	struct sockaddr			addr;
#endif
	struct sockaddr_in      *nptr;
	struct sockaddr_in6     *nptr6;

	char      ipstr[INET6_ADDRSTRLEN];
	socklen_t addrlen;
	int       rc;

	/* find out who just connected... */
	addrlen = sizeof(addr);
	rc = getpeername(sock, (struct sockaddr *)&addr, &addrlen);

	if (rc < 0) {
		/* log error */
		logit(LOG_ERR, "Error: Network server getpeername() failure (%d: %s)",
			   errno, strerror(errno));

		/* close socket prior to exiting */
		close(sock);
		return;
	}

#ifdef HAVE_STRUCT_SOCKADDR_STORAGE
	switch (addr.ss_family) {
#else
	switch (addr.sa_family) {
#endif

	case AF_INET:
		nptr = (struct sockaddr_in *)&addr;
		strncpy(remote_host, inet_ntoa(nptr->sin_addr), sizeof(remote_host) - 1);
		remote_host[MAX_HOST_ADDRESS_LENGTH - 1] = '\0';
		break;

	case AF_INET6:
		nptr6 = (struct sockaddr_in6 *)&addr;
		if (inet_ntop(AF_INET6, (const void *)&(nptr6->sin6_addr),
					  ipstr, sizeof(ipstr)) == NULL) {
			strncpy(ipstr, "Unknown", sizeof(ipstr));
		}
		strncpy(remote_host, ipstr, sizeof(remote_host) - 1);
		remote_host[MAX_HOST_ADDRESS_LENGTH - 1] = '\0';
		break;
	}

	if (debug == TRUE)
		logit(LOG_INFO, "CONN_CHECK_PEER: checking if host is allowed: %s port %d\n",
			 remote_host, nptr->sin_port);

	/* is this host allowed? */
	if (allowed_hosts) {
#ifdef HAVE_STRUCT_SOCKADDR_STORAGE
		switch (addr.ss_family) {
#else
		switch (addr.sa_family) {
#endif

		case AF_INET:
			/* log info */
			if (debug == TRUE || (sslprm.log_opts & SSL_LogIpAddr))
				logit(LOG_DEBUG, "Connection from %s port %d", remote_host, nptr->sin_port);

			if (!is_an_allowed_host(AF_INET, (void *)&(nptr->sin_addr))) {
				/* log error */
				logit(LOG_ERR, "Host %s is not allowed to talk to us!", remote_host);

				/* log info */
				if (debug == TRUE)
					logit(LOG_DEBUG, "Connection from %s closed.", remote_host);

				/* close socket prior to exiting */
				close(sock);
				exit(STATE_OK);

			} else {

				/* log info */
				if (debug == TRUE) {
					logit(LOG_DEBUG, "Host address is in allowed_hosts");
				}

			}
			break;

		case AF_INET6:
			/* log info */
			strcpy(remote_host, ipstr);
			if (debug == TRUE || (sslprm.log_opts & SSL_LogIpAddr)) {
				logit(LOG_DEBUG, "Connection from %s port %d", ipstr, nptr6->sin6_port);
			}

			if (!is_an_allowed_host(AF_INET6, (void *)&(nptr6->sin6_addr))) {
				/* log error */
				logit(LOG_ERR, "Host %s is not allowed to talk to us!", ipstr);

				/* log info */
				if (debug == TRUE)
					logit(LOG_DEBUG, "Connection from %s closed.", ipstr);

				/* close socket prior to exiting */
				close(sock);
				exit(STATE_OK);

			} else {
				/* log info */
				if (debug == TRUE)
					logit(LOG_DEBUG, "Host address is in allowed_hosts");
			}
			break;
		}
	}

#ifdef HAVE_LIBWRAP
	/* Check whether or not connections are allowed from this host */
	request_init(&req, RQ_DAEMON, "nrpe", RQ_FILE, sock, 0);
	fromhost(&req);

	if (!hosts_access(&req)) {
		logit(LOG_DEBUG, "Connection refused by TCP wrapper");
		refuse(&req);			/* refuse the connection */
		/* should not be reached */
		logit(LOG_ERR, "libwrap refuse() returns!");
		close(sock);
		exit(STATE_CRITICAL);
	}
#endif
}

/* handles a client connection */
void handle_connection(int sock)
{
	u_int32_t calculated_crc32;
	command  *temp_command;
	v2_packet receive_packet, send_packet;
	v3_packet *v3_receive_packet = NULL, *v3_send_packet = NULL;
	int       bytes_to_send;
	char      buffer[MAX_INPUT_BUFFER], *send_buff = NULL, *send_pkt;
	char      raw_command[MAX_INPUT_BUFFER];
	char      processed_command[MAX_INPUT_BUFFER];
	int       result = STATE_OK;
	int       early_timeout = FALSE;
	int       rc;
	int       x;
	int32_t   pkt_size;
#ifdef DEBUG
	FILE     *errfp;
#endif
#ifdef HAVE_SSL
	SSL      *ssl = NULL;
#endif

	/* do SSL handshake */
#ifdef HAVE_SSL
	if (use_ssl == TRUE) {
    	if ((ssl = SSL_new(ctx)) == NULL) {
        	logit(LOG_ERR, "Error: Could not create SSL connection structure.");
# ifdef DEBUG
            errfp = fopen("/tmp/err.log", "a");
    		ERR_print_errors_fp(errfp);
        	fclose(errfp);
# endif
    		return;
        }

		if (handle_conn_ssl(sock, ssl) != OK)
			return;
	}
#endif

#ifdef HAVE_SSL
	rc = read_packet(sock, ssl, &receive_packet, &v3_receive_packet);
#else
	rc = read_packet(sock, NULL, &receive_packet, &v3_receive_packet);
#endif

	/* disable connection alarm - a new alarm will be setup during my_system */
	alarm(0);

	/* recv() error or client disconnect */
	if (rc <= 0) {
		/* log error */
		logit(LOG_ERR, "Could not read request from client %s, bailing out...", remote_host);
		if (v3_receive_packet)
			free(v3_receive_packet);
#ifdef HAVE_SSL
		if (ssl) {
			complete_SSL_shutdown(ssl);
			SSL_free(ssl);
			logit(LOG_INFO, "INFO: SSL Socket Shutdown.\n");
		}
#endif
		return;
	}

	/* make sure the request is valid */
	if (validate_request(&receive_packet, v3_receive_packet) == ERROR) {
		/* log an error */
		logit(LOG_ERR, "Client request from %s was invalid, bailing out...", remote_host);

		/* free memory */
		free(command_name);
		command_name = NULL;
		for (x = 0; x < MAX_COMMAND_ARGUMENTS; x++) {
			free(macro_argv[x]);
			macro_argv[x] = NULL;
		}
		if (v3_receive_packet)
			free(v3_receive_packet);

#ifdef HAVE_SSL
		if (ssl) {
			complete_SSL_shutdown(ssl);
			SSL_free(ssl);
		}
#endif

		return;
	}

	/* log info */
	if (debug == TRUE)
		logit(LOG_DEBUG, "Host %s is asking for command '%s' to be run...",
			   remote_host, command_name);

	/* if this is the version check command, just spew it out */
	if (!strcmp(command_name, NRPE_HELLO_COMMAND)) {
		snprintf(buffer, sizeof(buffer), "NRPE v%s", PROGRAM_VERSION);
		buffer[sizeof(buffer) - 1] = '\x0';
		if (debug == TRUE)		/* log info */
			logit(LOG_DEBUG, "Response to %s: %s", remote_host, buffer);
		if (v3_receive_packet)
			send_buff = strdup(buffer);
		else {
			send_buff = calloc(1, sizeof(buffer));
			strcpy(send_buff, buffer);
		}
		result = STATE_OK;

	} else {

		/* find the command we're supposed to run */
		temp_command = find_command(command_name);
		if (temp_command == NULL) {
			snprintf(buffer, sizeof(buffer), "NRPE: Command '%s' not defined", command_name);
			buffer[sizeof(buffer) - 1] = '\x0';
			if (debug == TRUE)	/* log error */
				logit(LOG_DEBUG, "%s", buffer);
			if (v3_receive_packet)
				send_buff = strdup(buffer);
			else {
				send_buff = calloc(1, sizeof(buffer));
				strcpy(send_buff, buffer);
			}
			result = STATE_UNKNOWN;

		} else {

			/* process command line */
			if (command_prefix == NULL)
				strncpy(raw_command, temp_command->command_line, sizeof(raw_command) - 1);
			else
				snprintf(raw_command, sizeof(raw_command) - 1, "%s %s", command_prefix,
						 temp_command->command_line);
			raw_command[sizeof(raw_command) - 1] = '\x0';
			process_macros(raw_command, processed_command, sizeof(processed_command));

			if (debug == TRUE)	/* log info */
				logit(LOG_DEBUG, "Running command: %s", processed_command);

			/* run the command */
			strcpy(buffer, "");
			result = my_system(processed_command, command_timeout, &early_timeout, &send_buff);

			if (debug == TRUE)	/* log debug info */
				logit(LOG_DEBUG, "Command completed with return code %d and output: %s",
					   result, send_buff);

			/* see if the command timed out */
			if (early_timeout == TRUE) {
				sprintf(send_buff, "NRPE: Command timed out after %d seconds\n",
						command_timeout);
				result = STATE_UNKNOWN;
			} else if (!strcmp(send_buff, "")) {
				sprintf(send_buff, "NRPE: Unable to read output\n");
				result = STATE_UNKNOWN;
			}

			/* check return code bounds */
			if ((result < 0) || (result > 3)) {
				/* log error */
				logit(LOG_ERR, "Bad return code for [%s]: %d", send_buff, result);
				result = STATE_UNKNOWN;
			}
		}
	}

	/* free memory */
	free(command_name);
	command_name = NULL;
	for (x = 0; x < MAX_COMMAND_ARGUMENTS; x++) {
		free(macro_argv[x]);
		macro_argv[x] = NULL;
	}
	if (v3_receive_packet)
		free(v3_receive_packet);
	pkt_size = strlen(send_buff);
	/* strip newline character from end of output buffer */
	if (send_buff[strlen(send_buff) - 1] == '\n')
		send_buff[strlen(send_buff) - 1] = '\x0';

	if (packet_ver == NRPE_PACKET_VERSION_2) {
		pkt_size = sizeof(v2_packet);
		send_pkt = (char *)&send_packet;

		/* clear the response packet buffer */
		memset(&send_packet, 0, sizeof(send_packet));
		/* fill the packet with semi-random data */
		randomize_buffer((char *)&send_packet, sizeof(send_packet));

		/* initialize response packet data */
		send_packet.packet_version = htons(packet_ver);
		send_packet.packet_type = htons(RESPONSE_PACKET);
		send_packet.result_code = htons(result);
		strncpy(&send_packet.buffer[0], send_buff, MAX_PACKETBUFFER_LENGTH);
		send_packet.buffer[MAX_PACKETBUFFER_LENGTH - 1] = '\x0';

		/* calculate the crc 32 value of the packet */
		send_packet.crc32_value = 0;
		calculated_crc32 = calculate_crc32((char *)&send_packet, sizeof(send_packet));
		send_packet.crc32_value = htonl(calculated_crc32);

	} else {

		pkt_size = (sizeof(v3_packet) - NRPE_V4_PACKET_SIZE_OFFSET) + strlen(send_buff) + 1;
		if (packet_ver == NRPE_PACKET_VERSION_3) {
			pkt_size = (sizeof(v3_packet) - NRPE_V3_PACKET_SIZE_OFFSET) + strlen(send_buff) + 1;
		}
		v3_send_packet = calloc(1, pkt_size);
		send_pkt = (char *)v3_send_packet;
		/* initialize response packet data */
		v3_send_packet->packet_version = htons(packet_ver);
		v3_send_packet->packet_type = htons(RESPONSE_PACKET);
		v3_send_packet->result_code = htons(result);
		v3_send_packet->alignment = 0;
		v3_send_packet->buffer_length = htonl(strlen(send_buff) + 1);
		strcpy(&v3_send_packet->buffer[0], send_buff);

		/* calculate the crc 32 value of the packet */
		v3_send_packet->crc32_value = 0;
		calculated_crc32 = calculate_crc32((char *)v3_send_packet, pkt_size);
		v3_send_packet->crc32_value = htonl(calculated_crc32);
	}

	/* send the response back to the client */
	bytes_to_send = pkt_size;
	if (use_ssl == FALSE)
		sendall(sock, send_pkt, &bytes_to_send);
#ifdef HAVE_SSL
	else
		SSL_write(ssl, send_pkt, bytes_to_send);
#endif

#ifdef HAVE_SSL
	if (ssl) {
		complete_SSL_shutdown(ssl);
		SSL_free(ssl);
	}
#endif

	if (v3_send_packet)
		free(v3_send_packet);

	/* log info */
	if (debug == TRUE)
		logit(LOG_DEBUG, "Return Code: %d, Output: %s", result, send_buff);

	free(send_buff);

	return;
}

void init_handle_conn(void)
{
#ifdef HAVE_SIGACTION
	struct sigaction sig_action;
#endif

	/* log info */
	if (debug == TRUE)
		logit(LOG_DEBUG, "Handling the connection...");

	/* set connection handler */
#ifdef HAVE_SIGACTION
	sig_action.sa_sigaction = NULL;
	sig_action.sa_handler = my_connection_sighandler;
	sigfillset(&sig_action.sa_mask);
	sig_action.sa_flags = SA_NODEFER | SA_RESTART;
	sigaction(SIGALRM, &sig_action, NULL);
#else
	signal(SIGALRM, my_connection_sighandler);
#endif	 /* HAVE_SIGACTION */
	alarm(connection_timeout);
}

int handle_conn_ssl(int sock, void *ssl_ptr)
{
#ifdef HAVE_SSL
# if (defined(__sun) && defined(SOLARIS_10)) || defined(_AIX) || defined(__hpux)
	SSL_CIPHER *c;
#else
	const SSL_CIPHER *c;
#endif
	const char *errmsg = NULL;
	char      buffer[MAX_INPUT_BUFFER];
	SSL      *ssl = (SSL*)ssl_ptr;
	X509     *peer;
	int       rc, x, sockfd, retval;
	fd_set    rfds;
	struct timeval timeout;

	SSL_set_fd(ssl, sock);
	sockfd = SSL_get_fd(ssl);

	FD_ZERO(&rfds);
	FD_SET(sockfd, &rfds);

	timeout.tv_sec = connection_timeout;
	timeout.tv_usec = 0;


	/* keep attempting the request if needed */
	do {
		retval = select(sockfd + 1, &rfds, NULL, NULL, &timeout);

		if (retval > 0) {
			rc = SSL_accept(ssl);
		} else {
			logit(LOG_ERR, "Error: (!log_opts) Could not complete SSL handshake with %s: timeout %d seconds", remote_host, connection_timeout);
			return ERROR;
		}
	} while (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ);

	if (rc != 1) {
		/* oops, got an unrecoverable error -- get out */
		if (sslprm.log_opts & (SSL_LogCertDetails | SSL_LogIfClientCert)) {
			int nerrs = 0;
			rc = 0;
			while ((x = ERR_get_error_line_data(NULL, NULL, NULL, NULL)) != 0) {
				errmsg = ERR_reason_error_string(x);
				logit(LOG_ERR, "Error: (ERR_get_error_line_data = %d), Could not complete SSL handshake with %s: %s", x, remote_host, errmsg);
				
				if (errmsg && !strcmp(errmsg, "no shared cipher") && (sslprm.cert_file == NULL || sslprm.cacert_file == NULL))
					logit(LOG_ERR, "Error: This could be because you have not specified certificate or ca-certificate files");

				++nerrs;
			}

			if (nerrs == 0) {
				logit(LOG_ERR, "Error: (nerrs = 0) Could not complete SSL handshake with %s: %d", remote_host, SSL_get_error(ssl, rc));
			}
		} else {
			logit(LOG_ERR, "Error: (!log_opts) Could not complete SSL handshake with %s: %d", remote_host, SSL_get_error(ssl, rc));
		}
# ifdef DEBUG
		errfp = fopen("/tmp/err.log", "a");
		ERR_print_errors_fp(errfp);
		fclose(errfp);
# endif
		return ERROR;
	}

	/* successful handshake */
	if (sslprm.log_opts & SSL_LogVersion)
		logit(LOG_NOTICE, "Remote %s - SSL Version: %s", remote_host, SSL_get_version(ssl));

	if (sslprm.log_opts & SSL_LogCipher) {
		c = SSL_get_current_cipher(ssl);
		logit(LOG_NOTICE, "Remote %s - %s, Cipher is %s", remote_host, SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
	}

	if ((sslprm.log_opts & SSL_LogIfClientCert)
		|| (sslprm.log_opts & SSL_LogCertDetails)) {


		peer = SSL_get_peer_certificate(ssl);

		if (peer) {
			if (sslprm.log_opts & SSL_LogIfClientCert)
				logit(LOG_NOTICE, "SSL Client %s has %s certificate",
					   remote_host, SSL_get_verify_result(ssl) == X509_V_OK ? "a valid" : "an invalid");

			if (sslprm.log_opts & SSL_LogCertDetails) {

				X509_NAME_oneline(X509_get_subject_name(peer), buffer, sizeof(buffer));
				logit(LOG_NOTICE, "SSL Client %s Cert Name: %s",
					   remote_host, buffer);

				X509_NAME_oneline(X509_get_issuer_name(peer), buffer, sizeof(buffer));
				logit(LOG_NOTICE, "SSL Client %s Cert Issuer: %s",
					   remote_host, buffer);
			}

		} else if (sslprm.client_certs == 0)
			logit(LOG_NOTICE, "SSL Not asking for client certification");

		else
			logit(LOG_NOTICE, "SSL Client %s did not present a certificate",
				   remote_host);
	}
#endif

	return OK;
}

int read_packet(int sock, void *ssl_ptr, v2_packet * v2_pkt, v3_packet ** v3_pkt)
{
	int32_t   common_size, tot_bytes, bytes_to_recv, buffer_size;
	int       rc;
	char     *buff_ptr;

	/* Read only the part that's common between versions 2 & 3 */
	common_size = tot_bytes = bytes_to_recv = (char *)&v2_pkt->buffer - (char *)v2_pkt;

	if (use_ssl == FALSE) {
		rc = recvall(sock, (char *)v2_pkt, &tot_bytes, socket_timeout);

		if (rc <= 0 || rc != bytes_to_recv)
			return -1;

		packet_ver = ntohs(v2_pkt->packet_version);
		if (packet_ver != NRPE_PACKET_VERSION_2 && packet_ver != NRPE_PACKET_VERSION_4) {
			logit(LOG_ERR, "Error: (use_ssl == false): Request packet version was invalid!");
			return -1;
		}

		if (packet_ver == NRPE_PACKET_VERSION_2) {
			buffer_size = sizeof(v2_packet) - common_size;
			buff_ptr = (char *)v2_pkt + common_size;

		} else {
			int32_t   pkt_size = sizeof(v3_packet) - 1;

			/* Read the alignment filler */
			bytes_to_recv = sizeof(int16_t);
			rc = recvall(sock, (char *)&buffer_size, &bytes_to_recv, socket_timeout);
			if (rc <= 0 || bytes_to_recv != sizeof(int16_t))
				return -1;
			tot_bytes += rc;

			/* Read the buffer size */
			bytes_to_recv = sizeof(buffer_size);
			rc = recvall(sock, (char *)&buffer_size, &bytes_to_recv, socket_timeout);
			if (rc <= 0 || bytes_to_recv != sizeof(buffer_size))
				return -1;
			tot_bytes += rc;

			buffer_size = ntohl(buffer_size);
			if (buffer_size < 0 || buffer_size > 65536) {
				logit(LOG_ERR, "Error: (use_ssl == false): Received packet with invalid buffer size");
				return -1;
			}
			pkt_size += buffer_size;
			if ((*v3_pkt = calloc(1, pkt_size)) == NULL) {
				logit(LOG_ERR, "Error: (use_ssl == false): Could not allocate memory for packet");
				return -1;
			}

			memcpy(*v3_pkt, v2_pkt, common_size);
			(*v3_pkt)->buffer_length = htonl(buffer_size);
			buff_ptr = (*v3_pkt)->buffer;
		}

		bytes_to_recv = buffer_size;
		rc = recvall(sock, buff_ptr, &bytes_to_recv, socket_timeout);

		if (rc <= 0 || rc != buffer_size) {
			if (packet_ver == NRPE_PACKET_VERSION_3) {
				free(*v3_pkt);
				*v3_pkt = NULL;
			}
			return -1;
		} else
			tot_bytes += rc;
	}
#ifdef HAVE_SSL
	else {
		SSL      *ssl = (SSL *) ssl_ptr;
		int       sockfd, retval;
		fd_set    rfds;
		struct timeval timeout;

		sockfd = SSL_get_fd(ssl);

		FD_ZERO(&rfds);
		FD_SET(sockfd, &rfds);

		timeout.tv_sec = connection_timeout;
		timeout.tv_usec = 0;

		do {
			retval = select(sockfd + 1, &rfds, NULL, NULL, &timeout);

			if (retval > 0) {
				rc = SSL_read(ssl, v2_pkt, bytes_to_recv);
			} else {
				logit(LOG_ERR, "Error (!log_opts): Could not complete SSL_read with %s: timeout %d seconds", remote_host, connection_timeout);
				return -1;
			}
		} while (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ);

		if (rc <= 0 || rc != bytes_to_recv)
			return -1;

		packet_ver = ntohs(v2_pkt->packet_version);
		if (packet_ver != NRPE_PACKET_VERSION_2 && packet_ver != NRPE_PACKET_VERSION_4) {
			logit(LOG_ERR, "Error: (use_ssl == true): Request packet version was invalid!");
			return -1;
		}

		if (packet_ver == NRPE_PACKET_VERSION_2) {
			buffer_size = sizeof(v2_packet) - common_size;
			buff_ptr = (char *)v2_pkt + common_size;
		} else {
			int32_t   pkt_size = sizeof(v3_packet);
			if (packet_ver == NRPE_PACKET_VERSION_3) {
				pkt_size -= NRPE_V3_PACKET_SIZE_OFFSET;
			}
			else if (packet_ver == NRPE_PACKET_VERSION_4) {
				pkt_size -= NRPE_V4_PACKET_SIZE_OFFSET;
			}

			/* Read the alignment filler */
			bytes_to_recv = sizeof(int16_t);
			while (((rc = SSL_read(ssl, &buffer_size, bytes_to_recv)) <= 0)
				   && (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ)) {
			}

			if (rc <= 0 || bytes_to_recv != sizeof(int16_t))
				return -1;
			tot_bytes += rc;

			/* Read the buffer size */
			bytes_to_recv = sizeof(buffer_size);
			while (((rc = SSL_read(ssl, &buffer_size, bytes_to_recv)) <= 0)
				   && (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ)) {
			}

			if (rc <= 0 || bytes_to_recv != sizeof(buffer_size))
				return -1;
			tot_bytes += rc;

			buffer_size = ntohl(buffer_size);
			if (buffer_size < 0 || buffer_size > 65536) {
				logit(LOG_ERR, "Error: (use_ssl == true): Received packet with invalid buffer size");
				return -1;
			}
			pkt_size += buffer_size;
			if ((*v3_pkt = calloc(1, pkt_size)) == NULL) {
				logit(LOG_ERR, "Error: (use_ssl == true): Could not allocate memory for packet");
				return -1;
			}

			memcpy(*v3_pkt, v2_pkt, common_size);
			(*v3_pkt)->buffer_length = htonl(buffer_size);
			buff_ptr = (*v3_pkt)->buffer;
		}

		bytes_to_recv = buffer_size;
		while (((rc = SSL_read(ssl, buff_ptr, bytes_to_recv)) <= 0)
			   && (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ)) {
		}

		if (rc <= 0 || rc != buffer_size) {
			if (packet_ver == NRPE_PACKET_VERSION_3) {
				free(*v3_pkt);
				*v3_pkt = NULL;
			}
			return -1;
		} else
			tot_bytes += rc;
	}
#endif

	return tot_bytes;
}

/* free all allocated memory */
void free_memory(void)
{
	command  *this_command;
	command  *next_command;

	/* free memory for the command list */
	this_command = command_list;
	while (this_command != NULL) {
		next_command = this_command->next;
		if (this_command->command_name)
			free(this_command->command_name);
		if (this_command->command_line)
			free(this_command->command_line);
		free(this_command);
		this_command = next_command;
	}

	command_list = NULL;
	return;
}

/* executes a system command via popen(), but protects against timeouts */
int my_system(char *command, int timeout, int *early_timeout, char **output)
{
	FILE     *fp;
	pid_t     pid;
	time_t    start_time, end_time;
	int       status;
	int       result;
	char      buffer[MAX_INPUT_BUFFER];
	int       fd[2];
	int       bytes_read = 0, tot_bytes = 0;
	int       output_size;
#ifdef HAVE_SIGACTION
	struct sigaction sig_action;
#endif

	*early_timeout = FALSE;		/* initialize return variables */

	if (command == NULL)		/* if no command was passed, return with no error */
		return STATE_OK;

	/* make sure that we are within max_commands boundaries before attempting */
	if (max_commands != 0) {
		while (commands_running >= max_commands) {
			logit(LOG_WARNING, "Commands choked. Sleeping 1s - commands_running: %d, max_commands: %d", commands_running, max_commands);
			sleep(1);
		}
	}

	/* create a pipe */
	if (pipe(fd) == -1) {
		logit(LOG_ERR, "ERROR: pipe(): %s, bailing out...", strerror(errno));
		exit(STATE_CRITICAL);
	}

	/* make the pipe non-blocking */
	fcntl(fd[0], F_SETFL, O_NONBLOCK);
	fcntl(fd[1], F_SETFL, O_NONBLOCK);

	time(&start_time);			/* get the command start time */

	pid = fork();				/* fork */

	/* return an error if we couldn't fork */
	if (pid == -1) {
		snprintf(buffer, sizeof(buffer) - 1, "NRPE: Call to fork() failed\n");
		buffer[sizeof(buffer) - 1] = '\x0';

		if (packet_ver == NRPE_PACKET_VERSION_2) {
			int       output_size = sizeof(v2_packet);
			*output = calloc(1, output_size);
			strncpy(*output, buffer, output_size - 1);
			*output[output_size - 1] = '\0';
		} else
			*output = strdup(buffer);

		/* close both ends of the pipe */
		close(fd[0]);
		close(fd[1]);

		return STATE_UNKNOWN;
	}

	/* execute the command in the child process */
	if (pid == 0) {

		/* get root back so the next call works correctly */
		if (SETEUID(0) == -1 && debug)
			logit(LOG_WARNING, "WARNING: my_system() seteuid(0): %s", strerror(errno));

		drop_privileges(nrpe_user, nrpe_group, 1);	/* drop privileges */
		close(fd[0]);			/* close pipe for reading */
		setpgid(0, 0);			/* become process group leader */

		/* trap commands that timeout */
#ifdef HAVE_SIGACTION
		sig_action.sa_sigaction = NULL;
		sig_action.sa_handler = my_system_sighandler;
		sigfillset(&sig_action.sa_mask);
		sig_action.sa_flags = SA_NODEFER | SA_RESTART;
		sigaction(SIGALRM, &sig_action, NULL);
#else
		signal(SIGALRM, my_system_sighandler);
#endif	 /* HAVE_SIGACTION */
		alarm(timeout);

		fp = popen(command, "r");	/* run the command */

		/* report an error if we couldn't run the command */
		if (fp == NULL) {
			strncpy(buffer, "NRPE: Call to popen() failed\n", sizeof(buffer) - 1);
			buffer[sizeof(buffer) - 1] = '\x0';

			/* write the error back to the parent process */
			if (write(fd[1], buffer, strlen(buffer) + 1) == -1)
				logit(LOG_ERR, "ERROR: my_system() write(fd, buffer)-1 failed...");

			result = STATE_CRITICAL;

		} else {

			/* read all lines of output - supports Nagios 3.x multiline output */
			while ((bytes_read = fread(buffer, 1, sizeof(buffer) - 1, fp)) > 0) {
				/* write the output back to the parent process */
				if (write(fd[1], buffer, bytes_read) == -1)
					logit(LOG_ERR, "ERROR: my_system() write(fd, buffer)-2 failed...");
			}

			if (write(fd[1], "\0", 1) == -1)
				logit(LOG_ERR, "ERROR: my_system() write(fd, NULL) failed...");

			status = pclose(fp);	/* close the command and get termination status */

			/* report an error if we couldn't close the command */
			if (status == -1)
				result = STATE_CRITICAL;
			else if (!WIFEXITED(status))
				/* report an error if child died due to signal (Klas Lindfors) */
				result = STATE_CRITICAL;
			else
				result = WEXITSTATUS(status);
		}

		close(fd[1]);			/* close pipe for writing */
		alarm(0);				/* reset the alarm */
		exit(result);			/* return plugin exit code to parent process */

	} else {
		/* parent waits for child to finish executing command */

		commands_running++;

		close(fd[1]);			/* close pipe for writing */
		waitpid(pid, &status, 0);	/* wait for child to exit */
		time(&end_time);		/* get the end time for running the command */
		result = WEXITSTATUS(status);	/* get the exit code returned from the program */

		/* because of my idiotic idea of having UNKNOWN states be equivalent to -1, I must hack things a bit... */
		if (result == 255)
			result = STATE_UNKNOWN;

		/* check bounds on the return value */
		if (result < 0 || result > 3)
			result = STATE_UNKNOWN;

		if (packet_ver == NRPE_PACKET_VERSION_2) {
			output_size = sizeof(v2_packet);
			*output = calloc(1, output_size);
		} else {
			output_size = 1024 * 64;	/* Maximum buffer is 64K */
			*output = calloc(1, output_size);
		}

		/* try and read the results from the command output (retry if we encountered a signal) */
		for (;;) {
			bytes_read = read(fd[0], buffer, sizeof(buffer) - 1);
			if (bytes_read == 0)
				break;
			if (bytes_read == -1) {
				if (errno == EINTR)
					continue;
				else
					break;
			}
			if (tot_bytes < output_size)	/* If buffer is full, discard the rest */
				strncat(*output, buffer, output_size - tot_bytes - 1);
			tot_bytes += bytes_read;
		}

		(*output)[output_size - 1] = '\0';

		/* if there was a critical return code and no output AND the
		 * command time exceeded the timeout thresholds, assume a timeout */
		if (result == STATE_CRITICAL && bytes_read == -1 && (end_time - start_time) >= timeout) {
			*early_timeout = TRUE;

			/* send termination signal to child process group */
			kill((pid_t) (-pid), SIGTERM);
			kill((pid_t) (-pid), SIGKILL);
		}

		close(fd[0]);			/* close the pipe for reading */

		commands_running--;
	}

#ifdef DEBUG
	printf("my_system() end\n");
#endif

	return result;
}

/* handle timeouts when executing commands via my_system() */
void my_system_sighandler(int sig)
{
	exit(STATE_CRITICAL);		/* force the child process to exit... */
}

/* handle errors where connection takes too long */
void my_connection_sighandler(int sig)
{
	logit(LOG_ERR, "Connection has taken too long to establish. Exiting...");
	exit(STATE_CRITICAL);
}

/* drops privileges */
int drop_privileges(char *user, char *group, int full_drop)
{
	uid_t     uid = (uid_t)-1;
	gid_t     gid = (gid_t)-1;
	struct group *grp;
	struct passwd *pw;

	if (use_inetd == TRUE)
		return OK;

	/* set effective group ID */
	if (group != NULL) {

		/* see if this is a group name */
		if (strspn(group, "0123456789") < strlen(group)) {
			grp = (struct group *)getgrnam(group);
			if (grp != NULL)
				gid = (gid_t) (grp->gr_gid);
			else
				logit(LOG_ERR, "Warning: Could not get group entry for '%s'", group);
			endgrent();

		} else
			/* else we were passed the GID */
			gid = (gid_t) atoi(group);

		/* set effective group ID if other than current EGID */
		if (gid != getegid()) {
			if (setgid(gid) == -1)
				logit(LOG_ERR, "Warning: Could not set effective GID=%d", (int)gid);
		}
	}


	/* set effective user ID */
	if (user != NULL) {

		/* see if this is a user name */
		if (strspn(user, "0123456789") < strlen(user)) {
			pw = (struct passwd *)getpwnam(user);
			if (pw != NULL)
				uid = (uid_t) (pw->pw_uid);
			else
				logit(LOG_ERR, "Warning: Could not get passwd entry for '%s'", user);
			endpwent();

		} else
			/* else we were passed the UID */
			uid = (uid_t) atoi(user);

		if (uid != geteuid()) {
		/* set effective user ID if other than current EUID */
#ifdef HAVE_INITGROUPS
			/* initialize supplementary groups */
			if (initgroups(user, gid) == -1) {
				if (errno == EPERM)
					logit(LOG_ERR, "Warning: Unable to change supplementary groups using initgroups()");
				else {
					logit(LOG_ERR, "Warning: Possibly root user failed dropping privileges with initgroups()");
					return ERROR;
				}
			}
#endif

			if (full_drop) {
				if (setuid(uid) == -1)
					logit(LOG_ERR, "Warning: Could not set UID=%d", (int)uid);
			} else if (SETEUID(uid) == -1)
				logit(LOG_ERR, "Warning: Could not set effective UID=%d", (int)uid);
		}
	}

	return OK;
}

/* write an optional pid file */
int write_pid_file(void)
{
	int       fd;
	int       result = 0;
	pid_t     pid = 0;
	char      pbuf[16];

	/* no pid file was specified */
	if (pid_file == NULL)
		return OK;

	/* read existing pid file */
	if ((fd = open(pid_file, O_RDONLY)) >= 0) {

		result = read(fd, pbuf, (sizeof pbuf) - 1);
		close(fd);

		if (result > 0) {
			pbuf[result] = '\x0';
			pid = (pid_t) atoi(pbuf);

			/* if previous process is no longer running running, remove the old pid file */
			if (pid && (pid == getpid() || kill(pid, 0) < 0))
				unlink(pid_file);

			else {
				/* previous process is still running */
				logit(LOG_ERR, "There's already an NRPE server running (PID %lu).  Bailing out...", (unsigned long)pid);
				return ERROR;
			}
		}
	}

	/* write new pid file */
	if ((fd = open(pid_file, O_WRONLY | O_CREAT, 0644)) >= 0) {
		sprintf(pbuf, "%d\n", (int)getpid());

		if (write(fd, pbuf, strlen(pbuf)) == -1)
			logit(LOG_ERR, "ERROR: write_pid_file() write(fd, pbuf) failed...");

		close(fd);
		wrote_pid_file = TRUE;
	} else {
		logit(LOG_ERR, "Cannot write to pidfile '%s' - check your privileges.", pid_file);
		return ERROR;
	}

	return OK;
}

/* remove pid file */
int remove_pid_file(void)
{
	if (pid_file == NULL)
		return OK;				/* no pid file was specified */
	if (wrote_pid_file == FALSE)
		return OK;				/* pid file was not written */

	/* get root back so we can delete the pid file */
	if (SETEUID(0) == -1 && debug)
		logit(LOG_WARNING, "WARNING: remove_pid_file() seteuid(0): %s", strerror(errno));

	if (unlink(pid_file) == -1) {
		logit(LOG_ERR, "Cannot remove pidfile '%s' - check your privileges.", pid_file);
		return ERROR;
	}

	return OK;
}

#ifdef HAVE_SSL

void my_disconnect_sighandler(int sig)
{
	logit(LOG_ERR, "SSL_shutdown() has taken too long to complete. Exiting now..");
	exit(STATE_CRITICAL);
}

void complete_SSL_shutdown(SSL * ssl)
{
	/* Thanks to Jari Takkala (jtakkala@gmail.com) for the following information.

	   We need to call SSL_shutdown() at least twice, otherwise we'll
	   be left with data in the socket receive buffer, and the
	   subsequent process termination will cause TCP RST's to be sent
	   to the client.

	   See http://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/32219/diff
	   for more information.
	 */

	int       x;

	/* set disconnection handler */
	signal(SIGALRM, my_disconnect_sighandler);
	alarm(ssl_shutdown_timeout);

	for (x = 0; x < 4; x++) {
		if (SSL_shutdown(ssl))
			break;
	}

	alarm(0);
}
#endif	 /*HAVE_SSL */

/* bail if daemon is running as root */
int check_privileges(void)
{
	uid_t     uid = geteuid();
	gid_t     gid = getegid();

	if (uid == 0 || gid == 0) {
		logit(LOG_ERR, "Error: NRPE daemon cannot be run as user/group root!");
		exit(STATE_CRITICAL);
	}

	return OK;
}

/* handle signals (parent process) */
void sighandler(int sig)
{
	static char *sigs[] = {
		"EXIT", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE",
		"KILL", "USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT",
		"CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU",
		"XFSZ", "VTALRM", "PROF", "WINCH", "IO", "PWR", "UNUSED", "ZERR",
		"DEBUG", (char *)NULL
	};
	int       i;

	if (sig < 0)
		sig = -sig;

	for (i = 0; sigs[i] != (char *)NULL; i++) ;
	sig %= i;

	/* we received a SIGHUP, so restart... */
	if (sig == SIGHUP) {
		sigrestart = TRUE;
		logit(LOG_NOTICE, "Caught SIGHUP - restarting...\n");
	}

	/* else begin shutting down... */
	if (sig == SIGTERM) {
		/* if shutdown is already true, we're in a signal trap loop! */
		if (sigshutdown == TRUE)
			exit(STATE_CRITICAL);
		sigshutdown = TRUE;
		logit(LOG_NOTICE, "Caught SIG%s - shutting down...\n", sigs[sig]);
	}

	return;
}

/* handle signals (child processes) */
void child_sighandler(int sig)
{
	exit(0);					/* terminate */
}

/* tests whether or not a client request is valid */
int validate_request(v2_packet * v2pkt, v3_packet * v3pkt)
{
	u_int32_t	packet_crc32;
	u_int32_t	calculated_crc32;
	int32_t		pkt_size, buffer_size;
	char		*buff, *ptr;
	int			rc;
#ifdef ENABLE_COMMAND_ARGUMENTS
	int			x;
#endif

	/* check the crc 32 value */
	if (packet_ver >= NRPE_PACKET_VERSION_3) {

		buffer_size = ntohl(v3pkt->buffer_length);

		pkt_size = sizeof(v3_packet);
		pkt_size -= (packet_ver == NRPE_PACKET_VERSION_3 ? NRPE_V3_PACKET_SIZE_OFFSET : NRPE_V4_PACKET_SIZE_OFFSET);
		pkt_size += buffer_size;

		packet_crc32 = ntohl(v3pkt->crc32_value);
		v3pkt->crc32_value = 0L;
		v3pkt->alignment = 0;
		calculated_crc32 = calculate_crc32((char *)v3pkt, pkt_size);
	} else {
		packet_crc32 = ntohl(v2pkt->crc32_value);
		v2pkt->crc32_value = 0L;
		calculated_crc32 = calculate_crc32((char *)v2pkt, sizeof(v2_packet));
	}

	if (packet_crc32 != calculated_crc32) {
		logit(LOG_ERR, "Error: Request packet had invalid CRC32.");
		return ERROR;
	}

	/* make sure this is the right type of packet */
	if (ntohs(v2pkt->packet_type) != QUERY_PACKET) {
		logit(LOG_ERR, "Error: Request packet type was invalid!");
		return ERROR;
	}

	/* make sure buffer is terminated */
	if (packet_ver >= NRPE_PACKET_VERSION_3) {
		int32_t   l = ntohs(v3pkt->buffer_length);
		v3pkt->buffer[l - 1] = '\x0';
		buff = v3pkt->buffer;
	} else {
		v2pkt->buffer[MAX_PACKETBUFFER_LENGTH - 1] = '\x0';
		buff = v2pkt->buffer;
	}

	/* client must send some kind of request */
	if (buff[0] == '\0') {
		logit(LOG_ERR, "Error: Request contained no query!");
		return ERROR;
	}

	/* make sure request doesn't contain nasties */
	if (packet_ver >= NRPE_PACKET_VERSION_3)
		rc = contains_nasty_metachars(v3pkt->buffer);
	else
		rc = contains_nasty_metachars(v2pkt->buffer);
	if (rc == TRUE) {
		logit(LOG_ERR, "Error: Request contained illegal metachars!");
		return ERROR;
	}

	/* make sure the request doesn't contain arguments */
	if (strchr(buff, '!')) {
#ifdef ENABLE_COMMAND_ARGUMENTS
		if (allow_arguments == FALSE) {
			logit(LOG_ERR, "Error: Request contained command arguments, but argument option is not enabled!");
			return ERROR;
		}
#else
		logit(LOG_ERR, "Error: Request contained command arguments!");
		return ERROR;
#endif
	}

	/* get command name */
#ifdef ENABLE_COMMAND_ARGUMENTS
	ptr = strtok(buff, "!");
#else
	ptr = buff;
#endif
	command_name = strdup(ptr);
	if (command_name == NULL) {
		logit(LOG_ERR, "Error: Memory allocation failed");
		return ERROR;
	}
#ifdef ENABLE_COMMAND_ARGUMENTS
	/* get command arguments */
	if (allow_arguments == TRUE) {

		for (x = 0; x < MAX_COMMAND_ARGUMENTS; x++) {
			ptr = strtok(NULL, "!");
			if (ptr == NULL)
				break;
			macro_argv[x] = strdup(ptr);
			if (macro_argv[x] == NULL) {
				logit(LOG_ERR, "Error: Memory allocation failed");
				return ERROR;
			}
			if (!strcmp(macro_argv[x], "")) {
				logit(LOG_ERR, "Error: Request contained an empty command argument");
				return ERROR;
			}
			if (strstr(macro_argv[x], "$(")) {
# ifndef ENABLE_BASH_COMMAND_SUBSTITUTION
				logit(LOG_ERR, "Error: Request contained a bash command substitution!");
				return ERROR;
# else
				if (FALSE == allow_bash_cmd_subst) {
					logit(LOG_ERR, "Error: Request contained a bash command substitution, but they are disallowed!");
					return ERROR;
				}
# endif
			}
		}
	}
#endif
	return OK;
}

/* tests whether a buffer contains illegal metachars */
int contains_nasty_metachars(char *str)
{
	int       result;

	if (str == NULL)
		return FALSE;

	result = strcspn(str, nasty_metachars);
	if (result != strlen(str))
		return TRUE;

	return FALSE;
}

/* replace macros in buffer */
int process_macros(char *input_buffer, char *output_buffer, int buffer_length)
{
	char     *temp_buffer;
	int       in_macro;
	int       arg_index = 0;
	char     *selected_macro = NULL;

	strcpy(output_buffer, "");

	in_macro = FALSE;

	for (temp_buffer = my_strsep(&input_buffer, "$"); temp_buffer != NULL;
		 temp_buffer = my_strsep(&input_buffer, "$")) {

		selected_macro = NULL;

		if (in_macro == FALSE) {
			if (strlen(output_buffer) + strlen(temp_buffer) < buffer_length - 1) {
				strncat(output_buffer, temp_buffer, buffer_length - strlen(output_buffer) - 1);
				output_buffer[buffer_length - 1] = '\x0';
			}
			in_macro = TRUE;

		} else {

			if (strlen(output_buffer) + strlen(temp_buffer) < buffer_length - 1) {

				/* argument macro */
				if (strstr(temp_buffer, "ARG") == temp_buffer) {
					arg_index = atoi(temp_buffer + 3);
					if (arg_index >= 1 && arg_index <= MAX_COMMAND_ARGUMENTS)
						selected_macro = macro_argv[arg_index - 1];

				} else if (!strcmp(temp_buffer, "")) {
					/* an escaped $ is done by specifying two $$ next to each other */
					strncat(output_buffer, "$", buffer_length - strlen(output_buffer) - 1);

				} else {
					/* a non-macro, just some user-defined string between two $s */
					strncat(output_buffer, "$", buffer_length - strlen(output_buffer) - 1);
					output_buffer[buffer_length - 1] = '\x0';
					strncat(output_buffer, temp_buffer,
							buffer_length - strlen(output_buffer) - 1);
					output_buffer[buffer_length - 1] = '\x0';
					strncat(output_buffer, "$", buffer_length - strlen(output_buffer) - 1);
				}


				/* insert macro */
				if (selected_macro != NULL)
					strncat(output_buffer, (selected_macro == NULL) ? "" : selected_macro,
							buffer_length - strlen(output_buffer) - 1);

				output_buffer[buffer_length - 1] = '\x0';
			}

			in_macro = FALSE;
		}
	}

	return OK;
}

/* process command line arguments */
int process_arguments(int argc, char **argv)
{
	char      optchars[MAX_INPUT_BUFFER];
	int       c = 1;
	int       have_mode = FALSE;
#ifdef HAVE_GETOPT_LONG
	int       option_index = 0;
	static struct option long_options[] = {
		{"config", required_argument, 0, 'c'},
		{"inetd", no_argument, 0, 'i'},
		/* To compatibility between short and long options but not used on AIX */
		{"src", no_argument, 0, 's'},
		{"no-forking", no_argument, 0, 'f'},
		{"4", no_argument, 0, '4'},
		{"ipv6", no_argument, 0, '6'},
		{"daemon", no_argument, 0, 'd'},
		{"no-ssl", no_argument, 0, 'n'},
		{"help", no_argument, 0, 'h'},
		{"license", no_argument, 0, 'l'},
		{"version", no_argument, 0, 'V'},
		{0, 0, 0, 0}
	};
#endif

	/* no options were supplied */
	if (argc < 2)
		return ERROR;

	snprintf(optchars, MAX_INPUT_BUFFER, "c:hVldi46nsf");

	while (1) {
#ifdef HAVE_GETOPT_LONG
		c = getopt_long(argc, argv, optchars, long_options, &option_index);
#else
		c = getopt(argc, argv, optchars);
#endif
		if (c == -1 || c == EOF)
			break;

		/* process all arguments */
		switch (c) {

		case '?':
		case 'h':
			show_help = TRUE;
			break;

		case 'V':
			show_version = TRUE;
			have_mode = TRUE;
			break;

		case 'l':
			show_license = TRUE;
			break;

		case 'c':
			strncpy(config_file, optarg, sizeof(config_file));
			config_file[sizeof(config_file) - 1] = '\x0';
			break;

		case 'd':
			use_inetd = FALSE;
			have_mode = TRUE;
			break;

		case 'i':
			use_inetd = TRUE;
			have_mode = TRUE;
			break;

		case '4':
			address_family = AF_INET;
			break;

		case '6':
			address_family = AF_INET6;
			break;

		case 'n':
			use_ssl = FALSE;
			break;

		case 's':				/* Argument s to indicate SRC option */
			use_src = TRUE;
			have_mode = TRUE;
			break;

		case 'f':
			use_inetd = FALSE;
			no_forking = TRUE;
			have_mode = TRUE;
			break;

		default:
			return ERROR;
		}
	}

	/* bail if we didn't get required args */
	if (have_mode == FALSE)
		return ERROR;

	return OK;
}