summaryrefslogtreecommitdiffstats
path: root/src/openvpn/init.c
blob: 5dd87815b327dcc2cc5dad7da407af6750e27093 (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
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
/*
 *  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"

#include "win32.h"
#include "init.h"
#include "sig.h"
#include "occ.h"
#include "list.h"
#include "otime.h"
#include "pool.h"
#include "gremlin.h"
#include "pkcs11.h"
#include "ps.h"
#include "lladdr.h"
#include "ping.h"
#include "mstats.h"
#include "ssl_verify.h"

#include "memdbg.h"

#include "occ-inline.h"

static struct context *static_context; /* GLOBAL */

/*
 * Crypto initialization flags
 */
#define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
#define CF_INIT_TLS_MULTI           (1<<1)
#define CF_INIT_TLS_AUTH_STANDALONE (1<<2)

static void do_init_first_time (struct context *c);

void
context_clear (struct context *c)
{
  CLEAR (*c);
}

void
context_clear_1 (struct context *c)
{
  CLEAR (c->c1);
}

void
context_clear_2 (struct context *c)
{
  CLEAR (c->c2);
}

void
context_clear_all_except_first_time (struct context *c)
{
  const bool first_time_save = c->first_time;
  const struct context_persist cpsave = c->persist;
  context_clear (c);
  c->first_time = first_time_save;
  c->persist = cpsave;
}

/*
 * Should be called after options->ce is modified at the top
 * of a SIGUSR1 restart.
 */
static void
update_options_ce_post (struct options *options)
{
#if P2MP
  /*
   * In pull mode, we usually import --ping/--ping-restart parameters from
   * the server.  However we should also set an initial default --ping-restart
   * for the period of time before we pull the --ping-restart parameter
   * from the server.
   */
  if (options->pull
      && options->ping_rec_timeout_action == PING_UNDEF
      && proto_is_dgram(options->ce.proto))
    {
      options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART;
      options->ping_rec_timeout_action = PING_RESTART;
    }
#endif
}

#ifdef ENABLE_MANAGEMENT
static bool
management_callback_proxy_cmd (void *arg, const char **p)
{
  struct context *c = arg;
  struct connection_entry *ce = &c->options.ce;
  struct gc_arena *gc = &c->c2.gc;
  bool ret = false;

  update_time();
  if (streq (p[1], "NONE"))
    ret = true;
  else if (p[2] && p[3])
    {
      if (streq (p[1], "HTTP"))
        {
          struct http_proxy_options *ho;
          if (ce->proto != PROTO_TCP && ce->proto != PROTO_TCP_CLIENT )
            {
              msg (M_WARN, "HTTP proxy support only works for TCP based connections");
              return false;
            }
          ho = init_http_proxy_options_once (&ce->http_proxy_options, gc);
          ho->server = string_alloc (p[2], gc);
          ho->port = string_alloc (p[3], gc);
          ho->retry = true;
          ho->auth_retry = (p[4] && streq (p[4], "nct") ? PAR_NCT : PAR_ALL);
          ret = true;
        }
      else if (streq (p[1], "SOCKS"))
        {
          ce->socks_proxy_server = string_alloc (p[2], gc);
          ce->socks_proxy_port = p[3];
          ret = true;
        }
    }
  else
    msg (M_WARN, "Bad proxy command");

  ce->flags &= ~CE_MAN_QUERY_PROXY;

  return ret;
}

static bool
ce_management_query_proxy (struct context *c)
{
  const struct connection_list *l = c->options.connection_list;
  struct connection_entry *ce = &c->options.ce;
  struct gc_arena gc;
  bool ret = true;

  update_time();
  if (management)
    {
      gc = gc_new ();
      {
	struct buffer out = alloc_buf_gc (256, &gc);
	buf_printf (&out, ">PROXY:%u,%s,%s", (l ? l->current : 0) + 1,
		    (proto_is_udp (ce->proto) ? "UDP" : "TCP"), np (ce->remote));
	management_notify_generic (management, BSTR (&out));
      }
      ce->flags |= CE_MAN_QUERY_PROXY;
      while (ce->flags & CE_MAN_QUERY_PROXY)
        {
          management_event_loop_n_seconds (management, 1);
          if (IS_SIG (c))
            {
              ret = false;
              break;
            }
        }
      gc_free (&gc);
    }

  return ret;
}


static bool
management_callback_remote_cmd (void *arg, const char **p)
{
  struct context *c = (struct context *) arg;
  struct connection_entry *ce = &c->options.ce;
  int ret = false;
  if (p[1] && ((ce->flags>>CE_MAN_QUERY_REMOTE_SHIFT)&CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
    {
      int flags = 0;
      if (!strcmp(p[1], "ACCEPT"))
	{
	  flags = CE_MAN_QUERY_REMOTE_ACCEPT;
	  ret = true;
	}
      else if (!strcmp(p[1], "SKIP"))
	{
	  flags = CE_MAN_QUERY_REMOTE_SKIP;
	  ret = true;
	}
      else if (!strcmp(p[1], "MOD") && p[2] && p[3])
	{
	  if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
	    {
	      struct remote_host_store *rhs = c->options.rh_store;
	      if (!rhs)
		{
		  ALLOC_OBJ_CLEAR_GC (rhs, struct remote_host_store, &c->options.gc);
		  c->options.rh_store = rhs;
		}
	      strncpynt(rhs->host, p[2], RH_HOST_LEN);
              strncpynt(rhs->port, p[3], RH_PORT_LEN);

	      ce->remote = rhs->host;
	      ce->remote_port = rhs->port;
	      flags = CE_MAN_QUERY_REMOTE_MOD;
	      ret = true;
	    }
	}
      if (ret)
	{
	  ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK<<CE_MAN_QUERY_REMOTE_SHIFT);
	  ce->flags |= ((flags&CE_MAN_QUERY_REMOTE_MASK)<<CE_MAN_QUERY_REMOTE_SHIFT);
	}
    }
  return ret;
}

static bool
ce_management_query_remote (struct context *c)
{
  struct gc_arena gc = gc_new ();
  volatile struct connection_entry *ce = &c->options.ce;
  int ret = true;
  update_time();
  if (management)
    {
      struct buffer out = alloc_buf_gc (256, &gc);
      buf_printf (&out, ">REMOTE:%s,%s,%s", np(ce->remote), ce->remote_port, proto2ascii(ce->proto, ce->af, false));
      management_notify_generic(management, BSTR (&out));
      ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK<<CE_MAN_QUERY_REMOTE_SHIFT);
      ce->flags |= (CE_MAN_QUERY_REMOTE_QUERY<<CE_MAN_QUERY_REMOTE_SHIFT);
      while (((ce->flags>>CE_MAN_QUERY_REMOTE_SHIFT) & CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
	{
	  management_event_loop_n_seconds (management, 1);
	  if (IS_SIG (c))
	    {
	      ret = false;
	      break;
	    }
	}
    }
  {
    const int flags = ((ce->flags>>CE_MAN_QUERY_REMOTE_SHIFT) & CE_MAN_QUERY_REMOTE_MASK);
    ret = (flags != CE_MAN_QUERY_REMOTE_SKIP);
  }
  gc_free (&gc);
  return ret;
}
#endif /* ENABLE_MANAGEMENT */

/*
 * Initialize and possibly randomize connection list.
 */
static void
init_connection_list (struct context *c)
{
  struct connection_list *l = c->options.connection_list;

  l->current = -1;
  if (c->options.remote_random)
    {
      int i;
      for (i = 0; i < l->len; ++i)
        {
          const int j = get_random () % l->len;
          if (i != j)
            {
              struct connection_entry *tmp;
              tmp = l->array[i];
              l->array[i] = l->array[j];
              l->array[j] = tmp;
            }
        }
    }
}

/*
 * Clear the remote address list
 */
static void clear_remote_addrlist (struct link_socket_addr *lsa, bool free)
{
    if (lsa->remote_list && free)
      freeaddrinfo(lsa->remote_list);
    lsa->remote_list = NULL;
    lsa->current_remote = NULL;
}

/*
 * Increment to next connection entry
 */
static void
next_connection_entry (struct context *c)
{
  struct connection_list *l = c->options.connection_list;
  bool ce_defined;
  struct connection_entry *ce;
  int n_cycles = 0;

  do {
    ce_defined = true;
    if (c->options.no_advance && l->current >= 0)
      {
        c->options.no_advance = false;
      }
    else
      {
        /* Check if there is another resolved address to try for
         * the current connection */
        if (c->c1.link_socket_addr.current_remote &&
            c->c1.link_socket_addr.current_remote->ai_next)
          {
            c->c1.link_socket_addr.current_remote =
                c->c1.link_socket_addr.current_remote->ai_next;
          }
        else
          {
            /* FIXME (schwabe) fix the persist-remote-ip option for real,
             * this is broken probably ever since connection lists and multiple
             * remote existed
             */
            if (!c->options.persist_remote_ip)
	      {
		/* close_instance should have cleared the addrinfo objects */
		ASSERT (c->c1.link_socket_addr.current_remote == NULL);
		ASSERT (c->c1.link_socket_addr.remote_list == NULL);
	      }
            else
                c->c1.link_socket_addr.current_remote =
                c->c1.link_socket_addr.remote_list;

            /*
             * Increase the number of connection attempts
             * If this is connect-retry-max * size(l)
             * OpenVPN will quit
             */

            c->options.unsuccessful_attempts++;

            if (++l->current >= l->len)
              {

                l->current = 0;
                if (++n_cycles >= 2)
                    msg (M_FATAL, "No usable connection profiles are present");
              }
          }
      }

    ce = l->array[l->current];

    if (ce->flags & CE_DISABLED)
      ce_defined = false;

    c->options.ce = *ce;
#ifdef ENABLE_MANAGEMENT
    if (ce_defined && management && management_query_remote_enabled(management))
      {
        /* allow management interface to override connection entry details */
        ce_defined = ce_management_query_remote(c);
        if (IS_SIG (c))
          break;
      }
    else
#endif

#ifdef ENABLE_MANAGEMENT
      if (ce_defined && management && management_query_proxy_enabled (management))
        {
          ce_defined = ce_management_query_proxy (c);
          if (IS_SIG (c))
            break;
        }
#endif
  } while (!ce_defined);

  /* Check if this connection attempt would bring us over the limit */
  if (c->options.connect_retry_max > 0 &&
      c->options.unsuccessful_attempts > (l->len  * c->options.connect_retry_max))
      msg(M_FATAL, "All connections have been connect-retry-max (%d) times unsuccessful, exiting",
          c->options.connect_retry_max);
  update_options_ce_post (&c->options);
}

/*
 * Query for private key and auth-user-pass username/passwords
 */
void
init_query_passwords (const struct context *c)
{
#ifdef ENABLE_CRYPTO
  /* Certificate password input */
  if (c->options.key_pass_file)
    pem_password_setup (c->options.key_pass_file);
#endif
  
#if P2MP
  /* Auth user/pass input */
  if (c->options.auth_user_pass_file)
    {
#ifdef ENABLE_CLIENT_CR
      auth_user_pass_setup (c->options.auth_user_pass_file, &c->options.sc_info);
#else
      auth_user_pass_setup (c->options.auth_user_pass_file, NULL);
#endif
    }
#endif
}

/*
 * Initialize/Uninitialize HTTP or SOCKS proxy
 */

static void
uninit_proxy_dowork (struct context *c)
{
  if (c->c1.http_proxy_owned && c->c1.http_proxy)
    {
      http_proxy_close (c->c1.http_proxy);
      c->c1.http_proxy = NULL;
      c->c1.http_proxy_owned = false;
    }
  if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
    {
      socks_proxy_close (c->c1.socks_proxy);
      c->c1.socks_proxy = NULL;
      c->c1.socks_proxy_owned = false;
    }
}

static void
init_proxy_dowork (struct context *c)
{
  bool did_http = false;

  uninit_proxy_dowork (c);

  if (c->options.ce.http_proxy_options)
    {
      /* Possible HTTP proxy user/pass input */
      c->c1.http_proxy = http_proxy_new (c->options.ce.http_proxy_options);
      if (c->c1.http_proxy)
	{
	  did_http = true;
	  c->c1.http_proxy_owned = true;
	}
    }

    if (!did_http && c->options.ce.socks_proxy_server)
    {
      c->c1.socks_proxy = socks_proxy_new (c->options.ce.socks_proxy_server,
					   c->options.ce.socks_proxy_port,
					   c->options.ce.socks_proxy_authfile,
					   c->options.ce.socks_proxy_retry);
      if (c->c1.socks_proxy)
	{
	  c->c1.socks_proxy_owned = true;
	}
    }
}

static void
init_proxy (struct context *c)
{
  init_proxy_dowork (c);
}

static void
uninit_proxy (struct context *c)
{
   uninit_proxy_dowork (c);
}

void
context_init_1 (struct context *c)
{
  context_clear_1 (c);

  packet_id_persist_init (&c->c1.pid_persist);

  init_connection_list (c);

#if defined(ENABLE_PKCS11)
  if (c->first_time) {
    int i;
    pkcs11_initialize (true, c->options.pkcs11_pin_cache_period);
    for (i=0;i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL;i++)
     pkcs11_addProvider (c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
       c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
  }
#endif

#if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
 {
   /*
    * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
    */
   struct user_pass up;
   CLEAR (up);
   strcpy (up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
   get_user_pass (&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
   msg (M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
                                           'needok' command, usually 'ok' or 'cancel'. */
 }
#endif

}

void
context_gc_free (struct context *c)
{
  gc_free (&c->c2.gc);
  gc_free (&c->options.gc);
  gc_free (&c->gc);
}

#if PORT_SHARE

static void
close_port_share (void)
{
  if (port_share)
    {
      port_share_close (port_share);
      port_share = NULL;
    }
}

static void
init_port_share (struct context *c)
{
  if (!port_share && (c->options.port_share_host && c->options.port_share_port))
    {
      port_share = port_share_open (c->options.port_share_host,
				    c->options.port_share_port,
				    MAX_RW_SIZE_LINK (&c->c2.frame),
				    c->options.port_share_journal_dir);
      if (port_share == NULL)
	msg (M_FATAL, "Fatal error: Port sharing failed");
    }
}

#endif

bool
init_static (void)
{
  /* configure_path (); */

#if defined(ENABLE_CRYPTO) && defined(DMALLOC)
  crypto_init_dmalloc();
#endif

  init_random_seed ();		/* init random() function, only used as
				   source for weak random numbers */
  error_reset ();		/* initialize error.c */
  reset_check_status ();	/* initialize status check code in socket.c */

#ifdef WIN32
  init_win32 ();
#endif

#ifdef OPENVPN_DEBUG_COMMAND_LINE
  {
    int i;
    for (i = 0; i < argc; ++i)
      msg (M_INFO, "argv[%d] = '%s'", i, argv[i]);
  }
#endif

  update_time ();

#ifdef ENABLE_CRYPTO
  init_ssl_lib ();

  /* init PRNG used for IV generation */
  /* When forking, copy this to more places in the code to avoid fork
     random-state predictability */
  prng_init (NULL, 0);
#endif

#ifdef PID_TEST
  packet_id_interactive_test ();	/* test the sequence number code */
  return false;
#endif

#ifdef SCHEDULE_TEST
  schedule_test ();
  return false;
#endif

#ifdef LIST_TEST
  list_test ();
  return false;
#endif

#ifdef IFCONFIG_POOL_TEST
  ifconfig_pool_test (0x0A010004, 0x0A0100FF);
  return false;
#endif

#ifdef CHARACTER_CLASS_DEBUG
  character_class_debug ();
  return false;
#endif

#ifdef EXTRACT_X509_FIELD_TEST
  extract_x509_field_test ();
  return false;
#endif

#ifdef TIME_TEST
  time_test ();
  return false;
#endif

#ifdef TEST_GET_DEFAULT_GATEWAY
  {
    struct route_gateway_info rgi;
    struct route_ipv6_gateway_info rgi6;
    get_default_gateway(&rgi);
    get_default_gateway_ipv6(&rgi6, NULL);
    print_default_gateway(M_INFO, &rgi, &rgi6);
    return false;
  }
#endif

#ifdef GEN_PATH_TEST
  {
    struct gc_arena gc = gc_new ();
    const char *fn = gen_path ("foo",
			       "bar",
			       &gc);
    printf ("%s\n", fn);
    gc_free (&gc);
  }
  return false;
#endif

#ifdef STATUS_PRINTF_TEST
  {
    struct gc_arena gc = gc_new ();
    const char *tmp_file = create_temp_file ("/tmp", "foo", &gc);
    struct status_output *so = status_open (tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
    status_printf (so, "%s", "foo");
    status_printf (so, "%s", "bar");
    if (!status_close (so))
      msg (M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
    gc_free (&gc);
  }
  return false;
#endif

#ifdef ARGV_TEST
  {
    void argv_test (void);
    argv_test ();
    return false;
  }
#endif

#ifdef PRNG_TEST
  {
    struct gc_arena gc = gc_new ();
    uint8_t rndbuf[8];
    int i;
    prng_init ("sha1", 16);
    /*prng_init (NULL, 0);*/
    const int factor = 1;
    for (i = 0; i < factor * 8; ++i)
      {
#if 1
	prng_bytes (rndbuf, sizeof (rndbuf));
#else
	ASSERT(rand_bytes (rndbuf, sizeof (rndbuf)));
#endif
	printf ("[%d] %s\n", i, format_hex (rndbuf, sizeof (rndbuf), 0, &gc));
      }
    gc_free (&gc);
    prng_uninit ();
    return false;
  }
#endif

#ifdef BUFFER_LIST_AGGREGATE_TEST
  /* test buffer_list_aggregate function */
  {
    static const char *text[] = {
      "It was a bright cold day in April, ",
      "and the clocks were striking ",
      "thirteen. ",
      "Winston Smith, ",
      "his chin nuzzled into his breast in an ",
      "effort to escape the vile wind, ",
      "slipped quickly through the glass doors ",
      "of Victory Mansions, though not quickly ",
      "enough to prevent a swirl of gritty dust from ",
      "entering along with him."
    };

    int iter, listcap;
    for (listcap = 0; listcap < 12; ++listcap)
      {
	for (iter = 0; iter < 512; ++iter)
	  {
	    struct buffer_list *bl = buffer_list_new(listcap);
	    {
	      int i;
	      for (i = 0; i < SIZE(text); ++i)
		buffer_list_push(bl, (unsigned char *)text[i]);
	    }
	    printf("[cap=%d i=%d] *************************\n", listcap, iter);
	    if (!(iter & 8))
	      buffer_list_aggregate(bl, iter/2);
	    if (!(iter & 16))
	      buffer_list_push(bl, (unsigned char *)"Even more text...");
	    buffer_list_aggregate(bl, iter);
	    if (!(iter & 1))
	      buffer_list_push(bl, (unsigned char *)"More text...");
	    {
	      struct buffer *buf;
	      while ((buf = buffer_list_peek(bl)))
		{
		  int c;
		  printf ("'");
		  while ((c = buf_read_u8(buf)) >= 0)
		    putchar(c);
		  printf ("'\n");
		  buffer_list_advance(bl, 0);
		}
	    }
	    buffer_list_free(bl);
	  }
      }
    return false;
  }
#endif

#ifdef MSTATS_TEST
  {
    int i;
    mstats_open("/dev/shm/mstats.dat");
    for (i = 0; i < 30; ++i)
      {
	mmap_stats->n_clients += 1;
	mmap_stats->link_write_bytes += 8;
	mmap_stats->link_read_bytes += 16;
	sleep(1);
      }
    mstats_close();
    return false;
  }
#endif

  return true;
}

void
uninit_static (void)
{
#ifdef ENABLE_CRYPTO
  free_ssl_lib ();
#endif

#ifdef ENABLE_PKCS11
  pkcs11_terminate ();
#endif

#if PORT_SHARE
  close_port_share ();
#endif

#if defined(MEASURE_TLS_HANDSHAKE_STATS) && defined(ENABLE_CRYPTO)
  show_tls_performance_stats ();
#endif
}

void
init_verb_mute (struct context *c, unsigned int flags)
{
  if (flags & IVM_LEVEL_1)
    {
      /* set verbosity and mute levels */
      set_check_status (D_LINK_ERRORS, D_READ_WRITE);
      set_debug_level (c->options.verbosity, SDL_CONSTRAIN);
      set_mute_cutoff (c->options.mute);
    }

  /* special D_LOG_RW mode */
  if (flags & IVM_LEVEL_2)
    c->c2.log_rw = (check_debug_level (D_LOG_RW) && !check_debug_level (D_LOG_RW + 1));
}

/*
 * Possibly set --dev based on --dev-node.
 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
 * set --dev to tun.
 */
void
init_options_dev (struct options *options)
{
  if (!options->dev && options->dev_node) {
    char *dev_node = string_alloc(options->dev_node, NULL); /* POSIX basename() implementaions may modify its arguments */
    options->dev = basename (dev_node);
  }
}

bool
print_openssl_info (const struct options *options)
{
  /*
   * OpenSSL info print mode?
   */
#ifdef ENABLE_CRYPTO
  if (options->show_ciphers || options->show_digests || options->show_engines
      || options->show_tls_ciphers || options->show_curves)
    {
      if (options->show_ciphers)
	show_available_ciphers ();
      if (options->show_digests)
	show_available_digests ();
      if (options->show_engines)
	show_available_engines ();
      if (options->show_tls_ciphers)
	show_available_tls_ciphers (options->cipher_list);
      if (options->show_curves)
	show_available_curves();
      return true;
    }
#endif
  return false;
}

/*
 * Static pre-shared key generation mode?
 */
bool
do_genkey (const struct options * options)
{
#ifdef ENABLE_CRYPTO
  if (options->genkey)
    {
      int nbits_written;

      notnull (options->shared_secret_file,
	       "shared secret output file (--secret)");

      if (options->mlock)	/* should we disable paging? */
	platform_mlockall (true);

      nbits_written = write_key_file (2, options->shared_secret_file);

      msg (D_GENKEY | M_NOPREFIX,
	   "Randomly generated %d bit key written to %s", nbits_written,
	   options->shared_secret_file);
      return true;
    }
#endif
  return false;
}

/*
 * Persistent TUN/TAP device management mode?
 */
bool
do_persist_tuntap (const struct options *options)
{
  if (options->persist_config)
    {
      /* sanity check on options for --mktun or --rmtun */
      notnull (options->dev, "TUN/TAP device (--dev)");
      if (options->ce.remote || options->ifconfig_local
	  || options->ifconfig_remote_netmask
#ifdef ENABLE_CRYPTO
	  || options->shared_secret_file
	  || options->tls_server || options->tls_client
#endif
	)
	msg (M_FATAL|M_OPTERR,
	     "options --mktun or --rmtun should only be used together with --dev");
#ifdef ENABLE_FEATURE_TUN_PERSIST
      tuncfg (options->dev, options->dev_type, options->dev_node,
	      options->persist_mode,
	      options->username, options->groupname, &options->tuntap_options);
      if (options->persist_mode && options->lladdr)
        set_lladdr(options->dev, options->lladdr, NULL);
      return true;
#else
      msg( M_FATAL|M_OPTERR,
	"options --mktun and --rmtun are not available on your operating "
	"system.  Please check 'man tun' (or 'tap'), whether your system "
        "supports using 'ifconfig %s create' / 'destroy' to create/remove "
        "persistant tunnel interfaces.", options->dev );
#endif
    }
  return false;
}

/*
 * Should we become a daemon?
 * Return true if we did it.
 */
bool
possibly_become_daemon (const struct options *options)
{
  bool ret = false;
  if (options->daemon)
    {
      ASSERT (!options->inetd);
      /* Don't chdir immediately, but the end of the init sequence, if needed */
      if (daemon (1, options->log) < 0)
	msg (M_ERR, "daemon() failed or unsupported");
      restore_signal_state ();
      if (options->log)
	set_std_files_to_null (true);

      ret = true;
    }
  return ret;
}

/*
 * Actually do UID/GID downgrade, chroot and SELinux context switching, if requested.
 */
static void
do_uid_gid_chroot (struct context *c, bool no_delay)
{
  static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
  struct context_0 *c0 = c->c0;

  if (c->first_time && c0 && !c0->uid_gid_set)
    {
      /* chroot if requested */
      if (c->options.chroot_dir)
	{
	  if (no_delay)
	    platform_chroot (c->options.chroot_dir);
	  else
	    msg (M_INFO, "NOTE: chroot %s", why_not);
	}

      /* set user and/or group that we want to setuid/setgid to */
      if (no_delay)
	{
	  platform_group_set (&c0->platform_state_group);
	  platform_user_set (&c0->platform_state_user);
	  c0->uid_gid_set = true;
	}
      else if (c0->uid_gid_specified)
	{
	  msg (M_INFO, "NOTE: UID/GID downgrade %s", why_not);
	}

#ifdef ENABLE_MEMSTATS
      if (c->options.memstats_fn)
	mstats_open(c->options.memstats_fn);
#endif

#ifdef ENABLE_SELINUX
      /* Apply a SELinux context in order to restrict what OpenVPN can do
       * to _only_ what it is supposed to do after initialization is complete
       * (basically just network I/O operations). Doing it after chroot
       * requires /proc to be mounted in the chroot (which is annoying indeed
       * but doing it before requires more complex SELinux policies.
       */
      if (c->options.selinux_context)
	{
	  if (no_delay) {
	    if (-1 == setcon (c->options.selinux_context))
	      msg (M_ERR, "setcon to '%s' failed; is /proc accessible?", c->options.selinux_context);
	    else
	      msg (M_INFO, "setcon to '%s' succeeded", c->options.selinux_context);
	  }
	  else
	    msg (M_INFO, "NOTE: setcon %s", why_not);
	}
#endif
    }
}

/*
 * Return common name in a way that is formatted for
 * prepending to msg() output.
 */
const char *
format_common_name (struct context *c, struct gc_arena *gc)
{
  struct buffer out = alloc_buf_gc (256, gc);
#ifdef ENABLE_CRYPTO
  if (c->c2.tls_multi)
    {
      buf_printf (&out, "[%s] ", tls_common_name (c->c2.tls_multi, false));
    }
#endif
  return BSTR (&out);
}

void
pre_setup (const struct options *options)
{
#ifdef WIN32
  if (options->exit_event_name)
    {
      win32_signal_open (&win32_signal,
			 WSO_FORCE_SERVICE,
			 options->exit_event_name,
			 options->exit_event_initial_state);
    }
  else
    {
      win32_signal_open (&win32_signal,
			 WSO_FORCE_CONSOLE,
			 NULL,
			 false);

      /* put a title on the top window bar */
      if (win32_signal.mode == WSO_MODE_CONSOLE)
	{
	  window_title_save (&window_title); 
	  window_title_generate (options->config);
	}
    }
#endif
}

void
reset_coarse_timers (struct context *c)
{
  c->c2.coarse_timer_wakeup = 0;
}

/*
 * Initialize timers
 */
static void
do_init_timers (struct context *c, bool deferred)
{
  update_time ();
  reset_coarse_timers (c);

  /* initialize inactivity timeout */
  if (c->options.inactivity_timeout)
    event_timeout_init (&c->c2.inactivity_interval, c->options.inactivity_timeout, now);

  /* initialize pings */

  if (c->options.ping_send_timeout)
    event_timeout_init (&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);

  if (c->options.ping_rec_timeout)
    event_timeout_init (&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);

#if P2MP
  if (c->options.server_poll_timeout)
    event_timeout_init (&c->c2.server_poll_interval, c->options.server_poll_timeout, now);
#endif

  if (!deferred)
    {
      /* initialize connection establishment timer */
      event_timeout_init (&c->c2.wait_for_connect, 1, now);

#ifdef ENABLE_OCC
      /* initialize occ timers */

      if (c->options.occ
	  && !TLS_MODE (c)
	  && c->c2.options_string_local && c->c2.options_string_remote)
	event_timeout_init (&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);

      if (c->options.mtu_test)
	event_timeout_init (&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
#endif

      /* initialize packet_id persistence timer */
#ifdef ENABLE_CRYPTO
      if (c->options.packet_id_file)
	event_timeout_init (&c->c2.packet_id_persist_interval, 60, now);

      /* initialize tmp_int optimization that limits the number of times we call
	 tls_multi_process in the main event loop */
      interval_init (&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
#endif
    }
}

/*
 * Initialize traffic shaper.
 */
static void
do_init_traffic_shaper (struct context *c)
{
#ifdef ENABLE_FEATURE_SHAPER
  /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
  if (c->options.shaper)
    {
      shaper_init (&c->c2.shaper, c->options.shaper);
      shaper_msg (&c->c2.shaper);
    }
#endif
}

/*
 * Allocate route list structures for IPv4 and IPv6
 * (we do this for IPv4 even if no --route option has been seen, as other
 * parts of OpenVPN might want to fill the route-list with info, e.g. DHCP)
 */
static void
do_alloc_route_list (struct context *c)
{
  if (!c->c1.route_list)
    ALLOC_OBJ_CLEAR_GC (c->c1.route_list, struct route_list, &c->gc);
  if (c->options.routes_ipv6 && !c->c1.route_ipv6_list)
    ALLOC_OBJ_CLEAR_GC (c->c1.route_ipv6_list, struct route_ipv6_list, &c->gc);
}


/*
 * Initialize the route list, resolving any DNS names in route
 * options and saving routes in the environment.
 */
static void
do_init_route_list (const struct options *options,
		    struct route_list *route_list,
		    const struct link_socket_info *link_socket_info,
		    bool fatal,
		    struct env_set *es)
{
  const char *gw = NULL;
  int dev = dev_type_enum (options->dev, options->dev_type);
  int metric = 0;

  if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
    gw = options->ifconfig_remote_netmask;
  if (options->route_default_gateway)
    gw = options->route_default_gateway;
  if (options->route_default_metric)
    metric = options->route_default_metric;

  if (!init_route_list (route_list,
			options->routes,
			gw,
			metric,
			link_socket_current_remote (link_socket_info),
			es))
    {
      if (fatal)
	openvpn_exit (OPENVPN_EXIT_STATUS_ERROR);	/* exit point */
    }
  else
    {
      /* copy routes to environment */
      setenv_routes (es, route_list);
    }
}

static void
do_init_route_ipv6_list (const struct options *options,
		    struct route_ipv6_list *route_ipv6_list,
		    const struct link_socket_info *link_socket_info,
		    bool fatal,
		    struct env_set *es)
{
  const char *gw = NULL;
  int metric = -1;		/* no metric set */

  gw = options->ifconfig_ipv6_remote;		/* default GW = remote end */
#if 0					/* not yet done for IPv6 - TODO!*/
  if ( options->route_ipv6_default_gateway )		/* override? */
    gw = options->route_ipv6_default_gateway;
#endif

  if (options->route_default_metric)
    metric = options->route_default_metric;

  /* redirect (IPv6) gateway to VPN?  if yes, add a few more specifics
   */
  if ( options->routes_ipv6->flags & RG_REROUTE_GW )
    {
      char *opt_list[] = { "::/3", "2000::/4", "3000::/4", "fc00::/7", NULL };
      int i;

      for (i=0; opt_list[i]; i++)
	{
	  add_route_ipv6_to_option_list( options->routes_ipv6,
		      string_alloc (opt_list[i], options->routes_ipv6->gc),
		      NULL, NULL );
	}
    }

  if (!init_route_ipv6_list (route_ipv6_list,
			options->routes_ipv6,
			gw,
			metric,
			link_socket_current_remote_ipv6 (link_socket_info),
			es))
    {
      if (fatal)
	openvpn_exit (OPENVPN_EXIT_STATUS_ERROR);	/* exit point */
    }
  else
    {
      /* copy routes to environment */
      setenv_routes_ipv6 (es, route_ipv6_list);
    }
}


/*
 * Called after all initialization has been completed.
 */
void
initialization_sequence_completed (struct context *c, const unsigned int flags)
{
  static const char message[] = "Initialization Sequence Completed";

  /* Reset the unsuccessful connection counter on complete initialisation */
  c->options.unsuccessful_attempts=0;

  /* If we delayed UID/GID downgrade or chroot, do it now */
  do_uid_gid_chroot (c, true);

  /* Test if errors */
  if (flags & ISC_ERRORS)
    {
#ifdef WIN32
      show_routes (M_INFO|M_NOPREFIX);
      show_adapters (M_INFO|M_NOPREFIX);
      msg (M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
#else
      msg (M_INFO, "%s With Errors", message);
#endif
    }
  else
    msg (M_INFO, "%s", message);

  /* Flag that we initialized */
  if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0)
    c->options.no_advance=true;

#ifdef WIN32
  fork_register_dns_action (c->c1.tuntap);
#endif

#ifdef ENABLE_MANAGEMENT
  /* Tell management interface that we initialized */
  if (management)
    {
      in_addr_t tun_local = 0;
      in_addr_t tun_remote = 0; /* FKS */
      const char *detail = "SUCCESS";
      if (c->c1.tuntap)
	tun_local = c->c1.tuntap->local;
      /* TODO(jjo): for ipv6 this will convert some 32bits in the ipv6 addr
       *            to a meaningless ipv4 address.
       *            In any case, is somewhat inconsistent to send local tunnel
       *            addr with remote _endpoint_ addr (?)
       */
      tun_remote = htonl (c->c1.link_socket_addr.actual.dest.addr.in4.sin_addr.s_addr);
      if (flags & ISC_ERRORS)
	detail = "ERROR";
      management_set_state (management,
			    OPENVPN_STATE_CONNECTED,
			    detail,
			    tun_local,
			    tun_remote);
      if (tun_local)
	management_post_tunnel_open (management, tun_local);
    }
#endif
}

/*
 * Possibly add routes and/or call route-up script
 * based on options.
 */
void
do_route (const struct options *options,
	  struct route_list *route_list,
	  struct route_ipv6_list *route_ipv6_list,
	  const struct tuntap *tt,
	  const struct plugin_list *plugins,
	  struct env_set *es)
{
  if (!options->route_noexec && ( route_list || route_ipv6_list ) )
    {
      add_routes (route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS (options), es);
      setenv_int (es, "redirect_gateway", route_did_redirect_default_gateway(route_list));
    }
#ifdef ENABLE_MANAGEMENT
  if (management)
    management_up_down (management, "UP", es);
#endif

  if (plugin_defined (plugins, OPENVPN_PLUGIN_ROUTE_UP))
    {
      if (plugin_call (plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
	msg (M_WARN, "WARNING: route-up plugin call failed");
    }

  if (options->route_script)
    {
      struct argv argv = argv_new ();
      setenv_str (es, "script_type", "route-up");
      argv_printf (&argv, "%sc", options->route_script);
      openvpn_run_script (&argv, es, 0, "--route-up");
      argv_reset (&argv);
    }

#ifdef WIN32
  if (options->show_net_up)
    {
      show_routes (M_INFO|M_NOPREFIX);
      show_adapters (M_INFO|M_NOPREFIX);
    }
  else if (check_debug_level (D_SHOW_NET))
    {
      show_routes (D_SHOW_NET|M_NOPREFIX);
      show_adapters (D_SHOW_NET|M_NOPREFIX);
    }
#endif
}

/*
 * initialize tun/tap device object
 */
static void
do_init_tun (struct context *c)
{
  c->c1.tuntap = init_tun (c->options.dev,
			   c->options.dev_type,
			   c->options.topology,
			   c->options.ifconfig_local,
			   c->options.ifconfig_remote_netmask,
			   c->options.ifconfig_ipv6_local,
			   c->options.ifconfig_ipv6_netbits,
			   c->options.ifconfig_ipv6_remote,
			   c->c1.link_socket_addr.bind_local,
			   c->c1.link_socket_addr.remote_list,
			   !c->options.ifconfig_nowarn,
			   c->c2.es);

  /* flag tunnel for IPv6 config if --tun-ipv6 is set */
  c->c1.tuntap->ipv6 = c->options.tun_ipv6;

  init_tun_post (c->c1.tuntap,
		 &c->c2.frame,
		 &c->options.tuntap_options);

  c->c1.tuntap_owned = true;
}

/*
 * Open tun/tap device, ifconfig, call up script, etc.
 */

static bool
do_open_tun (struct context *c)
{
  struct gc_arena gc = gc_new ();
  bool ret = false;

  c->c2.ipv4_tun = (!c->options.tun_ipv6
		    && is_dev_type (c->options.dev, c->options.dev_type, "tun"));

#ifndef TARGET_ANDROID
  if (!c->c1.tuntap)
    {
#endif

#ifdef TARGET_ANDROID
      /* If we emulate persist-tun on android we still have to open a new tun and
       * then close the old */
      int oldtunfd=-1;
      if (c->c1.tuntap)
	oldtunfd = c->c1.tuntap->fd;
#endif

      /* initialize (but do not open) tun/tap object */
      do_init_tun (c);

      /* allocate route list structure */
      do_alloc_route_list (c);

      /* parse and resolve the route option list */
      if (c->options.routes && c->c1.route_list && c->c2.link_socket)
	do_init_route_list (&c->options, c->c1.route_list, &c->c2.link_socket->info, false, c->c2.es);
      if (c->options.routes_ipv6 && c->c1.route_ipv6_list )
	do_init_route_ipv6_list (&c->options, c->c1.route_ipv6_list, &c->c2.link_socket->info, false, c->c2.es);

      /* do ifconfig */
      if (!c->options.ifconfig_noexec
	  && ifconfig_order () == IFCONFIG_BEFORE_TUN_OPEN)
	{
	  /* guess actual tun/tap unit number that will be returned
	     by open_tun */
	  const char *guess = guess_tuntap_dev (c->options.dev,
						c->options.dev_type,
						c->options.dev_node,
						&gc);
	  do_ifconfig (c->c1.tuntap, guess, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
	}

      /* possibly add routes */
      if (route_order() == ROUTE_BEFORE_TUN) {
        /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */
        do_route (&c->options, c->c1.route_list, c->c1.route_ipv6_list,
                  c->c1.tuntap, c->plugins, c->c2.es);
      }
#ifdef TARGET_ANDROID
	/* Store the old fd inside the fd so open_tun can use it */
	c->c1.tuntap->fd = oldtunfd;
#endif
      /* open the tun device */
      open_tun (c->options.dev, c->options.dev_type, c->options.dev_node,
		c->c1.tuntap);

      /* set the hardware address */
      if (c->options.lladdr)
	  set_lladdr(c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);

      /* do ifconfig */
      if (!c->options.ifconfig_noexec
	  && ifconfig_order () == IFCONFIG_AFTER_TUN_OPEN)
	{
	  do_ifconfig (c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
	}

      /* run the up script */
      run_up_down (c->options.up_script,
		   c->plugins,
		   OPENVPN_PLUGIN_UP,
		   c->c1.tuntap->actual_name,
		   dev_type_string (c->options.dev, c->options.dev_type),
		   TUN_MTU_SIZE (&c->c2.frame),
		   EXPANDED_SIZE (&c->c2.frame),
		   print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
		   print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
		   "init",
		   NULL,
		   "up",
		   c->c2.es);

      /* possibly add routes */
      if ((route_order() == ROUTE_AFTER_TUN) && (!c->options.route_delay_defined))
	do_route (&c->options, c->c1.route_list, c->c1.route_ipv6_list,
		  c->c1.tuntap, c->plugins, c->c2.es);

      /*
       * Did tun/tap driver give us an MTU?
       */
      if (c->c1.tuntap->post_open_mtu)
	frame_set_mtu_dynamic (&c->c2.frame,
			       c->c1.tuntap->post_open_mtu,
			       SET_MTU_TUN | SET_MTU_UPPER_BOUND);

      ret = true;
      static_context = c;
#ifndef TARGET_ANDROID
    }
  else
    {
      msg (M_INFO, "Preserving previous TUN/TAP instance: %s",
	   c->c1.tuntap->actual_name);

      /* explicitly set the ifconfig_* env vars */
      do_ifconfig_setenv(c->c1.tuntap, c->c2.es);

      /* run the up script if user specified --up-restart */
      if (c->options.up_restart)
	run_up_down (c->options.up_script,
		     c->plugins,
		     OPENVPN_PLUGIN_UP,
		     c->c1.tuntap->actual_name,
		     dev_type_string (c->options.dev, c->options.dev_type),
		     TUN_MTU_SIZE (&c->c2.frame),
		     EXPANDED_SIZE (&c->c2.frame),
		     print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
		     print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
		     "restart",
		     NULL,
		     "up",
		     c->c2.es);
    }
#endif
  gc_free (&gc);
  return ret;
}

/*
 * Close TUN/TAP device
 */

static void
do_close_tun_simple (struct context *c)
{
  msg (D_CLOSE, "Closing TUN/TAP interface");
  close_tun (c->c1.tuntap);
  c->c1.tuntap = NULL;
  c->c1.tuntap_owned = false;
#if P2MP
  CLEAR (c->c1.pulled_options_digest_save);
#endif
}

static void
do_close_tun (struct context *c, bool force)
{
  struct gc_arena gc = gc_new ();
  if (c->c1.tuntap && c->c1.tuntap_owned)
    {
      const char *tuntap_actual = string_alloc (c->c1.tuntap->actual_name, &gc);
      const in_addr_t local = c->c1.tuntap->local;
      const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;

      if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
	{
	  static_context = NULL;

#ifdef ENABLE_MANAGEMENT
	  /* tell management layer we are about to close the TUN/TAP device */
	  if (management)
	    {
	      management_pre_tunnel_close (management);
	      management_up_down (management, "DOWN", c->c2.es);
	    }
#endif

	  /* delete any routes we added */
	  if (c->c1.route_list || c->c1.route_ipv6_list )
           {
              run_up_down (c->options.route_predown_script,
                           c->plugins,
                           OPENVPN_PLUGIN_ROUTE_PREDOWN,
                           tuntap_actual,
                           NULL,
                           TUN_MTU_SIZE (&c->c2.frame),
                           EXPANDED_SIZE (&c->c2.frame),
                           print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
                           print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
                           "init",
                           signal_description (c->sig->signal_received,
                                               c->sig->signal_text),
                           "route-pre-down",
                           c->c2.es);

              delete_routes (c->c1.route_list, c->c1.route_ipv6_list,
                             c->c1.tuntap, ROUTE_OPTION_FLAGS (&c->options), c->c2.es);
            }

	  /* actually close tun/tap device based on --down-pre flag */
	  if (!c->options.down_pre)
	    do_close_tun_simple (c);

	  /* Run the down script -- note that it will run at reduced
	     privilege if, for example, "--user nobody" was used. */
	  run_up_down (c->options.down_script,
		       c->plugins,
		       OPENVPN_PLUGIN_DOWN,
		       tuntap_actual,
		       NULL,
		       TUN_MTU_SIZE (&c->c2.frame),
		       EXPANDED_SIZE (&c->c2.frame),
		       print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
		       print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
		       "init",
		       signal_description (c->sig->signal_received,
					   c->sig->signal_text),
		       "down",
		       c->c2.es);

	  /* actually close tun/tap device based on --down-pre flag */
	  if (c->options.down_pre)
	    do_close_tun_simple (c);
	}
      else
	{
	  /* run the down script on this restart if --up-restart was specified */
	  if (c->options.up_restart)
	    run_up_down (c->options.down_script,
			 c->plugins,
			 OPENVPN_PLUGIN_DOWN,
			 tuntap_actual,
			 NULL,
			 TUN_MTU_SIZE (&c->c2.frame),
			 EXPANDED_SIZE (&c->c2.frame),
			 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
			 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
			 "restart",
			 signal_description (c->sig->signal_received,
					     c->sig->signal_text),
			 "down",
			 c->c2.es);
	}
    }
  gc_free (&gc);
}

void
tun_abort()
{
  struct context *c = static_context;
  if (c)
    {
      static_context = NULL;
      do_close_tun (c, true);
    }
}

/*
 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
 */

#if P2MP
/**
 * Helper for do_up().  Take two option hashes and return true if they are not
 * equal, or either one is all-zeroes.
 */
static bool
options_hash_changed_or_zero(const struct md5_digest *a,
    const struct md5_digest *b)
{
  const struct md5_digest zero = {{0}};
  return memcmp (a, b, sizeof(struct md5_digest)) ||
      memcmp (a, &zero, sizeof(struct md5_digest));
}
#endif /* P2MP */

void
do_up (struct context *c, bool pulled_options, unsigned int option_types_found)
{
  if (!c->c2.do_up_ran)
    {
      reset_coarse_timers (c);

      if (pulled_options && option_types_found)
	do_deferred_options (c, option_types_found);

      /* if --up-delay specified, open tun, do ifconfig, and run up script now */
      if (c->options.up_delay || PULL_DEFINED (&c->options))
	{
	  c->c2.did_open_tun = do_open_tun (c);
	  update_time ();

#if P2MP
	  /*
	   * Was tun interface object persisted from previous restart iteration,
	   * and if so did pulled options string change from previous iteration?
	   */
	  if (!c->c2.did_open_tun
	      && PULL_DEFINED (&c->options)
	      && c->c1.tuntap
	      && options_hash_changed_or_zero (&c->c1.pulled_options_digest_save,
		  &c->c2.pulled_options_digest))
	    {
	      /* if so, close tun, delete routes, then reinitialize tun and add routes */
	      msg (M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
	      do_close_tun (c, true);
	      openvpn_sleep (1);
	      c->c2.did_open_tun = do_open_tun (c);
	      update_time ();
	    }
#endif
	}

      if (c->c2.did_open_tun)
	{
#if P2MP
	  c->c1.pulled_options_digest_save = c->c2.pulled_options_digest;
#endif

	  /* if --route-delay was specified, start timer */
	  if ((route_order() == ROUTE_AFTER_TUN) && c->options.route_delay_defined)
	    {
	      event_timeout_init (&c->c2.route_wakeup, c->options.route_delay, now);
	      event_timeout_init (&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
	      if (c->c1.tuntap)
		tun_standby_init (c->c1.tuntap);
	    }
	  else
	    {
	      initialization_sequence_completed (c, 0); /* client/p2p --route-delay undefined */
	    }
	}
      else if (c->options.mode == MODE_POINT_TO_POINT)
	{
	  initialization_sequence_completed (c, 0); /* client/p2p restart with --persist-tun */
	}
	
      c->c2.do_up_ran = true;
    }
}

/*
 * These are the option categories which will be accepted by pull.
 */
unsigned int
pull_permission_mask (const struct context *c)
{
  unsigned int flags =
      OPT_P_UP
    | OPT_P_ROUTE_EXTRAS
    | OPT_P_SOCKBUF
    | OPT_P_SOCKFLAGS
    | OPT_P_SETENV
    | OPT_P_SHAPER
    | OPT_P_TIMER
    | OPT_P_COMP
    | OPT_P_PERSIST
    | OPT_P_MESSAGES
    | OPT_P_EXPLICIT_NOTIFY
    | OPT_P_ECHO
    | OPT_P_PULL_MODE
    | OPT_P_PEER_ID;

  if (!c->options.route_nopull)
    flags |= (OPT_P_ROUTE | OPT_P_IPWIN32);

  return flags;
}

/*
 * Handle non-tun-related pulled options.
 */
void
do_deferred_options (struct context *c, const unsigned int found)
{
  if (found & OPT_P_MESSAGES)
    {
      init_verb_mute (c, IVM_LEVEL_1|IVM_LEVEL_2);
      msg (D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
    }
  if (found & OPT_P_TIMER)
    {
      do_init_timers (c, true);
      msg (D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
    }

#ifdef ENABLE_OCC
  if (found & OPT_P_EXPLICIT_NOTIFY)
    {
      if (!proto_is_udp(c->options.ce.proto) && c->options.ce.explicit_exit_notification)
	{
	  msg (D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
	  c->options.ce.explicit_exit_notification = 0;
	}
      else
	msg (D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
    }
#endif

#ifdef USE_COMP
  if (found & OPT_P_COMP)
    {
      msg (D_PUSH, "OPTIONS IMPORT: compression parms modified");
      comp_uninit (c->c2.comp_context);
      c->c2.comp_context = comp_init (&c->options.comp);
    }
#endif

  if (found & OPT_P_SHAPER)
    {
      msg (D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
      do_init_traffic_shaper (c);
    }

  if (found & OPT_P_SOCKBUF)
    {
      msg (D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
      link_socket_update_buffer_sizes (c->c2.link_socket, c->options.rcvbuf, c->options.sndbuf);
    }

  if (found & OPT_P_SOCKFLAGS)
    {
      msg (D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
      link_socket_update_flags (c->c2.link_socket, c->options.sockflags);
    }

  if (found & OPT_P_PERSIST)
    msg (D_PUSH, "OPTIONS IMPORT: --persist options modified");
  if (found & OPT_P_UP)
    msg (D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
  if (found & OPT_P_ROUTE)
    msg (D_PUSH, "OPTIONS IMPORT: route options modified");
  if (found & OPT_P_ROUTE_EXTRAS)
    msg (D_PUSH, "OPTIONS IMPORT: route-related options modified");
  if (found & OPT_P_IPWIN32)
    msg (D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
  if (found & OPT_P_SETENV)
    msg (D_PUSH, "OPTIONS IMPORT: environment modified");

#ifdef ENABLE_CRYPTO
  if (found & OPT_P_PEER_ID)
    {
      msg (D_PUSH, "OPTIONS IMPORT: peer-id set");
      c->c2.tls_multi->use_peer_id = true;
      c->c2.tls_multi->peer_id = c->options.peer_id;
      frame_add_to_extra_frame(&c->c2.frame, +3);	/* peer-id overhead */
      if ( !c->options.ce.link_mtu_defined )
	{
	  frame_add_to_link_mtu(&c->c2.frame, +3);
	  msg (D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
				EXPANDED_SIZE(&c->c2.frame));
	}
      else
	{
	  msg (M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
                       " fixed by config - reducing tun-mtu to %d, expect"
                       " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
	}
    }
#endif
}

/*
 * Possible hold on initialization
 */
static bool
do_hold (void)
{
#ifdef ENABLE_MANAGEMENT
  if (management)
    {
      /* block until management hold is released */
      if (management_hold (management))
	return true;
    }
#endif
  return false;
}

/*
 * Sleep before restart.
 */
static void
socket_restart_pause (struct context *c)
{
  int sec = 2;

  switch (c->options.ce.proto)
    {
    case PROTO_TCP_SERVER:
      sec = 1;
      break;
    case PROTO_UDP:
    case PROTO_TCP_CLIENT:
      sec = c->options.ce.connect_retry_seconds;
      break;
    }

#ifdef ENABLE_DEBUG
  if (GREMLIN_CONNECTION_FLOOD_LEVEL (c->options.gremlin))
    sec = 0;
#endif

#if P2MP
  if (auth_retry_get () == AR_NOINTERACT)
    sec = 10;

#if 0 /* not really needed because of c->persist.restart_sleep_seconds */
  if (c->options.server_poll_timeout && sec > 1)
    sec = 1;
#endif
#endif

  if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
    sec = c->persist.restart_sleep_seconds;
  else if (c->persist.restart_sleep_seconds == -1)
    sec = 0;
  c->persist.restart_sleep_seconds = 0;

  /* do managment hold on context restart, i.e. second, third, fourth, etc. initialization */
  if (do_hold ())
    sec = 0;

  if (sec)
    {
      msg (D_RESTART, "Restart pause, %d second(s)", sec);
      openvpn_sleep (sec);
    }
}

/*
 * Do a possible pause on context_2 initialization.
 */
static void
do_startup_pause (struct context *c)
{
  if (!c->first_time)
    socket_restart_pause (c);
  else
    do_hold (); /* do management hold on first context initialization */
}

/*
 * Finalize MTU parameters based on command line or config file options.
 */
static void
frame_finalize_options (struct context *c, const struct options *o)
{
  if (!o)
    o = &c->options;

  /*
   * Set adjustment factor for buffer alignment when no
   * cipher is used.
   */
  if (!CIPHER_ENABLED (c))
    {
      frame_align_to_extra_frame (&c->c2.frame);
      frame_or_align_flags (&c->c2.frame,
			    FRAME_HEADROOM_MARKER_FRAGMENT
			    |FRAME_HEADROOM_MARKER_READ_LINK
			    |FRAME_HEADROOM_MARKER_READ_STREAM);
    }
  
  frame_finalize (&c->c2.frame,
		  o->ce.link_mtu_defined,
		  o->ce.link_mtu,
		  o->ce.tun_mtu_defined,
		  o->ce.tun_mtu);
}

/*
 * Free a key schedule, including OpenSSL components.
 */
static void
key_schedule_free (struct key_schedule *ks, bool free_ssl_ctx)
{
#ifdef ENABLE_CRYPTO
  free_key_ctx_bi (&ks->static_key);
  if (tls_ctx_initialised(&ks->ssl_ctx) && free_ssl_ctx)
    {
      tls_ctx_free (&ks->ssl_ctx);
      free_key_ctx_bi (&ks->tls_auth_key);
    }
#endif /* ENABLE_CRYPTO */
  CLEAR (*ks);
}

#ifdef ENABLE_CRYPTO

static void
init_crypto_pre (struct context *c, const unsigned int flags)
{
  if (c->options.engine)
    crypto_init_lib_engine (c->options.engine);

  if (flags & CF_LOAD_PERSISTED_PACKET_ID)
    {
      /* load a persisted packet-id for cross-session replay-protection */
      if (c->options.packet_id_file)
	packet_id_persist_load (&c->c1.pid_persist, c->options.packet_id_file);
    }

  /* Initialize crypto options */

  if (c->options.use_iv)
    c->c2.crypto_options.flags |= CO_USE_IV;

  if (c->options.mute_replay_warnings)
    c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;

#ifdef ENABLE_PREDICTION_RESISTANCE
  if (c->options.use_prediction_resistance)
    rand_ctx_enable_prediction_resistance();
#endif

}

/*
 * Static Key Mode (using a pre-shared key)
 */
static void
do_init_crypto_static (struct context *c, const unsigned int flags)
{
  const struct options *options = &c->options;
  ASSERT (options->shared_secret_file);

  init_crypto_pre (c, flags);

  /* Initialize packet ID tracking */
  if (options->replay)
    {
      packet_id_init (&c->c2.packet_id,
		      link_socket_proto_connection_oriented (options->ce.proto),
		      options->replay_window,
		      options->replay_time,
		      "STATIC", 0);
      c->c2.crypto_options.packet_id = &c->c2.packet_id;
      c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
      c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
      packet_id_persist_load_obj (&c->c1.pid_persist,
				  c->c2.crypto_options.packet_id);
    }

  if (!key_ctx_bi_defined (&c->c1.ks.static_key))
    {
      struct key2 key2;
      struct key_direction_state kds;

      /* Get cipher & hash algorithms */
      init_key_type (&c->c1.ks.key_type, options->ciphername,
		     options->ciphername_defined, options->authname,
		     options->authname_defined, options->keysize,
		     options->test_crypto, true);

      /* Read cipher and hmac keys from shared secret file */
      {
	unsigned int rkf_flags = RKF_MUST_SUCCEED;
	const char *rkf_file = options->shared_secret_file;

	if (options->shared_secret_file_inline)
	  {
	    rkf_file = options->shared_secret_file_inline;
	    rkf_flags |= RKF_INLINE;
	  }
	read_key_file (&key2, rkf_file, rkf_flags);
      }

      /* Check for and fix highly unlikely key problems */
      verify_fix_key2 (&key2, &c->c1.ks.key_type,
		       options->shared_secret_file);

      /* Initialize OpenSSL key objects */
      key_direction_state_init (&kds, options->key_direction);
      must_have_n_keys (options->shared_secret_file, "secret", &key2,
			kds.need_keys);
      init_key_ctx (&c->c1.ks.static_key.encrypt, &key2.keys[kds.out_key],
		    &c->c1.ks.key_type, OPENVPN_OP_ENCRYPT, "Static Encrypt");
      init_key_ctx (&c->c1.ks.static_key.decrypt, &key2.keys[kds.in_key],
		    &c->c1.ks.key_type, OPENVPN_OP_DECRYPT, "Static Decrypt");

      /* Erase the temporary copy of key */
      CLEAR (key2);
    }
  else
    {
      msg (M_INFO, "Re-using pre-shared static key");
    }

  /* Get key schedule */
  c->c2.crypto_options.key_ctx_bi = &c->c1.ks.static_key;

  /* Compute MTU parameters */
  crypto_adjust_frame_parameters (&c->c2.frame,
				  &c->c1.ks.key_type,
				  options->ciphername_defined,
				  options->use_iv, options->replay, true);

  /* Sanity check on IV, sequence number, and cipher mode options */
  check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
			       options->use_iv);
}

/*
 * Initialize the persistent component of OpenVPN's TLS mode,
 * which is preserved across SIGUSR1 resets.
 */
static void
do_init_crypto_tls_c1 (struct context *c)
{
  const struct options *options = &c->options;

  if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
    {
      /*
       * Initialize the OpenSSL library's global
       * SSL context.
       */
      init_ssl (options, &(c->c1.ks.ssl_ctx));
      if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
	{
#if P2MP
	  switch (auth_retry_get ())
	    {
	    case AR_NONE:
	      msg (M_FATAL, "Error: private key password verification failed");
	      break;
	    case AR_INTERACT:
	      ssl_purge_auth (false);
	    case AR_NOINTERACT:
	      c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
	      break;
	    default:
	      ASSERT (0);
	    }
	  c->sig->signal_text = "private-key-password-failure";
	  return;
#else
	  msg (M_FATAL, "Error: private key password verification failed");
#endif
	}

      /* Get cipher & hash algorithms */
      init_key_type (&c->c1.ks.key_type, options->ciphername,
		     options->ciphername_defined, options->authname,
		     options->authname_defined, options->keysize, true, true);

      /* Initialize PRNG with config-specified digest */
      prng_init (options->prng_hash, options->prng_nonce_secret_len);

      /* TLS handshake authentication (--tls-auth) */
      if (options->tls_auth_file)
	{
	  unsigned int flags = 0;
	  const char *file = options->tls_auth_file;

	  if (options->tls_auth_file_inline)
	    {
	      flags |= GHK_INLINE;
	      file = options->tls_auth_file_inline;
	    }
	  get_tls_handshake_key (&c->c1.ks.key_type,
				 &c->c1.ks.tls_auth_key,
				 file,
				 options->key_direction,
				 flags);
	}

#if 0 /* was: #if ENABLE_INLINE_FILES --  Note that enabling this code will break restarts */
      if (options->priv_key_file_inline)
	{
	  string_clear (c->options.priv_key_file_inline);
	  c->options.priv_key_file_inline = NULL;
	}
#endif
    }
  else
    {
      msg (D_INIT_MEDIUM, "Re-using SSL/TLS context");
    }
}

static void
do_init_crypto_tls (struct context *c, const unsigned int flags)
{
  const struct options *options = &c->options;
  struct tls_options to;
  bool packet_id_long_form;

  ASSERT (options->tls_server || options->tls_client);
  ASSERT (!options->test_crypto);

  init_crypto_pre (c, flags);

  /* Make sure we are either a TLS client or server but not both */
  ASSERT (options->tls_server == !options->tls_client);

  /* initialize persistent component */
  do_init_crypto_tls_c1 (c);
  if (IS_SIG (c))
    return;

  /* Sanity check on IV, sequence number, and cipher mode options */
  check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
			       options->use_iv);

  /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
  packet_id_long_form = cipher_kt_mode_ofb_cfb (c->c1.ks.key_type.cipher);

  /* Compute MTU parameters */
  crypto_adjust_frame_parameters (&c->c2.frame,
				  &c->c1.ks.key_type,
				  options->ciphername_defined,
				  options->use_iv,
				  options->replay, packet_id_long_form);
  tls_adjust_frame_parameters (&c->c2.frame);

  /* Set all command-line TLS-related options */
  CLEAR (to);

  to.crypto_flags_and = ~(CO_PACKET_ID_LONG_FORM);
  if (packet_id_long_form)
    to.crypto_flags_or = CO_PACKET_ID_LONG_FORM;

  to.ssl_ctx = c->c1.ks.ssl_ctx;
  to.key_type = c->c1.ks.key_type;
  to.server = options->tls_server;
  to.key_method = options->key_method;
  to.replay = options->replay;
  to.replay_window = options->replay_window;
  to.replay_time = options->replay_time;
  to.tcp_mode = link_socket_proto_connection_oriented (options->ce.proto);
  to.transition_window = options->transition_window;
  to.handshake_window = options->handshake_window;
  to.packet_timeout = options->tls_timeout;
  to.renegotiate_bytes = options->renegotiate_bytes;
  to.renegotiate_packets = options->renegotiate_packets;
  to.renegotiate_seconds = options->renegotiate_seconds;
  to.single_session = options->single_session;
#ifdef ENABLE_PUSH_PEER_INFO
  if (options->push_peer_info)		/* all there is */
    to.push_peer_info_detail = 2;
  else if (options->pull)		/* pull clients send some details */
    to.push_peer_info_detail = 1;
  else					/* default: no peer-info at all */
    to.push_peer_info_detail = 0;
#endif

  /* should we not xmit any packets until we get an initial
     response from client? */
  if (to.server && options->ce.proto == PROTO_TCP_SERVER)
    to.xmit_hold = true;

#ifdef ENABLE_OCC
  to.disable_occ = !options->occ;
#endif

  to.verify_command = options->tls_verify;
  to.verify_export_cert = options->tls_export_cert;
  to.verify_x509_type = (options->verify_x509_type & 0xff);
  to.verify_x509_name = options->verify_x509_name;
  to.crl_file = options->crl_file;
  to.ssl_flags = options->ssl_flags;
  to.ns_cert_type = options->ns_cert_type;
  memmove (to.remote_cert_ku, options->remote_cert_ku, sizeof (to.remote_cert_ku));
  to.remote_cert_eku = options->remote_cert_eku;
  to.verify_hash = options->verify_hash;
#ifdef ENABLE_X509ALTUSERNAME
  to.x509_username_field = (char *) options->x509_username_field;
#else
  to.x509_username_field = X509_USERNAME_FIELD_DEFAULT;
#endif
  to.es = c->c2.es;

#ifdef ENABLE_DEBUG
  to.gremlin = c->options.gremlin;
#endif

  to.plugins = c->plugins;

#ifdef MANAGEMENT_DEF_AUTH
  to.mda_context = &c->c2.mda_context;
#endif

#if P2MP_SERVER
  to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
  to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
  to.tmp_dir = options->tmp_dir;
  if (options->ccd_exclusive)
    to.client_config_dir_exclusive = options->client_config_dir;
  to.auth_user_pass_file = options->auth_user_pass_file;
#endif

#ifdef ENABLE_X509_TRACK
  to.x509_track = options->x509_track;
#endif

#if P2MP
#ifdef ENABLE_CLIENT_CR
  to.sci = &options->sc_info;
#endif
#endif

#ifdef USE_COMP
  to.comp_options = options->comp;
#endif

#if defined(ENABLE_CRYPTO_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10001000
  if (options->keying_material_exporter_label)
    {
      to.ekm_size = options->keying_material_exporter_length;
      if (to.ekm_size < 16 || to.ekm_size > 4095)
          to.ekm_size = 0;

      to.ekm_label = options->keying_material_exporter_label;
      to.ekm_label_size = strlen(to.ekm_label);
    }
  else
    {
      to.ekm_size = 0;
    }
#endif

  /* TLS handshake authentication (--tls-auth) */
  if (options->tls_auth_file)
    {
      to.tls_auth_key = c->c1.ks.tls_auth_key;
      to.tls_auth.pid_persist = &c->c1.pid_persist;
      to.tls_auth.flags |= CO_PACKET_ID_LONG_FORM;
      crypto_adjust_frame_parameters (&to.frame,
				      &c->c1.ks.key_type,
				      false, false, true, true);
    }

  /* If we are running over TCP, allow for
     length prefix */
  socket_adjust_frame_parameters (&to.frame, options->ce.proto);

  /*
   * Initialize OpenVPN's master TLS-mode object.
   */
  if (flags & CF_INIT_TLS_MULTI)
    c->c2.tls_multi = tls_multi_init (&to);

  if (flags & CF_INIT_TLS_AUTH_STANDALONE)
    c->c2.tls_auth_standalone = tls_auth_standalone_init (&to, &c->c2.gc);
}

static void
do_init_finalize_tls_frame (struct context *c)
{
  if (c->c2.tls_multi)
    {
      tls_multi_init_finalize (c->c2.tls_multi, &c->c2.frame);
      ASSERT (EXPANDED_SIZE (&c->c2.tls_multi->opt.frame) <=
	      EXPANDED_SIZE (&c->c2.frame));
      frame_print (&c->c2.tls_multi->opt.frame, D_MTU_INFO,
		   "Control Channel MTU parms");
    }
  if (c->c2.tls_auth_standalone)
    {
      tls_auth_standalone_finalize (c->c2.tls_auth_standalone, &c->c2.frame);
      frame_print (&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
		   "TLS-Auth MTU parms");
    }
}

/*
 * No encryption or authentication.
 */
static void
do_init_crypto_none (const struct context *c)
{
  ASSERT (!c->options.test_crypto);
  msg (M_WARN,
       "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
}
#endif

static void
do_init_crypto (struct context *c, const unsigned int flags)
{
#ifdef ENABLE_CRYPTO
  if (c->options.shared_secret_file)
    do_init_crypto_static (c, flags);
  else if (c->options.tls_server || c->options.tls_client)
    do_init_crypto_tls (c, flags);
  else				/* no encryption or authentication. */
    do_init_crypto_none (c);
#else /* ENABLE_CRYPTO */
  msg (M_WARN,
       "******* WARNING *******: " PACKAGE_NAME
       " built without crypto library -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
#endif /* ENABLE_CRYPTO */
}

static void
do_init_frame (struct context *c)
{
#ifdef USE_COMP
  /*
   * modify frame parameters if compression is enabled
   */
  if (comp_enabled(&c->options.comp))
    {
      comp_add_to_extra_frame (&c->c2.frame);

#if !defined(ENABLE_LZ4)
      /*
       * Compression usage affects buffer alignment when non-swapped algs
       * such as LZO is used.
       * Newer algs like LZ4 and comp-stub with COMP_F_SWAP don't need
       * any special alignment because of the control-byte swap approach.
       * LZO alignment (on the other hand) is problematic because
       * the presence of the control byte means that either the output of
       * decryption must be written to an unaligned buffer, or the input
       * to compression (or packet dispatch if packet is uncompressed)
       * must be read from an unaligned buffer.
       * This code tries to align the input to compression (or packet
       * dispatch if packet is uncompressed) at the cost of requiring
       * decryption output to be written to an unaligned buffer, so
       * it's more of a tradeoff than an optimal solution and we don't
       * include it when we are doing a modern build with LZ4.
       * Strictly speaking, on the server it would be better to execute
       * this code for every connection after we decide the compression
       * method, but currently the frame code doesn't appear to be
       * flexible enough for this, since the frame is already established
       * before it is known which compression options will be pushed.
       */
      if (comp_unswapped_prefix (&c->options.comp) && CIPHER_ENABLED (c))
	{
	  frame_add_to_align_adjust (&c->c2.frame, COMP_PREFIX_LEN);
	  frame_or_align_flags (&c->c2.frame,
				FRAME_HEADROOM_MARKER_FRAGMENT
				|FRAME_HEADROOM_MARKER_DECRYPT);
	}
#endif

#ifdef ENABLE_FRAGMENT
      comp_add_to_extra_frame (&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
#endif
    }
#endif /* USE_COMP */

  /*
   * Adjust frame size for UDP Socks support.
   */
  if (c->options.ce.socks_proxy_server)
    socks_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);

  /*
   * Adjust frame size based on the --tun-mtu-extra parameter.
   */
  if (c->options.ce.tun_mtu_extra_defined)
    tun_adjust_frame_parameters (&c->c2.frame, c->options.ce.tun_mtu_extra);

  /*
   * Adjust frame size based on link socket parameters.
   * (Since TCP is a stream protocol, we need to insert
   * a packet length uint16_t in the buffer.)
   */
  socket_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);

  /*
   * Fill in the blanks in the frame parameters structure,
   * make sure values are rational, etc.
   */
  frame_finalize_options (c, NULL);

#ifdef USE_COMP
  /*
   * Modify frame parameters if compression is compiled in.
   * Should be called after frame_finalize_options.
   */
  comp_add_to_extra_buffer (&c->c2.frame);
#ifdef ENABLE_FRAGMENT
  comp_add_to_extra_buffer (&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
#endif
#endif /* USE_COMP */

  /* packets with peer-id (P_DATA_V2) need 3 extra bytes in frame (on client)
   * and need link_mtu+3 bytes on socket reception (on server).
   *
   * accomodate receive path in f->extra_link, which has the side effect of
   * also increasing send buffers (BUF_SIZE() macro), which need to be
   * allocated big enough before receiving peer-id option from server.
   *
   * f->extra_frame is adjusted when peer-id option is push-received
   */
  frame_add_to_extra_link(&c->c2.frame, 3);

#ifdef ENABLE_FRAGMENT
  /*
   * Set frame parameter for fragment code.  This is necessary because
   * the fragmentation code deals with payloads which have already been
   * passed through the compression code.
   */
  c->c2.frame_fragment = c->c2.frame;
  frame_subtract_extra (&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
#endif

#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
  /*
   * MTU advisories
   */
  if (c->options.ce.fragment && c->options.mtu_test)
    msg (M_WARN,
	 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
#endif

#ifdef ENABLE_FRAGMENT
  if ((c->options.ce.mssfix || c->options.ce.fragment)
      && TUN_MTU_SIZE (&c->c2.frame_fragment) != ETHERNET_MTU)
    msg (M_WARN,
	 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
	 ETHERNET_MTU, TUN_MTU_SIZE (&c->c2.frame_fragment));
#endif
}

static void
do_option_warnings (struct context *c)
{
  const struct options *o = &c->options;

  if (o->ping_send_timeout && !o->ping_rec_timeout)
    msg (M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");

  if (o->username || o->groupname || o->chroot_dir
#ifdef ENABLE_SELINUX
      || o->selinux_context
#endif
      )
   {
    if (!o->persist_tun)
     msg (M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
    if (!o->persist_key
#ifdef ENABLE_PKCS11
	&& !o->pkcs11_id
#endif
	)
     msg (M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail");
   }

  if (o->chroot_dir && !(o->username && o->groupname))
    msg (M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");

#if P2MP
  if (o->pull && o->ifconfig_local && c->first_time)
    msg (M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");

#if P2MP_SERVER
  if (o->server_bridge_defined | o->server_bridge_proxy_dhcp)
    msg (M_WARN, "NOTE: when bridging your LAN adapter with the TAP adapter, note that the new bridge adapter will often take on its own IP address that is different from what the LAN adapter was previously set to");

  if (o->mode == MODE_SERVER)
    {
      if (o->duplicate_cn && o->client_config_dir)
	msg (M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
      if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
	msg (M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
      if (!o->keepalive_ping || !o->keepalive_timeout)
	msg (M_WARN, "WARNING: --keepalive option is missing from server config");
    }
#endif
#endif

#ifdef ENABLE_CRYPTO
  if (!o->replay)
    msg (M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
  if (!o->use_iv)
    msg (M_WARN, "WARNING: You have disabled Crypto IVs (--no-iv) which may make " PACKAGE_NAME " less secure");

  if (o->tls_server)
    warn_on_use_of_common_subnets ();
  if (o->tls_client
      && !o->tls_verify
      && o->verify_x509_type == VERIFY_X509_NONE
      && !(o->ns_cert_type & NS_CERT_CHECK_SERVER)
      && !o->remote_cert_eku)
    msg (M_WARN, "WARNING: No server certificate verification method has been enabled.  See http://openvpn.net/howto.html#mitm for more info.");
#endif

#ifndef CONNECT_NONBLOCK
  if (o->ce.connect_timeout_defined)
    msg (M_WARN, "NOTE: --connect-timeout option is not supported on this OS");
#endif

  /* If a script is used, print appropiate warnings */
  if (o->user_script_used)
   {
     if (script_security >= SSEC_SCRIPTS)
       msg (M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
     else if (script_security >= SSEC_PW_ENV)
       msg (M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
     else
       msg (M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '--script-security 2' or higher is required to call user-defined scripts or executables");
   }
}

static void
do_init_frame_tls (struct context *c)
{
#ifdef ENABLE_CRYPTO
  do_init_finalize_tls_frame (c);
#endif
}

struct context_buffers *
init_context_buffers (const struct frame *frame)
{
  struct context_buffers *b;

  ALLOC_OBJ_CLEAR (b, struct context_buffers);

  b->read_link_buf = alloc_buf (BUF_SIZE (frame));
  b->read_tun_buf = alloc_buf (BUF_SIZE (frame));

  b->aux_buf = alloc_buf (BUF_SIZE (frame));

#ifdef ENABLE_CRYPTO
  b->encrypt_buf = alloc_buf (BUF_SIZE (frame));
  b->decrypt_buf = alloc_buf (BUF_SIZE (frame));
#endif

#ifdef USE_COMP
  b->compress_buf = alloc_buf (BUF_SIZE (frame));
  b->decompress_buf = alloc_buf (BUF_SIZE (frame));
#endif

  return b;
}

void
free_context_buffers (struct context_buffers *b)
{
  if (b)
    {
      free_buf (&b->read_link_buf);
      free_buf (&b->read_tun_buf);
      free_buf (&b->aux_buf);

#ifdef USE_COMP
      free_buf (&b->compress_buf);
      free_buf (&b->decompress_buf);
#endif

#ifdef ENABLE_CRYPTO
      free_buf (&b->encrypt_buf);
      free_buf (&b->decrypt_buf);
#endif

      free (b);
    }
}

/*
 * Now that we know all frame parameters, initialize
 * our buffers.
 */
static void
do_init_buffers (struct context *c)
{
  c->c2.buffers = init_context_buffers (&c->c2.frame);
  c->c2.buffers_owned = true;
}

#ifdef ENABLE_FRAGMENT
/*
 * Fragmenting code has buffers to initialize
 * once frame parameters are known.
 */
static void
do_init_fragment (struct context *c)
{
  ASSERT (c->options.ce.fragment);
  frame_set_mtu_dynamic (&c->c2.frame_fragment,
			 c->options.ce.fragment, SET_MTU_UPPER_BOUND);
  fragment_frame_init (c->c2.fragment, &c->c2.frame_fragment);
}
#endif

/*
 * Set the --mssfix option.
 */
static void
do_init_mssfix (struct context *c)
{
  if (c->options.ce.mssfix)
    {
      frame_set_mtu_dynamic (&c->c2.frame,
			     c->options.ce.mssfix, SET_MTU_UPPER_BOUND);
    }
}

/*
 * Allocate our socket object.
 */
static void
do_link_socket_new (struct context *c)
{
  ASSERT (!c->c2.link_socket);
  c->c2.link_socket = link_socket_new ();
  c->c2.link_socket_owned = true;
}

/*
 * bind the TCP/UDP socket
 */
static void
do_init_socket_1 (struct context *c, const int mode)
{
  unsigned int sockflags = c->options.sockflags;

#if PORT_SHARE
  if (c->options.port_share_host && c->options.port_share_port)
    sockflags |= SF_PORT_SHARE;
#endif

  link_socket_init_phase1 (c->c2.link_socket,
			   c->options.ce.local,
			   c->options.ce.local_port,
			   c->options.ce.remote,
			   c->options.ce.remote_port,
			   c->c1.dns_cache,
			   c->options.ce.proto,
			   c->options.ce.af,
			   c->options.ce.bind_ipv6_only,
			   mode,
			   c->c2.accept_from,
			   c->c1.http_proxy,
			   c->c1.socks_proxy,
#ifdef ENABLE_DEBUG
			   c->options.gremlin,
#endif
			   c->options.ce.bind_local,
			   c->options.ce.remote_float,
			   c->options.inetd,
			   &c->c1.link_socket_addr,
			   c->options.ipchange,
			   c->plugins,
			   c->options.resolve_retry_seconds,
			   c->options.ce.connect_timeout,
			   c->options.ce.mtu_discover_type,
			   c->options.rcvbuf,
			   c->options.sndbuf,
			   c->options.mark,
			   sockflags);
}

/*
 * finalize the TCP/UDP socket
 */
static void
do_init_socket_2 (struct context *c)
{
  link_socket_init_phase2 (c->c2.link_socket, &c->c2.frame,
			   c->sig);
}

/*
 * Print MTU INFO
 */
static void
do_print_data_channel_mtu_parms (struct context *c)
{
  frame_print (&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
#ifdef ENABLE_FRAGMENT
  if (c->c2.fragment)
    frame_print (&c->c2.frame_fragment, D_MTU_INFO,
		 "Fragmentation MTU parms");
#endif
}

#ifdef ENABLE_OCC
/*
 * Get local and remote options compatibility strings.
 */
static void
do_compute_occ_strings (struct context *c)
{
  struct gc_arena gc = gc_new ();

  c->c2.options_string_local =
    options_string (&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
  c->c2.options_string_remote =
    options_string (&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);

  msg (D_SHOW_OCC, "Local Options String (VER=%s): '%s'",
      options_string_version (c->c2.options_string_local, &gc),
      c->c2.options_string_local);
  msg (D_SHOW_OCC, "Expected Remote Options String (VER=%s): '%s'",
      options_string_version (c->c2.options_string_remote, &gc),
      c->c2.options_string_remote);

#ifdef ENABLE_CRYPTO
  if (c->c2.tls_multi)
    tls_multi_init_set_options (c->c2.tls_multi,
				c->c2.options_string_local,
				c->c2.options_string_remote);
#endif

  gc_free (&gc);
}
#endif

/*
 * These things can only be executed once per program instantiation.
 * Set up for possible UID/GID downgrade, but don't do it yet.
 * Daemonize if requested.
 */
static void
do_init_first_time (struct context *c)
{
  if (c->first_time && !c->c0)
    {
      struct context_0 *c0;

      ALLOC_OBJ_CLEAR_GC (c->c0, struct context_0, &c->gc);
      c0 = c->c0;
      
      /* get user and/or group that we want to setuid/setgid to */
      c0->uid_gid_specified =
	platform_group_get (c->options.groupname, &c0->platform_state_group) |
	platform_user_get (c->options.username, &c0->platform_state_user);

      /* perform postponed chdir if --daemon */
      if (c->did_we_daemonize && c->options.cd_dir == NULL)
	platform_chdir("/");

      /* should we change scheduling priority? */
      platform_nice (c->options.nice);
    }
}

/*
 * If xinetd/inetd mode, don't allow restart.
 */
static void
do_close_check_if_restart_permitted (struct context *c)
{
  if (c->options.inetd
      && (c->sig->signal_received == SIGHUP
	  || c->sig->signal_received == SIGUSR1))
    {
      c->sig->signal_received = SIGTERM;
      msg (M_INFO,
	   PACKAGE_NAME
	   " started by inetd/xinetd cannot restart... Exiting.");
    }
}

/*
 * free buffers
 */
static void
do_close_free_buf (struct context *c)
{
  if (c->c2.buffers_owned)
    {
      free_context_buffers (c->c2.buffers);
      c->c2.buffers = NULL;
      c->c2.buffers_owned = false;
    }
}

/*
 * close TLS
 */
static void
do_close_tls (struct context *c)
{
#ifdef ENABLE_CRYPTO
  if (c->c2.tls_multi)
    {
      tls_multi_free (c->c2.tls_multi, true);
      c->c2.tls_multi = NULL;
    }

#ifdef ENABLE_OCC
  /* free options compatibility strings */
  if (c->c2.options_string_local)
    free (c->c2.options_string_local);
  if (c->c2.options_string_remote)
    free (c->c2.options_string_remote);
  c->c2.options_string_local = c->c2.options_string_remote = NULL;
#endif
#endif
}

/*
 * Free key schedules
 */
static void
do_close_free_key_schedule (struct context *c, bool free_ssl_ctx)
{
  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
    key_schedule_free (&c->c1.ks, free_ssl_ctx);
}

/*
 * Close TCP/UDP connection
 */
static void
do_close_link_socket (struct context *c)
{
  if (c->c2.link_socket && c->c2.link_socket_owned)
    {
      link_socket_close (c->c2.link_socket);
      c->c2.link_socket = NULL;
    }

    
  /* Preserve the resolved list of remote if the user request to or if we want
   * reconnect to the same host again or there are still addresses that need
   * to be tried */
  if (!(c->sig->signal_received == SIGUSR1 &&
        ( (c->options.persist_remote_ip)
         ||
         ( c->sig->source != SIG_SOURCE_HARD &&
          ((c->c1.link_socket_addr.current_remote && c->c1.link_socket_addr.current_remote->ai_next)
           || c->options.no_advance))
         )))
    {
      clear_remote_addrlist(&c->c1.link_socket_addr, !c->options.resolve_in_advance);
    }

    /* Clear the remote actual address when persist_remote_ip is not in use */
    if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
      CLEAR (c->c1.link_socket_addr.actual);

  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip)) {
    if (c->c1.link_socket_addr.bind_local && !c->options.resolve_in_advance)
	freeaddrinfo(c->c1.link_socket_addr.bind_local);

    c->c1.link_socket_addr.bind_local=NULL;
  }
}

/*
 * Close packet-id persistance file
 */
static void
do_close_packet_id (struct context *c)
{
#ifdef ENABLE_CRYPTO
  packet_id_free (&c->c2.packet_id);
  packet_id_persist_save (&c->c1.pid_persist);
  if (!(c->sig->signal_received == SIGUSR1))
    packet_id_persist_close (&c->c1.pid_persist);
#endif
}

#ifdef ENABLE_FRAGMENT
/*
 * Close fragmentation handler.
 */
static void
do_close_fragment (struct context *c)
{
  if (c->c2.fragment)
    {
      fragment_free (c->c2.fragment);
      c->c2.fragment = NULL;
    }
}
#endif

/*
 * Open and close our event objects.
 */

static void
do_event_set_init (struct context *c,
		   bool need_us_timeout)
{
  unsigned int flags = 0;

  c->c2.event_set_max = BASE_N_EVENTS;

  flags |= EVENT_METHOD_FAST;

  if (need_us_timeout)
    flags |= EVENT_METHOD_US_TIMEOUT;

  c->c2.event_set = event_set_init (&c->c2.event_set_max, flags);
  c->c2.event_set_owned = true;
}

static void
do_close_event_set (struct context *c)
{
  if (c->c2.event_set && c->c2.event_set_owned)
    {
      event_free (c->c2.event_set);
      c->c2.event_set = NULL;
      c->c2.event_set_owned = false;
    }
}

/*
 * Open and close --status file
 */

static void
do_open_status_output (struct context *c)
{
  if (!c->c1.status_output)
    {
      c->c1.status_output = status_open (c->options.status_file,
					 c->options.status_file_update_freq,
					 -1,
					 NULL,
					 STATUS_OUTPUT_WRITE);
      c->c1.status_output_owned = true;
    }
}

static void
do_close_status_output (struct context *c)
{
  if (!(c->sig->signal_received == SIGUSR1))
    {
      if (c->c1.status_output_owned && c->c1.status_output)
	{
	  status_close (c->c1.status_output);
	  c->c1.status_output = NULL;
	  c->c1.status_output_owned = false;
	}
    }
}

/*
 * Handle ifconfig-pool persistance object.
 */
static void
do_open_ifconfig_pool_persist (struct context *c)
{
#if P2MP_SERVER
  if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
    {
      c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init (c->options.ifconfig_pool_persist_filename,
								c->options.ifconfig_pool_persist_refresh_freq);
      c->c1.ifconfig_pool_persist_owned = true;
    }
#endif
}

static void
do_close_ifconfig_pool_persist (struct context *c)
{
#if P2MP_SERVER
  if (!(c->sig->signal_received == SIGUSR1))
    {
      if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
	{
	  ifconfig_pool_persist_close (c->c1.ifconfig_pool_persist);
	  c->c1.ifconfig_pool_persist = NULL;
	  c->c1.ifconfig_pool_persist_owned = false;
	}
    }
#endif
}

/*
 * Inherit environmental variables
 */

static void
do_inherit_env (struct context *c, const struct env_set *src)
{
  c->c2.es = env_set_create (NULL);
  c->c2.es_owned = true;
  env_set_inherit (c->c2.es, src);
}

static void
do_env_set_destroy (struct context *c)
{
  if (c->c2.es && c->c2.es_owned)
    {
      env_set_destroy (c->c2.es);
      c->c2.es = NULL;
      c->c2.es_owned = false;
    }
}

/*
 * Fast I/O setup.  Fast I/O is an optimization which only works
 * if all of the following are true:
 *
 * (1) The platform is not Windows
 * (2) --proto udp is enabled
 * (3) --shaper is disabled
 */
static void
do_setup_fast_io (struct context *c)
{
  if (c->options.fast_io)
    {
#ifdef WIN32
      msg (M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
#else
      if (!proto_is_udp(c->options.ce.proto))
	msg (M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
      else
	{
#ifdef ENABLE_FEATURE_SHAPER
	  if (c->options.shaper)
	    msg (M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
	  else
#endif
	    {
	      c->c2.fast_io = true;
	    }
	}
#endif
    }
}

static void
do_signal_on_tls_errors (struct context *c)
{
#ifdef ENABLE_CRYPTO
  if (c->options.tls_exit)
    c->c2.tls_exit_signal = SIGTERM;
  else
    c->c2.tls_exit_signal = SIGUSR1;    
#endif
}

#ifdef ENABLE_PLUGIN

void
init_plugins (struct context *c)
{
  if (c->options.plugin_list && !c->plugins)
    {
      c->plugins = plugin_list_init (c->options.plugin_list);
      c->plugins_owned = true;
    }
}

void
open_plugins (struct context *c, const bool import_options, int init_point)
{
  if (c->plugins && c->plugins_owned)
    {
      if (import_options)
	{
	  struct plugin_return pr, config;
	  plugin_return_init (&pr);
	  plugin_list_open (c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
	  plugin_return_get_column (&pr, &config, "config");
	  if (plugin_return_defined (&config))
	    {
	      int i;
	      for (i = 0; i < config.n; ++i)
		{
		  unsigned int option_types_found = 0;
		  if (config.list[i] && config.list[i]->value)
		    options_string_import (&c->options,
					   config.list[i]->value,
					   D_IMPORT_ERRORS|M_OPTERR,
					   OPT_P_DEFAULT & ~OPT_P_PLUGIN,
					   &option_types_found,
					   c->es);
		}
	    }
	  plugin_return_free (&pr);
	}
      else
	{
	  plugin_list_open (c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
	}
    }
}

static void
do_close_plugins (struct context *c)
{
  if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
    {
      plugin_list_close (c->plugins);
      c->plugins = NULL;
      c->plugins_owned = false;
    }
}

static void
do_inherit_plugins (struct context *c, const struct context *src)
{
  if (!c->plugins && src->plugins)
    {
      c->plugins = plugin_list_inherit (src->plugins);
      c->plugins_owned = true;
    }
}

#endif

#ifdef ENABLE_MANAGEMENT

static void
management_callback_status_p2p (void *arg, const int version, struct status_output *so)
{
  struct context *c = (struct context *) arg;
  print_status (c, so);
}

void
management_show_net_callback (void *arg, const int msglevel)
{
#ifdef WIN32
  show_routes (msglevel);
  show_adapters (msglevel);
  msg (msglevel, "END");
#else
  msg (msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
#endif
}

#ifdef TARGET_ANDROID
int
management_callback_network_change (void *arg, bool samenetwork)
{
    /* Check if the client should translate the network change to a SIGUSR1 to
     reestablish the connection or just reprotect the socket

     At the moment just assume that, for all settings that use pull (not
     --static) and are not using peer-id reestablishing the connection is
     required (unless the network is the same)

     The function returns -1 on invalid fd and -2 if the socket cannot be
     reused. On the -2 return value the man_network_change function triggers
     a SIGUSR1 to force a reconnect.
    */

  int socketfd=-1;
  struct context *c = (struct context *) arg;
  if (!c->c2.link_socket)
    return -1;
  if (c->c2.link_socket->sd == SOCKET_UNDEFINED)
    return -1;

  socketfd = c->c2.link_socket->sd;
  if (!c->options.pull || c->c2.tls_multi->use_peer_id || samenetwork)
    return socketfd;
  else
    return -2;
}
#endif

#endif

void
init_management_callback_p2p (struct context *c)
{
#ifdef ENABLE_MANAGEMENT
  if (management)
    {
      struct management_callback cb;
      CLEAR (cb);
      cb.arg = c;
      cb.status = management_callback_status_p2p;
      cb.show_net = management_show_net_callback;
      cb.proxy_cmd = management_callback_proxy_cmd;
      cb.remote_cmd = management_callback_remote_cmd;
#ifdef TARGET_ANDROID
      cb.network_change = management_callback_network_change;
#endif
      management_set_callback (management, &cb);
    }
#endif
}

#ifdef ENABLE_MANAGEMENT

void
init_management (struct context *c)
{
  if (!management)
    management = management_init ();
}

bool
open_management (struct context *c)
{
  /* initialize management layer */
  if (management)
    {
      if (c->options.management_addr)
	{
	  unsigned int flags = c->options.management_flags;
	  if (c->options.mode == MODE_SERVER)
	    flags |= MF_SERVER;
	  if (management_open (management,
			       c->options.management_addr,
			       c->options.management_port,
			       c->options.management_user_pass,
			       c->options.management_client_user,
			       c->options.management_client_group,
			       c->options.management_log_history_cache,
			       c->options.management_echo_buffer_size,
			       c->options.management_state_buffer_size,
			       c->options.management_write_peer_info_file,
			       c->options.remap_sigusr1,
			       flags))
	    {
	      management_set_state (management,
				    OPENVPN_STATE_CONNECTING,
				    NULL,
				    (in_addr_t)0,
				    (in_addr_t)0);
	    }

	  /* initial management hold, called early, before first context initialization */
	  do_hold ();
	  if (IS_SIG (c))
	    {
	      msg (M_WARN, "Signal received from management interface, exiting");
	      return false;
	    }
	}
      else
	close_management ();
    }
  return true;
}

void
close_management (void)
{
  if (management)
    {
      management_close (management);
      management = NULL;
    }
}

#endif


void
uninit_management_callback (void)
{
#ifdef ENABLE_MANAGEMENT
  if (management)
    {
      management_clear_callback (management);
    }
#endif
}

/*
 * Initialize a tunnel instance, handle pre and post-init
 * signal settings.
 */
void
init_instance_handle_signals (struct context *c, const struct env_set *env, const unsigned int flags)
{
  pre_init_signal_catch ();
  init_instance (c, env, flags);
  post_init_signal_catch ();

  /*
   * This is done so that signals thrown during
   * initialization can bring us back to
   * a management hold.
   */
  if (IS_SIG (c))
    {
      remap_signal (c);
      uninit_management_callback ();  
    }
}

/*
 * Initialize a tunnel instance.
 */
void
init_instance (struct context *c, const struct env_set *env, const unsigned int flags)
{
  const struct options *options = &c->options;
  const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
  int link_socket_mode = LS_MODE_DEFAULT;

  /* init garbage collection level */
  gc_init (&c->c2.gc);

  /* inherit environmental variables */
  if (env)
     do_inherit_env (c, env);

  /* signals caught here will abort */
  c->sig->signal_received = 0;
  c->sig->signal_text = NULL;
  c->sig->source = SIG_SOURCE_SOFT;

  if (c->mode == CM_P2P)
    init_management_callback_p2p (c);

  /* possible sleep or management hold if restart */
  if (c->mode == CM_P2P || c->mode == CM_TOP)
    {
      do_startup_pause (c);
      if (IS_SIG (c))
	goto sig;
    }

  if (c->options.resolve_in_advance)
    {
      do_preresolve (c);
      if (IS_SIG (c))
	goto sig;
    }

  /* map in current connection entry */
  next_connection_entry (c);

  /* link_socket_mode allows CM_CHILD_TCP
     instances to inherit acceptable fds
     from a top-level parent */
  if (c->options.ce.proto == PROTO_TCP_SERVER)
    {
      if (c->mode == CM_TOP)
	link_socket_mode = LS_MODE_TCP_LISTEN;
      else if (c->mode == CM_CHILD_TCP)
	link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
    }

  /* should we disable paging? */
  if (c->first_time && options->mlock)
    platform_mlockall (true);

#if P2MP
  /* get passwords if undefined */
  if (auth_retry_get () == AR_INTERACT)
    init_query_passwords (c);
#endif

  /* initialize context level 2 --verb/--mute parms */
  init_verb_mute (c, IVM_LEVEL_2);

  /* set error message delay for non-server modes */
  if (c->mode == CM_P2P)
    set_check_status_error_delay (P2P_ERROR_DELAY_MS);
    
  /* warn about inconsistent options */
  if (c->mode == CM_P2P || c->mode == CM_TOP)
    do_option_warnings (c);

#ifdef ENABLE_PLUGIN
  /* initialize plugins */
  if (c->mode == CM_P2P || c->mode == CM_TOP)
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
#endif

  /* should we enable fast I/O? */
  if (c->mode == CM_P2P || c->mode == CM_TOP)
    do_setup_fast_io (c);

  /* should we throw a signal on TLS errors? */
  do_signal_on_tls_errors (c);

  /* open --status file */
  if (c->mode == CM_P2P || c->mode == CM_TOP)
    do_open_status_output (c);

  /* open --ifconfig-pool-persist file */
  if (c->mode == CM_TOP)
    do_open_ifconfig_pool_persist (c);

#ifdef ENABLE_OCC
  /* reset OCC state */
  if (c->mode == CM_P2P || child)
    c->c2.occ_op = occ_reset_op ();
#endif

  /* our wait-for-i/o objects, different for posix vs. win32 */
  if (c->mode == CM_P2P)
    do_event_set_init (c, SHAPER_DEFINED (&c->options));
  else if (c->mode == CM_CHILD_TCP)
    do_event_set_init (c, false);

  /* initialize HTTP or SOCKS proxy object at scope level 2 */
  init_proxy (c);

  /* allocate our socket object */
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
    do_link_socket_new (c);

#ifdef ENABLE_FRAGMENT
  /* initialize internal fragmentation object */
  if (options->ce.fragment && (c->mode == CM_P2P || child))
    c->c2.fragment = fragment_init (&c->c2.frame);
#endif

  /* init crypto layer */
  {
    unsigned int crypto_flags = 0;
    if (c->mode == CM_TOP)
      crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
    else if (c->mode == CM_P2P)
      crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
    else if (child)
      crypto_flags = CF_INIT_TLS_MULTI;
    do_init_crypto (c, crypto_flags);
    if (IS_SIG (c) && !child)
      goto sig;
  }

#ifdef USE_COMP
  /* initialize compression library. */
  if (comp_enabled(&options->comp) && (c->mode == CM_P2P || child))
    c->c2.comp_context = comp_init (&options->comp);
#endif

  /* initialize MTU variables */
  do_init_frame (c);

  /* initialize TLS MTU variables */
  do_init_frame_tls (c);

  /* init workspace buffers whose size is derived from frame size */
  if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
    do_init_buffers (c);

#ifdef ENABLE_FRAGMENT
  /* initialize internal fragmentation capability with known frame size */
  if (options->ce.fragment && (c->mode == CM_P2P || child))
    do_init_fragment (c);
#endif

  /* initialize dynamic MTU variable */
  do_init_mssfix (c);

  /* bind the TCP/UDP socket */
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
    do_init_socket_1 (c, link_socket_mode);

  /* initialize tun/tap device object,
     open tun/tap device, ifconfig, run up script, etc. */
  if (!(options->up_delay || PULL_DEFINED (options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
    c->c2.did_open_tun = do_open_tun (c);

  /* print MTU info */
  do_print_data_channel_mtu_parms (c);

#ifdef ENABLE_OCC
  /* get local and remote options compatibility strings */
  if (c->mode == CM_P2P || child)
    do_compute_occ_strings (c);
#endif

  /* initialize output speed limiter */
  if (c->mode == CM_P2P)
    do_init_traffic_shaper (c);

  /* do one-time inits, and possibily become a daemon here */
  do_init_first_time (c);

#ifdef ENABLE_PLUGIN
  /* initialize plugins */
  if (c->mode == CM_P2P || c->mode == CM_TOP)
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
#endif

  /*
   * Actually do UID/GID downgrade, and chroot, if requested.
   * May be delayed by --client, --pull, or --up-delay.
   */
  do_uid_gid_chroot (c, c->c2.did_open_tun);

  /* finalize the TCP/UDP socket */
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
    do_init_socket_2 (c);

  /* initialize timers */
  if (c->mode == CM_P2P || child)
    do_init_timers (c, false);

#ifdef ENABLE_PLUGIN
  /* initialize plugins */
  if (c->mode == CM_P2P || c->mode == CM_TOP)
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
#endif

#if PORT_SHARE
  /* share OpenVPN port with foreign (such as HTTPS) server */
  if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
    init_port_share (c);
#endif
	  
#ifdef ENABLE_PF
  if (child)
    pf_init_context (c);
#endif

  /* Check for signals */
  if (IS_SIG (c))
    goto sig;

  return;

 sig:
  if (!c->sig->signal_text)
    c->sig->signal_text = "init_instance";
  close_context (c, -1, flags);
  return;
}

/*
 * Close a tunnel instance.
 */
void
close_instance (struct context *c)
{
  /* close event objects */
  do_close_event_set (c);

    if (c->mode == CM_P2P
	|| c->mode == CM_CHILD_TCP
	|| c->mode == CM_CHILD_UDP
	|| c->mode == CM_TOP)
      {
	/* if xinetd/inetd mode, don't allow restart */
	do_close_check_if_restart_permitted (c);

#ifdef USE_COMP
	if (c->c2.comp_context)
	  {
	    comp_uninit (c->c2.comp_context);
	    c->c2.comp_context = NULL;
	  }
#endif

	/* free buffers */
	do_close_free_buf (c);

	/* close TLS */
	do_close_tls (c);

	/* free key schedules */
	do_close_free_key_schedule (c, (c->mode == CM_P2P || c->mode == CM_TOP));

	/* close TCP/UDP connection */
	do_close_link_socket (c);

	/* close TUN/TAP device */
	do_close_tun (c, false);

#ifdef MANAGEMENT_DEF_AUTH
	if (management)
	  management_notify_client_close (management, &c->c2.mda_context, NULL);
#endif

#ifdef ENABLE_PF
	pf_destroy_context (&c->c2.pf);
#endif

#ifdef ENABLE_PLUGIN
	/* call plugin close functions and unload */
	do_close_plugins (c);
#endif

	/* close packet-id persistance file */
	do_close_packet_id (c);

	/* close --status file */
	do_close_status_output (c);

#ifdef ENABLE_FRAGMENT
	/* close fragmentation handler */
	do_close_fragment (c);
#endif

	/* close --ifconfig-pool-persist obj */
	do_close_ifconfig_pool_persist (c);

	/* free up environmental variable store */
	do_env_set_destroy (c);

	/* close HTTP or SOCKS proxy */
	uninit_proxy (c);

	/* garbage collect */
	gc_free (&c->c2.gc);
      }
}

void
inherit_context_child (struct context *dest,
		       const struct context *src)
{
  CLEAR (*dest);

  /* proto_is_dgram will ASSERT(0) if proto is invalid */
  dest->mode = proto_is_dgram(src->options.ce.proto)? CM_CHILD_UDP : CM_CHILD_TCP;

  dest->gc = gc_new ();

  ALLOC_OBJ_CLEAR_GC (dest->sig, struct signal_info, &dest->gc);

  /* c1 init */
  packet_id_persist_init (&dest->c1.pid_persist);

#ifdef ENABLE_CRYPTO
  dest->c1.ks.key_type = src->c1.ks.key_type;
  /* inherit SSL context */
  dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
  dest->c1.ks.tls_auth_key = src->c1.ks.tls_auth_key;
#endif

  /* options */
  dest->options = src->options;
  options_detach (&dest->options);

  if (dest->mode == CM_CHILD_TCP)
    {
      /*
       * The CM_TOP context does the socket listen(),
       * and the CM_CHILD_TCP context does the accept().
       */
      dest->c2.accept_from = src->c2.link_socket;
    }

#ifdef ENABLE_PLUGIN
  /* inherit plugins */
  do_inherit_plugins (dest, src);
#endif

  /* context init */
  init_instance (dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
  if (IS_SIG (dest))
    return;

  /* inherit tun/tap interface object */
  dest->c1.tuntap = src->c1.tuntap;

  /* UDP inherits some extra things which TCP does not */
  if (dest->mode == CM_CHILD_UDP)
    {
      /* inherit buffers */
      dest->c2.buffers = src->c2.buffers;

      /* inherit parent link_socket and tuntap */
      dest->c2.link_socket = src->c2.link_socket;

      ALLOC_OBJ_GC (dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
      *dest->c2.link_socket_info = src->c2.link_socket->info;

      /* locally override some link_socket_info fields */
      dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
      dest->c2.link_socket_info->connection_established = false;
    }
}

void
inherit_context_top (struct context *dest,
		     const struct context *src)
{
  /* copy parent */
  *dest = *src;

  /*
   * CM_TOP_CLONE will prevent close_instance from freeing or closing
   * resources owned by the parent.
   *
   * Also note that CM_TOP_CLONE context objects are
   * closed by multi_top_free in multi.c.
   */
  dest->mode = CM_TOP_CLONE; 

  dest->first_time = false;
  dest->c0 = NULL;

  options_detach (&dest->options);
  gc_detach (&dest->gc);
  gc_detach (&dest->c2.gc);

  /* detach plugins */
  dest->plugins_owned = false;

#ifdef ENABLE_CRYPTO
  dest->c2.tls_multi = NULL;
#endif

  /* detach c1 ownership */
  dest->c1.tuntap_owned = false;
  dest->c1.status_output_owned = false;
#if P2MP_SERVER
  dest->c1.ifconfig_pool_persist_owned = false;
#endif

  /* detach c2 ownership */
  dest->c2.event_set_owned = false;
  dest->c2.link_socket_owned = false;
  dest->c2.buffers_owned = false;
  dest->c2.es_owned = false;

  dest->c2.event_set = NULL;
  if (proto_is_dgram(src->options.ce.proto))
    do_event_set_init (dest, false);

#ifdef USE_COMP
  dest->c2.comp_context = NULL;
#endif
}

void
close_context (struct context *c, int sig, unsigned int flags)
{
  ASSERT (c);
  ASSERT (c->sig);

  if (sig >= 0)
    c->sig->signal_received = sig;

  if (c->sig->signal_received == SIGUSR1)
    {
      if ((flags & CC_USR1_TO_HUP)
	  || (c->sig->source == SIG_SOURCE_HARD && (flags & CC_HARD_USR1_TO_HUP)))
        {
          c->sig->signal_received = SIGHUP;
          c->sig->signal_text = "close_context usr1 to hup";
        }
    }

  if (!(flags & CC_NO_CLOSE))
    close_instance (c);

  if (flags & CC_GC_FREE)
    context_gc_free (c);
}

#ifdef ENABLE_CRYPTO

/*
 * Do a loopback test
 * on the crypto subsystem.
 */
static void *
test_crypto_thread (void *arg)
{
  struct context *c = (struct context *) arg;
  const struct options *options = &c->options;

  ASSERT (options->test_crypto);
  init_verb_mute (c, IVM_LEVEL_1);
  context_init_1 (c);
  next_connection_entry(c);
  do_init_crypto_static (c, 0);

  frame_finalize_options (c, options);

  test_crypto (&c->c2.crypto_options, &c->c2.frame);

  key_schedule_free (&c->c1.ks, true);
  packet_id_free (&c->c2.packet_id);

  context_gc_free (c);
  return NULL;
}

#endif

bool
do_test_crypto (const struct options *o)
{
#ifdef ENABLE_CRYPTO
  if (o->test_crypto)
    {
      struct context c;

      /* print version number */
      msg (M_INFO, "%s", title_string);

      context_clear (&c);
      c.options = *o;
      options_detach (&c.options);
      c.first_time = true;
      test_crypto_thread ((void *) &c);
      return true;
    }
#endif
  return false;
}