Project

General

Profile

Download (76.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2019 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

    
28
function activate_powerd() {
29
	global $config, $g;
30

    
31
	if (is_process_running("powerd")) {
32
		exec("/usr/bin/killall powerd");
33
	}
34
	if (isset($config['system']['powerd_enable'])) {
35
		$ac_mode = "hadp";
36
		if (!empty($config['system']['powerd_ac_mode'])) {
37
			$ac_mode = $config['system']['powerd_ac_mode'];
38
		}
39

    
40
		$battery_mode = "hadp";
41
		if (!empty($config['system']['powerd_battery_mode'])) {
42
			$battery_mode = $config['system']['powerd_battery_mode'];
43
		}
44

    
45
		$normal_mode = "hadp";
46
		if (!empty($config['system']['powerd_normal_mode'])) {
47
			$normal_mode = $config['system']['powerd_normal_mode'];
48
		}
49

    
50
		mwexec("/usr/sbin/powerd" .
51
			" -b " . escapeshellarg($battery_mode) .
52
			" -a " . escapeshellarg($ac_mode) .
53
			" -n " . escapeshellarg($normal_mode));
54
	}
55
}
56

    
57
function get_default_sysctl_value($id) {
58
	global $sysctls;
59

    
60
	if (isset($sysctls[$id])) {
61
		return $sysctls[$id];
62
	}
63
}
64

    
65
function get_sysctl_descr($sysctl) {
66
	unset($output);
67
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
68

    
69
	return $output[0];
70
}
71

    
72
function system_get_sysctls() {
73
	global $config, $sysctls;
74

    
75
	$disp_sysctl = array();
76
	$disp_cache = array();
77
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
78
		foreach ($config['sysctl']['item'] as $id => $tunable) {
79
			if ($tunable['value'] == "default") {
80
				$value = get_default_sysctl_value($tunable['tunable']);
81
			} else {
82
				$value = $tunable['value'];
83
			}
84

    
85
			$disp_sysctl[$id] = $tunable;
86
			$disp_sysctl[$id]['modified'] = true;
87
			$disp_cache[$tunable['tunable']] = 'set';
88
		}
89
	}
90

    
91
	foreach ($sysctls as $sysctl => $value) {
92
		if (isset($disp_cache[$sysctl])) {
93
			continue;
94
		}
95

    
96
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
97
	}
98
	unset($disp_cache);
99
	return $disp_sysctl;
100
}
101

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

    
105
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
106
		foreach ($config['sysctl']['item'] as $tunable) {
107
			if ($tunable['value'] == "default") {
108
				$value = get_default_sysctl_value($tunable['tunable']);
109
			} else {
110
				$value = $tunable['value'];
111
			}
112

    
113
			$sysctls[$tunable['tunable']] = $value;
114
		}
115
	}
116

    
117
	set_sysctl($sysctls);
118
}
119

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

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

    
128
	$syscfg = $config['system'];
129

    
130
	foreach(get_dns_nameservers() as $dns_ns) {
131
		$resolvconf .= "nameserver $dns_ns\n";
132
	}
133

    
134
	$ns = array();
135
	if (isset($syscfg['dnsallowoverride'])) {
136
		/* get dynamically assigned DNS servers (if any) */
137
		$ns = array_unique(get_searchdomains());
138
		foreach ($ns as $searchserver) {
139
			if ($searchserver) {
140
				$resolvconf .= "search {$searchserver}\n";
141
			}
142
		}
143
	}
144
	if (empty($ns)) {
145
		// Do not create blank search/domain lines, it can break tools like dig.
146
		if ($syscfg['domain']) {
147
			$resolvconf .= "search {$syscfg['domain']}\n";
148
		}
149
	}
150

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

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

    
158
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
159
	if (!$fd) {
160
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
161
		unlock($dnslock);
162
		return 1;
163
	}
164

    
165
	fwrite($fd, $resolvconf);
166
	fclose($fd);
167

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

    
177
	if (!platform_booting()) {
178
		/* restart dhcpd (nameservers may have changed) */
179
		if (!$dynupdate) {
180
			services_dhcpd_configure();
181
		}
182
	}
183

    
184
	/* setup static routes for DNS servers. */
185
	$dnscounter = 1;
186
	$dnsgw = "dns{$dnscounter}gw";
187
	while (isset($config['system'][$dnsgw])) {
188
		/* setup static routes for dns servers */
189
		if (!(empty($config['system'][$dnsgw]) ||
190
		    $config['system'][$dnsgw] == "none")) {
191
			$gwname = $config['system'][$dnsgw];
192
			$gatewayip = lookup_gateway_ip_by_name($gwname);
193
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
194
			/* dns server array starts at 0 */
195
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
196

    
197
			if (is_ipaddr($gatewayip)) {
198
				route_add_or_change("-host {$inet6}{$dnsserver} {$gatewayip}");
199
			} else {
200
				/* Remove old route when disable gw */
201
				mwexec("/sbin/route delete -host {$inet6}{$dnsserver}");
202
				if (isset($config['system']['route-debug'])) {
203
					$mt = microtime();
204
					log_error("ROUTING debug: $mt - route delete -host {$inet6}{$dnsserver}");
205
				}
206
			}
207
		}
208
		$dnscounter++;
209
		$dnsgw = "dns{$dnscounter}gw";
210
	}
211

    
212
	unlock($dnslock);
213

    
214
	return 0;
215
}
216

    
217
function get_searchdomains() {
218
	global $config, $g;
219

    
220
	$master_list = array();
221

    
222
	// Read in dhclient nameservers
223
	$search_list = glob("/var/etc/searchdomain_*");
224
	if (is_array($search_list)) {
225
		foreach ($search_list as $fdns) {
226
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
227
			if (!is_array($contents)) {
228
				continue;
229
			}
230
			foreach ($contents as $dns) {
231
				if (is_hostname($dns)) {
232
					$master_list[] = $dns;
233
				}
234
			}
235
		}
236
	}
237

    
238
	return $master_list;
239
}
240

    
241
function get_nameservers() {
242
	global $config, $g;
243
	$master_list = array();
244

    
245
	// Read in dhclient nameservers
246
	$dns_lists = glob("/var/etc/nameserver_*");
247
	if (is_array($dns_lists)) {
248
		foreach ($dns_lists as $fdns) {
249
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
250
			if (!is_array($contents)) {
251
				continue;
252
			}
253
			foreach ($contents as $dns) {
254
				if (is_ipaddr($dns)) {
255
					$master_list[] = $dns;
256
				}
257
			}
258
		}
259
	}
260

    
261
	// Read in any extra nameservers
262
	if (file_exists("/var/etc/nameservers.conf")) {
263
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
264
		if (is_array($dns_s)) {
265
			foreach ($dns_s as $dns) {
266
				if (is_ipaddr($dns)) {
267
					$master_list[] = $dns;
268
				}
269
			}
270
		}
271
	}
272

    
273
	return $master_list;
274
}
275

    
276
/* Create localhost + local interfaces entries for /etc/hosts */
277
function system_hosts_local_entries() {
278
	global $config;
279

    
280
	$syscfg = $config['system'];
281

    
282
	$hosts = array();
283
	$hosts[] = array(
284
	    'ipaddr' => '127.0.0.1',
285
	    'fqdn' => 'localhost.' . $syscfg['domain'],
286
	    'name' => 'localhost',
287
	    'domain' => $syscfg['domain']
288
	);
289
	$hosts[] = array(
290
	    'ipaddr' => '::1',
291
	    'fqdn' => 'localhost.' . $syscfg['domain'],
292
	    'name' => 'localhost',
293
	    'domain' => $syscfg['domain']
294
	);
295

    
296
	if ($config['interfaces']['lan']) {
297
		$sysiflist = array('lan' => "lan");
298
	} else {
299
		$sysiflist = get_configured_interface_list();
300
	}
301

    
302
	$hosts_if_found = false;
303
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
304
	foreach ($sysiflist as $sysif) {
305
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
306
			continue;
307
		}
308
		$cfgip = get_interface_ip($sysif);
309
		if (is_ipaddrv4($cfgip)) {
310
			$hosts[] = array(
311
			    'ipaddr' => $cfgip,
312
			    'fqdn' => $local_fqdn,
313
			    'name' => $syscfg['hostname'],
314
			    'domain' => $syscfg['domain']
315
			);
316
			$hosts_if_found = true;
317
		}
318
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
319
			$cfgipv6 = get_interface_ipv6($sysif);
320
			if (is_ipaddrv6($cfgipv6)) {
321
				$hosts[] = array(
322
					'ipaddr' => $cfgipv6,
323
					'fqdn' => $local_fqdn,
324
					'name' => $syscfg['hostname'],
325
					'domain' => $syscfg['domain']
326
				);
327
				$hosts_if_found = true;
328
			}
329
		}
330
		if ($hosts_if_found == true) {
331
			break;
332
		}
333
	}
334

    
335
	return $hosts;
