Project

General

Profile

Download (71.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-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.' . $syscfg['domain'],
341
	    'name' => 'localhost',
342
	    'domain' => $syscfg['domain']
343
	);
344
	$hosts[] = array(
345
	    'ipaddr' => '::1',
346
	    'fqdn' => 'localhost.' . $syscfg['domain'],
347
	    'name' => 'localhost',
348
	    'domain' => $syscfg['domain']
349
	);
350

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

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

    
388
	return $hosts;
389
}
390

    
391
/* Read host override entries from dnsmasq or unbound */
392
function system_hosts_override_entries($dnscfg) {
393
	$hosts = array();
394

    
395
	if (!is_array($dnscfg) ||
396
	    !is_array($dnscfg['hosts']) ||
397
	    !isset($dnscfg['enable'])) {
398
		return $hosts;
399
	}
400

    
401
	foreach ($dnscfg['hosts'] as $host) {
402
		$fqdn = '';
403
		if ($host['host'] || $host['host'] == "0") {
404
			$fqdn .= "{$host['host']}.";
405
		}
406
		$fqdn .= $host['domain'];
407

    
408
		$hosts[] = array(
409
		    'ipaddr' => $host['ip'],
410
		    'fqdn' => $fqdn,
411
		    'name' => $host['host'],
412
		    'domain' => $host['domain']
413
		);
414

    
415
		if (!is_array($host['aliases']) ||
416
		    !is_array($host['aliases']['item'])) {
417
			continue;
418
		}
419

    
420
		foreach ($host['aliases']['item'] as $alias) {
421
			$fqdn = '';
422
			if ($alias['host'] || $alias['host'] == "0") {
423
				$fqdn .= "{$alias['host']}.";
424
			}
425
			$fqdn .= $alias['domain'];
426

    
427
			$hosts[] = array(
428
			    'ipaddr' => $host['ip'],
429
			    'fqdn' => $fqdn,
430
			    'name' => $alias['host'],
431
			    'domain' => $alias['domain']
432
			);
433
		}
434
	}
435

    
436
	return $hosts;
437
}
438

    
439
/* Read all dhcpd/dhcpdv6 staticmap entries */
440
function system_hosts_dhcpd_entries() {
441
	global $config;
442

    
443
	$hosts = array();
444
	$syscfg = $config['system'];
445

    
446
	if (is_array($config['dhcpd'])) {
447
		$conf_dhcpd = $config['dhcpd'];
448
	} else {
449
		$conf_dhcpd = array();
450
	}
451

    
452
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
453
		if (!is_array($dhcpifconf['staticmap']) ||
454
		    !isset($dhcpifconf['enable'])) {
455
			continue;
456
		}
457
		foreach ($dhcpifconf['staticmap'] as $host) {
458
			if (!$host['ipaddr'] ||
459
			    !$host['hostname']) {
460
				continue;
461
			}
462

    
463
			$fqdn = $host['hostname'] . ".";
464
			$domain = "";
465
			if ($host['domain']) {
466
				$domain = $host['domain'];
467
			} elseif ($dhcpifconf['domain']) {
468
				$domain = $dhcpifconf['domain'];
469
			} else {
470
				$domain = $syscfg['domain'];
471
			}
472

    
473
			$hosts[] = array(
474
			    'ipaddr' => $host['ipaddr'],
475
			    'fqdn' => $fqdn . $domain,
476
			    'name' => $host['hostname'],
477
			    'domain' => $domain
478
			);
479
		}
480
	}
481
	unset($conf_dhcpd);
482

    
483
	if (is_array($config['dhcpdv6'])) {
484
		$conf_dhcpdv6 = $config['dhcpdv6'];
485
	} else {
486
		$conf_dhcpdv6 = array();
487
	}
488

    
489
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
490
		if (!is_array($dhcpifconf['staticmap']) ||
491
		    !isset($dhcpifconf['enable'])) {
492
			continue;
493
		}
494

    
495
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
496
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
497
		    'track6') {
498
			$isdelegated = true;
499
		} else {
500
			$isdelegated = false;
501
		}
502

    
503
		foreach ($dhcpifconf['staticmap'] as $host) {
504
			$ipaddrv6 = $host['ipaddrv6'];
505

    
506
			if (!$ipaddrv6 || !$host['hostname']) {
507
				continue;
508
			}
509

    
510
			if ($isdelegated) {
511
				/*
512
				 * We are always in an "end-user" subnet
513
				 * here, which all are /64 for IPv6.
514
				 */
515
				$ipaddrv6 = merge_ipv6_delegated_prefix(
516
				    get_interface_ipv6($dhcpif),
517
				    $ipaddrv6, 64);
518
			}
519

    
520
			$fqdn = $host['hostname'] . ".";
521
			$domain = "";
522
			if ($host['domain']) {
523
				$domain = $host['domain'];
524
			} elseif ($dhcpifconf['domain']) {
525
				$domain = $dhcpifconf['domain'];
526
			} else {
527
				$domain = $syscfg['domain'];
528
			}
529

    
530
			$hosts[] = array(
531
			    'ipaddr' => $ipaddrv6,
532
			    'fqdn' => $fqdn . $domain,
533
			    'name' => $host['hostname'],
534
			    'domain' => $domain
535
			);
536
		}
537
	}
538
	unset($conf_dhcpdv6);
539

    
540
	return $hosts;
