summaryrefslogtreecommitdiffstats
path: root/src/openvpn/manage.c
blob: 4f0945ca5c640d481ed7bb53de45925145b777f2 (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
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
/*
 *  OpenVPN -- An application to securely tunnel IP networks
 *             over a single TCP/UDP port, with support for SSL/TLS-based
 *             session authentication and key exchange,
 *             packet encryption, packet authentication, and
 *             packet compression.
 *
 *  Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2
 *  as published by the Free Software Foundation.
 *
 *  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 (see the file COPYING included with this
 *  distribution); if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_MSC_VER)
#include "config-msvc.h"
#endif

#include "syshead.h"

#ifdef ENABLE_MANAGEMENT

#include "error.h"
#include "fdmisc.h"
#include "options.h"
#include "sig.h"
#include "event.h"
#include "otime.h"
#include "integer.h"
#include "misc.h"
#include "ssl.h"
#include "common.h"
#include "manage.h"

#include "memdbg.h"

#ifdef ENABLE_PKCS11
#include "pkcs11.h"
#endif

#define MANAGEMENT_ECHO_PULL_INFO 0

#if MANAGEMENT_ECHO_PULL_INFO
#define MANAGEMENT_ECHO_FLAGS LOG_PRINT_INTVAL
#else
#define MANAGEMENT_ECHO_FLAGS 0
#endif

/* tag for blank username/password */
static const char blank_up[] = "[[BLANK]]";

struct management *management; /* GLOBAL */

/* static forward declarations */
static void man_output_standalone (struct management *man, volatile int *signal_received);
static void man_reset_client_socket (struct management *man, const bool exiting);

static void
man_help ()
{
  msg (M_CLIENT, "Management Interface for %s", title_string);
  msg (M_CLIENT, "Commands:");
  msg (M_CLIENT, "auth-retry t           : Auth failure retry mode (none,interact,nointeract).");
  msg (M_CLIENT, "bytecount n            : Show bytes in/out, update every n secs (0=off).");
  msg (M_CLIENT, "echo [on|off] [N|all]  : Like log, but only show messages in echo buffer.");
  msg (M_CLIENT, "exit|quit              : Close management session.");
  msg (M_CLIENT, "forget-passwords       : Forget passwords entered so far.");
  msg (M_CLIENT, "help                   : Print this message.");
  msg (M_CLIENT, "hold [on|off|release]  : Set/show hold flag to on/off state, or"); 
  msg (M_CLIENT, "                         release current hold and start tunnel."); 
  msg (M_CLIENT, "kill cn                : Kill the client instance(s) having common name cn.");
  msg (M_CLIENT, "kill IP:port           : Kill the client instance connecting from IP:port.");
  msg (M_CLIENT, "load-stats             : Show global server load stats.");
  msg (M_CLIENT, "log [on|off] [N|all]   : Turn on/off realtime log display");
  msg (M_CLIENT, "                         + show last N lines or 'all' for entire history.");
  msg (M_CLIENT, "mute [n]               : Set log mute level to n, or show level if n is absent.");
  msg (M_CLIENT, "needok type action     : Enter confirmation for NEED-OK request of 'type',");
  msg (M_CLIENT, "                         where action = 'ok' or 'cancel'.");
  msg (M_CLIENT, "needstr type action    : Enter confirmation for NEED-STR request of 'type',");
  msg (M_CLIENT, "                         where action is reply string.");
  msg (M_CLIENT, "net                    : (Windows only) Show network info and routing table.");
  msg (M_CLIENT, "password type p        : Enter password p for a queried OpenVPN password.");
  msg (M_CLIENT, "remote type [host port] : Override remote directive, type=ACCEPT|MOD|SKIP.");
  msg (M_CLIENT, "proxy type [host port flags] : Enter dynamic proxy server info.");
  msg (M_CLIENT, "pid                    : Show process ID of the current OpenVPN process.");
#ifdef ENABLE_PKCS11
  msg (M_CLIENT, "pkcs11-id-count        : Get number of available PKCS#11 identities.");
  msg (M_CLIENT, "pkcs11-id-get index    : Get PKCS#11 identity at index.");
#endif
#ifdef MANAGEMENT_DEF_AUTH
  msg (M_CLIENT, "client-auth CID KID    : Authenticate client-id/key-id CID/KID (MULTILINE)");
  msg (M_CLIENT, "client-auth-nt CID KID : Authenticate client-id/key-id CID/KID");
  msg (M_CLIENT, "client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID with log reason");
  msg (M_CLIENT, "                             text R and optional client reason text CR");
  msg (M_CLIENT, "client-kill CID [M]    : Kill client instance CID with message M (def=RESTART)");
  msg (M_CLIENT, "env-filter [level]     : Set env-var filter level");
#ifdef MANAGEMENT_PF
  msg (M_CLIENT, "client-pf CID          : Define packet filter for client CID (MULTILINE)");
#endif
#endif
#ifdef MANAGMENT_EXTERNAL_KEY
  msg (M_CLIENT, "rsa-sig                : Enter an RSA signature in response to >RSA_SIGN challenge");
  msg (M_CLIENT, "                         Enter signature base64 on subsequent lines followed by END");
  msg (M_CLIENT, "certificate            : Enter a client certificate in response to >NEED-CERT challenge");
  msg (M_CLIENT, "                         Enter certificate base64 on subsequent lines followed by END");
#endif
  msg (M_CLIENT, "signal s               : Send signal s to daemon,");
  msg (M_CLIENT, "                         s = SIGHUP|SIGTERM|SIGUSR1|SIGUSR2.");
  msg (M_CLIENT, "state [on|off] [N|all] : Like log, but show state history.");
  msg (M_CLIENT, "status [n]             : Show current daemon status info using format #n.");
  msg (M_CLIENT, "test n                 : Produce n lines of output for testing/debugging.");
  msg (M_CLIENT, "username type u        : Enter username u for a queried OpenVPN username.");
  msg (M_CLIENT, "verb [n]               : Set log verbosity level to n, or show if n is absent.");
  msg (M_CLIENT, "version                : Show current version number.");
  msg (M_CLIENT, "END");
}

static const char *
man_state_name (const int state)
{
  switch (state)
    {
    case OPENVPN_STATE_INITIAL:
      return "INITIAL";
    case OPENVPN_STATE_CONNECTING:
      return "CONNECTING";
    case OPENVPN_STATE_WAIT:
      return "WAIT";
    case OPENVPN_STATE_AUTH:
      return "AUTH";
    case OPENVPN_STATE_GET_CONFIG:
      return "GET_CONFIG";
    case OPENVPN_STATE_ASSIGN_IP:
      return "ASSIGN_IP";
    case OPENVPN_STATE_ADD_ROUTES:
      return "ADD_ROUTES";
    case OPENVPN_STATE_CONNECTED:
      return "CONNECTED";
    case OPENVPN_STATE_RECONNECTING:
      return "RECONNECTING";
    case OPENVPN_STATE_EXITING:
      return "EXITING";
    case OPENVPN_STATE_RESOLVE:
      return "RESOLVE";
    case OPENVPN_STATE_TCP_CONNECT:
      return "TCP_CONNECT";
    default:
      return "?";
    }
}

static void
man_welcome (struct management *man)
{
  msg (M_CLIENT, ">INFO:OpenVPN Management Interface Version %d -- type 'help' for more info",
       MANAGEMENT_VERSION);
  if (man->persist.special_state_msg)
    msg (M_CLIENT, "%s", man->persist.special_state_msg);
}

static inline bool
man_password_needed (struct management *man)
{
  return man->settings.up.defined && !man->connection.password_verified;
}

static void
man_check_password (struct management *man, const char *line)
{
  if (man_password_needed (man))
    {
      if (streq (line, man->settings.up.password))
	{
	  man->connection.password_verified = true;
	  msg (M_CLIENT, "SUCCESS: password is correct");
	  man_welcome (man);
	}
      else
	{
	  man->connection.password_verified = false;
	  msg (M_CLIENT, "ERROR: bad password");
	  if (++man->connection.password_tries >= MANAGEMENT_N_PASSWORD_RETRIES)
	    {
	      msg (M_WARN, "MAN: client connection rejected after %d failed password attempts",
		   MANAGEMENT_N_PASSWORD_RETRIES);
	      man->connection.halt = true;
	    }
	}
    }
}

static void
man_update_io_state (struct management *man)
{
  if (socket_defined (man->connection.sd_cli))
    {
      if (buffer_list_defined (man->connection.out))
	{
	  man->connection.state = MS_CC_WAIT_WRITE;
	}
      else
	{
	  man->connection.state = MS_CC_WAIT_READ;
	}
    }
}

static void
man_output_list_push_finalize (struct management *man)
{
  if (management_connected (man))
    {
      man_update_io_state (man);
      if (!man->persist.standalone_disabled)
	{
	  volatile int signal_received = 0;
	  man_output_standalone (man, &signal_received);
	}
    }
}

static void
man_output_list_push_str (struct management *man, const char *str)
{
  if (management_connected (man) && str)
    {
      buffer_list_push (man->connection.out, (const unsigned char *) str);
    }
}

static void
man_output_list_push (struct management *man, const char *str)
{
  man_output_list_push_str (man, str);
  man_output_list_push_finalize (man);
}

static void
man_prompt (struct management *man)
{
  if (man_password_needed (man))
    man_output_list_push (man, "ENTER PASSWORD:");
#if 0 /* should we use prompt? */
  else
    man_output_list_push (man, ">");
#endif
}

static void
man_delete_unix_socket (struct management *man)
{
#if UNIX_SOCK_SUPPORT
  if ((man->settings.flags & (MF_UNIX_SOCK|MF_CONNECT_AS_CLIENT)) == MF_UNIX_SOCK)
    socket_delete_unix (&man->settings.local_unix);
#endif
}

static void
man_close_socket (struct management *man, const socket_descriptor_t sd)
{
#ifndef WIN32
  /*
   * Windows doesn't need this because the ne32 event is permanently
   * enabled at struct management scope.
   */
  if (man->persist.callback.delete_event)
    (*man->persist.callback.delete_event) (man->persist.callback.arg, sd);
#endif
  openvpn_close_socket (sd);
}

static void
virtual_output_callback_func (void *arg, const unsigned int flags, const char *str)
{
  struct management *man = (struct management *) arg;
  static int recursive_level = 0; /* GLOBAL */

# define AF_DID_PUSH  (1<<0)
# define AF_DID_RESET (1<<1)

  if (!recursive_level) /* don't allow recursion */
    {
      struct gc_arena gc = gc_new ();
      struct log_entry e;
      const char *out = NULL;
      unsigned int action_flags = 0;

      ++recursive_level;

      CLEAR (e);
      update_time ();
      e.timestamp = now;
      e.u.msg_flags = flags;
      e.string = str;

      if (flags & M_FATAL)
	man->persist.standalone_disabled = false;

      if (flags != M_CLIENT)
	log_history_add (man->persist.log, &e);

      if (!man_password_needed (man))
	{
	  if (flags == M_CLIENT)
	    out = log_entry_print (&e, LOG_PRINT_CRLF, &gc);
	  else if (man->connection.log_realtime)
	    out = log_entry_print (&e, LOG_PRINT_INT_DATE
				   |   LOG_PRINT_MSG_FLAGS
				   |   LOG_PRINT_LOG_PREFIX
				   |   LOG_PRINT_CRLF, &gc);
	  if (out)
	    {
	      man_output_list_push_str (man, out);
	      action_flags |= AF_DID_PUSH;
	    }
	  if (flags & M_FATAL)
	    {
	      out = log_entry_print (&e, LOG_FATAL_NOTIFY|LOG_PRINT_CRLF, &gc);
	      if (out)
		{
		  man_output_list_push_str (man, out);
		  action_flags |= (AF_DID_PUSH|AF_DID_RESET);
		}
	    }
	}

      gc_free (&gc);

      if (action_flags & AF_DID_PUSH)
        man_output_list_push_finalize (man);
      if (action_flags & AF_DID_RESET)
        man_reset_client_socket (man, true);

      --recursive_level;
    }
}

/*
 * Given a signal, return the signal with possible remapping applied,
 * or -1 if the signal should be ignored.
 */
static int
man_mod_signal (const struct management *man, const int signum)
{
  const unsigned int flags = man->settings.mansig;
  int s = signum;
  if (s == SIGUSR1)
    {
      if (flags & MANSIG_MAP_USR1_TO_HUP)
	s = SIGHUP;
      if (flags & MANSIG_MAP_USR1_TO_TERM)
	s = SIGTERM;
    }
  if (flags & MANSIG_IGNORE_USR1_HUP)
    {
      if (s == SIGHUP || s == SIGUSR1)
	s = -1;
    }
  return s;
}

static void
man_signal (struct management *man, const char *name)
{
  const int sig = parse_signal (name);
  if (sig >= 0)
    {
      const int sig_mod = man_mod_signal (man, sig);
      if (sig_mod >= 0)
	{
	  throw_signal (sig_mod);
	  msg (M_CLIENT, "SUCCESS: signal %s thrown", signal_name (sig_mod, true));
	}
      else
	{
	  if (man->persist.special_state_msg)
	    msg (M_CLIENT, "%s", man->persist.special_state_msg);
	  else
	    msg (M_CLIENT, "ERROR: signal '%s' is currently ignored", name);
	}
    }
  else
    {
      msg (M_CLIENT, "ERROR: signal '%s' is not a known signal type", name);
    }
}

static void
man_status (struct management *man, const int version, struct status_output *so)
{
  if (man->persist.callback.status)
    {
      (*man->persist.callback.status) (man->persist.callback.arg, version, so);
    }
  else
    {
      msg (M_CLIENT, "ERROR: The 'status' command is not supported by the current daemon mode");
    }
}

static void
man_bytecount (struct management *man, const int update_seconds)
{
  if (update_seconds >= 0)
    man->connection.bytecount_update_seconds = update_seconds;
  else
    man->connection.bytecount_update_seconds = 0;
  msg (M_CLIENT, "SUCCESS: bytecount interval changed");
}

void
man_bytecount_output_client (struct management *man)
{
  char in[32];
  char out[32];
  /* do in a roundabout way to work around possible mingw or mingw-glibc bug */
  openvpn_snprintf (in, sizeof (in), counter_format, man->persist.bytes_in);
  openvpn_snprintf (out, sizeof (out), counter_format, man->persist.bytes_out);
  msg (M_CLIENT, ">BYTECOUNT:%s,%s", in, out);
  man->connection.bytecount_last_update = now;
}

#ifdef MANAGEMENT_DEF_AUTH

void
man_bytecount_output_server (struct management *man,
			     const counter_type *bytes_in_total,
			     const counter_type *bytes_out_total,
			     struct man_def_auth_context *mdac)
{
  char in[32];
  char out[32];
  /* do in a roundabout way to work around possible mingw or mingw-glibc bug */
  openvpn_snprintf (in, sizeof (in), counter_format, *bytes_in_total);
  openvpn_snprintf (out, sizeof (out), counter_format, *bytes_out_total);
  msg (M_CLIENT, ">BYTECOUNT_CLI:%lu,%s,%s", mdac->cid, in, out);
  mdac->bytecount_last_update = now;
}

#endif

static void
man_kill (struct management *man, const char *victim)
{
  struct gc_arena gc = gc_new ();

  if (man->persist.callback.kill_by_cn && man->persist.callback.kill_by_addr)
    {
      struct buffer buf;
      char p1[128];
      char p2[128];
      int n_killed;

      buf_set_read (&buf, (uint8_t*) victim, strlen (victim) + 1);
      buf_parse (&buf, ':', p1, sizeof (p1));
      buf_parse (&buf, ':', p2, sizeof (p2));

      if (strlen (p1) && strlen (p2))
	{
	  /* IP:port specified */
	  bool status;
	  const in_addr_t addr = getaddr (GETADDR_HOST_ORDER|GETADDR_MSG_VIRT_OUT, p1, 0, &status, NULL);
	  if (status)
	    {
	      const int port = atoi (p2);
	      if (port > 0 && port < 65536)
		{
		  n_killed = (*man->persist.callback.kill_by_addr) (man->persist.callback.arg, addr, port);
		  if (n_killed > 0)
		    {
		      msg (M_CLIENT, "SUCCESS: %d client(s) at address %s:%d killed",
			   n_killed,
			   print_in_addr_t (addr, 0, &gc),
			   port);
		    }
		  else
		    {
		      msg (M_CLIENT, "ERROR: client at address %s:%d not found",
			   print_in_addr_t (addr, 0, &gc),
			   port);
		    }
		}
	      else
		{
		  msg (M_CLIENT, "ERROR: port number is out of range: %s", p2);
		}
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: error parsing IP address: %s", p1);
	    }
	}
      else if (strlen (p1))
	{
	  /* common name specified */
	  n_killed = (*man->persist.callback.kill_by_cn) (man->persist.callback.arg, p1);
	  if (n_killed > 0)
	    {
	      msg (M_CLIENT, "SUCCESS: common name '%s' found, %d client(s) killed", p1, n_killed);
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: common name '%s' not found", p1);
	    }
	}
      else
	{
	  msg (M_CLIENT, "ERROR: kill parse");
	}
    }
  else
    {
      msg (M_CLIENT, "ERROR: The 'kill' command is not supported by the current daemon mode");
    }

  gc_free (&gc);
}

/*
 * General-purpose history command handler
 * for the log and echo commands.
 */
static void
man_history (struct management *man,
	     const char *parm,
	     const char *type,
	     struct log_history *log,
	     bool *realtime,
	     const unsigned int lep_flags)
{
  struct gc_arena gc = gc_new ();
  int n = 0;

  if (streq (parm, "on"))
    {
      *realtime = true;
      msg (M_CLIENT, "SUCCESS: real-time %s notification set to ON", type);
    }
  else if (streq (parm, "off"))
    {
      *realtime = false;
      msg (M_CLIENT, "SUCCESS: real-time %s notification set to OFF", type);
    }
  else if (streq (parm, "all") || (n = atoi (parm)) > 0)
    {
      const int size = log_history_size (log);
      const int start = (n ? n : size) - 1;
      int i;

      for (i = start; i >= 0; --i)
	{
	  const struct log_entry *e = log_history_ref (log, i);
	  if (e)
	    {
	      const char *out = log_entry_print (e, lep_flags, &gc);
	      virtual_output_callback_func (man, M_CLIENT, out);
	    }
	}
      msg (M_CLIENT, "END");
    }
  else
    {
      msg (M_CLIENT, "ERROR: %s parameter must be 'on' or 'off' or some number n or 'all'", type);
    }

  gc_free (&gc);
}

static void
man_log (struct management *man, const char *parm)
{
  man_history (man,
	       parm,
	       "log",
	       man->persist.log,
	       &man->connection.log_realtime,
	       LOG_PRINT_INT_DATE|LOG_PRINT_MSG_FLAGS);
}

static void
man_echo (struct management *man, const char *parm)
{
  man_history (man,
	       parm,
	       "echo",
	       man->persist.echo,
	       &man->connection.echo_realtime,
	       LOG_PRINT_INT_DATE|MANAGEMENT_ECHO_FLAGS);
}

static void
man_state (struct management *man, const char *parm)
{
  man_history (man,
	       parm,
	       "state",
	       man->persist.state,
	       &man->connection.state_realtime,
	       LOG_PRINT_INT_DATE|LOG_PRINT_STATE|
	       LOG_PRINT_LOCAL_IP|LOG_PRINT_REMOTE_IP);
}

static void
man_up_finalize (struct management *man)
{
  switch (man->connection.up_query_mode)
    {
    case UP_QUERY_USER_PASS:
      if (!strlen (man->connection.up_query.username))
	break;
      /* fall through */
    case UP_QUERY_PASS:
    case UP_QUERY_NEED_OK:
    case UP_QUERY_NEED_STR:
      if (strlen (man->connection.up_query.password))
	man->connection.up_query.defined = true;
      break;
    case UP_QUERY_DISABLED:
      man->connection.up_query.defined = false;
      break;
    default:
      ASSERT (0);
    }
}

static void
man_query_user_pass (struct management *man,
		     const char *type,
		     const char *string,
		     const bool needed,
		     const char *prompt,
		     char *dest,
		     int len)
{
  if (needed)
    {
      ASSERT (man->connection.up_query_type);
      if (streq (man->connection.up_query_type, type))
	{
	  strncpynt (dest, string, len);
	  man_up_finalize (man);
	  msg (M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified",
	       type,
	       prompt);
	}
      else
	msg (M_CLIENT, "ERROR: %s of type '%s' entered, but we need one of type '%s'",
	     prompt,
	     type,
	     man->connection.up_query_type);
    }
  else
    {
      msg (M_CLIENT, "ERROR: no %s is currently needed at this time", prompt);
    }
}

static void
man_query_username (struct management *man, const char *type, const char *string)
{
  const bool needed = ((man->connection.up_query_mode == UP_QUERY_USER_PASS
			) && man->connection.up_query_type);
  man_query_user_pass (man, type, string, needed, "username", man->connection.up_query.username, USER_PASS_LEN);
}

static void
man_query_password (struct management *man, const char *type, const char *string)
{
  const bool needed = ((man->connection.up_query_mode == UP_QUERY_PASS
			|| man->connection.up_query_mode == UP_QUERY_USER_PASS
			) && man->connection.up_query_type);
  if (!string[0]) /* allow blank passwords to be passed through using the blank_up tag */
    string = blank_up;
  man_query_user_pass (man, type, string, needed, "password", man->connection.up_query.password, USER_PASS_LEN);
}

static void
man_query_need_ok (struct management *man, const char *type, const char *action)
{
  const bool needed = ((man->connection.up_query_mode == UP_QUERY_NEED_OK) && man->connection.up_query_type);
  man_query_user_pass (man, type, action, needed, "needok-confirmation", man->connection.up_query.password, USER_PASS_LEN);
}

static void
man_query_need_str (struct management *man, const char *type, const char *action)
{
  const bool needed = ((man->connection.up_query_mode == UP_QUERY_NEED_STR) && man->connection.up_query_type);
  man_query_user_pass (man, type, action, needed, "needstr-string", man->connection.up_query.password, USER_PASS_LEN);
}

static void
man_forget_passwords (struct management *man)
{
#ifdef ENABLE_CRYPTO
  ssl_purge_auth (false);
  msg (M_CLIENT, "SUCCESS: Passwords were forgotten");
#endif
}

static void
man_net (struct management *man)
{
  if (man->persist.callback.show_net)
    {
      (*man->persist.callback.show_net) (man->persist.callback.arg, M_CLIENT);
    }
  else
    {
      msg (M_CLIENT, "ERROR: The 'net' command is not supported by the current daemon mode");
    }
}

#ifdef ENABLE_PKCS11

static void
man_pkcs11_id_count (struct management *man)
{
  msg (M_CLIENT, ">PKCS11ID-COUNT:%d", pkcs11_management_id_count ());
}

static void
man_pkcs11_id_get (struct management *man, const int index)
{
  char *id = NULL;
  char *base64 = NULL;

  if (pkcs11_management_id_get (index, &id, &base64))
    msg (M_CLIENT, ">PKCS11ID-ENTRY:'%d', ID:'%s', BLOB:'%s'", index, id, base64);
  else
    msg (M_CLIENT, ">PKCS11ID-ENTRY:'%d'", index);

  if (id != NULL)
    free (id);
  if (base64 != NULL)
    free (base64);
}

#endif

static void
man_hold (struct management *man, const char *cmd)
{
  if (cmd)
    {
      if (streq (cmd, "on"))
	{
	  man->settings.flags |= MF_HOLD;
	  msg (M_CLIENT, "SUCCESS: hold flag set to ON");
	}
      else if (streq (cmd, "off"))
	{
	  man->settings.flags &= ~MF_HOLD;
	  msg (M_CLIENT, "SUCCESS: hold flag set to OFF");
	}
      else if (streq (cmd, "release"))
	{
	  man->persist.hold_release = true;
	  msg (M_CLIENT, "SUCCESS: hold release succeeded");
	}
      else
	{
	  msg (M_CLIENT, "ERROR: bad hold command parameter");
	}
    }
  else
    msg (M_CLIENT, "SUCCESS: hold=%d", BOOL_CAST(man->settings.flags & MF_HOLD));
}

#ifdef MANAGEMENT_IN_EXTRA

#define IER_RESET      0
#define IER_NEW        1

static void
in_extra_reset (struct man_connection *mc, const int mode)
{
  if (mc)
    {
      if (mode != IER_NEW)
	{
	  mc->in_extra_cmd = IEC_UNDEF;
#ifdef MANAGEMENT_DEF_AUTH
	  mc->in_extra_cid = 0;
	  mc->in_extra_kid = 0;
#endif
	}
      if (mc->in_extra)
	{
	  buffer_list_free (mc->in_extra);
	  mc->in_extra = NULL;
	}
      if (mode == IER_NEW)
	mc->in_extra = buffer_list_new (0);
    }
}

static void
in_extra_dispatch (struct management *man)
{
   switch (man->connection.in_extra_cmd)
    {
#ifdef MANAGEMENT_DEF_AUTH
    case IEC_CLIENT_AUTH:
       if (man->persist.callback.client_auth)
	{
	  const bool status = (*man->persist.callback.client_auth)
	    (man->persist.callback.arg,
	     man->connection.in_extra_cid,
	     man->connection.in_extra_kid,
	     true,
	     NULL,
	     NULL,
	     man->connection.in_extra);
	  man->connection.in_extra = NULL;
	  if (status)
	    {
	      msg (M_CLIENT, "SUCCESS: client-auth command succeeded");
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: client-auth command failed");
	    }
	}
      else
	{
	  msg (M_CLIENT, "ERROR: The client-auth command is not supported by the current daemon mode");
	}
      break;
#endif
#ifdef MANAGEMENT_PF
    case IEC_CLIENT_PF:
      if (man->persist.callback.client_pf)
	{
	  const bool status = (*man->persist.callback.client_pf)
	    (man->persist.callback.arg,
	     man->connection.in_extra_cid,
	     man->connection.in_extra);
	  man->connection.in_extra = NULL;
	  if (status)
	    {
	      msg (M_CLIENT, "SUCCESS: client-pf command succeeded");
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: client-pf command failed");
	    }
	}
      else
	{
	  msg (M_CLIENT, "ERROR: The client-pf command is not supported by the current daemon mode");
	}
      break;
#endif
#ifdef MANAGMENT_EXTERNAL_KEY
    case IEC_RSA_SIGN:
      man->connection.ext_key_state = EKS_READY;
      buffer_list_free (man->connection.ext_key_input);
      man->connection.ext_key_input = man->connection.in_extra;
      man->connection.in_extra = NULL;
      return;
    case IEC_CERTIFICATE:
      man->connection.ext_cert_state = EKS_READY;
      buffer_list_free (man->connection.ext_cert_input);
      man->connection.ext_cert_input = man->connection.in_extra;
      man->connection.in_extra = NULL;
      return;
#endif
    }
   in_extra_reset (&man->connection, IER_RESET);
}

#endif /* MANAGEMENT_IN_EXTRA */

#ifdef MANAGEMENT_DEF_AUTH

static bool
parse_cid (const char *str, unsigned long *cid)
{
  if (sscanf (str, "%lu", cid) == 1)
    return true;
  else
    {
      msg (M_CLIENT, "ERROR: cannot parse CID");
      return false;
    }
}

static bool
parse_kid (const char *str, unsigned int *kid)
{
  if (sscanf (str, "%u", kid) == 1)
    return true;
  else
    {
      msg (M_CLIENT, "ERROR: cannot parse KID");
      return false;
    }
}

static void
man_client_auth (struct management *man, const char *cid_str, const char *kid_str, const bool extra)
{
  struct man_connection *mc = &man->connection;
  mc->in_extra_cid = 0;
  mc->in_extra_kid = 0;
  if (parse_cid (cid_str, &mc->in_extra_cid)
      && parse_kid (kid_str, &mc->in_extra_kid))
    {
      mc->in_extra_cmd = IEC_CLIENT_AUTH;
      in_extra_reset (mc, IER_NEW);
      if (!extra)
	in_extra_dispatch (man);
    }
}

static void
man_client_deny (struct management *man, const char *cid_str, const char *kid_str, const char *reason, const char *client_reason)
{
  unsigned long cid = 0;
  unsigned int kid = 0;
  if (parse_cid (cid_str, &cid) && parse_kid (kid_str, &kid))
    {
      if (man->persist.callback.client_auth)
	{
	  const bool status = (*man->persist.callback.client_auth)
	    (man->persist.callback.arg,
	     cid,
	     kid,
	     false,
	     reason,
	     client_reason,
	     NULL);
	  if (status)
	    {
	      msg (M_CLIENT, "SUCCESS: client-deny command succeeded");
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: client-deny command failed");
	    }
	}
      else
	{
	  msg (M_CLIENT, "ERROR: The client-deny command is not supported by the current daemon mode");
	}
    }
}

static void
man_client_kill (struct management *man, const char *cid_str, const char *kill_msg)
{
  unsigned long cid = 0;
  if (parse_cid (cid_str, &cid))
    {
      if (man->persist.callback.kill_by_cid)
	{
	  const bool status = (*man->persist.callback.kill_by_cid) (man->persist.callback.arg, cid, kill_msg);
	  if (status)
	    {
	      msg (M_CLIENT, "SUCCESS: client-kill command succeeded");
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: client-kill command failed");
	    }
	}
      else
	{
	  msg (M_CLIENT, "ERROR: The client-kill command is not supported by the current daemon mode");
	}
    }
}

static void
man_client_n_clients (struct management *man)
{
  if (man->persist.callback.n_clients)
    {
      const int nclients = (*man->persist.callback.n_clients) (man->persist.callback.arg);
      msg (M_CLIENT, "SUCCESS: nclients=%d", nclients);
    }
  else
    {
      msg (M_CLIENT, "ERROR: The nclients command is not supported by the current daemon mode");
    }
}

static void
man_env_filter (struct management *man, const int level)
{
  man->connection.env_filter_level = level;
  msg (M_CLIENT, "SUCCESS: env_filter_level=%d", level);
}

#ifdef MANAGEMENT_PF

static void
man_client_pf (struct management *man, const char *cid_str)
{
  struct man_connection *mc = &man->connection;
  mc->in_extra_cid = 0;
  mc->in_extra_kid = 0;
  if (parse_cid (cid_str, &mc->in_extra_cid))
    {
      mc->in_extra_cmd = IEC_CLIENT_PF;
      in_extra_reset (mc, IER_NEW);
    }
}

#endif /* MANAGEMENT_PF */
#endif /* MANAGEMENT_DEF_AUTH */

#ifdef MANAGMENT_EXTERNAL_KEY

static void
man_rsa_sig (struct management *man)
{
  struct man_connection *mc = &man->connection;
  if (mc->ext_key_state == EKS_SOLICIT)
    {
      mc->ext_key_state = EKS_INPUT;
      mc->in_extra_cmd = IEC_RSA_SIGN;
      in_extra_reset (mc, IER_NEW);
    }
  else
    msg (M_CLIENT, "ERROR: The rsa-sig command is not currently available");
}

static void
man_certificate (struct management *man)
{
  struct man_connection *mc = &man->connection;
  if (mc->ext_cert_state == EKS_SOLICIT)
    {
      mc->ext_cert_state = EKS_INPUT;
      mc->in_extra_cmd = IEC_CERTIFICATE;
      in_extra_reset (mc, IER_NEW);
    }
  else
    msg (M_CLIENT, "ERROR: The certificate command is not currently available");
}

#endif

static void
man_load_stats (struct management *man)
{
  extern counter_type link_read_bytes_global;
  extern counter_type link_write_bytes_global;
  int nclients = 0;

  if (man->persist.callback.n_clients)
    nclients = (*man->persist.callback.n_clients) (man->persist.callback.arg);
  msg (M_CLIENT, "SUCCESS: nclients=%d,bytesin=" counter_format ",bytesout=" counter_format,
       nclients,
       link_read_bytes_global,
       link_write_bytes_global);
}

#define MN_AT_LEAST (1<<0)

static bool
man_need (struct management *man, const char **p, const int n, unsigned int flags)
{
  int i;
  ASSERT (p[0]);
  for (i = 1; i <= n; ++i)
    {
      if (!p[i])
	{
	  msg (M_CLIENT, "ERROR: the '%s' command requires %s%d parameter%s",
	       p[0],
	       (flags & MN_AT_LEAST) ? "at least " : "",
	       n,
	       n > 1 ? "s" : "");
	  return false;
	}
    }
  return true;
}

static void
man_proxy (struct management *man, const char **p)
{
  if (man->persist.callback.proxy_cmd)
    {
      const bool status = (*man->persist.callback.proxy_cmd)(man->persist.callback.arg, p);
      if (status)
        msg (M_CLIENT, "SUCCESS: proxy command succeeded");
      else
        msg (M_CLIENT, "ERROR: proxy command failed");
    }
  else
    msg (M_CLIENT, "ERROR: The proxy command is not supported by the current daemon mode");
}

static void
man_remote (struct management *man, const char **p)
{
  if (man->persist.callback.remote_cmd)
    {
      const bool status = (*man->persist.callback.remote_cmd)(man->persist.callback.arg, p);
      if (status)
	{
	  msg (M_CLIENT, "SUCCESS: remote command succeeded");
	}
      else
	{
	  msg (M_CLIENT, "ERROR: remote command failed");
	}
    }
  else
    {
      msg (M_CLIENT, "ERROR: The remote command is not supported by the current daemon mode");
    }
}

static void
man_dispatch_command (struct management *man, struct status_output *so, const char **p, const int nparms)
{
  struct gc_arena gc = gc_new ();

  ASSERT (p[0]);
  if (streq (p[0], "exit") || streq (p[0], "quit"))
    {
      man->connection.halt = true;
      goto done;
    }
  else if (streq (p[0], "help"))
    {
      man_help ();
    }
  else if (streq (p[0], "version"))
    {
      msg (M_CLIENT, "OpenVPN Version: %s", title_string);
      msg (M_CLIENT, "Management Version: %d", MANAGEMENT_VERSION);
      msg (M_CLIENT, "END");
    }
  else if (streq (p[0], "pid"))
    {
      msg (M_CLIENT, "SUCCESS: pid=%d", platform_getpid ());
    }
#ifdef MANAGEMENT_DEF_AUTH
  else if (streq (p[0], "nclients"))
    {
      man_client_n_clients (man);
    }
  else if (streq (p[0], "env-filter"))
    {
      int level = 0;
      if (p[1])
	level = atoi (p[1]);
      man_env_filter (man, level);
    }
#endif
  else if (streq (p[0], "signal"))
    {
      if (man_need (man, p, 1, 0))
	man_signal (man, p[1]);
    }
  else if (streq (p[0], "load-stats"))
    {
      man_load_stats (man);
    }
  else if (streq (p[0], "status"))
    {
      int version = 0;
      if (p[1])
	version = atoi (p[1]);
      man_status (man, version, so);
    }
  else if (streq (p[0], "kill"))
    {
      if (man_need (man, p, 1, 0))
	man_kill (man, p[1]);
    }
  else if (streq (p[0], "verb"))
    {
      if (p[1])
	{
	  const int level = atoi(p[1]);
	  if (set_debug_level (level, 0))
	    msg (M_CLIENT, "SUCCESS: verb level changed");
	  else
	    msg (M_CLIENT, "ERROR: verb level is out of range");
	}
      else
	msg (M_CLIENT, "SUCCESS: verb=%d", get_debug_level ());
    }
  else if (streq (p[0], "mute"))
    {
      if (p[1])
	{
	  const int level = atoi(p[1]);
	  if (set_mute_cutoff (level))
	    msg (M_CLIENT, "SUCCESS: mute level changed");
	  else
	    msg (M_CLIENT, "ERROR: mute level is out of range");
	}
      else
	msg (M_CLIENT, "SUCCESS: mute=%d", get_mute_cutoff ());
    }
  else if (streq (p[0], "auth-retry"))
    {
#if P2MP
      if (p[1])
	{
	  if (auth_retry_set (M_CLIENT, p[1]))
	    msg (M_CLIENT, "SUCCESS: auth-retry parameter changed");
	  else
	    msg (M_CLIENT, "ERROR: bad auth-retry parameter");
	}
      else
	msg (M_CLIENT, "SUCCESS: auth-retry=%s", auth_retry_print ());	
#else
      msg (M_CLIENT, "ERROR: auth-retry feature is unavailable");
#endif
    }
  else if (streq (p[0], "state"))
    {
      if (!p[1])
	{
	  man_state (man, "1");
	}
      else
	{
	  if (p[1])
	    man_state (man, p[1]);
	  if (p[2])
	    man_state (man, p[2]);
	}
    }
  else if (streq (p[0], "log"))
    {
      if (man_need (man, p, 1, MN_AT_LEAST))
	{
	  if (p[1])
	    man_log (man, p[1]);
	  if (p[2])
	    man_log (man, p[2]);
	}
    }
  else if (streq (p[0], "echo"))
    {
      if (man_need (man, p, 1, MN_AT_LEAST))
	{
	  if (p[1])
	    man_echo (man, p[1]);
	  if (p[2])
	    man_echo (man, p[2]);
	}
    }
  else if (streq (p[0], "username"))
    {
      if (man_need (man, p, 2, 0))
	man_query_username (man, p[1], p[2]);
    }
  else if (streq (p[0], "password"))
    {
      if (man_need (man, p, 2, 0))
	man_query_password (man, p[1], p[2]);
    }
  else if (streq (p[0], "forget-passwords"))
    {
      man_forget_passwords (man);
    }
  else if (streq (p[0], "needok"))
    {
      if (man_need (man, p, 2, 0))
	man_query_need_ok (man, p[1], p[2]);
    }
  else if (streq (p[0], "needstr"))
    {
      if (man_need (man, p, 2, 0))
	man_query_need_str (man, p[1], p[2]);
    }
  else if (streq (p[0], "net"))
    {
      man_net (man);
    }
  else if (streq (p[0], "hold"))
    {
      man_hold (man, p[1]);
    }
  else if (streq (p[0], "bytecount"))
    {
      if (man_need (man, p, 1, 0))
	man_bytecount (man, atoi(p[1]));
    }
#ifdef MANAGEMENT_DEF_AUTH
  else if (streq (p[0], "client-kill"))
    {
      if (man_need (man, p, 1, MN_AT_LEAST))
	man_client_kill (man, p[1], p[2]);
    }
  else if (streq (p[0], "client-deny"))
    {
      if (man_need (man, p, 3, MN_AT_LEAST))
	man_client_deny (man, p[1], p[2], p[3], p[4]);
    }
  else if (streq (p[0], "client-auth-nt"))
    {
      if (man_need (man, p, 2, 0))
	man_client_auth (man, p[1], p[2], false);
    }
  else if (streq (p[0], "client-auth"))
    {
      if (man_need (man, p, 2, 0))
	man_client_auth (man, p[1], p[2], true);
    }
#ifdef MANAGEMENT_PF
  else if (streq (p[0], "client-pf"))
    {
      if (man_need (man, p, 1, 0))
	man_client_pf (man, p[1]);
    }
#endif
#endif
#ifdef MANAGMENT_EXTERNAL_KEY
  else if (streq (p[0], "rsa-sig"))
    {
      man_rsa_sig (man);
    }
  else if (streq (p[0], "certificate"))
    {
      man_certificate (man);
    }
#endif
#ifdef ENABLE_PKCS11
  else if (streq (p[0], "pkcs11-id-count"))
    {
      man_pkcs11_id_count (man);
    }
  else if (streq (p[0], "pkcs11-id-get"))
    {
      if (man_need (man, p, 1, 0))
	man_pkcs11_id_get (man, atoi(p[1]));
    }
#endif
  else if (streq (p[0], "proxy"))
    {
      if (man_need (man, p, 1, MN_AT_LEAST))
        man_proxy (man, p);
    }
  else if (streq (p[0], "remote"))
    {
      if (man_need (man, p, 1, MN_AT_LEAST))
	man_remote (man, p);
    }
#if 1
  else if (streq (p[0], "test"))
    {
      if (man_need (man, p, 1, 0))
	{
	  int i;
	  const int n = atoi (p[1]);
	  for (i = 0; i < n; ++i)
	    {
	      msg (M_CLIENT, "[%d] The purpose of this command is to generate large amounts of output.", i);
	    }
	}
    }
#endif
  else
    {
      msg (M_CLIENT, "ERROR: unknown command, enter 'help' for more options");
    }

 done:
  gc_free (&gc);
}

#ifdef WIN32

static void
man_start_ne32 (struct management *man)
{
  switch (man->connection.state)
    {
    case MS_LISTEN:
      net_event_win32_start (&man->connection.ne32, FD_ACCEPT, man->connection.sd_top);
      break;
    case MS_CC_WAIT_READ:
    case MS_CC_WAIT_WRITE:
      net_event_win32_start (&man->connection.ne32, FD_READ|FD_WRITE|FD_CLOSE, man->connection.sd_cli);
      break;
    default:
      ASSERT (0);
    }  
}

static void
man_stop_ne32 (struct management *man)
{
  net_event_win32_stop (&man->connection.ne32);
}

#endif

static void
man_record_peer_info (struct management *man)
{
  struct gc_arena gc = gc_new ();
  if (man->settings.write_peer_info_file)
    {
      bool success = false;
#ifdef HAVE_GETSOCKNAME
      if (socket_defined (man->connection.sd_cli))
	{
	  struct sockaddr_in addr;
	  socklen_t addrlen = sizeof (addr);
	  int status;

	  CLEAR (addr);
	  status = getsockname (man->connection.sd_cli, (struct sockaddr *)&addr, &addrlen);
	  if (!status && addrlen == sizeof (addr))
	    {
	      const in_addr_t a = ntohl (addr.sin_addr.s_addr);
	      const int p = ntohs (addr.sin_port);
	      FILE *fp = platform_fopen (man->settings.write_peer_info_file, "w");
	      if (fp)
		{
		  fprintf (fp, "%s\n%d\n", print_in_addr_t (a, 0, &gc), p);
		  if (!fclose (fp))
		    success = true;
		}
	    }
	}
#endif
      if (!success)
	{
	  msg (D_MANAGEMENT, "MANAGEMENT: failed to write peer info to file %s",
	       man->settings.write_peer_info_file);
	  throw_signal_soft (SIGTERM, "management-connect-failed");
	}
    }
  gc_free (&gc);
}

static void
man_connection_settings_reset (struct management *man)
{
  man->connection.state_realtime = false;
  man->connection.log_realtime = false;
  man->connection.echo_realtime = false;
  man->connection.bytecount_update_seconds = 0;
  man->connection.password_verified = false;
  man->connection.password_tries = 0;
  man->connection.halt = false;
  man->connection.state = MS_CC_WAIT_WRITE;
}

static void
man_new_connection_post (struct management *man, const char *description)
{
  struct gc_arena gc = gc_new ();

  set_nonblock (man->connection.sd_cli);
  set_cloexec (man->connection.sd_cli);

  man_connection_settings_reset (man);

#ifdef WIN32
  man_start_ne32 (man);
#endif

#if UNIX_SOCK_SUPPORT
  if (man->settings.flags & MF_UNIX_SOCK)
    {
      msg (D_MANAGEMENT, "MANAGEMENT: %s %s",
	   description,
	   sockaddr_unix_name (&man->settings.local_unix, "NULL"));
    }
  else
#endif
    msg (D_MANAGEMENT, "MANAGEMENT: %s %s",
	 description,
	 print_sockaddr (man->settings.local->ai_addr, &gc));

  buffer_list_reset (man->connection.out);

  if (!man_password_needed (man))
    man_welcome (man);
  man_prompt (man);
  man_update_io_state (man);

  gc_free (&gc);
}

#if UNIX_SOCK_SUPPORT
static bool
man_verify_unix_peer_uid_gid (struct management *man, const socket_descriptor_t sd)
{
  if (socket_defined (sd) && (man->settings.client_uid != -1 || man->settings.client_gid != -1))
    {
      static const char err_prefix[] = "MANAGEMENT: unix domain socket client connection rejected --";
      int uid, gid;
      if (unix_socket_get_peer_uid_gid (man->connection.sd_cli, &uid, &gid))
	{
	  if (man->settings.client_uid != -1 && man->settings.client_uid != uid)
	    {
	      msg (D_MANAGEMENT, "%s UID of socket peer (%d) doesn't match required value (%d) as given by --management-client-user",
		   err_prefix, uid, man->settings.client_uid);
	      return false;
	    }
	  if (man->settings.client_gid != -1 && man->settings.client_gid != gid)
	    {
	      msg (D_MANAGEMENT, "%s GID of socket peer (%d) doesn't match required value (%d) as given by --management-client-group",
		   err_prefix, gid, man->settings.client_gid);
	      return false;
	    }
	}
      else
	{
	  msg (D_MANAGEMENT, "%s cannot get UID/GID of socket peer", err_prefix);
	  return false;
	}
    }
  return true;
}
#endif

static void
man_accept (struct management *man)
{
  struct link_socket_actual act;
  CLEAR (act);

  /*
   * Accept the TCP or Unix domain socket client.
   */
#if UNIX_SOCK_SUPPORT
  if (man->settings.flags & MF_UNIX_SOCK)
    {
      struct sockaddr_un remote;
      man->connection.sd_cli = socket_accept_unix (man->connection.sd_top, &remote);
      if (!man_verify_unix_peer_uid_gid (man, man->connection.sd_cli))
	sd_close (&man->connection.sd_cli);
    }
  else
#endif
    man->connection.sd_cli = socket_do_accept (man->connection.sd_top, &act, false);

  if (socket_defined (man->connection.sd_cli))
    {
      man->connection.remote = act.dest;

      if (socket_defined (man->connection.sd_top))
	{
#ifdef WIN32
	  man_stop_ne32 (man);
#endif
	}

      man_new_connection_post (man, "Client connected from");
    }
}

static void
man_listen (struct management *man)
{
  struct gc_arena gc = gc_new ();

  /*
   * Initialize state
   */
  man->connection.state = MS_LISTEN;
  man->connection.sd_cli = SOCKET_UNDEFINED;

  /*
   * Initialize listening socket
   */
  if (man->connection.sd_top == SOCKET_UNDEFINED)
    {
#if UNIX_SOCK_SUPPORT
      if (man->settings.flags & MF_UNIX_SOCK)
	{
	  man_delete_unix_socket (man);
	  man->connection.sd_top = create_socket_unix ();
	  socket_bind_unix (man->connection.sd_top, &man->settings.local_unix, "MANAGEMENT");
	}
      else
#endif
	{
	  man->connection.sd_top = create_socket_tcp (man->settings.local);
	  socket_bind (man->connection.sd_top, man->settings.local,
                       man->settings.local->ai_family, "MANAGEMENT", false);
	}

      /*
       * Listen for connection
       */
      if (listen (man->connection.sd_top, 1))
	msg (M_ERR, "MANAGEMENT: listen() failed");

      /*
       * Set misc socket properties
       */
      set_nonblock (man->connection.sd_top);
      set_cloexec (man->connection.sd_top);

#if UNIX_SOCK_SUPPORT
      if (man->settings.flags & MF_UNIX_SOCK)
	{
	  msg (D_MANAGEMENT, "MANAGEMENT: unix domain socket listening on %s",
	       sockaddr_unix_name (&man->settings.local_unix, "NULL"));
	}
      else
#endif
	msg (D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s",
	     print_sockaddr (man->settings.local->ai_addr, &gc));
    }

#ifdef WIN32
  man_start_ne32 (man);
#endif
  
  gc_free (&gc);
}

static void
man_connect (struct management *man)
{
  struct gc_arena gc = gc_new ();
  int status;
  int signal_received = 0;

  /*
   * Initialize state
   */
  man->connection.state = MS_INITIAL;
  man->connection.sd_top = SOCKET_UNDEFINED;

#if UNIX_SOCK_SUPPORT
  if (man->settings.flags & MF_UNIX_SOCK)
    {
      man->connection.sd_cli = create_socket_unix ();
      status = socket_connect_unix (man->connection.sd_cli, &man->settings.local_unix);
      if (!status && !man_verify_unix_peer_uid_gid (man, man->connection.sd_cli))
	  {
#ifdef EPERM
	    status = EPERM;
#else
	    status = 1;
#endif
	    sd_close (&man->connection.sd_cli);
	  }
    }
  else
#endif
    {
      man->connection.sd_cli = create_socket_tcp (man->settings.local);
      status = openvpn_connect (man->connection.sd_cli,
				man->settings.local->ai_addr,
				5,
				&signal_received);
    }

  if (signal_received)
    {
      throw_signal (signal_received);
      goto done;
    }

  if (status)
    {
#if UNIX_SOCK_SUPPORT
      if (man->settings.flags & MF_UNIX_SOCK)
	{
	  msg (D_LINK_ERRORS,
	       "MANAGEMENT: connect to unix socket %s failed: %s",
	       sockaddr_unix_name (&man->settings.local_unix, "NULL"),
	       strerror_ts (status, &gc));
	}
      else
#endif
      msg (D_LINK_ERRORS,
	   "MANAGEMENT: connect to %s failed: %s",
	   print_sockaddr (man->settings.local->ai_addr, &gc),
	   strerror_ts (status, &gc));
      throw_signal_soft (SIGTERM, "management-connect-failed");
      goto done;
    }

  man_record_peer_info (man);
  man_new_connection_post (man, "Connected to management server at");

 done:
  gc_free (&gc);
}

static void
man_reset_client_socket (struct management *man, const bool exiting)
{
  if (socket_defined (man->connection.sd_cli))
    {
#ifdef WIN32
      man_stop_ne32 (man);
#endif
      man_close_socket (man, man->connection.sd_cli);
      man->connection.sd_cli = SOCKET_UNDEFINED;
      man->connection.state = MS_INITIAL;
      command_line_reset (man->connection.in);
      buffer_list_reset (man->connection.out);
#ifdef MANAGEMENT_IN_EXTRA
      in_extra_reset (&man->connection, IER_RESET);
#endif
      msg (D_MANAGEMENT, "MANAGEMENT: Client disconnected");
    }
  if (!exiting)
    {
#ifdef ENABLE_CRYPTO
      if (man->settings.flags & MF_FORGET_DISCONNECT)
	ssl_purge_auth (false);
#endif
      if (man->settings.flags & MF_SIGNAL) {
      	  int mysig = man_mod_signal (man, SIGUSR1);
	  if (mysig >= 0)
	    {
	      msg (D_MANAGEMENT, "MANAGEMENT: Triggering management signal");
	      throw_signal_soft (mysig, "management-disconnect");
	    }
      }

      if (man->settings.flags & MF_CONNECT_AS_CLIENT)
	{
	  msg (D_MANAGEMENT, "MANAGEMENT: Triggering management exit");
	  throw_signal_soft (SIGTERM, "management-exit");
	}
      else
	man_listen (man);
    }
}

static void
man_process_command (struct management *man, const char *line)
{
  struct gc_arena gc = gc_new ();
  struct status_output *so;
  int nparms;
  char *parms[MAX_PARMS+1];

  CLEAR (parms);
  so = status_open (NULL, 0, -1, &man->persist.vout, 0);
#ifdef MANAGEMENT_IN_EXTRA
  in_extra_reset (&man->connection, IER_RESET);
#endif

  if (man_password_needed (man))
    {
      man_check_password (man, line);
    }
  else
    {
      nparms = parse_line (line, parms, MAX_PARMS, "TCP", 0, M_CLIENT, &gc);
      if (parms[0] && streq (parms[0], "password"))
	msg (D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD 'password [...]'");
      else if (!streq (line, "load-stats"))
	msg (D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD '%s'", line);

#if 0
      /* DEBUGGING -- print args */
      {
	int i;
	for (i = 0; i < nparms; ++i)
	  msg (M_INFO, "[%d] '%s'", i, parms[i]);
      }
#endif

      if (nparms > 0)
	man_dispatch_command (man, so, (const char **)parms, nparms);
    }

  CLEAR (parms);
  status_close (so);
  gc_free (&gc);
}

static bool
man_io_error (struct management *man, const char *prefix)
{
  const int err = openvpn_errno ();

  if (!ignore_sys_error (err))
    {
      struct gc_arena gc = gc_new ();
      msg (D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s",
	   prefix,
	   strerror_ts (err, &gc));
      gc_free (&gc);
      return true;
    }
  else
    return false;
}

#ifdef TARGET_ANDROID
static ssize_t man_send_with_fd (int fd, void *ptr, size_t nbytes, int flags, int sendfd)
{
  struct msghdr msg;
  struct iovec iov[1];

  union {
    struct cmsghdr cm;
    char    control[CMSG_SPACE(sizeof(int))];
  } control_un;
  struct cmsghdr *cmptr;

  msg.msg_control = control_un.control;
  msg.msg_controllen = sizeof(control_un.control);

  cmptr = CMSG_FIRSTHDR(&msg);
  cmptr->cmsg_len = CMSG_LEN(sizeof(int));
  cmptr->cmsg_level = SOL_SOCKET;
  cmptr->cmsg_type = SCM_RIGHTS;
  *((int *) CMSG_DATA(cmptr)) = sendfd;

  msg.msg_name = NULL;
  msg.msg_namelen = 0;

  iov[0].iov_base = ptr;
  iov[0].iov_len = nbytes;
  msg.msg_iov = iov;
  msg.msg_iovlen = 1;

  return (sendmsg(fd, &msg, flags));
}

static ssize_t man_recv_with_fd (int fd, void *ptr, size_t nbytes, int flags, int *recvfd)
{
  struct msghdr msghdr;
  struct iovec iov[1];
  ssize_t n;

  union {
    struct cmsghdr cm;
    char     control[CMSG_SPACE(sizeof (int))];
  } control_un;
  struct cmsghdr  *cmptr;

  msghdr.msg_control  = control_un.control;
  msghdr.msg_controllen = sizeof(control_un.control);

  msghdr.msg_name = NULL;
  msghdr.msg_namelen = 0;

  iov[0].iov_base = ptr;
  iov[0].iov_len = nbytes;
  msghdr.msg_iov = iov;
  msghdr.msg_iovlen = 1;

  if ( (n = recvmsg(fd, &msghdr, flags)) <= 0)
    return (n);

  if ( (cmptr = CMSG_FIRSTHDR(&msghdr)) != NULL &&
       cmptr->cmsg_len == CMSG_LEN(sizeof(int))) {
    if (cmptr->cmsg_level != SOL_SOCKET)
      msg (M_ERR, "control level != SOL_SOCKET");
    if (cmptr->cmsg_type != SCM_RIGHTS)
      msg (M_ERR, "control type != SCM_RIGHTS");
    *recvfd = *((int *) CMSG_DATA(cmptr));
  } else
    *recvfd = -1;           /* descriptor was not passed */

  return (n);
}

/*
 * The android control method will instruct the GUI part of openvpn to do
 * the route/ifconfig/open tun command.   See doc/android.txt for details.
 */
bool management_android_control (struct management *man, const char *command, const char *msg)
{
  struct user_pass up;
  CLEAR(up);
  strncpy (up.username, msg, sizeof(up.username)-1);

  management_query_user_pass(management, &up , command, GET_USER_PASS_NEED_OK,(void*) 0);
  return strcmp ("ok", up.password)==0;
}

/*
 * In Android 4.4 it is not possible to open a new tun device and then close the
 * old tun device without breaking the whole VPNService stack until the device
 * is rebooted. This management method ask the UI what method should be taken to
 * ensure the optimal solution for the situation
 */
int managment_android_persisttun_action (struct management *man)
{
  struct user_pass up;
  CLEAR(up);
  strcpy(up.username,"tunmethod");
  management_query_user_pass(management, &up , "PERSIST_TUN_ACTION",
			     GET_USER_PASS_NEED_OK,(void*) 0);
  if (!strcmp("NOACTION", up.password))
    return ANDROID_KEEP_OLD_TUN;
  else if (!strcmp ("OPEN_AFTER_CLOSE", up.password))
    return ANDROID_OPEN_AFTER_CLOSE;
  else if (!strcmp ("OPEN_BEFORE_CLOSE", up.password))
    return ANDROID_OPEN_BEFORE_CLOSE;
  else
    msg (M_ERR, "Got unrecognised '%s' from management for PERSIST_TUN_ACTION query", up.password);

  ASSERT(0);
  return ANDROID_OPEN_AFTER_CLOSE;
}


#endif

static int
man_read (struct management *man)
{
  /*
   * read command line from socket
   */
  unsigned char buf[256];
  int len = 0;

#ifdef TARGET_ANDROID
  int fd;
  len = man_recv_with_fd (man->connection.sd_cli, buf, sizeof (buf), MSG_NOSIGNAL, &fd);
  if(fd >= 0)
     man->connection.lastfdreceived = fd;
#else
  len = recv (man->connection.sd_cli, buf, sizeof (buf), MSG_NOSIGNAL);
#endif

  if (len == 0)
    {
      man_reset_client_socket (man, false);
    }
  else if (len > 0)
    {
      bool processed_command = false;

      ASSERT (len <= (int) sizeof (buf));
      command_line_add (man->connection.in, buf, len);

      /*
       * Reset output object
       */
      buffer_list_reset (man->connection.out);

      /*
       * process command line if complete
       */
      {
	const unsigned char *line;
	while ((line = command_line_get (man->connection.in)))
	  {
#ifdef MANAGEMENT_IN_EXTRA
	    if (man->connection.in_extra)
	      {
		if (!strcmp ((char *)line, "END"))
		  in_extra_dispatch (man);
		else
		  buffer_list_push (man->connection.in_extra, line);
	      }
	    else
#endif
	      man_process_command (man, (char *) line);
	    if (man->connection.halt)
	      break;
	    command_line_next (man->connection.in);
	    processed_command = true;
	  }
      }

      /*
       * Reset output state to MS_CC_WAIT_(READ|WRITE)
       */
      if (man->connection.halt)
	{
	  man_reset_client_socket (man, false);
	  len = 0;
	}
      else
	{
	  if (processed_command)
	    man_prompt (man);
	  man_update_io_state (man);
	}
    }
  else /* len < 0 */
    {
      if (man_io_error (man, "recv"))
	man_reset_client_socket (man, false);
    }
  return len;
}

static int
man_write (struct management *man)
{
  const int size_hint = 1024;
  int sent = 0;
  const struct buffer *buf;

  buffer_list_aggregate(man->connection.out, size_hint);
  buf = buffer_list_peek (man->connection.out);
  if (buf && BLEN (buf))
    {
      const int len = min_int (size_hint, BLEN (buf));
#ifdef TARGET_ANDROID
      if (man->connection.fdtosend > 0)
        {
         sent = man_send_with_fd (man->connection.sd_cli, BPTR (buf), len, MSG_NOSIGNAL,man->connection.fdtosend);
            man->connection.fdtosend = -1;
        } else
#endif
      sent = send (man->connection.sd_cli, BPTR (buf), len, MSG_NOSIGNAL);
      if (sent >= 0)
	{
	  buffer_list_advance (man->connection.out, sent);
	}
      else if (sent < 0)
	{
	  if (man_io_error (man, "send"))
	    man_reset_client_socket (man, false);
	}
    }

  /*
   * Reset output state to MS_CC_WAIT_(READ|WRITE)
   */
  man_update_io_state (man);

  return sent;
}

static void
man_connection_clear (struct man_connection *mc)
{
  CLEAR (*mc);

  /* set initial state */
  mc->state = MS_INITIAL;

  /* clear socket descriptors */
  mc->sd_top = SOCKET_UNDEFINED;
  mc->sd_cli = SOCKET_UNDEFINED;
}

static void
man_persist_init (struct management *man,
		  const int log_history_cache,
		  const int echo_buffer_size,
		  const int state_buffer_size)
{
  struct man_persist *mp = &man->persist;
  if (!mp->defined)
    {
      CLEAR (*mp);

      /* initialize log history store */
      mp->log = log_history_init (log_history_cache);  

      /*
       * Initialize virtual output object, so that functions
       * which write to a virtual_output object can be redirected
       * here to the management object.
       */
      mp->vout.func = virtual_output_callback_func;
      mp->vout.arg = man;
      mp->vout.flags_default = M_CLIENT;
      msg_set_virtual_output (&mp->vout);

      /*
       * Initialize --echo list
       */
      man->persist.echo = log_history_init (echo_buffer_size);

      /*
       * Initialize --state list
       */
      man->persist.state = log_history_init (state_buffer_size);

      mp->defined = true;
    }
}

static void
man_persist_close (struct man_persist *mp)
{
  if (mp->log)
    {
      msg_set_virtual_output (NULL);
      log_history_close (mp->log);
    }

  if (mp->echo)
    log_history_close (mp->echo);

  if (mp->state)
    log_history_close (mp->state);

  CLEAR (*mp);
}
      
static void
man_settings_init (struct man_settings *ms,
		   const char *addr,
		   const char *port,
		   const char *pass_file,
		   const char *client_user,
		   const char *client_group,
		   const int log_history_cache,
		   const int echo_buffer_size,
		   const int state_buffer_size,
		   const char *write_peer_info_file,
		   const int remap_sigusr1,
		   const unsigned int flags)
{
  if (!ms->defined)
    {
      CLEAR (*ms);

      ms->flags = flags;
      ms->client_uid = -1;
      ms->client_gid = -1;

      /*
       * Get username/password
       */
      if (pass_file)
	get_user_pass (&ms->up, pass_file, "Management", GET_USER_PASS_PASSWORD_ONLY);

      /*
       * lookup client UID/GID if specified
       */
      if (client_user)
	{
	  struct platform_state_user s;
	  platform_user_get (client_user, &s);
	  ms->client_uid = platform_state_user_uid (&s);
	  msg (D_MANAGEMENT, "MANAGEMENT: client_uid=%d", ms->client_uid);
	  ASSERT (ms->client_uid >= 0);
	}
      if (client_group)
	{
	  struct platform_state_group s;
	  platform_group_get (client_group, &s);
	  ms->client_gid = platform_state_group_gid (&s);
	  msg (D_MANAGEMENT, "MANAGEMENT: client_gid=%d", ms->client_gid);
	  ASSERT (ms->client_gid >= 0);
	}

      ms->write_peer_info_file = string_alloc (write_peer_info_file, NULL);

#if UNIX_SOCK_SUPPORT
      if (ms->flags & MF_UNIX_SOCK)
	sockaddr_unix_init (&ms->local_unix, addr);
      else
#endif
	{

	  /*
	   * Run management over tunnel, or
	   * separate channel?
	   */
	  if (streq (addr, "tunnel") && !(flags & MF_CONNECT_AS_CLIENT))
	    {
	      ms->management_over_tunnel = true;
	    }
	  else
	    {
	      int status;
	      int resolve_flags = GETADDR_RESOLVE|GETADDR_WARN_ON_SIGNAL|GETADDR_FATAL;

	      if (! (flags & MF_CONNECT_AS_CLIENT))
		  resolve_flags |= GETADDR_PASSIVE;

              status = openvpn_getaddrinfo (resolve_flags, addr, port, 0,
					    NULL, AF_UNSPEC, &ms->local);
              ASSERT(status==0);
	    }
	}
      
      /*
       * Log history and echo buffer may need to be resized
       */
      ms->log_history_cache = log_history_cache;
      ms->echo_buffer_size = echo_buffer_size;
      ms->state_buffer_size = state_buffer_size;

      /*
       * Set remap sigusr1 flags
       */
      if (remap_sigusr1 == SIGHUP)
	ms->mansig |= MANSIG_MAP_USR1_TO_HUP;
      else if (remap_sigusr1 == SIGTERM)
	ms->mansig |= MANSIG_MAP_USR1_TO_TERM;

      ms->defined = true;
    }
}

static void
man_settings_close (struct man_settings *ms)
{
  if (ms->local)
    freeaddrinfo(ms->local);
  free (ms->write_peer_info_file);
  CLEAR (*ms);
}


static void
man_connection_init (struct management *man)
{
  if (man->connection.state == MS_INITIAL)
    {
#ifdef WIN32
      /*
       * This object is a sort of TCP/IP helper
       * for Windows.
       */
      net_event_win32_init (&man->connection.ne32);
#endif

      /*
       * Allocate helper objects for command line input and
       * command output from/to the socket.
       */
      man->connection.in = command_line_new (1024);
      man->connection.out = buffer_list_new (0);

      /*
       * Initialize event set for standalone usage, when we are
       * running outside of the primary event loop.
       */
      {
	int maxevents = 1;
	man->connection.es = event_set_init (&maxevents, EVENT_METHOD_FAST);
      }

      /*
       * Listen/connect socket
       */
      if (man->settings.flags & MF_CONNECT_AS_CLIENT)
	man_connect (man);
      else
	man_listen (man);
    }
}

static void
man_connection_close (struct management *man)
{
  struct man_connection *mc = &man->connection;

  if (mc->es)
    event_free (mc->es);
#ifdef WIN32
  net_event_win32_close (&mc->ne32);
#endif
  if (socket_defined (mc->sd_top))
    {
      man_close_socket (man, mc->sd_top);
      man_delete_unix_socket (man);
    }
  if (socket_defined (mc->sd_cli))
    man_close_socket (man, mc->sd_cli);
  if (mc->in)
    command_line_free (mc->in);
  if (mc->out)
    buffer_list_free (mc->out);
#ifdef MANAGEMENT_IN_EXTRA
  in_extra_reset (&man->connection, IER_RESET);
#endif
#ifdef MANAGMENT_EXTERNAL_KEY
  buffer_list_free (mc->ext_key_input);
#endif
  man_connection_clear (mc);
}

struct management *
management_init (void)
{
  struct management *man;
  ALLOC_OBJ_CLEAR (man, struct management);

  man_persist_init (man,
		    MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
		    MANAGEMENT_ECHO_BUFFER_SIZE,
		    MANAGEMENT_STATE_BUFFER_SIZE);

  man_connection_clear (&man->connection);

  return man;
}

bool
management_open (struct management *man,
		 const char *addr,
		 const char *port,
		 const char *pass_file,
		 const char *client_user,
		 const char *client_group,
		 const int log_history_cache,
		 const int echo_buffer_size,
		 const int state_buffer_size,
		 const char *write_peer_info_file,
		 const int remap_sigusr1,
		 const unsigned int flags)
{
  bool ret = false;

  /*
   * Save the settings only if they have not
   * been saved before.
   */
  man_settings_init (&man->settings,
		     addr,
		     port,
		     pass_file,
		     client_user,
		     client_group,
		     log_history_cache,
		     echo_buffer_size,
		     state_buffer_size,
		     write_peer_info_file,
		     remap_sigusr1,
		     flags);

  /*
   * The log is initially sized to MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
   * but may be changed here.  Ditto for echo and state buffers.
   */
  log_history_resize (man->persist.log, man->settings.log_history_cache);
  log_history_resize (man->persist.echo, man->settings.echo_buffer_size);
  log_history_resize (man->persist.state, man->settings.state_buffer_size);

  /*
   * If connection object is uninitialized and we are not doing
   * over-the-tunnel management, then open (listening) connection.
   */
  if (man->connection.state == MS_INITIAL)
    {
      if (!man->settings.management_over_tunnel)
	{
	  man_connection_init (man);
	  ret = true;
	}
    }

  return ret;
}

void
management_close (struct management *man)
{
  man_output_list_push_finalize (man);  /* flush output queue */
  man_connection_close (man);
  man_settings_close (&man->settings);
  man_persist_close (&man->persist);
  free (man);
}

void
management_set_callback (struct management *man,
			 const struct management_callback *cb)
{
  man->persist.standalone_disabled = true;
  man->persist.callback = *cb;
}

void
management_clear_callback (struct management *man)
{
  man->persist.standalone_disabled = false;
  man->persist.hold_release = false;
  CLEAR (man->persist.callback);
  man_output_list_push_finalize (man); /* flush output queue */
}

void
management_set_state (struct management *man,
		      const int state,
		      const char *detail,
		      const in_addr_t tun_local_ip,
		      const in_addr_t tun_remote_ip)
{
  if (man->persist.state && (!(man->settings.flags & MF_SERVER) || state < OPENVPN_STATE_CLIENT_BASE))
    {
      struct gc_arena gc = gc_new ();
      struct log_entry e;
      const char *out = NULL;

      update_time ();
      CLEAR (e);
      e.timestamp = now;
      e.u.state = state;
      e.string = detail;
      e.local_ip = tun_local_ip;
      e.remote_ip = tun_remote_ip;
      
      log_history_add (man->persist.state, &e);

      if (man->connection.state_realtime)
	out = log_entry_print (&e, LOG_PRINT_STATE_PREFIX
			       |   LOG_PRINT_INT_DATE
                               |   LOG_PRINT_STATE
			       |   LOG_PRINT_LOCAL_IP
			       |   LOG_PRINT_REMOTE_IP
                               |   LOG_PRINT_CRLF
			       |   LOG_ECHO_TO_LOG, &gc);

      if (out)
	man_output_list_push (man, out);

      gc_free (&gc);
    }
}

static bool
env_filter_match (const char *env_str, const int env_filter_level)
{
  static const char *env_names[] = {
    "username=",
    "password=",
    "X509_0_CN=",
    "tls_serial_",
    "untrusted_ip=",
    "ifconfig_local=",
    "ifconfig_netmask=",
    "daemon_start_time=",
    "daemon_pid=",
    "dev=",
    "ifconfig_pool_remote_ip=",
    "ifconfig_pool_netmask=",
    "time_duration=",
    "bytes_sent=",
    "bytes_received="
  };

  if (env_filter_level == 0)
    return true;
  else if (env_filter_level <= 1 && !strncmp(env_str, "X509_", 5))
    return true;
  else if (env_filter_level <= 2)
    {
      size_t i;
      for (i = 0; i < SIZE(env_names); ++i)
	{
	  const char *en = env_names[i];
	  const size_t len = strlen(en);
	  if (!strncmp(env_str, en, len))
	    return true;
	}
      return false;
    }
  return false;
}

static void
man_output_env (const struct env_set *es, const bool tail, const int env_filter_level, const char *prefix)
{
  if (es)
    {
      struct env_item *e;
      for (e = es->list; e != NULL; e = e->next)
	{
	  if (e->string && (!env_filter_level || env_filter_match(e->string, env_filter_level)))
	    msg (M_CLIENT, ">%s:ENV,%s", prefix, e->string);
	}
    }
  if (tail)
    msg (M_CLIENT, ">%s:ENV,END", prefix);
}

static void
man_output_extra_env (struct management *man, const char *prefix)
{
  struct gc_arena gc = gc_new ();
  struct env_set *es = env_set_create (&gc);
  if (man->persist.callback.n_clients)
    {
      const int nclients = (*man->persist.callback.n_clients) (man->persist.callback.arg);
      setenv_int (es, "n_clients", nclients);
    }
  man_output_env (es, false, man->connection.env_filter_level, prefix);
  gc_free (&gc);
}

void
management_up_down(struct management *man, const char *updown, const struct env_set *es)
{
  if (man->settings.flags & MF_UP_DOWN)
    {
      msg (M_CLIENT, ">UPDOWN:%s", updown);
      man_output_env (es, true, 0, "UPDOWN");
    }
}

void
management_notify(struct management *man, const char *severity, const char *type, const char *text)
{
  msg (M_CLIENT, ">NOTIFY:%s,%s,%s", severity, type, text);
}

void
management_notify_generic (struct management *man, const char *str)
{
  msg (M_CLIENT, "%s", str);
}

#ifdef MANAGEMENT_DEF_AUTH

static void
man_output_peer_info_env (struct management *man, struct man_def_auth_context *mdac)
{
  char line[256];
  if (man->persist.callback.get_peer_info)
    {
      const char *peer_info = (*man->persist.callback.get_peer_info) (man->persist.callback.arg, mdac->cid);
      if (peer_info)
	{
	  struct buffer buf;
	  buf_set_read (&buf, (const uint8_t *) peer_info, strlen(peer_info));
	  while (buf_parse (&buf, '\n', line, sizeof (line)))
	    {
	      chomp (line);
	      if (validate_peer_info_line(line))
		{
		  msg (M_CLIENT, ">CLIENT:ENV,%s", line);
		}
	      else
		msg (D_MANAGEMENT, "validation failed on peer_info line received from client");
	    }
	}
    }
}

void
management_notify_client_needing_auth (struct management *management,
				       const unsigned int mda_key_id,
				       struct man_def_auth_context *mdac,
				       const struct env_set *es)
{
  if (!(mdac->flags & DAF_CONNECTION_CLOSED))
    {
      const char *mode = "CONNECT";
      if (mdac->flags & DAF_CONNECTION_ESTABLISHED)
	mode = "REAUTH";
      msg (M_CLIENT, ">CLIENT:%s,%lu,%u", mode, mdac->cid, mda_key_id);
      man_output_extra_env (management, "CLIENT");
      if (management->connection.env_filter_level>0)
        man_output_peer_info_env(management, mdac);
      man_output_env (es, true, management->connection.env_filter_level, "CLIENT");
      mdac->flags |= DAF_INITIAL_AUTH;
    }
}

void
management_connection_established (struct management *management,
				   struct man_def_auth_context *mdac,
				   const struct env_set *es)
{
  mdac->flags |= DAF_CONNECTION_ESTABLISHED;
  msg (M_CLIENT, ">CLIENT:ESTABLISHED,%lu", mdac->cid);
  man_output_extra_env (management, "CLIENT");
  man_output_env (es, true, management->connection.env_filter_level, "CLIENT");
}

void
management_notify_client_close (struct management *management,
				struct man_def_auth_context *mdac,
				const struct env_set *es)
{
  if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))
    {
      msg (M_CLIENT, ">CLIENT:DISCONNECT,%lu", mdac->cid);
      man_output_env (es, true, management->connection.env_filter_level, "CLIENT");
      mdac->flags |= DAF_CONNECTION_CLOSED;
    }
}

void
management_learn_addr (struct management *management,
		       struct man_def_auth_context *mdac,
		       const struct mroute_addr *addr,
		       const bool primary)
{
  struct gc_arena gc = gc_new ();
  if ((mdac->flags & DAF_INITIAL_AUTH) && !(mdac->flags & DAF_CONNECTION_CLOSED))
    {
      msg (M_CLIENT, ">CLIENT:ADDRESS,%lu,%s,%d",
	   mdac->cid,
	   mroute_addr_print_ex (addr, MAPF_SUBNET, &gc),
	   BOOL_CAST (primary));
    }
  gc_free (&gc);
}

#endif /* MANAGEMENT_DEF_AUTH */

void
management_echo (struct management *man, const char *string, const bool pull)
{
  if (man->persist.echo)
    {
      struct gc_arena gc = gc_new ();
      struct log_entry e;
      const char *out = NULL;

      update_time ();
      CLEAR (e);
      e.timestamp = now;
      e.string = string;
      e.u.intval = BOOL_CAST (pull);

      log_history_add (man->persist.echo, &e);

      if (man->connection.echo_realtime)
	out = log_entry_print (&e, LOG_PRINT_INT_DATE|LOG_PRINT_ECHO_PREFIX|LOG_PRINT_CRLF|MANAGEMENT_ECHO_FLAGS, &gc);

      if (out)
	man_output_list_push (man, out);

      gc_free (&gc);
    }
}

void
management_post_tunnel_open (struct management *man, const in_addr_t tun_local_ip)
{
  /*
   * If we are running management over the tunnel,
   * this is the place to initialize the connection.
   */
  if (man->settings.management_over_tunnel
      && man->connection.state == MS_INITIAL)
    {
      /* listen on our local TUN/TAP IP address */
      struct in_addr ia;
      int ret;

      ia.s_addr = htonl(tun_local_ip);
      ret = openvpn_getaddrinfo(GETADDR_PASSIVE, inet_ntoa(ia), NULL, 0, NULL,
                                AF_INET, &man->settings.local);
      ASSERT (ret==0);
      man_connection_init (man);
    }

}

void
management_pre_tunnel_close (struct management *man)
{
  if (man->settings.management_over_tunnel)
    man_connection_close (man);
}

void
management_auth_failure (struct management *man, const char *type, const char *reason)
{
  if (reason)
    msg (M_CLIENT, ">PASSWORD:Verification Failed: '%s' ['%s']", type, reason);
  else
    msg (M_CLIENT, ">PASSWORD:Verification Failed: '%s'", type);
}

void
management_auth_token (struct management *man, const char *token)
{
  msg (M_CLIENT, ">PASSWORD:Auth-Token:%s", token);  
}

static inline bool
man_persist_state (unsigned int *persistent, const int n)
{
  if (persistent)
    {
      if (*persistent == (unsigned int)n)
	return false;
      *persistent = n;
    }
  return true;
}

#ifdef WIN32

void
management_socket_set (struct management *man,
		       struct event_set *es,
		       void *arg,
		       unsigned int *persistent)
{
  if (man->connection.state != MS_INITIAL)
    {
      event_t ev = net_event_win32_get_event (&man->connection.ne32);
      net_event_win32_reset_write (&man->connection.ne32);

      switch (man->connection.state)
	{
	case MS_LISTEN:
	  if (man_persist_state (persistent, 1))
	    event_ctl (es, ev, EVENT_READ, arg);
	  break;
	case MS_CC_WAIT_READ:
	  if (man_persist_state (persistent, 2))
	    event_ctl (es, ev, EVENT_READ, arg);
	  break;
	case MS_CC_WAIT_WRITE:
	  if (man_persist_state (persistent, 3))
	    event_ctl (es, ev, EVENT_READ|EVENT_WRITE, arg);
	  break;
	default:
	  ASSERT (0);
	}
    }
}

void
management_io (struct management *man)
{
  if (man->connection.state != MS_INITIAL)
    {
      long net_events;
      net_event_win32_reset (&man->connection.ne32);
      net_events = net_event_win32_get_event_mask (&man->connection.ne32);

      if (net_events & FD_CLOSE)
	{
	  man_reset_client_socket (man, false);
	}
      else
	{
	  if (man->connection.state == MS_LISTEN)
	    {
	      if (net_events & FD_ACCEPT)
		{
		  man_accept (man);
		  net_event_win32_clear_selected_events (&man->connection.ne32, FD_ACCEPT);
		}
	    }
	  else if (man->connection.state == MS_CC_WAIT_READ || man->connection.state == MS_CC_WAIT_WRITE)
	    {
	      if (net_events & FD_READ)
		{
		  while (man_read (man) > 0)
		    ;
		  net_event_win32_clear_selected_events (&man->connection.ne32, FD_READ);
		}

	      if (net_events & FD_WRITE)
		{
		  int status;
		  status = man_write (man);
		  if (status < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
		    {
		      net_event_win32_clear_selected_events (&man->connection.ne32, FD_WRITE);
		    }
		}
	    }
	}
    }
}

#else

void
management_socket_set (struct management *man,
		       struct event_set *es,
		       void *arg,
		       unsigned int *persistent)
{
  switch (man->connection.state)
    {
    case MS_LISTEN:
      if (man_persist_state (persistent, 1))
	event_ctl (es, man->connection.sd_top, EVENT_READ, arg);
      break;
    case MS_CC_WAIT_READ:
      if (man_persist_state (persistent, 2))
	event_ctl (es, man->connection.sd_cli, EVENT_READ, arg);
      break;
    case MS_CC_WAIT_WRITE:
      if (man_persist_state (persistent, 3))
	event_ctl (es, man->connection.sd_cli, EVENT_WRITE, arg);
      break;
    case MS_INITIAL:
      break;
    default:
      ASSERT (0);
    }
}

void
management_io (struct management *man)
{
  switch (man->connection.state)
    {
    case MS_LISTEN:
      man_accept (man);
      break;
    case MS_CC_WAIT_READ:
      man_read (man);
      break;
    case MS_CC_WAIT_WRITE:
      man_write (man);
      break;
    case MS_INITIAL:
      break;
    default:
      ASSERT (0);
    }
}

#endif

static inline bool
man_standalone_ok (const struct management *man)
{
  return !man->settings.management_over_tunnel && man->connection.state != MS_INITIAL;
}

static bool
man_check_for_signals (volatile int *signal_received)
{
  if (signal_received)
    {
      get_signal (signal_received);
      if (*signal_received)
	return true;
    }
  return false;
}

/*
 * Wait for socket I/O when outside primary event loop
 */
static int
man_block (struct management *man, volatile int *signal_received, const time_t expire)
{
  struct timeval tv;
  struct event_set_return esr;
  int status = -1;
  
  if (man_standalone_ok (man))
    {
      while (true)
	{
	  event_reset (man->connection.es);
	  management_socket_set (man, man->connection.es, NULL, NULL);
	  tv.tv_usec = 0;
	  tv.tv_sec = 1;
	  if (man_check_for_signals (signal_received))
	    {
	      status = -1;
	      break;
	    }
	  status = event_wait (man->connection.es, &tv, &esr, 1);
	  update_time ();
	  if (man_check_for_signals (signal_received))
	    {
	      status = -1;
	      break;
	    }

	  if (status > 0)
	    break;
	  else if (expire && now >= expire)
	    {
	      /* set SIGINT signal if expiration time exceeded */
	      status = 0;
	      if (signal_received)
		*signal_received = SIGINT;
	      break;
	    }
	}
    }
  return status;
}

/*
 * Perform management socket output outside primary event loop
 */
static void
man_output_standalone (struct management *man, volatile int *signal_received)
{
  if (man_standalone_ok (man))
    {
      while (man->connection.state == MS_CC_WAIT_WRITE)
	{
	  management_io (man);
	  if (man->connection.state == MS_CC_WAIT_WRITE)
	    man_block (man, signal_received, 0);
	  if (signal_received && *signal_received)
	    break;
	}
    }
}

/*
 * Process management event loop outside primary event loop
 */
static int
man_standalone_event_loop (struct management *man, volatile int *signal_received, const time_t expire)
{
  int status = -1;
  if (man_standalone_ok (man))
    {
      status = man_block (man, signal_received, expire);
      if (status > 0)
	management_io (man);
    }
  return status;
}

#define MWCC_PASSWORD_WAIT (1<<0)
#define MWCC_HOLD_WAIT     (1<<1)
#define MWCC_OTHER_WAIT    (1<<2)

/*
 * Block until client connects
 */
static void
man_wait_for_client_connection (struct management *man,
				volatile int *signal_received,
				const time_t expire,
				unsigned int flags)
{
  ASSERT (man_standalone_ok (man));
  if (man->connection.state == MS_LISTEN)
    {
      if (flags & MWCC_PASSWORD_WAIT)
	msg (D_MANAGEMENT, "Need password(s) from management interface, waiting...");
      if (flags & MWCC_HOLD_WAIT)
	msg (D_MANAGEMENT, "Need hold release from management interface, waiting...");
      if (flags & MWCC_OTHER_WAIT)
	msg (D_MANAGEMENT, "Need information from management interface, waiting...");
      do {
	man_standalone_event_loop (man, signal_received, expire);
	if (signal_received && *signal_received)
	  break;
      } while (man->connection.state == MS_LISTEN || man_password_needed (man));
    }
}

/*
 * Process the management event loop for sec seconds
 */
void
management_event_loop_n_seconds (struct management *man, int sec)
{
  if (man_standalone_ok (man))
    {
      volatile int signal_received = 0;
      const bool standalone_disabled_save = man->persist.standalone_disabled;
      time_t expire = 0;

      man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */

      /* set expire time */
      update_time ();
      if (sec)
	expire = now + sec;

      /* if no client connection, wait for one */
      man_wait_for_client_connection (man, &signal_received, expire, 0);
      if (signal_received)
	return;

      /* run command processing event loop */
      do
	{
	  man_standalone_event_loop (man, &signal_received, expire);
	  if (!signal_received)
	    man_check_for_signals (&signal_received);
	  if (signal_received)
	    return;
	} while (expire);

      /* revert state */
      man->persist.standalone_disabled = standalone_disabled_save;
    }
  else
    {
      sleep (sec);
    }
}

/*
 * Get a username/password from management channel in standalone mode.
 */
bool
management_query_user_pass (struct management *man,
			    struct user_pass *up,
			    const char *type,
			    const unsigned int flags,
			    const char *static_challenge)
{
  struct gc_arena gc = gc_new ();
  bool ret = false;

  if (man_standalone_ok (man))
    {
      volatile int signal_received = 0;
      const bool standalone_disabled_save = man->persist.standalone_disabled;
      struct buffer alert_msg = alloc_buf_gc (128, &gc);
      const char *alert_type = NULL;
      const char *prefix = NULL;
      unsigned int up_query_mode = 0;
#ifdef ENABLE_CLIENT_CR
      const char *sc = NULL;
#endif
      ret = true;
      man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
      man->persist.special_state_msg = NULL;

      CLEAR (man->connection.up_query);

      if (flags & GET_USER_PASS_NEED_OK)
	{
	  up_query_mode = UP_QUERY_NEED_OK;
	  prefix= "NEED-OK";
	  alert_type = "confirmation";
	}
      else if (flags & GET_USER_PASS_NEED_STR)
        {
	  up_query_mode = UP_QUERY_NEED_STR;
	  prefix= "NEED-STR";
	  alert_type = "string";
	}
      else if (flags & GET_USER_PASS_PASSWORD_ONLY)
	{
	  up_query_mode = UP_QUERY_PASS;
	  prefix = "PASSWORD";
	  alert_type = "password";
	}
      else
	{
	  up_query_mode = UP_QUERY_USER_PASS;
	  prefix = "PASSWORD";
	  alert_type = "username/password";
#ifdef ENABLE_CLIENT_CR
	  if (static_challenge)
	    sc = static_challenge;
#endif
	}
      buf_printf (&alert_msg, ">%s:Need '%s' %s",
		  prefix,
		  type,
		  alert_type);

      if (flags & (GET_USER_PASS_NEED_OK | GET_USER_PASS_NEED_STR))
	buf_printf (&alert_msg, " MSG:%s", up->username);

#ifdef ENABLE_CLIENT_CR
      if (sc)
	buf_printf (&alert_msg, " SC:%d,%s",
		    BOOL_CAST(flags & GET_USER_PASS_STATIC_CHALLENGE_ECHO),
		    sc);
#endif

      man_wait_for_client_connection (man, &signal_received, 0, MWCC_PASSWORD_WAIT);
      if (signal_received)
	ret = false;

      if (ret)
	{
	  man->persist.special_state_msg = BSTR (&alert_msg);
	  msg (M_CLIENT, "%s", man->persist.special_state_msg);

	  /* tell command line parser which info we need */
	  man->connection.up_query_mode = up_query_mode;
	  man->connection.up_query_type = type;

	  /* run command processing event loop until we get our username/password/response */
	  do
	    {
	      man_standalone_event_loop (man, &signal_received, 0);
	      if (!signal_received)
		man_check_for_signals (&signal_received);
	      if (signal_received)
		{
		  ret = false;
		  break;
		}
	    } while (!man->connection.up_query.defined);
	}

      /* revert state */
      man->connection.up_query_mode = UP_QUERY_DISABLED;
      man->connection.up_query_type = NULL;
      man->persist.standalone_disabled = standalone_disabled_save;
      man->persist.special_state_msg = NULL;

      /* pass through blank passwords */
      if (!strcmp (man->connection.up_query.password, blank_up))
	CLEAR (man->connection.up_query.password);

      /*
       * Transfer u/p to return object, zero any record
       * we hold in the management object.
       */
      if (ret)
	{
	  man->connection.up_query.nocache = up->nocache; /* preserve caller's nocache setting */
	  *up = man->connection.up_query;
	}
      CLEAR (man->connection.up_query);
    }

  gc_free (&gc);
  return ret;
}

#ifdef MANAGMENT_EXTERNAL_KEY

int
management_query_multiline (struct management *man,
			  const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
{
  struct gc_arena gc = gc_new ();
  int ret = 0;
  volatile int signal_received = 0;
  struct buffer alert_msg = clear_buf();
  const bool standalone_disabled_save = man->persist.standalone_disabled;
  struct man_connection *mc = &man->connection;

  if (man_standalone_ok (man))
    {
      man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
      man->persist.special_state_msg = NULL;

      *state = EKS_SOLICIT;

      if (b64_data) {
        alert_msg = alloc_buf_gc (strlen(b64_data)+strlen(prompt)+3, &gc);
        buf_printf (&alert_msg, ">%s:%s", prompt, b64_data);
      } else {
        alert_msg = alloc_buf_gc (strlen(prompt)+3, &gc);
        buf_printf (&alert_msg, ">%s", prompt);
      }

      man_wait_for_client_connection (man, &signal_received, 0, MWCC_OTHER_WAIT);

      if (signal_received)
	goto done;

      man->persist.special_state_msg = BSTR (&alert_msg);
      msg (M_CLIENT, "%s", man->persist.special_state_msg);

      /* run command processing event loop until we get our signature */
      do
	{
	  man_standalone_event_loop (man, &signal_received, 0);
	  if (!signal_received)
	    man_check_for_signals (&signal_received);
	  if (signal_received)
	    goto done;
	} while (*state != EKS_READY);

      ret = 1;
    }

 done:
  if (*state == EKS_READY && ret)
    msg (M_CLIENT, "SUCCESS: %s command succeeded", cmd);
  else if (*state == EKS_INPUT || *state == EKS_READY)
    msg (M_CLIENT, "ERROR: %s command failed", cmd);

  /* revert state */
  man->persist.standalone_disabled = standalone_disabled_save;
  man->persist.special_state_msg = NULL;
  in_extra_reset (mc, IER_RESET);
  *state = EKS_UNDEF;

  gc_free (&gc);
  return ret;
}

char * /* returns allocated base64 signature */
management_query_multiline_flatten_newline (struct management *man,
    const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
{
  int ok;
  char *result = NULL;
  struct buffer *buf;

  ok = management_query_multiline(man, b64_data, prompt, cmd, state, input);
  if (ok && buffer_list_defined(*input))
  {
    buffer_list_aggregate_separator (*input, 10000, "\n");
    buf = buffer_list_peek (*input);
    if (buf && BLEN(buf) > 0)
    {
      result = (char *) malloc(BLEN(buf)+1);
      check_malloc_return(result);
      memcpy(result, buf->data, BLEN(buf));
      result[BLEN(buf)] = '\0';
    }
  }

  buffer_list_free (*input);
  *input = NULL;

  return result;
}

char * /* returns allocated base64 signature */
management_query_multiline_flatten (struct management *man,
    const char *b64_data, const char *prompt, const char *cmd, int *state, struct buffer_list **input)
{
  int ok;
  char *result = NULL;
  struct buffer *buf;

  ok = management_query_multiline(man, b64_data, prompt, cmd, state, input);
  if (ok && buffer_list_defined(*input))
  {
    buffer_list_aggregate (*input, 2048);
    buf = buffer_list_peek (*input);
    if (buf && BLEN(buf) > 0)
    {
      result = (char *) malloc(BLEN(buf)+1);
      check_malloc_return(result);
      memcpy(result, buf->data, BLEN(buf));
      result[BLEN(buf)] = '\0';
    }
  }

  buffer_list_free (*input);
  *input = NULL;

  return result;
}

char * /* returns allocated base64 signature */
management_query_rsa_sig (struct management *man,
			  const char *b64_data)
{
  return management_query_multiline_flatten(man, b64_data, "RSA_SIGN", "rsa-sign",
      &man->connection.ext_key_state, &man->connection.ext_key_input);
}


char* management_query_cert (struct management *man, const char *cert_name)
{
  const char prompt_1[] = "NEED-CERTIFICATE:";
  struct buffer buf_prompt = alloc_buf(strlen(cert_name) + 20);
  buf_write(&buf_prompt, prompt_1, strlen(prompt_1));
  buf_write(&buf_prompt, cert_name, strlen(cert_name)+1); // +1 for \0

  char *result;
  result = management_query_multiline_flatten_newline(management,
      NULL, (char*)buf_bptr(&buf_prompt), "certificate",
      &man->connection.ext_cert_state, &man->connection.ext_cert_input);
  free_buf(&buf_prompt);
  return result;
}

#endif

/*
 * Return true if management_hold() would block
 */
bool
management_would_hold (struct management *man)
{
  return (man->settings.flags & MF_HOLD) && !man->persist.hold_release && man_standalone_ok (man);
}

/*
 * Return true if (from the management interface's perspective) OpenVPN should
 * daemonize.
 */
bool
management_should_daemonize (struct management *man)
{
  return management_would_hold (man) || (man->settings.flags & MF_QUERY_PASSWORDS);
}

/*
 * If the hold flag is enabled, hibernate until a management client releases the hold.
 * Return true if the caller should not sleep for an additional time interval.
 */
bool
management_hold (struct management *man)
{
  if (management_would_hold (man))
    {
      volatile int signal_received = 0;
      const bool standalone_disabled_save = man->persist.standalone_disabled;

      man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */
      man->persist.special_state_msg = NULL;
      man->settings.mansig |= MANSIG_IGNORE_USR1_HUP;

      man_wait_for_client_connection (man, &signal_received, 0, MWCC_HOLD_WAIT);

      if (!signal_received)
	{
	  man->persist.special_state_msg = ">HOLD:Waiting for hold release";
	  msg (M_CLIENT, "%s", man->persist.special_state_msg);

	  /* run command processing event loop until we get our username/password */
	  do
	    {
	      man_standalone_event_loop (man, &signal_received, 0);
	      if (!signal_received)
		man_check_for_signals (&signal_received);
	      if (signal_received)
		break;
	    } while (!man->persist.hold_release);
	}

      /* revert state */
      man->persist.standalone_disabled = standalone_disabled_save;
      man->persist.special_state_msg = NULL;
      man->settings.mansig &= ~MANSIG_IGNORE_USR1_HUP;

      return true;
    }
  return false;
}

/*
 * struct command_line
 */

struct command_line *
command_line_new (const int buf_len)
{
  struct command_line *cl;
  ALLOC_OBJ_CLEAR (cl, struct command_line);
  cl->buf = alloc_buf (buf_len);
  cl->residual = alloc_buf (buf_len);
  return cl;
}

void
command_line_reset (struct command_line *cl)
{
  buf_clear (&cl->buf);
  buf_clear (&cl->residual);
}

void
command_line_free (struct command_line *cl)
{
  command_line_reset (cl);
  free_buf (&cl->buf);
  free_buf (&cl->residual);
  free (cl);
}

void
command_line_add (struct command_line *cl, const unsigned char *buf, const int len)
{
  int i;
  for (i = 0; i < len; ++i)
    {
      if (buf[i] && char_class(buf[i], (CC_PRINT|CC_NEWLINE)))
	{
	  if (!buf_write_u8 (&cl->buf, buf[i]))
	    buf_clear (&cl->buf);
	}
    }
}

const unsigned char *
command_line_get (struct command_line *cl)
{
  int i;
  const unsigned char *ret = NULL;

  i = buf_substring_len (&cl->buf, '\n');
  if (i >= 0)
    {
      buf_copy_excess (&cl->residual, &cl->buf, i);
      buf_chomp (&cl->buf);
      ret = (const unsigned char *) BSTR (&cl->buf);
    }
  return ret;
}

void
command_line_next (struct command_line *cl)
{
  buf_clear (&cl->buf);
  buf_copy (&cl->buf, &cl->residual);
  buf_clear (&cl->residual);
}

/*
 * struct log_entry
 */

const char *
log_entry_print (const struct log_entry *e, unsigned int flags, struct gc_arena *gc)
{
  struct buffer out = alloc_buf_gc (ERR_BUF_SIZE, gc);
  if (flags & LOG_FATAL_NOTIFY)
    buf_printf (&out, ">FATAL:");    
  if (flags & LOG_PRINT_LOG_PREFIX)
    buf_printf (&out, ">LOG:");
  if (flags & LOG_PRINT_ECHO_PREFIX)
    buf_printf (&out, ">ECHO:");
  if (flags & LOG_PRINT_STATE_PREFIX)
    buf_printf (&out, ">STATE:");
  if (flags & LOG_PRINT_INT_DATE)
    buf_printf (&out, "%u,", (unsigned int)e->timestamp);
  if (flags & LOG_PRINT_MSG_FLAGS)
    buf_printf (&out, "%s,", msg_flags_string (e->u.msg_flags, gc));
  if (flags & LOG_PRINT_STATE)
    buf_printf (&out, "%s,", man_state_name (e->u.state));
  if (flags & LOG_PRINT_INTVAL)
    buf_printf (&out, "%d,", e->u.intval);
  if (e->string)
    buf_printf (&out, "%s", e->string);
  if (flags & LOG_PRINT_LOCAL_IP)
    buf_printf (&out, ",%s", print_in_addr_t (e->local_ip, IA_EMPTY_IF_UNDEF, gc));
  if (flags & LOG_PRINT_REMOTE_IP)
    buf_printf (&out, ",%s", print_in_addr_t (e->remote_ip, IA_EMPTY_IF_UNDEF, gc));
  if (flags & LOG_ECHO_TO_LOG)
    msg (D_MANAGEMENT, "MANAGEMENT: %s", BSTR (&out));
  if (flags & LOG_PRINT_CRLF)
    buf_printf (&out, "\r\n");
  return BSTR (&out);
}

static void
log_entry_free_contents (struct log_entry *e)
{
  if (e->string)
    free ((char *)e->string);
  CLEAR (*e);
}

/*
 * struct log_history
 */

static inline int
log_index (const struct log_history *h, int i)
{
  return modulo_add (h->base, i, h->capacity);
}

static void
log_history_obj_init (struct log_history *h, int capacity)
{
  CLEAR (*h);
  h->capacity = capacity;
  ALLOC_ARRAY_CLEAR (h->array, struct log_entry, capacity);
}

struct log_history *
log_history_init (const int capacity)
{
  struct log_history *h;
  ASSERT (capacity > 0);
  ALLOC_OBJ (h, struct log_history);
  log_history_obj_init (h, capacity);
  return h;
}

static void
log_history_free_contents (struct log_history *h)
{
  int i;
  for (i = 0; i < h->size; ++i)
    log_entry_free_contents (&h->array[log_index(h, i)]);
  free (h->array);
}

void
log_history_close (struct log_history *h)
{
  log_history_free_contents (h);
  free (h);
}

void
log_history_add (struct log_history *h, const struct log_entry *le)
{
  struct log_entry *e;
  ASSERT (h->size >= 0 && h->size <= h->capacity);
  if (h->size == h->capacity)
    {
      e = &h->array[h->base];
      log_entry_free_contents (e);
      h->base = log_index (h, 1);
    }
  else
    {
      e = &h->array[log_index(h, h->size)];
      ++h->size;
    }

  *e = *le;
  e->string = string_alloc (le->string, NULL);
}

void
log_history_resize (struct log_history *h, const int capacity)
{
  if (capacity != h->capacity)
    {
      struct log_history newlog;
      int i;

      ASSERT (capacity > 0);
      log_history_obj_init (&newlog, capacity);

      for (i = 0; i < h->size; ++i)
	log_history_add (&newlog, &h->array[log_index(h, i)]);
			 
      log_history_free_contents (h);
      *h = newlog;
    }
}

const struct log_entry *
log_history_ref (const struct log_history *h, const int index)
{
  if (index >= 0 && index < h->size)
    return &h->array[log_index(h, (h->size - 1) - index)];
  else
    return NULL;
}

#else
static void dummy(void) {}
#endif /* ENABLE_MANAGEMENT */