336
}
337

    
338
/* Read host override entries from dnsmasq or unbound */
339
function system_hosts_override_entries($dnscfg) {
340
	$hosts = array();
341

    
342
	if (!is_array($dnscfg) ||
343
	    !is_array($dnscfg['hosts']) ||
344
	    !isset($dnscfg['enable'])) {
345
		return $hosts;
346
	}
347

    
348
	foreach ($dnscfg['hosts'] as $host) {
349
		$fqdn = '';
350
		if ($host['host'] || $host['host'] == "0") {
351
			$fqdn .= "{$host['host']}.";
352
		}
353
		$fqdn .= $host['domain'];
354

    
355
		$hosts[] = array(
356
		    'ipaddr' => $host['ip'],
357
		    'fqdn' => $fqdn,
358
		    'name' => $host['host'],
359
		    'domain' => $host['domain']
360
		);
361

    
362
		if (!is_array($host['aliases']) ||
363
		    !is_array($host['aliases']['item'])) {
364
			continue;
365
		}
366

    
367
		foreach ($host['aliases']['item'] as $alias) {
368
			$fqdn = '';
369
			if ($alias['host'] || $alias['host'] == "0") {
370
				$fqdn .= "{$alias['host']}.";
371
			}
372
			$fqdn .= $alias['domain'];
373

    
374
			$hosts[] = array(
375
			    'ipaddr' => $host['ip'],
376
			    'fqdn' => $fqdn,
377
			    'name' => $alias['host'],
378
			    'domain' => $alias['domain']
379
			);
380
		}
381
	}
382

    
383
	return $hosts;
384
}
385

    
386
/* Read all dhcpd/dhcpdv6 staticmap entries */
387
function system_hosts_dhcpd_entries() {
388
	global $config;
389

    
390
	$hosts = array();
391
	$syscfg = $config['system'];
392

    
393
	if (is_array($config['dhcpd'])) {
394
		$conf_dhcpd = $config['dhcpd'];
395
	} else {
396
		$conf_dhcpd = array();
397
	}
398

    
399
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
400
		if (!is_array($dhcpifconf['staticmap']) ||
401
		    !isset($dhcpifconf['enable'])) {
402
			continue;
403
		}
404
		foreach ($dhcpifconf['staticmap'] as $host) {
405
			if (!$host['ipaddr'] ||
406
			    !$host['hostname']) {
407
				continue;
408
			}
409

    
410
			$fqdn = $host['hostname'] . ".";
411
			$domain = "";
412
			if ($host['domain']) {
413
				$domain = $host['domain'];
414
			} elseif ($dhcpifconf['domain']) {
415
				$domain = $dhcpifconf['domain'];
416
			} else {
417
				$domain = $syscfg['domain'];
418
			}
419

    
420
			$hosts[] = array(
421
			    'ipaddr' => $host['ipaddr'],
422
			    'fqdn' => $fqdn . $domain,
423
			    'name' => $host['hostname'],
424
			    'domain' => $domain
425
			);
426
		}
427
	}
428
	unset($conf_dhcpd);
429

    
430
	if (is_array($config['dhcpdv6'])) {
431
		$conf_dhcpdv6 = $config['dhcpdv6'];
432
	} else {
433
		$conf_dhcpdv6 = array();
434
	}
435

    
436
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
437
		if (!is_array($dhcpifconf['staticmap']) ||
438
		    !isset($dhcpifconf['enable'])) {
439
			continue;
440
		}
441

    
442
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
443
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
444
		    'track6') {
445
			$isdelegated = true;
446
		} else {
447
			$isdelegated = false;
448
		}
449

    
450
		foreach ($dhcpifconf['staticmap'] as $host) {
451
			$ipaddrv6 = $host['ipaddrv6'];
452

    
453
			if (!$ipaddrv6 || !$host['hostname']) {
454
				continue;
455
			}
456

    
457
			if ($isdelegated) {
458
				/*
459
				 * We are always in an "end-user" subnet
460
				 * here, which all are /64 for IPv6.
461
				 */
462
				$ipaddrv6 = merge_ipv6_delegated_prefix(
463
				    get_interface_ipv6($dhcpif),
464
				    $ipaddrv6, 64);
465
			}
466

    
467
			$fqdn = $host['hostname'] . ".";
468
			$domain = "";
469
			if ($host['domain']) {
470
				$domain = $host['domain'];
471
			} elseif ($dhcpifconf['domain']) {
472
				$domain = $dhcpifconf['domain'];
473
			} else {
474
				$domain = $syscfg['domain'];
475
			}
476

    
477
			$hosts[] = array(
478
			    'ipaddr' => $ipaddrv6,
479
			    'fqdn' => $fqdn . $domain,
480
			    'name' => $host['hostname'],
481
			    'domain' => $domain
482
			);
483
		}
484
	}
485
	unset($conf_dhcpdv6);
486

    
487
	return $hosts;
488
}
489

    
490
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
491
function system_hosts_entries($dnscfg) {
492
	$local = array();
493
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
494
		$local = system_hosts_local_entries();
495
	}
496

    
497
	$dns = array();
498
	$dhcpd = array();
499
	if (isset($dnscfg['enable'])) {
500
		$dns = system_hosts_override_entries($dnscfg);
501
		if (isset($dnscfg['regdhcpstatic'])) {
502
			$dhcpd = system_hosts_dhcpd_entries();
503
		}
504
	}
505

    
506
	if (isset($dnscfg['dhcpfirst'])) {
507
		return array_merge($local, $dns, $dhcpd);
508
	} else {
509
		return array_merge($local, $dhcpd, $dns);
510
	}
511
}
512

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

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

    
528
	$syscfg = $config['system'];
529
	$hosts = "";
530
	$lhosts = "";
531
	$dhosts = "";
532

    
533
	$hosts_array = system_hosts_entries($dnsmasqcfg);
534
	foreach ($hosts_array as $host) {
535
		$hosts .= "{$host['ipaddr']}\t";
536
		if ($host['name'] == "localhost") {
537
			$hosts .= "{$host['name']} {$host['fqdn']}";
538
		} else {
539
			$hosts .= "{$host['fqdn']} {$host['name']}";
540
		}
541
		$hosts .= "\n";
542
	}
543
	unset($hosts_array);
544

    
545
	$fd = fopen("{$g['etc_path']}/hosts", "w");
546
	if (!$fd) {
547
		log_error(gettext(
548
		    "Error: cannot open hosts file in system_hosts_generate()."
549
		    ));
550
		return 1;
551
	}
552

    
553
	/*
554
	 * Do not remove this because dhcpleases monitors with kqueue it needs
555
	 * to be killed before writing to hosts files.
556
	 */
557
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
558
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
559
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
560
	}
561

    
562
	fwrite($fd, $hosts);
563
	fclose($fd);
564

    
565
	if (isset($config['unbound']['enable'])) {
566
		require_once("unbound.inc");
567
		unbound_hosts_generate();
568
	}
569

    
570
	/* restart dhcpleases */
571
	if (!platform_booting()) {
572
		system_dhcpleases_configure();
573
	}
574

    
575
	return 0;
576
}
577

    
578
function system_dhcpleases_configure() {
579
	global $config, $g;
580
	if (!function_exists('is_dhcp_server_enabled')) {
581
		require_once('pfsense-utils.inc');
582
	}
583
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
584

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

    
595
		if (isset($config['unbound']['enable'])) {
596
			$dns_pid = "unbound.pid";
597
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
598
		} else {
599
			$dns_pid = "dnsmasq.pid";
600
			$unbound_conf = "";
601
		}
602

    
603
		if (isvalidpid($pidfile)) {
604
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
605
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
606
			if (intval($retval) == 0) {
607
				sigkillbypid($pidfile, "HUP");
608
				return;
609
			} else {
610
				sigkillbypid($pidfile, "TERM");
611
			}
612
		}
613

    
614
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
615
		if (is_process_running("dhcpleases")) {
616
			sigkillbyname('dhcpleases', "TERM");
617
		}
618
		@unlink($pidfile);
619
		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['etc_path']}/hosts");
620
	} elseif (isvalidpid($pidfile)) {
621
		sigkillbypid($pidfile, "TERM");
622
		@unlink($pidfile);
623
	}
624
}
625

    
626
function system_get_dhcpleases() {
627
	global $config, $g;
628

    
629
	$leases = array();
630
	$leases['lease'] = array();
631
	$leases['failover'] = array();
632

    
633
	$leases_file = "{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases";
634

    
635
	if (!file_exists($leases_file)) {
636
		return $leases;
637
	}
638

    
639
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
640
	    FILE_IGNORE_NEW_LINES);
641

    
642
	if ($leases_content === FALSE) {
643
		return $leases;
644
	}
645

    
646
	$arp_table = system_get_arp_table();
647

    
648
	$arpdata_ip = array();
649
	$arpdata_mac = array();
