summaryrefslogtreecommitdiff
path: root/src/openvpn/route.c
blob: 532edc6ad672753326a92be3e86e7f8e6a5494b9 (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
/*
 *  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
 */

/*
 * Support routines for adding/deleting network routes.
 */

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

#include "syshead.h"

#include "common.h"
#include "error.h"
#include "route.h"
#include "misc.h"
#include "socket.h"
#include "manage.h"
#include "win32.h"
#include "options.h"

#include "memdbg.h"

#ifdef WIN32
#define METRIC_NOT_USED ((DWORD)-1)
#endif

static void delete_route (struct route_ipv4 *r, const struct tuntap *tt, unsigned int flags, const struct route_gateway_info *rgi, const struct env_set *es);

static void get_bypass_addresses (struct route_bypass *rb, const unsigned int flags);

#ifdef ENABLE_DEBUG

static void
print_bypass_addresses (const struct route_bypass *rb)
{
  struct gc_arena gc = gc_new ();
  int i;
  for (i = 0; i < rb->n_bypass; ++i)
    {
      msg (D_ROUTE, "ROUTE: bypass_host_route[%d]=%s",
	   i,
	   print_in_addr_t (rb->bypass[i], 0, &gc));
    }
  gc_free (&gc);
}

#endif

static bool
add_bypass_address (struct route_bypass *rb, const in_addr_t a)
{
  int i;
  for (i = 0; i < rb->n_bypass; ++i)
    {
      if (a == rb->bypass[i]) /* avoid duplicates */
	return true;
    }
  if (rb->n_bypass < N_ROUTE_BYPASS)
    {
      rb->bypass[rb->n_bypass++] = a;
      return true;
    }
  else
    {
      return false;
    }
}

struct route_option_list *
new_route_option_list (const int max_routes, struct gc_arena *a)
{
  struct route_option_list *ret;
  ALLOC_VAR_ARRAY_CLEAR_GC (ret, struct route_option_list, struct route_option, max_routes, a);
  ret->capacity = max_routes;
  return ret;
}

struct route_ipv6_option_list *
new_route_ipv6_option_list (const int max_routes, struct gc_arena *a)
{
  struct route_ipv6_option_list *ret;
  ALLOC_VAR_ARRAY_CLEAR_GC (ret, struct route_ipv6_option_list, struct route_ipv6_option, max_routes, a);
  ret->capacity = max_routes;
  return ret;
}

struct route_option_list *
clone_route_option_list (const struct route_option_list *src, struct gc_arena *a)
{
  const size_t rl_size = array_mult_safe (sizeof(struct route_option), src->capacity, sizeof(struct route_option_list));
  struct route_option_list *ret = gc_malloc (rl_size, false, a);
  memcpy (ret, src, rl_size);
  return ret;
}

struct route_ipv6_option_list *
clone_route_ipv6_option_list (const struct route_ipv6_option_list *src, struct gc_arena *a)
{
  const size_t rl_size = array_mult_safe (sizeof(struct route_ipv6_option), src->capacity, sizeof(struct route_ipv6_option_list));
  struct route_ipv6_option_list *ret = gc_malloc (rl_size, false, a);
  memcpy (ret, src, rl_size);
  return ret;
}

void
copy_route_option_list (struct route_option_list *dest, const struct route_option_list *src)
{
  const size_t src_size = array_mult_safe (sizeof(struct route_option), src->capacity, sizeof(struct route_option_list));
  if (src->capacity > dest->capacity)
    msg (M_FATAL, PACKAGE_NAME " ROUTE: (copy) number of route options in src (%d) is greater than route list capacity in dest (%d)", src->capacity, dest->capacity);
  memcpy (dest, src, src_size);
}

void
copy_route_ipv6_option_list (struct route_ipv6_option_list *dest,
			     const struct route_ipv6_option_list *src)
{
  const size_t src_size = array_mult_safe (sizeof(struct route_ipv6_option), src->capacity, sizeof(struct route_ipv6_option_list));
  if (src->capacity > dest->capacity)
    msg (M_FATAL, PACKAGE_NAME " ROUTE: (copy) number of route options in src (%d) is greater than route list capacity in dest (%d)", src->capacity, dest->capacity);
  memcpy (dest, src, src_size);
}

struct route_list *
new_route_list (const int max_routes, struct gc_arena *a)
{
  struct route_list *ret;
  ALLOC_VAR_ARRAY_CLEAR_GC (ret, struct route_list, struct route_ipv4, max_routes, a);
  ret->capacity = max_routes;
  return ret;
}

struct route_ipv6_list *
new_route_ipv6_list (const int max_routes, struct gc_arena *a)
{
  struct route_ipv6_list *ret;
  ALLOC_VAR_ARRAY_CLEAR_GC (ret, struct route_ipv6_list, struct route_ipv6, max_routes, a);
  ret->capacity = max_routes;
  return ret;
}

static const char *
route_string (const struct route_ipv4 *r, struct gc_arena *gc)
{
  struct buffer out = alloc_buf_gc (256, gc);
  buf_printf (&out, "ROUTE network %s netmask %s gateway %s",
	      print_in_addr_t (r->network, 0, gc),
	      print_in_addr_t (r->netmask, 0, gc),
	      print_in_addr_t (r->gateway, 0, gc)
	      );
  if (r->flags & RT_METRIC_DEFINED)
    buf_printf (&out, " metric %d", r->metric);
  return BSTR (&out);
}

static bool
is_route_parm_defined (const char *parm)
{
  if (!parm)
    return false;
  if (!strcmp (parm, "default"))
    return false;
  return true;
}

static void
setenv_route_addr (struct env_set *es, const char *key, const in_addr_t addr, int i)
{
  struct gc_arena gc = gc_new ();
  struct buffer name = alloc_buf_gc (256, &gc);
  if (i >= 0)
    buf_printf (&name, "route_%s_%d", key, i);
  else
    buf_printf (&name, "route_%s", key);
  setenv_str (es, BSTR (&name), print_in_addr_t (addr, 0, &gc));
  gc_free (&gc);
}

static bool
get_special_addr (const struct route_list *rl,
		  const char *string,
		  in_addr_t *out,
		  bool *status)
{
  if (status)
    *status = true;
  if (!strcmp (string, "vpn_gateway"))
    {
      if (rl)
	{
	  if (rl->spec.flags & RTSA_REMOTE_ENDPOINT)
	    *out = rl->spec.remote_endpoint;
	  else
	    {
	      msg (M_INFO, PACKAGE_NAME " ROUTE: vpn_gateway undefined");
	      if (status)
		*status = false;
	    }
	}
      return true;
    }
  else if (!strcmp (string, "net_gateway"))
    {
      if (rl)
	{
	  if (rl->rgi.flags & RGI_ADDR_DEFINED)
	    *out = rl->rgi.gateway.addr;
	  else
	    {
	      msg (M_INFO, PACKAGE_NAME " ROUTE: net_gateway undefined -- unable to get default gateway from system");
	      if (status)
		*status = false;
	    }
	}
      return true;
    }
  else if (!strcmp (string, "remote_host"))
    {
      if (rl)
	{
	  if (rl->spec.flags & RTSA_REMOTE_HOST)
	    *out = rl->spec.remote_host;
	  else
	    {
	      msg (M_INFO, PACKAGE_NAME " ROUTE: remote_host undefined");
	      if (status)
		*status = false;
	    }
	}
      return true;
    }
  return false;
}

bool
is_special_addr (const char *addr_str)
{
  if (addr_str)
    return get_special_addr (NULL, addr_str, NULL, NULL);
  else
    return false;
}

static bool
init_route (struct route_ipv4 *r,
	    struct addrinfo **network_list,
	    const struct route_option *ro,
	    const struct route_list *rl)
{
  const in_addr_t default_netmask = IPV4_NETMASK_HOST;
  bool status;
  int ret;
  struct in_addr special;

  CLEAR (*r);
  r->option = ro;

  /* network */

  if (!is_route_parm_defined (ro->network))
    {
      goto fail;
    }


  /* get_special_addr replaces specialaddr with a special ip addr
     like gw. getaddrinfo is called to convert a a addrinfo struct */

  if(get_special_addr (rl, ro->network, &special.s_addr, &status))
    {
      special.s_addr = htonl(special.s_addr);
      ret = openvpn_getaddrinfo(0, inet_ntoa(special), 0, NULL,
                                AF_INET, network_list);
    }
  else
    ret = openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL,
                              ro->network, 0, NULL, AF_INET, network_list);

  status = (ret == 0);

  if (!status)
    goto fail;

  /* netmask */

  if (is_route_parm_defined (ro->netmask))
    {
      r->netmask = getaddr (
			    GETADDR_HOST_ORDER
			    | GETADDR_WARN_ON_SIGNAL,
			    ro->netmask,
			    0,
			    &status,
			    NULL);
      if (!status)
	goto fail;
    }
  else
    r->netmask = default_netmask;

  /* gateway */

  if (is_route_parm_defined (ro->gateway))
    {
      if (!get_special_addr (rl, ro->gateway, &r->gateway, &status))
	{
	  r->gateway = getaddr (
				GETADDR_RESOLVE
				| GETADDR_HOST_ORDER
				| GETADDR_WARN_ON_SIGNAL,
				ro->gateway,
				0,
				&status,
				NULL);
	}
      if (!status)
	goto fail;
    }
  else
    {
      if (rl->spec.flags & RTSA_REMOTE_ENDPOINT)
	r->gateway = rl->spec.remote_endpoint;
      else
	{
	  msg (M_WARN, PACKAGE_NAME " ROUTE: " PACKAGE_NAME " needs a gateway parameter for a --route option and no default was specified by either --route-gateway or --ifconfig options");
	  goto fail;
	}
    }

  /* metric */

  r->metric = 0;
  if (is_route_parm_defined (ro->metric))
    {
      r->metric = atoi (ro->metric);
      if (r->metric < 0)
	{
	  msg (M_WARN, PACKAGE_NAME " ROUTE: route metric for network %s (%s) must be >= 0",
	       ro->network,
	       ro->metric);
	  goto fail;
	}
      r->flags |= RT_METRIC_DEFINED;
    }
  else if (rl->spec.flags & RTSA_DEFAULT_METRIC)
    {
      r->metric = rl->spec.default_metric;
      r->flags |= RT_METRIC_DEFINED;
    }

  r->flags |= RT_DEFINED;

  return true;

 fail:
  msg (M_WARN, PACKAGE_NAME " ROUTE: failed to parse/resolve route for host/network: %s",
       ro->network);
  return false;
}

static bool
init_route_ipv6 (struct route_ipv6 *r6,
	         const struct route_ipv6_option *r6o,
	         const struct route_ipv6_list *rl6 )
{
  r6->defined = false;

  if ( !get_ipv6_addr( r6o->prefix, &r6->network, &r6->netbits, NULL, M_WARN ))
    goto fail;

  /* gateway */
  if (is_route_parm_defined (r6o->gateway))
    {
      if ( inet_pton( AF_INET6, r6o->gateway, &r6->gateway ) != 1 )
        {
	  msg( M_WARN, PACKAGE_NAME "ROUTE6: cannot parse gateway spec '%s'", r6o->gateway );
        }
    }
  else if (rl6->remote_endpoint_defined)
    {
      r6->gateway = rl6->remote_endpoint_ipv6;
    }
  else
    {
      msg (M_WARN, PACKAGE_NAME " ROUTE6: " PACKAGE_NAME " needs a gateway parameter for a --route-ipv6 option and no default was specified by either --route-ipv6-gateway or --ifconfig-ipv6 options");
      goto fail;
    }

  /* metric */

  r6->metric_defined = false;
  r6->metric = -1;
  if (is_route_parm_defined (r6o->metric))
    {
      r6->metric = atoi (r6o->metric);
      if (r6->metric < 0)
	{
	  msg (M_WARN, PACKAGE_NAME " ROUTE: route metric for network %s (%s) must be >= 0",
	       r6o->prefix,
	       r6o->metric);
	  goto fail;
	}
      r6->metric_defined = true;
    }
  else if (rl6->default_metric_defined)
    {
      r6->metric = rl6->default_metric;
      r6->metric_defined = true;
    }

  r6->defined = true;

  return true;

 fail:
  msg (M_WARN, PACKAGE_NAME " ROUTE: failed to parse/resolve route for host/network: %s",
       r6o->prefix);
  r6->defined = false;
  return false;
}

