Project

General

Profile

Download (71 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
	if (!function_exists('is_dhcp_server_enabled')) {
613
		require_once('pfsense-utils.inc');
614
	}
615
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
616

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

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

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

    
646
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
647
		if (is_process_running("dhcpleases")) {
648
			sigkillbyname('dhcpleases', "TERM");
649
		}
650
		@unlink($pidfile);
651
		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");
652
	} elseif (isvalidpid($pidfile)) {
653
		sigkillbypid($pidfile, "TERM");
654
		@unlink($pidfile);
655
	}
656
}
657

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

    
665
	$syscfg = $config['system'];
666

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

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

    
674
	return $status;
675
}
676

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

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

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

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

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

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

    
794
	system_staticroutes_configure($interface, false);
795

    
796
	return 0;
797
}
798

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

    
802
	$filterdns_list = array();
803

    
804
	$static_routes = get_staticroutes(false, true);
805
	if (count($static_routes)) {
806
		$gateways_arr = return_gateways_array(false, true);
807

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

    
818
			$gatewayip = $gateway['gateway'];
819
			$interfacegw = $gateway['interface'];
820

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

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

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

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

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

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

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

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

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

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

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

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

    
931
	return 0;
932
}
933

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

    
941
	set_sysctl(array(
942
		"net.inet.ip.forwarding" => "1",
943
		"net.inet6.ip6.forwarding" => "1"
944
	));
945

    
946
	return;
947
}
948

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

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

    
978
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
979
	global $config, $g;
980

    
981
	if ($restart_syslogd) {
982
		/* syslogd does not react well to clog rewriting the file while it is running. */
983
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
984
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
985
		}
986
	}
987
	if (isset($config['system']['disablesyslogclog'])) {
988
		unlink($logfile);
989
		touch($logfile);
990
	} else {
991
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
992
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
993
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
994
	}
995
	if ($restart_syslogd) {
996
		system_syslogd_start();
997
	}
998
}
999

    
1000
function clear_all_log_files($restart = false) {
1001
	global $g;
1002
	if ($restart) {
1003
		/* syslogd does not react well to clog rewriting the file while it is running. */
1004
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1005
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1006
		}
1007
	}
1008

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

    
1014
	if ($restart) {
1015
		system_syslogd_start();
1016
		killbyname("dhcpd");
1017
		if (!function_exists('services_dhcpd_configure')) {
1018
			require_once('services.inc');
1019
		}
1020
		services_dhcpd_configure();
1021
		services_unbound_configure(false);
1022
	}
1023
	return;
1024
}
1025

    
1026
function system_syslogd_start($sighup = false) {
1027
	global $config, $g;
1028
	if (isset($config['system']['developerspew'])) {
1029
		$mt = microtime();
1030
		echo "system_syslogd_start() being called $mt\n";
1031
	}
1032

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

    
1035
	$syslogcfg = $config['syslog'];
1036

    
1037
	if (platform_booting()) {
1038
		echo gettext("Starting syslog...");
1039
	}
1040

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

    
1052
	$syslogd_extra = "";
1053
	if (isset($syslogcfg)) {
1054
		$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');
1055
		$syslogconf = "";
1056
		if ($config['installedpackages']['package']) {
1057
			foreach ($config['installedpackages']['package'] as $package) {
1058
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1059
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1060
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1061
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1062
					}
1063
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1064
				}
1065
			}
1066
		}
1067
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1068
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
1069
		if (!isset($syslogcfg['disablelocallogging'])) {
1070
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1071
		}
1072
		if (isset($syslogcfg['routing'])) {
1073
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1074
		}
1075

    
1076
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
1077
		if (!isset($syslogcfg['disablelocallogging'])) {
1078
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
1079
		}
1080
		if (isset($syslogcfg['ntpd'])) {
1081
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1082
		}
1083

    
1084
		$syslogconf .= "!ppp\n";
1085
		if (!isset($syslogcfg['disablelocallogging'])) {
1086
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
1087
		}
1088
		if (isset($syslogcfg['ppp'])) {
1089
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1090
		}
1091

    
1092
		$syslogconf .= "!poes\n";
1093
		if (!isset($syslogcfg['disablelocallogging'])) {
1094
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
1095
		}
1096
		if (isset($syslogcfg['vpn'])) {
1097
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1098
		}
1099

    
1100
		$syslogconf .= "!l2tps\n";
1101
		if (!isset($syslogcfg['disablelocallogging'])) {
1102
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
1103
		}
