summaryrefslogtreecommitdiffstats
path: root/src/etc/inc/system.inc
blob: 6b7d19fff3e7dc2baa934dbb9ca6be6ca8780a30 (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
<?php
/*
	system.inc

	part of pfSense (https://www.pfsense.org)
	Copyright (c) 2004-2016 Electric Sheep Fencing, LLC.
	All rights reserved.

	originally part of m0n0wall (http://m0n0.ch/wall)
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in
	   the documentation and/or other materials provided with the
	   distribution.

	3. All advertising materials mentioning features or use of this software
	   must display the following acknowledgment:
	   "This product includes software developed by the pfSense Project
	   for use in the pfSense® software distribution. (http://www.pfsense.org/).

	4. The names "pfSense" and "pfSense Project" must not be used to
	   endorse or promote products derived from this software without
	   prior written permission. For written permission, please contact
	   coreteam@pfsense.org.

	5. Products derived from this software may not be called "pfSense"
	   nor may "pfSense" appear in their names without prior written
	   permission of the Electric Sheep Fencing, LLC.

	6. Redistributions of any form whatsoever must retain the following
	   acknowledgment:

	"This product includes software developed by the pfSense Project
	for use in the pfSense software distribution (http://www.pfsense.org/).

	THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
	EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
	ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
	NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
*/

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

	if (is_process_running("powerd")) {
		exec("/usr/bin/killall powerd");
	}
	if (isset($config['system']['powerd_enable'])) {
		if ($g["platform"] == "nanobsd") {
			exec("/sbin/kldload cpufreq");
		}

		$ac_mode = "hadp";
		if (!empty($config['system']['powerd_ac_mode'])) {
			$ac_mode = $config['system']['powerd_ac_mode'];
		}

		$battery_mode = "hadp";
		if (!empty($config['system']['powerd_battery_mode'])) {
			$battery_mode = $config['system']['powerd_battery_mode'];
		}

		$normal_mode = "hadp";
		if (!empty($config['system']['powerd_normal_mode'])) {
			$normal_mode = $config['system']['powerd_normal_mode'];
		}

		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode");
	}
}

function get_default_sysctl_value($id) {
	global $sysctls;

	if (isset($sysctls[$id])) {
		return $sysctls[$id];
	}
}

function get_sysctl_descr($sysctl) {
	unset($output);
	$_gb = exec("/sbin/sysctl -nd {$sysctl}", $output);

	return $output[0];
}

function system_get_sysctls() {
	global $config, $sysctls;

	$disp_sysctl = array();
	$disp_cache = array();
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
		foreach ($config['sysctl']['item'] as $id => $tunable) {
			if ($tunable['value'] == "default") {
				$value = get_default_sysctl_value($tunable['tunable']);
			} else {
				$value = $tunable['value'];
			}

			$disp_sysctl[$id] = $tunable;
			$disp_sysctl[$id]['modified'] = true;
			$disp_cache[$tunable['tunable']] = 'set';
		}
	}

	foreach ($sysctls as $sysctl => $value) {
		if (isset($disp_cache[$sysctl])) {
			continue;
		}

		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
	}
	unset($disp_cache);
	return $disp_sysctl;
}

function activate_sysctls() {
	global $config, $g, $sysctls;

	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
		foreach ($config['sysctl']['item'] as $tunable) {
			if ($tunable['value'] == "default") {
				$value = get_default_sysctl_value($tunable['tunable']);
			} else {
				$value = $tunable['value'];
			}

			$sysctls[$tunable['tunable']] = $value;
		}
	}

	set_sysctl($sysctls);
}

