Project

General

Profile

Download (67.2 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 Electric Sheep Fencing, LLC
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
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
238
		/* setup static routes for dns servers */
239
		$dnsgw = "dns{$dnscounter}gw";
240
		if (isset($config['system'][$dnsgw])) {
241
			if (empty($config['system'][$dnsgw]) ||
242
			    $config['system'][$dnsgw] == "none") {
243
				continue;
244
			}
245
			$gwname = $config['system'][$dnsgw];
246
			$gatewayip = lookup_gateway_ip_by_name($gwname);
247
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
248
			/* dns server array starts at 0 */
249
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
250

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

    
259
			mwexec("/sbin/route {$cmd} -host {$inet6}{$dnsserver} {$gatewayip}");
260
			if (isset($config['system']['route-debug'])) {
261
				$mt = microtime();
262
				log_error("ROUTING debug: $mt - route {$cmd} -host {$inet6}{$dnsserver} {$gatewayip}");
263
			}
264
		}
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
function system_hosts_generate() {
332
	global $config, $g;
333
	if (isset($config['system']['developerspew'])) {
334
		$mt = microtime();
335
		echo "system_hosts_generate() being called $mt\n";
336
	}
337

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

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

    
352
	if ($config['interfaces']['lan']) {
353
		$cfgip = get_interface_ip("lan");
354
		if (is_ipaddr($cfgip)) {
355
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
356
		}
357
		$cfgipv6 = get_interface_ipv6("lan");
358
		if (is_ipaddrv6($cfgipv6)) {
359
			$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
360
		}
361
	} else {
362
		$sysiflist = get_configured_interface_list();
363
		$hosts_if_found = false;
364
		foreach ($sysiflist as $sysif) {
365
			if (!interface_has_gateway($sysif)) {
366
				$cfgip = get_interface_ip($sysif);
367
				if (is_ipaddr($cfgip)) {
368
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
369
					$hosts_if_found = true;
370
				}
371
				$cfgipv6 = get_interface_ipv6($sysif);
372
				if (is_ipaddrv6($cfgipv6)) {
373
					$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
374
					$hosts_if_found = true;
375
				}
376
				if ($hosts_if_found == true) {
377
					break;
378
				}
379
			}
380
		}
381
	}
382

    
383
	if (isset($dnsmasqcfg['enable'])) {
384
		if (!is_array($dnsmasqcfg['hosts'])) {
385
			$dnsmasqcfg['hosts'] = array();
386
		}
387

    
388
		foreach ($dnsmasqcfg['hosts'] as $host) {
389
			if ($host['host'] || $host['host'] == "0") {
390
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
391
			} else {
392
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
393
			}
394
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item'])) {
395
				continue;
396
			}
397
			foreach ($host['aliases']['item'] as $alias) {
398
				if ($alias['host'] || $alias['host'] == "0") {
399
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
400
				} else {
401
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
402
				}
403
			}
404
		}
405
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
406
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
407
				if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) {
408
					foreach ($dhcpifconf['staticmap'] as $host) {
409
						if ($host['ipaddr'] && $host['hostname'] && $host['domain']) {
410
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
411
						} else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain']) {
412
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
413
						} else if ($host['ipaddr'] && $host['hostname']) {
414
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
415
						}
416
					}
417
				}
418
			}
419
		}
420
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
421
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf) {
422
				if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) {
423
					$isdelegated = $config['interfaces'][$dhcpif]['ipaddrv6'] == 'track6';
424
					foreach ($dhcpifconf['staticmap'] as $host) {
425
						$ipaddrv6 = $host['ipaddrv6'];
426
						if ($ipaddrv6 && $host['hostname']) {
427
							if ($isdelegated) {
428
								$trackifname = $config['interfaces'][$dhcpif]['track6-interface'];
429
								$trackcfg = $config['interfaces'][$trackifname];
430
								$pdlen = 64 - $trackcfg['dhcp6-ia-pd-len'];
431
								$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $pdlen);
432
							}
433
							if ($host['domain']) {
434
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
435
							} else if ($dhcpifconf['domain']) {
436
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
437
							} else {
438
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
439
							}
440
						}
441
					}
442
				}
443
			}
444
		}
445

    
446
		if (isset($dnsmasqcfg['dhcpfirst'])) {
447
			$hosts .= $dhosts . $lhosts;
448
		} else {
449
			$hosts .= $lhosts . $dhosts;
450
		}
451
	}
452

    
453
	/*
454
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be
455
	 * killed before writing to hosts files.
456
	 */
457
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
458
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
459
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
460
	}
461

    
462
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
463
	if (!$fd) {
464
		log_error(gettext("Error: cannot open hosts file in system_hosts_generate()."));
465
		return 1;
466
	}
467
	fwrite($fd, $hosts);
468
	fclose($fd);
469

    
470
	if (isset($config['unbound']['enable'])) {
471
		require_once("unbound.inc");
472
		unbound_hosts_generate();
473
	}
474

    
475
	/* restart dhcpleases */
476
	if (!platform_booting()) {
477
		system_dhcpleases_configure();
478
	}
479

    
480
	return 0;