void
add_route_to_option_list (struct route_option_list *l,
			  const char *network,
			  const char *netmask,
			  const char *gateway,
			  const char *metric)
{
  struct route_option *ro;
  if (l->n >= l->capacity)
    msg (M_FATAL, PACKAGE_NAME " ROUTE: cannot add more than %d routes -- please increase the max-routes option in the client configuration file",
	 l->capacity);
  ro = &l->routes[l->n];
  ro->network = network;
  ro->netmask = netmask;
  ro->gateway = gateway;
  ro->metric = metric;
  ++l->n;
}

void
add_route_ipv6_to_option_list (struct route_ipv6_option_list *l,
			  const char *prefix,
			  const char *gateway,
			  const char *metric)
{
  struct route_ipv6_option *ro;
  if (l->n >= l->capacity)
    msg (M_FATAL, PACKAGE_NAME " ROUTE: cannot add more than %d IPv6 routes -- please increase the max-routes option in the client configuration file",
	 l->capacity);
  ro = &l->routes_ipv6[l->n];
  ro->prefix = prefix;
  ro->gateway = gateway;
  ro->metric = metric;
  ++l->n;
}

void
clear_route_list (struct route_list *rl)
{
  const int capacity = rl->capacity;
  const size_t rl_size = array_mult_safe (sizeof(struct route_ipv4), capacity, sizeof(struct route_list));
  memset(rl, 0, rl_size);
  rl->capacity = capacity;
}

void
clear_route_ipv6_list (struct route_ipv6_list *rl6)
{
  const int capacity = rl6->capacity;
  const size_t rl6_size = array_mult_safe (sizeof(struct route_ipv6), capacity, sizeof(struct route_ipv6_list));
  memset(rl6, 0, rl6_size);
  rl6->capacity = capacity;
}

void
route_list_add_vpn_gateway (struct route_list *rl,
			    struct env_set *es,
			    const in_addr_t addr)
{
  ASSERT(rl);
  rl->spec.remote_endpoint = addr;
  rl->spec.flags |= RTSA_REMOTE_ENDPOINT;
  setenv_route_addr (es, "vpn_gateway", rl->spec.remote_endpoint, -1);
}

static void
add_block_local_item (struct route_list *rl,
		      const struct route_gateway_address *gateway,
		      in_addr_t target)
{
  const int rgi_needed = (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED);
  if ((rl->rgi.flags & rgi_needed) == rgi_needed
      && rl->rgi.gateway.netmask < 0xFFFFFFFF
      && (rl->n)+2 <= rl->capacity)
    {
      struct route_ipv4 r;
      unsigned int l2;

      /* split a route into two smaller blocking routes, and direct them to target */
      CLEAR(r);
      r.flags = RT_DEFINED;
      r.gateway = target;
      r.network = gateway->addr & gateway->netmask;
      l2 = ((~gateway->netmask)+1)>>1;
      r.netmask = ~(l2-1);
      rl->routes[rl->n++] = r;
      r.network += l2;
      rl->routes[rl->n++] = r;
    }
}

static void
add_block_local (struct route_list *rl)
{
  const int rgi_needed = (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED);
  if ((rl->flags & RG_BLOCK_LOCAL)
      && (rl->rgi.flags & rgi_needed) == rgi_needed
      && (rl->spec.flags & RTSA_REMOTE_ENDPOINT)
      && rl->spec.remote_host_local != TLA_LOCAL)
    {
      size_t i;

      /* add bypass for gateway addr */
      add_bypass_address (&rl->spec.bypass, rl->rgi.gateway.addr);

      /* block access to local subnet */
      add_block_local_item (rl, &rl->rgi.gateway, rl->spec.remote_endpoint);

      /* process additional subnets on gateway interface */
      for (i = 0; i < rl->rgi.n_addrs; ++i)
	{
	  const struct route_gateway_address *gwa = &rl->rgi.addrs[i];
	  /* omit the add/subnet in &rl->rgi which we processed above */
	  if (!((rl->rgi.gateway.addr & rl->rgi.gateway.netmask) == (gwa->addr & gwa->netmask)
		&& rl->rgi.gateway.netmask == gwa->netmask))
	    add_block_local_item (rl, gwa, rl->spec.remote_endpoint);
	}
    }
}

bool
init_route_list (struct route_list *rl,
		 const struct route_option_list *opt,
		 const char *remote_endpoint,
		 int default_metric,
		 in_addr_t remote_host,
		 struct env_set *es)
{
  struct gc_arena gc = gc_new ();
  bool ret = true;

  clear_route_list (rl);

  rl->flags = opt->flags;

  if (remote_host)
    {
      rl->spec.remote_host = remote_host;
      rl->spec.flags |= RTSA_REMOTE_HOST;
    }

  if (default_metric)
    {
      rl->spec.default_metric = default_metric;
      rl->spec.flags |= RTSA_DEFAULT_METRIC;
    }

  get_default_gateway (&rl->rgi);
  if (rl->rgi.flags & RGI_ADDR_DEFINED)
    {
      setenv_route_addr (es, "net_gateway", rl->rgi.gateway.addr, -1);
#if defined(ENABLE_DEBUG) && !defined(ENABLE_SMALL)
      print_default_gateway (D_ROUTE, &rl->rgi);
#endif
    }
  else
    {
      dmsg (D_ROUTE, "ROUTE: default_gateway=UNDEF");
    }

  if (rl->spec.flags & RTSA_REMOTE_HOST)
    rl->spec.remote_host_local = test_local_addr (remote_host, &rl->rgi);

  if (is_route_parm_defined (remote_endpoint))
    {
      bool defined = false;
      rl->spec.remote_endpoint = getaddr (
				     GETADDR_RESOLVE
				     | GETADDR_HOST_ORDER
				     | GETADDR_WARN_ON_SIGNAL,
				     remote_endpoint,
				     0,
				     &defined,
				     NULL);

      if (defined)
	{
	  setenv_route_addr (es, "vpn_gateway", rl->spec.remote_endpoint, -1);
	  rl->spec.flags |= RTSA_REMOTE_ENDPOINT;
	}
      else
	{
	  msg (M_WARN, PACKAGE_NAME " ROUTE: failed to parse/resolve default gateway: %s",
	       remote_endpoint);
	  ret = false;
	}
    }

  if (rl->flags & RG_ENABLE)
    {
      add_block_local (rl);
      get_bypass_addresses (&rl->spec.bypass, rl->flags);
#ifdef ENABLE_DEBUG
      print_bypass_addresses (&rl->spec.bypass);
#endif
    }

  /* parse the routes from opt to rl */
  {
    int i = 0;
    int j = rl->n;
    bool warned = false;
    for (i = 0; i < opt->n; ++i)
      {
        struct addrinfo* netlist;
	struct route_ipv4 r;

	if (!init_route (&r,
			 &netlist,
			 &opt->routes[i],
			 rl))
	  ret = false;
	else
	  {
            struct addrinfo* curele;
            for (curele	= netlist; curele; curele = curele->ai_next)
	      {
		if (j < rl->capacity)
		  {
                    r.network = ntohl(((struct sockaddr_in*)(curele)->ai_addr)->sin_addr.s_addr);
		    rl->routes[j++] = r;
		  }
		else
		  {
		    if (!warned)
		      {
			msg (M_WARN, PACKAGE_NAME " ROUTE: routes dropped because number of expanded routes is greater than route list capacity (%d)", rl->capacity);
			warned = true;
		      }
		  }
	      }
            freeaddrinfo(netlist);
	  }
      }
    rl->n = j;
  }

  gc_free (&gc);
  return ret;
}

bool
init_route_ipv6_list (struct route_ipv6_list *rl6,
		 const struct route_ipv6_option_list *opt6,
		 const char *remote_endpoint,
		 int default_metric,
		 struct env_set *es)
{
  struct gc_arena gc = gc_new ();
  bool ret = true;

  clear_route_ipv6_list (rl6);

  rl6->flags = opt6->flags;

  if (default_metric >= 0 )
    {
      rl6->default_metric = default_metric;
      rl6->default_metric_defined = true;
    }

  /* "default_gateway" is stuff for "redirect-gateway", which we don't
   * do for IPv6 yet -> TODO
   */
    {
      dmsg (D_ROUTE, "ROUTE6: default_gateway=UNDEF");
    }

  if ( is_route_parm_defined( remote_endpoint ))
    {
      if ( inet_pton( AF_INET6, remote_endpoint, 
			&rl6->remote_endpoint_ipv6) == 1 )
        {
	  rl6->remote_endpoint_defined = true;
        }
      else
	{
	  msg (M_WARN, PACKAGE_NAME " ROUTE: failed to parse/resolve default gateway: %s", remote_endpoint);
          ret = false;
	}
    }
  else
    rl6->remote_endpoint_defined = false;


  if (!(opt6->n >= 0 && opt6->n <= rl6->capacity))
    msg (M_FATAL, PACKAGE_NAME " ROUTE6: (init) number of route options (%d) is greater than route list capacity (%d)", opt6->n, rl6->capacity);

  /* parse the routes from opt to rl6 */
  {
    int i, j = 0;
    for (i = 0; i < opt6->n; ++i)
      {
	if (!init_route_ipv6 (&rl6->routes_ipv6[j],
			      &opt6->routes_ipv6[i],
			      rl6 ))
	  ret = false;
	else
	  ++j;
      }
    rl6->n = j;
  }

  gc_free (&gc);
  return ret;
}

static void
add_route3 (in_addr_t network,
	    in_addr_t netmask,
	    in_addr_t gateway,
	    const struct tuntap *tt,
	    unsigned int flags,
	    const struct route_gateway_info *rgi,
	    const struct env_set *es)
{
  struct route_ipv4 r;
  CLEAR (r);
  r.flags = RT_DEFINED;
  r.network = network;
  r.netmask = netmask;
  r.gateway = gateway;
  add_route (&r, tt, flags, rgi, es);
}

static void
del_route3 (in_addr_t network,
	    in_addr_t netmask,
	    in_addr_t gateway,
	    const struct tuntap *tt,
	    unsigned int flags,
	    const struct route_gateway_info *rgi,
	    const struct env_set *es)
{
  struct route_ipv4 r;
  CLEAR (r);
  r.flags = RT_DEFINED|RT_ADDED;
  r.network = network;
  r.netmask = netmask;
  r.gateway = gateway;
  delete_route (&r, tt, flags, rgi, es);
}

static void
add_bypass_routes (struct route_bypass *rb,
		   in_addr_t gateway,
		   const struct tuntap *tt,
		   unsigned int flags,
		   const struct route_gateway_info *rgi,
		   const struct env_set *es)
{
  int i;
  for (i = 0; i < rb->n_bypass; ++i)
    {
      if (rb->bypass[i])
	add_route3 (rb->bypass[i],
		    IPV4_NETMASK_HOST,
		    gateway,
		    tt,
		    flags | ROUTE_REF_GW,
		    rgi,
		    es);
    }
}

static void
del_bypass_routes (struct route_bypass *rb,
		   in_addr_t gateway,
		   const struct tuntap *tt,
		   unsigned int flags,
		   const struct route_gateway_info *rgi,
		   const struct env_set *es)
{
  int i;
  for (i = 0; i < rb->n_bypass; ++i)
    {
      if (rb->bypass[i])
	del_route3 (rb->bypass[i],
		    IPV4_NETMASK_HOST,
		    gateway,
		    tt,
		    flags | ROUTE_REF_GW,
		    rgi,
		    es);
    }
}

