summaryrefslogtreecommitdiffstats
path: root/src/etc/inc/services.inc
blob: b17b088c117decfd77cd013c1d4685d144291c78 (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
<?php
/*
 * services.inc
 *
 * part of pfSense (https://www.pfsense.org)
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
 * All rights reserved.
 *
 * originally part of m0n0wall (http://m0n0.ch/wall)
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define('DYNDNS_PROVIDER_VALUES', 'all-inkl citynetwork cloudflare cloudflare-v6 custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost spdyn spdyn-v6 zoneedit');
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,City Network,CloudFlare,CloudFlare (v6),Custom,Custom (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,DreamHost,Dreamhost (v6),DuiaDns.net,DuiaDns.net (v6),DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,freeDNS (v6),GleSYS,Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Hover,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,SPDYN,SPDYN (v6),ZoneEdit');

/* implement ipv6 route advertising daemon */
function services_radvd_configure($blacklist = array()) {
	global $config, $g;

	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_radvd_configure() being called $mt\n";
	}

	if (!is_array($config['dhcpdv6'])) {
		$config['dhcpdv6'] = array();
	}

	$Iflist = get_configured_interface_list();
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());

	$radvdconf = "# Automatically Generated, do not edit\n";

	/* Process all links which need the router advertise daemon */
	$radvdifs = array();

	/* handle manually configured DHCP6 server settings first */
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
		if (!is_array($config['interfaces'][$dhcpv6if])) {
			continue;
		}
		if (!isset($config['interfaces'][$dhcpv6if]['enable'])) {
			continue;
		}

		/* Do not put in the config an interface which is down */
		if (isset($blacklist[$dhcpv6if])) {
			continue;
		}
		if (!isset($dhcpv6ifconf['ramode'])) {
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
		}

		/* are router advertisements enabled? */
		if ($dhcpv6ifconf['ramode'] == "disabled") {
			continue;
		}

		if (!isset($dhcpv6ifconf['rapriority'])) {
			$dhcpv6ifconf['rapriority'] = "medium";
		}

		$racarpif = false;
		/* check if binding to CARP IP */
		if (!empty($dhcpv6ifconf['rainterface'])) {
			if (strstr($dhcpv6ifconf['rainterface'], "_vip")) {
				if (get_carp_interface_status($dhcpv6ifconf['rainterface']) == "MASTER") {
					$dhcpv6if = $dhcpv6ifconf['rainterface'];
					$racarpif = true;
				} else {
					continue;
				}
			}
		}

		$realif = get_real_interface($dhcpv6if, "inet6");

		if (isset($radvdifs[$realif])) {
			continue;
		}

		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
		if (!is_ipaddrv6($ifcfgipv6)) {
			continue;
		}

		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
		if (!is_subnetv6($subnetv6 . "/" . $ifcfgsnv6)) {
			log_error("radvd: skipping configuration for interface $dhcpv6if because its subnet or prefix length is invalid.");
			continue;
		}
		$radvdifs[$realif] = $realif;

		$radvdconf .= "# Generated for DHCPv6 Server $dhcpv6if\n";
		$radvdconf .= "interface {$realif} {\n";
		if (strstr($realif, "ovpn")) {
			$radvdconf .= "\tUnicastOnly on;\n";
		}
		$radvdconf .= "\tAdvSendAdvert on;\n";

		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
		} else {
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
		}

		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
		} else {
			$radvdconf .= "\tMaxRtrAdvInterval 20;\n";
		}
		if (is_numericint($dhcpv6ifconf['raadvdefaultlifetime'])) {
			$radvdconf .= "\tAdvDefaultLifetime {$dhcpv6ifconf['raadvdefaultlifetime']};\n";
		}

		$mtu = get_interface_mtu($realif);
		if (is_numeric($mtu)) {
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
		} else {
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
		}
		switch ($dhcpv6ifconf['rapriority']) {
			case "low":
				$radvdconf .= "\tAdvDefaultPreference low;\n";
				break;
			case "high":
				$radvdconf .= "\tAdvDefaultPreference high;\n";
				break;
			default:
				$radvdconf .= "\tAdvDefaultPreference medium;\n";
				break;
		}
		switch ($dhcpv6ifconf['ramode']) {
			case "managed":
			case "assist":
				$radvdconf .= "\tAdvManagedFlag on;\n";
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
				break;
			case "stateless_dhcp":
				$radvdconf .= "\tAdvManagedFlag off;\n";
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
				break;
		}
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
		if ($racarpif == true) {
			$radvdconf .= "\t\tDeprecatePrefix off;\n";
		} else {
			$radvdconf .= "\t\tDeprecatePrefix on;\n";
		}
		switch ($dhcpv6ifconf['ramode']) {
			case "managed":
				$radvdconf .= "\t\tAdvOnLink on;\n";
				$radvdconf .= "\t\tAdvAutonomous off;\n";
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
				break;
			case "router":
				$radvdconf .= "\t\tAdvOnLink off;\n";
				$radvdconf .= "\t\tAdvAutonomous off;\n";
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
				break;
			case "stateless_dhcp":
			case "assist":
				$radvdconf .= "\t\tAdvOnLink on;\n";
				$radvdconf .= "\t\tAdvAutonomous on;\n";
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
				break;
			case "unmanaged":
				$radvdconf .= "\t\tAdvOnLink on;\n";
				$radvdconf .= "\t\tAdvAutonomous on;\n";
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
				break;
		}

		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
		} else {
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
		}

		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
		} else {
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
		}

		$radvdconf .= "\t};\n";

		if (is_array($dhcpv6ifconf['subnets']['item'])) {
			foreach ($dhcpv6ifconf['subnets']['item'] as $subnet) {
				if (is_subnetv6($subnet)) {
					$radvdconf .= "\tprefix {$subnet} {\n";
					$radvdconf .= "\t\tDeprecatePrefix on;\n";
					switch ($dhcpv6ifconf['ramode']) {
						case "managed":
							$radvdconf .= "\t\tAdvOnLink on;\n";
							$radvdconf .= "\t\tAdvAutonomous off;\n";
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
							break;
						case "router":
							$radvdconf .= "\t\tAdvOnLink off;\n";
							$radvdconf .= "\t\tAdvAutonomous off;\n";
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
							break;
						case "assist":
							$radvdconf .= "\t\tAdvOnLink on;\n";
							$radvdconf .= "\t\tAdvAutonomous on;\n";
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
							break;
						case "unmanaged":
							$radvdconf .= "\t\tAdvOnLink on;\n";
							$radvdconf .= "\t\tAdvAutonomous on;\n";
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
							break;
					}
					$radvdconf .= "\t};\n";
				}
			}
		}
		$radvdconf .= "\troute ::/0 {\n";
		$radvdconf .= "\t\tRemoveRoute on;\n";
		$radvdconf .= "\t};\n";

		/* add DNS servers */
		$dnslist = array();
		if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
			foreach ($dhcpv6ifconf['dnsserver'] as $server) {
				if (is_ipaddrv6($server)) {
					$dnslist[] = $server;
				}
			}
		} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
			foreach ($dhcpv6ifconf['radnsserver'] as $server) {
				if (is_ipaddrv6($server)) {
					$dnslist[] = $server;
				}
			}
		} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
			$dnslist[] = get_interface_ipv6($realif);
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
			foreach ($config['system']['dnsserver'] as $server) {
				if (is_ipaddrv6($server)) {
					$dnslist[] = $server;
				}
			}
		}
		if (count($dnslist) > 0) {
			$dnsstring = implode(" ", $dnslist);
			if ($dnsstring <> "") {
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
			}
		}

		$searchlist = array();
		$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
		foreach ($domainsearchlist as $sd) {
			$sd = trim($sd);
			if (is_hostname($sd)) {
				$searchlist[] = $sd;
			}
		}
		if (count($searchlist) > 0) {
			$searchliststring = trim(implode(" ", $searchlist));
		}
		if (!empty($dhcpv6ifconf['domain'])) {
			$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} { };\n";
		} elseif (!empty($config['system']['domain'])) {
			$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} { };\n";
		}
		$radvdconf .= "};\n";
	}

	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
	foreach ($Iflist as $if => $ifdescr) {
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
			continue;
		}
		if (!isset($config['interfaces'][$if]['enable'])) {
			continue;
		}
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
			continue;
		}
		/* Do not put in the config an interface which is down */
		if (isset($blacklist[$if])) {
			continue;
		}
		$trackif = $config['interfaces'][$if]['track6-interface'];
		if (empty($config['interfaces'][$trackif])) {
			continue;
		}

		$realif = get_real_interface($if, "inet6");

		/* prevent duplicate entries, manual overrides */
		if (isset($radvdifs[$realif])) {
			continue;
		}

		$ifcfgipv6 = get_interface_ipv6($if);
		if (!is_ipaddrv6($ifcfgipv6)) {
			$subnetv6 = "::";
			$ifcfgsnv6 = "64";
		} else {
			$ifcfgsnv6 = get_interface_subnetv6($if);
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
		}
		$radvdifs[$realif] = $realif;

		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];

		if ($g['debug']) {
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
		}

		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
		$radvdconf .= "interface {$realif} {\n";
		$radvdconf .= "\tAdvSendAdvert on;\n";
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
		} else {
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
                }
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
		} else {
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
		}
		$mtu = get_interface_mtu($realif);
		if (is_numeric($mtu)) {
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
		} else {
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
		}
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
		$radvdconf .= "\t\tAdvOnLink on;\n";
		$radvdconf .= "\t\tAdvAutonomous on;\n";
		$radvdconf .= "\t\tAdvRouterAddr on;\n";
		$radvdconf .= "\t};\n";

		/* add DNS servers */
		$dnslist = array();
		if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
			$dnslist[] = $ifcfgipv6;
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
			foreach ($config['system']['dnsserver'] as $server) {
				if (is_ipaddrv6($server)) {
					$dnslist[] = $server;
				}
			}
		}
		if (count($dnslist) > 0) {
			$dnsstring = implode(" ", $dnslist);
			if (!empty($dnsstring)) {
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
			}
		}
		if (!empty($config['system']['domain'])) {
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
		}
		$radvdconf .= "};\n";
	}

	/* write radvd.conf */
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
		if (platform_booting()) {
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
		}
	}
	unset($radvdconf);

	if (count($radvdifs) > 0) {
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
		} else {
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
		}
	} else {
		/* we need to shut down the radvd cleanly, it will send out the prefix
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
			killbypid("{$g['varrun_path']}/radvd.pid");
			@unlink("{$g['varrun_path']}/radvd.pid");
		}
	}
	return 0;
}

function services_dhcpd_configure($family = "all", $blacklist = array()) {
	global $config, $g;

	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);

	/* configure DHCPD chroot once */
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");

	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
	if (!trim($status)) {
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
	}
	fclose($fd);
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");

	if ($family == "all" || $family == "inet") {
		services_dhcpdv4_configure();
	}
	if ($family == "all" || $family == "inet6") {
		services_dhcpdv6_configure($blacklist);
		services_radvd_configure($blacklist);
	}

	unlock($dhcpdconfigurelck);
}