function system_resolvconf_generate($dynupdate = false) {
	global $config, $g;

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

	$syscfg = $config['system'];

	if ((((isset($config['dnsmasq']['enable'])) &&
	      (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
	      (empty($config['dnsmasq']['interface']) ||
	       in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
	     ((isset($config['unbound']['enable'])) &&
	      (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
	      (empty($config['unbound']['active_interface']) ||
	       in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
	       in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
	     (!isset($config['system']['dnslocalhost']))) {
		$resolvconf .= "nameserver 127.0.0.1\n";
	}

	if (isset($syscfg['dnsallowoverride'])) {
		/* get dynamically assigned DNS servers (if any) */
		$ns = array_unique(get_searchdomains());
		foreach ($ns as $searchserver) {
			if ($searchserver) {
				$resolvconf .= "search {$searchserver}\n";
			}
		}
		$ns = array_unique(get_nameservers());
		foreach ($ns as $nameserver) {
			if ($nameserver) {
				$resolvconf .= "nameserver $nameserver\n";
			}
		}
	} else {
		$ns = array();
		// Do not create blank search/domain lines, it can break tools like dig.
		if ($syscfg['domain']) {
			$resolvconf .= "search {$syscfg['domain']}\n";
		}
	}
	if (is_array($syscfg['dnsserver'])) {
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
				$resolvconf .= "nameserver $sys_dnsserver\n";
			}
		}
	}

	// Add EDNS support
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
		$resolvconf .= "options edns0\n";
	}

	$dnslock = lock('resolvconf', LOCK_EX);

	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
	if (!$fd) {
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
		unlock($dnslock);
		return 1;
	}

	fwrite($fd, $resolvconf);
	fclose($fd);

	// Prevent resolvconf(8) from rewriting our resolv.conf
	$fd = fopen("{$g['varetc_path']}/resolvconf.conf", "w");
	if (!$fd) {
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
		return 1;
	}
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
	fclose($fd);

	if (!platform_booting()) {
		/* restart dhcpd (nameservers may have changed) */
		if (!$dynupdate) {
			services_dhcpd_configure();
		}
	}

	/* setup static routes for DNS servers. */
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
		/* setup static routes for dns servers */
		$dnsgw = "dns{$dnscounter}gw";
		if (isset($config['system'][$dnsgw])) {
			if (empty($config['system'][$dnsgw]) ||
			    $config['system'][$dnsgw] == "none") {
				continue;
			}
			$gwname = $config['system'][$dnsgw];
			$gatewayip = lookup_gateway_ip_by_name($gwname);
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
			/* dns server array starts at 0 */
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];

			if (is_ipaddr($gatewayip)) {
				$cmd = 'change';
			} else {
				/* Remove old route when disable gw */
				$cmd = 'delete';
				$gatewayip = '';
			}

			mwexec("/sbin/route {$cmd} -host {$inet6}{$dnsserver} {$gatewayip}");
			if (isset($config['system']['route-debug'])) {
				$mt = microtime();
				log_error("ROUTING debug: $mt - route {$cmd} -host {$inet6}{$dnsserver} {$gatewayip}");
			}
		}
	}

	unlock($dnslock);

	return 0;
}

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

	$master_list = array();

	// Read in dhclient nameservers
	$search_list = glob("/var/etc/searchdomain_*");
	if (is_array($search_list)) {
		foreach ($search_list as $fdns) {
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
			if (!is_array($contents)) {
				continue;
			}
			foreach ($contents as $dns) {
				if (is_hostname($dns)) {
					$master_list[] = $dns;
				}
			}
		}
	}

	return $master_list;
}

function get_nameservers() {
	global $config, $g;
	$master_list = array();

	// Read in dhclient nameservers
	$dns_lists = glob("/var/etc/nameserver_*");
	if (is_array($dns_lists)) {
		foreach ($dns_lists as $fdns) {
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
			if (!is_array($contents)) {
				continue;
			}
			foreach ($contents as $dns) {
				if (is_ipaddr($dns)) {
					$master_list[] = $dns;
				}
			}
		}
	}

	// Read in any extra nameservers
	if (file_exists("/var/etc/nameservers.conf")) {
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
		if (is_array($dns_s)) {
			foreach ($dns_s as $dns) {
				if (is_ipaddr($dns)) {
					$master_list[] = $dns;
				}
			}
		}
	}

	return $master_list;
}

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

	$syscfg = $config['system'];
	// prefer dnsmasq for hosts generation where it's enabled. It relies
	// on hosts for name resolution of its overrides, unbound does not.
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
		$dnsmasqcfg = $config['dnsmasq'];
	} else {
		$dnsmasqcfg = $config['unbound'];
	}

	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
	$hosts .= "::1		localhost localhost.{$syscfg['domain']}\n";
	$lhosts = "";
	$dhosts = "";

	if ($config['interfaces']['lan']) {
		$cfgip = get_interface_ip("lan");
		if (is_ipaddr($cfgip)) {
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
		}
		$cfgipv6 = get_interface_ipv6("lan");
		if (is_ipaddrv6($cfgipv6)) {
			$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
		}
	} else {
		$sysiflist = get_configured_interface_list();
		$hosts_if_found = false;
		foreach ($sysiflist as $sysif) {
			if (!interface_has_gateway($sysif)) {
				$cfgip = get_interface_ip($sysif);
				if (is_ipaddr($cfgip)) {
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
					$hosts_if_found = true;
				}
				$cfgipv6 = get_interface_ipv6($sysif);
				if (is_ipaddrv6($cfgipv6)) {
					$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
					$hosts_if_found = true;
				}
				if ($hosts_if_found == true) {
					break;
				}
			}
		}
	}

	if (isset($dnsmasqcfg['enable'])) {
		if (!is_array($dnsmasqcfg['hosts'])) {
			$dnsmasqcfg['hosts'] = array();
		}

		foreach ($dnsmasqcfg['hosts'] as $host) {
			if ($host['host'] || $host['host'] == "0") {
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
			} else {
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
			}
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item'])) {
				continue;
			}
			foreach ($host['aliases']['item'] as $alias) {
				if ($alias['host'] || $alias['host'] == "0") {
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
				} else {
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
				}
			}
		}
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
				if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) {
					foreach ($dhcpifconf['staticmap'] as $host) {
						if ($host['ipaddr'] && $host['hostname'] && $host['domain']) {
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
						} else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain']) {
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
						} else if ($host['ipaddr'] && $host['hostname']) {
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
						}
					}
				}
			}
		}
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf) {
				if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) {
					$isdelegated = $config['interfaces'][$dhcpif]['ipaddrv6'] == 'track6';
					foreach ($dhcpifconf['staticmap'] as $host) {
						$ipaddrv6 = $host['ipaddrv6'];
						if ($ipaddrv6 && $host['hostname']) {
							if ($isdelegated) {
								$trackifname = $config['interfaces'][$dhcpif]['track6-interface'];
								$trackcfg = $config['interfaces'][$trackifname];
								$pdlen = 64 - $trackcfg['dhcp6-ia-pd-len'];
								$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $pdlen);
							}
							if ($host['domain']) {
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
							} else if ($dhcpifconf['domain']) {
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
							} else {
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
							}
						}
					}
				}
			}
		}

		if (isset($dnsmasqcfg['dhcpfirst'])) {
			$hosts .= $dhosts . $lhosts;
		} else {
			$hosts .= $lhosts . $dhosts;
		}
	}

	/*
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be
	 * killed before writing to hosts files.
	 */
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
	}
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
	if (!$fd) {
		log_error(gettext("Error: cannot open hosts file in system_hosts_generate()."));
		return 1;
	}
	fwrite($fd, $hosts);
	fclose($fd);

	if (isset($config['unbound']['enable'])) {
		require_once("unbound.inc");
		unbound_hosts_generate();
	}

	return 0;
}

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

	/* Start the monitoring process for dynamic dhcpclients. */
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
		/* Make sure we do not error out */
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
		}

		if (isset($config['unbound']['enable'])) {
			$dns_pid = "unbound.pid";
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
		} else {
			$dns_pid = "dnsmasq.pid";
			$unbound_conf = "";
		}

		$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
		if (isvalidpid($pidfile)) {
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
			if (intval($retval) == 0) {
				sigkillbypid($pidfile, "HUP");
				return;
			} else {
				sigkillbypid($pidfile, "TERM");
			}
		}

		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
		if (is_process_running("dhcpleases")) {
			sigkillbyname('dhcpleases', "TERM");
		}
		@unlink($pidfile);
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['varetc_path']}/hosts");
	} else {
		sigkillbypid($pidfile, "TERM");
		@unlink($pidfile);
	}
}

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

	$syscfg = $config['system'];

	/* set hostname */
	$status = mwexec("/bin/hostname " .
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));

	/* Setup host GUID ID.  This is used by ZFS. */
	mwexec("/etc/rc.d/hostid start");

	return $status;
}