650
	foreach ($arp_table as $arp_entry) {
651
		if (isset($arpentry['incomplete'])) {
652
			continue;
653
		}
654
		$arpdata_ip[] = $arp_entry['ip-address'];
655
		$arpdata_mac[] = $arp_entry['mac-address'];
656
	}
657
	unset($arp_table);
658

    
659
	/*
660
	 * Translate these once so we don't do it over and over in the loops
661
	 * below.
662
	 */
663
	$online_string = gettext("online");
664
	$offline_string = gettext("offline");
665
	$active_string = gettext("active");
666
	$expired_string = gettext("expired");
667
	$reserved_string = gettext("reserved");
668
	$dynamic_string = gettext("dynamic");
669
	$static_string = gettext("static");
670

    
671
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
672
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
673
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
674
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
675
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
676

    
677
	$failover_regex = '/^failover\s+peer\s+"(.+)"\s+state\s+{$/';
678
	$state_regex = '/\s*(my|partner)\s+state\s+(.+)\s+at\s+\d+\s+([\d\/]+)\s+([\d:]+);$/';
679

    
680
	$lease = false;
681
	$failover = false;
682
	$dedup_lease = false;
683
	$dedup_failover = false;
684
	foreach ($leases_content as $line) {
685
		/* Skip comments */
686
		if (preg_match('/^\s*(|#.*)$/', $line)) {
687
			continue;
688
		}
689

    
690
		if (preg_match('/}$/', $line)) {
691
			if ($lease) {
692
				if (empty($item['hostname'])) {
693
					$hostname = gethostbyaddr($item['ip']);
694
					if (!empty($hostname)) {
695
						$item['hostname'] = $hostname;
696
					}
697
				}
698
				$leases['lease'][] = $item;
699
				$lease = false;
700
				$dedup_lease = true;
701
			} else if ($failover) {
702
				$leases['failover'][] = $item;
703
				$failover = false;
704
				$dedup_failover = true;
705
			}
706
			continue;
707
		}
708

    
709
		if (preg_match($lease_regex, $line, $m)) {
710
			$lease = true;
711
			$item = array();
712
			$item['ip'] = $m[1];
713
			$item['type'] = $dynamic_string;
714
			continue;
715
		}
716

    
717
		if ($lease) {
718
			if (preg_match($starts_regex, $line, $m)) {
719
				/*
720
				 * Quote from dhcpd.leases(5) man page:
721
				 * If a lease will never expire, date is never
722
				 * instead of an actual date
723
				 */
724
				if ($m[2] == "never") {
725
					$item[$m[1]] = gettext("Never");
726
				} else {
727
					$item[$m[1]] = dhcpd_date_adjust_gmt(
728
					    $m[2] . ' ' . $m[3]);
729
				}
730
				continue;
731
			}
732

    
733
			if (preg_match($binding_regex, $line, $m)) {
734
				switch ($m[1]) {
735
					case "active":
736
						$item['act'] = $active_string;
737
						break;
738
					case "free":
739
						$item['act'] = $expired_string;
740
						$item['online'] =
741
						    $offline_string;
742
						break;
743
					case "backup":
744
						$item['act'] = $reserved_string;
745
						$item['online'] =
746
						    $offline_string;
747
						break;
748
				}
749
				continue;
750
			}
751

    
752
			if (preg_match($mac_regex, $line, $m) &&
753
			    is_macaddr($m[1])) {
754
				$item['mac'] = $m[1];
755

    
756
				if (in_array($item['ip'], $arpdata_ip)) {
757
					$item['online'] = $online_string;
758
				} else {
759
					$item['online'] = $offline_string;
760
				}
761
				continue;
762
			}
763

    
764
			if (preg_match($hostname_regex, $line, $m)) {
765
				$item['hostname'] = $m[1];
766
			}
767
		}
768

    
769
		if (preg_match($failover_regex, $line, $m)) {
770
			$failover = true;
771
			$item = array();
772
			$item['name'] = $m[1] . ' (' .
773
			    convert_friendly_interface_to_friendly_descr(
774
			    substr($m[1],5)) . ')';
775
			continue;
776
		}
777

    
778
		if ($failover && preg_match($state_regex, $line, $m)) {
779
			$item[$m[1] . 'state'] = $m[2];
780
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
781
			    ' ' . $m[4]);
782
			continue;
783
		}
784
	}
785

    
786
	foreach ($config['interfaces'] as $ifname => $ifarr) {
787
		if (!is_array($config['dhcpd'][$ifname]) ||
788
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
789
			continue;
790
		}
791

    
792
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
793
		    $static) {
794
			if (empty($static['mac']) && empty($static['cid'])) {
795
				continue;
796
			}
797

    
798
			$slease = array();
799
			$slease['ip'] = $static['ipaddr'];
800
			$slease['type'] = $static_string;
801
			if (!empty($static['cid'])) {
802
				$slease['cid'] = $static['cid'];
803
			}
804
			$slease['mac'] = $static['mac'];
805
			$slease['if'] = $ifname;
806
			$slease['starts'] = "";
807
			$slease['ends'] = "";
808
			$slease['hostname'] = $static['hostname'];
809
			$slease['descr'] = $static['descr'];
810
			$slease['act'] = $static_string;
811
			$slease['online'] = in_array(strtolower($slease['mac']),
812
			    $arpdata_mac) ? $online_string : $offline_string;
813
			$slease['staticmap_array_index'] = $idx;
814
			$leases['lease'][] = $slease;
815
			$dedup_lease = true;
816
		}
817
	}
818

    
819
	if ($dedup_lease) {
820
		$leases['lease'] = array_remove_duplicate($leases['lease'],
821
		    'ip');
822
	}
823
	if ($dedup_failover) {
824
		$leases['failover'] = array_remove_duplicate(
825
		    $leases['failover'], 'name');
826
		asort($leases['failover']);
827
	}
828

    
829
	return $leases;
830
}
831

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

    
839
	$syscfg = $config['system'];
840

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

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

    
848
	return $status;
849
}
850

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

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

    
859
	$gateways_arr = return_gateways_array(false, true);
860
	foreach ($gateways_arr as $gateway) {
861
		// setup static interface routes for nonlocal gateways
862
		if (isset($gateway["nonlocalgateway"])) {
863
			$srgatewayip = $gateway['gateway'];
864
			$srinterfacegw = $gateway['interface'];
865
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
866
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
867
				route_add_or_change("{$inet} {$srgatewayip} " .
868
				    "-iface {$srinterfacegw}");
869
			}
870
		}
871
	}
872

    
873
	$gateways_status = return_gateways_status(true);
874
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
875
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
876

    
877
	system_staticroutes_configure($interface, false);
878

    
879
	return 0;
880
}
881

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

    
885
	$filterdns_list = array();
886

    
887
	$static_routes = get_staticroutes(false, true);
888
	if (count($static_routes)) {
889
		$gateways_arr = return_gateways_array(false, true);
890

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

    
901
			$gatewayip = $gateway['gateway'];
902
			$interfacegw = $gateway['interface'];
903

    
904
			$blackhole = "";
905
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
906
				$blackhole = "-blackhole";
907
			}
908

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

    
913
			$dnscache = array();
914
			if ($update_dns === true) {
915
				if (is_subnet($rtent['network'])) {
916
					continue;
917
				}
918
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
919
				if (empty($dnscache)) {
920
					continue;
921
				}
922
			}
923

    
924
			if (is_subnet($rtent['network'])) {
925
				$ips = array($rtent['network']);
926
			} else {
927
				if (!isset($rtent['disabled'])) {
928
					$filterdns_list[] = $rtent['network'];
929
				}
930
				$ips = add_hostname_to_watch($rtent['network']);
931
			}
932

    
933
			foreach ($dnscache as $ip) {
934
				if (in_array($ip, $ips)) {
935
					continue;
936
				}
937
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
938
				if (isset($config['system']['route-debug'])) {
939
					$mt = microtime();
940
					log_error("ROUTING debug: $mt - route delete $ip ");
941
				}
942
			}
943

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

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

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

    
964
				$cmd = "{$inet} {$blackhole} {$ip} ";
965

    
966
				if (is_subnet($ip)) {
967
					if (is_ipaddr($gatewayip)) {
968
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
969
							// add interface scope for link local v6 routes
970
							$gatewayip .= "%$interfacegw";
971
						}
972
						route_add_or_change($cmd . $gatewayip);
973
					} else if (!empty($interfacegw)) {
974
						route_add_or_change($cmd . "-iface {$interfacegw}");
975
					}
976
				}
977
			}
978
		}
979
		unset($gateways_arr);
980
	}
981
	unset($static_routes);
982

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

    
994
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
995
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
996
			} else {
997
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
998
			}
999
		} else {
1000
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1001
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1002
		}
1003
	}
1004
	unset($filterdns_list);
1005

    
1006
	return 0;
1007
}
1008

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

    
1016
	set_sysctl(array(
1017
		"net.inet.ip.forwarding" => "1",
1018
		"net.inet6.ip6.forwarding" => "1"
1019
	));