481
}
482

    
483
function system_dhcpleases_configure() {
484
	global $config, $g;
485

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

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

    
497
		if (isset($config['unbound']['enable'])) {
498
			$dns_pid = "unbound.pid";
499
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
500
		} else {
501
			$dns_pid = "dnsmasq.pid";
502
			$unbound_conf = "";
503
		}
504

    
505
		if (isvalidpid($pidfile)) {
506
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
507
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
508
			if (intval($retval) == 0) {
509
				sigkillbypid($pidfile, "HUP");
510
				return;
511
			} else {
512
				sigkillbypid($pidfile, "TERM");
513
			}
514
		}
515

    
516
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
517
		if (is_process_running("dhcpleases")) {
518
			sigkillbyname('dhcpleases', "TERM");
519
		}
520
		@unlink($pidfile);
521
		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");
522
	} elseif (isvalidpid($pidfile)) {
523
		sigkillbypid($pidfile, "TERM");
524
		@unlink($pidfile);
525
	}
526
}
527

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

    
535
	$syscfg = $config['system'];
536

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

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

    
544
	return $status;
545
}
546

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

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

    
555
	$gatewayip = "";
556
	$interfacegw = "";
557
	$gatewayipv6 = "";
558
	$interfacegwv6 = "";
559
	$foundgw = false;
560
	$foundgwv6 = false;
561
	/* tack on all the hard defined gateways as well */
562
	if (is_array($config['gateways']['gateway_item'])) {
563
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
564
		foreach	($config['gateways']['gateway_item'] as $gateway) {
565
			if (isset($gateway['defaultgw'])) {
566
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
567
					if (strpos($gateway['gateway'], ":")) {
568
						continue;
569
					}
570
					if ($gateway['gateway'] == "dynamic") {
571
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
572
					}
573
					$gatewayip = $gateway['gateway'];
574
					$interfacegw = $gateway['interface'];
575
					if (!empty($gateway['interface'])) {
576
						$defaultif = get_real_interface($gateway['interface']);
577
						if ($defaultif) {
578
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
579
						}
580
					}
581
					$foundgw = true;
582
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
583
					if ($gateway['gateway'] == "dynamic") {
584
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
585
					}
586
					$gatewayipv6 = $gateway['gateway'];
587
					$interfacegwv6 = $gateway['interface'];
588
					if (!empty($gateway['interface'])) {
589
						$defaultifv6 = get_real_interface($gateway['interface']);
590
						if ($defaultifv6) {
591
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
592
						}
593
					}
594
					$foundgwv6 = true;
595
				}
596
			}
597
			if ($foundgw === true && $foundgwv6 === true) {
598
				break;
599
			}
600
		}
601
	}
602
	if ($foundgw == false) {
603
		$defaultif = get_real_interface("wan");
604
		$interfacegw = "wan";
605
		$gatewayip = get_interface_gateway("wan");
606
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
607
	}
608
	if ($foundgwv6 == false) {
609
		$defaultifv6 = get_real_interface("wan");
610
		$interfacegwv6 = "wan";
611
		$gatewayipv6 = get_interface_gateway_v6("wan");
612
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
613
	}
614
	$dont_add_route = false;
615
	/* if OLSRD is enabled, allow WAN to house DHCP. */
616
	if (is_array($config['installedpackages']['olsrd'])) {
617
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
618
			if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
619
				$dont_add_route = true;
620
				log_error(gettext("Not adding default route because OLSR dynamic gateway is enabled."));
621
				break;
622
			}
623
		}
624
	}
625

    
626
	$gateways_arr = return_gateways_array(false, true);
627
	foreach ($gateways_arr as $gateway) {
628
		// setup static interface routes for nonlocal gateways
629
		if (isset($gateway["nonlocalgateway"])) {
630
			$srgatewayip = $gateway['gateway'];
631
			$srinterfacegw = $gateway['interface'];
632
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
633
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
634
				$cmd = "/sbin/route change {$inet} " . escapeshellarg($srgatewayip) . " ";
635
				mwexec($cmd . "-iface " . escapeshellarg($srinterfacegw));
636
				if (isset($config['system']['route-debug'])) {
637
					$mt = microtime();
638
					log_error("ROUTING debug: $mt - $cmd -iface $srinterfacegw ");
639
				}
640
			}
641
		}
642
	}
643

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

    
652
		if (!empty($interface) && $interface != $interfacegwv6) {
653
			;
654
		} else if (is_ipaddrv6($gatewayipv6)) {
655
			$ifscope = "";
656
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
657
				$ifscope = "%{$defaultifv6}";
658
			}
659
			log_error(sprintf(gettext("ROUTING: setting IPv6 default route to %s"), $gatewayipv6 . $ifscope));
660
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
661
		}
662
	}
663

    
664
	system_staticroutes_configure($interface, false);
665

    
666
	return 0;
667
}
668

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

    
672
	$filterdns_list = array();
673

    
674
	$static_routes = get_staticroutes(false, true);
675
	if (count($static_routes)) {
676
		$gateways_arr = return_gateways_array(false, true);
677

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

    
688
			$gatewayip = $gateway['gateway'];
689
			$interfacegw = $gateway['interface'];
690

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

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

    
700
			$dnscache = array();
701
			if ($update_dns === true) {
702
				if (is_subnet($rtent['network'])) {
703
					continue;
704
				}
705
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
706
				if (empty($dnscache)) {
707
					continue;
708
				}
709
			}
710

    
711
			if (is_subnet($rtent['network'])) {
712
				$ips = array($rtent['network']);
713
			} else {
714
				if (!isset($rtent['disabled'])) {
715
					$filterdns_list[] = $rtent['network'];
716
				}
717
				$ips = add_hostname_to_watch($rtent['network']);
718
			}
719

    
720
			foreach ($dnscache as $ip) {
721
				if (in_array($ip, $ips)) {
722
					continue;
723
				}
724
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
725
				if (isset($config['system']['route-debug'])) {
726
					$mt = microtime();
727
					log_error("ROUTING debug: $mt - route delete $ip ");
728
				}
729
			}
730

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

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

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

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

    
753
				if (is_subnet($ip)) {
754
					if (is_ipaddr($gatewayip)) {
755
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
756
							// add interface scope for link local v6 routes
757
							$gatewayip .= "%$interfacegw";
758
						}
759
						mwexec($cmd . escapeshellarg($gatewayip));
760
						if (isset($config['system']['route-debug'])) {
761
							$mt = microtime();
762
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
763
						}
764
					} else if (!empty($interfacegw)) {
765
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
766
						if (isset($config['system']['route-debug'])) {
767
							$mt = microtime();
768
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
769
						}
770
					}
771
				}
