Project

General

Profile

Download (69.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
7
 * All rights reserved.
8
 *
9
 * originally part of m0n0wall (http://m0n0.ch/wall)
10
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
11
 * All rights reserved.
12
 *
13
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are met:
15
 *
16
 * 1. Redistributions of source code must retain the above copyright notice,
17
 *    this list of conditions and the following disclaimer.
18
 *
19
 * 2. Redistributions in binary form must reproduce the above copyright
20
 *    notice, this list of conditions and the following disclaimer in
21
 *    the documentation and/or other materials provided with the
22
 *    distribution.
23
 *
24
 * 3. All advertising materials mentioning features or use of this software
25
 *    must display the following acknowledgment:
26
 *    "This product includes software developed by the pfSense Project
27
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
28
 *
29
 * 4. The names "pfSense" and "pfSense Project" must not be used to
30
 *    endorse or promote products derived from this software without
31
 *    prior written permission. For written permission, please contact
32
 *    coreteam@pfsense.org.
33
 *
34
 * 5. Products derived from this software may not be called "pfSense"
35
 *    nor may "pfSense" appear in their names without prior written
36
 *    permission of the Electric Sheep Fencing, LLC.
37
 *
38
 * 6. Redistributions of any form whatsoever must retain the following
39
 *    acknowledgment:
40
 *
41
 * "This product includes software developed by the pfSense Project
42
 * for use in the pfSense software distribution (http://www.pfsense.org/).
43
 *
44
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
45
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
47
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
48
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
49
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
50
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
54
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
55
 * OF THE POSSIBILITY OF SUCH DAMAGE.
56
 */
57

    
58
function activate_powerd() {
59
	global $config, $g;
60

    
61
	if (is_process_running("powerd")) {
62
		exec("/usr/bin/killall powerd");
63
	}
64
	if (isset($config['system']['powerd_enable'])) {
65
		if ($g["platform"] == "nanobsd") {
66
			exec("/sbin/kldload cpufreq");
67
		}
68

    
69
		$ac_mode = "hadp";
70
		if (!empty($config['system']['powerd_ac_mode'])) {
71
			$ac_mode = $config['system']['powerd_ac_mode'];
72
		}
73

    
74
		$battery_mode = "hadp";
75
		if (!empty($config['system']['powerd_battery_mode'])) {
76
			$battery_mode = $config['system']['powerd_battery_mode'];
77
		}
78

    
79
		$normal_mode = "hadp";
80
		if (!empty($config['system']['powerd_normal_mode'])) {
81
			$normal_mode = $config['system']['powerd_normal_mode'];
82
		}
83

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

    
88
function get_default_sysctl_value($id) {
89
	global $sysctls;
90

    
91
	if (isset($sysctls[$id])) {
92
		return $sysctls[$id];
93
	}
94
}
95

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

    
100
	return $output[0];
101
}
102

    
103
function system_get_sysctls() {
104
	global $config, $sysctls;
105

    
106
	$disp_sysctl = array();
107
	$disp_cache = array();
108
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
109
		foreach ($config['sysctl']['item'] as $id => $tunable) {
110
			if ($tunable['value'] == "default") {
111
				$value = get_default_sysctl_value($tunable['tunable']);
112
			} else {
113
				$value = $tunable['value'];
114
			}
115

    
116
			$disp_sysctl[$id] = $tunable;
117
			$disp_sysctl[$id]['modified'] = true;
118
			$disp_cache[$tunable['tunable']] = 'set';
119
		}
120
	}
121

    
122
	foreach ($sysctls as $sysctl => $value) {
123
		if (isset($disp_cache[$sysctl])) {
124
			continue;
125
		}
126

    
127
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
128
	}
129
	unset($disp_cache);
130
	return $disp_sysctl;
131
}
132

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

    
136
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
137
		foreach ($config['sysctl']['item'] as $tunable) {
138
			if ($tunable['value'] == "default") {
139
				$value = get_default_sysctl_value($tunable['tunable']);
140
			} else {
141
				$value = $tunable['value'];
142
			}
143

    
144
			$sysctls[$tunable['tunable']] = $value;
145
		}
146
	}
147

    
148
	set_sysctl($sysctls);
149
}
150

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

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

    
159
	$syscfg = $config['system'];
160

    
161
	if ((((isset($config['dnsmasq']['enable'])) &&
162
	      (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
163
	      (empty($config['dnsmasq']['interface']) ||
164
	       in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
165
	     ((isset($config['unbound']['enable'])) &&
166
	      (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
167
	      (empty($config['unbound']['active_interface']) ||
168
	       in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
169
	       in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
170
	     (!isset($config['system']['dnslocalhost']))) {
171
		$resolvconf .= "nameserver 127.0.0.1\n";
172
	}
173

    
174
	if (isset($syscfg['dnsallowoverride'])) {
175
		/* get dynamically assigned DNS servers (if any) */
176
		$ns = array_unique(get_searchdomains());
177
		foreach ($ns as $searchserver) {
178
			if ($searchserver) {
179
				$resolvconf .= "search {$searchserver}\n";
180
			}
181
		}
182
		$ns = array_unique(get_nameservers());
183
		foreach ($ns as $nameserver) {
184
			if ($nameserver) {
185
				$resolvconf .= "nameserver $nameserver\n";
186
			}
187
		}
188
	} else {
189
		$ns = array();
190
		// Do not create blank search/domain lines, it can break tools like dig.
191
		if ($syscfg['domain']) {
192
			$resolvconf .= "search {$syscfg['domain']}\n";
193
		}
194
	}
195
	if (is_array($syscfg['dnsserver'])) {
196
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
197
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
198
				$resolvconf .= "nameserver $sys_dnsserver\n";
199
			}
200
		}
201
	}
202

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

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

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

    
217
	fwrite($fd, $resolvconf);
218
	fclose($fd);
219

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

    
229
	if (!platform_booting()) {
230
		/* restart dhcpd (nameservers may have changed) */
231
		if (!$dynupdate) {
232
			services_dhcpd_configure();
233
		}
234
	}
235

    
236
	/* setup static routes for DNS servers. */
237
	$dnscounter = 1;
238
	$dnsgw = "dns{$dnscounter}gw";
239
	while (isset($config['system'][$dnsgw])) {
240
		/* setup static routes for dns servers */
241
		if (!(empty($config['system'][$dnsgw]) ||
242
		    $config['system'][$dnsgw] == "none")) {
243
			$gwname = $config['system'][$dnsgw];
244
			$gatewayip = lookup_gateway_ip_by_name($gwname);
245
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
246
			/* dns server array starts at 0 */
247
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
248

    
249
			if (is_ipaddr($gatewayip)) {
250
				$cmd = 'change';
251
			} else {
252
				/* Remove old route when disable gw */
253
				$cmd = 'delete';
254
				$gatewayip = '';
255
			}
256

    
257
			mwexec("/sbin/route {$cmd} -host {$inet6}{$dnsserver} {$gatewayip}");
258
			if (isset($config['system']['route-debug'])) {
259
				$mt = microtime();
260
				log_error("ROUTING debug: $mt - route {$cmd} -host {$inet6}{$dnsserver} {$gatewayip}");
261
			}
262
		}
263
		$dnscounter++;
264
		$dnsgw = "dns{$dnscounter}gw";
265
	}
266

    
267
	unlock($dnslock);
268

    
269
	return 0;
270
}
271

    
272
function get_searchdomains() {
273
	global $config, $g;
274

    
275
	$master_list = array();
276

    
277
	// Read in dhclient nameservers
278
	$search_list = glob("/var/etc/searchdomain_*");
279
	if (is_array($search_list)) {
280
		foreach ($search_list as $fdns) {
281
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
282
			if (!is_array($contents)) {
283
				continue;
284
			}
285
			foreach ($contents as $dns) {
286
				if (is_hostname($dns)) {
287
					$master_list[] = $dns;
288
				}
289
			}
290
		}
291
	}
292

    
293
	return $master_list;
294
}
295

    
296
function get_nameservers() {
297
	global $config, $g;
298
	$master_list = array();
299

    
300
	// Read in dhclient nameservers
301
	$dns_lists = glob("/var/etc/nameserver_*");
302
	if (is_array($dns_lists)) {
303
		foreach ($dns_lists as $fdns) {
304
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
305
			if (!is_array($contents)) {
306
				continue;
307
			}
308
			foreach ($contents as $dns) {
309
				if (is_ipaddr($dns)) {
310
					$master_list[] = $dns;
311
				}
312
			}
313
		}
314
	}
315

    
316
	// Read in any extra nameservers
317
	if (file_exists("/var/etc/nameservers.conf")) {
318
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
319
		if (is_array($dns_s)) {
320
			foreach ($dns_s as $dns) {
321
				if (is_ipaddr($dns)) {
322
					$master_list[] = $dns;
323
				}
324
			}
325
		}
326
	}
327

    
328
	return $master_list;
329
}
330

    
331
/* Create localhost + local interfaces entries for /etc/hosts */
332
function system_hosts_local_entries() {
333
	global $config;
334

    
335
	$syscfg = $config['system'];
336

    
337
	$hosts = array();
338
	$hosts[] = array(
339
	    'ipaddr' => '127.0.0.1',
340
	    'fqdn' => 'localhost',
341
	    'name' => 'localhost.' . $syscfg['domain']
342
	);
343
	$hosts[] = array(
344
	    'ipaddr' => '::1',
345
	    'fqdn' => 'localhost',
346
	    'name' => 'localhost.' . $syscfg['domain']
347
	);
348

    
349
	if ($config['interfaces']['lan']) {
350
		$sysiflist = array('lan' => "lan");
351
	} else {
352
		$sysiflist = get_configured_interface_list();
353
	}
354

    
355
	$hosts_if_found = false;
356
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
357
	foreach ($sysiflist as $sysif) {
358
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
359
			continue;
360
		}
361
		$cfgip = get_interface_ip($sysif);
362
		if (is_ipaddrv4($cfgip)) {
363
			$hosts[] = array(
364
			    'ipaddr' => $cfgip,
365
			    'fqdn' => $local_fqdn
366
			);
367
			$hosts_if_found = true;
368
		}
369
		$cfgipv6 = get_interface_ipv6($sysif);
370
		if (is_ipaddrv6($cfgipv6)) {
371
			$hosts[] = array(
372
			    'ipaddr' => $cfgipv6,
373
			    'fqdn' => $local_fqdn
374
			);
375
			$hosts_if_found = true;
376
		}
377
		if ($hosts_if_found == true) {
378
			break;
379
		}
380
	}
381

    
382
	return $hosts;
383
}
384

    
385
/* Read host override entries from dnsmasq or unbound */
386
function system_hosts_override_entries($dnscfg) {
387
	$hosts = array();
388

    
389
	if (!is_array($dnscfg) ||
390
	    !is_array($dnscfg['hosts']) ||
391
	    !isset($dnscfg['enable'])) {
392
		return $hosts;
393
	}
394

    
395
	foreach ($dnscfg['hosts'] as $host) {
396
		$fqdn = '';
397
		if ($host['host'] || $host['host'] == "0") {
398
			$fqdn .= "{$host['host']}.";
399
		}
400
		$fqdn .= $host['domain'];
401

    
402
		$hosts[] = array(
403
		    'ipaddr' => $host['ip'],
404
		    'fqdn' => $fqdn
405
		);
406

    
407
		if (!is_array($host['aliases']) ||
408
		    !is_array($host['aliases']['item'])) {
409
			continue;
410
		}
411

    
412
		foreach ($host['aliases']['item'] as $alias) {
413
			$fqdn = '';
414
			if ($alias['host'] || $alias['host'] == "0") {
415
				$fqdn .= "{$alias['host']}.";
416
			}
417
			$fqdn .= $alias['domain'];
418

    
419
			$hosts[] = array(
420
			    'ipaddr' => $host['ip'],
421
			    'fqdn' => $fqdn
422
			);
423
		}
424
	}
425

    
426
	return $hosts;
427
}
428

    
429
/* Read all dhcpd/dhcpdv6 staticmap entries */
430
function system_hosts_dhcpd_entries() {
431
	global $config;
432

    
433
	$hosts = array();
434
	$syscfg = $config['system'];
435

    
436
	if (is_array($config['dhcpd'])) {
437
		$conf_dhcpd = $config['dhcpd'];
438
	} else {
439
		$conf_dhcpd = array();
440
	}
441

    
442
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
443
		if (!is_array($dhcpifconf['staticmap']) ||
444
		    !isset($dhcpifconf['enable'])) {
445
			continue;
446
		}
447
		foreach ($dhcpifconf['staticmap'] as $host) {
448
			if (!$host['ipaddr'] ||
449
			    !$host['hostname']) {
450
				continue;
451
			}
452

    
453
			$fqdn = $host['hostname'] . ".";
454
			if ($host['domain']) {
455
				$fqdn .= $host['domain'];
456
			} elseif ($dhcpifconf['domain']) {
457
				$fqdn .= $dhcpifconf['domain'];
458
			} else {
459
				$fqdn .= $syscfg['domain'];
460
			}
461

    
462
			$hosts[] = array(
463
			    'ipaddr' => $host['ipaddr'],
464
			    'fqdn' => $fqdn
465
			);
466
		}
467
	}
468
	unset($conf_dhcpd);
469

    
470
	if (is_array($config['dhcpdv6'])) {
471
		$conf_dhcpdv6 = $config['dhcpdv6'];
472
	} else {
473
		$conf_dhcpdv6 = array();
474
	}
475

    
476
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
477
		if (!is_array($dhcpifconf['staticmap']) ||
478
		    !isset($dhcpifconf['enable'])) {
479
			continue;
480
		}
481

    
482
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
483
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
484
		    'track6') {
485
			$isdelegated = true;
486
		} else {
487
			$isdelegated = false;
488
		}
489

    
490
		foreach ($dhcpifconf['staticmap'] as $host) {
491
			$ipaddrv6 = $host['ipaddrv6'];
492

    
493
			if (!$ipaddrv6 || !$host['hostname']) {
494
				continue;
495
			}
496

    
497
			if ($isdelegated) {
498
				/*
499
				 * We are always in an "end-user" subnet
500
				 * here, which all are /64 for IPv6.
501
				 */
502
				$ipaddrv6 = merge_ipv6_delegated_prefix(
503
				    get_interface_ipv6($dhcpif),
504
				    $ipaddrv6, 64);
505
			}
506

    
507
			$fqdn = $host['hostname'] . ".";
508
			if ($host['domain']) {
509
				$fqdn .= $host['domain'];
510
			} else if ($dhcpifconf['domain']) {
511
				$fqdn .= $dhcpifconf['domain'];
512
			} else {
513
				$fqdn .= $syscfg['domain'];
514
			}
515

    
516
			$hosts[] = array(
517
			    'ipaddr' => $ipaddrv6,
518
			    'fqdn' => $fqdn
519
			);
520
		}
521
	}
522
	unset($conf_dhcpdv6);
523

    
524
	return $hosts;
525
}
526

    
527
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
528
function system_hosts_entries($dnscfg) {
529
	$local = system_hosts_local_entries();
530

    
531
	$dns = array();
532
	$dhcpd = array();
533
	if (isset($dnscfg['enable'])) {
534
		$dns = system_hosts_override_entries($dnscfg);
535
		if (isset($dnscfg['regdhcpstatic'])) {
536
			$dhcpd = system_hosts_dhcpd_entries();
537
		}
538
	}
539

    
540
	if (isset($dnscfg['dhcpfirst'])) {
541
		return array_merge($local, $dns, $dhcpd);
542
	} else {
543
		return array_merge($local, $dhcpd, $dns);
544
	}
545
}
546

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

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

    
562
	$syscfg = $config['system'];
563
	$hosts = "";
564
	$lhosts = "";
565
	$dhosts = "";
566

    
567
	$hosts_array = system_hosts_entries($dnsmasqcfg);
568
	foreach ($hosts_array as $host) {
569
		$hosts .= "{$host['ipaddr']}\t{$host['fqdn']}";
570
		if (!empty($host['name'])) {
571
			$hosts .= " {$host['name']}";
572
		}
573
		$hosts .= "\n";
574
	}
575
	unset($hosts_array);
576

    
577
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
578
	if (!$fd) {
579
		log_error(gettext(
580
		    "Error: cannot open hosts file in system_hosts_generate()."
581
		    ));
582
		return 1;
583
	}
584

    
585
	/*
586
	 * Do not remove this because dhcpleases monitors with kqueue it needs
587
	 * to be killed before writing to hosts files.
588
	 */
589
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
590
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
591
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
592
	}