function services_dhcpdv4_configure() {
	global $config, $g;
	$need_ddns_updates = false;
	$ddns_zones = array();

	if ($g['services_dhcp_server_enable'] == false) {
		return;
	}

	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_dhcpdv4_configure($if) being called $mt\n";
	}

	/* kill any running dhcpd */
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
	}

	/* DHCP enabled on any interfaces? */
	if (!is_dhcp_server_enabled()) {
		return 0;
	}

	/* if OLSRD is enabled, allow WAN to house DHCP. */
	if (!function_exists('is_package_installed')) {
		require_once('pkg-utils.inc');
	}
	if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) {
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
			if (isset($olsrd['enable']) && $olsrd['enable'] == "on") {
				$is_olsr_enabled = true;
				break;
			}
		}
	}

	$syscfg = $config['system'];
	if (!is_array($config['dhcpd'])) {
		$config['dhcpd'] = array();
	}
	$dhcpdcfg = $config['dhcpd'];
	$Iflist = get_configured_interface_list();

	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
	$dns_arrv4 = array();
	if (is_array($syscfg['dnsserver'])) {
		foreach ($syscfg['dnsserver'] as $dnsserver) {
			if (is_ipaddrv4($dnsserver)) {
				$dns_arrv4[] = $dnsserver;
			}
		}
	}

	if (platform_booting()) {
		echo gettext("Starting DHCP service...");
	} else {
		sleep(1);
	}

	$custoptions = "";
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
				if (!empty($item['type'])) {
					$itemtype = $item['type'];
				} else {
					$itemtype = "text";
				}
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
			}
		}
		if (is_array($dhcpifconf['pool'])) {
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
						if (!empty($item['type'])) {
							$itemtype = $item['type'];
						} else {
							$itemtype = "text";
						}
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
					}
				}
			}
		}
	}

	$dhcpdconf = <<<EOD

option domain-name "{$syscfg['domain']}";
option ldap-server code 95 = text;
option domain-search-list code 119 = text;
option arch code 93 = unsigned integer 16; # RFC4578
{$custoptions}
default-lease-time 7200;
max-lease-time 86400;
log-facility local7;
one-lease-per-client true;
deny duplicates;
ping-check true;
update-conflict-detection false;