static void
redirect_default_route_to_vpn (struct route_list *rl, const struct tuntap *tt, unsigned int flags, const struct env_set *es)
{
  const char err[] = "NOTE: unable to redirect default gateway --";

  if ( rl && rl->flags & RG_ENABLE )
    {
      if (!(rl->spec.flags & RTSA_REMOTE_ENDPOINT))
	{
	  msg (M_WARN, "%s VPN gateway parameter (--route-gateway or --ifconfig) is missing", err);
	}
      else if (!(rl->rgi.flags & RGI_ADDR_DEFINED))
	{
	  msg (M_WARN, "%s Cannot read current default gateway from system", err);
	}
      else if (!(rl->spec.flags & RTSA_REMOTE_HOST))
	{
	  msg (M_WARN, "%s Cannot obtain current remote host address", err);
	}
      else
	{
	  bool local = BOOL_CAST(rl->flags & RG_LOCAL);
	  if (rl->flags & RG_AUTO_LOCAL) {
	    const int tla = rl->spec.remote_host_local;
	    if (tla == TLA_NONLOCAL)
	      {
		dmsg (D_ROUTE, "ROUTE remote_host is NOT LOCAL");
		local = false;
	      }
	    else if (tla == TLA_LOCAL)
	      {
		dmsg (D_ROUTE, "ROUTE remote_host is LOCAL");
		local = true;
	      }
	  }
	  if (!local)
	    {
	      /* route remote host to original default gateway */
	      /* if remote_host is not ipv4 (ie: ipv6), just skip
	       * adding this special /32 route */
	      if (rl->spec.remote_host != IPV4_INVALID_ADDR) {
		add_route3 (rl->spec.remote_host,
			    IPV4_NETMASK_HOST,
			    rl->rgi.gateway.addr,
			    tt,
			    flags | ROUTE_REF_GW,
			    &rl->rgi,
			    es);
		rl->iflags |= RL_DID_LOCAL;
	      } else {
		dmsg (D_ROUTE, "ROUTE remote_host protocol differs from tunneled");
	      }
	    }

	  /* route DHCP/DNS server traffic through original default gateway */
	  add_bypass_routes (&rl->spec.bypass, rl->rgi.gateway.addr, tt, flags, &rl->rgi, es);

	  if (rl->flags & RG_REROUTE_GW)
	    {
	      if (rl->flags & RG_DEF1)
		{
		  /* add new default route (1st component) */
		  add_route3 (0x00000000,
			      0x80000000,
			      rl->spec.remote_endpoint,
			      tt,
			      flags,
			      &rl->rgi,
			      es);

		  /* add new default route (2nd component) */
		  add_route3 (0x80000000,
			      0x80000000,
			      rl->spec.remote_endpoint,
			      tt,
			      flags,
			      &rl->rgi,
			      es);
		}
	      else
		{
		  /* delete default route */
		  del_route3 (0,
			      0,
			      rl->rgi.gateway.addr,
			      tt,
			      flags | ROUTE_REF_GW,
			      &rl->rgi,
			      es);

		  /* add new default route */
		  add_route3 (0,
			      0,
			      rl->spec.remote_endpoint,
			      tt,
			      flags,
			      &rl->rgi,
			      es);
		}
	    }

	  /* set a flag so we can undo later */
	  rl->iflags |= RL_DID_REDIRECT_DEFAULT_GATEWAY;
	}
    }
}

static void
undo_redirect_default_route_to_vpn (struct route_list *rl, const struct tuntap *tt, unsigned int flags, const struct env_set *es)
{
  if ( rl && rl->iflags & RL_DID_REDIRECT_DEFAULT_GATEWAY )
    {
      /* delete remote host route */
      if (rl->iflags & RL_DID_LOCAL)
	{
	  del_route3 (rl->spec.remote_host,
		      IPV4_NETMASK_HOST,
		      rl->rgi.gateway.addr,
		      tt,
		      flags | ROUTE_REF_GW,
		      &rl->rgi,
		      es);
	  rl->iflags &= ~RL_DID_LOCAL;
	}

      /* delete special DHCP/DNS bypass route */
      del_bypass_routes (&rl->spec.bypass, rl->rgi.gateway.addr, tt, flags, &rl->rgi, es);

      if (rl->flags & RG_REROUTE_GW)
	{
	  if (rl->flags & RG_DEF1)
	    {
	      /* delete default route (1st component) */
	      del_route3 (0x00000000,
			  0x80000000,
			  rl->spec.remote_endpoint,
			  tt,
			  flags,
			  &rl->rgi,
			  es);

	      /* delete default route (2nd component) */
	      del_route3 (0x80000000,
			  0x80000000,
			  rl->spec.remote_endpoint,
			  tt,
			  flags,
			  &rl->rgi,
			  es);
	    }
	  else
	    {
	      /* delete default route */
	      del_route3 (0,
			  0,
			  rl->spec.remote_endpoint,
			  tt,
			  flags,
			  &rl->rgi,
			  es);

	      /* restore original default route */
	      add_route3 (0,
			  0,
			  rl->rgi.gateway.addr,
			  tt,
			  flags | ROUTE_REF_GW,
			  &rl->rgi,
			  es);
	    }
	}

      rl->iflags &= ~RL_DID_REDIRECT_DEFAULT_GATEWAY;
    }
}

void
add_routes (struct route_list *rl, struct route_ipv6_list *rl6, const struct tuntap *tt, unsigned int flags, const struct env_set *es)
{
  redirect_default_route_to_vpn (rl, tt, flags, es);
  if ( rl && !(rl->iflags & RL_ROUTES_ADDED) )
    {
      int i;

#ifdef ENABLE_MANAGEMENT
      if (management && rl->n)
	{
	  management_set_state (management,
				OPENVPN_STATE_ADD_ROUTES,
				NULL,
				0,
				0);
	}
#endif
      
      for (i = 0; i < rl->n; ++i)
	{
	  struct route_ipv4 *r = &rl->routes[i];
	  check_subnet_conflict (r->network, r->netmask, "route");
	  if (flags & ROUTE_DELETE_FIRST)
	    delete_route (r, tt, flags, &rl->rgi, es);
	  add_route (r, tt, flags, &rl->rgi, es);
	}
      rl->iflags |= RL_ROUTES_ADDED;
    }
  if (rl6 && !rl6->routes_added)
    {
      int i;

      for (i = 0; i < rl6->n; ++i)
	{
	  struct route_ipv6 *r = &rl6->routes_ipv6[i];
	  if (flags & ROUTE_DELETE_FIRST)
	    delete_route_ipv6 (r, tt, flags, es);
	  add_route_ipv6 (r, tt, flags, es);
	}
      rl6->routes_added = true;
    }
}

void
delete_routes (struct route_list *rl, struct route_ipv6_list *rl6,
	       const struct tuntap *tt, unsigned int flags, const struct env_set *es)
{
  if ( rl && rl->iflags & RL_ROUTES_ADDED )
    {
      int i;
      for (i = rl->n - 1; i >= 0; --i)
	{
	  struct route_ipv4 * r = &rl->routes[i];
	  delete_route (r, tt, flags, &rl->rgi, es);
	}
      rl->iflags &= ~RL_ROUTES_ADDED;
    }

   undo_redirect_default_route_to_vpn (rl, tt, flags, es);

  if ( rl )
    {
      clear_route_list (rl);
    }

  if ( rl6 && rl6->routes_added )
    {
      int i;
      for (i = rl6->n - 1; i >= 0; --i)
	{
	  const struct route_ipv6 *r6 = &rl6->routes_ipv6[i];
	  delete_route_ipv6 (r6, tt, flags, es);
	}
      rl6->routes_added = false;
    }

  if ( rl6 )
    {
      clear_route_ipv6_list (rl6);
    }
}

#ifndef ENABLE_SMALL

static const char *
show_opt (const char *option)
{
  if (!option)
    return "nil";
  else
    return option;
}

static void
print_route_option (const struct route_option *ro, int level)
{
  msg (level, "  route %s/%s/%s/%s",
       show_opt (ro->network),
       show_opt (ro->netmask),
       show_opt (ro->gateway),
       show_opt (ro->metric));
}

void
print_route_options (const struct route_option_list *rol,
		     int level)
{
  int i;
  if (rol->flags & RG_ENABLE)
    msg (level, "  [redirect_default_gateway local=%d]",
	 (rol->flags & RG_LOCAL) != 0);
  for (i = 0; i < rol->n; ++i)
    print_route_option (&rol->routes[i], level);
}

void
print_default_gateway(const int msglevel, const struct route_gateway_info *rgi)
{
  struct gc_arena gc = gc_new ();
  if (rgi->flags & RGI_ADDR_DEFINED)
    {
      struct buffer out = alloc_buf_gc (256, &gc);
      buf_printf (&out, "ROUTE_GATEWAY");
      if (rgi->flags & RGI_ON_LINK)
	buf_printf (&out, " ON_LINK");
      else
	buf_printf (&out, " %s", print_in_addr_t (rgi->gateway.addr, 0, &gc));
      if (rgi->flags & RGI_NETMASK_DEFINED)
	buf_printf (&out, "/%s", print_in_addr_t (rgi->gateway.netmask, 0, &gc));
#ifdef WIN32
      if (rgi->flags & RGI_IFACE_DEFINED)
	buf_printf (&out, " I=%u", (unsigned int)rgi->adapter_index);
#else
      if (rgi->flags & RGI_IFACE_DEFINED)
	buf_printf (&out, " IFACE=%s", rgi->iface);
#endif
      if (rgi->flags & RGI_HWADDR_DEFINED)
	buf_printf (&out, " HWADDR=%s", format_hex_ex (rgi->hwaddr, 6, 0, 1, ":", &gc));
      msg (msglevel, "%s", BSTR (&out));
    }
  gc_free (&gc);
}

#endif

static void
print_route (const struct route_ipv4 *r, int level)
{
  struct gc_arena gc = gc_new ();
  if (r->flags & RT_DEFINED)
    msg (level, "%s", route_string (r, &gc));
  gc_free (&gc);
}

void
print_routes (const struct route_list *rl, int level)
{
  int i;
  for (i = 0; i < rl->n; ++i)
    print_route (&rl->routes[i], level);
}

static void
setenv_route (struct env_set *es, const struct route_ipv4 *r, int i)
{
  struct gc_arena gc = gc_new ();
  if (r->flags & RT_DEFINED)
    {
      setenv_route_addr (es, "network", r->network, i);
      setenv_route_addr (es, "netmask", r->netmask, i);
      setenv_route_addr (es, "gateway", r->gateway, i);

      if (r->flags & RT_METRIC_DEFINED)
	{
	  struct buffer name = alloc_buf_gc (256, &gc);
	  buf_printf (&name, "route_metric_%d", i);
	  setenv_int (es, BSTR (&name), r->metric);
	}
    }
  gc_free (&gc);
}

void
setenv_routes (struct env_set *es, const struct route_list *rl)
{
  int i;
  for (i = 0; i < rl->n; ++i)
    setenv_route (es, &rl->routes[i], i + 1);
}

static void
setenv_route_ipv6 (struct env_set *es, const struct route_ipv6 *r6, int i)
{
  struct gc_arena gc = gc_new ();
  if (r6->defined)
    {
      struct buffer name1 = alloc_buf_gc( 256, &gc );
      struct buffer val = alloc_buf_gc( 256, &gc );
      struct buffer name2 = alloc_buf_gc( 256, &gc );

      buf_printf( &name1, "route_ipv6_network_%d", i );
      buf_printf( &val, "%s/%d", print_in6_addr( r6->network, 0, &gc ),
				 r6->netbits );
      setenv_str( es, BSTR(&name1), BSTR(&val) );

      buf_printf( &name2, "route_ipv6_gateway_%d", i );
      setenv_str( es, BSTR(&name2), print_in6_addr( r6->gateway, 0, &gc ));
    }
  gc_free (&gc);
}
void
setenv_routes_ipv6 (struct env_set *es, const struct route_ipv6_list *rl6)
{
  int i;
  for (i = 0; i < rl6->n; ++i)
    setenv_route_ipv6 (es, &rl6->routes_ipv6[i], i + 1);
}

/*
 * local_route() determines whether the gateway of a provided host
 * route is on the same interface that owns the default gateway.
 * It uses the data structure
 * returned by get_default_gateway() (struct route_gateway_info)
 * to determine this.  If the route is local, LR_MATCH is returned.
 * When adding routes into the kernel, if LR_MATCH is defined for
 * a given route, the route should explicitly reference the default
 * gateway interface as the route destination.  For example, here
 * is an example on Linux that uses LR_MATCH:
 *
 *   route add -net 10.10.0.1 netmask 255.255.255.255 dev eth0
 *
 * This capability is needed by the "default-gateway block-local"
 * directive, to allow client access to the local subnet to be
 * blocked but still allow access to the local default gateway.
 */

