Project

General

Profile

Download (68.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 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
	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
								// We are always in an "end-user" subnet here, which all are /64 for IPv6.
429
								$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, 64);
430
							}
431
							if ($host['domain']) {
432
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
433
							} else if ($dhcpifconf['domain']) {
434
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
435
							} else {
436
								$dhosts .= "{$ipaddrv6}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
437
							}
438
						}
439
					}
440
				}
441
			}
442
		}
443

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

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

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

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

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

    
478
	return 0;
479
}
480

    
481
function system_dhcpleases_configure() {
482
	global $config, $g;
483

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

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

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

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

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

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

    
533
	$syscfg = $config['system'];
534

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

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

    
542
	return $status;
543
}
544

    
545
function system_routing_configure($interface = "") {
546
	global $config, $g;
547

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

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

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

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

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

    
662
	system_staticroutes_configure($interface, false);
663

    
664
	return 0;
665
}
666

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

    
670
	$filterdns_list = array();
671

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

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

    
686
			$gatewayip = $gateway['gateway'];
687
			$interfacegw = $gateway['interface'];
688

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

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

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

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

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

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

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

    
747
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
748

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

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

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

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

    
799
	return 0;
800
}
801

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

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

    
814
	return;
815
}
816

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

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

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

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

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

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

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

    
888
	mwexec("/etc/rc.d/hostid start");
889

    
890
	$syslogcfg = $config['syslog'];
891

    
892
	if (platform_booting()) {
893
		echo gettext("Starting syslog...");
894
	}
895

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

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

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

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

    
947
		$syslogconf .= "!poes\n";
948
		if (!isset($syslogcfg['disablelocallogging'])) {
949
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
950
		}
951
		if (isset($syslogcfg['vpn'])) {
952
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
953
		}
954

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

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

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

    
979
		$syslogconf .= "!dpinger\n";
980
		if (!isset($syslogcfg['disablelocallogging'])) {
981
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
982
		}
983
		if (isset($syslogcfg['dpinger'])) {
984
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
985
		}
986

    
987
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
988
		if (!isset($syslogcfg['disablelocallogging'])) {
989
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
990
		}
991
		if (isset($syslogcfg['resolver'])) {
992
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
993
		}
994

    
995
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
996
		if (!isset($syslogcfg['disablelocallogging'])) {
997
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
998
		}
999
		if (isset($syslogcfg['dhcp'])) {
1000
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1001
		}
1002

    
1003
		$syslogconf .= "!relayd\n";
1004
		if (!isset($syslogcfg['disablelocallogging'])) {
1005
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
1006
		}
1007
		if (isset($syslogcfg['relayd'])) {
1008
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1009
		}
1010

    
1011
		$syslogconf .= "!hostapd\n";
1012
		if (!isset($syslogcfg['disablelocallogging'])) {
1013
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
1014
		}
1015
		if (isset($syslogcfg['hostapd'])) {
1016
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1017
		}
1018

    
1019
		$syslogconf .= "!filterlog\n";
1020
		if (!isset($syslogcfg['disablelocallogging'])) {
1021
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
1022
		}
1023
		if (isset($syslogcfg['filter'])) {
1024
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1025
		}
1026

    
1027
		$syslogconf .= "!-{$facilitylist}\n";
1028
		if (!isset($syslogcfg['disablelocallogging'])) {
1029
			$syslogconf .= <<<EOD
1030
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1031
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1032
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1033
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1034
*.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
1035
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1036
*.emerg								*
1037

    
1038
EOD;
1039
		}
1040
		if (isset($syslogcfg['vpn'])) {
1041
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1042
		}
1043
		if (isset($syslogcfg['portalauth'])) {
1044
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1045
		}
1046
		if (isset($syslogcfg['dhcp'])) {
1047
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1048
		}
1049
		if (isset($syslogcfg['system'])) {
1050
			$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");
1051
		}
1052
		if (isset($syslogcfg['logall'])) {
1053
			// Make everything mean everything, including facilities excluded above.
1054
			$syslogconf .= "!*\n";
1055
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1056
		}
1057

    
1058
		if (isset($syslogcfg['zmqserver'])) {
1059
				$syslogconf .= <<<EOD
1060
*.*								^{$syslogcfg['zmqserver']}
1061

    
1062
EOD;
1063
		}
1064
		/* write syslog.conf */
1065
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
1066
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1067
			unset($syslogconf);
1068
			return 1;
1069
		}
1070
		unset($syslogconf);
1071

    
1072
		// Ensure that the log directory exists
1073
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run")) {
1074
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
1075
		}
1076

    
1077
		$sourceip = "";
1078
		if (!empty($syslogcfg['sourceip'])) {
1079
			if ($syslogcfg['ipproto'] == "ipv6") {
1080
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1081
				if (!is_ipaddr($ifaddr)) {
1082
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1083
				}
1084
			} else {
1085
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1086
				if (!is_ipaddr($ifaddr)) {
1087
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1088
				}
1089
			}
1090
			if (is_ipaddr($ifaddr)) {
1091
				$sourceip = "-b {$ifaddr}";
1092
			}
1093
		}
1094

    
1095
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
1096
	}