593

    
594
	fwrite($fd, $hosts);
595
	fclose($fd);
596

    
597
	if (isset($config['unbound']['enable'])) {
598
		require_once("unbound.inc");
599
		unbound_hosts_generate();
600
	}
601

    
602
	/* restart dhcpleases */
603
	if (!platform_booting()) {
604
		system_dhcpleases_configure();
605
	}
606

    
607
	return 0;
608
}
609

    
610
function system_dhcpleases_configure() {
611
	global $config, $g;
612

    
613
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
614

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

    
624
		if (isset($config['unbound']['enable'])) {
625
			$dns_pid = "unbound.pid";
626
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
627
		} else {
628
			$dns_pid = "dnsmasq.pid";
629
			$unbound_conf = "";
630
		}
631

    
632
		if (isvalidpid($pidfile)) {
633
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
634
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
635
			if (intval($retval) == 0) {
636
				sigkillbypid($pidfile, "HUP");
637
				return;
638
			} else {
639
				sigkillbypid($pidfile, "TERM");
640
			}
641
		}
642

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

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

    
662
	$syscfg = $config['system'];
663

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

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

    
671
	return $status;
672
}
673

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

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

    
682
	$gatewayip = "";
683
	$interfacegw = "";
684
	$gatewayipv6 = "";