1104
		if (isset($syslogcfg['vpn'])) {
1105
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1106
		}
1107

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

    
1116
		$syslogconf .= "!openvpn\n";
1117
		if (!isset($syslogcfg['disablelocallogging'])) {
1118
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
1119
		}
1120
		if (isset($syslogcfg['vpn'])) {
1121
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1122
		}
1123

    
1124
		$syslogconf .= "!dpinger\n";
1125
		if (!isset($syslogcfg['disablelocallogging'])) {
1126
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
1127
		}
1128
		if (isset($syslogcfg['dpinger'])) {
1129
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1130
		}
1131

    
1132
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1133
		if (!isset($syslogcfg['disablelocallogging'])) {
1134
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1135
		}
1136
		if (isset($syslogcfg['resolver'])) {
1137
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1138
		}
1139

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

    
1148
		$syslogconf .= "!relayd\n";
1149
		if (!isset($syslogcfg['disablelocallogging'])) {
1150
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
1151
		}
1152
		if (isset($syslogcfg['relayd'])) {
1153
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1154
		}
1155

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

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

    
1172
		$syslogconf .= "!-{$facilitylist}\n";
1173
		if (!isset($syslogcfg['disablelocallogging'])) {
1174
			$syslogconf .= <<<EOD
1175
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1176
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1177
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1178
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1179
*.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
1180
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1181
*.emerg								*
1182

    
1183
EOD;
1184
		}
1185
		if (isset($syslogcfg['vpn'])) {
1186
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1187
		}
1188
		if (isset($syslogcfg['portalauth'])) {
1189
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1190
		}
1191
		if (isset($syslogcfg['dhcp'])) {
1192
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1193
		}
1194
		if (isset($syslogcfg['system'])) {
1195
			$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");
1196
		}
1197
		if (isset($syslogcfg['logall'])) {
1198
			// Make everything mean everything, including facilities excluded above.
1199
			$syslogconf .= "!*\n";
1200
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1201
		}
1202

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

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

    
1217
		$sourceip = "";
1218
		if (!empty($syslogcfg['sourceip'])) {
1219
			if ($syslogcfg['ipproto'] == "ipv6") {
1220
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1221
				if (!is_ipaddr($ifaddr)) {
1222
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1223
				}
1224
			} else {
1225
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1226
				if (!is_ipaddr($ifaddr)) {
1227
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1228
				}
1229
			}
1230
			if (is_ipaddr($ifaddr)) {
1231
				$sourceip = "-b {$ifaddr}";
1232
			}
1233
		}
1234

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

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

    
1240
	if (isset($config['installedpackages']['package'])) {
1241
		foreach ($config['installedpackages']['package'] as $package) {
1242
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1243
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1244
				$log_sockets[] = $package['logging']['logsocket'];
1245
			}
1246
		}
1247
	}
1248
	
1249
	$syslogd_sockets = "";
1250
	foreach ($log_sockets as $log_socket) {
1251
		// Ensure that the log directory exists
1252
		$logpath = dirname($log_socket);
1253
		safe_mkdir($logpath);
1254
		$syslogd_sockets .= " -l {$log_socket}";
1255
	}
1256

    
1257
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1258
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1259
		$sighup = false;
1260
	}
1261

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

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

    
1274
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1275
	} else {
1276
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1277
	}
1278

    
1279
	if (platform_booting()) {
1280
		echo gettext("done.") . "\n";
1281
	}
1282

    
1283
	return $retval;
1284
}
1285

    
1286
function system_webgui_create_certificate() {
1287
	global $config, $g;
1288

    
1289
	if (!is_array($config['ca'])) {
1290
		$config['ca'] = array();
1291
	}
1292
	$a_ca =& $config['ca'];
1293
	if (!is_array($config['cert'])) {
1294
		$config['cert'] = array();
1295
	}
1296
	$a_cert =& $config['cert'];
1297
	log_error(gettext("Creating SSL Certificate for this host"));
1298

    
1299
	$cert = array();
1300
	$cert['refid'] = uniqid();
1301
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1302
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1303

    
1304
	$dn = array(
1305
		'countryName' => "US",
1306
		'stateOrProvinceName' => "State",
1307
		'localityName' => "Locality",
1308
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1309
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1310
		'commonName' => $cert_hostname,
1311
		'subjectAltName' => "DNS:{$cert_hostname}");
1312
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1313
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1314
		while ($ssl_err = openssl_error_string()) {
1315
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1316
		}
1317
		error_reporting($old_err_level);
1318
		return null;
1319
	}