1097

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

    
1100
	if (isset($config['installedpackages']['package'])) {
1101
		foreach ($config['installedpackages']['package'] as $package) {
1102
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1103
			    is_dir(dirname($package['logging']['logsocket'])) &&
1104
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1105
				$log_sockets[] = $package['logging']['logsocket'];
1106
			}
1107
		}
1108
	}
1109
	$syslogd_sockets = "";
1110
	foreach ($log_sockets as $log_socket) {
1111
		$syslogd_sockets .= " -l {$log_socket}";
1112
	}
1113

    
1114
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1115
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1116
		usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1117
	}
1118

    
1119
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1120
		// if it still hasn't responded to the TERM, KILL it.
1121
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1122
		usleep(100000);
1123
	}
1124

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

    
1127
	if (platform_booting()) {
1128
		echo gettext("done.") . "\n";
1129
	}
1130

    
1131
	return $retval;
1132
}
1133

    
1134
function system_webgui_create_certificate() {
1135
	global $config, $g;
1136

    
1137
	if (!is_array($config['ca'])) {
1138
		$config['ca'] = array();
1139
	}
1140
	$a_ca =& $config['ca'];
1141
	if (!is_array($config['cert'])) {
1142
		$config['cert'] = array();
1143
	}
1144
	$a_cert =& $config['cert'];
1145
	log_error(gettext("Creating SSL Certificate for this host"));
1146

    
1147
	$cert = array();
1148
	$cert['refid'] = uniqid();
1149
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1150

    
1151
	$dn = array(
1152
		'countryName' => "US",
1153
		'stateOrProvinceName' => "State",
1154
		'localityName' => "Locality",
1155
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1156
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1157
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
1158
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1159
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1160
		while ($ssl_err = openssl_error_string()) {
1161
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1162
		}
1163
		error_reporting($old_err_level);
1164
		return null;
1165
	}
1166
	error_reporting($old_err_level);
1167

    
1168
	$a_cert[] = $cert;
1169
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1170
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1171
	return $cert;
1172
}
1173

    
1174
function system_webgui_start() {
1175
	global $config, $g;
1176

    
1177
	if (platform_booting()) {
1178
		echo gettext("Starting webConfigurator...");
1179
	}
1180

    
1181
	chdir($g['www_path']);
1182

    
1183
	/* defaults */
1184
	$portarg = "80";
1185
	$crt = "";
1186
	$key = "";
1187
	$ca = "";
1188

    
1189
	/* non-standard port? */
1190
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1191
		$portarg = "{$config['system']['webgui']['port']}";
1192
	}
1193

    
1194
	if ($config['system']['webgui']['protocol'] == "https") {
1195
		// Ensure that we have a webConfigurator CERT
1196
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1197
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1198
			$cert = system_webgui_create_certificate();
1199
		}
1200
		$crt = base64_decode($cert['crt']);
1201
		$key = base64_decode($cert['prv']);
1202

    
1203
		if (!$config['system']['webgui']['port']) {
1204
			$portarg = "443";
1205
		}
1206
		$ca = ca_chain($cert);
1207
	}
1208

    
1209
	/* generate nginx configuration */
1210
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1211
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1212
		"cert.crt", "cert.key");
1213

    
1214
	/* kill any running nginx */
1215
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1216

    
1217
	sleep(1);
1218

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

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

    
1224
	if (platform_booting()) {
1225
		if ($res == 0) {
1226
			echo gettext("done.") . "\n";
1227
		} else {
1228
			echo gettext("failed!") . "\n";
1229
		}
1230
	}
1231

    
1232
	return $res;
1233
}
1234

    
1235
function system_generate_nginx_config($filename,
1236
	$cert,
1237
	$key,
1238
	$ca,
1239
	$pid_file,
1240
	$port = 80,
1241
	$document_root = "/usr/local/www/",
1242
	$cert_location = "cert.crt",
1243
	$key_location = "cert.key",
1244
	$captive_portal = false) {
1245

    
1246
	global $config, $g;
1247

    
1248
	if (isset($config['system']['developerspew'])) {
1249
		$mt = microtime();
1250
		echo "system_generate_nginx_config() being called $mt\n";
1251
	}
1252

    
1253
	if ($captive_portal !== false) {
1254
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1255
		$cp_hostcheck = "";
1256
		foreach ($cp_interfaces as $cpint) {
1257
			$cpint_ip = get_interface_ip($cpint);
1258
			if (is_ipaddr($cpint_ip)) {
1259
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1260
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1261
				$cp_hostcheck .= "\t\t}\n";
1262
			}
1263
		}
1264
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1265
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1266
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1267
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1268
			$cp_hostcheck .= "\t\t}\n";
1269
		}
1270
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1271
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1272
		$cp_rewrite .= "\t\t}\n";
1273

    
1274
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1275
		if (empty($maxprocperip)) {
1276
			$maxprocperip = 10;
1277
		}
1278
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1279
	}
1280

    
1281
	if (empty($port)) {
1282
		$nginx_port = "80";
1283
	} else {
1284
		$nginx_port = $port;
1285
	}
1286

    
1287
	$memory = get_memory();
1288
	$realmem = $memory[1];
1289

    
1290
	// Determine web GUI process settings and take into account low memory systems