685
	$interfacegwv6 = "";
686
	$foundgw = false;
687
	$foundgwv6 = false;
688
	/* tack on all the hard defined gateways as well */
689
	if (is_array($config['gateways']['gateway_item'])) {
690
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
691
		foreach	($config['gateways']['gateway_item'] as $gateway) {
692
			if (isset($gateway['defaultgw'])) {
693
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
694
					if (strpos($gateway['gateway'], ":")) {
695
						continue;
696
					}
697
					if ($gateway['gateway'] == "dynamic") {
698
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
699
					}
700
					$gatewayip = $gateway['gateway'];
701
					$interfacegw = $gateway['interface'];
702
					if (!empty($gateway['interface'])) {
703
						$defaultif = get_real_interface($gateway['interface']);
704
						if ($defaultif) {
705
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
706
						}
707
					}
708
					$foundgw = true;
709
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
710
					if ($gateway['gateway'] == "dynamic") {
711
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
712
					}
713
					$gatewayipv6 = $gateway['gateway'];
714
					$interfacegwv6 = $gateway['interface'];
715
					if (!empty($gateway['interface'])) {
716
						$defaultifv6 = get_real_interface($gateway['interface']);
717
						if ($defaultifv6) {
718
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
719
						}
720
					}
721
					$foundgwv6 = true;
722
				}
723
			}
724
			if ($foundgw === true && $foundgwv6 === true) {
725
				break;
726
			}
727
		}
728
	}
729
	if ($foundgw == false) {
730
		$defaultif = get_real_interface("wan");
731
		$interfacegw = "wan";
732
		$gatewayip = get_interface_gateway("wan");
733
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
734
	}
735
	if ($foundgwv6 == false) {
736
		$defaultifv6 = get_real_interface("wan");
737
		$interfacegwv6 = "wan";
738
		$gatewayipv6 = get_interface_gateway_v6("wan");
739
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
740
	}
741
	$dont_add_route = false;
742
	/* if OLSRD is enabled, allow WAN to house DHCP. */
743
	if (is_array($config['installedpackages']['olsrd'])) {
744
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
745
			if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
746
				$dont_add_route = true;
747
				log_error(gettext("Not adding default route because OLSR dynamic gateway is enabled."));
748
				break;
749
			}
750
		}
751
	}
752

    
753
	$gateways_arr = return_gateways_array(false, true);
754
	foreach ($gateways_arr as $gateway) {
755
		// setup static interface routes for nonlocal gateways
756
		if (isset($gateway["nonlocalgateway"])) {
757
			$srgatewayip = $gateway['gateway'];
758
			$srinterfacegw = $gateway['interface'];
759
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
760
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
761
				$cmd = "/sbin/route change {$inet} " . escapeshellarg($srgatewayip) . " ";
762
				mwexec($cmd . "-iface " . escapeshellarg($srinterfacegw));
763
				if (isset($config['system']['route-debug'])) {
764
					$mt = microtime();
765
					log_error("ROUTING debug: $mt - $cmd -iface $srinterfacegw ");
766
				}
767
			}
768
		}
769
	}
770

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

    
779
		if (!empty($interface) && $interface != $interfacegwv6) {
780
			;
781
		} else if (is_ipaddrv6($gatewayipv6)) {
782
			$ifscope = "";
783
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
784
				$ifscope = "%{$defaultifv6}";
785
			}
786
			log_error(sprintf(gettext("ROUTING: setting IPv6 default route to %s"), $gatewayipv6 . $ifscope));
787
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
788
		}
789
	}
790

    
791
	system_staticroutes_configure($interface, false);