/* local_route() return values */
#define LR_NOMATCH 0 /* route is not local */
#define LR_MATCH   1 /* route is local */
#define LR_ERROR   2 /* caller should abort adding route */

static int
local_route (in_addr_t network,
	     in_addr_t netmask,
	     in_addr_t gateway,
	     const struct route_gateway_info *rgi)
{
  /* set LR_MATCH on local host routes */
  const int rgi_needed = (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED|RGI_IFACE_DEFINED);
  if (rgi
      && (rgi->flags & rgi_needed) == rgi_needed
      && gateway == rgi->gateway.addr
      && netmask == 0xFFFFFFFF)
    {
      if (((network ^  rgi->gateway.addr) & rgi->gateway.netmask) == 0)
	return LR_MATCH;
      else
	{
	  /* examine additional subnets on gateway interface */
	  size_t i;
	  for (i = 0; i < rgi->n_addrs; ++i)
	    {
	      const struct route_gateway_address *gwa = &rgi->addrs[i];
	      if (((network ^ gwa->addr) & gwa->netmask) == 0)
		return LR_MATCH;
	    }
	}
    }
    return LR_NOMATCH;
}

/* Return true if the "on-link" form of the route should be used.  This is when the gateway for a
   a route is specified as an interface rather than an address. */
static inline bool
is_on_link (const int is_local_route, const unsigned int flags, const struct route_gateway_info *rgi)
{
  return rgi && (is_local_route == LR_MATCH || ((flags & ROUTE_REF_GW) && (rgi->flags & RGI_ON_LINK)));
}

void
add_route (struct route_ipv4 *r,
	   const struct tuntap *tt,
	   unsigned int flags,
	   const struct route_gateway_info *rgi, /* may be NULL */
	   const struct env_set *es)
{
  struct gc_arena gc;
  struct argv argv;
  const char *network;
  const char *netmask;
  const char *gateway;
  bool status = false;
  int is_local_route;

  if (!(r->flags & RT_DEFINED))
    return;

  gc_init (&gc);
  argv_init (&argv);

  network = print_in_addr_t (r->network, 0, &gc);
  netmask = print_in_addr_t (r->netmask, 0, &gc);
  gateway = print_in_addr_t (r->gateway, 0, &gc);

  is_local_route = local_route(r->network, r->netmask, r->gateway, rgi);
  if (is_local_route == LR_ERROR)
    goto done;

#if defined(TARGET_LINUX)
#ifdef ENABLE_IPROUTE
  /* FIXME -- add on-link support for ENABLE_IPROUTE */
  argv_printf (&argv, "%s route add %s/%d via %s",
  	      iproute_path,
	      network,
	      count_netmask_bits(netmask),
	      gateway);
  if (r->flags & RT_METRIC_DEFINED)
    argv_printf_cat (&argv, "metric %d", r->metric);

#else
  argv_printf (&argv, "%s add -net %s netmask %s",
	       ROUTE_PATH,
	       network,
	       netmask);
  if (r->flags & RT_METRIC_DEFINED)
    argv_printf_cat (&argv, "metric %d", r->metric);
  if (is_on_link (is_local_route, flags, rgi))
    argv_printf_cat (&argv, "dev %s", rgi->iface);
  else
    argv_printf_cat (&argv, "gw %s", gateway);

#endif  /*ENABLE_IPROUTE*/
  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: Linux route add command failed");

#elif defined (WIN32)
  {
    DWORD ai = TUN_ADAPTER_INDEX_INVALID;
    argv_printf (&argv, "%s%sc ADD %s MASK %s %s",
		 get_win_sys_path(),
		 WIN_ROUTE_PATH_SUFFIX,
		 network,
		 netmask,
		 gateway);
    if (r->flags & RT_METRIC_DEFINED)
      argv_printf_cat (&argv, "METRIC %d", r->metric);
    if (is_on_link (is_local_route, flags, rgi))
      {
	ai = rgi->adapter_index;
	argv_printf_cat (&argv, "IF %u", (unsigned int)ai);
      }

    argv_msg (D_ROUTE, &argv);

    if ((flags & ROUTE_METHOD_MASK) == ROUTE_METHOD_IPAPI)
      {
	status = add_route_ipapi (r, tt, ai);
	msg (D_ROUTE, "Route addition via IPAPI %s", status ? "succeeded" : "failed");
      }
    else if ((flags & ROUTE_METHOD_MASK) == ROUTE_METHOD_EXE)
      {
	netcmd_semaphore_lock ();
	status = openvpn_execve_check (&argv, es, 0, "ERROR: Windows route add command failed");
	netcmd_semaphore_release ();
      }
    else if ((flags & ROUTE_METHOD_MASK) == ROUTE_METHOD_ADAPTIVE)
      {
	status = add_route_ipapi (r, tt, ai);
	msg (D_ROUTE, "Route addition via IPAPI %s [adaptive]", status ? "succeeded" : "failed");
	if (!status)
	  {
	    msg (D_ROUTE, "Route addition fallback to route.exe");
	    netcmd_semaphore_lock ();
	    status = openvpn_execve_check (&argv, es, 0, "ERROR: Windows route add command failed [adaptive]");
	    netcmd_semaphore_release ();
	  }
      }
    else
      {
	ASSERT (0);
      }
  }

#elif defined (TARGET_SOLARIS)

  /* example: route add 192.0.2.32 -netmask 255.255.255.224 somegateway */

  argv_printf (&argv, "%s add",
		ROUTE_PATH);

  argv_printf_cat (&argv, "%s -netmask %s %s",
	      network,
	      netmask,
	      gateway);

  /* Solaris can only distinguish between "metric 0" == "on-link on the
   * interface where the IP address given is configured" and "metric > 0"
   * == "use gateway specified" (no finer-grained route metrics available)
   *
   * More recent versions of Solaris can also do "-interface", but that
   * would break backwards compatibility with older versions for no gain.
   */
  if (r->flags & RT_METRIC_DEFINED )
    argv_printf_cat (&argv, "%d", r->metric);

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: Solaris route add command failed");

#elif defined(TARGET_FREEBSD)

  argv_printf (&argv, "%s add",
		ROUTE_PATH);

#if 0
  if (r->flags & RT_METRIC_DEFINED)
    argv_printf_cat (&argv, "-rtt %d", r->metric);
#endif

  argv_printf_cat (&argv, "-net %s %s %s",
	      network,
	      gateway,
	      netmask);

  /* FIXME -- add on-link support for FreeBSD */

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: FreeBSD route add command failed");

#elif defined(TARGET_DRAGONFLY)

  argv_printf (&argv, "%s add",
		ROUTE_PATH);

#if 0
  if (r->flags & RT_METRIC_DEFINED)
    argv_printf_cat (&argv, "-rtt %d", r->metric);
#endif

  argv_printf_cat (&argv, "-net %s %s %s",
	      network,
	      gateway,
	      netmask);

  /* FIXME -- add on-link support for Dragonfly */

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: DragonFly route add command failed");

#elif defined(TARGET_DARWIN)

  argv_printf (&argv, "%s add",
		ROUTE_PATH);

#if 0
  if (r->flags & RT_METRIC_DEFINED)
    argv_printf_cat (&argv, "-rtt %d", r->metric);
#endif

  if (is_on_link (is_local_route, flags, rgi))
    {
      /* Mac OS X route syntax for ON_LINK:
	 route add -cloning -net 10.10.0.1 -netmask 255.255.255.255 -interface en0 */
      argv_printf_cat (&argv, "-cloning -net %s -netmask %s -interface %s",
		       network,
		       netmask,
		       rgi->iface);
    }
  else
    {
      argv_printf_cat (&argv, "-net %s %s %s",
		       network,
		       gateway,
		       netmask);
    }

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: OS X route add command failed");

#elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD)

  argv_printf (&argv, "%s add",
		ROUTE_PATH);

#if 0
  if (r->flags & RT_METRIC_DEFINED)
    argv_printf_cat (&argv, "-rtt %d", r->metric);
#endif

  argv_printf_cat (&argv, "-net %s %s -netmask %s",
	      network,
	      gateway,
	      netmask);

  /* FIXME -- add on-link support for OpenBSD/NetBSD */

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: OpenBSD/NetBSD route add command failed");

#else
  msg (M_FATAL, "Sorry, but I don't know how to do 'route' commands on this operating system.  Try putting your routes in a --route-up script");
#endif

 done:
  if (status)
    r->flags |= RT_ADDED;
  else
    r->flags &= ~RT_ADDED;
  argv_reset (&argv);
  gc_free (&gc);
}


static const char * 
print_in6_addr_netbits_only( struct in6_addr network_copy, int netbits, 
                             struct gc_arena * gc)
{
  /* clear host bit parts of route 
   * (needed if routes are specified improperly, or if we need to 
   * explicitely setup/clear the "connected" network routes on some OSes)
   */
  int byte = 15;
  int bits_to_clear = 128 - netbits;

  while( byte >= 0 && bits_to_clear > 0 )
    {
      if ( bits_to_clear >= 8 )
	{ network_copy.s6_addr[byte--] = 0; bits_to_clear -= 8; }
      else
	{ network_copy.s6_addr[byte--] &= (0xff << bits_to_clear); bits_to_clear = 0; }
    }

  return print_in6_addr( network_copy, 0, gc);
}