1291
	if ($realmem < 255) {
1292
		$max_procs = 1;
1293
	} else {
1294
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1295
	}
1296

    
1297
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1298
	if ($captive_portal !== false) {
1299
		if ($realmem > 135 and $realmem < 256) {
1300
			$max_procs += 1; // 2 worker processes
1301
		} else if ($realmem > 255 and $realmem < 513) {
1302
			$max_procs += 2; // 3 worker processes
1303
		} else if ($realmem > 512) {
1304
			$max_procs += 4; // 6 worker processes
1305
		}
1306
	}
1307

    
1308
	$nginx_config = <<<EOD
1309
#
1310
# nginx configuration file
1311

    
1312
pid {$g['varrun_path']}/{$pid_file};
1313

    
1314
user  root wheel;
1315
worker_processes  {$max_procs};
1316

    
1317
EOD;
1318

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

    
1323
	$nginx_config .= <<<EOD
1324

    
1325
events {
1326
    worker_connections  1024;
1327
}
1328

    
1329
http {
1330
	include       /usr/local/etc/nginx/mime.types;
1331
	default_type  application/octet-stream;
1332
	add_header X-Frame-Options SAMEORIGIN;
1333
	server_tokens off;
1334

    
1335
	sendfile        on;
1336

    
1337
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1338

    
1339
EOD;
1340

    
1341
	if ($captive_portal !== false) {
1342
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1343
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1344
	} else {
1345
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1346
	}
1347

    
1348
	if ($cert <> "" and $key <> "") {
1349
		$nginx_config .= "\n";
1350
		$nginx_config .= "\tserver {\n";
1351
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1352
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1353
		$nginx_config .= "\n";
1354
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1355
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1356
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1357
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1358
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1359
		if ($captive_portal !== false) {
1360
			// leave TLSv1.0 for CP for now for compatibility
1361
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1362
		} else {
1363
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1364
		}
1365
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1366
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1367
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1368
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1369
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1370
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1371
	} else {
1372
		$nginx_config .= "\n";
1373
		$nginx_config .= "\tserver {\n";
1374
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1375
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1376
	}
1377

    
1378
	$nginx_config .= <<<EOD
1379

    
1380
		client_max_body_size 200m;
1381

    
1382
		gzip on;
1383
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1384

    
1385

    
1386
EOD;
1387

    
1388
	if ($captive_portal !== false) {
1389
		$nginx_config .= <<<EOD
1390
$captive_portal_maxprocperip
1391
$cp_hostcheck
1392
$cp_rewrite
1393
		log_not_found off;
1394

    
1395
EOD;
1396

    
1397
	}
1398

    
1399
	$nginx_config .= <<<EOD
1400
		root "{$document_root}";
1401
		location / {
1402
			index  index.php index.html index.htm;
1403
		}
1404

    
1405
		location ~ \.php$ {
1406
			try_files \$uri =404; #  This line closes a potential security hole
1407
			# ensuring users can't execute uploaded files
1408
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1409
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1410
			fastcgi_index  index.php;
1411
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1412
			# Fix httpoxy - https://httpoxy.org/#fix-now
1413
			fastcgi_param  HTTP_PROXY  "";
1414
			fastcgi_read_timeout 180;
1415
			include        /usr/local/etc/nginx/fastcgi_params;
1416
		}
1417
	}
1418

    
1419
EOD;
1420

    
1421
	$cert = str_replace("\r", "", $cert);
1422
	$key = str_replace("\r", "", $key);
1423

    
1424
	$cert = str_replace("\n\n", "\n", $cert);
1425
	$key = str_replace("\n\n", "\n", $key);
1426

    
1427
	if ($cert <> "" and $key <> "") {
1428
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1429
		if (!$fd) {
1430
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1431
			return 1;
1432
		}
1433
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1434
		if ($ca <> "") {
1435
			$cert_chain = $cert . "\n" . $ca;
1436
		} else {
1437
			$cert_chain = $cert;
1438
		}
1439
		fwrite($fd, $cert_chain);
1440
		fclose($fd);
1441
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1442
		if (!$fd) {
1443
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1444
			return 1;
1445
		}
1446
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1447
		fwrite($fd, $key);
1448
		fclose($fd);
1449
	}
1450

    
1451
	// Add HTTP to HTTPS redirect
1452
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1453
		if ($nginx_port != "443") {
1454
			$redirectport = ":{$nginx_port}";
1455
		}
1456
		$nginx_config .= <<<EOD
1457
	server {
1458
		listen 80;
1459
		listen [::]:80;
1460
		return 301 https://\$http_host$redirectport\$request_uri;
1461
	}
1462

    
1463
EOD;
1464
	}
1465

    
1466
	$nginx_config .= "}\n";
1467

    
1468
	$fd = fopen("{$filename}", "w");
1469
	if (!$fd) {
1470
		printf(gettext("Error: cannot open %s in system_generate_nginx_config().%s"), $filename, "\n");
1471
		return 1;
1472
	}
1473
	fwrite($fd, $nginx_config);
1474
	fclose($fd);
1475

    
1476
	/* nginx will fail to start if this directory does not exist. */
1477
	safe_mkdir("/var/tmp/nginx/");