772
			}
773
		}
774
		unset($gateways_arr);
775
	}
776
	unset($static_routes);
777

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

    
789
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
790
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
791
			} else {
792
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
793
			}
794
		} else {
795
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
796
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
797
		}
798
	}
799
	unset($filterdns_list);
800

    
801
	return 0;
802
}
803

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

    
811
	set_sysctl(array(
812
		"net.inet.ip.forwarding" => "1",
813
		"net.inet6.ip6.forwarding" => "1"
814
	));
815

    
816
	return;
817
}
818

    
819
function system_syslogd_fixup_server($server) {
820
	/* If it's an IPv6 IP alone, encase it in brackets */
821
	if (is_ipaddrv6($server)) {
822
		return "[$server]";
823
	} else {
824
		return $server;
825
	}
826
}
827

    
828
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
829
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
830
	$facility .= " ".
831
	$remote_servers = "";
832
	$pad_to  = max(strlen($facility), 56);
833
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
834
	if (isset($syslogcfg['enable'])) {
835
		if ($syslogcfg['remoteserver']) {
836
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
837
		}
838
		if ($syslogcfg['remoteserver2']) {
839
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
840
		}
841
		if ($syslogcfg['remoteserver3']) {
842
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
843
		}
844
	}
845
	return $remote_servers;
846
}
847

    
848
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
849
	global $config, $g;
850
	if ($restart_syslogd) {
851
		exec("/usr/bin/killall syslogd");
852
	}
853
	if (isset($config['system']['disablesyslogclog'])) {
854
		unlink($logfile);
855
		touch($logfile);
856
	} else {
857
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
858
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
859
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
860
	}
861
	if ($restart_syslogd) {
862
		system_syslogd_start();
863
	}
864
}
865

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

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

    
875
	if ($restart) {
876
		system_syslogd_start();
877
		killbyname("dhcpd");
878
		services_dhcpd_configure();
879
	}
880
	return;
881
}
882

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

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

    
892
	$syslogcfg = $config['syslog'];
893

    
894
	if (platform_booting()) {
895
		echo gettext("Starting syslog...");
896
	}
897

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

    
909
	$syslogd_extra = "";
910
	if (isset($syslogcfg)) {
911
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'pptps', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'olsrd', 'zebra', 'ospfd', 'bgpd', 'miniupnpd', 'filterlog');
912
		$syslogconf = "";
913
		if ($config['installedpackages']['package']) {
914
			foreach ($config['installedpackages']['package'] as $package) {
915
				if ($package['logging']) {
916
					array_push($separatelogfacilities, $package['logging']['facilityname']);
917
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
918
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
919
					}
920
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
921
				}
922
			}
923
		}
924
		$facilitylist = implode(',', array_unique($separatelogfacilities));
925
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
926
		if (!isset($syslogcfg['disablelocallogging'])) {
927
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
928
		}
929

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

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

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

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

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

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

    
963
		$syslogconf .= "!openvpn\n";
964
		if (!isset($syslogcfg['disablelocallogging'])) {
965
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
966
		}
967
		if (isset($syslogcfg['vpn'])) {
968
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
969
		}
970

    
971
		$syslogconf .= "!dpinger\n";
972
		if (!isset($syslogcfg['disablelocallogging'])) {
973
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
974
		}
975
		if (isset($syslogcfg['dpinger'])) {
976
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
977
		}
978

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

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

    
992
		$syslogconf .= "!relayd\n";
993
		if (!isset($syslogcfg['disablelocallogging'])) {
994
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
995
		}
996
		if (isset($syslogcfg['relayd'])) {
997
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
998
		}
999

    
1000
		$syslogconf .= "!hostapd\n";
1001
		if (!isset($syslogcfg['disablelocallogging'])) {
1002
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
1003
		}
1004
		if (isset($syslogcfg['hostapd'])) {
1005
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1006
		}
1007

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

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

    
1017
		$syslogconf .= "!-{$facilitylist}\n";
1018
		if (!isset($syslogcfg['disablelocallogging'])) {
1019
			$syslogconf .= <<<EOD
1020
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1021
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1022
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1023
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1024
*.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
1025
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1026
*.emerg								*
1027

    
1028
EOD;
1029
		}
1030
		if (isset($syslogcfg['vpn'])) {
1031
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1032
		}
1033
		if (isset($syslogcfg['portalauth'])) {
1034
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1035
		}
1036
		if (isset($syslogcfg['dhcp'])) {
1037
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1038
		}
1039
		if (isset($syslogcfg['system'])) {
1040
			$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");
1041
		}