1320
	error_reporting($old_err_level);
1321

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

    
1328
function system_webgui_start() {
1329
	global $config, $g;
1330

    
1331
	if (platform_booting()) {
1332
		echo gettext("Starting webConfigurator...");
1333
	}
1334

    
1335
	chdir($g['www_path']);
1336

    
1337
	/* defaults */
1338
	$portarg = "80";
1339
	$crt = "";
1340
	$key = "";
1341
	$ca = "";
1342

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

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

    
1357
		if (!$config['system']['webgui']['port']) {
1358
			$portarg = "443";
1359
		}
1360
		$ca = ca_chain($cert);
1361
	}
1362

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

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

    
1371
	sleep(1);
1372

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

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

    
1378
	if (platform_booting()) {
1379
		if ($res == 0) {
1380
			echo gettext("done.") . "\n";
1381
		} else {
1382
			echo gettext("failed!") . "\n";
1383
		}
1384
	}
1385

    
1386
	return $res;
1387
}
1388

    
1389
function system_generate_nginx_config($filename,
1390
	$cert,
1391
	$key,
1392
	$ca,
1393
	$pid_file,
1394
	$port = 80,
1395
	$document_root = "/usr/local/www/",
1396
	$cert_location = "cert.crt",
1397
	$key_location = "cert.key",
1398
	$captive_portal = false) {
1399

    
1400
	global $config, $g;
1401

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

    
1407
	if ($captive_portal !== false) {
1408
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1409
		$cp_hostcheck = "";
1410
		foreach ($cp_interfaces as $cpint) {
1411
			$cpint_ip = get_interface_ip($cpint);
1412
			if (is_ipaddr($cpint_ip)) {
1413
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1414
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1415
				$cp_hostcheck .= "\t\t}\n";
1416
			}
1417
		}
1418
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1419
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1420
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1421
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1422
			$cp_hostcheck .= "\t\t}\n";
1423
		}
1424
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1425
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1426
		$cp_rewrite .= "\t\t}\n";
1427

    
1428
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1429
		if (empty($maxprocperip)) {
1430
			$maxprocperip = 10;
1431
		}
1432
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1433
	}
1434

    
1435
	if (empty($port)) {
1436
		$nginx_port = "80";
1437
	} else {
1438
		$nginx_port = $port;
1439
	}
1440

    
1441
	$memory = get_memory();
1442
	$realmem = $memory[1];
1443

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

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

    
1462
	$nginx_config = <<<EOD
1463
#
1464
# nginx configuration file
1465

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

    
1468
user  root wheel;
1469
worker_processes  {$max_procs};
1470

    
1471
EOD;
1472

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

    
1477
	$nginx_config .= <<<EOD
1478

    
1479
events {
1480
    worker_connections  1024;
1481
}
1482

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

    
1489
	sendfile        on;
1490

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

    
1493
EOD;
1494

    
1495
	if ($captive_portal !== false) {
1496
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1497
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1498
	} else {
1499
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1500
	}
1501

    
1502
	if ($cert <> "" and $key <> "") {
1503
		$nginx_config .= "\n";
1504
		$nginx_config .= "\tserver {\n";
1505
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1506
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1507
		$nginx_config .= "\n";
1508
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1509
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1510
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1511
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1512
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1513
		if ($captive_portal !== false) {
1514
			// leave TLSv1.0 for CP for now for compatibility
1515
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1516
		} else {
1517
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1518
		}
1519
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1520
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1521
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1522
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1523
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1524
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1525
	} else {
1526
		$nginx_config .= "\n";
1527
		$nginx_config .= "\tserver {\n";
1528
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1529
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1530
	}
1531

    
1532
	$nginx_config .= <<<EOD
1533

    
1534
		client_max_body_size 200m;
1535

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

    
1539

    
1540
EOD;
1541

    
1542
	if ($captive_portal !== false) {
1543
		$nginx_config .= <<<EOD
1544
$captive_portal_maxprocperip
1545
$cp_hostcheck
1546
$cp_rewrite
1547
		log_not_found off;
1548

    
1549
EOD;
1550

    
1551
	}
1552

    
1553
	$nginx_config .= <<<EOD
1554
		root "{$document_root}";
1555
		location / {
1556
			index  index.php index.html index.htm;
1557
		}