function system_routing_configure($interface = "") {
	global $config, $g;

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

	$gatewayip = "";
	$interfacegw = "";
	$gatewayipv6 = "";
	$interfacegwv6 = "";
	$foundgw = false;
	$foundgwv6 = false;
	/* tack on all the hard defined gateways as well */
	if (is_array($config['gateways']['gateway_item'])) {
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
		foreach	($config['gateways']['gateway_item'] as $gateway) {
			if (isset($gateway['defaultgw'])) {
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
					if (strpos($gateway['gateway'], ":")) {
						continue;
					}
					if ($gateway['gateway'] == "dynamic") {
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
					}
					$gatewayip = $gateway['gateway'];
					$interfacegw = $gateway['interface'];
					if (!empty($gateway['interface'])) {
						$defaultif = get_real_interface($gateway['interface']);
						if ($defaultif) {
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
						}
					}
					$foundgw = true;
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
					if ($gateway['gateway'] == "dynamic") {
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
					}
					$gatewayipv6 = $gateway['gateway'];
					$interfacegwv6 = $gateway['interface'];
					if (!empty($gateway['interface'])) {
						$defaultifv6 = get_real_interface($gateway['interface']);
						if ($defaultifv6) {
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
						}
					}
					$foundgwv6 = true;
				}
			}
			if ($foundgw === true && $foundgwv6 === true) {
				break;
			}
		}
	}
	if ($foundgw == false) {
		$defaultif = get_real_interface("wan");
		$interfacegw = "wan";
		$gatewayip = get_interface_gateway("wan");
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
	}
	if ($foundgwv6 == false) {
		$defaultifv6 = get_real_interface("wan");
		$interfacegwv6 = "wan";
		$gatewayipv6 = get_interface_gateway_v6("wan");
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
	}
	$dont_add_route = false;
	/* if OLSRD is enabled, allow WAN to house DHCP. */
	if (is_array($config['installedpackages']['olsrd'])) {
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
			if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
				$dont_add_route = true;
				log_error(gettext("Not adding default route because OLSR dynamic gateway is enabled."));
				break;
			}
		}
	}

	$gateways_arr = return_gateways_array(false, true);
	foreach ($gateways_arr as $gateway) {
		// setup static interface routes for nonlocal gateways
		if (isset($gateway["nonlocalgateway"])) {
			$srgatewayip = $gateway['gateway'];
			$srinterfacegw = $gateway['interface'];
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
				$cmd = "/sbin/route change {$inet} " . escapeshellarg($srgatewayip) . " ";
				mwexec($cmd . "-iface " . escapeshellarg($srinterfacegw));
				if (isset($config['system']['route-debug'])) {
					$mt = microtime();
					log_error("ROUTING debug: $mt - $cmd -iface $srinterfacegw ");
				}
			}
		}
	}

	if ($dont_add_route == false) {
		if (!empty($interface) && $interface != $interfacegw) {
			;
		} else if (is_ipaddrv4($gatewayip)) {
			log_error(sprintf(gettext("ROUTING: setting default route to %s"), $gatewayip));
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
		}

		if (!empty($interface) && $interface != $interfacegwv6) {
			;
		} else if (is_ipaddrv6($gatewayipv6)) {
			$ifscope = "";
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
				$ifscope = "%{$defaultifv6}";
			}
			log_error(sprintf(gettext("ROUTING: setting IPv6 default route to %s"), $gatewayipv6 . $ifscope));
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
		}
	}

	system_staticroutes_configure($interface, false);

	return 0;
}

function system_staticroutes_configure($interface = "", $update_dns = false) {
	global $config, $g, $aliastable;

	$filterdns_list = array();

	$static_routes = get_staticroutes(false, true);
	if (count($static_routes)) {
		$gateways_arr = return_gateways_array(false, true);

		foreach ($static_routes as $rtent) {
			if (empty($gateways_arr[$rtent['gateway']])) {
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
				continue;
			}
			$gateway = $gateways_arr[$rtent['gateway']];
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
				continue;
			}

			$gatewayip = $gateway['gateway'];
			$interfacegw = $gateway['interface'];

			$blackhole = "";
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3))) {
				$blackhole = "-blackhole";
			}

			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
				continue;
			}

			$dnscache = array();
			if ($update_dns === true) {
				if (is_subnet($rtent['network'])) {
					continue;
				}
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
				if (empty($dnscache)) {
					continue;
				}
			}

			if (is_subnet($rtent['network'])) {
				$ips = array($rtent['network']);
			} else {
				if (!isset($rtent['disabled'])) {
					$filterdns_list[] = $rtent['network'];
				}
				$ips = add_hostname_to_watch($rtent['network']);
			}

			foreach ($dnscache as $ip) {
				if (in_array($ip, $ips)) {
					continue;
				}
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
				if (isset($config['system']['route-debug'])) {
					$mt = microtime();
					log_error("ROUTING debug: $mt - route delete $ip ");
				}
			}

			if (isset($rtent['disabled'])) {
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
				foreach ($ips as $ip) {
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
					if (isset($config['system']['route-debug'])) {
						$mt = microtime();
						log_error("ROUTING debug: $mt - route delete $ip ");
					}
				}
				continue;
			}

			foreach ($ips as $ip) {
				if (is_ipaddrv4($ip)) {
					$ip .= "/32";
				}
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes

				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");

				$cmd = "/sbin/route change {$inet} {$blackhole} " . escapeshellarg($ip) . " ";

				if (is_subnet($ip)) {
					if (is_ipaddr($gatewayip)) {
						mwexec($cmd . escapeshellarg($gatewayip));
						if (isset($config['system']['route-debug'])) {
							$mt = microtime();
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
						}
					} else if (!empty($interfacegw)) {
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
						if (isset($config['system']['route-debug'])) {
							$mt = microtime();
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
						}
					}
				}
			}
		}
		unset($gateways_arr);
	}
	unset($static_routes);

	if ($update_dns === false) {
		if (count($filterdns_list)) {
			$interval = 60;
			$hostnames = "";
			array_unique($filterdns_list);
			foreach ($filterdns_list as $hostname) {
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
			}
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
			unset($hostnames);

			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
			} else {
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
			}
		} else {
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
		}
	}
	unset($filterdns_list);

	return 0;
}

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

	set_sysctl(array(
		"net.inet.ip.forwarding" => "1",
		"net.inet6.ip6.forwarding" => "1"
	));

	return;
}