1042
		if (isset($syslogcfg['logall'])) {
1043
			// Make everything mean everything, including facilities excluded above.
1044
			$syslogconf .= "!*\n";
1045
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1046
		}
1047

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

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

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

    
1067
		$sourceip = "";
1068
		if (!empty($syslogcfg['sourceip'])) {
1069
			if ($syslogcfg['ipproto'] == "ipv6") {
1070
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1071
				if (!is_ipaddr($ifaddr)) {
1072
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1073
				}
1074
			} else {
1075
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1076
				if (!is_ipaddr($ifaddr)) {
1077
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1078
				}
1079
			}
1080
			if (is_ipaddr($ifaddr)) {
1081
				$sourceip = "-b {$ifaddr}";
1082
			}
1083
		}
1084

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

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

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

    
1099

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

    
1102
	if (platform_booting()) {
1103
		echo gettext("done.") . "\n";
1104
	}
1105

    
1106
	return $retval;
1107
}
1108

    
1109
function system_webgui_create_certificate() {
1110
	global $config, $g;
1111

    
1112
	if (!is_array($config['ca'])) {
1113
		$config['ca'] = array();
1114
	}
1115
	$a_ca =& $config['ca'];
1116
	if (!is_array($config['cert'])) {
1117
		$config['cert'] = array();
1118
	}
1119
	$a_cert =& $config['cert'];
1120
	log_error(gettext("Creating SSL Certificate for this host"));
1121

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

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

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

    
1149
function system_webgui_start() {
1150
	global $config, $g;
1151

    
1152
	if (platform_booting()) {
1153
		echo gettext("Starting webConfigurator...");
1154
	}
1155

    
1156
	chdir($g['www_path']);
1157

    
1158
	/* defaults */
1159
	$portarg = "80";
1160
	$crt = "";
1161
	$key = "";
1162
	$ca = "";
1163

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

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

    
1178
		if (!$config['system']['webgui']['port']) {
1179
			$portarg = "443";
1180
		}
1181
		$ca = ca_chain($cert);
1182
	}
1183

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

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

    
1192
	sleep(1);
1193

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

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

    
1199
	if (platform_booting()) {
1200
		if ($res == 0) {
1201
			echo gettext("done.") . "\n";
1202
		} else {
1203
			echo gettext("failed!") . "\n";
1204
		}
1205
	}
1206

    
1207
	return $res;
1208
}
1209

    
1210
function system_generate_nginx_config($filename,
1211
	$cert,
1212
	$key,
1213
	$ca,
1214
	$pid_file,
1215
	$port = 80,
1216
	$document_root = "/usr/local/www/",
1217
	$cert_location = "cert.crt",
1218
	$key_location = "cert.key",
1219
	$captive_portal = false) {
1220

    
1221
	global $config, $g;
1222

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

    
1228
	if ($captive_portal !== false) {
1229
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1230
		$cp_hostcheck = "";
1231
		foreach ($cp_interfaces as $cpint) {
1232
			$cpint_ip = get_interface_ip($cpint);
1233
			if (is_ipaddr($cpint_ip)) {
1234
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1235
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1236
				$cp_hostcheck .= "\t\t}\n";
1237
			}
1238
		}
1239
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1240
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1241
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1242
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1243
			$cp_hostcheck .= "\t\t}\n";
1244
		}
1245
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1246
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1247
		$cp_rewrite .= "\t\t}\n";
1248

    
1249
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1250
		if (empty($maxprocperip)) {
1251
			$maxprocperip = 10;
1252
		}
1253
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1254
	}
1255

    
1256
	if (empty($port)) {
1257
		$nginx_port = "80";
1258
	} else {
1259
		$nginx_port = $port;
1260
	}
1261

    
1262
	$memory = get_memory();
1263
	$realmem = $memory[1];
1264

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

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

    
1283
	$nginx_config = <<<EOD
1284
#
1285
# nginx configuration file
1286

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

    
1289
user  root wheel;
1290
worker_processes  {$max_procs};
1291

    
1292
EOD;
1293

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

    
1298
	$nginx_config .= <<<EOD
1299

    
1300
events {
1301
    worker_connections  1024;
1302
}
1303

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

    
1310
	sendfile        on;
1311

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

    
1314
EOD;
1315

    
1316
	if ($captive_portal !== false) {
1317
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1318
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1319
	} else {
1320
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1321
	}
1322

    
1323
	if ($cert <> "" and $key <> "") {
1324
		$nginx_config .= "\n";
1325
		$nginx_config .= "\tserver {\n";
1326
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1327
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1328
		$nginx_config .= "\n";
1329
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1330
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1331
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1332
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1333
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1334
		if ($captive_portal !== false) {
1335
			// leave TLSv1.0 for CP for now for compatibility
1336
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1337
		} else {
1338
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1339
		}
1340
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1341
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1342
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1343
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1344
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1345
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1346
	} else {
1347
		$nginx_config .= "\n";
1348
		$nginx_config .= "\tserver {\n";
1349
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1350
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1351
	}
1352

    
1353
	$nginx_config .= <<<EOD
1354

    
1355
		client_max_body_size 200m;
1356

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

    
1360

    
1361
EOD;
1362

    
1363
	if ($captive_portal !== false) {
1364
		$nginx_config .= <<<EOD
1365
$captive_portal_maxprocperip
1366
$cp_hostcheck
1367
$cp_rewrite
1368
		log_not_found off;
1369

    
1370
EOD;
1371

    
1372
	}
1373

    
1374
	$nginx_config .= <<<EOD
1375
		root "{$document_root}";