1020

    
1021
	return;
1022
}
1023

    
1024
function system_syslogd_fixup_server($server) {
1025
	/* If it's an IPv6 IP alone, encase it in brackets */
1026
	if (is_ipaddrv6($server)) {
1027
		return "[$server]";
1028
	} else {
1029
		return $server;
1030
	}
1031
}
1032

    
1033
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
1034
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
1035
	$facility .= " ".
1036
	$remote_servers = "";
1037
	$pad_to  = max(strlen($facility), 56);
1038
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
1039
	if (isset($syslogcfg['enable'])) {
1040
		if ($syslogcfg['remoteserver']) {
1041
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
1042
		}
1043
		if ($syslogcfg['remoteserver2']) {
1044
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
1045
		}
1046
		if ($syslogcfg['remoteserver3']) {
1047
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
1048
		}
1049
	}
1050
	return $remote_servers;
1051
}
1052

    
1053
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
1054
	global $config, $g;
1055

    
1056
	if ($restart_syslogd) {
1057
		/* syslogd does not react well to clog rewriting the file while it is running. */
1058
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1059
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1060
		}
1061
	}
1062
	if (isset($config['system']['disablesyslogclog'])) {
1063
		unlink($logfile);
1064
		touch($logfile);
1065
	} else {
1066
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
1067
		$log_size = ($log_size < (2**32)/2) ? $log_size : "511488";
1068
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
1069
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
1070
	}
1071
	if ($restart_syslogd) {
1072
		system_syslogd_start();
1073
	}
1074
	// Bug #6915
1075
	if ($logfile == "/var/log/resolver.log") {
1076
		services_unbound_configure(true);
1077
	}
1078
}
1079

    
1080
function clear_all_log_files($restart = false) {
1081
	global $g;
1082
	if ($restart) {
1083
		/* syslogd does not react well to clog rewriting the file while it is running. */
1084
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1085
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1086
		}
1087
	}
1088

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

    
1094
	if ($restart) {
1095
		system_syslogd_start();
1096
		killbyname("dhcpd");
1097
		if (!function_exists('services_dhcpd_configure')) {
1098
			require_once('services.inc');
1099
		}
1100
		services_dhcpd_configure();
1101
		// Bug #6915
1102
		services_unbound_configure(false);
1103
	}
1104
	return;
1105
}
1106

    
1107
function system_syslogd_start($sighup = false) {
1108
	global $config, $g;
1109
	if (isset($config['system']['developerspew'])) {
1110
		$mt = microtime();
1111
		echo "system_syslogd_start() being called $mt\n";
1112
	}
1113

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

    
1116
	$syslogcfg = $config['syslog'];
1117

    
1118
	if (platform_booting()) {
1119
		echo gettext("Starting syslog...");
1120
	}
1121

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

    
1133
	$syslogd_extra = "";
1134
	if (isset($syslogcfg)) {
1135
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'zebra', 'ospfd', 'ospf6d', 'bgpd', 'miniupnpd', 'filterlog');
1136
		$syslogconf = "";
1137
		if ($config['installedpackages']['package']) {
1138
			foreach ($config['installedpackages']['package'] as $package) {
1139
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1140
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1141
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1142
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1143
					}
1144
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1145
				}
1146
			}
1147
		}
1148
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1149
		$syslogconf .= "!radvd,routed,zebra,ospfd,ospf6d,bgpd,miniupnpd\n";
1150
		if (!isset($syslogcfg['disablelocallogging'])) {
1151
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1152
		}
1153
		if (isset($syslogcfg['routing'])) {
1154
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1155
		}
1156

    
1157
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
1158
		if (!isset($syslogcfg['disablelocallogging'])) {
1159
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
1160
		}
1161
		if (isset($syslogcfg['ntpd'])) {
1162
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1163
		}
1164

    
1165
		$syslogconf .= "!ppp\n";
1166
		if (!isset($syslogcfg['disablelocallogging'])) {
1167
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
1168
		}
1169
		if (isset($syslogcfg['ppp'])) {
1170
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1171
		}
1172

    
1173
		$syslogconf .= "!poes\n";
1174
		if (!isset($syslogcfg['disablelocallogging'])) {
1175
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
1176
		}
1177
		if (isset($syslogcfg['vpn'])) {
1178
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1179
		}
1180

    
1181
		$syslogconf .= "!l2tps\n";
1182
		if (!isset($syslogcfg['disablelocallogging'])) {
1183
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
1184
		}
1185
		if (isset($syslogcfg['vpn'])) {
1186
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1187
		}
1188

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

    
1197
		$syslogconf .= "!openvpn\n";
1198
		if (!isset($syslogcfg['disablelocallogging'])) {
1199
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
1200
		}
1201
		if (isset($syslogcfg['vpn'])) {
1202
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1203
		}
1204

    
1205
		$syslogconf .= "!dpinger\n";
1206
		if (!isset($syslogcfg['disablelocallogging'])) {
1207
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
1208
		}
1209
		if (isset($syslogcfg['dpinger'])) {
1210
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1211
		}
1212

    
1213
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1214
		if (!isset($syslogcfg['disablelocallogging'])) {
1215
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1216
		}
1217
		if (isset($syslogcfg['resolver'])) {
1218
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1219
		}
1220

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

    
1229
		$syslogconf .= "!hostapd\n";
1230
		if (!isset($syslogcfg['disablelocallogging'])) {
1231
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
1232
		}
1233
		if (isset($syslogcfg['hostapd'])) {
1234
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1235
		}
1236

    
1237
		$syslogconf .= "!filterlog\n";
1238
		if (!isset($syslogcfg['disablelocallogging'])) {
1239
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
1240
		}
1241
		if (isset($syslogcfg['filter'])) {
1242
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1243
		}
1244

    
1245
		$syslogconf .= "!-{$facilitylist}\n";
1246
		if (!isset($syslogcfg['disablelocallogging'])) {
1247
			$syslogconf .= <<<EOD
1248
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1249
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1250
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1251
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1252
*.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
1253
auth.info;authpriv.info 					|exec /usr/local/sbin/sshguard
1254
*.emerg								*
1255

    
1256
EOD;
1257
		}
1258
		if (isset($syslogcfg['vpn'])) {
1259
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1260
		}
1261
		if (isset($syslogcfg['portalauth'])) {
1262
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1263
		}
1264
		if (isset($syslogcfg['dhcp'])) {
1265
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1266
		}
1267
		if (isset($syslogcfg['system'])) {
1268
			$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");
1269
		}
1270
		if (isset($syslogcfg['logall'])) {
1271
			// Make everything mean everything, including facilities excluded above.
1272
			$syslogconf .= "!*\n";
1273
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1274
		}
1275

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

    
1280
EOD;
1281
		}
1282
		/* write syslog.conf */
1283
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1284
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1285
			unset($syslogconf);
1286
			return 1;
1287
		}
1288
		unset($syslogconf);
1289

    
1290
		$sourceip = "";
1291
		if (!empty($syslogcfg['sourceip'])) {
1292
			if ($syslogcfg['ipproto'] == "ipv6") {
1293
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1294
				if (!is_ipaddr($ifaddr)) {
1295
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1296
				}
1297
			} else {
1298
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1299
				if (!is_ipaddr($ifaddr)) {
1300
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1301
				}
1302
			}
1303
			if (is_ipaddr($ifaddr)) {
1304
				$sourceip = "-b {$ifaddr}";
1305
			}
1306
		}
1307

    
1308
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1309
	}
1310

    
1311
	$log_sockets = array("{$g['dhcpd_chroot_path']}/var/run/log");
1312

    
1313
	if (isset($config['installedpackages']['package'])) {
1314
		foreach ($config['installedpackages']['package'] as $package) {
1315
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1316
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1317
				$log_sockets[] = $package['logging']['logsocket'];
1318
			}
1319
		}
1320
	}
1321

    
1322
	$syslogd_sockets = "";
1323
	foreach ($log_sockets as $log_socket) {
1324
		// Ensure that the log directory exists
1325
		$logpath = dirname($log_socket);
1326
		safe_mkdir($logpath);
1327
		$syslogd_sockets .= " -l {$log_socket}";
1328
	}
1329

    
1330
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1331
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1332
		$sighup = false;
1333
	}
1334

    
1335
	$sshguard_whitelist = array();
1336
	if (!empty($config['system']['sshguard_whitelist'])) {
1337
		$sshguard_whitelist = explode(' ',
1338
		    $config['system']['sshguard_whitelist']);
1339
	}
1340

    
1341
	$sshguard_config = array();
1342
	$sshguard_config[] = 'BACKEND="/usr/local/libexec/sshg-fw-pf"' . "\n";
1343
	if (!empty($config['system']['sshguard_threshold'])) {
1344
		$sshguard_config[] = 'THRESHOLD=' .
1345
		    $config['system']['sshguard_threshold'] . "\n";
1346
	}