function system_syslogd_fixup_server($server) {
	/* If it's an IPv6 IP alone, encase it in brackets */
	if (is_ipaddrv6($server)) {
		return "[$server]";
	} else {
		return $server;
	}
}

function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
	$facility .= " ".
	$remote_servers = "";
	$pad_to  = max(strlen($facility), 56);
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
	if (isset($syslogcfg['enable'])) {
		if ($syslogcfg['remoteserver']) {
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
		}
		if ($syslogcfg['remoteserver2']) {
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
		}
		if ($syslogcfg['remoteserver3']) {
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
		}
	}
	return $remote_servers;
}

function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
	global $config, $g;
	if ($restart_syslogd) {
		exec("/usr/bin/killall syslogd");
	}
	if (isset($config['system']['disablesyslogclog'])) {
		unlink($logfile);
		touch($logfile);
	} else {
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
	}
	if ($restart_syslogd) {
		system_syslogd_start();
	}
}

function clear_all_log_files($restart = false) {
	global $g;
	exec("/usr/bin/killall syslogd");

	$log_files = array("system", "filter", "dhcpd", "vpn", "pptps", "poes", "l2tps", "openvpn", "portalauth", "ipsec", "ppp", "relayd", "wireless", "nginx", "ntpd", "gateways", "resolver", "routing");
	foreach ($log_files as $lfile) {
		clear_log_file("{$g['varlog_path']}/{$lfile}.log", false);
	}

	if ($restart) {
		system_syslogd_start();
		killbyname("dhcpd");
		services_dhcpd_configure();
	}
	return;
}

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

	mwexec("/etc/rc.d/hostid start");

	$syslogcfg = $config['syslog'];

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

	// Which logging type are we using this week??
	if (isset($config['system']['disablesyslogclog'])) {
		$log_directive = "";
		$log_create_directive = "/usr/bin/touch ";
		$log_size = "";
	} else { // Defaults to CLOG
		$log_directive = "%";
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
	}

	$syslogd_extra = "";
	if (isset($syslogcfg)) {
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'pptps', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'olsrd', 'zebra', 'ospfd', 'bgpd', 'miniupnpd', 'filterlog');
		$syslogconf = "";
		if ($config['installedpackages']['package']) {
			foreach ($config['installedpackages']['package'] as $package) {
				if ($package['logging']) {
					array_push($separatelogfacilities, $package['logging']['facilityname']);
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
					}
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
				}
			}
		}
		$facilitylist = implode(',', array_unique($separatelogfacilities));
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
		}

		$syslogconf .= "!ntp,ntpd,ntpdate\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
		}

		$syslogconf .= "!ppp\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
		}

		$syslogconf .= "!pptps\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
		}

		$syslogconf .= "!poes\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
		}

		$syslogconf .= "!l2tps\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
		}

		$syslogconf .= "!charon,ipsec_starter\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
		}
		if (isset($syslogcfg['vpn'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		$syslogconf .= "!openvpn\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
		}
		if (isset($syslogcfg['vpn'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		$syslogconf .= "!dpinger\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
		}
		if (isset($syslogcfg['dpinger'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
		}

		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
		}
		if (isset($syslogcfg['dhcp'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		$syslogconf .= "!relayd\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
		}
		if (isset($syslogcfg['relayd'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		$syslogconf .= "!hostapd\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
		}
		if (isset($syslogcfg['hostapd'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		$syslogconf .= "!filterlog\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
		}

		if (isset($syslogcfg['filter'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		$syslogconf .= "!-{$facilitylist}\n";
		if (!isset($syslogcfg['disablelocallogging'])) {
			$syslogconf .= <<<EOD
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;news.err;local0.none;local3.none;local4.none;local7.none;security.*;auth.info;authpriv.info;daemon.info	{$log_directive}{$g['varlog_path']}/system.log
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
*.emerg								*

EOD;
		}
		if (isset($syslogcfg['vpn'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
		}
		if (isset($syslogcfg['portalauth'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
		}
		if (isset($syslogcfg['dhcp'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
		}
		if (isset($syslogcfg['system'])) {
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg;*.notice;kern.debug;lpr.info;mail.crit;news.err;local0.none;local3.none;local7.none;security.*;auth.info;authpriv.info;daemon.info");
		}
		if (isset($syslogcfg['logall'])) {
			// Make everything mean everything, including facilities excluded above.
			$syslogconf .= "!*\n";
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
		}

		if (isset($syslogcfg['zmqserver'])) {
				$syslogconf .= <<<EOD
*.*								^{$syslogcfg['zmqserver']}

EOD;
		}
		/* write syslog.conf */
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
			unset($syslogconf);
			return 1;
		}
		unset($syslogconf);

		// Ensure that the log directory exists
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run")) {
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
		}

		$sourceip = "";
		if (!empty($syslogcfg['sourceip'])) {
			if ($syslogcfg['ipproto'] == "ipv6") {
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
				if (!is_ipaddr($ifaddr)) {
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
				}
			} else {
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
				if (!is_ipaddr($ifaddr)) {
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
				}
			}
			if (is_ipaddr($ifaddr)) {
				$sourceip = "-b {$ifaddr}";
			}
		}

		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
	}

	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
		usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
	}

	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
		// if it still hasn't responded to the TERM, KILL it.
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
		usleep(100000);
	}


	$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");

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

	return $retval;
}

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

	if (!is_array($config['ca'])) {
		$config['ca'] = array();
	}
	$a_ca =& $config['ca'];
	if (!is_array($config['cert'])) {
		$config['cert'] = array();
	}
	$a_cert =& $config['cert'];
	log_error(gettext("Creating SSL Certificate for this host"));

	$cert = array();
	$cert['refid'] = uniqid();
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);

	$dn = array(
		'countryName' => "US",
		'stateOrProvinceName' => "State",
		'localityName' => "Locality",
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
		while ($ssl_err = openssl_error_string()) {
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
		}
		error_reporting($old_err_level);
		return null;
	}
	error_reporting($old_err_level);

	$a_cert[] = $cert;
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
	return $cert;
}

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

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

	chdir($g['www_path']);

	/* defaults */
	$portarg = "80";
	$crt = "";
	$key = "";
	$ca = "";

	/* non-standard port? */
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
		$portarg = "{$config['system']['webgui']['port']}";
	}

	if ($config['system']['webgui']['protocol'] == "https") {
		// Ensure that we have a webConfigurator CERT
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
			$cert = system_webgui_create_certificate();
		}
		$crt = base64_decode($cert['crt']);
		$key = base64_decode($cert['prv']);

		if (!$config['system']['webgui']['port']) {
			$portarg = "443";
		}
		$ca = ca_chain($cert);
	}

	/* generate nginx configuration */
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
		"cert.crt", "cert.key");

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

	sleep(1);

	@unlink("{$g['varrun_path']}/nginx-webConfigurator.pid");

	/* start nginx */
	$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-webConfigurator.conf");

	if (platform_booting()) {
		if ($res == 0) {
			echo gettext("done.") . "\n";
		} else {
			echo gettext("failed!") . "\n";
		}
	}

	return $res;
}

function system_generate_nginx_config($filename,
	$cert,
	$key,
	$ca,
	$pid_file,
	$port = 80,
	$document_root = "/usr/local/www/",
	$cert_location = "cert.crt",
	$key_location = "cert.key",
	$captive_portal = false) {

	global $config, $g;

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

	if ($captive_portal !== false) {
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
		$cp_hostcheck = "";
		foreach ($cp_interfaces as $cpint) {
			$cpint_ip = get_interface_ip($cpint);
			if (is_ipaddr($cpint_ip)) {
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
				$cp_hostcheck .= "\t\t}\n";
			}
		}
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
			$cp_hostcheck .= "\t\t}\n";
		}
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
		$cp_rewrite .= "\t\t}\n";

		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
		if (empty($maxprocperip)) {
			$maxprocperip = 10;
		}
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
	}

	if (empty($port)) {
		$nginx_port = "80";
	} else {
		$nginx_port = $port;
	}

	$memory = get_memory();
	$realmem = $memory[1];

	// Determine web GUI process settings and take into account low memory systems
	if ($realmem < 255) {
		$max_procs = 1;
	} else {
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
	}

	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
	if ($captive_portal !== false) {
		if ($realmem > 135 and $realmem < 256) {
			$max_procs += 1; // 2 worker processes
		} else if ($realmem > 255 and $realmem < 513) {
			$max_procs += 2; // 3 worker processes
		} else if ($realmem > 512) {
			$max_procs += 4; // 6 worker processes
		}
	}

	$nginx_config = <<<EOD
#
# nginx configuration file

pid {$g['varrun_path']}/{$pid_file};

user  root wheel;
worker_processes  {$max_procs};

EOD;

	if (!isset($config['syslog']['nolognginx'])) {
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
	}

	$nginx_config .= <<<EOD

events {
    worker_connections  1024;
}

http {
	include       /usr/local/etc/nginx/mime.types;
	default_type  application/octet-stream;
	add_header X-Frame-Options SAMEORIGIN;
	server_tokens off;

	sendfile        on;
	keepalive_timeout  65;

	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;

EOD;

	if ($captive_portal !== false) {
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
	}

	if ($cert <> "" and $key <> "") {
		$nginx_config .= "\n";
		$nginx_config .= "\tserver {\n";
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
		$nginx_config .= "\n";
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
		if ($captive_portal !== false) {
			// leave TLSv1.0 for CP for now for compatibility
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
		} else {
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
		}
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
		$nginx_config .= "\t\tssl_session_tickets off;\n";
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
	} else {
		$nginx_config .= "\n";
		$nginx_config .= "\tserver {\n";
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
	}

	$nginx_config .= <<<EOD

		client_max_body_size 200m;

		gzip on;
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;


EOD;

	if ($captive_portal !== false) {
		$nginx_config .= <<<EOD
$captive_portal_maxprocperip
$cp_hostcheck
$cp_rewrite
		log_not_found off;

EOD;

	}

	$nginx_config .= <<<EOD
		root "{$document_root}";
		location / {
			index  index.html index.htm index.php;
		}

		location ~ \.php$ {
			try_files \$uri =404; #  This line closes a potential security hole
			# ensuring users can't execute uploaded files
			# see: http://forum.nginx.org/read.php?2,88845,page=3
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
			fastcgi_index  index.php;
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
			fastcgi_read_timeout 180;
			include        /usr/local/etc/nginx/fastcgi_params;
		}
	}

EOD;

	$cert = str_replace("\r", "", $cert);
	$key = str_replace("\r", "", $key);

	$cert = str_replace("\n\n", "\n", $cert);
	$key = str_replace("\n\n", "\n", $key);

	if ($cert <> "" and $key <> "") {
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
		if (!$fd) {
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
			return 1;
		}
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
		if ($ca <> "") {
			$cert_chain = $cert . "\n" . $ca;
		} else {
			$cert_chain = $cert;
		}
		fwrite($fd, $cert_chain);
		fclose($fd);
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
		if (!$fd) {
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
			return 1;
		}
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
		fwrite($fd, $key);
		fclose($fd);
	}

	// Add HTTP to HTTPS redirect
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
		if ($nginx_port != "443") {
			$redirectport = ":{$nginx_port}";
		}
		$nginx_config .= <<<EOD
	server {
		listen 80;
		listen [::]:80;
		return 301 https://\$http_host$redirectport\$request_uri;
	}

EOD;
	}

	$nginx_config .= "}\n";

	$fd = fopen("{$filename}", "w");
	if (!$fd) {
		printf(gettext("Error: cannot open %s in system_generate_nginx_config().%s"), $filename, "\n");
		return 1;
	}
	fwrite($fd, $nginx_config);
	fclose($fd);

	/* nginx will fail to start if this directory does not exist. */
	safe_mkdir("/var/tmp/nginx/");

	return 0;

}

function system_get_timezone_list() {
	global $g;

	$file_list = array_merge(
		glob("/usr/share/zoneinfo/[A-Z]*"),
		glob("/usr/share/zoneinfo/*/*"),
		glob("/usr/share/zoneinfo/*/*/*")
	);

	if (empty($file_list)) {
		$file_list[] = $g['default_timezone'];
	} else {
		/* Remove directories from list */
		$file_list = array_filter($file_list, function($v) {
			return !is_dir($v);
		});
	}

	/* Remove directory prefix */
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);

	sort($file_list);

	return $file_list;
}

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

	$syscfg = $config['system'];

	if (platform_booting()) {
		echo gettext("Setting timezone...");
	}

	/* extract appropriate timezone file */
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
	conf_mount_rw();
	/* DO NOT remove \n otherwise tzsetup will fail */
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
	mwexec("/usr/sbin/tzsetup -r");
	conf_mount_ro();

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

function system_ntp_setup_gps($serialport) {
	global $config, $g;
	$gps_device = '/dev/gps0';
	$serialport = '/dev/'.$serialport;

	if (!file_exists($serialport)) {
		return false;
	}

	conf_mount_rw();
	// Create symlink that ntpd requires
	unlink_if_exists($gps_device);
	@symlink($serialport, $gps_device);

	$gpsbaud = '4800';
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
		switch ($config['ntpd']['gps']['speed']) {
			case '16':
				$gpsbaud = '9600';
				break;
			case '32':
				$gpsbaud = '19200';
				break;
			case '48':
				$gpsbaud = '38400';
				break;
			case '64':
				$gpsbaud = '57600';
				break;
			case '80':
				$gpsbaud = '115200';
				break;
		}
	}

	/* Configure the serial port for raw IO and set the speed */
	mwexec("stty -f {$serialport}.init raw speed {$gpsbaud}");

	/* Send the following to the GPS port to initialize the GPS */
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
	} else {
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
	}

	/* XXX: Why not file_put_contents to the device */
	@file_put_contents('/tmp/gps.init', $gps_init);
	mwexec("cat /tmp/gps.init > {$serialport}");

	/* Add /etc/remote entry in case we need to read from the GPS with tip */
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
	}

	conf_mount_ro();

	return true;
}

function system_ntp_setup_pps($serialport) {
	global $config, $g;

	$pps_device = '/dev/pps0';
	$serialport = '/dev/'.$serialport;

	if (!file_exists($serialport)) {
		return false;
	}

	conf_mount_rw();
	// Create symlink that ntpd requires
	unlink_if_exists($pps_device);
	@symlink($serialport, $pps_device);

	conf_mount_ro();

	return true;
}


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

	$driftfile = "/var/db/ntpd.drift";
	$statsdir = "/var/log/ntp";
	$gps_device = '/dev/gps0';

	safe_mkdir($statsdir);

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

	$ntpcfg = "# \n";
	$ntpcfg .= "# pfSense ntp configuration file \n";
	$ntpcfg .= "# \n\n";
	$ntpcfg .= "tinker panic 0 \n";

	/* Add Orphan mode */
	$ntpcfg .= "# Orphan mode stratum\n";
	$ntpcfg .= 'tos orphan ';
	if (!empty($config['ntpd']['orphan'])) {
		$ntpcfg .= $config['ntpd']['orphan'];
	} else {
		$ntpcfg .= '12';
	}
	$ntpcfg .= "\n";

	/* Add PPS configuration */
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
		$ntpcfg .= "\n";
		$ntpcfg .= "# PPS Setup\n";
		$ntpcfg .= 'server 127.127.22.0';
		$ntpcfg .= ' minpoll 4 maxpoll 4';
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
			$ntpcfg .= ' prefer';
		}
		if (!empty($config['ntpd']['pps']['noselect'])) {
			$ntpcfg .= ' noselect ';
		}
		$ntpcfg .= "\n";
		$ntpcfg .= 'fudge 127.127.22.0';
		if (!empty($config['ntpd']['pps']['fudge1'])) {
			$ntpcfg .= ' time1 ';
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
		}
		if (!empty($config['ntpd']['pps']['flag2'])) {
			$ntpcfg .= ' flag2 1';
		}
		if (!empty($config['ntpd']['pps']['flag3'])) {
			$ntpcfg .= ' flag3 1';
		} else {
			$ntpcfg .= ' flag3 0';
		}
		if (!empty($config['ntpd']['pps']['flag4'])) {
			$ntpcfg .= ' flag4 1';
		}
		if (!empty($config['ntpd']['pps']['refid'])) {
			$ntpcfg .= ' refid ';
			$ntpcfg .= $config['ntpd']['pps']['refid'];
		}
		$ntpcfg .= "\n";
	}
	/* End PPS configuration */

	/* Add GPS configuration */
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
		$ntpcfg .= "\n";
		$ntpcfg .= "# GPS Setup\n";
		$ntpcfg .= 'server 127.127.20.0 mode ';
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
			if (!empty($config['ntpd']['gps']['nmea'])) {
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
			}
			if (!empty($config['ntpd']['gps']['speed'])) {
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
			}
			if (!empty($config['ntpd']['gps']['subsec'])) {
				$ntpmode += 128;
			}
			$ntpcfg .= (string) $ntpmode;
		} else {
			$ntpcfg .= '0';
		}
		$ntpcfg .= ' minpoll 4 maxpoll 4';
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
			$ntpcfg .= ' prefer';
		}
		if (!empty($config['ntpd']['gps']['noselect'])) {
			$ntpcfg .= ' noselect ';
		}
		$ntpcfg .= "\n";
		$ntpcfg .= 'fudge 127.127.20.0';
		if (!empty($config['ntpd']['gps']['fudge1'])) {
			$ntpcfg .= ' time1 ';
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
		}
		if (!empty($config['ntpd']['gps']['fudge2'])) {
			$ntpcfg .= ' time2 ';
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
		}
		if (!empty($config['ntpd']['gps']['flag1'])) {
			$ntpcfg .= ' flag1 1';
		} else {
			$ntpcfg .= ' flag1 0';
		}
		if (!empty($config['ntpd']['gps']['flag2'])) {
			$ntpcfg .= ' flag2 1';
		}
		if (!empty($config['ntpd']['gps']['flag3'])) {
			$ntpcfg .= ' flag3 1';
		} else {
			$ntpcfg .= ' flag3 0';
		}
		if (!empty($config['ntpd']['gps']['flag4'])) {
			$ntpcfg .= ' flag4 1';
		}
		if (!empty($config['ntpd']['gps']['refid'])) {
			$ntpcfg .= ' refid ';
			$ntpcfg .= $config['ntpd']['gps']['refid'];
		}
		if (!empty($config['ntpd']['gps']['stratum'])) {
			$ntpcfg .= ' stratum ';
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
		}
		$ntpcfg .= "\n";
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
		/* This handles a 2.1 and earlier config */
		$ntpcfg .= "# GPS Setup\n";
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
		// Fall back to local clock if GPS is out of sync?
		$ntpcfg .= "server 127.127.1.0\n";
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
	}
	/* End GPS configuration */

	$ntpcfg .= "\n\n# Upstream Servers\n";
	/* foreach through ntp servers and write out to ntpd.conf */
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
		if (substr_count($config['ntpd']['prefer'], $ts)) {
			$ntpcfg .= ' prefer';
		}
		if (substr_count($config['ntpd']['noselect'], $ts)) {
			$ntpcfg .= ' noselect';
		}
		$ntpcfg .= "\n";
	}
	unset($ts);

	$ntpcfg .= "\n\n";
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
		$ntpcfg .= "enable stats\n";
		$ntpcfg .= 'statistics';
		if (!empty($config['ntpd']['clockstats'])) {
			$ntpcfg .= ' clockstats';
		}
		if (!empty($config['ntpd']['loopstats'])) {
			$ntpcfg .= ' loopstats';
		}
		if (!empty($config['ntpd']['peerstats'])) {
			$ntpcfg .= ' peerstats';
		}
		$ntpcfg .= "\n";
	}
	$ntpcfg .= "statsdir {$statsdir}\n";
	$ntpcfg .= 'logconfig =syncall +clockall';
	if (!empty($config['ntpd']['logpeer'])) {
		$ntpcfg .= ' +peerall';
	}
	if (!empty($config['ntpd']['logsys'])) {
		$ntpcfg .= ' +sysall';
	}
	$ntpcfg .= "\n";
	$ntpcfg .= "driftfile {$driftfile}\n";

	/* Default Access restrictions */
	$ntpcfg .= 'restrict default';
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
		$ntpcfg .= ' kod limited';
	}
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
		$ntpcfg .= ' nomodify';
	}
	if (!empty($config['ntpd']['noquery'])) {
		$ntpcfg .= ' noquery';
	}
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
		$ntpcfg .= ' nopeer';
	}
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
		$ntpcfg .= ' notrap';
	}
	if (!empty($config['ntpd']['noserve'])) {
		$ntpcfg .= ' noserve';
	}
	$ntpcfg .= "\nrestrict -6 default";
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
		$ntpcfg .= ' kod limited';
	}
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
		$ntpcfg .= ' nomodify';
	}
	if (!empty($config['ntpd']['noquery'])) {
		$ntpcfg .= ' noquery';
	}
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
		$ntpcfg .= ' nopeer';
	}
	if (!empty($config['ntpd']['noserve'])) {
		$ntpcfg .= ' noserve';
	}
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
		$ntpcfg .= ' notrap';
	}
	/* Custom Access Restrictions */
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
		$networkacl = $config['ntpd']['restrictions']['row'];
		foreach ($networkacl as $acl) {
			$ntpcfg .= "\nrestrict ";
			if (is_ipaddrv6($acl['acl_network'])) {
				$ntpcfg .= "-6 {$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
			} elseif (is_ipaddrv4($acl['acl_network'])) {
				$ntpcfg .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
			} else {
				continue;
			}
			if (!empty($acl['kod'])) {
				$ntpcfg .= ' kod limited';
			}
			if (!empty($acl['nomodify'])) {
				$ntpcfg .= ' nomodify';
			}
			if (!empty($acl['noquery'])) {
				$ntpcfg .= ' noquery';
			}
			if (!empty($acl['nopeer'])) {
				$ntpcfg .= ' nopeer';
			}
			if (!empty($acl['noserve'])) {
				$ntpcfg .= ' noserve';
			}
			if (!empty($acl['notrap'])) {
				$ntpcfg .= ' notrap';
			}
		}
	}
	$ntpcfg .= "\n";
	/* End Custom Access Restrictions */

	/* A leapseconds file is really only useful if this clock is stratum 1 */
	$ntpcfg .= "\n";
	if (!empty($config['ntpd']['leapsec'])) {
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
		file_put_contents('/var/db/leap-seconds', $leapsec);
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
	}


	if (empty($config['ntpd']['interface'])) {
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
		} else {
			$interfaces = array();
		}
	} else {
		$interfaces = explode(",", $config['ntpd']['interface']);
	}

	if (is_array($interfaces) && count($interfaces)) {
		$finterfaces = array();
		$ntpcfg .= "interface ignore all\n";
		foreach ($interfaces as $interface) {
			$interface = get_real_interface($interface);
			if (!empty($interface)) {
				$finterfaces[] = $interface;
			}
		}
		foreach ($finterfaces as $interface) {
			$ntpcfg .= "interface listen {$interface}\n";
		}
	}

	/* open configuration for writing or bail */
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
		return;
	}

	/* if ntpd is running, kill it */
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
		killbypid("{$g['varrun_path']}/ntpd.pid");
	}
	@unlink("{$g['varrun_path']}/ntpd.pid");

	/* if /var/empty does not exist, create it */
	if (!is_dir("/var/empty")) {
		mkdir("/var/empty", 0775, true);
	}

	/* start opentpd, set time now and use /var/etc/ntpd.conf */
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);

	// Note that we are starting up
	log_error("NTPD is starting up.");
	return;
}