1558

    
1559
		location ~ \.php$ {
1560
			try_files \$uri =404; #  This line closes a potential security hole
1561
			# ensuring users can't execute uploaded files
1562
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1563
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1564
			fastcgi_index  index.php;
1565
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1566
			# Fix httpoxy - https://httpoxy.org/#fix-now
1567
			fastcgi_param  HTTP_PROXY  "";
1568
			fastcgi_read_timeout 180;
1569
			include        /usr/local/etc/nginx/fastcgi_params;
1570
		}
1571
	}
1572

    
1573
EOD;
1574

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

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

    
1581
	if ($cert <> "" and $key <> "") {
1582
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1583
		if (!$fd) {
1584
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1585
			return 1;
1586
		}
1587
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1588
		if ($ca <> "") {
1589
			$cert_chain = $cert . "\n" . $ca;
1590
		} else {
1591
			$cert_chain = $cert;
1592
		}
1593
		fwrite($fd, $cert_chain);
1594
		fclose($fd);
1595
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1596
		if (!$fd) {
1597
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1598
			return 1;
1599
		}
1600
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1601
		fwrite($fd, $key);
1602
		fclose($fd);
1603
	}
1604

    
1605
	// Add HTTP to HTTPS redirect
1606
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1607
		if ($nginx_port != "443") {
1608
			$redirectport = ":{$nginx_port}";
1609
		}
1610
		$nginx_config .= <<<EOD
1611
	server {
1612
		listen 80;
1613
		listen [::]:80;
1614
		return 301 https://\$http_host$redirectport\$request_uri;
1615
	}
1616

    
1617
EOD;
1618
	}
1619

    
1620
	$nginx_config .= "}\n";
1621

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

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

    
1633
	return 0;
1634

    
1635
}
1636

    
1637
function system_get_timezone_list() {
1638
	global $g;
1639

    
1640
	$file_list = array_merge(
1641
		glob("/usr/share/zoneinfo/[A-Z]*"),
1642
		glob("/usr/share/zoneinfo/*/*"),
1643
		glob("/usr/share/zoneinfo/*/*/*")
1644
	);
1645

    
1646
	if (empty($file_list)) {
1647
		$file_list[] = $g['default_timezone'];
1648
	} else {
1649
		/* Remove directories from list */
1650
		$file_list = array_filter($file_list, function($v) {
1651
			return !is_dir($v);
1652
		});
1653
	}
1654

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

    
1658
	sort($file_list);
1659

    
1660
	return $file_list;
1661
}
1662

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

    
1670
	$syscfg = $config['system'];
1671

    
1672
	if (platform_booting()) {
1673
		echo gettext("Setting timezone...");
1674
	}
1675

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

    
1684
	if (platform_booting()) {
1685
		echo gettext("done.") . "\n";
1686
	}
1687
}
1688

    
1689
function system_ntp_setup_gps($serialport) {
1690
	global $config, $g;
1691
	$gps_device = '/dev/gps0';
1692
	$serialport = '/dev/'.$serialport;
1693

    
1694
	if (!file_exists($serialport)) {
1695
		return false;
1696
	}
1697

    
1698
	conf_mount_rw();
1699
	// Create symlink that ntpd requires
1700
	unlink_if_exists($gps_device);
1701
	@symlink($serialport, $gps_device);
1702

    
1703
	$gpsbaud = '4800';
1704
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1705
		switch ($config['ntpd']['gps']['speed']) {
1706
			case '16':
1707
				$gpsbaud = '9600';
1708
				break;
1709
			case '32':
1710
				$gpsbaud = '19200';
1711
				break;
1712
			case '48':
1713
				$gpsbaud = '38400';
1714
				break;
1715
			case '64':
1716
				$gpsbaud = '57600';
1717
				break;
1718
			case '80':
1719
				$gpsbaud = '115200';
1720
				break;
1721
		}
1722
	}
1723

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

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

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

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

    
1743
	conf_mount_ro();
1744

    
1745
	return true;
1746
}
1747

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

    
1751
	$pps_device = '/dev/pps0';
1752
	$serialport = '/dev/'.$serialport;
1753

    
1754
	if (!file_exists($serialport)) {
1755
		return false;
1756
	}
1757

    
1758
	conf_mount_rw();
1759
	// Create symlink that ntpd requires
1760
	unlink_if_exists($pps_device);
1761
	@symlink($serialport, $pps_device);
1762

    
1763
	conf_mount_ro();
1764

    
1765
	return true;