792

    
793
	return 0;
794
}
795

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

    
799
	$filterdns_list = array();
800

    
801
	$static_routes = get_staticroutes(false, true);
802
	if (count($static_routes)) {
803
		$gateways_arr = return_gateways_array(false, true);
804

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

    
815
			$gatewayip = $gateway['gateway'];
816
			$interfacegw = $gateway['interface'];
817

    
818
			$blackhole = "";
819
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
820
				$blackhole = "-blackhole";
821
			}
822

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

    
827
			$dnscache = array();
828
			if ($update_dns === true) {
829
				if (is_subnet($rtent['network'])) {
830
					continue;
831
				}
832
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
833
				if (empty($dnscache)) {
834
					continue;
835
				}
836
			}
837

    
838
			if (is_subnet($rtent['network'])) {
839
				$ips = array($rtent['network']);
840
			} else {
841
				if (!isset($rtent['disabled'])) {
842
					$filterdns_list[] = $rtent['network'];
843
				}
844
				$ips = add_hostname_to_watch($rtent['network']);
845
			}
846

    
847
			foreach ($dnscache as $ip) {
848
				if (in_array($ip, $ips)) {
849
					continue;
850
				}
851
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
852
				if (isset($config['system']['route-debug'])) {
853
					$mt = microtime();
854
					log_error("ROUTING debug: $mt - route delete $ip ");
855
				}
856
			}
857

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

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

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

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

    
880
				if (is_subnet($ip)) {
881
					if (is_ipaddr($gatewayip)) {
882
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
883
							// add interface scope for link local v6 routes
884
							$gatewayip .= "%$interfacegw";
885
						}
886
						mwexec($cmd . escapeshellarg($gatewayip));
887
						if (isset($config['system']['route-debug'])) {
888
							$mt = microtime();
889
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
890
						}
891
					} else if (!empty($interfacegw)) {
892
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
893
						if (isset($config['system']['route-debug'])) {
894
							$mt = microtime();
895
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
896
						}
897
					}
898
				}
899
			}
900
		}
901
		unset($gateways_arr);
902
	}
903
	unset($static_routes);
904

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

    
916
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
917
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
918
			} else {
919
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
920
			}
921
		} else {
922
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
923
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
924
		}
925
	}
926
	unset($filterdns_list);
927

    
928
	return 0;
929
}
930

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

    
938
	set_sysctl(array(
939
		"net.inet.ip.forwarding" => "1",
940
		"net.inet6.ip6.forwarding" => "1"
941
	));
942

    
943
	return;
944
}
945

    
946
function system_syslogd_fixup_server($server) {
947
	/* If it's an IPv6 IP alone, encase it in brackets */
948
	if (is_ipaddrv6($server)) {
949
		return "[$server]";
950
	} else {
951
		return $server;
952
	}
953
}
954

    
955
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
956
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
957
	$facility .= " ".
958
	$remote_servers = "";
959
	$pad_to  = max(strlen($facility), 56);
960
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
961
	if (isset($syslogcfg['enable'])) {
962
		if ($syslogcfg['remoteserver']) {
963
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
964
		}
965
		if ($syslogcfg['remoteserver2']) {
966
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
967
		}
968
		if ($syslogcfg['remoteserver3']) {
969
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
970
		}
971
	}
972
	return $remote_servers;
973
}
974

    
975
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
976
	global $config, $g;
977
	if ($restart_syslogd) {
978
		exec("/usr/bin/killall syslogd");
979
	}
980
	if (isset($config['system']['disablesyslogclog'])) {
981
		unlink($logfile);
982
		touch($logfile);
983
	} else {
984
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
985
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
986
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
987
	}
988
	if ($restart_syslogd) {
989
		system_syslogd_start();
990
	}
991
}
992

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

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

    
1002
	if ($restart) {
1003
		system_syslogd_start();
1004
		killbyname("dhcpd");
1005
		if (!function_exists('services_dhcpd_configure')) {
1006
			require_once('services.inc');
1007
		}
1008
		services_dhcpd_configure();
1009
		services_unbound_configure(false);
1010
	}
1011
	return;
1012
}
1013

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

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

    
1023
	$syslogcfg = $config['syslog'];
1024

    
1025
	if (platform_booting()) {
1026
		echo gettext("Starting syslog...");
1027
	}
1028

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

    
1040
	$syslogd_extra = "";
1041
	if (isset($syslogcfg)) {
1042
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'olsrd', 'zebra', 'ospfd', 'bgpd', 'miniupnpd', 'filterlog');
1043
		$syslogconf = "";
1044
		if ($config['installedpackages']['package']) {
1045
			foreach ($config['installedpackages']['package'] as $package) {
1046
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1047
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1048
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1049
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1050
					}
1051
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1052
				}
1053
			}
1054
		}
1055
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1056
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
1057
		if (!isset($syslogcfg['disablelocallogging'])) {
1058
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1059
		}
1060
		if (isset($syslogcfg['routing'])) {
1061
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1062
		}
1063

    
1064
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
1065
		if (!isset($syslogcfg['disablelocallogging'])) {
1066
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
1067
		}
1068
		if (isset($syslogcfg['ntpd'])) {
1069
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1070
		}
1071

    
1072
		$syslogconf .= "!ppp\n";
1073
		if (!isset($syslogcfg['disablelocallogging'])) {
1074
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
1075
		}
1076
		if (isset($syslogcfg['ppp'])) {
1077
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1078
		}
1079

    
1080
		$syslogconf .= "!poes\n";
1081
		if (!isset($syslogcfg['disablelocallogging'])) {
1082
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
1083
		}
1084
		if (isset($syslogcfg['vpn'])) {
1085
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1086
		}
1087

    
1088
		$syslogconf .= "!l2tps\n";
1089
		if (!isset($syslogcfg['disablelocallogging'])) {
1090
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
1091
		}
1092
		if (isset($syslogcfg['vpn'])) {
1093
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1094
		}
1095

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

    
1104
		$syslogconf .= "!openvpn\n";
1105
		if (!isset($syslogcfg['disablelocallogging'])) {
1106
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
1107
		}
1108
		if (isset($syslogcfg['vpn'])) {
1109
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1110
		}
1111

    
1112
		$syslogconf .= "!dpinger\n";
1113
		if (!isset($syslogcfg['disablelocallogging'])) {
1114
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
1115
		}
1116
		if (isset($syslogcfg['dpinger'])) {
1117
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1118
		}
1119

    
1120
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1121
		if (!isset($syslogcfg['disablelocallogging'])) {
1122
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1123
		}
1124
		if (isset($syslogcfg['resolver'])) {
1125
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1126
		}
1127

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

    
1136
		$syslogconf .= "!relayd\n";
1137
		if (!isset($syslogcfg['disablelocallogging'])) {
1138
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
1139
		}
1140
		if (isset($syslogcfg['relayd'])) {
1141
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1142
		}
1143

    
1144
		$syslogconf .= "!hostapd\n";
1145
		if (!isset($syslogcfg['disablelocallogging'])) {
1146
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
1147
		}
1148
		if (isset($syslogcfg['hostapd'])) {
1149
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1150
		}
1151

    
1152
		$syslogconf .= "!filterlog\n";