function system_halt() {
	global $g;

	system_reboot_cleanup();

	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
}

function system_reboot() {
	global $g;

	system_reboot_cleanup();

	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
}

function system_reboot_sync() {
	global $g;

	system_reboot_cleanup();

	mwexec("/etc/rc.reboot > /dev/null 2>&1");
}

function system_reboot_cleanup() {
	global $config, $cpzone;

	mwexec("/usr/local/bin/beep.sh stop");
	require_once("captiveportal.inc");
	if (is_array($config['captiveportal'])) {
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
			captiveportal_radius_stop_all();
			captiveportal_send_server_accounting(true);
		}
	}
	require_once("voucher.inc");
	voucher_save_db_to_config();
	require_once("pkg-utils.inc");
	stop_packages();
}

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

	if ($early) {
		$cmdn = "earlyshellcmd";
	} else {
		$cmdn = "shellcmd";
	}

	if (is_array($config['system'][$cmdn])) {

		/* *cmd is an array, loop through */
		foreach ($config['system'][$cmdn] as $cmd) {
			exec($cmd);
		}

	} elseif ($config['system'][$cmdn] <> "") {

		/* execute single item */
		exec($config['system'][$cmdn]);

	}
}

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

	if (isset($config['system']['disableconsolemenu'])) {
		touch("{$g['varetc_path']}/disableconsole");
	} else {
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
	}
}

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

	$dmesg = "";
	$_gb = exec("/sbin/dmesg", $dmesg);

	/* find last copyright line (output from previous boots may be present) */
	$lastcpline = 0;

	for ($i = 0; $i < count($dmesg); $i++) {
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
			$lastcpline = $i;
		}
	}

	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
	if (!$fd) {
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
		return 1;
	}

	for ($i = $lastcpline; $i < count($dmesg); $i++) {
		fwrite($fd, $dmesg[$i] . "\n");
	}

	fclose($fd);
	unset($dmesg);

	return 0;
}

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

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

	if (isset($config['system']['harddiskstandby'])) {
		if (platform_booting()) {
			echo gettext('Setting hard disk standby... ');
		}

		$standby = $config['system']['harddiskstandby'];
		// Check for a numeric value
		if (is_numeric($standby)) {
			// Get only suitable candidates for standby; using get_smart_drive_list()
			// from utils.inc to get the list of drives.
			$harddisks = get_smart_drive_list();

			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
			// just in case of some weird pfSense platform installs.
			if (count($harddisks) > 0) {
				// Iterate disks and run the camcontrol command for each
				foreach ($harddisks as $harddisk) {
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
				}
				if (platform_booting()) {
					echo gettext("done.") . "\n";
				}
			} else if (platform_booting()) {
				echo gettext("failed!") . "\n";
			}
		} else if (platform_booting()) {
			echo gettext("failed!") . "\n";
		}
	}
}

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

	activate_sysctls();

	if (isset($config['system']['sharednet'])) {
		system_disable_arp_wrong_if();
	}
}