EOD;

	if (!isset($dhcpifconf['disableauthoritative'])) {
		$dhcpdconf .= "authoritative;\n";
	}

	if (isset($dhcpifconf['alwaysbroadcast'])) {
		$dhcpdconf .= "always-broadcast on\n";
	}

	$dhcpdifs = array();
	$enable_add_routers = false;
	$gateways_arr = return_gateways_array();
	/* only add a routers line if the system has any IPv4 gateway at all */
	/* a static route has a gateway, manually overriding this field always works */
	foreach ($gateways_arr as $gwitem) {
		if ($gwitem['ipprotocol'] == "inet") {
			$enable_add_routers = true;
			break;
		}
	}

	/*    loop through and determine if we need to setup
	 *    failover peer "bleh" entries
	 */
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {

		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
			continue;
		}

		interfaces_staticarp_configure($dhcpif);

		if (!isset($dhcpifconf['enable'])) {
			continue;
		}

		if ($dhcpifconf['failover_peerip'] <> "") {
			$intip = get_interface_ip($dhcpif);
			/*
			 *    yep, failover peer is defined.
			 *    does it match up to a defined vip?
			 */
			$skew = 110;
			if (is_array($config['virtualip']['vip'])) {
				foreach ($config['virtualip']['vip'] as $vipent) {
					if ($vipent['interface'] == $dhcpif) {
						$carp_nw = gen_subnet($vipent['subnet'], $vipent['subnet_bits']);
						if (ip_in_subnet($dhcpifconf['failover_peerip'], "{$carp_nw}/{$vipent['subnet_bits']}")) {
							/* this is the interface! */
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
								$skew = 0;
								break;
							}
						}
					}
				}
			} else {
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
			}
			if ($skew > 10) {
				$type = "secondary";
				$my_port = "520";
				$peer_port = "519";
				$dhcpdconf_pri = '';
			} else {
				$my_port = "519";
				$peer_port = "520";
				$type = "primary";
				$dhcpdconf_pri = "split 128;\n";
				$dhcpdconf_pri .= "  mclt 600;\n";
			}

			if (is_ipaddrv4($intip)) {
				$dhcpdconf .= <<<EOPP
failover peer "dhcp_{$dhcpif}" {
  {$type};
  address {$intip};
  port {$my_port};
  peer address {$dhcpifconf['failover_peerip']};
  peer port {$peer_port};
  max-response-delay 10;
  max-unacked-updates 10;
  {$dhcpdconf_pri}
  load balance max seconds 3;
}
\n
EOPP;
			}
		}
	}

	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {

		$newzone = array();
		$ifcfg = $config['interfaces'][$dhcpif];

		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
			continue;
		}
		$ifcfgip = get_interface_ip($dhcpif);
		$ifcfgsn = get_interface_subnet($dhcpif);
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
		$subnetmask = gen_subnet_mask($ifcfgsn);

		if (!is_ipaddr($subnet)) {
			continue;
		}

		if ($is_olsr_enabled == true) {
			if ($dhcpifconf['netmask']) {
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
			}
		}

		$all_pools = array();
		$all_pools[] = $dhcpifconf;
		if (is_array($dhcpifconf['pool'])) {
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
		}

		$dnscfg = "";

		if ($dhcpifconf['domain']) {
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
		}

		if ($dhcpifconf['domainsearchlist'] <> "") {
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
		}

		if (isset($dhcpifconf['ddnsupdate'])) {
			$need_ddns_updates = true;
			$newzone = array();
			if ($dhcpifconf['ddnsdomain'] <> "") {
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
			} else {
				$newzone['domain-name'] = $config['system']['domain'];
			}

			$revsubnet = array_reverse(explode('.',$subnet));

			/* Take care of full classes first */
			switch ($ifcfgsn) {
				case 8:
					$start_octet = 3;
					break;
				case 16:
					$start_octet = 2;
					break;
				case 24:
					$start_octet = 1;
					break;
				default:
					$start_octet = 0;
					/* Add subnet bitmask to first octet */
					$revsubnet[0] .= '-' . $ifcfgsn;
					break;

			}

			$ptr_domain = '';
			for ($octet = 0; $octet <= 3; $octet++) {
				if ($octet < $start_octet) {
					continue;
				}
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
				$ptr_domain .= $revsubnet[$octet];
			}
			$ptr_domain .= ".in-addr.arpa";
			$newzone['ptr-domain'] = $ptr_domain;
			unset($ptr_domain, $revsubnet, $start_octet);
		}

		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
			if ($newzone['domain-name']) {
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
			}
		} else if (isset($config['dnsmasq']['enable'])) {
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
				$newzone['dns-servers'] = $syscfg['dnsserver'];
			}
		} else if (isset($config['unbound']['enable'])) {
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
		} else if (!empty($dns_arrv4)) {
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
			if ($newzone['domain-name']) {
				$newzone['dns-servers'] = $dns_arrv4;
			}
		}

		/* Create classes - These all contain comma separated lists. Join them into one
		   big comma separated string then split them all up. */
		$all_mac_strings = array();
		if (is_array($dhcpifconf['pool'])) {
			foreach ($all_pools as $poolconf) {
				$all_mac_strings[] = $poolconf['mac_allow'];
				$all_mac_strings[] = $poolconf['mac_deny'];
			}
		}
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
		if (!empty($all_mac_strings)) {
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
			foreach ($all_mac_list as $mac) {
				if (empty($mac)) {
					continue;
				}
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
				$dhcpdconf .= '}' . "\n";
			}
		}

		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";

		// Setup pool options
		foreach ($all_pools as $all_pools_idx => $poolconf) {
			if (!(ip_in_subnet($poolconf['range']['from'], "{$subnet}/{$ifcfgsn}") && ip_in_subnet($poolconf['range']['to'], "{$subnet}/{$ifcfgsn}"))) {
				// If the user has changed the subnet from the interfaces page and applied,
				// but has not updated the DHCP range, then the range to/from of the pool can be outside the subnet.
				// This can also happen when implementing the batch of changes when the setup wizard reloads the new settings.
				$error_msg = sprintf(gettext('Invalid DHCP pool %1$s - %2$s for %3$s subnet %4$s/%5$s detected. Please correct the settings in Services, DHCP Server'), $poolconf['range']['from'], $poolconf['range']['to'], convert_real_interface_to_friendly_descr($dhcpif), $subnet, $ifcfgsn);
				$do_file_notice = true;
				$conf_ipv4_address = $ifcfg['ipaddr'];
				$conf_ipv4_subnetmask = $ifcfg['subnet'];
				if (is_ipaddrv4($conf_ipv4_address) && is_subnet("{$conf_ipv4_address}/{$conf_ipv4_subnetmask}")) {
					$conf_subnet_base = gen_subnet($conf_ipv4_address, $conf_ipv4_subnetmask);
					if (ip_in_subnet($poolconf['range']['from'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}") &&
					    ip_in_subnet($poolconf['range']['to'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}")) {
						// Even though the running interface subnet does not match the pool range,
						// the interface subnet in the config file contains the pool range.
						// We are somewhere part-way through a settings reload, e.g. after running the setup wizard.
						// services_dhcpdv4_configure will be called again later when the new interface settings from
						// the config are applied and at that time everything will match up.
						// Ignore this pool on this interface for now and just log the error to the system log.
						log_error($error_msg);
						$do_file_notice = false;
					}
				}
				if ($do_file_notice) {
					file_notice("DHCP", $error_msg);
				}
				continue;
			}
			$dhcpdconf .= "	pool {\n";
			/* is failover dns setup? */
			if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") {
				$dhcpdconf .= "		option domain-name-servers {$poolconf['dnsserver'][0]}";
				if ($poolconf['dnsserver'][1] <> "") {
					$dhcpdconf .= ",{$poolconf['dnsserver'][1]}";
				}
				if ($poolconf['dnsserver'][2] <> "") {
					$dhcpdconf .= ",{$poolconf['dnsserver'][2]}";
				}
				if ($poolconf['dnsserver'][3] <> "") {
					$dhcpdconf .= ",{$poolconf['dnsserver'][3]}";
				}
				$dhcpdconf .= ";\n";
			}

			/* allow/deny MACs */
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
			foreach ($mac_allow_list as $mac) {
				if (empty($mac)) {
					continue;
				}
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
			}
			$deny_action = "deny";
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
				$deny_action = "ignore";
			}
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
			foreach ($mac_deny_list as $mac) {
				if (empty($mac)) {
					continue;
				}
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
			}

			if ($poolconf['failover_peerip'] <> "") {
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
			}

			if (isset($poolconf['denyunknown'])) {
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
			}

			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
			}

			if ($dhcpifconf['failover_peerip'] <> "") {
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
			}

			$pdnscfg = "";

			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
			}

			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
			}

			if (isset($poolconf['ddnsupdate'])) {
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
				}
				$pdnscfg .= "		ddns-update-style interim;\n";
			}

			$dhcpdconf .= "{$pdnscfg}";

			// default-lease-time
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
			}

			// max-lease-time
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
			}

			// ignore bootp
			if (isset($poolconf['ignorebootp'])) {
				$dhcpdconf .= "		ignore bootp;\n";
			}

			// ignore-client-uids
			if (isset($poolconf['ignoreclientuids'])) {
				$dhcpdconf .= "		ignore-client-uids true;\n";
			}

			// netbios-name*
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
				$dhcpdconf .= "		option netbios-node-type 8;\n";
			}

			// ntp-servers
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
			}

			// tftp-server-name
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
			}

			// Handle pool-specific options
			$dhcpdconf .= "\n";
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
			if ($poolconf['numberoptions']['item'] && ($all_pools_idx > 0)) {
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
				$poolidx = $all_pools_idx - 1;
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
					$item_value = base64_decode($item['value']);
					if (empty($item['type']) || $item['type'] == "text") {
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
					} else {
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
					}
				}
			}

			// ldap-server
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
			}

			// net boot information
			if (isset($poolconf['netboot'])) {
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
				}
				if (!empty($poolconf['filename']) && ($poolconf['filename'] != $dhcpifconf['filename'])) {
					$dhcpdconf .= "		filename \"{$poolconf['filename']}\";\n";
				}
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
				}
			}
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
			$dhcpdconf .= "	}\n\n";
		}
// End of settings inside pools

		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
			$routers = $dhcpifconf['gateway'];
			$add_routers = true;
		} elseif ($dhcpifconf['gateway'] == "none") {
			$add_routers = false;
		} else {
			$add_routers = $enable_add_routers;
			$routers = $ifcfgip;
		}
		if ($add_routers) {
			$dhcpdconf .= "	option routers {$routers};\n";
		}

		$dhcpdconf .= <<<EOD
$dnscfg

EOD;
		// default-lease-time
		if ($dhcpifconf['defaultleasetime']) {
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
		}

		// max-lease-time
		if ($dhcpifconf['maxleasetime']) {
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
		}

		// netbios-name*
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
			$dhcpdconf .= "	option netbios-node-type 8;\n";
		}

		// ntp-servers
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
		}

		// tftp-server-name
		if ($dhcpifconf['tftp'] <> "") {
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
		}

		// Handle option, number rowhelper values
		$dhcpdconf .= "\n";
		if ($dhcpifconf['numberoptions']['item']) {
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
				$item_value = base64_decode($item['value']);
				if (empty($item['type']) || $item['type'] == "text") {
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
				} else {
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
				}
			}
		}

		// ldap-server
		if ($dhcpifconf['ldap'] <> "") {
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
		}

		// net boot information
		if (isset($dhcpifconf['netboot'])) {
			if ($dhcpifconf['nextserver'] <> "") {
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
			}
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
				$dhcpdconf .= "	if option arch = 00:06 {\n";
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
				$dhcpdconf .= "	} else {\n";
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
				$dhcpdconf .= "	}\n\n";
			} elseif (!empty($dhcpifconf['filename'])) {
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
			}
			if (!empty($dhcpifconf['rootpath'])) {
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
			}
		}

		$dhcpdconf .= <<<EOD
}