1153
		if (!isset($syslogcfg['disablelocallogging'])) {
1154
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
1155
		}
1156
		if (isset($syslogcfg['filter'])) {
1157
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1158
		}
1159

    
1160
		$syslogconf .= "!-{$facilitylist}\n";
1161
		if (!isset($syslogcfg['disablelocallogging'])) {
1162
			$syslogconf .= <<<EOD
1163
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1164
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1165
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1166
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1167
*.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
1168
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1169
*.emerg								*
1170

    
1171
EOD;
1172
		}
1173
		if (isset($syslogcfg['vpn'])) {
1174
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1175
		}
1176
		if (isset($syslogcfg['portalauth'])) {
1177
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1178
		}
1179
		if (isset($syslogcfg['dhcp'])) {
1180
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1181
		}
1182
		if (isset($syslogcfg['system'])) {
1183
			$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");
1184
		}
1185
		if (isset($syslogcfg['logall'])) {
1186
			// Make everything mean everything, including facilities excluded above.
1187
			$syslogconf .= "!*\n";
1188
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1189
		}
1190

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

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

    
1205
		$sourceip = "";
1206
		if (!empty($syslogcfg['sourceip'])) {
1207
			if ($syslogcfg['ipproto'] == "ipv6") {
1208
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1209
				if (!is_ipaddr($ifaddr)) {
1210
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1211
				}
1212
			} else {
1213
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1214
				if (!is_ipaddr($ifaddr)) {
1215
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1216
				}
1217
			}
1218
			if (is_ipaddr($ifaddr)) {
1219
				$sourceip = "-b {$ifaddr}";
1220
			}
1221
		}
1222

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

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

    
1228
	if (isset($config['installedpackages']['package'])) {
1229
		foreach ($config['installedpackages']['package'] as $package) {
1230
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1231
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1232
				$log_sockets[] = $package['logging']['logsocket'];
1233
			}
1234
		}
1235
	}
1236
	
1237
	$syslogd_sockets = "";
1238
	foreach ($log_sockets as $log_socket) {
1239
		// Ensure that the log directory exists
1240
		$logpath = dirname($log_socket);
1241
		safe_mkdir($logpath);
1242
		$syslogd_sockets .= " -l {$log_socket}";
1243
	}
1244

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

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

    
1256
	$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1257

    
1258
	if (platform_booting()) {
1259
		echo gettext("done.") . "\n";
1260
	}
1261

    
1262
	return $retval;
1263
}
1264

    
1265
function system_webgui_create_certificate() {
1266
	global $config, $g;
1267

    
1268
	if (!is_array($config['ca'])) {
1269
		$config['ca'] = array();
1270
	}
1271
	$a_ca =& $config['ca'];
1272
	if (!is_array($config['cert'])) {
1273
		$config['cert'] = array();
1274
	}
1275
	$a_cert =& $config['cert'];
1276
	log_error(gettext("Creating SSL Certificate for this host"));
1277

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

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

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

    
1305
function system_webgui_start() {
1306
	global $config, $g;
1307

    
1308
	if (platform_booting()) {
1309
		echo gettext("Starting webConfigurator...");
1310
	}
1311

    
1312
	chdir($g['www_path']);
1313

    
1314
	/* defaults */
1315
	$portarg = "80";
1316
	$crt = "";
1317
	$key = "";
1318
	$ca = "";
1319

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

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

    
1334
		if (!$config['system']['webgui']['port']) {
1335
			$portarg = "443";
1336
		}
1337
		$ca = ca_chain($cert);
1338
	}
1339

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

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

    
1348
	sleep(1);
1349

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

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

    
1355
	if (platform_booting()) {
1356
		if ($res == 0) {
1357
			echo gettext("done.") . "\n";
1358
		} else {
1359
			echo gettext("failed!") . "\n";
1360
		}
1361
	}
1362

    
1363
	return $res;
1364
}
1365

    
1366
function system_generate_nginx_config($filename,
1367
	$cert,
1368
	$key,
1369
	$ca,
1370
	$pid_file,
1371
	$port = 80,
1372
	$document_root = "/usr/local/www/",
1373
	$cert_location = "cert.crt",
1374
	$key_location = "cert.key",
1375
	$captive_portal = false) {
1376

    
1377
	global $config, $g;
1378

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

    
1384
	if ($captive_portal !== false) {
1385
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1386
		$cp_hostcheck = "";
1387
		foreach ($cp_interfaces as $cpint) {
1388
			$cpint_ip = get_interface_ip($cpint);
1389
			if (is_ipaddr($cpint_ip)) {
1390
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1391
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1392
				$cp_hostcheck .= "\t\t}\n";
1393
			}
1394
		}
1395
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1396
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1397
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1398
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1399
			$cp_hostcheck .= "\t\t}\n";
1400
		}
1401
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1402
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1403
		$cp_rewrite .= "\t\t}\n";
1404

    
1405
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1406
		if (empty($maxprocperip)) {
1407
			$maxprocperip = 10;
1408
		}
1409
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1410
	}
1411

    
1412
	if (empty($port)) {
1413
		$nginx_port = "80";
1414
	} else {
1415
		$nginx_port = $port;
1416
	}
1417

    
1418
	$memory = get_memory();
1419
	$realmem = $memory[1];
1420

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

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

    
1439
	$nginx_config = <<<EOD
1440
#
1441
# nginx configuration file
1442

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

    
1445
user  root wheel;
1446
worker_processes  {$max_procs};
1447

    
1448
EOD;
1449

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

    
1454
	$nginx_config .= <<<EOD
1455

    
1456
events {
1457
    worker_connections  1024;
1458
}
1459

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

    
1466
	sendfile        on;
1467

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

    
1470
EOD;
1471

    
1472
	if ($captive_portal !== false) {
1473
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1474
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1475
	} else {
1476
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1477
	}
1478

    
1479
	if ($cert <> "" and $key <> "") {
1480
		$nginx_config .= "\n";
1481
		$nginx_config .= "\tserver {\n";
1482
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1483
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1484
		$nginx_config .= "\n";
1485
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1486
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1487
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1488
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1489
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1490
		if ($captive_portal !== false) {
1491
			// leave TLSv1.0 for CP for now for compatibility
1492
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1493
		} else {
1494
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1495
		}
1496
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1497
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1498
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1499
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1500
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1501
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1502
	} else {
1503
		$nginx_config .= "\n";
1504
		$nginx_config .= "\tserver {\n";
1505
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1506
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1507
	}
1508

    
1509
	$nginx_config .= <<<EOD
1510

    
1511
		client_max_body_size 200m;
1512

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

    
1516

    
1517
EOD;
1518

    
1519
	if ($captive_portal !== false) {
1520
		$nginx_config .= <<<EOD
1521
$captive_portal_maxprocperip
1522
$cp_hostcheck
1523
$cp_rewrite
1524
		log_not_found off;
1525

    
1526
EOD;
1527

    
1528
	}
1529

    
1530
	$nginx_config .= <<<EOD
1531
		root "{$document_root}";
1532
		location / {
1533
			index  index.php index.html index.htm;
1534
		}