function system_disable_arp_wrong_if() {
	global $config;
	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "system_disable_arp_wrong_if() being called $mt\n";
	}
	set_sysctl(array(
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
		"net.link.ether.inet.log_arp_movements" => "0"
	));
}

function system_enable_arp_wrong_if() {
	global $config;
	if (isset($config['system']['developerspew'])) {
		$mt = microtime();
		echo "system_enable_arp_wrong_if() being called $mt\n";
	}
	set_sysctl(array(
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
		"net.link.ether.inet.log_arp_movements" => "1"
	));
}

function enable_watchdog() {
	global $config;
	return;
	$install_watchdog = false;
	$supported_watchdogs = array("Geode");
	$file = file_get_contents("/var/log/dmesg.boot");
	foreach ($supported_watchdogs as $sd) {
		if (stristr($file, "Geode")) {
			$install_watchdog = true;
		}
	}
	if ($install_watchdog == true) {
		if (is_process_running("watchdogd")) {
			mwexec("/usr/bin/killall watchdogd", true);
		}
		exec("/usr/sbin/watchdogd");
	}
}

function system_check_reset_button() {
	global $g;

	$specplatform = system_identify_specific_platform();

	switch ($specplatform['name']) {
		case 'alix':
		case 'wrap':
		case 'FW7541':
		case 'APU':
		case 'RCC-VE':
		case 'RCC':
		case 'RCC-DFF':
			break;
		default:
			return 0;
	}

	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");

	if ($retval == 99) {
		/* user has pressed reset button for 2 seconds -
		   reset to factory defaults */
		echo <<<EOD

***********************************************************************
* Reset button pressed - resetting configuration to factory defaults. *
* All additional packages installed will be removed                   *
* The system will reboot after this completes.                        *
***********************************************************************


EOD;

		reset_factory_defaults();
		system_reboot_sync();
		exit(0);
	}

	return 0;
}