1766
}
1767

    
1768

    
1769
function system_ntp_configure() {
1770
	global $config, $g;
1771

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

    
1776
	safe_mkdir($statsdir);
1777

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

    
1782
	$ntpcfg = "# \n";
1783
	$ntpcfg .= "# pfSense ntp configuration file \n";
1784
	$ntpcfg .= "# \n\n";
1785
	$ntpcfg .= "tinker panic 0 \n";
1786

    
1787
	/* Add Orphan mode */
1788
	$ntpcfg .= "# Orphan mode stratum\n";
1789
	$ntpcfg .= 'tos orphan ';
1790
	if (!empty($config['ntpd']['orphan'])) {
1791
		$ntpcfg .= $config['ntpd']['orphan'];
1792
	} else {
1793
		$ntpcfg .= '12';
1794
	}
1795
	$ntpcfg .= "\n";
1796

    
1797
	/* Add PPS configuration */
1798
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1799
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1800
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1801
		$ntpcfg .= "\n";
1802
		$ntpcfg .= "# PPS Setup\n";
1803
		$ntpcfg .= 'server 127.127.22.0';
1804
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1805
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1806
			$ntpcfg .= ' prefer';
1807
		}
1808
		if (!empty($config['ntpd']['pps']['noselect'])) {
1809
			$ntpcfg .= ' noselect ';
1810
		}
1811
		$ntpcfg .= "\n";
1812
		$ntpcfg .= 'fudge 127.127.22.0';
1813
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1814
			$ntpcfg .= ' time1 ';
1815
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1816
		}
1817
		if (!empty($config['ntpd']['pps']['flag2'])) {
1818
			$ntpcfg .= ' flag2 1';
1819
		}
1820
		if (!empty($config['ntpd']['pps']['flag3'])) {
1821
			$ntpcfg .= ' flag3 1';
1822
		} else {
1823
			$ntpcfg .= ' flag3 0';
1824
		}
1825
		if (!empty($config['ntpd']['pps']['flag4'])) {
1826
			$ntpcfg .= ' flag4 1';
1827
		}
1828
		if (!empty($config['ntpd']['pps']['refid'])) {
1829
			$ntpcfg .= ' refid ';
1830
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1831
		}
1832
		$ntpcfg .= "\n";
1833
	}
1834
	/* End PPS configuration */
1835

    
1836
	/* Add GPS configuration */
1837
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1838
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1839
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1840
		$ntpcfg .= "\n";
1841
		$ntpcfg .= "# GPS Setup\n";
1842
		$ntpcfg .= 'server 127.127.20.0 mode ';
1843
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1844
			if (!empty($config['ntpd']['gps']['nmea'])) {
1845
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1846
			}
1847
			if (!empty($config['ntpd']['gps']['speed'])) {
1848
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1849
			}
1850
			if (!empty($config['ntpd']['gps']['subsec'])) {
1851
				$ntpmode += 128;
1852
			}
1853
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1854
				$ntpmode += 256;
1855
			}
1856
			$ntpcfg .= (string) $ntpmode;
1857
		} else {
1858
			$ntpcfg .= '0';
1859
		}
1860
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1861
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1862
			$ntpcfg .= ' prefer';
1863
		}
1864
		if (!empty($config['ntpd']['gps']['noselect'])) {
1865
			$ntpcfg .= ' noselect ';
1866
		}
1867
		$ntpcfg .= "\n";
1868
		$ntpcfg .= 'fudge 127.127.20.0';
1869
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1870
			$ntpcfg .= ' time1 ';
1871
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1872
		}
1873
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1874
			$ntpcfg .= ' time2 ';
1875
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1876
		}
1877
		if (!empty($config['ntpd']['gps']['flag1'])) {
1878
			$ntpcfg .= ' flag1 1';
1879
		} else {
1880
			$ntpcfg .= ' flag1 0';
1881
		}
1882
		if (!empty($config['ntpd']['gps']['flag2'])) {
1883
			$ntpcfg .= ' flag2 1';
1884
		}
1885
		if (!empty($config['ntpd']['gps']['flag3'])) {
1886
			$ntpcfg .= ' flag3 1';
1887
		} else {
1888
			$ntpcfg .= ' flag3 0';
1889
		}
1890
		if (!empty($config['ntpd']['gps']['flag4'])) {
1891
			$ntpcfg .= ' flag4 1';
1892
		}
1893
		if (!empty($config['ntpd']['gps']['refid'])) {
1894
			$ntpcfg .= ' refid ';
1895
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1896
		}