1535

    
1536
		location ~ \.php$ {
1537
			try_files \$uri =404; #  This line closes a potential security hole
1538
			# ensuring users can't execute uploaded files
1539
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1540
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1541
			fastcgi_index  index.php;
1542
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1543
			# Fix httpoxy - https://httpoxy.org/#fix-now
1544
			fastcgi_param  HTTP_PROXY  "";
1545
			fastcgi_read_timeout 180;
1546
			include        /usr/local/etc/nginx/fastcgi_params;
1547
		}
1548
	}
1549

    
1550
EOD;
1551

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

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

    
1558
	if ($cert <> "" and $key <> "") {
1559
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1560
		if (!$fd) {
1561
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1562
			return 1;
1563
		}
1564
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1565
		if ($ca <> "") {
1566
			$cert_chain = $cert . "\n" . $ca;
1567
		} else {
1568
			$cert_chain = $cert;
1569
		}
1570
		fwrite($fd, $cert_chain);
1571
		fclose($fd);
1572
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1573
		if (!$fd) {
1574
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1575
			return 1;
1576
		}
1577
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1578
		fwrite($fd, $key);
1579
		fclose($fd);
1580
	}
1581

    
1582
	// Add HTTP to HTTPS redirect
1583
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1584
		if ($nginx_port != "443") {
1585
			$redirectport = ":{$nginx_port}";
1586
		}
1587
		$nginx_config .= <<<EOD
1588
	server {
1589
		listen 80;
1590
		listen [::]:80;
1591
		return 301 https://\$http_host$redirectport\$request_uri;
1592
	}
1593

    
1594
EOD;
1595
	}
1596

    
1597
	$nginx_config .= "}\n";
1598

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

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

    
1610
	return 0;
1611

    
1612
}
1613

    
1614
function system_get_timezone_list() {
1615
	global $g;
1616

    
1617
	$file_list = array_merge(
1618
		glob("/usr/share/zoneinfo/[A-Z]*"),
1619
		glob("/usr/share/zoneinfo/*/*"),
1620
		glob("/usr/share/zoneinfo/*/*/*")
1621
	);
1622

    
1623
	if (empty($file_list)) {
1624
		$file_list[] = $g['default_timezone'];
1625
	} else {
1626
		/* Remove directories from list */
1627
		$file_list = array_filter($file_list, function($v) {
1628
			return !is_dir($v);
1629
		});
1630
	}
1631

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

    
1635
	sort($file_list);
1636

    
1637
	return $file_list;
1638
}
1639

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

    
1647
	$syscfg = $config['system'];
1648

    
1649
	if (platform_booting()) {
1650
		echo gettext("Setting timezone...");
1651
	}
1652

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

    
1661
	if (platform_booting()) {
1662
		echo gettext("done.") . "\n";
1663
	}
1664
}
1665

    
1666
function system_ntp_setup_gps($serialport) {
1667
	global $config, $g;
1668
	$gps_device = '/dev/gps0';
1669
	$serialport = '/dev/'.$serialport;
1670

    
1671
	if (!file_exists($serialport)) {
1672
		return false;
1673
	}
1674

    
1675
	conf_mount_rw();
1676
	// Create symlink that ntpd requires
1677
	unlink_if_exists($gps_device);
1678
	@symlink($serialport, $gps_device);
1679

    
1680
	$gpsbaud = '4800';
1681
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1682
		switch ($config['ntpd']['gps']['speed']) {
1683
			case '16':
1684
				$gpsbaud = '9600';
1685
				break;
1686
			case '32':
1687
				$gpsbaud = '19200';
1688
				break;
1689
			case '48':
1690
				$gpsbaud = '38400';
1691
				break;
1692
			case '64':
1693
				$gpsbaud = '57600';
1694
				break;
1695
			case '80':
1696
				$gpsbaud = '115200';
1697
				break;
1698
		}
1699
	}
1700

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

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

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

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

    
1720
	conf_mount_ro();
1721

    
1722
	return true;
1723
}
1724

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

    
1728
	$pps_device = '/dev/pps0';
1729
	$serialport = '/dev/'.$serialport;
1730

    
1731
	if (!file_exists($serialport)) {
1732
		return false;
1733
	}
1734

    
1735
	conf_mount_rw();
1736
	// Create symlink that ntpd requires
1737
	unlink_if_exists($pps_device);
1738
	@symlink($serialport, $pps_device);
1739

    
1740
	conf_mount_ro();
1741

    
1742
	return true;
1743
}
1744

    
1745

    
1746
function system_ntp_configure() {
1747
	global $config, $g;
1748

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

    
1753
	safe_mkdir($statsdir);
1754

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

    
1759
	$ntpcfg = "# \n";
1760
	$ntpcfg .= "# pfSense ntp configuration file \n";
1761
	$ntpcfg .= "# \n\n";
1762
	$ntpcfg .= "tinker panic 0 \n";
1763

    
1764
	/* Add Orphan mode */
1765
	$ntpcfg .= "# Orphan mode stratum\n";
1766
	$ntpcfg .= 'tos orphan ';
1767
	if (!empty($config['ntpd']['orphan'])) {
1768
		$ntpcfg .= $config['ntpd']['orphan'];
1769
	} else {
1770
		$ntpcfg .= '12';
1771
	}
1772
	$ntpcfg .= "\n";
1773

    
1774
	/* Add PPS configuration */
1775
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1776
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1777
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1778
		$ntpcfg .= "\n";
1779
		$ntpcfg .= "# PPS Setup\n";
1780
		$ntpcfg .= 'server 127.127.22.0';
1781
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1782
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1783
			$ntpcfg .= ' prefer';
1784
		}
1785
		if (!empty($config['ntpd']['pps']['noselect'])) {
1786
			$ntpcfg .= ' noselect ';
1787
		}
1788
		$ntpcfg .= "\n";
1789
		$ntpcfg .= 'fudge 127.127.22.0';
1790
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1791
			$ntpcfg .= ' time1 ';
1792
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1793
		}
1794
		if (!empty($config['ntpd']['pps']['flag2'])) {
1795
			$ntpcfg .= ' flag2 1';
1796
		}
1797
		if (!empty($config['ntpd']['pps']['flag3'])) {
1798
			$ntpcfg .= ' flag3 1';
1799
		} else {
1800
			$ntpcfg .= ' flag3 0';
1801
		}
1802
		if (!empty($config['ntpd']['pps']['flag4'])) {
1803
			$ntpcfg .= ' flag4 1';
1804
		}
1805
		if (!empty($config['ntpd']['pps']['refid'])) {
1806
			$ntpcfg .= ' refid ';
1807
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1808
		}
1809
		$ntpcfg .= "\n";
1810
	}
1811
	/* End PPS configuration */
1812

    
1813
	/* Add GPS configuration */
1814
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1815
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1816
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1817
		$ntpcfg .= "\n";
1818
		$ntpcfg .= "# GPS Setup\n";
1819
		$ntpcfg .= 'server 127.127.20.0 mode ';
1820
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1821
			if (!empty($config['ntpd']['gps']['nmea'])) {
1822
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1823
			}
1824
			if (!empty($config['ntpd']['gps']['speed'])) {
1825
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1826
			}
1827
			if (!empty($config['ntpd']['gps']['subsec'])) {
1828
				$ntpmode += 128;
1829
			}
1830
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1831
				$ntpmode += 256;