1478

    
1479
	return 0;
1480

    
1481
}
1482

    
1483
function system_get_timezone_list() {
1484
	global $g;
1485

    
1486
	$file_list = array_merge(
1487
		glob("/usr/share/zoneinfo/[A-Z]*"),
1488
		glob("/usr/share/zoneinfo/*/*"),
1489
		glob("/usr/share/zoneinfo/*/*/*")
1490
	);
1491

    
1492
	if (empty($file_list)) {
1493
		$file_list[] = $g['default_timezone'];
1494
	} else {
1495
		/* Remove directories from list */
1496
		$file_list = array_filter($file_list, function($v) {
1497
			return !is_dir($v);
1498
		});
1499
	}
1500

    
1501
	/* Remove directory prefix */
1502
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1503

    
1504
	sort($file_list);
1505

    
1506
	return $file_list;
1507
}
1508

    
1509
function system_timezone_configure() {
1510
	global $config, $g;
1511
	if (isset($config['system']['developerspew'])) {
1512
		$mt = microtime();
1513
		echo "system_timezone_configure() being called $mt\n";
1514
	}
1515

    
1516
	$syscfg = $config['system'];
1517

    
1518
	if (platform_booting()) {
1519
		echo gettext("Setting timezone...");
1520
	}
1521

    
1522
	/* extract appropriate timezone file */
1523
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1524
	conf_mount_rw();
1525
	/* DO NOT remove \n otherwise tzsetup will fail */
1526
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1527
	mwexec("/usr/sbin/tzsetup -r");
1528
	conf_mount_ro();
1529

    
1530
	if (platform_booting()) {
1531
		echo gettext("done.") . "\n";
1532
	}
1533
}
1534

    
1535
function system_ntp_setup_gps($serialport) {
1536
	global $config, $g;
1537
	$gps_device = '/dev/gps0';
1538
	$serialport = '/dev/'.$serialport;
1539

    
1540
	if (!file_exists($serialport)) {
1541
		return false;
1542
	}
1543

    
1544
	conf_mount_rw();
1545
	// Create symlink that ntpd requires
1546
	unlink_if_exists($gps_device);
1547
	@symlink($serialport, $gps_device);
1548

    
1549
	$gpsbaud = '4800';
1550
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1551
		switch ($config['ntpd']['gps']['speed']) {
1552
			case '16':
1553
				$gpsbaud = '9600';
1554
				break;
1555
			case '32':
1556
				$gpsbaud = '19200';
1557
				break;
1558
			case '48':
1559
				$gpsbaud = '38400';
1560
				break;
1561
			case '64':
1562
				$gpsbaud = '57600';
1563
				break;
1564
			case '80':
1565
				$gpsbaud = '115200';
1566
				break;
1567
		}
1568
	}
1569

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

    
1573
	/* Send the following to the GPS port to initialize the GPS */
1574
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1575
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1576
	} else {
1577
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1578
	}
1579

    
1580
	/* XXX: Why not file_put_contents to the device */
1581
	@file_put_contents('/tmp/gps.init', $gps_init);
1582
	mwexec("cat /tmp/gps.init > {$serialport}");
1583

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

    
1589
	conf_mount_ro();
1590

    
1591
	return true;
1592
}
1593

    
1594
function system_ntp_setup_pps($serialport) {
1595
	global $config, $g;
1596

    
1597
	$pps_device = '/dev/pps0';
1598
	$serialport = '/dev/'.$serialport;
1599

    
1600
	if (!file_exists($serialport)) {
1601
		return false;
1602
	}
1603

    
1604
	conf_mount_rw();
1605
	// Create symlink that ntpd requires
1606
	unlink_if_exists($pps_device);
1607
	@symlink($serialport, $pps_device);
1608

    
1609
	conf_mount_ro();
1610

    
1611
	return true;
1612
}
1613

    
1614

    
1615
function system_ntp_configure() {
1616
	global $config, $g;
1617

    
1618
	$driftfile = "/var/db/ntpd.drift";
1619
	$statsdir = "/var/log/ntp";
1620
	$gps_device = '/dev/gps0';
1621

    
1622
	safe_mkdir($statsdir);
1623

    
1624
	if (!is_array($config['ntpd'])) {
1625
		$config['ntpd'] = array();
1626
	}
1627

    
1628
	$ntpcfg = "# \n";
1629
	$ntpcfg .= "# pfSense ntp configuration file \n";
1630
	$ntpcfg .= "# \n\n";
1631
	$ntpcfg .= "tinker panic 0 \n";
1632

    
1633
	/* Add Orphan mode */
1634
	$ntpcfg .= "# Orphan mode stratum\n";
1635
	$ntpcfg .= 'tos orphan ';
1636
	if (!empty($config['ntpd']['orphan'])) {
1637
		$ntpcfg .= $config['ntpd']['orphan'];
1638
	} else {
1639
		$ntpcfg .= '12';
1640
	}
1641
	$ntpcfg .= "\n";
1642

    
1643
	/* Add PPS configuration */
1644
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1645
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1646
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1647
		$ntpcfg .= "\n";
1648
		$ntpcfg .= "# PPS Setup\n";
1649
		$ntpcfg .= 'server 127.127.22.0';
1650
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1651
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1652
			$ntpcfg .= ' prefer';
1653
		}