void
add_route_ipv6 (struct route_ipv6 *r6, const struct tuntap *tt, unsigned int flags, const struct env_set *es)
{
  struct gc_arena gc;
  struct argv argv;

  const char *network;
  const char *gateway;
  bool status = false;
  const char *device = tt->actual_name;

  bool gateway_needed = false;

  if (!r6->defined)
    return;

  gc_init (&gc);
  argv_init (&argv);

  network = print_in6_addr_netbits_only( r6->network, r6->netbits, &gc);
  gateway = print_in6_addr( r6->gateway, 0, &gc);

  if ( !tt->ipv6 )
    {
      msg( M_INFO, "add_route_ipv6(): not adding %s/%d, no IPv6 on if %s",
		    network, r6->netbits, device );
      return;
    }

  msg( M_INFO, "add_route_ipv6(%s/%d -> %s metric %d) dev %s",
		network, r6->netbits, gateway, r6->metric, device );

  /*
   * Filter out routes which are essentially no-ops
   * (not currently done for IPv6)
   */

  /* On "tun" interface, we never set a gateway if the operating system
   * can do "route to interface" - it does not add value, as the target
   * dev already fully qualifies the route destination on point-to-point
   * interfaces.   OTOH, on "tap" interface, we must always set the
   * gateway unless the route is to be an on-link network
   */
  if ( tt->type == DEV_TYPE_TAP &&
                  !(r6->metric_defined && r6->metric == 0 ) )
    {
      gateway_needed = true;
    }

#if defined(TARGET_LINUX)
#ifdef ENABLE_IPROUTE
  argv_printf (&argv, "%s -6 route add %s/%d dev %s",
  	      iproute_path,
	      network,
	      r6->netbits,
	      device);
  if (gateway_needed)
    argv_printf_cat (&argv, "via %s", gateway);
  if (r6->metric_defined && r6->metric > 0 )
    argv_printf_cat (&argv, " metric %d", r6->metric);

#else
  argv_printf (&argv, "%s -A inet6 add %s/%d dev %s",
		ROUTE_PATH,
	      network,
	      r6->netbits,
	      device);
  if (gateway_needed)
    argv_printf_cat (&argv, "gw %s", gateway);
  if (r6->metric_defined && r6->metric > 0 )
    argv_printf_cat (&argv, " metric %d", r6->metric);
#endif  /*ENABLE_IPROUTE*/
  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: Linux route -6/-A inet6 add command failed");

#elif defined (WIN32)

  /* netsh interface ipv6 add route 2001:db8::/32 MyTunDevice */
  argv_printf (&argv, "%s%sc interface ipv6 add route %s/%d %s",
	       get_win_sys_path(),
	       NETSH_PATH_SUFFIX,
	       network,
	       r6->netbits,
	       device);

  /* next-hop depends on TUN or TAP mode:
   * - in TAP mode, we use the "real" next-hop
   * - in TUN mode we use a special-case link-local address that the tapdrvr
   *   knows about and will answer ND (neighbor discovery) packets for
   */
  if ( tt->type == DEV_TYPE_TUN )
	argv_printf_cat( &argv, " %s", "fe80::8" );
  else
	argv_printf_cat( &argv, " %s", gateway );

#if 0
  if (r->metric_defined)
    argv_printf_cat (&argv, " METRIC %d", r->metric);
#endif

  /* in some versions of Windows, routes are persistent across reboots by
   * default, unless "store=active" is set (pointed out by Tony Lim, thanks)
   */
  argv_printf_cat( &argv, " store=active" );

  argv_msg (D_ROUTE, &argv);

  netcmd_semaphore_lock ();
  status = openvpn_execve_check (&argv, es, 0, "ERROR: Windows route add ipv6 command failed");
  netcmd_semaphore_release ();

#elif defined (TARGET_SOLARIS)

  /* example: route add -inet6 2001:db8::/32 somegateway 0 */

  /* for some weird reason, this does not work for me unless I set
   * "metric 0" - otherwise, the routes will be nicely installed, but
   * packets will just disappear somewhere.  So we use "0" now...
   */

  argv_printf (&argv, "%s add -inet6 %s/%d %s 0",
		ROUTE_PATH,
		network,
		r6->netbits,
		gateway );

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: Solaris route add -inet6 command failed");

#elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY)

  argv_printf (&argv, "%s add -inet6 %s/%d",
		ROUTE_PATH,
	        network,
	        r6->netbits);

  if (gateway_needed)
    argv_printf_cat (&argv, "%s", gateway);
  else
    argv_printf_cat (&argv, "-iface %s", device);

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: *BSD route add -inet6 command failed");

#elif defined(TARGET_DARWIN) 

  argv_printf (&argv, "%s add -inet6 %s -prefixlen %d",
		ROUTE_PATH,
	        network, r6->netbits );

  if (gateway_needed)
    argv_printf_cat (&argv, "%s", gateway);
  else
    argv_printf_cat (&argv, "-iface %s", device);

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: MacOS X route add -inet6 command failed");

#elif defined(TARGET_OPENBSD)

  argv_printf (&argv, "%s add -inet6 %s -prefixlen %d %s",
		ROUTE_PATH,
	        network, r6->netbits, gateway );

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: OpenBSD route add -inet6 command failed");

#elif defined(TARGET_NETBSD)

  argv_printf (&argv, "%s add -inet6 %s/%d %s",
		ROUTE_PATH,
	        network, r6->netbits, gateway );

  argv_msg (D_ROUTE, &argv);
  status = openvpn_execve_check (&argv, es, 0, "ERROR: NetBSD route add -inet6 command failed");

#else
  msg (M_FATAL, "Sorry, but I don't know how to do 'route ipv6' commands on this operating system.  Try putting your routes in a --route-up script");
#endif

  r6->defined = status;
  argv_reset (&argv);
  gc_free (&gc);
}

static void
delete_route (struct route_ipv4 *r,
	      const struct tuntap *tt,
	      unsigned int flags,
	      const struct route_gateway_info *rgi,
	      const struct env_set *es)
{
  struct gc_arena gc;
  struct argv argv;
  const char *network;
  const char *netmask;
  const char *gateway;
  int is_local_route;

  if ((r->flags & (RT_DEFINED|RT_ADDED)) != (RT_DEFINED|RT_ADDED))
    return;

  gc_init (&gc);
  argv_init (&argv);

  network = print_in_addr_t (r->network, 0, &gc);
  netmask = print_in_addr_t (r->netmask, 0, &gc);
  gateway = print_in_addr_t (r->gateway, 0, &gc);

  is_local_route = local_route(r->network, r->netmask, r->gateway, rgi);
  if (is_local_route == LR_ERROR)
    goto done;

#if defined(TARGET_LINUX)
#ifdef ENABLE_IPROUTE
  argv_printf (&argv, "%s route del %s/%d",
  	      iproute_path,
	      network,
	      count_netmask_bits(netmask));
#else
  argv_printf (&argv, "%s del -net %s netmask %s",
	       ROUTE_PATH,
	       network,
	       netmask);
#endif /*ENABLE_IPROUTE*/
  if (r->flags & RT_METRIC_DEFINED)
    argv_printf_cat (&argv, "metric %d", r->metric);
  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: Linux route delete command failed");

#elif defined (WIN32)
  
  argv_printf (&argv, "%s%sc DELETE %s MASK %s %s",
	       get_win_sys_path(),
	       WIN_ROUTE_PATH_SUFFIX,
	       network,
	       netmask,
	       gateway);

  argv_msg (D_ROUTE, &argv);

  if ((flags & ROUTE_METHOD_MASK) == ROUTE_METHOD_IPAPI)
    {
      const bool status = del_route_ipapi (r, tt);
      msg (D_ROUTE, "Route deletion via IPAPI %s", status ? "succeeded" : "failed");
    }
  else if ((flags & ROUTE_METHOD_MASK) == ROUTE_METHOD_EXE)
    {
      netcmd_semaphore_lock ();
      openvpn_execve_check (&argv, es, 0, "ERROR: Windows route delete command failed");
      netcmd_semaphore_release ();
    }
  else if ((flags & ROUTE_METHOD_MASK) == ROUTE_METHOD_ADAPTIVE)
    {
      const bool status = del_route_ipapi (r, tt);
      msg (D_ROUTE, "Route deletion via IPAPI %s [adaptive]", status ? "succeeded" : "failed");
      if (!status)
	{
	  msg (D_ROUTE, "Route deletion fallback to route.exe");
	  netcmd_semaphore_lock ();
	  openvpn_execve_check (&argv, es, 0, "ERROR: Windows route delete command failed [adaptive]");
	  netcmd_semaphore_release ();
	}
    }
  else
    {
      ASSERT (0);
    }

#elif defined (TARGET_SOLARIS)

  argv_printf (&argv, "%s delete %s -netmask %s %s",
		ROUTE_PATH,
	      network,
	      netmask,
	      gateway);

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: Solaris route delete command failed");

#elif defined(TARGET_FREEBSD)

  argv_printf (&argv, "%s delete -net %s %s %s",
		ROUTE_PATH,
	      network,
	      gateway,
	      netmask);

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: FreeBSD route delete command failed");

#elif defined(TARGET_DRAGONFLY)

  argv_printf (&argv, "%s delete -net %s %s %s",
		ROUTE_PATH,
	      network,
	      gateway,
	      netmask);

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: DragonFly route delete command failed");

#elif defined(TARGET_DARWIN)

  if (is_on_link (is_local_route, flags, rgi))
    {
      argv_printf (&argv, "%s delete -cloning -net %s -netmask %s -interface %s",
		   ROUTE_PATH,
		   network,
		   netmask,
		   rgi->iface);
    }
  else
    {
      argv_printf (&argv, "%s delete -net %s %s %s",
		   ROUTE_PATH,
		   network,
		   gateway,
		   netmask);
    }

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: OS X route delete command failed");

#elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD)

  argv_printf (&argv, "%s delete -net %s %s -netmask %s",
		ROUTE_PATH,
	      network,
	      gateway,
	      netmask);

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: OpenBSD/NetBSD route delete command failed");

#else
  msg (M_FATAL, "Sorry, but I don't know how to do 'route' commands on this operating system.  Try putting your routes in a --route-up script");
#endif

 done:
  r->flags &= ~RT_ADDED;
  argv_reset (&argv);
  gc_free (&gc);
}

void
delete_route_ipv6 (const struct route_ipv6 *r6, const struct tuntap *tt, unsigned int flags, const struct env_set *es)
{
  struct gc_arena gc;
  struct argv argv;
  const char *network;
  const char *gateway;
  const char *device = tt->actual_name;
  bool gateway_needed = false;

  if (!r6->defined)
    return;

  gc_init (&gc);
  argv_init (&argv);

  network = print_in6_addr_netbits_only( r6->network, r6->netbits, &gc);
  gateway = print_in6_addr( r6->gateway, 0, &gc);

  if ( !tt->ipv6 )
    {
      msg( M_INFO, "delete_route_ipv6(): not deleting %s/%d, no IPv6 on if %s",
		    network, r6->netbits, device );
      return;
    }

  msg( M_INFO, "delete_route_ipv6(%s/%d)", network, r6->netbits );

  /* if we used a gateway on "add route", we also need to specify it on
   * delete, otherwise some OSes will refuse to delete the route
   */
  if ( tt->type == DEV_TYPE_TAP &&
                  !(r6->metric_defined && r6->metric == 0 ) )
    {
      gateway_needed = true;
    }


#if defined(TARGET_LINUX)
#ifdef ENABLE_IPROUTE
  argv_printf (&argv, "%s -6 route del %s/%d dev %s",
  	      iproute_path,
	      network,
	      r6->netbits,
	      device);
  if (gateway_needed)
    argv_printf_cat (&argv, "via %s", gateway);
#else
  argv_printf (&argv, "%s -A inet6 del %s/%d dev %s",
		ROUTE_PATH,
	      network,
	      r6->netbits,
	      device);
  if (gateway_needed)
    argv_printf_cat (&argv, "gw %s", gateway);
  if (r6->metric_defined && r6->metric > 0 )
    argv_printf_cat (&argv, " metric %d", r6->metric);
#endif  /*ENABLE_IPROUTE*/
  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: Linux route -6/-A inet6 del command failed");

#elif defined (WIN32)

  /* netsh interface ipv6 delete route 2001:db8::/32 MyTunDevice */
  argv_printf (&argv, "%s%sc interface ipv6 delete route %s/%d %s",
	       get_win_sys_path(),
	       NETSH_PATH_SUFFIX,
	       network,
	       r6->netbits,
	       device);

  /* next-hop depends on TUN or TAP mode:
   * - in TAP mode, we use the "real" next-hop
   * - in TUN mode we use a special-case link-local address that the tapdrvr
   *   knows about and will answer ND (neighbor discovery) packets for
   * (and "route deletion without specifying next-hop" does not work...)
   */
  if ( tt->type == DEV_TYPE_TUN )
	argv_printf_cat( &argv, " %s", "fe80::8" );
  else
	argv_printf_cat( &argv, " %s", gateway );

#if 0
  if (r->metric_defined)
    argv_printf_cat (&argv, "METRIC %d", r->metric);
#endif

  /* Windows XP to 7 "just delete" routes, wherever they came from, but
   * in Windows 8(.1?), if you create them with "store=active", this is
   * how you should delete them as well (pointed out by Cedric Tabary)
   */
  argv_printf_cat( &argv, " store=active" );

  argv_msg (D_ROUTE, &argv);

  netcmd_semaphore_lock ();
  openvpn_execve_check (&argv, es, 0, "ERROR: Windows route delete ipv6 command failed");
  netcmd_semaphore_release ();

#elif defined (TARGET_SOLARIS)

  /* example: route delete -inet6 2001:db8::/32 somegateway */
  /* GERT-TODO: this is untested, but should work */

  argv_printf (&argv, "%s delete -inet6 %s/%d %s",
		ROUTE_PATH,
		network,
		r6->netbits,
		gateway );

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: Solaris route delete -inet6 command failed");

#elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY)

  argv_printf (&argv, "%s delete -inet6 %s/%d",
		ROUTE_PATH,
	        network,
	        r6->netbits );

  if (gateway_needed)
    argv_printf_cat (&argv, "%s", gateway);
  else
    argv_printf_cat (&argv, "-iface %s", device);

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: *BSD route delete -inet6 command failed");

#elif defined(TARGET_DARWIN) 

  argv_printf (&argv, "%s delete -inet6 %s -prefixlen %d",
		ROUTE_PATH, 
		network, r6->netbits );

  if (gateway_needed)
    argv_printf_cat (&argv, "%s", gateway);
  else
    argv_printf_cat (&argv, "-iface %s", device);

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: MacOS X route delete -inet6 command failed");

#elif defined(TARGET_OPENBSD)

  argv_printf (&argv, "%s delete -inet6 %s -prefixlen %d %s",
		ROUTE_PATH,
	        network, r6->netbits, gateway );

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: OpenBSD route delete -inet6 command failed");

#elif defined(TARGET_NETBSD)

  argv_printf (&argv, "%s delete -inet6 %s/%d %s",
		ROUTE_PATH,
	        network, r6->netbits, gateway );

  argv_msg (D_ROUTE, &argv);
  openvpn_execve_check (&argv, es, 0, "ERROR: NetBSD route delete -inet6 command failed");

#else
  msg (M_FATAL, "Sorry, but I don't know how to do 'route ipv6' commands on this operating system.  Try putting your routes in a --route-down script");
#endif

  argv_reset (&argv);
  gc_free (&gc);
}