EOD;

		/* add static mappings */
		if (is_array($dhcpifconf['staticmap'])) {

			$i = 0;
			foreach ($dhcpifconf['staticmap'] as $sm) {
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";

				if ($sm['mac']) {
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
				}

				if ($sm['cid']) {
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
				}

				if ($sm['ipaddr']) {
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
				}

				if ($sm['hostname']) {
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
					$dhhostname = str_replace(".", "_", $dhhostname);
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
					}
				}
				if ($sm['filename']) {
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
				}

				if ($sm['rootpath']) {
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
				}

				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
				}

				$smdnscfg = "";

				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
				}

				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
				}

				if (isset($sm['ddnsupdate'])) {
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
					}
					$smdnscfg .= "		ddns-update-style interim;\n";
				}

				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
				}
				$dhcpdconf .= "{$smdnscfg}";

				// default-lease-time
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
				}

				// max-lease-time
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
				}

				// netbios-name*
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
					$dhcpdconf .= "	option netbios-node-type 8;\n";
				}

				// ntp-servers
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
				}

				// tftp-server-name
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
				}

				$dhcpdconf .= "}\n";
				$i++;
			}
		}

		$dhcpdifs[] = get_real_interface($dhcpif);
		if ($newzone['domain-name']) {
			if ($need_ddns_updates) {
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
				$dhcpdconf .= dhcpdkey($dhcpifconf);
			}
			$ddns_zones[] = $newzone;
		}
	}

	if ($need_ddns_updates) {
		$dhcpdconf .= "ddns-update-style interim;\n";
		$dhcpdconf .= "update-static-leases on;\n";

		$dhcpdconf .= dhcpdzones($ddns_zones);
	}

	/* write dhcpd.conf */
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
		unset($dhcpdconf);
		return 1;
	}
	unset($dhcpdconf);

	/* create an empty leases database */
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
	}

	/* make sure there isn't a stale dhcpd.pid file, which can make dhcpd fail to start.   */
	/* if we get here, dhcpd has been killed and is not started yet                        */
	unlink_if_exists("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");

	/* fire up dhcpd in a chroot */
	if (count($dhcpdifs) > 0) {
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
			join(" ", $dhcpdifs));
	}

	if (platform_booting()) {
		print "done.\n";
	}

	return 0;
}

function dhcpdkey($dhcpifconf) {
	$dhcpdconf = "";
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
		$dhcpdconf .= "	algorithm hmac-md5;\n";
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
		$dhcpdconf .= "}\n";
	}

	return $dhcpdconf;
}

function dhcpdzones($ddns_zones) {
	$dhcpdconf = "";

	if (is_array($ddns_zones)) {
		$added_zones = array();
		foreach ($ddns_zones as $zone) {
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
				continue;
			}
			$primary = $zone['dns-servers'][0];
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];

			// Make sure we aren't using any invalid or IPv6 DNS servers.
			if (!is_ipaddrv4($primary)) {
				if (is_ipaddrv4($secondary)) {
					$primary = $secondary;
					$secondary = "";
				} else {
					continue;
				}
			}

			// We don't need to add zones multiple times.
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
				$dhcpdconf .= "	primary {$primary};\n";
				if (is_ipaddrv4($secondary)) {
					$dhcpdconf .= "	secondary {$secondary};\n";
				}
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
				}
				$dhcpdconf .= "}\n";
				$added_zones[] = $zone['domain-name'];
			}
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
				$dhcpdconf .= "	primary {$primary};\n";
				if (is_ipaddrv4($secondary)) {
					$dhcpdconf .= "	secondary {$secondary};\n";
				}
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
				}
				$dhcpdconf .= "}\n";
				$added_zones[] = $zone['ptr-domain'];
			}
		}
	}

	return $dhcpdconf;
}

function services_dhcpdv6_configure($blacklist = array()) {
	global $config, $g;

	if ($g['services_dhcp_server_enable'] == false) {
		return;
	}

	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_dhcpd_configure($if) being called $mt\n";
	}

	/* kill any running dhcpd */
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
	}
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
	}

	/* DHCP enabled on any interfaces? */
	if (!is_dhcpv6_server_enabled()) {
		return 0;
	}

	$syscfg = $config['system'];
	if (!is_array($config['dhcpdv6'])) {
		$config['dhcpdv6'] = array();
	}
	$dhcpdv6cfg = $config['dhcpdv6'];
	$Iflist = get_configured_interface_list();
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());


	if (platform_booting()) {
		echo "Starting DHCPv6 service...";
	} else {
		sleep(1);
	}

	$custoptionsv6 = "";
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
			}
		}
	}

	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
	}

	$dhcpdv6conf = <<<EOD

option domain-name "{$syscfg['domain']}";
option ldap-server code 95 = text;
option domain-search-list code 119 = text;
{$custoptionsv6}
default-lease-time 7200;
max-lease-time 86400;
log-facility local7;
one-lease-per-client true;
deny duplicates;
ping-check true;
update-conflict-detection false;

EOD;

	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
		$dhcpdv6conf .= "authoritative;\n";
	}

	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
		$dhcpdv6conf .= "always-broadcast on\n";
	}

	$dhcpdv6ifs = array();

	$dhcpv6num = 0;
	$nsupdate = false;

	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {

		$ddns_zones = array();

		$ifcfgv6 = $config['interfaces'][$dhcpv6if];

		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
			continue;
		}
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
		if (!is_ipaddrv6($ifcfgipv6)) {
			continue;
		}
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
		// We might have some prefix-delegation on WAN (e.g. /48),
		// but then it is split and given out to individual interfaces
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
		// of each subnet here is always /64.
		$pdlen = 64;

		if ($is_olsr_enabled == true) {
			if ($dhcpv6ifconf['netmask']) {
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
			}
		}

		$dnscfgv6 = "";

		if ($dhcpv6ifconf['domain']) {
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
		}

		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
		}

		if (isset($dhcpv6ifconf['ddnsupdate'])) {
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
			}
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
				$ddnsclientupdates = 'allow';
			} else {
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
			}
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
			$nsupdate = true;
		} else {
			$dnscfgv6 .= "	do-forward-updates false;\n";
		}

		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
			$dns_arrv6 = array();
			foreach ($syscfg['dnsserver'] as $dnsserver) {
				if (is_ipaddrv6($dnsserver)) {
					$dns_arrv6[] = $dnsserver;
				}
			}
			if (!empty($dns_arrv6)) {
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
			}
		}

		if (!is_ipaddrv6($ifcfgipv6)) {
			$ifcfgsnv6 = "64";
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
		}

		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";

		if (isset($dhcpv6ifconf['ddnsupdate']) &&
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
			$newzone = array();
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
			$ddns_zones[] = $newzone;
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
				foreach ($ptr_zones as $ptr_zone) {
					$reversezone = array();
					$reversezone['domain-name'] = $ptr_zone;
					$reversezone['dns-servers'][] =
					    $dhcpv6ifconf['ddnsdomainprimary'];
					$ddns_zones[] = $reversezone;
				}
			}
		}

		$dhcpdv6conf .= " {\n";

		$range_from = $dhcpv6ifconf['range']['from'];
		$range_to = $dhcpv6ifconf['range']['to'];
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
		}

		$dhcpdv6conf .= <<<EOD
	range6 {$range_from} {$range_to};
$dnscfgv6