1897
		if (!empty($config['ntpd']['gps']['stratum'])) {
1898
			$ntpcfg .= ' stratum ';
1899
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1900
		}
1901
		$ntpcfg .= "\n";
1902
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1903
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1904
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1905
		/* This handles a 2.1 and earlier config */
1906
		$ntpcfg .= "# GPS Setup\n";
1907
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1908
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1909
		// Fall back to local clock if GPS is out of sync?
1910
		$ntpcfg .= "server 127.127.1.0\n";
1911
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1912
	}
1913
	/* End GPS configuration */
1914

    
1915
	$ntpcfg .= "\n\n# Upstream Servers\n";
1916
	/* foreach through ntp servers and write out to ntpd.conf */
1917
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1918
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1919
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1920
			$ntpcfg .= ' prefer';
1921
		}
1922
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1923
			$ntpcfg .= ' noselect';
1924
		}
1925
		$ntpcfg .= "\n";
1926
	}
1927
	unset($ts);
1928

    
1929
	$ntpcfg .= "\n\n";
1930
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1931
		$ntpcfg .= "enable stats\n";
1932
		$ntpcfg .= 'statistics';
1933
		if (!empty($config['ntpd']['clockstats'])) {
1934
			$ntpcfg .= ' clockstats';
1935
		}
1936
		if (!empty($config['ntpd']['loopstats'])) {
1937
			$ntpcfg .= ' loopstats';
1938
		}
1939
		if (!empty($config['ntpd']['peerstats'])) {
1940
			$ntpcfg .= ' peerstats';
1941
		}
1942
		$ntpcfg .= "\n";
1943
	}
1944
	$ntpcfg .= "statsdir {$statsdir}\n";
1945
	$ntpcfg .= 'logconfig =syncall +clockall';
1946
	if (!empty($config['ntpd']['logpeer'])) {
1947
		$ntpcfg .= ' +peerall';
1948
	}
1949
	if (!empty($config['ntpd']['logsys'])) {
1950
		$ntpcfg .= ' +sysall';
1951
	}
1952
	$ntpcfg .= "\n";
1953
	$ntpcfg .= "driftfile {$driftfile}\n";
1954

    
1955
	/* Default Access restrictions */
1956
	$ntpcfg .= 'restrict default';
1957
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1958
		$ntpcfg .= ' kod limited';
1959
	}
1960
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1961
		$ntpcfg .= ' nomodify';
1962
	}
1963
	if (!empty($config['ntpd']['noquery'])) {
1964
		$ntpcfg .= ' noquery';
1965
	}
1966
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1967
		$ntpcfg .= ' nopeer';
1968
	}
1969
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1970
		$ntpcfg .= ' notrap';
1971
	}
1972
	if (!empty($config['ntpd']['noserve'])) {
1973
		$ntpcfg .= ' noserve';
1974
	}
1975
	$ntpcfg .= "\nrestrict -6 default";
1976
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1977
		$ntpcfg .= ' kod limited';
1978
	}
1979
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1980
		$ntpcfg .= ' nomodify';
1981
	}
1982
	if (!empty($config['ntpd']['noquery'])) {
1983
		$ntpcfg .= ' noquery';
1984
	}
1985
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1986
		$ntpcfg .= ' nopeer';
1987
	}
1988
	if (!empty($config['ntpd']['noserve'])) {
1989
		$ntpcfg .= ' noserve';
1990
	}
1991
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1992
		$ntpcfg .= ' notrap';
1993
	}
1994
	/* Custom Access Restrictions */
1995
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1996
		$networkacl = $config['ntpd']['restrictions']['row'];
1997
		foreach ($networkacl as $acl) {
1998
			$restrict = "";
1999
			if (is_ipaddrv6($acl['acl_network'])) {
2000
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2001
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2002
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2003
			} else {
2004
				continue;
2005
			}
2006
			if (!empty($acl['kod'])) {
2007
				$restrict .= ' kod limited';
2008
			}
2009
			if (!empty($acl['nomodify'])) {
2010
				$restrict .= ' nomodify';
2011
			}
2012
			if (!empty($acl['noquery'])) {
2013
				$restrict .= ' noquery';
2014
			}
2015
			if (!empty($acl['nopeer'])) {
2016
				$restrict .= ' nopeer';
2017
			}
2018
			if (!empty($acl['noserve'])) {
2019
				$restrict .= ' noserve';
2020
			}
2021
			if (!empty($acl['notrap'])) {
2022
				$restrict .= ' notrap';
2023
			}
2024
			if (!empty($restrict)) {
2025
				$ntpcfg .= "\nrestrict {$restrict} ";
2026
			}
2027
		}