/*
 * The --redirect-gateway option requires OS-specific code below
 * to get the current default gateway.
 */

#if defined(WIN32)

static const MIB_IPFORWARDTABLE *
get_windows_routing_table (struct gc_arena *gc)
{
  ULONG size = 0;
  PMIB_IPFORWARDTABLE rt = NULL;
  DWORD status;

  status = GetIpForwardTable (NULL, &size, TRUE);
  if (status == ERROR_INSUFFICIENT_BUFFER)
    {
      rt = (PMIB_IPFORWARDTABLE) gc_malloc (size, false, gc);
      status = GetIpForwardTable (rt, &size, TRUE);
      if (status != NO_ERROR)
	{
	  msg (D_ROUTE, "NOTE: GetIpForwardTable returned error: %s (code=%u)",
	       strerror_win32 (status, gc),
	       (unsigned int)status);
	  rt = NULL;
	}
    }
  return rt;
}

static int
test_route (const IP_ADAPTER_INFO *adapters,
	    const in_addr_t gateway,
	    DWORD *index)
{
  int count = 0;
  DWORD i = adapter_index_of_ip (adapters, gateway, &count, NULL);
  if (index)
    *index = i;
  return count;
}

static void
test_route_helper (bool *ret,
		   int *count,
		   int *good,
		   int *ambig,
		   const IP_ADAPTER_INFO *adapters,
		   const in_addr_t gateway)
{
  int c;

  ++*count;
  c = test_route (adapters, gateway, NULL);
  if (c == 0)
    *ret = false;
  else
    ++*good;
  if (c > 1)
    ++*ambig;
}

/*
 * If we tried to add routes now, would we succeed?
 */
bool
test_routes (const struct route_list *rl, const struct tuntap *tt)
{
  struct gc_arena gc = gc_new ();
  const IP_ADAPTER_INFO *adapters = get_adapter_info_list (&gc);
  bool ret = false;
  int count = 0;
  int good = 0;
  int ambig = 0;
  bool adapter_up = false;

  if (is_adapter_up (tt, adapters))
    {
      ret = true;
      adapter_up = true;

      if (rl)
	{
	  int i;
	  for (i = 0; i < rl->n; ++i)
	    test_route_helper (&ret, &count, &good, &ambig, adapters, rl->routes[i].gateway);

	  if ((rl->flags & RG_ENABLE) && (rl->spec.flags & RTSA_REMOTE_ENDPOINT))
	    test_route_helper (&ret, &count, &good, &ambig, adapters, rl->spec.remote_endpoint);
	}
    }

  msg (D_ROUTE, "TEST ROUTES: %d/%d succeeded len=%d ret=%d a=%d u/d=%s",
       good,
       count,
       rl ? rl->n : -1,
       (int)ret,
       ambig,
       adapter_up ? "up" : "down");

  gc_free (&gc);
  return ret;
}

static const MIB_IPFORWARDROW *
get_default_gateway_row (const MIB_IPFORWARDTABLE *routes)
{
  struct gc_arena gc = gc_new ();
  DWORD lowest_metric = MAXDWORD;
  const MIB_IPFORWARDROW *ret = NULL;
  int i;
  int best = -1;

  if (routes)
    {
      for (i = 0; i < routes->dwNumEntries; ++i)
	{
	  const MIB_IPFORWARDROW *row = &routes->table[i];
	  const in_addr_t net = ntohl (row->dwForwardDest);
	  const in_addr_t mask = ntohl (row->dwForwardMask);
	  const DWORD index = row->dwForwardIfIndex;
	  const DWORD metric = row->dwForwardMetric1;

	  dmsg (D_ROUTE_DEBUG, "GDGR: route[%d] %s/%s i=%d m=%d",
		i,
		print_in_addr_t ((in_addr_t) net, 0, &gc),
		print_in_addr_t ((in_addr_t) mask, 0, &gc),
		(int)index,
		(int)metric);

	  if (!net && !mask && metric < lowest_metric)
	    {
	      ret = row;
	      lowest_metric = metric;
	      best = i;
	    }
	}
    }

  dmsg (D_ROUTE_DEBUG, "GDGR: best=%d lm=%u", best, (unsigned int)lowest_metric);

  gc_free (&gc);
  return ret;
}

void
get_default_gateway (struct route_gateway_info *rgi)
{
  struct gc_arena gc = gc_new ();

  const IP_ADAPTER_INFO *adapters = get_adapter_info_list (&gc);
  const MIB_IPFORWARDTABLE *routes = get_windows_routing_table (&gc);
  const MIB_IPFORWARDROW *row = get_default_gateway_row (routes);
  DWORD a_index;
  const IP_ADAPTER_INFO *ai;

  CLEAR(*rgi);

  if (row)
    {
      rgi->gateway.addr = ntohl (row->dwForwardNextHop);
      if (rgi->gateway.addr)
	{
	  rgi->flags |= RGI_ADDR_DEFINED;
	  a_index = adapter_index_of_ip (adapters, rgi->gateway.addr, NULL, &rgi->gateway.netmask);
	  if (a_index != TUN_ADAPTER_INDEX_INVALID)
	    {
	      rgi->adapter_index = a_index;
	      rgi->flags |= (RGI_IFACE_DEFINED|RGI_NETMASK_DEFINED);
	      ai = get_adapter (adapters, a_index);
	      if (ai)
		{
		  memcpy (rgi->hwaddr, ai->Address, 6);
		  rgi->flags |= RGI_HWADDR_DEFINED;
		}
	    }
	}
    }

  gc_free (&gc);
}

static DWORD
windows_route_find_if_index (const struct route_ipv4 *r, const struct tuntap *tt)
{
  struct gc_arena gc = gc_new ();
  DWORD ret = TUN_ADAPTER_INDEX_INVALID;
  int count = 0;
  const IP_ADAPTER_INFO *adapters = get_adapter_info_list (&gc);
  const IP_ADAPTER_INFO *tun_adapter = get_tun_adapter (tt, adapters);
  bool on_tun = false;

  /* first test on tun interface */
  if (is_ip_in_adapter_subnet (tun_adapter, r->gateway, NULL))
    {
      ret = tun_adapter->Index;
      count = 1;
      on_tun = true;
    }
  else /* test on other interfaces */
    {
      count = test_route (adapters, r->gateway, &ret);
    }

  if (count == 0)
    {
      msg (M_WARN, "Warning: route gateway is not reachable on any active network adapters: %s",
	   print_in_addr_t (r->gateway, 0, &gc));
      ret = TUN_ADAPTER_INDEX_INVALID;
    }
  else if (count > 1)
    {
      msg (M_WARN, "Warning: route gateway is ambiguous: %s (%d matches)",
	   print_in_addr_t (r->gateway, 0, &gc),
	   count);
      ret = TUN_ADAPTER_INDEX_INVALID;
    }

  dmsg (D_ROUTE_DEBUG, "DEBUG: route find if: on_tun=%d count=%d index=%d",
       on_tun,
       count,
       (int)ret);

  gc_free (&gc);
  return ret;
}

bool
add_route_ipapi (const struct route_ipv4 *r, const struct tuntap *tt, DWORD adapter_index)
{
  struct gc_arena gc = gc_new ();
  bool ret = false;
  DWORD status;
  const DWORD if_index = (adapter_index == TUN_ADAPTER_INDEX_INVALID) ? windows_route_find_if_index (r, tt) : adapter_index;

  if (if_index != TUN_ADAPTER_INDEX_INVALID)
    {
      MIB_IPFORWARDROW fr;
      CLEAR (fr);
      fr.dwForwardDest = htonl (r->network);
      fr.dwForwardMask = htonl (r->netmask);
      fr.dwForwardPolicy = 0;
      fr.dwForwardNextHop = htonl (r->gateway);
      fr.dwForwardIfIndex = if_index;
      fr.dwForwardType = 4;  /* the next hop is not the final dest */
      fr.dwForwardProto = 3; /* PROTO_IP_NETMGMT */
      fr.dwForwardAge = 0;
      fr.dwForwardNextHopAS = 0;
      fr.dwForwardMetric1 = (r->flags & RT_METRIC_DEFINED) ? r->metric : 1;
      fr.dwForwardMetric2 = METRIC_NOT_USED;
      fr.dwForwardMetric3 = METRIC_NOT_USED;
      fr.dwForwardMetric4 = METRIC_NOT_USED;
      fr.dwForwardMetric5 = METRIC_NOT_USED;

      if ((r->network & r->netmask) != r->network)
	msg (M_WARN, "Warning: address %s is not a network address in relation to netmask %s",
	     print_in_addr_t (r->network, 0, &gc),
	     print_in_addr_t (r->netmask, 0, &gc));

      status = CreateIpForwardEntry (&fr);

      if (status == NO_ERROR)
	ret = true;
      else
	{
	  /* failed, try increasing the metric to work around Vista issue */
	  const unsigned int forward_metric_limit = 2048; /* iteratively retry higher metrics up to this limit */

	  for ( ; fr.dwForwardMetric1 <= forward_metric_limit; ++fr.dwForwardMetric1)
	    {
	      /* try a different forward type=3 ("the next hop is the final dest") in addition to 4.
		 --redirect-gateway over RRAS seems to need this. */
	      for (fr.dwForwardType = 4; fr.dwForwardType >= 3; --fr.dwForwardType)
		{
		  status = CreateIpForwardEntry (&fr);
		  if (status == NO_ERROR)
		    {
		      msg (D_ROUTE, "ROUTE: CreateIpForwardEntry succeeded with dwForwardMetric1=%u and dwForwardType=%u",
			   (unsigned int)fr.dwForwardMetric1,
			   (unsigned int)fr.dwForwardType);
		      ret = true;
		      goto doublebreak;
		    }
		  else if (status != ERROR_BAD_ARGUMENTS)
		    goto doublebreak;
		}
	    }

	doublebreak:
	  if (status != NO_ERROR)
	    msg (M_WARN, "ROUTE: route addition failed using CreateIpForwardEntry: %s [status=%u if_index=%u]",
		 strerror_win32 (status, &gc),
		 (unsigned int)status,
		 (unsigned int)if_index);
	}
    }

  gc_free (&gc);
  return ret;
}

bool
del_route_ipapi (const struct route_ipv4 *r, const struct tuntap *tt)
{
  struct gc_arena gc = gc_new ();
  bool ret = false;
  DWORD status;
  const DWORD if_index = windows_route_find_if_index (r, tt);

  if (if_index != TUN_ADAPTER_INDEX_INVALID)
    {
      MIB_IPFORWARDROW fr;
      CLEAR (fr);

      fr.dwForwardDest = htonl (r->network);
      fr.dwForwardMask = htonl (r->netmask);
      fr.dwForwardPolicy = 0;
      fr.dwForwardNextHop = htonl (r->gateway);
      fr.dwForwardIfIndex = if_index;

      status = DeleteIpForwardEntry (&fr);

      if (status == NO_ERROR)
	ret = true;
      else
	msg (M_WARN, "ROUTE: route deletion failed using DeleteIpForwardEntry: %s",
	     strerror_win32 (status, &gc));
    }

  gc_free (&gc);
  return ret;
}