1347
	if (!empty($config['system']['sshguard_blocktime'])) {
1348
		$sshguard_config[] = 'BLOCK_TIME=' .
1349
		    $config['system']['sshguard_blocktime'] . "\n";
1350
	}
1351
	if (!empty($config['system']['sshguard_detection_time'])) {
1352
		$sshguard_config[] = 'DETECTION_TIME=' .
1353
		    $config['system']['sshguard_detection_time'] . "\n";
1354
	}
1355
	if (!empty($sshguard_whitelist)) {
1356
		@file_put_contents("/usr/local/etc/sshguard.whitelist",
1357
		    implode(PHP_EOL, $sshguard_whitelist));
1358
		$sshguard_config[] =
1359
		    'WHITELIST_FILE=/usr/local/etc/sshguard.whitelist' . "\n";
1360
	} else {
1361
		unlink_if_exists("/usr/local/etc/sshguard.whitelist");
1362
	}
1363
	file_put_contents("/usr/local/etc/sshguard.conf", $sshguard_config);
1364

    
1365
	if (!$sighup) {
1366
		sigkillbyname("sshguard", "TERM");
1367
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1368
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1369
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1370
		}
1371

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

    
1378
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1379
	} else {
1380
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1381
	}
1382

    
1383
	if (platform_booting()) {
1384
		echo gettext("done.") . "\n";
1385
	}
1386

    
1387
	return $retval;
1388
}
1389

    
1390
function system_webgui_create_certificate() {
1391
	global $config, $g;
1392

    
1393
	init_config_arr(array('ca'));
1394
	$a_ca = &$config['ca'];
1395
	init_config_arr(array('cert'));
1396
	$a_cert = &$config['cert'];
1397
	log_error(gettext("Creating SSL Certificate for this host"));
1398

    
1399
	$cert = array();
1400
	$cert['refid'] = uniqid();
1401
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1402
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1403

    
1404
	$dn = array(
1405
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1406
		'commonName' => $cert_hostname,
1407
		'subjectAltName' => "DNS:{$cert_hostname}");
1408
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1409
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1410
		while ($ssl_err = openssl_error_string()) {
1411
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1412
		}
1413
		error_reporting($old_err_level);
1414
		return null;
1415
	}
1416
	error_reporting($old_err_level);
1417

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

    
1424
function system_webgui_start() {
1425
	global $config, $g;
1426

    
1427
	if (platform_booting()) {
1428
		echo gettext("Starting webConfigurator...");
1429
	}
1430

    
1431
	chdir($g['www_path']);
1432

    
1433
	/* defaults */
1434
	$portarg = "80";
1435
	$crt = "";
1436
	$key = "";
1437
	$ca = "";
1438

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

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

    
1453
		if (!$config['system']['webgui']['port']) {
1454
			$portarg = "443";
1455
		}
1456
		$ca = ca_chain($cert);
1457
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1458
	}
1459

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

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

    
1468
	sleep(1);
1469

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

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

    
1475
	if (platform_booting()) {
1476
		if ($res == 0) {
1477
			echo gettext("done.") . "\n";
1478
		} else {
1479
			echo gettext("failed!") . "\n";
1480
		}
1481
	}
1482

    
1483
	return $res;
1484
}
1485

    
1486
function get_dns_nameservers($add_v6_brackets = false) {
1487
	global $config;
1488

    
1489
	$dns_nameservers = array();
1490

    
1491
	if (isset($config['system']['developerspew'])) {
1492
		$mt = microtime();
1493
		echo "get_dns_nameservers() being called $mt\n";
1494
	}
1495

    
1496
	$syscfg = $config['system'];
1497
	if ((((isset($config['dnsmasq']['enable'])) &&
1498
   		(empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1499
	      	(empty($config['dnsmasq']['interface']) ||
1500
	       	in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1501
	     	((isset($config['unbound']['enable'])) &&
1502
	      	(empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1503
	      	(empty($config['unbound']['active_interface']) ||
1504
	       	in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1505
	       	in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1506
	     	(!isset($config['system']['dnslocalhost']))) {
1507
			$dns_nameservers[] = "127.0.0.1";
1508
	}
1509
	/* get dynamically assigned DNS servers (if any) */
1510
	$ns = array_unique(get_nameservers());
1511
	if (isset($syscfg['dnsallowoverride'])) {
1512
		if(!is_array($ns)) {
1513
			$ns = array();
1514
		}
1515
		foreach ($ns as $nameserver) {
1516
			if ($nameserver) {
1517
				if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1518
					$nameserver = "[{$nameserver}]";
1519
				}
1520
				$dns_nameservers[] = $nameserver;
1521
			}
1522
		}
1523
	}
1524
	if (is_array($syscfg['dnsserver'])) {
1525
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1526
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
1527
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1528
					$sys_dnsserver = "[{$sys_dnsserver}]";
1529
				}
1530
				$dns_nameservers[] = $sys_dnsserver;
1531
			}
1532
		}
1533
	}
1534
	return array_unique($dns_nameservers);
1535
}
1536

    
1537
function system_generate_nginx_config($filename,
1538
	$cert,
1539
	$key,
1540
	$ca,
1541
	$pid_file,
1542
	$port = 80,
1543
	$document_root = "/usr/local/www/",
1544
	$cert_location = "cert.crt",
1545
	$key_location = "cert.key",
1546
	$captive_portal = false,
1547
	$hsts = true) {
1548

    
1549
	global $config, $g;
1550

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

    
1556
	if ($captive_portal !== false) {
1557
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1558
		$cp_hostcheck = "";
1559
		foreach ($cp_interfaces as $cpint) {
1560
			$cpint_ip = get_interface_ip($cpint);
1561
			if (is_ipaddr($cpint_ip)) {
1562
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1563
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1564
				$cp_hostcheck .= "\t\t}\n";
1565
			}
1566
		}
1567
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1568
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1569
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1570
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1571
			$cp_hostcheck .= "\t\t}\n";
1572
		}
1573
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1574
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1575
		$cp_rewrite .= "\t\t}\n";
1576

    
1577
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1578
		if (empty($maxprocperip)) {
1579
			$maxprocperip = 10;
1580
		}
1581
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1582
	}
1583

    
1584
	if (empty($port)) {
1585
		$nginx_port = "80";
1586
	} else {
1587
		$nginx_port = $port;
1588
	}
1589

    
1590
	$memory = get_memory();
1591
	$realmem = $memory[1];
1592

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

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

    
1611
	$nginx_config = <<<EOD
1612
#
1613
# nginx configuration file
1614

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

    
1617
user  root wheel;
1618
worker_processes  {$max_procs};
1619

    
1620
EOD;
1621

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

    
1626
	$nginx_config .= <<<EOD
1627

    
1628
events {
1629
    worker_connections  1024;
1630
}
1631

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

    
1638
	sendfile        on;
1639

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

    
1642
EOD;
1643

    
1644
	if ($captive_portal !== false) {
1645
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1646
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1647
	} else {
1648
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1649
	}
1650

    
1651
	if ($cert <> "" and $key <> "") {
1652
		$nginx_config .= "\n";
1653
		$nginx_config .= "\tserver {\n";
1654
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1655
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1656
		$nginx_config .= "\n";
1657
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1658
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1659
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1660
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1661
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1662
		if ($captive_portal !== false) {
1663
			// leave TLSv1.1 for CP for now for compatibility
1664
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1665
		} else {
1666
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1667
		}
1668
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1669
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1670
		if ($captive_portal === false && $hsts !== false) {
1671
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1672
		}
1673
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1674
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1675
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1676
		$cert_temp = lookup_cert($config['system']['webgui']['ssl-certref']);
1677
		if (($config['system']['webgui']['ocsp-staple'] == true) or
1678
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1679
			$nginx_config .= "\t\tssl_stapling on;\n";
1680
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1681
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1682
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1683
		}
1684
	} else {
1685
		$nginx_config .= "\n";
1686
		$nginx_config .= "\tserver {\n";
1687
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1688
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1689
	}
1690

    
1691
	$nginx_config .= <<<EOD
1692

    
1693
		client_max_body_size 200m;
1694

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

    
1698

    
1699
EOD;
1700

    
1701
	if ($captive_portal !== false) {
1702
		$nginx_config .= <<<EOD
1703
$captive_portal_maxprocperip
1704
$cp_hostcheck
1705
$cp_rewrite
1706
		log_not_found off;
1707

    
1708
EOD;
1709

    
1710
	}
1711

    
1712
	$nginx_config .= <<<EOD
1713
		root "{$document_root}";
1714
		location / {
1715
			index  index.php index.html index.htm;
1716
		}
1717
		location ~ \.inc$ {
1718
			deny all;
1719
			return 403;
1720
		}
1721
		location ~ \.php$ {
1722
			try_files \$uri =404; #  This line closes a potential security hole
1723
			# ensuring users can't execute uploaded files
1724
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1725
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1726
			fastcgi_index  index.php;
1727
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1728
			# Fix httpoxy - https://httpoxy.org/#fix-now
1729
			fastcgi_param  HTTP_PROXY  "";
1730
			fastcgi_read_timeout 180;
1731
			include        /usr/local/etc/nginx/fastcgi_params;
1732
		}
1733
		location ~ (^/status$) {
1734
			allow 127.0.0.1;
1735
			deny all;
1736
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1737
			fastcgi_index  index.php;
1738
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1739
			# Fix httpoxy - https://httpoxy.org/#fix-now
1740
			fastcgi_param  HTTP_PROXY  "";
1741
			fastcgi_read_timeout 360;
1742
			include        /usr/local/etc/nginx/fastcgi_params;
1743
		}
1744
	}
1745

    
1746
EOD;
1747

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

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

    
1754
	if ($cert <> "" and $key <> "") {
1755
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1756
		if (!$fd) {
1757
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1758
			return 1;
1759
		}
1760
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1761
		if ($ca <> "") {
1762
			$cert_chain = $cert . "\n" . $ca;
1763
		} else {
1764
			$cert_chain = $cert;
1765
		}
1766
		fwrite($fd, $cert_chain);
1767
		fclose($fd);
1768
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1769
		if (!$fd) {
1770
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1771
			return 1;
1772
		}
1773
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1774
		fwrite($fd, $key);
1775
		fclose($fd);
1776
	}
1777

    
1778
	// Add HTTP to HTTPS redirect
1779
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1780
		if ($nginx_port != "443") {
1781
			$redirectport = ":{$nginx_port}";
1782
		}
1783
		$nginx_config .= <<<EOD
1784
	server {
1785
		listen 80;
1786
		listen [::]:80;
1787
		return 301 https://\$http_host$redirectport\$request_uri;
1788
	}
1789

    
1790
EOD;
1791
	}
1792

    
1793
	$nginx_config .= "}\n";
1794

    
1795
	$fd = fopen("{$filename}", "w");
1796
	if (!$fd) {
1797
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1798
		return 1;
1799
	}
1800
	fwrite($fd, $nginx_config);
1801
	fclose($fd);
1802

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

    
1806
	return 0;
1807

    
1808
}
1809

    
1810
function system_get_timezone_list() {
1811
	global $g;
1812

    
1813
	$file_list = array_merge(
1814
		glob("/usr/share/zoneinfo/[A-Z]*"),
1815
		glob("/usr/share/zoneinfo/*/*"),
1816
		glob("/usr/share/zoneinfo/*/*/*")
1817
	);
1818

    
1819
	if (empty($file_list)) {
1820
		$file_list[] = $g['default_timezone'];
1821
	} else {
1822
		/* Remove directories from list */
1823
		$file_list = array_filter($file_list, function($v) {
1824
			return !is_dir($v);
1825
		});
1826
	}
1827

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

    
1831
	sort($file_list);
1832

    
1833
	return $file_list;
1834
}
1835

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

    
1843
	$syscfg = $config['system'];