1832
			}
1833
			$ntpcfg .= (string) $ntpmode;
1834
		} else {
1835
			$ntpcfg .= '0';
1836
		}
1837
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1838
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1839
			$ntpcfg .= ' prefer';
1840
		}
1841
		if (!empty($config['ntpd']['gps']['noselect'])) {
1842
			$ntpcfg .= ' noselect ';
1843
		}
1844
		$ntpcfg .= "\n";
1845
		$ntpcfg .= 'fudge 127.127.20.0';
1846
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1847
			$ntpcfg .= ' time1 ';
1848
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1849
		}
1850
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1851
			$ntpcfg .= ' time2 ';
1852
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1853
		}
1854
		if (!empty($config['ntpd']['gps']['flag1'])) {
1855
			$ntpcfg .= ' flag1 1';
1856
		} else {
1857
			$ntpcfg .= ' flag1 0';
1858
		}
1859
		if (!empty($config['ntpd']['gps']['flag2'])) {
1860
			$ntpcfg .= ' flag2 1';
1861
		}
1862
		if (!empty($config['ntpd']['gps']['flag3'])) {
1863
			$ntpcfg .= ' flag3 1';
1864
		} else {
1865
			$ntpcfg .= ' flag3 0';
1866
		}
1867
		if (!empty($config['ntpd']['gps']['flag4'])) {
1868
			$ntpcfg .= ' flag4 1';
1869
		}
1870
		if (!empty($config['ntpd']['gps']['refid'])) {
1871
			$ntpcfg .= ' refid ';
1872
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1873
		}
1874
		if (!empty($config['ntpd']['gps']['stratum'])) {
1875
			$ntpcfg .= ' stratum ';
1876
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1877
		}
1878
		$ntpcfg .= "\n";
1879
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1880
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1881
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1882
		/* This handles a 2.1 and earlier config */
1883
		$ntpcfg .= "# GPS Setup\n";
1884
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1885
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1886
		// Fall back to local clock if GPS is out of sync?
1887
		$ntpcfg .= "server 127.127.1.0\n";
1888
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1889
	}
1890
	/* End GPS configuration */
1891

    
1892
	$ntpcfg .= "\n\n# Upstream Servers\n";
1893
	/* foreach through ntp servers and write out to ntpd.conf */
1894
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1895
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1896
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1897
			$ntpcfg .= ' prefer';
1898
		}
1899
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1900
			$ntpcfg .= ' noselect';
1901
		}
1902
		$ntpcfg .= "\n";
1903
	}
1904
	unset($ts);
1905

    
1906
	$ntpcfg .= "\n\n";
1907
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1908
		$ntpcfg .= "enable stats\n";
1909
		$ntpcfg .= 'statistics';
1910
		if (!empty($config['ntpd']['clockstats'])) {
1911
			$ntpcfg .= ' clockstats';
1912
		}
1913
		if (!empty($config['ntpd']['loopstats'])) {
1914
			$ntpcfg .= ' loopstats';
1915
		}
1916
		if (!empty($config['ntpd']['peerstats'])) {
1917
			$ntpcfg .= ' peerstats';
1918
		}
1919
		$ntpcfg .= "\n";
1920
	}
1921
	$ntpcfg .= "statsdir {$statsdir}\n";
1922
	$ntpcfg .= 'logconfig =syncall +clockall';
1923
	if (!empty($config['ntpd']['logpeer'])) {
1924
		$ntpcfg .= ' +peerall';
1925
	}
1926
	if (!empty($config['ntpd']['logsys'])) {
1927
		$ntpcfg .= ' +sysall';
1928
	}
1929
	$ntpcfg .= "\n";
1930
	$ntpcfg .= "driftfile {$driftfile}\n";
1931

    
1932
	/* Default Access restrictions */
1933
	$ntpcfg .= 'restrict default';
1934
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1935
		$ntpcfg .= ' kod limited';
1936
	}
1937
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1938
		$ntpcfg .= ' nomodify';
1939
	}
1940
	if (!empty($config['ntpd']['noquery'])) {
1941
		$ntpcfg .= ' noquery';
1942
	}
1943
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1944
		$ntpcfg .= ' nopeer';
1945
	}
1946
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1947
		$ntpcfg .= ' notrap';
1948
	}
1949
	if (!empty($config['ntpd']['noserve'])) {
1950
		$ntpcfg .= ' noserve';
1951
	}
1952
	$ntpcfg .= "\nrestrict -6 default";
1953
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1954
		$ntpcfg .= ' kod limited';
1955
	}
1956
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1957
		$ntpcfg .= ' nomodify';
1958
	}
1959
	if (!empty($config['ntpd']['noquery'])) {
1960
		$ntpcfg .= ' noquery';
1961
	}
1962
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1963
		$ntpcfg .= ' nopeer';
1964
	}
1965
	if (!empty($config['ntpd']['noserve'])) {
1966
		$ntpcfg .= ' noserve';
1967
	}
1968
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1969
		$ntpcfg .= ' notrap';
1970
	}
1971
	/* Custom Access Restrictions */
1972
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1973
		$networkacl = $config['ntpd']['restrictions']['row'];
1974
		foreach ($networkacl as $acl) {
1975
			$restrict = "";
1976
			if (is_ipaddrv6($acl['acl_network'])) {
1977
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1978
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1979
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
1980
			} else {
1981
				continue;
1982
			}
1983
			if (!empty($acl['kod'])) {
1984
				$restrict .= ' kod limited';
1985
			}
1986
			if (!empty($acl['nomodify'])) {
1987
				$restrict .= ' nomodify';
1988
			}
1989
			if (!empty($acl['noquery'])) {
1990
				$restrict .= ' noquery';
1991
			}
1992
			if (!empty($acl['nopeer'])) {
1993
				$restrict .= ' nopeer';
1994
			}
1995
			if (!empty($acl['noserve'])) {
1996
				$restrict .= ' noserve';
1997
			}
1998
			if (!empty($acl['notrap'])) {
1999
				$restrict .= ' notrap';
2000
			}
2001
			if (!empty($restrict)) {
2002
				$ntpcfg .= "\nrestrict {$restrict} ";
2003
			}
2004
		}
2005
	}
2006
	/* End Custom Access Restrictions */
2007

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

    
2016

    
2017
	if (empty($config['ntpd']['interface'])) {
2018
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2019
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2020
		} else {
2021
			$interfaces = array();
2022
		}
2023
	} else {
2024
		$interfaces = explode(",", $config['ntpd']['interface']);
2025
	}
2026

    
2027
	if (is_array($interfaces) && count($interfaces)) {
2028
		$finterfaces = array();
2029
		$ntpcfg .= "interface ignore all\n";
2030
		foreach ($interfaces as $interface) {
2031
			$interface = get_real_interface($interface);
2032
			if (!empty($interface)) {
2033
				$finterfaces[] = $interface;
2034
			}
2035
		}
2036
		foreach ($finterfaces as $interface) {
2037
			$ntpcfg .= "interface listen {$interface}\n";
2038
		}
2039
	}
2040

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

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

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

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

    
2061
	// Note that we are starting up
2062
	log_error("NTPD is starting up.");
2063
	return;