EOD;

		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
		}
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
			$dns6ip = $dhcpv6ifconf['dns6ip'];
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
			}
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
		}
		// default-lease-time
		if ($dhcpv6ifconf['defaultleasetime']) {
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
		}

		// max-lease-time
		if ($dhcpv6ifconf['maxleasetime']) {
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
		}

		// ntp-servers
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
			$ntpservers = array();
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
				if (!is_ipaddrv6($ntpserver)) {
					continue;
				}
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
				}
				$ntpservers[] = $ntpserver;
			}
			if (count($ntpservers) > 0) {
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
			}
		}
		// tftp-server-name
		/* Needs ISC DHCPD support
		 if ($dhcpv6ifconf['tftp'] <> "") {
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
		 }
		*/

		// Handle option, number rowhelper values
		$dhcpdv6conf .= "\n";
		if ($dhcpv6ifconf['numberoptions']['item']) {
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
				$itemv6_value = base64_decode($itemv6['value']);
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
			}
		}

		// ldap-server
		if ($dhcpv6ifconf['ldap'] <> "") {
			$ldapserver = $dhcpv6ifconf['ldap'];
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
			}
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
		}

		// net boot information
		if (isset($dhcpv6ifconf['netboot'])) {
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
			}
		}

		$dhcpdv6conf .= "}\n";

		/* add static mappings */
		/* Needs to use DUID */
		if (is_array($dhcpv6ifconf['staticmap'])) {
			$i = 0;
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
				$dhcpdv6conf .= <<<EOD
host s_{$dhcpv6if}_{$i} {
	host-identifier option dhcp6.client-id {$sm['duid']};

EOD;
				if ($sm['ipaddrv6']) {
					$ipaddrv6 = $sm['ipaddrv6'];
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
					}
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
				}

				if ($sm['hostname']) {
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
					$dhhostname = str_replace(".", "_", $dhhostname);
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
				}
				if ($sm['filename']) {
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
				}

				if ($sm['rootpath']) {
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
				}

				$dhcpdv6conf .= "}\n";
				$i++;
			}
		}

		if ($dhcpv6ifconf['ddnsdomain']) {
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
		}

		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
			if (preg_match("/poes/si", $dhcpv6if)) {
				/* magic here */
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
			} else {
				$realif = get_real_interface($dhcpv6if, "inet6");
				if (stristr("$realif", "bridge")) {
					$mac = get_interface_mac($realif);
					$v6address = generate_ipv6_from_mac($mac);
					/* Create link local address for bridges */
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
				}
				$realif = escapeshellcmd($realif);
				$dhcpdv6ifs[] = $realif;
			}
		}
	}

	if ($nsupdate) {
		$dhcpdv6conf .= "ddns-update-style interim;\n";
	} else {
		$dhcpdv6conf .= "ddns-update-style none;\n";
	}

	/* write dhcpdv6.conf */
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
		if (platform_booting()) {
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
		}
		unset($dhcpdv6conf);
		return 1;
	}
	unset($dhcpdv6conf);

	/* create an empty leases v6 database */
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
	}

	/* make sure there isn't a stale dhcpdv6.pid file, which may make dhcpdv6 fail to start.  */
	/* if we get here, dhcpdv6 has been killed and is not started yet                         */
	unlink_if_exists("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");

	/* fire up dhcpd in a chroot */
	if (count($dhcpdv6ifs) > 0) {
		mwexec("/usr/local/sbin/dhcpd -6 -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpdv6.conf -pf {$g['varrun_path']}/dhcpdv6.pid " .
			join(" ", $dhcpdv6ifs));
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php|/bin/sh\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
	}
	if (platform_booting()) {
		print gettext("done.") . "\n";
	}

	return 0;
}

function services_igmpproxy_configure() {
	global $config, $g;

	/* kill any running igmpproxy */
	killbyname("igmpproxy");

	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
		return 1;
	}

	$iflist = get_configured_interface_list();

	$igmpconf = <<<EOD

##------------------------------------------------------
## Enable Quickleave mode (Sends Leave instantly)
##------------------------------------------------------
quickleave

EOD;

	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
		unset($iflist[$igmpcf['ifname']]);
		$realif = get_real_interface($igmpcf['ifname']);
		if (empty($igmpcf['threshold'])) {
			$threshld = 1;
		} else {
			$threshld = $igmpcf['threshold'];
		}
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";

		if ($igmpcf['address'] <> "") {
			$item = explode(" ", $igmpcf['address']);
			foreach ($item as $iww) {
				$igmpconf .= "altnet {$iww}\n";
			}
		}
		$igmpconf .= "\n";
	}
	foreach ($iflist as $ifn) {
		$realif = get_real_interface($ifn);
		$igmpconf .= "phyint {$realif} disabled\n";
	}
	$igmpconf .= "\n";

	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
	if (!$igmpfl) {
		log_error(gettext("Could not write Igmpproxy configuration file!"));
		return;
	}
	fwrite($igmpfl, $igmpconf);
	fclose($igmpfl);
	unset($igmpconf);

	if (isset($config['syslog']['igmpxverbose'])) {
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
	} else {
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
	}

	log_error(gettext("Started IGMP proxy service."));

	return 0;
}

function services_dhcrelay_configure() {
	global $config, $g;

	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_dhcrelay_configure() being called $mt\n";
	}

	/* kill any running dhcrelay */
	killbypid("{$g['varrun_path']}/dhcrelay.pid");

	$dhcrelaycfg =& $config['dhcrelay'];

	/* DHCPRelay enabled on any interfaces? */
	if (!isset($dhcrelaycfg['enable'])) {
		return 0;
	}

	if (platform_booting()) {
		echo gettext("Starting DHCP relay service...");
	} else {
		sleep(1);
	}

	$iflist = get_configured_interface_list();

	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
	foreach ($dhcifaces as $dhcrelayif) {
		if (!isset($iflist[$dhcrelayif]) ||
		    link_interface_to_bridge($dhcrelayif)) {
			continue;
		}

		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
		}
	}

	/*
	 * In order for the relay to work, it needs to be active
	 * on the interface in which the destination server sits.
	 */
	$srvips = explode(",", $dhcrelaycfg['server']);
	if (!is_array($srvips)) {
		log_error(gettext("No destination IP has been configured!"));
		return;
	}

	foreach ($srvips as $srcidx => $srvip) {
		unset($destif);
		foreach ($iflist as $ifname) {
			$subnet = get_interface_ip($ifname);
			if (!is_ipaddr($subnet)) {
				continue;
			}
			$subnet .= "/" . get_interface_subnet($ifname);
			if (ip_in_subnet($srvip, $subnet)) {
				$destif = get_real_interface($ifname);
				break;
			}
		}
		if (!isset($destif)) {
			// For each enabled static route
			foreach (get_staticroutes(false, false, true) as $rtent) {
				if (ip_in_subnet($srvip, $rtent['network'])) {
					$a_gateways = return_gateways_array(true);
					$destif = $a_gateways[$rtent['gateway']]['interface'];
					break;
				}
			}
		}

		if (!isset($destif)) {
			/* Create a array from the existing route table */
			exec("/usr/bin/netstat -rnWf inet", $route_str);
			array_shift($route_str);
			array_shift($route_str);
			array_shift($route_str);
			array_shift($route_str);
			$route_arr = array();
			foreach ($route_str as $routeline) {
				$items = preg_split("/[ ]+/i", $routeline);
				if (is_subnetv4($items[0])) {
					$subnet = $items[0];
				} elseif (is_ipaddrv4($items[0])) {
					$subnet = "{$items[0]}/32";
				} else {
					// Not a subnet or IP address, skip to the next line.
					continue;
				}
				if (ip_in_subnet($srvip, $subnet)) {
					$destif = trim($items[6]);
					break;
				}
			}
		}

		if (!isset($destif)) {
			if (is_array($config['gateways']['gateway_item'])) {
				foreach ($config['gateways']['gateway_item'] as $gateway) {
					if (isset($gateway['defaultgw'])) {
						$destif = get_real_interface($gateway['interface']);
						break;
					}
				}
			} else {
				$destif = get_real_interface("wan");
			}
		}

		if (!empty($destif)) {
			$dhcrelayifs[] = $destif;
		}
	}
	$dhcrelayifs = array_unique($dhcrelayifs);

	/* fire up dhcrelay */
	if (empty($dhcrelayifs)) {
		log_error(gettext("No suitable interface found for running dhcrelay!"));
		return; /* XXX */
	}

	$cmd = "/usr/local/sbin/dhcrelay -i " . implode(" -i ", $dhcrelayifs);

	if (isset($dhcrelaycfg['agentoption'])) {
		$cmd .= " -a -m replace";
	}

	$cmd .= " " . implode(" ", $srvips);
	mwexec($cmd);
	unset($cmd);

	return 0;
}