541
}
542

    
543
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
544
function system_hosts_entries($dnscfg) {
545
	$local = system_hosts_local_entries();
546

    
547
	$dns = array();
548
	$dhcpd = array();
549
	if (isset($dnscfg['enable'])) {
550
		$dns = system_hosts_override_entries($dnscfg);
551
		if (isset($dnscfg['regdhcpstatic'])) {
552
			$dhcpd = system_hosts_dhcpd_entries();
553
		}
554
	}
555

    
556
	if (isset($dnscfg['dhcpfirst'])) {
557
		return array_merge($local, $dns, $dhcpd);
558
	} else {
559
		return array_merge($local, $dhcpd, $dns);
560
	}
561
}
562

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

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

    
578
	$syscfg = $config['system'];
579
	$hosts = "";
580
	$lhosts = "";
581
	$dhosts = "";
582

    
583
	$hosts_array = system_hosts_entries($dnsmasqcfg);
584
	foreach ($hosts_array as $host) {
585
		$hosts .= "{$host['ipaddr']}\t";
586
		if ($host['name'] == "localhost") {
587
			$hosts .= "{$host['name']} {$host['fqdn']}";
588
		} else {
589
			$hosts .= "{$host['fqdn']} {$host['name']}";
590
		}
591
		$hosts .= "\n";
592
	}
593
	unset($hosts_array);
594

    
595
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
596
	if (!$fd) {
597
		log_error(gettext(
598
		    "Error: cannot open hosts file in system_hosts_generate()."
599
		    ));
600
		return 1;
601
	}
602

    
603
	/*
604
	 * Do not remove this because dhcpleases monitors with kqueue it needs
605
	 * to be killed before writing to hosts files.
606
	 */
607
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
608
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
609
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
610
	}
611

    
612
	fwrite($fd, $hosts);
613
	fclose($fd);
614

    
615
	if (isset($config['unbound']['enable'])) {
616
		require_once("unbound.inc");
617
		unbound_hosts_generate();
618
	}
619

    
620
	/* restart dhcpleases */
621
	if (!platform_booting()) {
622
		system_dhcpleases_configure();
623
	}
624

    
625
	return 0;
626
}
627

    
628
function system_dhcpleases_configure() {
629
	global $config, $g;
630
	if (!function_exists('is_dhcp_server_enabled')) {
631
		require_once('pfsense-utils.inc');
632
	}
633
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
634

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

    
645
		if (isset($config['unbound']['enable'])) {
646
			$dns_pid = "unbound.pid";
647
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
648
		} else {
649
			$dns_pid = "dnsmasq.pid";
650
			$unbound_conf = "";
651
		}
652

    
653
		if (isvalidpid($pidfile)) {
654
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
655
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
656
			if (intval($retval) == 0) {
657
				sigkillbypid($pidfile, "HUP");
658
				return;
659
			} else {
660
				sigkillbypid($pidfile, "TERM");
661
			}
662
		}
663

    
664
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
665
		if (is_process_running("dhcpleases")) {
666
			sigkillbyname('dhcpleases', "TERM");
667
		}
668
		@unlink($pidfile);
669
		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");
670
	} elseif (isvalidpid($pidfile)) {
671
		sigkillbypid($pidfile, "TERM");
672
		@unlink($pidfile);
673
	}
674
}
675

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

    
683
	$syscfg = $config['system'];
684

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

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

    
692
	return $status;
693
}
694

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

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

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

    
774
	$gateways_arr = return_gateways_array(false, true);
775
	foreach ($gateways_arr as $gateway) {
776
		// setup static interface routes for nonlocal gateways
777
		if (isset($gateway["nonlocalgateway"])) {
778
			$srgatewayip = $gateway['gateway'];
779
			$srinterfacegw = $gateway['interface'];
780
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
781
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
782
				$cmd = "/sbin/route change {$inet} " . escapeshellarg($srgatewayip) . " ";
783
				mwexec($cmd . "-iface " . escapeshellarg($srinterfacegw));
784
				if (isset($config['system']['route-debug'])) {
785
					$mt = microtime();
786
					log_error("ROUTING debug: $mt - $cmd -iface $srinterfacegw ");
787
				}
788
			}
789
		}
790
	}
791

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

    
800
		if (!empty($interface) && $interface != $interfacegwv6) {
801
			;
802
		} else if (is_ipaddrv6($gatewayipv6)) {
803
			$ifscope = "";
804
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
805
				$ifscope = "%{$defaultifv6}";
806
			}
807
			log_error(sprintf(gettext("ROUTING: setting IPv6 default route to %s"), $gatewayipv6 . $ifscope));
808
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
809
		}
810
	}
811

    
812
	system_staticroutes_configure($interface, false);
813

    
814
	return 0;
815
}
816

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

    
820
	$filterdns_list = array();
821

    
822
	$static_routes = get_staticroutes(false, true);
823
	if (count($static_routes)) {
824
		$gateways_arr = return_gateways_array(false, true);
825

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

    
836
			$gatewayip = $gateway['gateway'];
837
			$interfacegw = $gateway['interface'];
838

    
839
			$blackhole = "";
840
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
841
				$blackhole = "-blackhole";
842
			}
843

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

    
848
			$dnscache = array();
849
			if ($update_dns === true) {
850
				if (is_subnet($rtent['network'])) {
851
					continue;
852
				}
853
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
854
				if (empty($dnscache)) {
855
					continue;
856
				}
857
			}