2064
}
2065

    
2066
function system_halt() {
2067
	global $g;
2068

    
2069
	system_reboot_cleanup();
2070

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

    
2074
function system_reboot() {
2075
	global $g;
2076

    
2077
	system_reboot_cleanup();
2078

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

    
2082
function system_reboot_sync() {
2083
	global $g;
2084

    
2085
	system_reboot_cleanup();
2086

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

    
2090
function system_reboot_cleanup() {
2091
	global $config, $cpzone, $cpzoneid;
2092

    
2093
	mwexec("/usr/local/bin/beep.sh stop");
2094
	require_once("captiveportal.inc");
2095
	if (is_array($config['captiveportal'])) {
2096
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2097
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2098
			$cpzoneid = $cp[zoneid];
2099
			captiveportal_radius_stop_all(7); // Admin-Reboot
2100
			/* Send Accounting-Off packet to the RADIUS server */
2101
			captiveportal_send_server_accounting(true);
2102
		}
2103
	}
2104
	require_once("voucher.inc");
2105
	voucher_save_db_to_config();
2106
	require_once("pkg-utils.inc");
2107
	stop_packages();
2108
}
2109

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

    
2117
	if ($early) {
2118
		$cmdn = "earlyshellcmd";
2119
	} else {
2120
		$cmdn = "shellcmd";
2121
	}
2122

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

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

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

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

    
2135
	}
2136
}
2137

    
2138
function system_dmesg_save() {
2139
	global $g;
2140
	if (isset($config['system']['developerspew'])) {
2141
		$mt = microtime();
2142
		echo "system_dmesg_save() being called $mt\n";
2143
	}
2144

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

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

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

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

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

    
2167
	fclose($fd);
2168
	unset($dmesg);
2169
	
2170
	// vm-bhyve expects dmesg.boot at the standard location
2171
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2172

    
2173
	return 0;
2174
}
2175

    
2176
function system_set_harddisk_standby() {
2177
	global $g, $config;
2178

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

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

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

    
2196
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2197
			// just in case of some weird pfSense platform installs.
2198
			if (count($harddisks) > 0) {
2199
				// Iterate disks and run the camcontrol command for each
2200
				foreach ($harddisks as $harddisk) {
2201
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2202
				}
2203
				if (platform_booting()) {
2204
					echo gettext("done.") . "\n";
2205
				}
2206
			} else if (platform_booting()) {
2207
				echo gettext("failed!") . "\n";
2208
			}
2209
		} else if (platform_booting()) {
2210
			echo gettext("failed!") . "\n";
2211
		}
2212
	}
2213
}
2214

    
2215
function system_setup_sysctl() {
2216
	global $config;
2217
	if (isset($config['system']['developerspew'])) {
2218
		$mt = microtime();
2219
		echo "system_setup_sysctl() being called $mt\n";
2220
	}
2221

    
2222
	activate_sysctls();
2223

    
2224
	if (isset($config['system']['sharednet'])) {
2225
		system_disable_arp_wrong_if();
2226
	}
2227
}
2228

    
2229
function system_disable_arp_wrong_if() {
2230
	global $config;
2231
	if (isset($config['system']['developerspew'])) {
2232
		$mt = microtime();
2233
		echo "system_disable_arp_wrong_if() being called $mt\n";
2234
	}
2235
	set_sysctl(array(
2236
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2237
		"net.link.ether.inet.log_arp_movements" => "0"
2238
	));
2239
}
2240

    
2241
function system_enable_arp_wrong_if() {
2242
	global $config;
2243
	if (isset($config['system']['developerspew'])) {
2244
		$mt = microtime();
2245
		echo "system_enable_arp_wrong_if() being called $mt\n";
2246
	}
2247
	set_sysctl(array(
2248
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2249
		"net.link.ether.inet.log_arp_movements" => "1"
2250
	));
2251
}
2252

    
2253
function enable_watchdog() {
2254
	global $config;
2255
	return;
2256
	$install_watchdog = false;
2257
	$supported_watchdogs = array("Geode");
2258
	$file = file_get_contents("/var/log/dmesg.boot");
2259
	foreach ($supported_watchdogs as $sd) {
2260
		if (stristr($file, "Geode")) {
2261
			$install_watchdog = true;
2262
		}
2263
	}
2264
	if ($install_watchdog == true) {
2265
		if (is_process_running("watchdogd")) {
2266
			mwexec("/usr/bin/killall watchdogd", true);
2267
		}
2268
		exec("/usr/sbin/watchdogd");
2269
	}
2270
}
2271

    
2272
function system_check_reset_button() {
2273
	global $g;
2274

    
2275
	$specplatform = system_identify_specific_platform();
2276

    
2277
	switch ($specplatform['name']) {
2278
		case 'alix':
2279
		case 'wrap':
2280
		case 'FW7541':
2281
		case 'APU':
2282
		case 'RCC-VE':
2283
		case 'RCC':
2284
		case 'RCC-DFF':
2285
			break;
2286
		default:
2287
			return 0;
2288
	}
2289

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

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

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

    
2303

    
2304
EOD;
2305

    
2306
		reset_factory_defaults();
2307
		system_reboot_sync();
2308
		exit(0);
2309
	}
2310

    
2311
	return 0;
2312
}
2313

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

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

    
2321
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2322
	    $vm_guest == 'none') {
2323
		return $serial;
2324
	}
2325

    
2326
	return get_single_sysctl('kern.hostuuid');
2327
}
2328

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

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

    
2340
	/* Try to guess from smbios strings */
2341
	unset($product);
2342
	unset($maker);
2343
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2344
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2345
	switch ($product[0]) {
2346
		case 'FW7541':
2347
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2348
			break;
2349
		case 'APU':
2350
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2351
			break;
2352
		case 'RCC-VE':
2353
			$result = array();
2354
			$result['name'] = 'RCC-VE';
2355

    
2356
			/* Detect specific models */
2357
			if (!function_exists('does_interface_exist')) {
2358
				require_once("interfaces.inc");
2359
			}
2360
			if (!does_interface_exist('igb4')) {
2361
				$result['model'] = 'SG-2440';
2362
			} elseif (strpos($hw_model, "C2558") !== false) {
2363
				$result['model'] = 'SG-4860';
2364
			} elseif (strpos($hw_model, "C2758") !== false) {
2365
				$result['model'] = 'SG-8860';
2366
			} else {
2367
				$result['model'] = 'RCC-VE';
2368
			}
2369
			$result['descr'] = 'Netgate ' . $result['model'];
2370
			return $result;
2371
			break;
2372
		case 'DFFv2':
2373
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2374
			break;
2375
		case 'RCC':
2376
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2377
			break;
2378
		case 'SYS-5018A-FTN4':
2379
		case 'A1SAi':
2380
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2381
			break;
2382
		case 'SYS-5018D-FN4T':
2383
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2384
			break;
2385
		case 'apu2':
2386
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2387
			break;
2388
		case 'Virtual Machine':
2389
			if ($maker[0] == "Microsoft Corporation") {
2390
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2391
			}
2392
			break;
2393
	}
2394

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

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

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

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

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

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

    
2420
	unset($hw_model);
2421

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

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

    
2432
function system_get_dmesg_boot() {
2433
	global $g;
2434

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

    
2438
?>
(52-52/65)