1376
		location / {
1377
			index  index.php index.html index.htm;
1378
		}
1379

    
1380
		location ~ \.php$ {
1381
			try_files \$uri =404; #  This line closes a potential security hole
1382
			# ensuring users can't execute uploaded files
1383
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1384
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1385
			fastcgi_index  index.php;
1386
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1387
			# Fix httpoxy - https://httpoxy.org/#fix-now
1388
			fastcgi_param  HTTP_PROXY  "";
1389
			fastcgi_read_timeout 180;
1390
			include        /usr/local/etc/nginx/fastcgi_params;
1391
		}
1392
	}
1393

    
1394
EOD;
1395

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

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

    
1402
	if ($cert <> "" and $key <> "") {
1403
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1404
		if (!$fd) {
1405
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1406
			return 1;
1407
		}
1408
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1409
		if ($ca <> "") {
1410
			$cert_chain = $cert . "\n" . $ca;
1411
		} else {
1412
			$cert_chain = $cert;
1413
		}
1414
		fwrite($fd, $cert_chain);
1415
		fclose($fd);
1416
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1417
		if (!$fd) {
1418
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1419
			return 1;
1420
		}
1421
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1422
		fwrite($fd, $key);
1423
		fclose($fd);
1424
	}
1425

    
1426
	// Add HTTP to HTTPS redirect
1427
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1428
		if ($nginx_port != "443") {
1429
			$redirectport = ":{$nginx_port}";
1430
		}
1431
		$nginx_config .= <<<EOD
1432
	server {
1433
		listen 80;
1434
		listen [::]:80;
1435
		return 301 https://\$http_host$redirectport\$request_uri;
1436
	}
1437

    
1438
EOD;
1439
	}
1440

    
1441
	$nginx_config .= "}\n";
1442

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

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

    
1454
	return 0;
1455

    
1456
}
1457

    
1458
function system_get_timezone_list() {
1459
	global $g;
1460

    
1461
	$file_list = array_merge(
1462
		glob("/usr/share/zoneinfo/[A-Z]*"),
1463
		glob("/usr/share/zoneinfo/*/*"),
1464
		glob("/usr/share/zoneinfo/*/*/*")
1465
	);
1466

    
1467
	if (empty($file_list)) {
1468
		$file_list[] = $g['default_timezone'];
1469
	} else {
1470
		/* Remove directories from list */
1471
		$file_list = array_filter($file_list, function($v) {
1472
			return !is_dir($v);
1473
		});
1474
	}
1475

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

    
1479
	sort($file_list);
1480

    
1481
	return $file_list;
1482
}
1483

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

    
1491
	$syscfg = $config['system'];
1492

    
1493
	if (platform_booting()) {
1494
		echo gettext("Setting timezone...");
1495
	}
1496

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

    
1505
	if (platform_booting()) {
1506
		echo gettext("done.") . "\n";
1507
	}
1508
}
1509

    
1510
function system_ntp_setup_gps($serialport) {
1511
	global $config, $g;
1512
	$gps_device = '/dev/gps0';
1513
	$serialport = '/dev/'.$serialport;
1514

    
1515
	if (!file_exists($serialport)) {
1516
		return false;
1517
	}
1518

    
1519
	conf_mount_rw();
1520
	// Create symlink that ntpd requires
1521
	unlink_if_exists($gps_device);
1522
	@symlink($serialport, $gps_device);
1523

    
1524
	$gpsbaud = '4800';
1525
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1526
		switch ($config['ntpd']['gps']['speed']) {
1527
			case '16':
1528
				$gpsbaud = '9600';
1529
				break;
1530
			case '32':
1531
				$gpsbaud = '19200';
1532
				break;
1533
			case '48':
1534
				$gpsbaud = '38400';
1535
				break;
1536
			case '64':
1537
				$gpsbaud = '57600';
1538
				break;
1539
			case '80':
1540
				$gpsbaud = '115200';
1541
				break;
1542
		}
1543
	}
1544

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

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

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

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

    
1564
	conf_mount_ro();
1565

    
1566
	return true;
1567
}
1568

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

    
1572
	$pps_device = '/dev/pps0';
1573
	$serialport = '/dev/'.$serialport;
1574

    
1575
	if (!file_exists($serialport)) {
1576
		return false;
1577
	}
1578

    
1579
	conf_mount_rw();
1580
	// Create symlink that ntpd requires
1581
	unlink_if_exists($pps_device);
1582
	@symlink($serialport, $pps_device);
1583

    
1584
	conf_mount_ro();
1585

    
1586
	return true;
1587
}
1588

    
1589

    
1590
function system_ntp_configure() {
1591
	global $config, $g;
1592

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

    
1597
	safe_mkdir($statsdir);
1598

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

    
1603
	$ntpcfg = "# \n";
1604
	$ntpcfg .= "# pfSense ntp configuration file \n";
1605
	$ntpcfg .= "# \n\n";
1606
	$ntpcfg .= "tinker panic 0 \n";
1607

    
1608
	/* Add Orphan mode */
1609
	$ntpcfg .= "# Orphan mode stratum\n";
1610
	$ntpcfg .= 'tos orphan ';
1611
	if (!empty($config['ntpd']['orphan'])) {
1612
		$ntpcfg .= $config['ntpd']['orphan'];
1613
	} else {
1614
		$ntpcfg .= '12';
1615
	}
1616
	$ntpcfg .= "\n";
1617

    
1618
	/* Add PPS configuration */
1619
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1620
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1621
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1622
		$ntpcfg .= "\n";
1623
		$ntpcfg .= "# PPS Setup\n";
1624
		$ntpcfg .= 'server 127.127.22.0';
1625
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1626
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1627
			$ntpcfg .= ' prefer';
1628
		}