858

    
859
			if (is_subnet($rtent['network'])) {
860
				$ips = array($rtent['network']);
861
			} else {
862
				if (!isset($rtent['disabled'])) {
863
					$filterdns_list[] = $rtent['network'];
864
				}
865
				$ips = add_hostname_to_watch($rtent['network']);
866
			}
867

    
868
			foreach ($dnscache as $ip) {
869
				if (in_array($ip, $ips)) {
870
					continue;
871
				}
872
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
873
				if (isset($config['system']['route-debug'])) {
874
					$mt = microtime();
875
					log_error("ROUTING debug: $mt - route delete $ip ");
876
				}
877
			}
878

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

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

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

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

    
901
				if (is_subnet($ip)) {
902
					if (is_ipaddr($gatewayip)) {
903
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
904
							// add interface scope for link local v6 routes
905
							$gatewayip .= "%$interfacegw";
906
						}
907
						mwexec($cmd . escapeshellarg($gatewayip));
908
						if (isset($config['system']['route-debug'])) {
909
							$mt = microtime();
910
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
911
						}
912
					} else if (!empty($interfacegw)) {
913
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
914
						if (isset($config['system']['route-debug'])) {
915
							$mt = microtime();
916
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
917
						}
918
					}
919
				}
920
			}
921
		}
922
		unset($gateways_arr);
923
	}
924
	unset($static_routes);
925

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

    
937
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
938
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
939
			} else {
940
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
941
			}
942
		} else {
943
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
944
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
945
		}
946
	}
947
	unset($filterdns_list);
948

    
949
	return 0;
950
}
951

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

    
959
	set_sysctl(array(
960
		"net.inet.ip.forwarding" => "1",
961
		"net.inet6.ip6.forwarding" => "1"
962
	));
963

    
964
	return;
965
}
966

    
967
function system_syslogd_fixup_server($server) {
968
	/* If it's an IPv6 IP alone, encase it in brackets */
969
	if (is_ipaddrv6($server)) {
970
		return "[$server]";
971
	} else {
972
		return $server;
973
	}
974
}
975

    
976
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
977
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
978
	$facility .= " ".
979
	$remote_servers = "";
980
	$pad_to  = max(strlen($facility), 56);
981
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
982
	if (isset($syslogcfg['enable'])) {
983
		if ($syslogcfg['remoteserver']) {
984
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
985
		}
986
		if ($syslogcfg['remoteserver2']) {
987
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
988
		}
989
		if ($syslogcfg['remoteserver3']) {
990
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
991
		}
992
	}
993
	return $remote_servers;
994
}
995

    
996
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
997
	global $config, $g;
998

    
999
	if ($restart_syslogd) {
1000
		/* syslogd does not react well to clog rewriting the file while it is running. */
1001
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1002
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1003
		}
1004
	}
1005
	if (isset($config['system']['disablesyslogclog'])) {
1006
		unlink($logfile);
1007
		touch($logfile);
1008
	} else {
1009
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
1010
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
1011
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
1012
	}
1013
	if ($restart_syslogd) {
1014
		system_syslogd_start();
1015
	}
1016
}
1017

    
1018
function clear_all_log_files($restart = false) {
1019
	global $g;
1020
	if ($restart) {
1021
		/* syslogd does not react well to clog rewriting the file while it is running. */
1022
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1023
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1024
		}
1025
	}
1026

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

    
1032
	if ($restart) {
1033
		system_syslogd_start();
1034
		killbyname("dhcpd");
1035
		if (!function_exists('services_dhcpd_configure')) {
1036
			require_once('services.inc');
1037
		}
1038
		services_dhcpd_configure();
1039
		services_unbound_configure(false);
1040
	}
1041
	return;
1042
}
1043

    
1044
function system_syslogd_start($sighup = false) {
1045
	global $config, $g;
1046
	if (isset($config['system']['developerspew'])) {
1047
		$mt = microtime();
1048
		echo "system_syslogd_start() being called $mt\n";
1049
	}
1050

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

    
1053
	$syslogcfg = $config['syslog'];
1054

    
1055
	if (platform_booting()) {
1056
		echo gettext("Starting syslog...");
1057
	}
1058

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

    
1070
	$syslogd_extra = "";
1071
	if (isset($syslogcfg)) {
1072
		$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');
1073
		$syslogconf = "";
1074
		if ($config['installedpackages']['package']) {
1075
			foreach ($config['installedpackages']['package'] as $package) {
1076
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1077
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1078
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1079
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1080
					}
1081
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1082
				}
1083
			}
1084
		}
1085
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1086
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
1087
		if (!isset($syslogcfg['disablelocallogging'])) {
1088
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1089
		}
1090
		if (isset($syslogcfg['routing'])) {
1091
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1092
		}
1093

    
1094
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
1095
		if (!isset($syslogcfg['disablelocallogging'])) {
1096
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
1097
		}
1098
		if (isset($syslogcfg['ntpd'])) {
1099
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1100
		}
1101

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

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

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

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

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

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

    
1150
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1151
		if (!isset($syslogcfg['disablelocallogging'])) {
1152
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1153
		}
1154
		if (isset($syslogcfg['resolver'])) {
1155
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1156
		}
1157

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

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

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

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

    
1190
		$syslogconf .= "!-{$facilitylist}\n";