1844

    
1845
	if (platform_booting()) {
1846
		echo gettext("Setting timezone...");
1847
	}
1848

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

    
1855
	if (platform_booting()) {
1856
		echo gettext("done.") . "\n";
1857
	}
1858
}
1859

    
1860
function system_ntp_setup_gps($serialport) {
1861
	global $config, $g;
1862
	$gps_device = '/dev/gps0';
1863
	$serialport = '/dev/'.$serialport;
1864

    
1865
	if (!file_exists($serialport)) {
1866
		return false;
1867
	}
1868

    
1869
	// Create symlink that ntpd requires
1870
	unlink_if_exists($gps_device);
1871
	@symlink($serialport, $gps_device);
1872

    
1873
	$gpsbaud = '4800';
1874
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1875
		switch ($config['ntpd']['gps']['speed']) {
1876
			case '16':
1877
				$gpsbaud = '9600';
1878
				break;
1879
			case '32':
1880
				$gpsbaud = '19200';
1881
				break;
1882
			case '48':
1883
				$gpsbaud = '38400';
1884
				break;
1885
			case '64':
1886
				$gpsbaud = '57600';
1887
				break;
1888
			case '80':
1889
				$gpsbaud = '115200';
1890
				break;
1891
		}
1892
	}
1893

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

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

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

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

    
1913

    
1914
	return true;
1915
}
1916

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

    
1920
	$pps_device = '/dev/pps0';
1921
	$serialport = '/dev/'.$serialport;
1922

    
1923
	if (!file_exists($serialport)) {
1924
		return false;
1925
	}
1926

    
1927
	// Create symlink that ntpd requires
1928
	unlink_if_exists($pps_device);
1929
	@symlink($serialport, $pps_device);
1930

    
1931

    
1932
	return true;
1933
}
1934

    
1935

    
1936
function system_ntp_configure() {
1937
	global $config, $g;
1938

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

    
1943
	safe_mkdir($statsdir);
1944

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

    
1949
	$ntpcfg = "# \n";
1950
	$ntpcfg .= "# pfSense ntp configuration file \n";
1951
	$ntpcfg .= "# \n\n";
1952
	$ntpcfg .= "tinker panic 0 \n";
1953

    
1954
	/* Add Orphan mode */
1955
	$ntpcfg .= "# Orphan mode stratum\n";
1956
	$ntpcfg .= 'tos orphan ';
1957
	if (!empty($config['ntpd']['orphan'])) {
1958
		$ntpcfg .= $config['ntpd']['orphan'];
1959
	} else {
1960
		$ntpcfg .= '12';
1961
	}
1962
	$ntpcfg .= "\n";
1963

    
1964
	/* Add PPS configuration */
1965
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1966
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1967
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1968
		$ntpcfg .= "\n";
1969
		$ntpcfg .= "# PPS Setup\n";
1970
		$ntpcfg .= 'server 127.127.22.0';
1971
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1972
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1973
			$ntpcfg .= ' prefer';
1974
		}
1975
		if (!empty($config['ntpd']['pps']['noselect'])) {
1976
			$ntpcfg .= ' noselect ';
1977
		}
1978
		$ntpcfg .= "\n";
1979
		$ntpcfg .= 'fudge 127.127.22.0';
1980
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1981
			$ntpcfg .= ' time1 ';
1982
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1983
		}
1984
		if (!empty($config['ntpd']['pps']['flag2'])) {
1985
			$ntpcfg .= ' flag2 1';
1986
		}
1987
		if (!empty($config['ntpd']['pps']['flag3'])) {
1988
			$ntpcfg .= ' flag3 1';
1989
		} else {
1990
			$ntpcfg .= ' flag3 0';
1991
		}
1992
		if (!empty($config['ntpd']['pps']['flag4'])) {
1993
			$ntpcfg .= ' flag4 1';
1994
		}
1995
		if (!empty($config['ntpd']['pps']['refid'])) {
1996
			$ntpcfg .= ' refid ';
1997
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1998
		}
1999
		$ntpcfg .= "\n";
2000
	}
2001
	/* End PPS configuration */
2002

    
2003
	/* Add GPS configuration */
2004
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
2005
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
2006
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
2007
		$ntpcfg .= "\n";
2008
		$ntpcfg .= "# GPS Setup\n";
2009
		$ntpcfg .= 'server 127.127.20.0 mode ';
2010
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
2011
			if (!empty($config['ntpd']['gps']['nmea'])) {
2012
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
2013
			}
2014
			if (!empty($config['ntpd']['gps']['speed'])) {
2015
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
2016
			}
2017
			if (!empty($config['ntpd']['gps']['subsec'])) {
2018
				$ntpmode += 128;
2019
			}
2020
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
2021
				$ntpmode += 256;
2022
			}
2023
			$ntpcfg .= (string) $ntpmode;
2024
		} else {
2025
			$ntpcfg .= '0';
2026
		}
2027
		$ntpcfg .= ' minpoll 4 maxpoll 4';
2028
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
2029
			$ntpcfg .= ' prefer';
2030
		}
2031
		if (!empty($config['ntpd']['gps']['noselect'])) {
2032
			$ntpcfg .= ' noselect ';
2033
		}
2034
		$ntpcfg .= "\n";
2035
		$ntpcfg .= 'fudge 127.127.20.0';
2036
		if (!empty($config['ntpd']['gps']['fudge1'])) {
2037
			$ntpcfg .= ' time1 ';
2038
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
2039
		}
2040
		if (!empty($config['ntpd']['gps']['fudge2'])) {
2041
			$ntpcfg .= ' time2 ';
2042
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
2043
		}
2044
		if (!empty($config['ntpd']['gps']['flag1'])) {
2045
			$ntpcfg .= ' flag1 1';
2046
		} else {
2047
			$ntpcfg .= ' flag1 0';
2048
		}
2049
		if (!empty($config['ntpd']['gps']['flag2'])) {
2050
			$ntpcfg .= ' flag2 1';
2051
		}
2052
		if (!empty($config['ntpd']['gps']['flag3'])) {
2053
			$ntpcfg .= ' flag3 1';
2054
		} else {
2055
			$ntpcfg .= ' flag3 0';
2056
		}