2028
	}
2029
	/* End Custom Access Restrictions */
2030

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

    
2039

    
2040
	if (empty($config['ntpd']['interface'])) {
2041
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2042
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2043
		} else {
2044
			$interfaces = array();
2045
		}
2046
	} else {
2047
		$interfaces = explode(",", $config['ntpd']['interface']);
2048
	}
2049

    
2050
	if (is_array($interfaces) && count($interfaces)) {
2051
		$finterfaces = array();
2052
		$ntpcfg .= "interface ignore all\n";
2053
		foreach ($interfaces as $interface) {
2054
			$interface = get_real_interface($interface);
2055
			if (!empty($interface)) {
2056
				$finterfaces[] = $interface;
2057
			}
2058
		}
2059
		foreach ($finterfaces as $interface) {
2060
			$ntpcfg .= "interface listen {$interface}\n";
2061
		}
2062
	}
2063

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

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

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

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

    
2084
	// Note that we are starting up
2085
	log_error("NTPD is starting up.");
2086
	return;
2087
}
2088

    
2089
function system_halt() {
2090
	global $g;
2091

    
2092
	system_reboot_cleanup();
2093

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

    
2097
function system_reboot() {
2098
	global $g;
2099

    
2100
	system_reboot_cleanup();
2101

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

    
2105
function system_reboot_sync() {
2106
	global $g;
2107

    
2108
	system_reboot_cleanup();
2109

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

    
2113
function system_reboot_cleanup() {
2114
	global $config, $cpzone, $cpzoneid;
2115

    
2116
	mwexec("/usr/local/bin/beep.sh stop");
2117
	require_once("captiveportal.inc");
2118
	if (is_array($config['captiveportal'])) {
2119
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2120
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2121
			$cpzoneid = $cp[zoneid];
2122
			captiveportal_radius_stop_all(7); // Admin-Reboot
2123
			/* Send Accounting-Off packet to the RADIUS server */
2124
			captiveportal_send_server_accounting(true);
2125
		}
2126
	}
2127
	require_once("voucher.inc");
2128
	voucher_save_db_to_config();
2129
	require_once("pkg-utils.inc");
2130
	stop_packages();
2131
}
2132

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

    
2140
	if ($early) {
2141
		$cmdn = "earlyshellcmd";
2142
	} else {
2143
		$cmdn = "shellcmd";
2144
	}
2145

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

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

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

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

    
2158
	}
2159
}
2160

    
2161
function system_dmesg_save() {
2162
	global $g;
2163
	if (isset($config['system']['developerspew'])) {
2164
		$mt = microtime();
2165
		echo "system_dmesg_save() being called $mt\n";
2166
	}
2167

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

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

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

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

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

    
2190
	fclose($fd);
2191
	unset($dmesg);
2192
	
2193
	// vm-bhyve expects dmesg.boot at the standard location
2194
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2195

    
2196
	return 0;
2197
}
2198

    
2199
function system_set_harddisk_standby() {
2200
	global $g, $config;
2201

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

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

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

    
2219
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2220
			// just in case of some weird pfSense platform installs.
2221
			if (count($harddisks) > 0) {
2222
				// Iterate disks and run the camcontrol command for each
2223
				foreach ($harddisks as $harddisk) {
2224
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2225
				}
2226
				if (platform_booting()) {
2227
					echo gettext("done.") . "\n";
2228
				}
2229
			} else if (platform_booting()) {
2230
				echo gettext("failed!") . "\n";
2231
			}
2232
		} else if (platform_booting()) {
2233
			echo gettext("failed!") . "\n";
2234
		}
2235
	}