1191
		if (!isset($syslogcfg['disablelocallogging'])) {
1192
			$syslogconf .= <<<EOD
1193
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1194
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1195
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1196
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1197
*.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
1198
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1199
*.emerg								*
1200

    
1201
EOD;
1202
		}
1203
		if (isset($syslogcfg['vpn'])) {
1204
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1205
		}
1206
		if (isset($syslogcfg['portalauth'])) {
1207
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1208
		}
1209
		if (isset($syslogcfg['dhcp'])) {
1210
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1211
		}
1212
		if (isset($syslogcfg['system'])) {
1213
			$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");
1214
		}
1215
		if (isset($syslogcfg['logall'])) {
1216
			// Make everything mean everything, including facilities excluded above.
1217
			$syslogconf .= "!*\n";
1218
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1219
		}
1220

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

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

    
1235
		$sourceip = "";
1236
		if (!empty($syslogcfg['sourceip'])) {
1237
			if ($syslogcfg['ipproto'] == "ipv6") {
1238
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1239
				if (!is_ipaddr($ifaddr)) {
1240
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1241
				}
1242
			} else {
1243
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1244
				if (!is_ipaddr($ifaddr)) {
1245
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1246
				}
1247
			}
1248
			if (is_ipaddr($ifaddr)) {
1249
				$sourceip = "-b {$ifaddr}";
1250
			}
1251
		}
1252

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

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

    
1258
	if (isset($config['installedpackages']['package'])) {
1259
		foreach ($config['installedpackages']['package'] as $package) {
1260
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1261
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1262
				$log_sockets[] = $package['logging']['logsocket'];
1263
			}
1264
		}
1265
	}
1266
	
1267
	$syslogd_sockets = "";
1268
	foreach ($log_sockets as $log_socket) {
1269
		// Ensure that the log directory exists
1270
		$logpath = dirname($log_socket);
1271
		safe_mkdir($logpath);
1272
		$syslogd_sockets .= " -l {$log_socket}";
1273
	}
1274

    
1275
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1276
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1277
		$sighup = false;
1278
	}
1279

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

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

    
1292
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1293
	} else {
1294
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1295
	}
1296

    
1297
	if (platform_booting()) {
1298
		echo gettext("done.") . "\n";
1299
	}
1300

    
1301
	return $retval;
1302
}
1303

    
1304
function system_webgui_create_certificate() {
1305
	global $config, $g;
1306

    
1307
	if (!is_array($config['ca'])) {
1308
		$config['ca'] = array();
1309
	}
1310
	$a_ca =& $config['ca'];
1311
	if (!is_array($config['cert'])) {
1312
		$config['cert'] = array();
1313
	}
1314
	$a_cert =& $config['cert'];
1315
	log_error(gettext("Creating SSL Certificate for this host"));
1316

    
1317
	$cert = array();
1318
	$cert['refid'] = uniqid();
1319
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1320
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1321

    
1322
	$dn = array(
1323
		'countryName' => "US",
1324
		'stateOrProvinceName' => "State",
1325
		'localityName' => "Locality",
1326
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1327
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1328
		'commonName' => $cert_hostname,
1329
		'subjectAltName' => "DNS:{$cert_hostname}");
1330
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1331
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1332
		while ($ssl_err = openssl_error_string()) {
1333
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1334
		}
1335
		error_reporting($old_err_level);
1336
		return null;
1337
	}
1338
	error_reporting($old_err_level);
1339

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

    
1346
function system_webgui_start() {
1347
	global $config, $g;
1348

    
1349
	if (platform_booting()) {
1350
		echo gettext("Starting webConfigurator...");
1351
	}
1352

    
1353
	chdir($g['www_path']);
1354

    
1355
	/* defaults */
1356
	$portarg = "80";
1357
	$crt = "";
1358
	$key = "";
1359
	$ca = "";
1360

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

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

    
1375
		if (!$config['system']['webgui']['port']) {
1376
			$portarg = "443";
1377
		}
1378
		$ca = ca_chain($cert);
1379
	}
1380

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

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

    
1389
	sleep(1);
1390

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

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

    
1396
	if (platform_booting()) {
1397
		if ($res == 0) {
1398
			echo gettext("done.") . "\n";
1399
		} else {
1400
			echo gettext("failed!") . "\n";
1401
		}
1402
	}
1403

    
1404
	return $res;
1405
}
1406

    
1407
function system_generate_nginx_config($filename,
1408
	$cert,
1409
	$key,
1410
	$ca,
1411
	$pid_file,
1412
	$port = 80,
1413
	$document_root = "/usr/local/www/",
1414
	$cert_location = "cert.crt",
1415
	$key_location = "cert.key",
1416
	$captive_portal = false) {
1417

    
1418
	global $config, $g;
1419

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

    
1425
	if ($captive_portal !== false) {
1426
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1427
		$cp_hostcheck = "";
1428
		foreach ($cp_interfaces as $cpint) {
1429
			$cpint_ip = get_interface_ip($cpint);
1430
			if (is_ipaddr($cpint_ip)) {
1431
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1432
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1433
				$cp_hostcheck .= "\t\t}\n";
1434
			}
1435
		}
1436
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1437
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1438
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1439
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1440
			$cp_hostcheck .= "\t\t}\n";
1441
		}
1442
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1443
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1444
		$cp_rewrite .= "\t\t}\n";
1445

    
1446
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1447
		if (empty($maxprocperip)) {
1448
			$maxprocperip = 10;
1449
		}
1450
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1451
	}