function system_get_serial() {
	unset($output);
	$_gb = exec('/bin/kenv smbios.system.serial 2>/dev/null', $output);
	$serial = $output[0];

	$vm_guest = get_single_sysctl('kern.vm_guest');

	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
	    $vm_guest == 'none') {
		return $serial;
	}

	return get_single_sysctl('kern.hostuuid');
}

/*
 * attempt to identify the specific platform (for embedded systems)
 * Returns an array with two elements:
 * name => platform string (e.g. 'wrap', 'alix' etc.)
 * descr => human-readable description (e.g. "PC Engines WRAP")
 */
function system_identify_specific_platform() {
	global $g;

	$hw_model = get_single_sysctl('hw.model');

	/* Try to guess from smbios strings */
	unset($product);
	unset($maker);
	$_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $product);
	$_gb = exec('/bin/kenv smbios.system.maker 2>/dev/null', $maker);
	switch ($product[0]) {
		case 'FW7541':
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
			break;
		case 'APU':
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
			break;
		case 'RCC-VE':
			$result = array();
			$result['name'] = 'RCC-VE';

			/* Detect specific models */
			if (!function_exists('does_interface_exist')) {
				require_once("interfaces.inc");
			}
			if (!does_interface_exist('igb4')) {
				$result['model'] = 'SG-2440';
			} elseif (strpos($hw_model, "C2558") !== false) {
				$result['model'] = 'SG-4860';
			} elseif (strpos($hw_model, "C2758") !== false) {
				$result['model'] = 'SG-8860';
			} else {
				$result['model'] = 'RCC-VE';
			}
			$result['descr'] = 'Netgate ' . $result['model'];
			return $result;
			break;
		case 'DFFv2':
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
			break;
		case 'RCC':
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
			break;
		case 'SYS-5018A-FTN4':
		case 'A1SAi':
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
			break;
		case 'SYS-5018D-FN4T':
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
			break;
		case 'Virtual Machine':
			if ($maker[0] == "Microsoft Corporation") {
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
			}
			break;
	}

	/* the rest of the code only deals with 'embedded' platforms */
	if ($g['platform'] != 'nanobsd') {
		return array('name' => $g['platform'], 'descr' => $g['platform']);
	}

	if (strpos($hw_model, "PC Engines WRAP") !== false) {
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
	}

	if (strpos($hw_model, "PC Engines ALIX") !== false) {
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
	}

	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
		return array('name' => 'net45xx', 'descr' => $matches[0]);
	}

	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
		return array('name' => 'net48xx', 'descr' => $matches[0]);
	}

	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
		return array('name' => 'net55xx', 'descr' => $matches[0]);
	}

	unset($hw_model);

	$dmesg_boot = system_get_dmesg_boot();
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
	}
	unset($dmesg_boot);

	/* unknown embedded platform */
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
}

function system_get_dmesg_boot() {
	global $g;

	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
}

?>
OpenPOWER on IntegriCloud