1654
		if (!empty($config['ntpd']['pps']['noselect'])) {
1655
			$ntpcfg .= ' noselect ';
1656
		}
1657
		$ntpcfg .= "\n";
1658
		$ntpcfg .= 'fudge 127.127.22.0';
1659
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1660
			$ntpcfg .= ' time1 ';
1661
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1662
		}
1663
		if (!empty($config['ntpd']['pps']['flag2'])) {
1664
			$ntpcfg .= ' flag2 1';
1665
		}
1666
		if (!empty($config['ntpd']['pps']['flag3'])) {
1667
			$ntpcfg .= ' flag3 1';
1668
		} else {
1669
			$ntpcfg .= ' flag3 0';
1670
		}
1671
		if (!empty($config['ntpd']['pps']['flag4'])) {
1672
			$ntpcfg .= ' flag4 1';
1673
		}
1674
		if (!empty($config['ntpd']['pps']['refid'])) {
1675
			$ntpcfg .= ' refid ';
1676
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1677
		}
1678
		$ntpcfg .= "\n";
1679
	}
1680
	/* End PPS configuration */
1681

    
1682
	/* Add GPS configuration */
1683
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1684
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1685
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1686
		$ntpcfg .= "\n";
1687
		$ntpcfg .= "# GPS Setup\n";
1688
		$ntpcfg .= 'server 127.127.20.0 mode ';
1689
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1690
			if (!empty($config['ntpd']['gps']['nmea'])) {
1691
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1692
			}
1693
			if (!empty($config['ntpd']['gps']['speed'])) {
1694
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1695
			}
1696
			if (!empty($config['ntpd']['gps']['subsec'])) {
1697
				$ntpmode += 128;
1698
			}
1699
			$ntpcfg .= (string) $ntpmode;
1700
		} else {
1701
			$ntpcfg .= '0';
1702
		}
1703
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1704
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1705
			$ntpcfg .= ' prefer';
1706
		}
1707
		if (!empty($config['ntpd']['gps']['noselect'])) {
1708
			$ntpcfg .= ' noselect ';
1709
		}
1710
		$ntpcfg .= "\n";
1711
		$ntpcfg .= 'fudge 127.127.20.0';
1712
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1713
			$ntpcfg .= ' time1 ';
1714
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1715
		}
1716
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1717
			$ntpcfg .= ' time2 ';
1718
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1719
		}
1720
		if (!empty($config['ntpd']['gps']['flag1'])) {
1721
			$ntpcfg .= ' flag1 1';
1722
		} else {
1723
			$ntpcfg .= ' flag1 0';
1724
		}
1725
		if (!empty($config['ntpd']['gps']['flag2'])) {
1726
			$ntpcfg .= ' flag2 1';
1727
		}
1728
		if (!empty($config['ntpd']['gps']['flag3'])) {
1729
			$ntpcfg .= ' flag3 1';
1730
		} else {
1731
			$ntpcfg .= ' flag3 0';
1732
		}
1733
		if (!empty($config['ntpd']['gps']['flag4'])) {
1734
			$ntpcfg .= ' flag4 1';
1735
		}
1736
		if (!empty($config['ntpd']['gps']['refid'])) {
1737
			$ntpcfg .= ' refid ';
1738
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1739
		}
1740
		if (!empty($config['ntpd']['gps']['stratum'])) {
1741
			$ntpcfg .= ' stratum ';
1742
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1743
		}
1744
		$ntpcfg .= "\n";
1745
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1746
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1747
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1748
		/* This handles a 2.1 and earlier config */
1749
		$ntpcfg .= "# GPS Setup\n";
1750
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1751
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1752
		// Fall back to local clock if GPS is out of sync?
1753
		$ntpcfg .= "server 127.127.1.0\n";
1754
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1755
	}
1756
	/* End GPS configuration */
1757

    
1758
	$ntpcfg .= "\n\n# Upstream Servers\n";
1759
	/* foreach through ntp servers and write out to ntpd.conf */
1760
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1761
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1762
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1763
			$ntpcfg .= ' prefer';
1764
		}
1765
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1766
			$ntpcfg .= ' noselect';
1767
		}
1768
		$ntpcfg .= "\n";
1769
	}
1770
	unset($ts);
1771

    
1772
	$ntpcfg .= "\n\n";
1773
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1774
		$ntpcfg .= "enable stats\n";
1775
		$ntpcfg .= 'statistics';
1776
		if (!empty($config['ntpd']['clockstats'])) {
1777
			$ntpcfg .= ' clockstats';
1778
		}
1779
		if (!empty($config['ntpd']['loopstats'])) {
1780
			$ntpcfg .= ' loopstats';
1781
		}
1782
		if (!empty($config['ntpd']['peerstats'])) {
1783
			$ntpcfg .= ' peerstats';
1784
		}
1785
		$ntpcfg .= "\n";
1786
	}
1787
	$ntpcfg .= "statsdir {$statsdir}\n";
1788
	$ntpcfg .= 'logconfig =syncall +clockall';
1789
	if (!empty($config['ntpd']['logpeer'])) {
1790
		$ntpcfg .= ' +peerall';
1791
	}