2057
		if (!empty($config['ntpd']['gps']['flag4'])) {
2058
			$ntpcfg .= ' flag4 1';
2059
		}
2060
		if (!empty($config['ntpd']['gps']['refid'])) {
2061
			$ntpcfg .= ' refid ';
2062
			$ntpcfg .= $config['ntpd']['gps']['refid'];
2063
		}
2064
		if (!empty($config['ntpd']['gps']['stratum'])) {
2065
			$ntpcfg .= ' stratum ';
2066
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
2067
		}
2068
		$ntpcfg .= "\n";
2069
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
2070
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
2071
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
2072
		/* This handles a 2.1 and earlier config */
2073
		$ntpcfg .= "# GPS Setup\n";
2074
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
2075
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
2076
		// Fall back to local clock if GPS is out of sync?
2077
		$ntpcfg .= "server 127.127.1.0\n";
2078
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
2079
	}
2080
	/* End GPS configuration */
2081
	$auto_pool_suffix = "pool.ntp.org";
2082
	$have_pools = false;
2083
	$ntpcfg .= "\n\n# Upstream Servers\n";
2084
	/* foreach through ntp servers and write out to ntpd.conf */
2085
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
2086
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
2087
		    || substr_count($config['ntpd']['ispool'], $ts)) {
2088
			$ntpcfg .= 'pool ';
2089
			$have_pools = true;
2090
		} else {
2091
			$ntpcfg .= 'server ';
2092
		}
2093

    
2094
		$ntpcfg .= "{$ts} iburst maxpoll 9";
2095
		if (substr_count($config['ntpd']['prefer'], $ts)) {
2096
			$ntpcfg .= ' prefer';
2097
		}
2098
		if (substr_count($config['ntpd']['noselect'], $ts)) {
2099
			$ntpcfg .= ' noselect';
2100
		}
2101
		$ntpcfg .= "\n";
2102
	}
2103
	unset($ts);
2104

    
2105
	$ntpcfg .= "\n\n";
2106
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
2107
		$ntpcfg .= "enable stats\n";
2108
		$ntpcfg .= 'statistics';
2109
		if (!empty($config['ntpd']['clockstats'])) {
2110
			$ntpcfg .= ' clockstats';
2111
		}
2112
		if (!empty($config['ntpd']['loopstats'])) {
2113
			$ntpcfg .= ' loopstats';
2114
		}
2115
		if (!empty($config['ntpd']['peerstats'])) {
2116
			$ntpcfg .= ' peerstats';
2117
		}
2118
		$ntpcfg .= "\n";
2119
	}
2120
	$ntpcfg .= "statsdir {$statsdir}\n";
2121
	$ntpcfg .= 'logconfig =syncall +clockall';
2122
	if (!empty($config['ntpd']['logpeer'])) {
2123
		$ntpcfg .= ' +peerall';
2124
	}
2125
	if (!empty($config['ntpd']['logsys'])) {
2126
		$ntpcfg .= ' +sysall';
2127
	}
2128
	$ntpcfg .= "\n";
2129
	$ntpcfg .= "driftfile {$driftfile}\n";
2130

    
2131
	/* Default Access restrictions */
2132
	$ntpcfg .= 'restrict default';
2133
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2134
		$ntpcfg .= ' kod limited';
2135
	}
2136
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2137
		$ntpcfg .= ' nomodify';
2138
	}
2139
	if (!empty($config['ntpd']['noquery'])) {
2140
		$ntpcfg .= ' noquery';
2141
	}
2142
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2143
		$ntpcfg .= ' nopeer';
2144
	}
2145
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2146
		$ntpcfg .= ' notrap';
2147
	}
2148
	if (!empty($config['ntpd']['noserve'])) {
2149
		$ntpcfg .= ' noserve';
2150
	}
2151
	$ntpcfg .= "\nrestrict -6 default";
2152
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2153
		$ntpcfg .= ' kod limited';
2154
	}
2155
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2156
		$ntpcfg .= ' nomodify';
2157
	}
2158
	if (!empty($config['ntpd']['noquery'])) {
2159
		$ntpcfg .= ' noquery';
2160
	}
2161
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2162
		$ntpcfg .= ' nopeer';
2163
	}
2164
	if (!empty($config['ntpd']['noserve'])) {
2165
		$ntpcfg .= ' noserve';
2166
	}
2167
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2168
		$ntpcfg .= ' notrap';
2169
	}
2170

    
2171
	/* Pools require "restrict source" and cannot contain "nopeer". */
2172
	if ($have_pools) {
2173
		$ntpcfg .= "\nrestrict source";
2174
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2175
			$ntpcfg .= ' kod limited';
2176
		}
2177
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2178
			$ntpcfg .= ' nomodify';
2179
		}
2180
		if (!empty($config['ntpd']['noquery'])) {
2181
			$ntpcfg .= ' noquery';
2182
		}
2183
		if (!empty($config['ntpd']['noserve'])) {
2184
			$ntpcfg .= ' noserve';
2185
		}
2186
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2187
			$ntpcfg .= ' notrap';
2188
		}
2189
	}
2190

    
2191
	/* Custom Access Restrictions */
2192
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2193
		$networkacl = $config['ntpd']['restrictions']['row'];
2194
		foreach ($networkacl as $acl) {
2195
			$restrict = "";
2196
			if (is_ipaddrv6($acl['acl_network'])) {
2197
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2198
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2199
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2200
			} else {
2201
				continue;
2202
			}
2203
			if (!empty($acl['kod'])) {
2204
				$restrict .= ' kod limited';
2205
			}
2206
			if (!empty($acl['nomodify'])) {
2207
				$restrict .= ' nomodify';
2208
			}
2209
			if (!empty($acl['noquery'])) {
2210
				$restrict .= ' noquery';
2211
			}
2212
			if (!empty($acl['nopeer'])) {
2213
				$restrict .= ' nopeer';
2214
			}
2215
			if (!empty($acl['noserve'])) {
2216
				$restrict .= ' noserve';
2217
			}
2218
			if (!empty($acl['notrap'])) {
2219
				$restrict .= ' notrap';
2220
			}
2221
			if (!empty($restrict)) {
2222
				$ntpcfg .= "\nrestrict {$restrict} ";
2223
			}
2224
		}
2225
	}
2226
	/* End Custom Access Restrictions */
2227

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

    
2236

    
2237
	if (empty($config['ntpd']['interface'])) {
2238
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2239
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2240
		} else {
2241
			$interfaces = array();
2242
		}
2243
	} else {
2244
		$interfaces = explode(",", $config['ntpd']['interface']);
2245
	}
2246

    
2247
	if (is_array($interfaces) && count($interfaces)) {
2248
		$finterfaces = array();
2249
		$ntpcfg .= "interface ignore all\n";
2250
		$ntpcfg .= "interface ignore wildcard\n";
2251
		foreach ($interfaces as $interface) {
2252
			$interface = get_real_interface($interface);
2253
			if (!empty($interface)) {
2254
				$finterfaces[] = $interface;
2255
			}
2256
		}
2257
		foreach ($finterfaces as $interface) {
2258
			$ntpcfg .= "interface listen {$interface}\n";
2259
		}
2260
	}
2261

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

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

    
2274
	/* if /var/empty does not exist, create it */
2275
	if (!is_dir("/var/empty")) {
2276
		mkdir("/var/empty", 0555, true);
2277
	}
2278

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

    
2282
	// Note that we are starting up
2283
	log_error("NTPD is starting up.");
2284
	return;
2285
}
2286

    
2287
function system_halt() {
2288
	global $g;
2289

    
2290
	system_reboot_cleanup();
2291

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

    
2295
function system_reboot() {
2296
	global $g;
2297

    
2298
	system_reboot_cleanup();
2299

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

    
2303
function system_reboot_sync($reroot=false) {
2304
	global $g;
2305

    
2306
	if ($reroot) {
2307
		$args = " -r ";
2308
	}
2309

    
2310
	system_reboot_cleanup();
2311

    
2312
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2313
}
2314

    
2315
function system_reboot_cleanup() {
2316
	global $config, $g, $cpzone;
2317

    
2318
	mwexec("/usr/local/bin/beep.sh stop");
2319
	require_once("captiveportal.inc");
2320
	if (is_array($config['captiveportal'])) {
2321
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2322
			if (!isset($cp['preservedb'])) {
2323
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2324
				captiveportal_radius_stop_all(7); // Admin-Reboot
2325
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2326
				captiveportal_free_dnrules();
2327
			}
2328
			/* Send Accounting-Off packet to the RADIUS server */
2329
			captiveportal_send_server_accounting('off');
2330
		}
2331
	}
2332
	require_once("voucher.inc");
2333
	voucher_save_db_to_config();
2334
	require_once("pkg-utils.inc");
2335
	stop_packages();
2336
}
2337

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

    
2345
	if ($early) {
2346
		$cmdn = "earlyshellcmd";
2347
	} else {
2348
		$cmdn = "shellcmd";
2349
	}
2350

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

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

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

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

    
2363
	}