1629
		if (!empty($config['ntpd']['pps']['noselect'])) {
1630
			$ntpcfg .= ' noselect ';
1631
		}
1632
		$ntpcfg .= "\n";
1633
		$ntpcfg .= 'fudge 127.127.22.0';
1634
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1635
			$ntpcfg .= ' time1 ';
1636
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1637
		}
1638
		if (!empty($config['ntpd']['pps']['flag2'])) {
1639
			$ntpcfg .= ' flag2 1';
1640
		}
1641
		if (!empty($config['ntpd']['pps']['flag3'])) {
1642
			$ntpcfg .= ' flag3 1';
1643
		} else {
1644
			$ntpcfg .= ' flag3 0';
1645
		}
1646
		if (!empty($config['ntpd']['pps']['flag4'])) {
1647
			$ntpcfg .= ' flag4 1';
1648
		}
1649
		if (!empty($config['ntpd']['pps']['refid'])) {
1650
			$ntpcfg .= ' refid ';
1651
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1652
		}
1653
		$ntpcfg .= "\n";
1654
	}
1655
	/* End PPS configuration */
1656

    
1657
	/* Add GPS configuration */
1658
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1659
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1660
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1661
		$ntpcfg .= "\n";
1662
		$ntpcfg .= "# GPS Setup\n";
1663
		$ntpcfg .= 'server 127.127.20.0 mode ';
1664
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1665
			if (!empty($config['ntpd']['gps']['nmea'])) {
1666
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1667
			}
1668
			if (!empty($config['ntpd']['gps']['speed'])) {
1669
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1670
			}
1671
			if (!empty($config['ntpd']['gps']['subsec'])) {
1672
				$ntpmode += 128;
1673
			}
1674
			$ntpcfg .= (string) $ntpmode;
1675
		} else {
1676
			$ntpcfg .= '0';
1677
		}
1678
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1679
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1680
			$ntpcfg .= ' prefer';
1681
		}
1682
		if (!empty($config['ntpd']['gps']['noselect'])) {
1683
			$ntpcfg .= ' noselect ';
1684
		}
1685
		$ntpcfg .= "\n";
1686
		$ntpcfg .= 'fudge 127.127.20.0';
1687
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1688
			$ntpcfg .= ' time1 ';
1689
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1690
		}
1691
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1692
			$ntpcfg .= ' time2 ';
1693
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1694
		}
1695
		if (!empty($config['ntpd']['gps']['flag1'])) {
1696
			$ntpcfg .= ' flag1 1';
1697
		} else {
1698
			$ntpcfg .= ' flag1 0';
1699
		}
1700
		if (!empty($config['ntpd']['gps']['flag2'])) {
1701
			$ntpcfg .= ' flag2 1';
1702
		}
1703
		if (!empty($config['ntpd']['gps']['flag3'])) {
1704
			$ntpcfg .= ' flag3 1';
1705
		} else {
1706
			$ntpcfg .= ' flag3 0';
1707
		}
1708
		if (!empty($config['ntpd']['gps']['flag4'])) {
1709
			$ntpcfg .= ' flag4 1';
1710
		}
1711
		if (!empty($config['ntpd']['gps']['refid'])) {
1712
			$ntpcfg .= ' refid ';
1713
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1714
		}
1715
		if (!empty($config['ntpd']['gps']['stratum'])) {
1716
			$ntpcfg .= ' stratum ';
1717
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1718
		}
1719
		$ntpcfg .= "\n";
1720
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1721
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1722
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1723
		/* This handles a 2.1 and earlier config */
1724
		$ntpcfg .= "# GPS Setup\n";
1725
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1726
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1727
		// Fall back to local clock if GPS is out of sync?
1728
		$ntpcfg .= "server 127.127.1.0\n";
1729
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1730
	}
1731
	/* End GPS configuration */
1732

    
1733
	$ntpcfg .= "\n\n# Upstream Servers\n";
1734
	/* foreach through ntp servers and write out to ntpd.conf */
1735
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1736
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1737
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1738
			$ntpcfg .= ' prefer';
1739
		}
1740
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1741
			$ntpcfg .= ' noselect';
1742
		}
1743
		$ntpcfg .= "\n";
1744
	}
1745
	unset($ts);
1746

    
1747
	$ntpcfg .= "\n\n";
1748
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1749
		$ntpcfg .= "enable stats\n";
1750
		$ntpcfg .= 'statistics';
1751
		if (!empty($config['ntpd']['clockstats'])) {
1752
			$ntpcfg .= ' clockstats';
1753
		}
1754
		if (!empty($config['ntpd']['loopstats'])) {
1755
			$ntpcfg .= ' loopstats';
1756
		}
1757
		if (!empty($config['ntpd']['peerstats'])) {
1758
			$ntpcfg .= ' peerstats';
1759
		}
1760
		$ntpcfg .= "\n";
1761
	}
1762
	$ntpcfg .= "statsdir {$statsdir}\n";
1763
	$ntpcfg .= 'logconfig =syncall +clockall';
1764
	if (!empty($config['ntpd']['logpeer'])) {
1765
		$ntpcfg .= ' +peerall';
1766
	}