1792
	if (!empty($config['ntpd']['logsys'])) {
1793
		$ntpcfg .= ' +sysall';
1794
	}
1795
	$ntpcfg .= "\n";
1796
	$ntpcfg .= "driftfile {$driftfile}\n";
1797

    
1798
	/* Default Access restrictions */
1799
	$ntpcfg .= 'restrict default';
1800
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1801
		$ntpcfg .= ' kod limited';
1802
	}
1803
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1804
		$ntpcfg .= ' nomodify';
1805
	}
1806
	if (!empty($config['ntpd']['noquery'])) {
1807
		$ntpcfg .= ' noquery';
1808
	}
1809
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1810
		$ntpcfg .= ' nopeer';
1811
	}
1812
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1813
		$ntpcfg .= ' notrap';
1814
	}
1815
	if (!empty($config['ntpd']['noserve'])) {
1816
		$ntpcfg .= ' noserve';
1817
	}
1818
	$ntpcfg .= "\nrestrict -6 default";
1819
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1820
		$ntpcfg .= ' kod limited';
1821
	}
1822
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1823
		$ntpcfg .= ' nomodify';
1824
	}
1825
	if (!empty($config['ntpd']['noquery'])) {
1826
		$ntpcfg .= ' noquery';
1827
	}
1828
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1829
		$ntpcfg .= ' nopeer';
1830
	}
1831
	if (!empty($config['ntpd']['noserve'])) {
1832
		$ntpcfg .= ' noserve';
1833
	}
1834
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1835
		$ntpcfg .= ' notrap';
1836
	}
1837
	/* Custom Access Restrictions */
1838
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1839
		$networkacl = $config['ntpd']['restrictions']['row'];
1840
		foreach ($networkacl as $acl) {
1841
			$ntpcfg .= "\nrestrict ";
1842
			if (is_ipaddrv6($acl['acl_network'])) {
1843
				$ntpcfg .= "-6 {$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1844
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1845
				$ntpcfg .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
1846
			} else {
1847
				continue;
1848
			}
1849
			if (!empty($acl['kod'])) {
1850
				$ntpcfg .= ' kod limited';
1851
			}
1852
			if (!empty($acl['nomodify'])) {
1853
				$ntpcfg .= ' nomodify';
1854
			}
1855
			if (!empty($acl['noquery'])) {
1856
				$ntpcfg .= ' noquery';
1857
			}
1858
			if (!empty($acl['nopeer'])) {
1859
				$ntpcfg .= ' nopeer';
1860
			}
1861
			if (!empty($acl['noserve'])) {
1862
				$ntpcfg .= ' noserve';
1863
			}
1864
			if (!empty($acl['notrap'])) {
1865
				$ntpcfg .= ' notrap';
1866
			}
1867
		}
1868
	}
1869
	$ntpcfg .= "\n";
1870
	/* End Custom Access Restrictions */
1871

    
1872
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1873
	$ntpcfg .= "\n";
1874
	if (!empty($config['ntpd']['leapsec'])) {
1875
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1876
		file_put_contents('/var/db/leap-seconds', $leapsec);
1877
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1878
	}
1879

    
1880

    
1881
	if (empty($config['ntpd']['interface'])) {
1882
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
1883
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1884
		} else {
1885
			$interfaces = array();
1886
		}
1887
	} else {
1888
		$interfaces = explode(",", $config['ntpd']['interface']);
1889
	}
1890

    
1891
	if (is_array($interfaces) && count($interfaces)) {
1892
		$finterfaces = array();
1893
		$ntpcfg .= "interface ignore all\n";
1894
		foreach ($interfaces as $interface) {
1895
			$interface = get_real_interface($interface);
1896
			if (!empty($interface)) {
1897
				$finterfaces[] = $interface;
1898
			}
1899
		}
1900
		foreach ($finterfaces as $interface) {
1901
			$ntpcfg .= "interface listen {$interface}\n";
1902
		}
1903
	}
1904

    
1905
	/* open configuration for writing or bail */
1906
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1907
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
1908
		return;
1909
	}
1910

    
1911
	/* if ntpd is running, kill it */
1912
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1913
		killbypid("{$g['varrun_path']}/ntpd.pid");
1914
	}
1915
	@unlink("{$g['varrun_path']}/ntpd.pid");
1916

    
1917
	/* if /var/empty does not exist, create it */
1918
	if (!is_dir("/var/empty")) {
1919
		mkdir("/var/empty", 0775, true);
1920
	}
1921

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

    
1925
	// Note that we are starting up
1926
	log_error("NTPD is starting up.");
1927
	return;
1928
}
1929

    
1930
function system_halt() {
1931
	global $g;
1932

    
1933
	system_reboot_cleanup();
1934

    
1935
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1936
}
1937

    
1938
function system_reboot() {
1939
	global $g;
1940

    
1941
	system_reboot_cleanup();
1942

    
1943
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1944
}
1945

    
1946
function system_reboot_sync() {
1947
	global $g;
1948

    
1949
	system_reboot_cleanup();
1950

    
1951
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1952
}
1953

    
1954
function system_reboot_cleanup() {
1955
	global $config, $cpzone;
1956

    
1957
	mwexec("/usr/local/bin/beep.sh stop");
1958
	require_once("captiveportal.inc");
1959
	if (is_array($config['captiveportal'])) {
1960
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1961
			captiveportal_radius_stop_all();
1962
			captiveportal_send_server_accounting(true);
1963
		}
1964
	}