function services_dhcrelay6_configure() {
	global $config, $g;

	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_dhcrelay6_configure() being called $mt\n";
	}

	/* kill any running dhcrelay */
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");

	$dhcrelaycfg =& $config['dhcrelay6'];

	/* DHCPv6 Relay enabled on any interfaces? */
	if (!isset($dhcrelaycfg['enable'])) {
		return 0;
	}

	if (platform_booting()) {
		echo gettext("Starting DHCPv6 relay service...");
	} else {
		sleep(1);
	}

	$iflist = get_configured_interface_list();

	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
	foreach ($dhcifaces as $dhcrelayif) {
		if (!isset($iflist[$dhcrelayif]) ||
		    link_interface_to_bridge($dhcrelayif)) {
			continue;
		}

		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
		}
	}
	$dhcrelayifs = array_unique($dhcrelayifs);

	/*
	 * In order for the relay to work, it needs to be active
	 * on the interface in which the destination server sits.
	 */
	$srvips = explode(",", $dhcrelaycfg['server']);
	$srvifaces = array();
	foreach ($srvips as $srcidx => $srvip) {
		unset($destif);
		foreach ($iflist as $ifname) {
			$subnet = get_interface_ipv6($ifname);
			if (!is_ipaddrv6($subnet)) {
				continue;
			}
			$subnet .= "/" . get_interface_subnetv6($ifname);
			if (ip_in_subnet($srvip, $subnet)) {
				$destif = get_real_interface($ifname);
				break;
			}
		}
		if (!isset($destif)) {
			if (is_array($config['staticroutes']['route'])) {
				foreach ($config['staticroutes']['route'] as $rtent) {
					if (isset($rtent['disabled'])) {
						continue;
					}
					if (ip_in_subnet($srvip, $rtent['network'])) {
						$a_gateways = return_gateways_array(true);
						$destif = $a_gateways[$rtent['gateway']]['interface'];
						break;
					}
				}
			}
		}

		if (!isset($destif)) {
			/* Create a array from the existing route table */
			exec("/usr/bin/netstat -rnWf inet6", $route_str);
			array_shift($route_str);
			array_shift($route_str);
			array_shift($route_str);
			array_shift($route_str);
			$route_arr = array();
			foreach ($route_str as $routeline) {
				$items = preg_split("/[ ]+/i", $routeline);
				if (ip_in_subnet($srvip, $items[0])) {
					$destif = trim($items[6]);
					break;
				}
			}
		}

		if (!isset($destif)) {
			if (is_array($config['gateways']['gateway_item'])) {
				foreach ($config['gateways']['gateway_item'] as $gateway) {
					if (isset($gateway['defaultgw'])) {
						$destif = get_real_interface($gateway['interface']);
						break;
					}
				}
			} else {
				$destif = get_real_interface("wan");
			}
		}

		if (!empty($destif)) {
			$srvifaces[] = "{$srvip}%{$destif}";
		}
	}

	/* fire up dhcrelay */
	if (empty($dhcrelayifs) || empty($srvifaces)) {
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
		return; /* XXX */
	}

	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
	foreach ($dhcrelayifs as $dhcrelayif) {
		$cmd .= " -l {$dhcrelayif}";
	}
	foreach ($srvifaces as $srviface) {
		$cmd .= " -u \"{$srviface}\"";
	}
	mwexec($cmd);
	unset($cmd);

	return 0;
}

function services_dyndns_configure_client($conf) {

	if (!isset($conf['enable'])) {
		return;
	}

	/* load up the dyndns.class */
	require_once("dyndns.class");

	$dns = new updatedns($dnsService = $conf['type'],
		$dnsHost = $conf['host'],
		$dnsDomain = $conf['domainname'],
		$dnsUser = $conf['username'],
		$dnsPass = $conf['password'],
		$dnsWildcard = $conf['wildcard'],
		$dnsProxied = $conf['proxied'],
		$dnsMX = $conf['mx'],
		$dnsIf = "{$conf['interface']}",
		$dnsBackMX = NULL,
		$dnsServer = NULL,
		$dnsPort = NULL,
		$dnsUpdateURL = "{$conf['updateurl']}",
		$forceUpdate = $conf['force'],
		$dnsZoneID = $conf['zoneid'],
		$dnsTTL = $conf['ttl'],
		$dnsResultMatch = "{$conf['resultmatch']}",
		$dnsRequestIf = "{$conf['requestif']}",
		$dnsID = "{$conf['id']}",
		$dnsVerboseLog = $conf['verboselog'],
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
}

function services_dyndns_configure($int = "") {
	global $config, $g;
	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_dyndns_configure() being called $mt\n";
	}

	$dyndnscfg = $config['dyndnses']['dyndns'];
	$gwgroups = return_gateway_groups_array();
	if (is_array($dyndnscfg)) {
		if (platform_booting()) {
			echo gettext("Starting DynDNS clients...");
		}

		foreach ($dyndnscfg as $dyndns) {
			/*
			 * If it's using a gateway group, check if interface is
			 * the active gateway for that group
			 */
			$group_int = '';
			if (is_array($gwgroups[$dyndns['interface']])) {
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
				} else {
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
				}
			}
			if ((empty($int)) || ($int == $dyndns['interface']) || ($int == $group_int)) {
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
				services_dyndns_configure_client($dyndns);
				sleep(1);
			}
		}

		if (platform_booting()) {
			echo gettext("done.") . "\n";
		}
	}

	return 0;
}

function dyndnsCheckIP($int) {
	global $config, $factory_default_checkipservice;
	$ip_address = get_interface_ip($int);
	if (is_private_ip($ip_address)) {
		$gateways_status = return_gateways_status(true);
		// If the gateway for this interface is down, then the external check cannot work.
		// Avoid the long wait for the external check to timeout.
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
			return "down";
		}

		// Append the factory default check IP service to the list (if not disabled).
		if (!isset($config['checkipservices']['disable_factory_default'])) {
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
		}

		// Use the first enabled check IP service as the default.
		if (is_array($config['checkipservices']['checkipservice'])) {
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
				if (isset($checkipservice['enable'])) {
					$url = $checkipservice['url'];
					$username = $checkipservice['username'];
					$password = $checkipservice['password'];
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
					break;
				}
			}
		}

		$hosttocheck = $url;
		$ip_ch = curl_init($hosttocheck);
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
		$ip_result_page = curl_exec($ip_ch);
		curl_close($ip_ch);
		$ip_result_decoded = urldecode($ip_result_page);
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
		$ip_address = trim($matches[1]);
	}
	return $ip_address;
}

function services_dnsmasq_configure($restart_dhcp = true) {
	global $config, $g;
	$return = 0;

	// hard coded args: will be removed to avoid duplication if specified in custom_options
	$standard_args = array(
		"dns-forward-max" => "--dns-forward-max=5000",
		"cache-size" => "--cache-size=10000",
		"local-ttl" => "--local-ttl=1"
	);


	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_dnsmasq_configure() being called $mt\n";
	}

	/* kill any running dnsmasq */
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
	}

	if (isset($config['dnsmasq']['enable'])) {

		if (platform_booting()) {
			echo gettext("Starting DNS forwarder...");
		} else {
			sleep(1);
		}

		/* generate hosts file */
		if (system_hosts_generate() != 0) {
			$return = 1;
		}

		$args = "";

		if (isset($config['dnsmasq']['regdhcp'])) {
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
		}

		/* Setup listen port, if non-default */
		if (is_port($config['dnsmasq']['port'])) {
			$args .= " --port={$config['dnsmasq']['port']} ";
		}

		$listen_addresses = "";
		if (isset($config['dnsmasq']['interface'])) {
			$interfaces = explode(",", $config['dnsmasq']['interface']);
			foreach ($interfaces as $interface) {
				$if = get_real_interface($interface);
				if (does_interface_exist($if)) {
					$laddr = get_interface_ip($interface);
					if (is_ipaddrv4($laddr)) {
						$listen_addresses .= " --listen-address={$laddr} ";
					}
					$laddr6 = get_interface_ipv6($interface);
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
						/*
						 * XXX: Since dnsmasq does not support link-local address
						 * with scope specified. These checks are being done.
						 */
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
							$tmpaddrll6 = explode("%", $laddr6);
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
						} else {
							$listen_addresses .= " --listen-address={$laddr6} ";
						}
					}
				}
			}
			if (!empty($listen_addresses)) {
				$args .= " {$listen_addresses} ";
				if (isset($config['dnsmasq']['strictbind'])) {
					$args .= " --bind-interfaces ";
				}
			}
		}

		/* If selected, then first forward reverse lookups for private IPv4 addresses to nowhere. */
		/* Only make entries for reverse domains that do not have a matching domain override. */
		if (isset($config['dnsmasq']['no_private_reverse'])) {
			/* Note: Carrier Grade NAT (CGN) addresses 100.64.0.0/10 are intentionally not here. */
			/* End-users should not be aware of CGN addresses, so reverse lookups for these should not happen. */
			/* Just the pfSense WAN might get a CGN address from an ISP. */

			// Build an array of domain overrides to help in checking for matches.
			$override_a = array();
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
					$override_a[$override['domain']] = "y";
				}
			}

			// Build an array of the private reverse lookup domain names
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
			}

			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
			foreach ($reverse_domain_a as $reverse_domain) {
				if (!isset($override_a[$reverse_domain])) {
					$args .= " --server=/$reverse_domain/ ";
				}
			}
			unset($override_a);
			unset($reverse_domain_a);
		}

		/* Setup forwarded domains */
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
				if ($override['ip'] == "!") {
					$override[ip] = "";
				}
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
			}
		}

		/* Allow DNS Rebind for forwarded domains */
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
				}
			}
		}

		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
		}

		if (isset($config['dnsmasq']['strict_order'])) {
			$args .= " --strict-order ";
		}

		if (isset($config['dnsmasq']['domain_needed'])) {
			$args .= " --domain-needed ";
		}

		if ($config['dnsmasq']['custom_options']) {
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
				$args .= " " . escapeshellarg("--{$c}");
				$p = explode('=', $c);
				if (array_key_exists($p[0], $standard_args)) {
					unset($standard_args[$p[0]]);
				}
			}
		}
		$args .= ' ' . implode(' ', array_values($standard_args));

		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
		//log_error("dnsmasq command: {$cmd}");
		mwexec_bg($cmd);
		unset($args);

		system_dhcpleases_configure();

		if (platform_booting()) {
			echo gettext("done.") . "\n";
		}
	}

	if (!platform_booting() && $restart_dhcp) {
		if (services_dhcpd_configure() != 0) {
			$return = 1;
		}
	}

	return $return;
}