1767
	if (!empty($config['ntpd']['logsys'])) {
1768
		$ntpcfg .= ' +sysall';
1769
	}
1770
	$ntpcfg .= "\n";
1771
	$ntpcfg .= "driftfile {$driftfile}\n";
1772

    
1773
	/* Default Access restrictions */
1774
	$ntpcfg .= 'restrict default';
1775
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1776
		$ntpcfg .= ' kod limited';
1777
	}
1778
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1779
		$ntpcfg .= ' nomodify';
1780
	}
1781
	if (!empty($config['ntpd']['noquery'])) {
1782
		$ntpcfg .= ' noquery';
1783
	}
1784
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1785
		$ntpcfg .= ' nopeer';
1786
	}
1787
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1788
		$ntpcfg .= ' notrap';
1789
	}
1790
	if (!empty($config['ntpd']['noserve'])) {
1791
		$ntpcfg .= ' noserve';
1792
	}
1793
	$ntpcfg .= "\nrestrict -6 default";
1794
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1795
		$ntpcfg .= ' kod limited';
1796
	}
1797
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1798
		$ntpcfg .= ' nomodify';
1799
	}
1800
	if (!empty($config['ntpd']['noquery'])) {
1801
		$ntpcfg .= ' noquery';
1802
	}
1803
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1804
		$ntpcfg .= ' nopeer';
1805
	}
1806
	if (!empty($config['ntpd']['noserve'])) {
1807
		$ntpcfg .= ' noserve';
1808
	}
1809
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1810
		$ntpcfg .= ' notrap';
1811
	}
1812
	/* Custom Access Restrictions */
1813
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1814
		$networkacl = $config['ntpd']['restrictions']['row'];
1815
		foreach ($networkacl as $acl) {
1816
			$ntpcfg .= "\nrestrict ";
1817
			if (is_ipaddrv6($acl['acl_network'])) {
1818
				$ntpcfg .= "-6 {$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1819
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1820
				$ntpcfg .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
1821
			} else {
1822
				continue;
1823
			}
1824
			if (!empty($acl['kod'])) {
1825
				$ntpcfg .= ' kod limited';
1826
			}
1827
			if (!empty($acl['nomodify'])) {
1828
				$ntpcfg .= ' nomodify';
1829
			}
1830
			if (!empty($acl['noquery'])) {
1831
				$ntpcfg .= ' noquery';
1832
			}
1833
			if (!empty($acl['nopeer'])) {
1834
				$ntpcfg .= ' nopeer';
1835
			}
1836
			if (!empty($acl['noserve'])) {
1837
				$ntpcfg .= ' noserve';
1838
			}
1839
			if (!empty($acl['notrap'])) {
1840
				$ntpcfg .= ' notrap';
1841
			}
1842
		}
1843
	}
1844
	$ntpcfg .= "\n";
1845
	/* End Custom Access Restrictions */
1846

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

    
1855

    
1856
	if (empty($config['ntpd']['interface'])) {
1857
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
1858
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1859
		} else {
1860
			$interfaces = array();
1861
		}
1862
	} else {
1863
		$interfaces = explode(",", $config['ntpd']['interface']);
1864
	}
1865

    
1866
	if (is_array($interfaces) && count($interfaces)) {
1867
		$finterfaces = array();
1868
		$ntpcfg .= "interface ignore all\n";
1869
		foreach ($interfaces as $interface) {
1870
			$interface = get_real_interface($interface);
1871
			if (!empty($interface)) {
1872
				$finterfaces[] = $interface;
1873
			}
1874
		}
1875
		foreach ($finterfaces as $interface) {
1876
			$ntpcfg .= "interface listen {$interface}\n";
1877
		}
1878
	}
1879

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

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

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

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

    
1900
	// Note that we are starting up
1901
	log_error("NTPD is starting up.");
1902
	return;
1903
}
1904

    
1905
function system_halt() {
1906
	global $g;
1907

    
1908
	system_reboot_cleanup();
1909

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

    
1913
function system_reboot() {
1914
	global $g;
1915

    
1916
	system_reboot_cleanup();
1917

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

    
1921
function system_reboot_sync() {
1922
	global $g;
1923

    
1924
	system_reboot_cleanup();
1925

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

    
1929
function system_reboot_cleanup() {
1930
	global $config, $cpzone;
1931

    
1932
	mwexec("/usr/local/bin/beep.sh stop");
1933
	require_once("captiveportal.inc");
1934
	if (is_array($config['captiveportal'])) {
1935
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1936
			captiveportal_radius_stop_all();
1937
			captiveportal_send_server_accounting(true);
1938
		}
1939
	}
1940
	require_once("voucher.inc");
1941
	voucher_save_db_to_config();
1942
	require_once("pkg-utils.inc");
1943
	stop_packages();
1944
}
1945

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

    
1953
	if ($early) {
1954
		$cmdn = "earlyshellcmd";
1955
	} else {
1956
		$cmdn = "shellcmd";
1957
	}
1958

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

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

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

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

    
1971
	}
1972
}
1973

    
1974
function system_dmesg_save() {
1975
	global $g;
1976
	if (isset($config['system']['developerspew'])) {
1977
		$mt = microtime();
1978
		echo "system_dmesg_save() being called $mt\n";
1979
	}
1980

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

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

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

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

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

    
2003
	fclose($fd);
2004
	unset($dmesg);
2005
	
2006
	// vm-bhyve expects dmesg.boot at the standard location
2007
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2008

    
2009
	return 0;
2010
}
2011

    
2012
function system_set_harddisk_standby() {
2013
	global $g, $config;
2014

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

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

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

    
2032
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2033
			// just in case of some weird pfSense platform installs.
2034
			if (count($harddisks) > 0) {
2035
				// Iterate disks and run the camcontrol command for each
2036
				foreach ($harddisks as $harddisk) {
2037
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2038
				}
2039
				if (platform_booting()) {
2040
					echo gettext("done.") . "\n";
2041
				}
2042
			} else if (platform_booting()) {
2043
				echo gettext("failed!") . "\n";
2044
			}
2045
		} else if (platform_booting()) {
2046
			echo gettext("failed!") . "\n";
2047
		}