1452

    
1453
	if (empty($port)) {
1454
		$nginx_port = "80";
1455
	} else {
1456
		$nginx_port = $port;
1457
	}
1458

    
1459
	$memory = get_memory();
1460
	$realmem = $memory[1];
1461

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

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

    
1480
	$nginx_config = <<<EOD
1481
#
1482
# nginx configuration file
1483

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

    
1486
user  root wheel;
1487
worker_processes  {$max_procs};
1488

    
1489
EOD;
1490

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

    
1495
	$nginx_config .= <<<EOD
1496

    
1497
events {
1498
    worker_connections  1024;
1499
}
1500

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

    
1507
	sendfile        on;
1508

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

    
1511
EOD;
1512

    
1513
	if ($captive_portal !== false) {
1514
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1515
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1516
	} else {
1517
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1518
	}
1519

    
1520
	if ($cert <> "" and $key <> "") {
1521
		$nginx_config .= "\n";
1522
		$nginx_config .= "\tserver {\n";
1523
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1524
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1525
		$nginx_config .= "\n";
1526
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1527
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1528
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1529
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1530
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1531
		if ($captive_portal !== false) {
1532
			// leave TLSv1.0 for CP for now for compatibility
1533
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1534
		} else {
1535
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1536
		}
1537
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1538
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1539
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1540
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1541
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1542
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1543
	} else {
1544
		$nginx_config .= "\n";
1545
		$nginx_config .= "\tserver {\n";
1546
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1547
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1548
	}
1549

    
1550
	$nginx_config .= <<<EOD
1551

    
1552
		client_max_body_size 200m;
1553

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

    
1557

    
1558
EOD;
1559

    
1560
	if ($captive_portal !== false) {
1561
		$nginx_config .= <<<EOD
1562
$captive_portal_maxprocperip
1563
$cp_hostcheck
1564
$cp_rewrite
1565
		log_not_found off;
1566

    
1567
EOD;
1568

    
1569
	}
1570

    
1571
	$nginx_config .= <<<EOD
1572
		root "{$document_root}";
1573
		location / {
1574
			index  index.php index.html index.htm;
1575
		}
1576

    
1577
		location ~ \.php$ {
1578
			try_files \$uri =404; #  This line closes a potential security hole
1579
			# ensuring users can't execute uploaded files
1580
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1581
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1582
			fastcgi_index  index.php;
1583
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1584
			# Fix httpoxy - https://httpoxy.org/#fix-now
1585
			fastcgi_param  HTTP_PROXY  "";
1586
			fastcgi_read_timeout 180;
1587
			include        /usr/local/etc/nginx/fastcgi_params;
1588
		}
1589
	}
1590

    
1591
EOD;
1592

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

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

    
1599
	if ($cert <> "" and $key <> "") {
1600
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1601
		if (!$fd) {
1602
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1603
			return 1;
1604
		}
1605
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1606
		if ($ca <> "") {
1607
			$cert_chain = $cert . "\n" . $ca;
1608
		} else {
1609
			$cert_chain = $cert;
1610
		}
1611
		fwrite($fd, $cert_chain);
1612
		fclose($fd);
1613
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1614
		if (!$fd) {
1615
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1616
			return 1;
1617
		}
1618
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1619
		fwrite($fd, $key);
1620
		fclose($fd);
1621
	}
1622

    
1623
	// Add HTTP to HTTPS redirect
1624
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1625
		if ($nginx_port != "443") {
1626
			$redirectport = ":{$nginx_port}";
1627
		}
1628
		$nginx_config .= <<<EOD
1629
	server {
1630
		listen 80;
1631
		listen [::]:80;
1632
		return 301 https://\$http_host$redirectport\$request_uri;
1633
	}
1634

    
1635
EOD;
1636
	}
1637

    
1638
	$nginx_config .= "}\n";
1639

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

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

    
1651
	return 0;
1652

    
1653
}
1654

    
1655
function system_get_timezone_list() {
1656
	global $g;
1657

    
1658
	$file_list = array_merge(
1659
		glob("/usr/share/zoneinfo/[A-Z]*"),
1660
		glob("/usr/share/zoneinfo/*/*"),
1661
		glob("/usr/share/zoneinfo/*/*/*")
1662
	);
1663

    
1664
	if (empty($file_list)) {
1665
		$file_list[] = $g['default_timezone'];
1666
	} else {
1667
		/* Remove directories from list */
1668
		$file_list = array_filter($file_list, function($v) {
1669
			return !is_dir($v);
1670
		});
1671
	}
1672

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

    
1676
	sort($file_list);
1677

    
1678
	return $file_list;
1679
}
1680

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

    
1688
	$syscfg = $config['system'];
1689

    
1690
	if (platform_booting()) {
1691
		echo gettext("Setting timezone...");
1692
	}
1693

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

    
1702
	if (platform_booting()) {
1703
		echo gettext("done.") . "\n";
1704
	}