static const char *
format_route_entry (const MIB_IPFORWARDROW *r, struct gc_arena *gc)
{
  struct buffer out = alloc_buf_gc (256, gc);
  buf_printf (&out, "%s %s %s p=%d i=%d t=%d pr=%d a=%d h=%d m=%d/%d/%d/%d/%d", 
	      print_in_addr_t (r->dwForwardDest, IA_NET_ORDER, gc),
	      print_in_addr_t (r->dwForwardMask, IA_NET_ORDER, gc),
	      print_in_addr_t (r->dwForwardNextHop, IA_NET_ORDER, gc),
	      (int)r->dwForwardPolicy,
	      (int)r->dwForwardIfIndex,
	      (int)r->dwForwardType,
	      (int)r->dwForwardProto,
	      (int)r->dwForwardAge,
	      (int)r->dwForwardNextHopAS,
	      (int)r->dwForwardMetric1,
	      (int)r->dwForwardMetric2,
	      (int)r->dwForwardMetric3,
	      (int)r->dwForwardMetric4,
	      (int)r->dwForwardMetric5);
  return BSTR (&out);
}

/*
 * Show current routing table
 */
void
show_routes (int msglev)
{
  struct gc_arena gc = gc_new ();
  int i;

  const MIB_IPFORWARDTABLE *rt = get_windows_routing_table (&gc);

  msg (msglev, "SYSTEM ROUTING TABLE");
  if (rt)
    {
      for (i = 0; i < rt->dwNumEntries; ++i)
	{
	  msg (msglev, "%s", format_route_entry (&rt->table[i], &gc));
	}
    }
  gc_free (&gc);
}

#elif defined(TARGET_LINUX)

void
get_default_gateway (struct route_gateway_info *rgi)
{
  struct gc_arena gc = gc_new ();
  int sd = -1;
  char best_name[16];
  best_name[0] = 0;

  CLEAR(*rgi);

  /* get default gateway IP addr */
  {
    FILE *fp = fopen ("/proc/net/route", "r");
    if (fp)
      {
	char line[256];
	int count = 0;
	unsigned int lowest_metric = UINT_MAX;
	in_addr_t best_gw = 0;
	bool found = false;
	while (fgets (line, sizeof (line), fp) != NULL)
	  {
	    if (count)
	      {
		unsigned int net_x = 0;
		unsigned int mask_x = 0;
		unsigned int gw_x = 0;
		unsigned int metric = 0;
		unsigned int flags = 0;
		char name[16];
		name[0] = 0;
		const int np = sscanf (line, "%15s\t%x\t%x\t%x\t%*s\t%*s\t%d\t%x",
				       name,
				       &net_x,
				       &gw_x,
				       &flags,
				       &metric,
				       &mask_x);
		if (np == 6 && (flags & IFF_UP))
		  {
		    const in_addr_t net = ntohl (net_x);
		    const in_addr_t mask = ntohl (mask_x);
		    const in_addr_t gw = ntohl (gw_x);

		    if (!net && !mask && metric < lowest_metric)
		      {
			found = true;
			best_gw = gw;
			strcpy (best_name, name);
			lowest_metric = metric;
		      }
		  }
	      }
	    ++count;
	  }
	fclose (fp);

	if (found)
	  {
	    rgi->gateway.addr = best_gw;
	    rgi->flags |= RGI_ADDR_DEFINED;
	    if (!rgi->gateway.addr && best_name[0])
	      rgi->flags |= RGI_ON_LINK;
	  }
      }
  }

  /* scan adapter list */
  if (rgi->flags & RGI_ADDR_DEFINED)
    {
      struct ifreq *ifr, *ifend;
      in_addr_t addr, netmask;
      struct ifreq ifreq;
      struct ifconf ifc;
      struct ifreq ifs[20]; /* Maximum number of interfaces to scan */

      if ((sd = socket (AF_INET, SOCK_DGRAM, 0)) < 0)
	{
	  msg (M_WARN, "GDG: socket() failed");
	  goto done;
	}
      ifc.ifc_len = sizeof (ifs);
      ifc.ifc_req = ifs;
      if (ioctl (sd, SIOCGIFCONF, &ifc) < 0)
	{
	  msg (M_WARN, "GDG: ioctl(SIOCGIFCONF) failed");
	  goto done;
	}

      /* scan through interface list */
      ifend = ifs + (ifc.ifc_len / sizeof (struct ifreq));
      for (ifr = ifc.ifc_req; ifr < ifend; ifr++)
	{
	  if (ifr->ifr_addr.sa_family == AF_INET)
	    {
	      /* get interface addr */
	      addr = ntohl(((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr);

	      /* get interface name */
	      strncpynt (ifreq.ifr_name, ifr->ifr_name, sizeof (ifreq.ifr_name));

	      /* check that the interface is up */
	      if (ioctl (sd, SIOCGIFFLAGS, &ifreq) < 0)
		continue;
	      if (!(ifreq.ifr_flags & IFF_UP))
		continue;

	      if (rgi->flags & RGI_ON_LINK)
		{
		  /* check that interface name of current interface
		     matches interface name of best default route */
		  if (strcmp(ifreq.ifr_name, best_name))
		    continue;
#if 0
		  /* if point-to-point link, use remote addr as route gateway */
		  if ((ifreq.ifr_flags & IFF_POINTOPOINT) && ioctl (sd, SIOCGIFDSTADDR, &ifreq) >= 0)
		    {
		      rgi->gateway.addr = ntohl(((struct sockaddr_in *) &ifreq.ifr_addr)->sin_addr.s_addr);
		      if (rgi->gateway.addr)
			rgi->flags &= ~RGI_ON_LINK;
		    }
#endif
		}
	      else
		{
		  /* get interface netmask */
		  if (ioctl (sd, SIOCGIFNETMASK, &ifreq) < 0)
		    continue;
		  netmask = ntohl(((struct sockaddr_in *) &ifreq.ifr_addr)->sin_addr.s_addr);

		  /* check that interface matches default route */
		  if (((rgi->gateway.addr ^ addr) & netmask) != 0)
		    continue;

		  /* save netmask */
		  rgi->gateway.netmask = netmask;
		  rgi->flags |= RGI_NETMASK_DEFINED;
		}

	      /* save iface name */
	      strncpynt (rgi->iface, ifreq.ifr_name, sizeof(rgi->iface));
	      rgi->flags |= RGI_IFACE_DEFINED;

	      /* now get the hardware address. */
	      memset (&ifreq.ifr_hwaddr, 0, sizeof (struct sockaddr));
	      if (ioctl (sd, SIOCGIFHWADDR, &ifreq) < 0)
		{
		  msg (M_WARN, "GDG: SIOCGIFHWADDR(%s) failed", ifreq.ifr_name);
		  goto done;
		}
	      memcpy (rgi->hwaddr, &ifreq.ifr_hwaddr.sa_data, 6);
	      rgi->flags |= RGI_HWADDR_DEFINED;

	      break;
	    }
	}
    }

 done:
  if (sd >= 0)
    close (sd);
  gc_free (&gc);
}

#elif defined(TARGET_FREEBSD)||defined(TARGET_DRAGONFLY)

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/route.h>

struct {
  struct rt_msghdr m_rtm;
  char       m_space[512];
} m_rtmsg;

#define ROUNDUP(a) \
        ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))

/*
 * FIXME -- add support for netmask, hwaddr, and iface
 */
void
get_default_gateway (struct route_gateway_info *rgi)
{
  struct gc_arena gc = gc_new ();
  int s, seq, l, pid, rtm_addrs, i;
  struct sockaddr so_dst, so_mask;
  char *cp = m_rtmsg.m_space; 
  struct sockaddr *gate = NULL, *sa;
  struct  rt_msghdr *rtm_aux;

#define NEXTADDR(w, u) \
        if (rtm_addrs & (w)) {\
            l = ROUNDUP(u.sa_len); memmove(cp, &(u), l); cp += l;\
        }

#define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))

#define rtm m_rtmsg.m_rtm

  CLEAR(*rgi);

  pid = getpid();
  seq = 0;
  rtm_addrs = RTA_DST | RTA_NETMASK;

  bzero(&so_dst, sizeof(so_dst));
  bzero(&so_mask, sizeof(so_mask));
  bzero(&rtm, sizeof(struct rt_msghdr));

  rtm.rtm_type = RTM_GET;
  rtm.rtm_flags = RTF_UP | RTF_GATEWAY;
  rtm.rtm_version = RTM_VERSION;
  rtm.rtm_seq = ++seq;
  rtm.rtm_addrs = rtm_addrs; 

  so_dst.sa_family = AF_INET;
  so_dst.sa_len = sizeof(struct sockaddr_in);
  so_mask.sa_family = AF_INET;
  so_mask.sa_len = sizeof(struct sockaddr_in);

  NEXTADDR(RTA_DST, so_dst);
  NEXTADDR(RTA_NETMASK, so_mask);

  rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;

  s = socket(PF_ROUTE, SOCK_RAW, 0);

  if (write(s, (char *)&m_rtmsg, l) < 0)
    {
      msg(M_WARN|M_ERRNO, "Could not retrieve default gateway from route socket:");
      gc_free (&gc);
      close(s);
      return;
    }

  do {
    l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
  } while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid));
                        
  close(s);

  rtm_aux = &rtm;

  cp = ((char *)(rtm_aux + 1));
  if (rtm_aux->rtm_addrs) {
    for (i = 1; i; i <<= 1)
      if (i & rtm_aux->rtm_addrs) {
	sa = (struct sockaddr *)cp;
	if (i == RTA_GATEWAY )
	  gate = sa;
	ADVANCE(cp, sa);
      }
  }
  else
    {
      gc_free (&gc);
      return;
    }


  if (gate != NULL )
    {
      rgi->gateway.addr = ntohl(((struct sockaddr_in *)gate)->sin_addr.s_addr);
      rgi->flags |= RGI_ADDR_DEFINED;

      gc_free (&gc);
    }
  else
    {
      gc_free (&gc);
    }
}

#elif defined(TARGET_DARWIN)

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/route.h>
#include <net/if_dl.h>

struct rtmsg {
  struct rt_msghdr m_rtm;
  char       m_space[512];
};

#define ROUNDUP(a) \
        ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t))

#define NEXTADDR(w, u) \
        if (rtm_addrs & (w)) {\
            l = ROUNDUP(u.sa_len); memmove(cp, &(u), l); cp += l;\
        }

#define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))

#define max(a,b) ((a) > (b) ? (a) : (b))