2048
	}
2049
}
2050

    
2051
function system_setup_sysctl() {
2052
	global $config;
2053
	if (isset($config['system']['developerspew'])) {
2054
		$mt = microtime();
2055
		echo "system_setup_sysctl() being called $mt\n";
2056
	}
2057

    
2058
	activate_sysctls();
2059

    
2060
	if (isset($config['system']['sharednet'])) {
2061
		system_disable_arp_wrong_if();
2062
	}
2063
}
2064

    
2065
function system_disable_arp_wrong_if() {
2066
	global $config;
2067
	if (isset($config['system']['developerspew'])) {
2068
		$mt = microtime();
2069
		echo "system_disable_arp_wrong_if() being called $mt\n";
2070
	}
2071
	set_sysctl(array(
2072
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2073
		"net.link.ether.inet.log_arp_movements" => "0"
2074
	));
2075
}
2076

    
2077
function system_enable_arp_wrong_if() {
2078
	global $config;
2079
	if (isset($config['system']['developerspew'])) {
2080
		$mt = microtime();
2081
		echo "system_enable_arp_wrong_if() being called $mt\n";
2082
	}
2083
	set_sysctl(array(
2084
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2085
		"net.link.ether.inet.log_arp_movements" => "1"
2086
	));
2087
}
2088

    
2089
function enable_watchdog() {
2090
	global $config;
2091
	return;
2092
	$install_watchdog = false;
2093
	$supported_watchdogs = array("Geode");
2094
	$file = file_get_contents("/var/log/dmesg.boot");
2095
	foreach ($supported_watchdogs as $sd) {
2096
		if (stristr($file, "Geode")) {
2097
			$install_watchdog = true;
2098
		}
2099
	}
2100
	if ($install_watchdog == true) {
2101
		if (is_process_running("watchdogd")) {
2102
			mwexec("/usr/bin/killall watchdogd", true);
2103
		}
2104
		exec("/usr/sbin/watchdogd");
2105
	}
2106
}
2107

    
2108
function system_check_reset_button() {
2109
	global $g;
2110

    
2111
	$specplatform = system_identify_specific_platform();
2112

    
2113
	switch ($specplatform['name']) {
2114
		case 'alix':
2115
		case 'wrap':
2116
		case 'FW7541':
2117
		case 'APU':
2118
		case 'RCC-VE':
2119
		case 'RCC':
2120
		case 'RCC-DFF':
2121
			break;
2122
		default:
2123
			return 0;
2124
	}
2125

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

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

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

    
2139

    
2140
EOD;
2141

    
2142
		reset_factory_defaults();
2143
		system_reboot_sync();
2144
		exit(0);
2145
	}
2146

    
2147
	return 0;
2148
}
2149

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

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

    
2157
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2158
	    $vm_guest == 'none') {
2159
		return $serial;
2160
	}
2161

    
2162
	return get_single_sysctl('kern.hostuuid');
2163
}
2164

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

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

    
2176
	/* Try to guess from smbios strings */
2177
	unset($product);
2178
	unset($maker);
2179
	$_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $product);
2180
	$_gb = exec('/bin/kenv smbios.system.maker 2>/dev/null', $maker);
2181
	switch ($product[0]) {
2182
		case 'FW7541':
2183
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2184
			break;
2185
		case 'APU':
2186
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2187
			break;
2188
		case 'RCC-VE':
2189
			$result = array();
2190
			$result['name'] = 'RCC-VE';
2191

    
2192
			/* Detect specific models */
2193
			if (!function_exists('does_interface_exist')) {
2194
				require_once("interfaces.inc");
2195
			}
2196
			if (!does_interface_exist('igb4')) {
2197
				$result['model'] = 'SG-2440';
2198
			} elseif (strpos($hw_model, "C2558") !== false) {
2199
				$result['model'] = 'SG-4860';
2200
			} elseif (strpos($hw_model, "C2758") !== false) {
2201
				$result['model'] = 'SG-8860';
2202
			} else {
2203
				$result['model'] = 'RCC-VE';
2204
			}
2205
			$result['descr'] = 'Netgate ' . $result['model'];
2206
			return $result;
2207
			break;
2208
		case 'DFFv2':
2209
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2210
			break;
2211
		case 'RCC':
2212
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2213
			break;
2214
		case 'SYS-5018A-FTN4':
2215
		case 'A1SAi':
2216
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2217
			break;
2218
		case 'SYS-5018D-FN4T':
2219
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2220
			break;
2221
		case 'Virtual Machine':
2222
			if ($maker[0] == "Microsoft Corporation") {
2223
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2224
			}
2225
			break;
2226
	}
2227

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

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

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

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

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

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

    
2253
	unset($hw_model);
2254

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

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

    
2265
function system_get_dmesg_boot() {
2266
	global $g;
2267

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

    
2271
?>
(52-52/65)