1705
}
1706

    
1707
function system_ntp_setup_gps($serialport) {
1708
	global $config, $g;
1709
	$gps_device = '/dev/gps0';
1710
	$serialport = '/dev/'.$serialport;
1711

    
1712
	if (!file_exists($serialport)) {
1713
		return false;
1714
	}
1715

    
1716
	conf_mount_rw();
1717
	// Create symlink that ntpd requires
1718
	unlink_if_exists($gps_device);
1719
	@symlink($serialport, $gps_device);
1720

    
1721
	$gpsbaud = '4800';
1722
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1723
		switch ($config['ntpd']['gps']['speed']) {
1724
			case '16':
1725
				$gpsbaud = '9600';
1726
				break;
1727
			case '32':
1728
				$gpsbaud = '19200';
1729
				break;
1730
			case '48':
1731
				$gpsbaud = '38400';
1732
				break;
1733
			case '64':
1734
				$gpsbaud = '57600';
1735
				break;
1736
			case '80':
1737
				$gpsbaud = '115200';
1738
				break;
1739
		}
1740
	}
1741

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

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

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

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

    
1761
	conf_mount_ro();
1762

    
1763
	return true;
1764
}
1765

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

    
1769
	$pps_device = '/dev/pps0';
1770
	$serialport = '/dev/'.$serialport;
1771

    
1772
	if (!file_exists($serialport)) {
1773
		return false;
1774
	}
1775

    
1776
	conf_mount_rw();
1777
	// Create symlink that ntpd requires
1778
	unlink_if_exists($pps_device);
1779
	@symlink($serialport, $pps_device);
1780

    
1781
	conf_mount_ro();
1782

    
1783
	return true;
1784
}
1785

    
1786

    
1787
function system_ntp_configure() {
1788
	global $config, $g;
1789

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

    
1794
	safe_mkdir($statsdir);
1795

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

    
1800
	$ntpcfg = "# \n";
1801
	$ntpcfg .= "# pfSense ntp configuration file \n";
1802
	$ntpcfg .= "# \n\n";
1803
	$ntpcfg .= "tinker panic 0 \n";
1804

    
1805
	/* Add Orphan mode */
1806
	$ntpcfg .= "# Orphan mode stratum\n";
1807
	$ntpcfg .= 'tos orphan ';
1808
	if (!empty($config['ntpd']['orphan'])) {
1809
		$ntpcfg .= $config['ntpd']['orphan'];
1810
	} else {
1811
		$ntpcfg .= '12';
1812
	}
1813
	$ntpcfg .= "\n";
1814

    
1815
	/* Add PPS configuration */
1816
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1817
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1818
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1819
		$ntpcfg .= "\n";
1820
		$ntpcfg .= "# PPS Setup\n";
1821
		$ntpcfg .= 'server 127.127.22.0';
1822
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1823
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1824
			$ntpcfg .= ' prefer';
1825
		}
1826
		if (!empty($config['ntpd']['pps']['noselect'])) {
1827
			$ntpcfg .= ' noselect ';
1828
		}
1829
		$ntpcfg .= "\n";
1830
		$ntpcfg .= 'fudge 127.127.22.0';
1831
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1832
			$ntpcfg .= ' time1 ';
1833
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1834
		}
1835
		if (!empty($config['ntpd']['pps']['flag2'])) {
1836
			$ntpcfg .= ' flag2 1';
1837
		}
1838
		if (!empty($config['ntpd']['pps']['flag3'])) {
1839
			$ntpcfg .= ' flag3 1';
1840
		} else {
1841
			$ntpcfg .= ' flag3 0';
1842
		}
1843
		if (!empty($config['ntpd']['pps']['flag4'])) {
1844
			$ntpcfg .= ' flag4 1';
1845
		}
1846
		if (!empty($config['ntpd']['pps']['refid'])) {
1847
			$ntpcfg .= ' refid ';
1848
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1849
		}
1850
		$ntpcfg .= "\n";
1851
	}
1852
	/* End PPS configuration */
1853

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

    
1933
	$ntpcfg .= "\n\n# Upstream Servers\n";
1934
	/* foreach through ntp servers and write out to ntpd.conf */
1935
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1936
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1937
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1938
			$ntpcfg .= ' prefer';
1939
		}
1940
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1941
			$ntpcfg .= ' noselect';
1942
		}
1943
		$ntpcfg .= "\n";
1944
	}
1945
	unset($ts);
1946

    
1947
	$ntpcfg .= "\n\n";
1948
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1949
		$ntpcfg .= "enable stats\n";
1950
		$ntpcfg .= 'statistics';
1951
		if (!empty($config['ntpd']['clockstats'])) {
1952
			$ntpcfg .= ' clockstats';
1953
		}
1954
		if (!empty($config['ntpd']['loopstats'])) {
1955
			$ntpcfg .= ' loopstats';
1956
		}
1957
		if (!empty($config['ntpd']['peerstats'])) {
1958
			$ntpcfg .= ' peerstats';
1959
		}
1960
		$ntpcfg .= "\n";
1961
	}
1962
	$ntpcfg .= "statsdir {$statsdir}\n";
1963
	$ntpcfg .= 'logconfig =syncall +clockall';
1964
	if (!empty($config['ntpd']['logpeer'])) {
1965
		$ntpcfg .= ' +peerall';
1966
	}
1967
	if (!empty($config['ntpd']['logsys'])) {
1968
		$ntpcfg .= ' +sysall';
1969
	}
1970
	$ntpcfg .= "\n";
1971
	$ntpcfg .= "driftfile {$driftfile}\n";
1972

    
1973
	/* Default Access restrictions */
1974
	$ntpcfg .= 'restrict default';
1975
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1976
		$ntpcfg .= ' kod limited';
1977
	}
1978
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1979
		$ntpcfg .= ' nomodify';
1980
	}