void
get_default_gateway (struct route_gateway_info *rgi)
{
  struct gc_arena gc = gc_new ();
  struct rtmsg m_rtmsg;
  int sockfd = -1;
  int seq, l, pid, rtm_addrs, i;
  struct sockaddr so_dst, so_mask;
  char *cp = m_rtmsg.m_space; 
  struct sockaddr *gate = NULL, *ifp = NULL, *sa;
  struct  rt_msghdr *rtm_aux;

# define rtm m_rtmsg.m_rtm

  CLEAR(*rgi);

  /* setup data to send to routing socket */
  pid = getpid();
  seq = 0;
  rtm_addrs = RTA_DST | RTA_NETMASK | RTA_IFP;

  bzero(&m_rtmsg, sizeof(m_rtmsg));
  bzero(&so_dst, sizeof(so_dst));
  bzero(&so_mask, sizeof(so_mask));
  bzero(&rtm, sizeof(struct rt_msghdr));

  rtm.rtm_type = RTM_GET;
  rtm.rtm_flags = RTF_UP | RTF_GATEWAY;
  rtm.rtm_version = RTM_VERSION;
  rtm.rtm_seq = ++seq;
  rtm.rtm_addrs = rtm_addrs; 

  so_dst.sa_family = AF_INET;
  so_dst.sa_len = sizeof(struct sockaddr_in);
  so_mask.sa_family = AF_INET;
  so_mask.sa_len = sizeof(struct sockaddr_in);

  NEXTADDR(RTA_DST, so_dst);
  NEXTADDR(RTA_NETMASK, so_mask);

  rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;

  /* transact with routing socket */
  sockfd = socket(PF_ROUTE, SOCK_RAW, 0);
  if (sockfd < 0)
    {
      msg (M_WARN, "GDG: socket #1 failed");
      goto done;
    }
  if (write(sockfd, (char *)&m_rtmsg, l) < 0)
    {
      msg (M_WARN, "GDG: problem writing to routing socket");
      goto done;
    }
  do {
    l = read(sockfd, (char *)&m_rtmsg, sizeof(m_rtmsg));
  } while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid));
  close(sockfd);
  sockfd = -1;

  /* extract return data from routing socket */
  rtm_aux = &rtm;
  cp = ((char *)(rtm_aux + 1));
  if (rtm_aux->rtm_addrs)
    {
      for (i = 1; i; i <<= 1)
	{
	  if (i & rtm_aux->rtm_addrs)
	    {
	      sa = (struct sockaddr *)cp;
	      if (i == RTA_GATEWAY )
		gate = sa;
	      else if (i == RTA_IFP)
		ifp = sa;
	      ADVANCE(cp, sa);
	    }
	}
    }
  else
    goto done;

  /* get gateway addr and interface name */
  if (gate != NULL )
    {
      /* get default gateway addr */
      rgi->gateway.addr = ntohl(((struct sockaddr_in *)gate)->sin_addr.s_addr);
      if (rgi->gateway.addr)
	  rgi->flags |= RGI_ADDR_DEFINED;

      if (ifp)
	{
	  /* get interface name */
	  const struct sockaddr_dl *adl = (struct sockaddr_dl *) ifp;
	  int len = adl->sdl_nlen;
	  if (adl->sdl_nlen && adl->sdl_nlen < sizeof(rgi->iface))
	    {
	      memcpy (rgi->iface, adl->sdl_data, adl->sdl_nlen);
	      rgi->iface[adl->sdl_nlen] = '\0';
	      rgi->flags |= RGI_IFACE_DEFINED;
	    }
	}
    }

  /* get netmask of interface that owns default gateway */
  if (rgi->flags & RGI_IFACE_DEFINED) {
    struct ifreq ifr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
      {
	msg (M_WARN, "GDG: socket #2 failed");
	goto done;
      }

    CLEAR(ifr);
    ifr.ifr_addr.sa_family = AF_INET;
    strncpynt(ifr.ifr_name, rgi->iface, IFNAMSIZ);

    if (ioctl(sockfd, SIOCGIFNETMASK, (char *)&ifr) < 0)
      {
	msg (M_WARN, "GDG: ioctl #1 failed");
	goto done;
      }
    close(sockfd);
    sockfd = -1;

    rgi->gateway.netmask = ntohl(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr);
    rgi->flags |= RGI_NETMASK_DEFINED;
  }

  /* try to read MAC addr associated with interface that owns default gateway */
  if (rgi->flags & RGI_IFACE_DEFINED)
    {
      struct ifconf ifc;
      struct ifreq *ifr;
      const int bufsize = 4096;
      char *buffer;

      buffer = (char *) gc_malloc (bufsize, true, &gc);
      sockfd = socket(AF_INET, SOCK_DGRAM, 0);
      if (sockfd < 0)
	{
	  msg (M_WARN, "GDG: socket #3 failed");
	  goto done;
	}

      ifc.ifc_len = bufsize;
      ifc.ifc_buf = buffer;

      if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)
	{
	  msg (M_WARN, "GDG: ioctl #2 failed");
	  goto done;
	}
      close(sockfd);
      sockfd = -1;

      for (cp = buffer; cp <= buffer + ifc.ifc_len - sizeof(struct ifreq); )
	{
	  ifr = (struct ifreq *)cp;
	  const size_t len = sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
	  if (!ifr->ifr_addr.sa_family)
	    break;
	  if (!strncmp(ifr->ifr_name, rgi->iface, IFNAMSIZ))
	    {
	      if (ifr->ifr_addr.sa_family == AF_LINK)
		{
		  struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
		  memcpy(rgi->hwaddr, LLADDR(sdl), 6);
		  rgi->flags |= RGI_HWADDR_DEFINED;
		}
	    }
	  cp += len;
	}
    }

 done:
  if (sockfd >= 0)
    close(sockfd);
  gc_free (&gc);
}

#undef max

#elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD)

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/route.h>

struct {
  struct rt_msghdr m_rtm;
  char       m_space[512];
} m_rtmsg;

#define ROUNDUP(a) \
        ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))

/*
 * FIXME -- add support for netmask, hwaddr, and iface
 */
void
get_default_gateway (struct route_gateway_info *rgi)
{
  struct gc_arena gc = gc_new ();
  int s, seq, l, rtm_addrs, i;
  pid_t pid;
  struct sockaddr so_dst, so_mask;
  char *cp = m_rtmsg.m_space; 
  struct sockaddr *gate = NULL, *sa;
  struct  rt_msghdr *rtm_aux;

#define NEXTADDR(w, u) \
        if (rtm_addrs & (w)) {\
            l = ROUNDUP(u.sa_len); memmove(cp, &(u), l); cp += l;\
        }

#define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))

#define rtm m_rtmsg.m_rtm

  CLEAR(*rgi);

  pid = getpid();
  seq = 0;
  rtm_addrs = RTA_DST | RTA_NETMASK;

  bzero(&so_dst, sizeof(so_dst));
  bzero(&so_mask, sizeof(so_mask));
  bzero(&rtm, sizeof(struct rt_msghdr));

  rtm.rtm_type = RTM_GET;
  rtm.rtm_flags = RTF_UP | RTF_GATEWAY;
  rtm.rtm_version = RTM_VERSION;
  rtm.rtm_seq = ++seq;
  rtm.rtm_addrs = rtm_addrs; 

  so_dst.sa_family = AF_INET;
  so_dst.sa_len = sizeof(struct sockaddr_in);
  so_mask.sa_family = AF_INET;
  so_mask.sa_len = sizeof(struct sockaddr_in);

  NEXTADDR(RTA_DST, so_dst);
  NEXTADDR(RTA_NETMASK, so_mask);

  rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;

  s = socket(PF_ROUTE, SOCK_RAW, 0);

  if (write(s, (char *)&m_rtmsg, l) < 0)
    {
      msg(M_WARN|M_ERRNO, "Could not retrieve default gateway from route socket:");
      gc_free (&gc);
      close(s);
      return;
    }

  do {
    l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
  } while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid));
                        
  close(s);

  rtm_aux = &rtm;

  cp = ((char *)(rtm_aux + 1));
  if (rtm_aux->rtm_addrs) {
    for (i = 1; i; i <<= 1)
      if (i & rtm_aux->rtm_addrs) {
	sa = (struct sockaddr *)cp;
	if (i == RTA_GATEWAY )
	  gate = sa;
	ADVANCE(cp, sa);
      }
  }
  else
    {
      gc_free (&gc);
      return;
    }


  if (gate != NULL )
    {
      rgi->gateway.addr = ntohl(((struct sockaddr_in *)gate)->sin_addr.s_addr);
      rgi->flags |= RGI_ADDR_DEFINED;

      gc_free (&gc);
    }
  else
    {
      gc_free (&gc);
    }
}

#else

/*
 * This is a platform-specific method that returns data about
 * the current default gateway.  Return data is placed into
 * a struct route_gateway_info object provided by caller.  The
 * implementation should CLEAR the structure before adding
 * data to it.
 *
 * Data returned includes:
 * 1. default gateway address (rgi->gateway.addr)
 * 2. netmask of interface that owns default gateway
 *    (rgi->gateway.netmask)
 * 3. hardware address (i.e. MAC address) of interface that owns
 *    default gateway (rgi->hwaddr)
 * 4. interface name (or adapter index on Windows) that owns default
 *    gateway (rgi->iface or rgi->adapter_index)
 * 5. an array of additional address/netmask pairs defined by
 *    interface that owns default gateway (rgi->addrs with length
 *    given in rgi->n_addrs)
 *
 * The flags RGI_x_DEFINED may be used to indicate which of the data
 * members were successfully returned (set in rgi->flags).  All of
 * the data members are optional, however certain OpenVPN functionality
 * may be disabled by missing items.
 */
void
get_default_gateway (struct route_gateway_info *rgi)
{
  CLEAR(*rgi);
}

#endif

bool
netmask_to_netbits (const in_addr_t network, const in_addr_t netmask, int *netbits)
{
  int i;
  const int addrlen = sizeof (in_addr_t) * 8;

  if ((network & netmask) == network)
    {
      for (i = 0; i <= addrlen; ++i)
	{
	  in_addr_t mask = netbits_to_netmask (i);
	  if (mask == netmask)
	    {
	      if (i == addrlen)
		*netbits = -1;
	      else
		*netbits = i;
	      return true;
	    }
	}
    }
  return false;
}

/*
 * get_bypass_addresses() is used by the redirect-gateway bypass-x
 * functions to build a route bypass to selected DHCP/DNS servers,
 * so that outgoing packets to these servers don't end up in the tunnel.
 */

#if defined(WIN32)

static void
add_host_route_if_nonlocal (struct route_bypass *rb, const in_addr_t addr)
{
  if (test_local_addr(addr, NULL) == TLA_NONLOCAL && addr != 0 && addr != IPV4_NETMASK_HOST)
    add_bypass_address (rb, addr);
}

static void
add_host_route_array (struct route_bypass *rb, const IP_ADDR_STRING *iplist)
{
  while (iplist)
    {
      bool succeed = false;
      const in_addr_t ip = getaddr (GETADDR_HOST_ORDER, iplist->IpAddress.String, 0, &succeed, NULL);
      if (succeed)
	{
	  add_host_route_if_nonlocal (rb, ip);
	}
      iplist = iplist->Next;
    }
}

static void
get_bypass_addresses (struct route_bypass *rb, const unsigned int flags)
{
  struct gc_arena gc = gc_new ();
  /*bool ret_bool = false;*/

  /* get full routing table */
  const MIB_IPFORWARDTABLE *routes = get_windows_routing_table (&gc);

  /* get the route which represents the default gateway */
  const MIB_IPFORWARDROW *row = get_default_gateway_row (routes);

  if (row)
    {
      /* get the adapter which the default gateway is associated with */
      const IP_ADAPTER_INFO *dgi = get_adapter_info (row->dwForwardIfIndex, &gc);

      /* get extra adapter info, such as DNS addresses */
      const IP_PER_ADAPTER_INFO *pai = get_per_adapter_info (row->dwForwardIfIndex, &gc);

      /* Bypass DHCP server address */
      if ((flags & RG_BYPASS_DHCP) && dgi && dgi->DhcpEnabled)
	add_host_route_array (rb, &dgi->DhcpServer);

      /* Bypass DNS server addresses */
      if ((flags & RG_BYPASS_DNS) && pai)
	add_host_route_array (rb, &pai->DnsServerList);
    }

  gc_free (&gc);
}

#else

static void
get_bypass_addresses (struct route_bypass *rb, const unsigned int flags)  /* PLATFORM-SPECIFIC */
{
}

#endif

/*
 * Test if addr is reachable via a local interface (return ILA_LOCAL),
 * or if it needs to be routed via the default gateway (return
 * ILA_NONLOCAL).  If the target platform doesn't implement this
 * function, return ILA_NOT_IMPLEMENTED.
 *
 * Used by redirect-gateway autolocal feature
 */

#if defined(WIN32)

int
test_local_addr (const in_addr_t addr, const struct route_gateway_info *rgi)
{
  struct gc_arena gc = gc_new ();
  const in_addr_t nonlocal_netmask = 0x80000000L; /* routes with netmask <= to this are considered non-local */
  bool ret = TLA_NONLOCAL;

  /* get full routing table */
  const MIB_IPFORWARDTABLE *rt = get_windows_routing_table (&gc);
  if (rt)
    {
      int i;
      for (i = 0; i < rt->dwNumEntries; ++i)
	{
	  const MIB_IPFORWARDROW *row = &rt->table[i];
	  const in_addr_t net = ntohl (row->dwForwardDest);
	  const in_addr_t mask = ntohl (row->dwForwardMask);
	  if (mask > nonlocal_netmask && (addr & mask) == net)
	    {
	      ret = TLA_LOCAL;
	      break;
	    }
	}
    }

  gc_free (&gc);
  return ret;
}

#else

int
test_local_addr (const in_addr_t addr, const struct route_gateway_info *rgi) /* PLATFORM-SPECIFIC */
{
  if (rgi)
    {
      if (local_route (addr, 0xFFFFFFFF, rgi->gateway.addr, rgi))
	return TLA_LOCAL;
      else
	return TLA_NONLOCAL;
    }
  return TLA_NOT_IMPLEMENTED;
}

#endif