function services_unbound_configure($restart_dhcp = true) {
	global $config, $g;
	$return = 0;

	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_unbound_configure() being called $mt\n";
	}

	if (isset($config['unbound']['enable'])) {
		require_once('/etc/inc/unbound.inc');

		/* Stop Unbound using TERM */
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
		}

		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
		for ($i=1; $i <= 30; $i++) {
			if (is_process_running('unbound')) {
				sleep(1);
			}
		}

		if (platform_booting()) {
			echo gettext("Starting DNS Resolver...");
		} else {
			sleep(1);
		}

		/* generate hosts file */
		if (system_hosts_generate() != 0) {
			$return = 1;
		}

		sync_unbound_service();
		if (platform_booting()) {
			echo gettext("done.") . "\n";
		}

		system_dhcpleases_configure();
	} else {
		/* kill Unbound since it should not be enabled */
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
		}
	}

	if (!platform_booting() && $restart_dhcp) {
		if (services_dhcpd_configure() != 0) {
			$return = 1;
		}
	}

	return $return;
}

function services_snmpd_configure() {
	global $config, $g;
	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_snmpd_configure() being called $mt\n";
	}

	/* kill any running snmpd */
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
	sleep(2);
	if (is_process_running("bsnmpd")) {
		mwexec("/usr/bin/killall bsnmpd", true);
	}

	if (isset($config['snmpd']['enable'])) {

		if (platform_booting()) {
			echo gettext("Starting SNMP daemon... ");
		}

		/* Make sure a printcap file exists or else bsnmpd will log errors. See https://redmine.pfsense.org/issues/6838 */
		if (!file_exists('/etc/printcap')) {
			@file_put_contents('/etc/printcap', "# Empty file to prevent bsnmpd from logging errors.\n");
		}

		/* generate snmpd.conf */
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
		if (!$fd) {
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
			return 1;
		}


		$snmpdconf = <<<EOD
location := "{$config['snmpd']['syslocation']}"
contact := "{$config['snmpd']['syscontact']}"
read := "{$config['snmpd']['rocommunity']}"

EOD;

/* No docs on what write strings do there so disable for now.
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
			$snmpdconf .= <<<EOD
# write string
write := "{$config['snmpd']['rwcommunity']}"

EOD;
		}
*/


		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
			$snmpdconf .= <<<EOD
# SNMP Trap support.
traphost := {$config['snmpd']['trapserver']}
trapport := {$config['snmpd']['trapserverport']}
trap := "{$config['snmpd']['trapstring']}"


EOD;
		}

		$sysDescr = "{$g['product_name']} " . php_uname("n") .
			" {$g['product_version']} {$g['platform']} " . php_uname("s") .
			" " . php_uname("r") . " " . php_uname("m");

		$snmpdconf .= <<<EOD
system := 1     # pfSense
%snmpd
sysDescr			= "{$sysDescr}"
begemotSnmpdDebugDumpPdus       = 2
begemotSnmpdDebugSyslogPri      = 7
begemotSnmpdCommunityString.0.1 = $(read)

EOD;

/* No docs on what write strings do there so disable for now.
		if (isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
			$snmpdconf .= <<<EOD
begemotSnmpdCommunityString.0.2 = $(write)

EOD;
		}
*/


		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
			$snmpdconf .= <<<EOD
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)

EOD;
		}


		$snmpdconf .= <<<EOD
begemotSnmpdCommunityDisable    = 1

EOD;

		$bind_to_ips = array();
		if (isset($config['snmpd']['bindip'])) {
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
				if (is_ipaddr($bind_to_ip)) {
					$bind_to_ips[] = $bind_to_ip;
				} else {
					$if = get_real_interface($bind_to_ip);
					if (does_interface_exist($if)) {
						$bindip = get_interface_ip($bind_to_ip);
						if (is_ipaddr($bindip)) {
							$bind_to_ips[] = $bindip;
						}
					}
				}
			}
		}
		if (!count($bind_to_ips)) {
			$bind_to_ips = array("0.0.0.0");
		}

		if (is_port($config['snmpd']['pollport'])) {
			foreach ($bind_to_ips as $bind_to_ip) {
				$snmpdconf .= <<<EOD
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1

EOD;

			}
		}

		$snmpdconf .= <<<EOD
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4

# These are bsnmp macros not php vars.
sysContact      = $(contact)
sysLocation     = $(location)
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)

snmpEnableAuthenTraps = 2

EOD;

		if (is_array($config['snmpd']['modules'])) {
			if (isset($config['snmpd']['modules']['mibii'])) {
			$snmpdconf .= <<<EOD
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"

EOD;
			}

			if (isset($config['snmpd']['modules']['netgraph'])) {
				$snmpdconf .= <<<EOD
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
%netgraph
begemotNgControlNodeName = "snmpd"

EOD;
			}

			if (isset($config['snmpd']['modules']['pf'])) {
				$snmpdconf .= <<<EOD
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"

EOD;
			}

			if (isset($config['snmpd']['modules']['hostres'])
			    && !(($specplatform['name'] == 'VMware') && (file_exists('/dev/cd0')))) {
				$snmpdconf .= <<<EOD
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"

EOD;
			}

			if (isset($config['snmpd']['modules']['bridge'])) {
				$snmpdconf .= <<<EOD
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
# config must end with blank line

EOD;
			}
			if (isset($config['snmpd']['modules']['ucd'])) {
				$snmpdconf .= <<<EOD
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"

EOD;
			}
			if (isset($config['snmpd']['modules']['regex'])) {
				$snmpdconf .= <<<EOD
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"

EOD;
			}
		}

		fwrite($fd, $snmpdconf);
		fclose($fd);
		unset($snmpdconf);

		/* run bsnmpd */
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
			" -p {$g['varrun_path']}/snmpd.pid");

		if (platform_booting()) {
			echo gettext("done.") . "\n";
		}
	}

	return 0;
}

function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
	global $config, $g;
	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "services_dnsupdate_process() being called $mt\n";
	}

	/* Dynamic DNS updating active? */
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
		return 0;
	}

	$notify_text = "";
	$gwgroups = return_gateway_groups_array();
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
		if (!isset($dnsupdate['enable'])) {
			continue;
		}
		/*
		 * If it's using a gateway group, check if interface is
		 * the active gateway for that group
		 */
		$group_int = '';
		if (is_array($gwgroups[$dnsupdate['interface']])) {
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
			} else {
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
			}
		}
		if (!empty($int) && ($int != $dnsupdate['interface']) && ($int != $group_int)) {
			continue;
		}
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
			continue;
		}

		/* determine interface name */
		$if = get_failover_interface($dnsupdate['interface']);

		if (isset($dnsupdate['usepublicip'])) {
			$wanip = dyndnsCheckIP($if);
			$bindip = get_interface_ip($if);
		} else {
			$wanip = get_interface_ip($if);
			$bindip = $wanip;
		}

		$wanipv6 = get_interface_ipv6($if);
		$cacheFile = $g['conf_path'] .
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
		    escapeshellarg($dnsupdate['host']) .
		    "_{$dnsupdate['server']}.cache";
		$cacheFilev6 = $g['conf_path'] .
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
		    escapeshellarg($dnsupdate['host']) .
		    "_{$dnsupdate['server']}_v6.cache";
		$currentTime = time();

		if (!$wanip && !$wanipv6) {
			continue;
		}

		$keyname = $dnsupdate['keyname'];
		/* trailing dot */
		if (substr($keyname, -1) != ".") {
			$keyname .= ".";
		}

		$hostname = $dnsupdate['host'];
		/* trailing dot */
		if (substr($hostname, -1) != ".") {
			$hostname .= ".";
		}

		/*
		 * write private key file
		 * this is dumb - public and private keys are the same for
		 * HMAC-MD5, but nsupdate insists on having both
		 */
		$fd = fopen($g['varetc_path'] .
		    "/K{$i}{$keyname}+157+00000.private", "w");
		$privkey = <<<EOD