1981
	if (!empty($config['ntpd']['noquery'])) {
1982
		$ntpcfg .= ' noquery';
1983
	}
1984
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1985
		$ntpcfg .= ' nopeer';
1986
	}
1987
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1988
		$ntpcfg .= ' notrap';
1989
	}
1990
	if (!empty($config['ntpd']['noserve'])) {
1991
		$ntpcfg .= ' noserve';
1992
	}
1993
	$ntpcfg .= "\nrestrict -6 default";
1994
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1995
		$ntpcfg .= ' kod limited';
1996
	}
1997
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1998
		$ntpcfg .= ' nomodify';
1999
	}
2000
	if (!empty($config['ntpd']['noquery'])) {
2001
		$ntpcfg .= ' noquery';
2002
	}
2003
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2004
		$ntpcfg .= ' nopeer';
2005
	}
2006
	if (!empty($config['ntpd']['noserve'])) {
2007
		$ntpcfg .= ' noserve';
2008
	}
2009
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2010
		$ntpcfg .= ' notrap';
2011
	}
2012
	/* Custom Access Restrictions */
2013
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2014
		$networkacl = $config['ntpd']['restrictions']['row'];
2015
		foreach ($networkacl as $acl) {
2016
			$restrict = "";
2017
			if (is_ipaddrv6($acl['acl_network'])) {
2018
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2019
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2020
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2021
			} else {
2022
				continue;
2023
			}
2024
			if (!empty($acl['kod'])) {
2025
				$restrict .= ' kod limited';
2026
			}
2027
			if (!empty($acl['nomodify'])) {
2028
				$restrict .= ' nomodify';
2029
			}
2030
			if (!empty($acl['noquery'])) {
2031
				$restrict .= ' noquery';
2032
			}
2033
			if (!empty($acl['nopeer'])) {
2034
				$restrict .= ' nopeer';
2035
			}
2036
			if (!empty($acl['noserve'])) {
2037
				$restrict .= ' noserve';
2038
			}
2039
			if (!empty($acl['notrap'])) {
2040
				$restrict .= ' notrap';
2041
			}
2042
			if (!empty($restrict)) {
2043
				$ntpcfg .= "\nrestrict {$restrict} ";
2044
			}
2045
		}
2046
	}
2047
	/* End Custom Access Restrictions */
2048

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

    
2057

    
2058
	if (empty($config['ntpd']['interface'])) {
2059
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2060
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2061
		} else {
2062
			$interfaces = array();
2063
		}
2064
	} else {
2065
		$interfaces = explode(",", $config['ntpd']['interface']);
2066
	}
2067

    
2068
	if (is_array($interfaces) && count($interfaces)) {
2069
		$finterfaces = array();
2070
		$ntpcfg .= "interface ignore all\n";
2071
		foreach ($interfaces as $interface) {
2072
			$interface = get_real_interface($interface);
2073
			if (!empty($interface)) {
2074
				$finterfaces[] = $interface;
2075
			}
2076
		}
2077
		foreach ($finterfaces as $interface) {
2078
			$ntpcfg .= "interface listen {$interface}\n";
2079
		}
2080
	}
2081

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

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

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

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

    
2102
	// Note that we are starting up
2103
	log_error("NTPD is starting up.");
2104
	return;
2105
}
2106

    
2107
function system_halt() {
2108
	global $g;
2109

    
2110
	system_reboot_cleanup();
2111

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

    
2115
function system_reboot() {
2116
	global $g;
2117

    
2118
	system_reboot_cleanup();
2119

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

    
2123
function system_reboot_sync() {
2124
	global $g;
2125

    
2126
	system_reboot_cleanup();
2127

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

    
2131
function system_reboot_cleanup() {
2132
	global $config, $cpzone, $cpzoneid;
2133

    
2134
	mwexec("/usr/local/bin/beep.sh stop");
2135
	require_once("captiveportal.inc");
2136
	if (is_array($config['captiveportal'])) {
2137
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2138
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2139
			$cpzoneid = $cp[zoneid];
2140
			captiveportal_radius_stop_all(7); // Admin-Reboot
2141
			/* Send Accounting-Off packet to the RADIUS server */
2142
			captiveportal_send_server_accounting(true);
2143
		}
2144
	}
2145
	require_once("voucher.inc");
2146
	voucher_save_db_to_config();
2147
	require_once("pkg-utils.inc");
2148
	stop_packages();
2149
}
2150

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

    
2158
	if ($early) {
2159
		$cmdn = "earlyshellcmd";
2160
	} else {
2161
		$cmdn = "shellcmd";
2162
	}
2163

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

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

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

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

    
2176
	}
2177
}
2178

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

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

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

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

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

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

    
2208
	fclose($fd);
2209
	unset($dmesg);
2210
	
2211
	// vm-bhyve expects dmesg.boot at the standard location
2212
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2213

    
2214
	return 0;
2215
}
2216

    
2217
function system_set_harddisk_standby() {
2218
	global $g, $config;
2219

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

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

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

    
2237
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2238
			// just in case of some weird pfSense platform installs.
2239
			if (count($harddisks) > 0) {
2240
				// Iterate disks and run the camcontrol command for each
2241
				foreach ($harddisks as $harddisk) {
2242
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2243
				}
2244
				if (platform_booting()) {
2245
					echo gettext("done.") . "\n";
2246
				}
2247
			} else if (platform_booting()) {
2248
				echo gettext("failed!") . "\n";
2249
			}
2250
		} else if (platform_booting()) {
2251
			echo gettext("failed!") . "\n";
2252
		}