1965
	require_once("voucher.inc");
1966
	voucher_save_db_to_config();
1967
	require_once("pkg-utils.inc");
1968
	stop_packages();
1969
}
1970

    
1971
function system_do_shell_commands($early = 0) {
1972
	global $config, $g;
1973
	if (isset($config['system']['developerspew'])) {
1974
		$mt = microtime();
1975
		echo "system_do_shell_commands() being called $mt\n";
1976
	}
1977

    
1978
	if ($early) {
1979
		$cmdn = "earlyshellcmd";
1980
	} else {
1981
		$cmdn = "shellcmd";
1982
	}
1983

    
1984
	if (is_array($config['system'][$cmdn])) {
1985

    
1986
		/* *cmd is an array, loop through */
1987
		foreach ($config['system'][$cmdn] as $cmd) {
1988
			exec($cmd);
1989
		}
1990

    
1991
	} elseif ($config['system'][$cmdn] <> "") {
1992

    
1993
		/* execute single item */
1994
		exec($config['system'][$cmdn]);
1995

    
1996
	}
1997
}
1998

    
1999
function system_dmesg_save() {
2000
	global $g;
2001
	if (isset($config['system']['developerspew'])) {
2002
		$mt = microtime();
2003
		echo "system_dmesg_save() being called $mt\n";
2004
	}
2005

    
2006
	$dmesg = "";
2007
	$_gb = exec("/sbin/dmesg", $dmesg);
2008

    
2009
	/* find last copyright line (output from previous boots may be present) */
2010
	$lastcpline = 0;
2011

    
2012
	for ($i = 0; $i < count($dmesg); $i++) {
2013
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2014
			$lastcpline = $i;
2015
		}
2016
	}
2017

    
2018
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2019
	if (!$fd) {
2020
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2021
		return 1;
2022
	}
2023

    
2024
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2025
		fwrite($fd, $dmesg[$i] . "\n");
2026
	}
2027

    
2028
	fclose($fd);
2029
	unset($dmesg);
2030
	
2031
	// vm-bhyve expects dmesg.boot at the standard location
2032
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2033

    
2034
	return 0;
2035
}
2036

    
2037
function system_set_harddisk_standby() {
2038
	global $g, $config;
2039

    
2040
	if (isset($config['system']['developerspew'])) {
2041
		$mt = microtime();
2042
		echo "system_set_harddisk_standby() being called $mt\n";
2043
	}
2044

    
2045
	if (isset($config['system']['harddiskstandby'])) {
2046
		if (platform_booting()) {
2047
			echo gettext('Setting hard disk standby... ');
2048
		}
2049

    
2050
		$standby = $config['system']['harddiskstandby'];
2051
		// Check for a numeric value
2052
		if (is_numeric($standby)) {
2053
			// Get only suitable candidates for standby; using get_smart_drive_list()
2054
			// from utils.inc to get the list of drives.
2055
			$harddisks = get_smart_drive_list();
2056

    
2057
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2058
			// just in case of some weird pfSense platform installs.
2059
			if (count($harddisks) > 0) {
2060
				// Iterate disks and run the camcontrol command for each
2061
				foreach ($harddisks as $harddisk) {
2062
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2063
				}
2064
				if (platform_booting()) {
2065
					echo gettext("done.") . "\n";
2066
				}
2067
			} else if (platform_booting()) {
2068
				echo gettext("failed!") . "\n";
2069
			}
2070
		} else if (platform_booting()) {
2071
			echo gettext("failed!") . "\n";
2072
		}
2073
	}
2074
}
2075

    
2076
function system_setup_sysctl() {
2077
	global $config;
2078
	if (isset($config['system']['developerspew'])) {
2079
		$mt = microtime();
2080
		echo "system_setup_sysctl() being called $mt\n";
2081
	}
2082

    
2083
	activate_sysctls();
2084

    
2085
	if (isset($config['system']['sharednet'])) {
2086
		system_disable_arp_wrong_if();
2087
	}
2088
}
2089

    
2090
function system_disable_arp_wrong_if() {
2091
	global $config;
2092
	if (isset($config['system']['developerspew'])) {
2093
		$mt = microtime();
2094
		echo "system_disable_arp_wrong_if() being called $mt\n";
2095
	}
2096
	set_sysctl(array(
2097
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2098
		"net.link.ether.inet.log_arp_movements" => "0"
2099
	));
2100
}
2101

    
2102
function system_enable_arp_wrong_if() {
2103
	global $config;
2104
	if (isset($config['system']['developerspew'])) {
2105
		$mt = microtime();
2106
		echo "system_enable_arp_wrong_if() being called $mt\n";
2107
	}
2108
	set_sysctl(array(
2109
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2110
		"net.link.ether.inet.log_arp_movements" => "1"
2111
	));
2112
}
2113

    
2114
function enable_watchdog() {
2115
	global $config;
2116
	return;
2117
	$install_watchdog = false;
2118
	$supported_watchdogs = array("Geode");
2119
	$file = file_get_contents("/var/log/dmesg.boot");
2120
	foreach ($supported_watchdogs as $sd) {
2121
		if (stristr($file, "Geode")) {
2122
			$install_watchdog = true;
2123
		}
2124
	}
2125
	if ($install_watchdog == true) {
2126
		if (is_process_running("watchdogd")) {
2127
			mwexec("/usr/bin/killall watchdogd", true);
2128
		}
2129
		exec("/usr/sbin/watchdogd");
2130
	}
2131
}
2132

    
2133
function system_check_reset_button() {
2134
	global $g;
2135

    
2136
	$specplatform = system_identify_specific_platform();
2137

    
2138
	switch ($specplatform['name']) {
2139
		case 'alix':
2140
		case 'wrap':
2141
		case 'FW7541':
2142
		case 'APU':
2143
		case 'RCC-VE':
2144
		case 'RCC':
2145
		case 'RCC-DFF':
2146
			break;
2147
		default:
2148
			return 0;
2149
	}
2150

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

    
2153
	if ($retval == 99) {
2154
		/* user has pressed reset button for 2 seconds -
2155
		   reset to factory defaults */
2156
		echo <<<EOD
2157

    
2158
***********************************************************************
2159
* Reset button pressed - resetting configuration to factory defaults. *
2160
* All additional packages installed will be removed                   *
2161
* The system will reboot after this completes.                        *
2162
***********************************************************************
2163

    
2164

    
2165
EOD;
2166

    
2167
		reset_factory_defaults();
2168
		system_reboot_sync();
2169
		exit(0);
2170
	}
2171

    
2172
	return 0;
2173
}
2174

    
2175
function system_get_serial() {
2176
	unset($output);
2177
	$_gb = exec('/bin/kenv smbios.system.serial 2>/dev/null', $output);
2178
	$serial = $output[0];
2179

    
2180
	$vm_guest = get_single_sysctl('kern.vm_guest');
2181

    
2182
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2183
	    $vm_guest == 'none') {
2184
		return $serial;
2185
	}