2236
}
2237

    
2238
function system_setup_sysctl() {
2239
	global $config;
2240
	if (isset($config['system']['developerspew'])) {
2241
		$mt = microtime();
2242
		echo "system_setup_sysctl() being called $mt\n";
2243
	}
2244

    
2245
	activate_sysctls();
2246

    
2247
	if (isset($config['system']['sharednet'])) {
2248
		system_disable_arp_wrong_if();
2249
	}
2250
}
2251

    
2252
function system_disable_arp_wrong_if() {
2253
	global $config;
2254
	if (isset($config['system']['developerspew'])) {
2255
		$mt = microtime();
2256
		echo "system_disable_arp_wrong_if() being called $mt\n";
2257
	}
2258
	set_sysctl(array(
2259
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2260
		"net.link.ether.inet.log_arp_movements" => "0"
2261
	));
2262
}
2263

    
2264
function system_enable_arp_wrong_if() {
2265
	global $config;
2266
	if (isset($config['system']['developerspew'])) {
2267
		$mt = microtime();
2268
		echo "system_enable_arp_wrong_if() being called $mt\n";
2269
	}
2270
	set_sysctl(array(
2271
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2272
		"net.link.ether.inet.log_arp_movements" => "1"
2273
	));
2274
}
2275

    
2276
function enable_watchdog() {
2277
	global $config;
2278
	return;
2279
	$install_watchdog = false;
2280
	$supported_watchdogs = array("Geode");
2281
	$file = file_get_contents("/var/log/dmesg.boot");
2282
	foreach ($supported_watchdogs as $sd) {
2283
		if (stristr($file, "Geode")) {
2284
			$install_watchdog = true;
2285
		}
2286
	}
2287
	if ($install_watchdog == true) {
2288
		if (is_process_running("watchdogd")) {
2289
			mwexec("/usr/bin/killall watchdogd", true);
2290
		}
2291
		exec("/usr/sbin/watchdogd");
2292
	}
2293
}
2294

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

    
2298
	$specplatform = system_identify_specific_platform();
2299

    
2300
	switch ($specplatform['name']) {
2301
		case 'alix':
2302
		case 'wrap':
2303
		case 'FW7541':
2304
		case 'APU':
2305
		case 'RCC-VE':
2306
		case 'RCC':
2307
		case 'RCC-DFF':
2308
			break;
2309
		default:
2310
			return 0;
2311
	}
2312

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

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

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

    
2326

    
2327
EOD;
2328

    
2329
		reset_factory_defaults();
2330
		system_reboot_sync();
2331
		exit(0);
2332
	}
2333

    
2334
	return 0;
2335
}
2336

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

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

    
2344
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2345
	    $vm_guest == 'none') {
2346
		return $serial;
2347
	}
2348

    
2349
	return get_single_sysctl('kern.hostuuid');
2350
}
2351

    
2352
function system_get_uniqueid() {
2353
	global $g;
2354

    
2355
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2356

    
2357
	if (empty($g['uniqueid'])) {
2358
		if (!file_exists($uniqueid_file)) {
2359
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2360
			    "2>/dev/null");
2361
		}
2362
		if (file_exists($uniqueid_file)) {
2363
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2364
		}
2365
	}
2366

    
2367
	return ($g['uniqueid'] ?: '');
2368
}
2369

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

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

    
2381
	/* Try to guess from smbios strings */
2382
	unset($product);
2383
	unset($maker);
2384
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2385
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2386
	switch ($product[0]) {
2387
		case 'FW7541':
2388
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2389
			break;
2390
		case 'APU':
2391
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2392
			break;
2393
		case 'RCC-VE':
2394
			$result = array();
2395
			$result['name'] = 'RCC-VE';
2396

    
2397
			/* Detect specific models */
2398
			if (!function_exists('does_interface_exist')) {
2399
				require_once("interfaces.inc");
2400
			}
2401
			if (!does_interface_exist('igb4')) {
2402
				$result['model'] = 'SG-2440';
2403
			} elseif (strpos($hw_model, "C2558") !== false) {
2404
				$result['model'] = 'SG-4860';
2405
			} elseif (strpos($hw_model, "C2758") !== false) {
2406
				$result['model'] = 'SG-8860';
2407
			} else {
2408
				$result['model'] = 'RCC-VE';
2409
			}
2410
			$result['descr'] = 'Netgate ' . $result['model'];
2411
			return $result;
2412
			break;
2413
		case 'DFFv2':
2414
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2415
			break;
2416
		case 'RCC':
2417
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2418
			break;
2419
		case 'SYS-5018A-FTN4':
2420
		case 'A1SAi':
2421
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2422
			break;
2423
		case 'SYS-5018D-FN4T':
2424
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2425
			break;
2426
		case 'apu2':
2427
		case 'APU2':
2428
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2429
			break;
2430
		case 'Virtual Machine':
2431
			if ($maker[0] == "Microsoft Corporation") {
2432
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2433
			}
2434
			break;
2435
	}
2436

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

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

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

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

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

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

    
2462
	unset($hw_model);
2463

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

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

    
2474
function system_get_dmesg_boot() {
2475
	global $g;
2476

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

    
2480
?>
(54-54/67)