2253
	}
2254
}
2255

    
2256
function system_setup_sysctl() {
2257
	global $config;
2258
	if (isset($config['system']['developerspew'])) {
2259
		$mt = microtime();
2260
		echo "system_setup_sysctl() being called $mt\n";
2261
	}
2262

    
2263
	activate_sysctls();
2264

    
2265
	if (isset($config['system']['sharednet'])) {
2266
		system_disable_arp_wrong_if();
2267
	}
2268
}
2269

    
2270
function system_disable_arp_wrong_if() {
2271
	global $config;
2272
	if (isset($config['system']['developerspew'])) {
2273
		$mt = microtime();
2274
		echo "system_disable_arp_wrong_if() being called $mt\n";
2275
	}
2276
	set_sysctl(array(
2277
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2278
		"net.link.ether.inet.log_arp_movements" => "0"
2279
	));
2280
}
2281

    
2282
function system_enable_arp_wrong_if() {
2283
	global $config;
2284
	if (isset($config['system']['developerspew'])) {
2285
		$mt = microtime();
2286
		echo "system_enable_arp_wrong_if() being called $mt\n";
2287
	}
2288
	set_sysctl(array(
2289
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2290
		"net.link.ether.inet.log_arp_movements" => "1"
2291
	));
2292
}
2293

    
2294
function enable_watchdog() {
2295
	global $config;
2296
	return;
2297
	$install_watchdog = false;
2298
	$supported_watchdogs = array("Geode");
2299
	$file = file_get_contents("/var/log/dmesg.boot");
2300
	foreach ($supported_watchdogs as $sd) {
2301
		if (stristr($file, "Geode")) {
2302
			$install_watchdog = true;
2303
		}
2304
	}
2305
	if ($install_watchdog == true) {
2306
		if (is_process_running("watchdogd")) {
2307
			mwexec("/usr/bin/killall watchdogd", true);
2308
		}
2309
		exec("/usr/sbin/watchdogd");
2310
	}
2311
}
2312

    
2313
function system_check_reset_button() {
2314
	global $g;
2315

    
2316
	$specplatform = system_identify_specific_platform();
2317

    
2318
	switch ($specplatform['name']) {
2319
		case 'alix':
2320
		case 'wrap':
2321
		case 'FW7541':
2322
		case 'APU':
2323
		case 'RCC-VE':
2324
		case 'RCC':
2325
		case 'RCC-DFF':
2326
			break;
2327
		default:
2328
			return 0;
2329
	}
2330

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

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

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

    
2344

    
2345
EOD;
2346

    
2347
		reset_factory_defaults();
2348
		system_reboot_sync();
2349
		exit(0);
2350
	}
2351

    
2352
	return 0;
2353
}
2354

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

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

    
2362
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2363
	    $vm_guest == 'none') {
2364
		return $serial;
2365
	}
2366

    
2367
	return get_single_sysctl('kern.hostuuid');
2368
}
2369

    
2370
function system_get_uniqueid() {
2371
	global $g;
2372

    
2373
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2374

    
2375
	if (empty($g['uniqueid'])) {
2376
		if (!file_exists($uniqueid_file)) {
2377
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2378
			    "2>/dev/null");
2379
		}
2380
		if (file_exists($uniqueid_file)) {
2381
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2382
		}
2383
	}
2384

    
2385
	return ($g['uniqueid'] ?: '');
2386
}
2387

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

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

    
2399
	/* Try to guess from smbios strings */
2400
	unset($product);
2401
	unset($maker);
2402
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2403
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2404
	switch ($product[0]) {
2405
		case 'FW7541':
2406
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2407
			break;
2408
		case 'APU':
2409
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2410
			break;
2411
		case 'RCC-VE':
2412
			$result = array();
2413
			$result['name'] = 'RCC-VE';
2414

    
2415
			/* Detect specific models */
2416
			if (!function_exists('does_interface_exist')) {
2417
				require_once("interfaces.inc");
2418
			}
2419
			if (!does_interface_exist('igb4')) {
2420
				$result['model'] = 'SG-2440';
2421
			} elseif (strpos($hw_model, "C2558") !== false) {
2422
				$result['model'] = 'SG-4860';
2423
			} elseif (strpos($hw_model, "C2758") !== false) {
2424
				$result['model'] = 'SG-8860';
2425
			} else {
2426
				$result['model'] = 'RCC-VE';
2427
			}
2428
			$result['descr'] = 'Netgate ' . $result['model'];
2429
			return $result;
2430
			break;
2431
		case 'DFFv2':
2432
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2433
			break;
2434
		case 'RCC':
2435
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2436
			break;
2437
		case 'SYS-5018A-FTN4':
2438
		case 'A1SAi':
2439
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2440
			break;
2441
		case 'SYS-5018D-FN4T':
2442
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2443
			break;
2444
		case 'apu2':
2445
		case 'APU2':
2446
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2447
			break;
2448
		case 'Virtual Machine':
2449
			if ($maker[0] == "Microsoft Corporation") {
2450
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2451
			}
2452
			break;
2453
	}
2454

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

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

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

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

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

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

    
2480
	unset($hw_model);
2481

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

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

    
2492
function system_get_dmesg_boot() {
2493
	global $g;
2494

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

    
2498
?>
(52-52/65)