Private-key-format: v1.2
Algorithm: 157 (HMAC)
Key: {$dnsupdate['keydata']}

EOD;
		fwrite($fd, $privkey);
		fclose($fd);

		/* write public key file */
		if ($dnsupdate['keytype'] == "zone") {
			$flags = 257;
			$proto = 3;
		} else if ($dnsupdate['keytype'] == "host") {
			$flags = 513;
			$proto = 3;
		} else if ($dnsupdate['keytype'] == "user") {
			$flags = 0;
			$proto = 2;
		}

		$fd = fopen($g['varetc_path'] .
		    "/K{$i}{$keyname}+157+00000.key", "w");
		fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 " .
		    "{$dnsupdate['keydata']}\n");
		fclose($fd);

		/* generate update instructions */
		$upinst = "";
		if (!empty($dnsupdate['server'])) {
			$upinst .= "server {$dnsupdate['server']}\n";
		}

		$cachedipv4 = '';
		$cacheTimev4 = 0;
		if (file_exists($cacheFile)) {
			list($cachedipv4, $cacheTimev4) = explode("|",
			    file_get_contents($cacheFile));
		}
		$cachedipv6 = '';
		$cacheTimev6 = 0;
		if (file_exists($cacheFilev6)) {
			list($cachedipv6, $cacheTimev6) = explode("|",
			    file_get_contents($cacheFilev6));
		}

		// 25 Days
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
		$need_update = false;

		/* Update IPv4 if we have it. */
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
			if (($wanip != $cachedipv4) || $forced ||
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
				$upinst .= "update delete " .
				    "{$dnsupdate['host']}. A\n";
				$upinst .= "update add {$dnsupdate['host']}. " .
				    "{$dnsupdate['ttl']} A {$wanip}\n";
				$upinst .= "local {$bindip}\n";
				$need_update = true;
			} else {
				log_error(sprintf(gettext(
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
				    $dnsupdate['host']));
			}
		} else {
			@unlink($cacheFile);
			unset($cacheFile);
		}

		/* Update IPv6 if we have it. */
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
			if (($wanipv6 != $cachedipv6) || $forced ||
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
				$upinst .= "update delete " .
				    "{$dnsupdate['host']}. AAAA\n";
				$upinst .= "update add {$dnsupdate['host']}. " .
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
				$need_update = true;
			} else {
				log_error(sprintf(gettext(
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
				    $dnsupdate['host']));
			}
		} else {
			@unlink($cacheFilev6);
			unset($cacheFilev6);
		}

		$upinst .= "\n";	/* mind that trailing newline! */

		if (!$need_update) {
			continue;
		}

		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}",
		    $upinst);
		unset($upinst);
		/* invoke nsupdate */
		$cmd = "/usr/local/bin/nsupdate -k " .
		    "{$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";

		if (isset($dnsupdate['usetcp'])) {
			$cmd .= " -v";
		}

		$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";

		if (mwexec($cmd) == 0) {
			if (!empty($cacheFile)) {
				@file_put_contents($cacheFile,
				    "{$wanip}|{$currentTime}");
				log_error(sprintf(gettext(
				    'phpDynDNS: updating cache file %1$s: %2$s'),
				    $cacheFile, $wanip));
				$notify_text .= sprintf(gettext(
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
				    $dnsupdate['host'],
				    convert_real_interface_to_friendly_descr($if),
				    $if, $wanip) . "\n";
			}
			if (!empty($cacheFilev6)) {
				@file_put_contents($cacheFilev6,
				    "{$wanipv6}|{$currentTime}");
				log_error(sprintf(gettext(
				    'phpDynDNS: updating cache file %1$s: %2$s'),
				    $cacheFilev6, $wanipv6));
				$notify_text .= sprintf(gettext(
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
				    $dnsupdate['host'],
				    convert_real_interface_to_friendly_descr($if),
				    $if, $wanipv6) . "\n";
			}
		} else {
			if (!empty($cacheFile)) {
				log_error(sprintf(gettext(
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
				    $dnsupdate['host'], $wanip));
			}
			if (!empty($cacheFilev6)) {
				log_error(sprintf(gettext(
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
				    $dnsupdate['host'], $wanipv6));
			}
		}
		unset($cmd);
	}

	if (!empty($notify_text)) {
		notify_all_remote($notify_text);
	}

	return 0;
}

/* configure cron service */
function configure_cron() {
	global $g, $config;

	/* preserve existing crontab entries */
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

	for ($i = 0; $i < count($crontab_contents); $i++) {
		$cron_item =& $crontab_contents[$i];
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
			array_splice($crontab_contents, $i - 1);
			break;
		}
	}
	$crontab_contents = implode("\n", $crontab_contents) . "\n";


	if (is_array($config['cron']['item'])) {
		$crontab_contents .= "#\n";
		$crontab_contents .= "# pfSense specific crontab entries\n";
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
		$crontab_contents .= "#\n";

		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
			$http_proxy = $config['system']['proxyurl'];
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
				$http_proxy .= ':' . $config['system']['proxyport'];
			}
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";

			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
			}
		}

		foreach ($config['cron']['item'] as $item) {
			$crontab_contents .= "\n{$item['minute']}\t";
			$crontab_contents .= "{$item['hour']}\t";
			$crontab_contents .= "{$item['mday']}\t";
			$crontab_contents .= "{$item['month']}\t";
			$crontab_contents .= "{$item['wday']}\t";
			$crontab_contents .= "{$item['who']}\t";
			$crontab_contents .= "{$item['command']}";
		}

		$crontab_contents .= "\n#\n";
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
		$crontab_contents .= "#\n\n";
	}

	/* please maintain the newline at the end of file */
	file_put_contents("/etc/crontab", $crontab_contents);
	unset($crontab_contents);

	/* make sure that cron is running and start it if it got killed somehow */
	if (!is_process_running("cron")) {
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
	} else {
	/* do a HUP kill to force sync changes */
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
	}

}

function upnp_action ($action) {
	global $g, $config;
	switch ($action) {
		case "start":
			if (file_exists('/var/etc/miniupnpd.conf')) {
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
			}
			break;
		case "stop":
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
			}
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
			break;
		case "restart":
			upnp_action('stop');
			upnp_action('start');
			break;
	}
}

function upnp_start() {
	global $config;

	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
		return;
	}

	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
		echo gettext("Starting UPnP service... ");
		require_once('/usr/local/pkg/miniupnpd.inc');
		sync_package_miniupnpd();
		echo "done.\n";
	}
}

function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root", $write_config = true) {
	global $config, $g;

	$is_installed = false;
	$cron_changed = true;
	$change_message = "";

	if (!is_array($config['cron'])) {
		$config['cron'] = array();
	}
	if (!is_array($config['cron']['item'])) {
		$config['cron']['item'] = array();
	}

	$x = 0;
	foreach ($config['cron']['item'] as $item) {
		if (strstr($item['command'], $command)) {
			$is_installed = true;
			break;
		}
		$x++;
	}

	if ($active) {
		$cron_item = array();
		$cron_item['minute'] = $minute;
		$cron_item['hour'] = $hour;
		$cron_item['mday'] = $monthday;
		$cron_item['month'] = $month;
		$cron_item['wday'] = $weekday;
		$cron_item['who'] = $who;
		$cron_item['command'] = $command;
		if (!$is_installed) {
			$config['cron']['item'][] = $cron_item;
			$change_message = "Installed cron job for %s";
		} else {
			if ($config['cron']['item'][$x] == $cron_item) {
				$cron_changed = false;
			} else {
				$config['cron']['item'][$x] = $cron_item;
				$change_message = "Updated cron job for %s";
			}
		}
	} else {
		if ($is_installed == true) {
			array_splice($config['cron']['item'], $x, 1);
			$change_message = "Removed cron job for %s";
		} else {
			$cron_changed = false;
		}
	}

	if ($cron_changed) {
		/* Optionally write the configuration if this function made changes.
		 * Performing a write_config() in this way can have unintended side effects. See #7146
		 * Base system instances of this function do not need to write, packages may.
		 */
		if ($write_config) {
			write_config(sprintf(gettext($change_message), $command));
		}
		configure_cron();
	}
}

?>
OpenPOWER on IntegriCloud