2364
}
2365

    
2366
function system_dmesg_save() {
2367
	global $g;
2368
	if (isset($config['system']['developerspew'])) {
2369
		$mt = microtime();
2370
		echo "system_dmesg_save() being called $mt\n";
2371
	}
2372

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

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

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

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

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

    
2395
	fclose($fd);
2396
	unset($dmesg);
2397

    
2398
	// vm-bhyve expects dmesg.boot at the standard location
2399
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2400

    
2401
	return 0;
2402
}
2403

    
2404
function system_set_harddisk_standby() {
2405
	global $g, $config;
2406

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

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

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

    
2424
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2425
			// just in case of some weird pfSense platform installs.
2426
			if (count($harddisks) > 0) {
2427
				// Iterate disks and run the camcontrol command for each
2428
				foreach ($harddisks as $harddisk) {
2429
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2430
				}
2431
				if (platform_booting()) {
2432
					echo gettext("done.") . "\n";
2433
				}
2434
			} else if (platform_booting()) {
2435
				echo gettext("failed!") . "\n";
2436
			}
2437
		} else if (platform_booting()) {
2438
			echo gettext("failed!") . "\n";
2439
		}
2440
	}
2441
}
2442

    
2443
function system_setup_sysctl() {
2444
	global $config;
2445
	if (isset($config['system']['developerspew'])) {
2446
		$mt = microtime();
2447
		echo "system_setup_sysctl() being called $mt\n";
2448
	}
2449

    
2450
	activate_sysctls();
2451

    
2452
	if (isset($config['system']['sharednet'])) {
2453
		system_disable_arp_wrong_if();
2454
	}
2455
}
2456

    
2457
function system_disable_arp_wrong_if() {
2458
	global $config;
2459
	if (isset($config['system']['developerspew'])) {
2460
		$mt = microtime();
2461
		echo "system_disable_arp_wrong_if() being called $mt\n";
2462
	}
2463
	set_sysctl(array(
2464
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2465
		"net.link.ether.inet.log_arp_movements" => "0"
2466
	));
2467
}
2468

    
2469
function system_enable_arp_wrong_if() {
2470
	global $config;
2471
	if (isset($config['system']['developerspew'])) {
2472
		$mt = microtime();
2473
		echo "system_enable_arp_wrong_if() being called $mt\n";
2474
	}
2475
	set_sysctl(array(
2476
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2477
		"net.link.ether.inet.log_arp_movements" => "1"
2478
	));
2479
}
2480

    
2481
function enable_watchdog() {
2482
	global $config;
2483
	return;
2484
	$install_watchdog = false;
2485
	$supported_watchdogs = array("Geode");
2486
	$file = file_get_contents("/var/log/dmesg.boot");
2487
	foreach ($supported_watchdogs as $sd) {
2488
		if (stristr($file, "Geode")) {
2489
			$install_watchdog = true;
2490
		}
2491
	}
2492
	if ($install_watchdog == true) {
2493
		if (is_process_running("watchdogd")) {
2494
			mwexec("/usr/bin/killall watchdogd", true);
2495
		}
2496
		exec("/usr/sbin/watchdogd");
2497
	}
2498
}
2499

    
2500
function system_check_reset_button() {
2501
	global $g;
2502

    
2503
	$specplatform = system_identify_specific_platform();
2504

    
2505
	switch ($specplatform['name']) {
2506
		case 'SG-2220':
2507
			$binprefix = "RCC-DFF";
2508
			break;
2509
		case 'alix':
2510
		case 'wrap':
2511
		case 'FW7541':
2512
		case 'APU':
2513
		case 'RCC-VE':
2514
		case 'RCC':
2515
			$binprefix = $specplatform['name'];
2516
			break;
2517
		default:
2518
			return 0;
2519
	}
2520

    
2521
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2522

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

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

    
2534

    
2535
EOD;
2536

    
2537
		reset_factory_defaults();
2538
		system_reboot_sync();
2539
		exit(0);
2540
	}
2541

    
2542
	return 0;
2543
}
2544

    
2545
function system_get_serial() {
2546
	$platform = system_identify_specific_platform();
2547

    
2548
	unset($output);
2549
	if ($platform['name'] == 'Turbot Dual-E') {
2550
		$if_info = pfSense_get_interface_addresses('igb0');
2551
		if (!empty($if_info['hwaddr'])) {
2552
			$serial = str_replace(":", "", $if_info['hwaddr']);
2553
		}
2554
	} else {
2555
		foreach (array('system', 'planar', 'chassis') as $key) {
2556
			unset($output);
2557
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2558
			    $output);
2559
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2560
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2561
				$serial = $output[0];
2562
				break;
2563
			}
2564
		}
2565
	}
2566

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

    
2569
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2570
	    $vm_guest == 'none') {
2571
		return $serial;
2572
	}
2573

    
2574
	return "";
2575
}
2576

    
2577
function system_get_uniqueid() {
2578
	global $g;
2579

    
2580
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2581

    
2582
	if (empty($g['uniqueid'])) {
2583
		if (!file_exists($uniqueid_file)) {
2584
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2585
			    "2>/dev/null");
2586
		}
2587
		if (file_exists($uniqueid_file)) {
2588
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2589
		}
2590
	}
2591

    
2592
	return ($g['uniqueid'] ?: '');
2593
}
2594

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

    
2604
	$hw_model = get_single_sysctl('hw.model');
2605
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2606

    
2607
	/* Try to guess from smbios strings */
2608
	unset($product);
2609
	unset($maker);
2610
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2611
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2612
	switch ($product[0]) {
2613
		case 'FW7541':
2614
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2615
			break;
2616
		case 'APU':
2617
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2618
			break;
2619
		case 'RCC-VE':
2620
			$result = array();
2621
			$result['name'] = 'RCC-VE';
2622

    
2623
			/* Detect specific models */
2624
			if (!function_exists('does_interface_exist')) {
2625
				require_once("interfaces.inc");
2626
			}
2627
			if (!does_interface_exist('igb4')) {
2628
				$result['model'] = 'SG-2440';
2629
			} elseif (strpos($hw_model, "C2558") !== false) {
2630
				$result['model'] = 'SG-4860';
2631
			} elseif (strpos($hw_model, "C2758") !== false) {
2632
				$result['model'] = 'SG-8860';
2633
			} else {
2634
				$result['model'] = 'RCC-VE';
2635
			}
2636
			$result['descr'] = 'Netgate ' . $result['model'];
2637
			return $result;
2638
			break;
2639
		case 'DFFv2':
2640
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2641
			break;
2642
		case 'RCC':
2643
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2644
			break;
2645
		case 'Minnowboard Turbot D0 PLATFORM':
2646
			$result = array();
2647
			$result['name'] = 'Turbot Dual-E';
2648
			/* Detect specific model */
2649
			switch ($hw_ncpu) {
2650
			case '4':
2651
				$result['model'] = 'MBT-4220';
2652
				break;
2653
			case '2':
2654
				$result['model'] = 'MBT-2220';
2655
				break;
2656
			default:
2657
				$result['model'] = $result['name'];
2658
				break;
2659
			}
2660
			$result['descr'] = 'Netgate ' . $result['model'];
2661
			return $result;
2662
			break;
2663
		case 'SYS-5018A-FTN4':
2664
		case 'A1SAi':
2665
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2666
			break;
2667
		case 'SYS-5018D-FN4T':
2668
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2669
			break;
2670
		case 'apu2':
2671
		case 'APU2':
2672
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2673
			break;
2674
		case 'VirtualBox':
2675
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2676
			break;
2677
		case 'Virtual Machine':
2678
			if ($maker[0] == "Microsoft Corporation") {
2679
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2680
			}
2681
			break;
2682
		case 'VMware Virtual Platform':
2683
			if ($maker[0] == "VMware, Inc.") {
2684
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2685
			}
2686
			break;
2687
	}
2688

    
2689
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2690
	    $planar_product);
2691
	if (isset($planar_product[0]) &&
2692
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2693
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2694
	}
2695

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

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

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

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

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

    
2716
	unset($hw_model);
2717

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

    
2724
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2725
}
2726

    
2727
function system_get_dmesg_boot() {
2728
	global $g;
2729

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

    
2733
function system_get_arp_table($resolve_hostnames = false) {
2734
	$params="-a";
2735
	if (!$resolve_hostnames) {
2736
		$params .= "n";
2737
	}
2738

    
2739
	$arp_table = array();
2740
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2741
	if ($rc == 0) {
2742
		$arp_table = json_decode(implode(" ", $rawdata),
2743
		    JSON_OBJECT_AS_ARRAY);
2744
		if ($rc == 0) {
2745
			$arp_table = $arp_table['arp']['arp-cache'];
2746
		}
2747
	}
2748

    
2749
	return $arp_table;
2750
}
2751

    
2752
?>
(48-48/59)