2186

    
2187
	return get_single_sysctl('kern.hostuuid');
2188
}
2189

    
2190
/*
2191
 * attempt to identify the specific platform (for embedded systems)
2192
 * Returns an array with two elements:
2193
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2194
 * descr => human-readable description (e.g. "PC Engines WRAP")
2195
 */
2196
function system_identify_specific_platform() {
2197
	global $g;
2198

    
2199
	$hw_model = get_single_sysctl('hw.model');
2200

    
2201
	/* Try to guess from smbios strings */
2202
	unset($product);
2203
	unset($maker);
2204
	$_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $product);
2205
	$_gb = exec('/bin/kenv smbios.system.maker 2>/dev/null', $maker);
2206
	switch ($product[0]) {
2207
		case 'FW7541':
2208
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2209
			break;
2210
		case 'APU':
2211
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2212
			break;
2213
		case 'RCC-VE':
2214
			$result = array();
2215
			$result['name'] = 'RCC-VE';
2216

    
2217
			/* Detect specific models */
2218
			if (!function_exists('does_interface_exist')) {
2219
				require_once("interfaces.inc");
2220
			}
2221
			if (!does_interface_exist('igb4')) {
2222
				$result['model'] = 'SG-2440';
2223
			} elseif (strpos($hw_model, "C2558") !== false) {
2224
				$result['model'] = 'SG-4860';
2225
			} elseif (strpos($hw_model, "C2758") !== false) {
2226
				$result['model'] = 'SG-8860';
2227
			} else {
2228
				$result['model'] = 'RCC-VE';
2229
			}
2230
			$result['descr'] = 'Netgate ' . $result['model'];
2231
			return $result;
2232
			break;
2233
		case 'DFFv2':
2234
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2235
			break;
2236
		case 'RCC':
2237
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2238
			break;
2239
		case 'SYS-5018A-FTN4':
2240
		case 'A1SAi':
2241
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2242
			break;
2243
		case 'SYS-5018D-FN4T':
2244
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2245
			break;
2246
		case 'Virtual Machine':
2247
			if ($maker[0] == "Microsoft Corporation") {
2248
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2249
			}
2250
			break;
2251
	}
2252

    
2253
	/* the rest of the code only deals with 'embedded' platforms */
2254
	if ($g['platform'] != 'nanobsd') {
2255
		return array('name' => $g['platform'], 'descr' => $g['platform']);
2256
	}
2257

    
2258
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2259
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2260
	}
2261

    
2262
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2263
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2264
	}
2265

    
2266
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2267
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2268
	}
2269

    
2270
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2271
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2272
	}
2273

    
2274
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2275
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2276
	}
2277

    
2278
	unset($hw_model);
2279

    
2280
	$dmesg_boot = system_get_dmesg_boot();
2281
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2282
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2283
	}
2284
	unset($dmesg_boot);
2285

    
2286
	/* unknown embedded platform */
2287
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
2288
}
2289

    
2290
function system_get_dmesg_boot() {
2291
	global $g;
2292

    
2293
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2294
}
2295

    
2296
?>
(52-52/65)