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
 * Licensed under the Apache License, Version 2.0 (the "License");
14
 * you may not use this file except in compliance with the License.
15
 * You may obtain a copy of the License at
16
 *
17
 * http://www.apache.org/licenses/LICENSE-2.0
18
 *
19
 * Unless required by applicable law or agreed to in writing, software
20
 * distributed under the License is distributed on an "AS IS" BASIS,
21
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
 * See the License for the specific language governing permissions and
23
 * limitations under the License.
24
 */
25

    
26
function activate_powerd() {
27
	global $config, $g;
28

    
29
	if (is_process_running("powerd")) {
30
		exec("/usr/bin/killall powerd");
31
	}
32
	if (isset($config['system']['powerd_enable'])) {
33
		$ac_mode = "hadp";
34
		if (!empty($config['system']['powerd_ac_mode'])) {
35
			$ac_mode = $config['system']['powerd_ac_mode'];
36
		}
37

    
38
		$battery_mode = "hadp";
39
		if (!empty($config['system']['powerd_battery_mode'])) {
40
			$battery_mode = $config['system']['powerd_battery_mode'];
41
		}
42

    
43
		$normal_mode = "hadp";
44
		if (!empty($config['system']['powerd_normal_mode'])) {
45
			$normal_mode = $config['system']['powerd_normal_mode'];
46
		}
47

    
48
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode");
49
	}
50
}
51

    
52
function get_default_sysctl_value($id) {
53
	global $sysctls;
54

    
55
	if (isset($sysctls[$id])) {
56
		return $sysctls[$id];
57
	}
58
}
59

    
60
function get_sysctl_descr($sysctl) {
61
	unset($output);
62
	$_gb = exec("/sbin/sysctl -nd {$sysctl}", $output);
63

    
64
	return $output[0];
65
}
66

    
67
function system_get_sysctls() {
68
	global $config, $sysctls;
69

    
70
	$disp_sysctl = array();
71
	$disp_cache = array();
72
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
73
		foreach ($config['sysctl']['item'] as $id => $tunable) {
74
			if ($tunable['value'] == "default") {
75
				$value = get_default_sysctl_value($tunable['tunable']);
76
			} else {
77
				$value = $tunable['value'];
78
			}
79

    
80
			$disp_sysctl[$id] = $tunable;
81
			$disp_sysctl[$id]['modified'] = true;
82
			$disp_cache[$tunable['tunable']] = 'set';
83
		}
84
	}
85

    
86
	foreach ($sysctls as $sysctl => $value) {
87
		if (isset($disp_cache[$sysctl])) {
88
			continue;
89
		}
90

    
91
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
92
	}
93
	unset($disp_cache);
94
	return $disp_sysctl;
95
}
96

    
97
function activate_sysctls() {
98
	global $config, $g, $sysctls;
99

    
100
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
101
		foreach ($config['sysctl']['item'] as $tunable) {
102
			if ($tunable['value'] == "default") {
103
				$value = get_default_sysctl_value($tunable['tunable']);
104
			} else {
105
				$value = $tunable['value'];
106
			}
107

    
108
			$sysctls[$tunable['tunable']] = $value;
109
		}
110
	}
111

    
112
	set_sysctl($sysctls);
113
}
114

    
115
function system_resolvconf_generate($dynupdate = false) {
116
	global $config, $g;
117

    
118
	if (isset($config['system']['developerspew'])) {
119
		$mt = microtime();
120
		echo "system_resolvconf_generate() being called $mt\n";
121
	}
122

    
123
	$syscfg = $config['system'];
124

    
125
	if ((((isset($config['dnsmasq']['enable'])) &&
126
	      (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
127
	      (empty($config['dnsmasq']['interface']) ||
128
	       in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
129
	     ((isset($config['unbound']['enable'])) &&
130
	      (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
131
	      (empty($config['unbound']['active_interface']) ||
132
	       in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
133
	       in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
134
	     (!isset($config['system']['dnslocalhost']))) {
135
		$resolvconf .= "nameserver 127.0.0.1\n";
136
	}
137

    
138
	if (isset($syscfg['dnsallowoverride'])) {
139
		/* get dynamically assigned DNS servers (if any) */
140
		$ns = array_unique(get_searchdomains());
141
		foreach ($ns as $searchserver) {
142
			if ($searchserver) {
143
				$resolvconf .= "search {$searchserver}\n";
144
			}
145
		}
146
		$ns = array_unique(get_nameservers());
147
		foreach ($ns as $nameserver) {
148
			if ($nameserver) {
149
				$resolvconf .= "nameserver $nameserver\n";
150
			}
151
		}
152
	} else {
153
		$ns = array();
154
		// Do not create blank search/domain lines, it can break tools like dig.
155
		if ($syscfg['domain']) {
156
			$resolvconf .= "search {$syscfg['domain']}\n";
157
		}
158
	}
159
	if (is_array($syscfg['dnsserver'])) {
160
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
161
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
162
				$resolvconf .= "nameserver $sys_dnsserver\n";
163
			}
164
		}
165
	}
166

    
167
	// Add EDNS support
168
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
169
		$resolvconf .= "options edns0\n";
170
	}
171

    
172
	$dnslock = lock('resolvconf', LOCK_EX);
173

    
174
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
175
	if (!$fd) {
176
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
177
		unlock($dnslock);
178
		return 1;
179
	}
180

    
181
	fwrite($fd, $resolvconf);
182
	fclose($fd);
183

    
184
	// Prevent resolvconf(8) from rewriting our resolv.conf
185
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
186
	if (!$fd) {
187
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
188
		return 1;
189
	}
190
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
191
	fclose($fd);
192

    
193
	if (!platform_booting()) {
194
		/* restart dhcpd (nameservers may have changed) */
195
		if (!$dynupdate) {
196
			services_dhcpd_configure();
197
		}
198
	}
199

    
200
	/* setup static routes for DNS servers. */
201
	$dnscounter = 1;
202
	$dnsgw = "dns{$dnscounter}gw";
203
	while (isset($config['system'][$dnsgw])) {
204
		/* setup static routes for dns servers */
205
		if (!(empty($config['system'][$dnsgw]) ||
206
		    $config['system'][$dnsgw] == "none")) {
207
			$gwname = $config['system'][$dnsgw];
208
			$gatewayip = lookup_gateway_ip_by_name($gwname);
209
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
210
			/* dns server array starts at 0 */
211
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
212

    
213
			if (is_ipaddr($gatewayip)) {
214
				route_add_or_change("-host {$inet6}{$dnsserver} {$gatewayip}");
215
			} else {
216
				/* Remove old route when disable gw */
217
				mwexec("/sbin/route delete -host {$inet6}{$dnsserver}");
218
				if (isset($config['system']['route-debug'])) {
219
					$mt = microtime();
220
					log_error("ROUTING debug: $mt - route delete -host {$inet6}{$dnsserver}");
221
				}
222
			}
223
		}
224
		$dnscounter++;
225
		$dnsgw = "dns{$dnscounter}gw";
226
	}
227

    
228
	unlock($dnslock);
229

    
230
	return 0;
231
}
232

    
233
function get_searchdomains() {
234
	global $config, $g;
235

    
236
	$master_list = array();
237

    
238
	// Read in dhclient nameservers
239
	$search_list = glob("/var/etc/searchdomain_*");
240
	if (is_array($search_list)) {
241
		foreach ($search_list as $fdns) {
242
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
243
			if (!is_array($contents)) {
244
				continue;
245
			}
246
			foreach ($contents as $dns) {
247
				if (is_hostname($dns)) {
248
					$master_list[] = $dns;
249
				}
250
			}
251
		}
252
	}
253

    
254
	return $master_list;
255
}
256

    
257
function get_nameservers() {
258
	global $config, $g;
259
	$master_list = array();
260

    
261
	// Read in dhclient nameservers
262
	$dns_lists = glob("/var/etc/nameserver_*");
263
	if (is_array($dns_lists)) {
264
		foreach ($dns_lists as $fdns) {
265
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
266
			if (!is_array($contents)) {
267
				continue;
268
			}
269
			foreach ($contents as $dns) {
270
				if (is_ipaddr($dns)) {
271
					$master_list[] = $dns;
272
				}
273
			}
274
		}
275
	}
276

    
277
	// Read in any extra nameservers
278
	if (file_exists("/var/etc/nameservers.conf")) {
279
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
280
		if (is_array($dns_s)) {
281
			foreach ($dns_s as $dns) {
282
				if (is_ipaddr($dns)) {
283
					$master_list[] = $dns;
284
				}
285
			}
286
		}
287
	}
288

    
289
	return $master_list;
290
}
291

    
292
/* Create localhost + local interfaces entries for /etc/hosts */
293
function system_hosts_local_entries() {
294
	global $config;
295

    
296
	$syscfg = $config['system'];
297

    
298
	$hosts = array();
299
	$hosts[] = array(
300
	    'ipaddr' => '127.0.0.1',
301
	    'fqdn' => 'localhost',
302
	    'name' => 'localhost.' . $syscfg['domain']
303
	);
304
	$hosts[] = array(
305
	    'ipaddr' => '::1',
306
	    'fqdn' => 'localhost',
307
	    'name' => 'localhost.' . $syscfg['domain']
308
	);
309

    
310
	if ($config['interfaces']['lan']) {
311
		$sysiflist = array('lan' => "lan");
312
	} else {
313
		$sysiflist = get_configured_interface_list();
314
	}
315

    
316
	$hosts_if_found = false;
317
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
318
	foreach ($sysiflist as $sysif) {
319
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
320
			continue;
321
		}
322
		$cfgip = get_interface_ip($sysif);
323
		if (is_ipaddrv4($cfgip)) {
324
			$hosts[] = array(
325
			    'ipaddr' => $cfgip,
326
			    'fqdn' => $local_fqdn
327
			);
328
			$hosts_if_found = true;
329
		}
330
		$cfgipv6 = get_interface_ipv6($sysif);
331
		if (is_ipaddrv6($cfgipv6)) {
332
			$hosts[] = array(
333
			    'ipaddr' => $cfgipv6,
334
			    'fqdn' => $local_fqdn
335
			);
336
			$hosts_if_found = true;
337
		}
338
		if ($hosts_if_found == true) {
339
			break;
340
		}
341
	}
342

    
343
	return $hosts;
344
}
345

    
346
/* Read host override entries from dnsmasq or unbound */
347
function system_hosts_override_entries($dnscfg) {
348
	$hosts = array();
349

    
350
	if (!is_array($dnscfg) ||
351
	    !is_array($dnscfg['hosts']) ||
352
	    !isset($dnscfg['enable'])) {
353
		return $hosts;
354
	}
355

    
356
	foreach ($dnscfg['hosts'] as $host) {
357
		$fqdn = '';
358
		if ($host['host'] || $host['host'] == "0") {
359
			$fqdn .= "{$host['host']}.";
360
		}
361
		$fqdn .= $host['domain'];
362

    
363
		$hosts[] = array(
364
		    'ipaddr' => $host['ip'],
365
		    'fqdn' => $fqdn
366
		);
367

    
368
		if (!is_array($host['aliases']) ||
369
		    !is_array($host['aliases']['item'])) {
370
			continue;
371
		}
372

    
373
		foreach ($host['aliases']['item'] as $alias) {
374
			$fqdn = '';
375
			if ($alias['host'] || $alias['host'] == "0") {
376
				$fqdn .= "{$alias['host']}.";
377
			}
378
			$fqdn .= $alias['domain'];
379

    
380
			$hosts[] = array(
381
			    'ipaddr' => $host['ip'],
382
			    'fqdn' => $fqdn
383
			);
384
		}
385
	}
386

    
387
	return $hosts;
388
}
389

    
390
/* Read all dhcpd/dhcpdv6 staticmap entries */
391
function system_hosts_dhcpd_entries() {
392
	global $config;
393

    
394
	$hosts = array();
395
	$syscfg = $config['system'];
396

    
397
	if (is_array($config['dhcpd'])) {
398
		$conf_dhcpd = $config['dhcpd'];
399
	} else {
400
		$conf_dhcpd = array();
401
	}
402

    
403
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
404
		if (!is_array($dhcpifconf['staticmap']) ||
405
		    !isset($dhcpifconf['enable'])) {
406
			continue;
407
		}
408
		foreach ($dhcpifconf['staticmap'] as $host) {
409
			if (!$host['ipaddr'] ||
410
			    !$host['hostname']) {
411
				continue;
412
			}
413

    
414
			$fqdn = $host['hostname'] . ".";
415
			if ($host['domain']) {
416
				$fqdn .= $host['domain'];
417
			} elseif ($dhcpifconf['domain']) {
418
				$fqdn .= $dhcpifconf['domain'];
419
			} else {
420
				$fqdn .= $syscfg['domain'];
421
			}
422

    
423
			$hosts[] = array(
424
			    'ipaddr' => $host['ipaddr'],
425
			    'fqdn' => $fqdn
426
			);
427
		}
428
	}
429
	unset($conf_dhcpd);
430

    
431
	if (is_array($config['dhcpdv6'])) {
432
		$conf_dhcpdv6 = $config['dhcpdv6'];
433
	} else {
434
		$conf_dhcpdv6 = array();
435
	}
436

    
437
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
438
		if (!is_array($dhcpifconf['staticmap']) ||
439
		    !isset($dhcpifconf['enable'])) {
440
			continue;
441
		}
442

    
443
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
444
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
445
		    'track6') {
446
			$isdelegated = true;
447
		} else {
448
			$isdelegated = false;
449
		}
450

    
451
		foreach ($dhcpifconf['staticmap'] as $host) {
452
			$ipaddrv6 = $host['ipaddrv6'];
453

    
454
			if (!$ipaddrv6 || !$host['hostname']) {
455
				continue;
456
			}
457

    
458
			if ($isdelegated) {
459
				/*
460
				 * We are always in an "end-user" subnet
461
				 * here, which all are /64 for IPv6.
462
				 */
463
				$ipaddrv6 = merge_ipv6_delegated_prefix(
464
				    get_interface_ipv6($dhcpif),
465
				    $ipaddrv6, 64);
466
			}
467

    
468
			$fqdn = $host['hostname'] . ".";
469
			if ($host['domain']) {
470
				$fqdn .= $host['domain'];
471
			} else if ($dhcpifconf['domain']) {
472
				$fqdn .= $dhcpifconf['domain'];
473
			} else {
474
				$fqdn .= $syscfg['domain'];
475
			}
476

    
477
			$hosts[] = array(
478
			    'ipaddr' => $ipaddrv6,
479
			    'fqdn' => $fqdn
480
			);
481
		}
482
	}
483
	unset($conf_dhcpdv6);
484

    
485
	return $hosts;
486
}
487

    
488
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
489
function system_hosts_entries($dnscfg) {
490
	$local = system_hosts_local_entries();
491

    
492
	$dns = array();
493
	$dhcpd = array();
494
	if (isset($dnscfg['enable'])) {
495
		$dns = system_hosts_override_entries($dnscfg);
496
		if (isset($dnscfg['regdhcpstatic'])) {
497
			$dhcpd = system_hosts_dhcpd_entries();
498
		}
499
	}
500

    
501
	if (isset($dnscfg['dhcpfirst'])) {
502
		return array_merge($local, $dns, $dhcpd);
503
	} else {
504
		return array_merge($local, $dhcpd, $dns);
505
	}
506
}
507

    
508
function system_hosts_generate() {
509
	global $config, $g;
510
	if (isset($config['system']['developerspew'])) {
511
		$mt = microtime();
512
		echo "system_hosts_generate() being called $mt\n";
513
	}
514

    
515
	// prefer dnsmasq for hosts generation where it's enabled. It relies
516
	// on hosts for name resolution of its overrides, unbound does not.
517
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
518
		$dnsmasqcfg = $config['dnsmasq'];
519
	} else {
520
		$dnsmasqcfg = $config['unbound'];
521
	}
522

    
523
	$syscfg = $config['system'];
524
	$hosts = "";
525
	$lhosts = "";
526
	$dhosts = "";
527

    
528
	$hosts_array = system_hosts_entries($dnsmasqcfg);
529
	foreach ($hosts_array as $host) {
530
		$hosts .= "{$host['ipaddr']}\t{$host['fqdn']}";
531
		if (!empty($host['name'])) {
532
			$hosts .= " {$host['name']}";
533
		}
534
		$hosts .= "\n";
535
	}
536
	unset($hosts_array);
537

    
538
	$fd = fopen("{$g['etc_path']}/hosts", "w");
539
	if (!$fd) {
540
		log_error(gettext(
541
		    "Error: cannot open hosts file in system_hosts_generate()."
542
		    ));
543
		return 1;
544
	}
545

    
546
	/*
547
	 * Do not remove this because dhcpleases monitors with kqueue it needs
548
	 * to be killed before writing to hosts files.
549
	 */
550
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
551
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
552
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
553
	}
554

    
555
	fwrite($fd, $hosts);
556
	fclose($fd);
557

    
558
	if (isset($config['unbound']['enable'])) {
559
		require_once("unbound.inc");
560
		unbound_hosts_generate();
561
	}
562

    
563
	/* restart dhcpleases */
564
	if (!platform_booting()) {
565
		system_dhcpleases_configure();
566
	}
567

    
568
	return 0;
569
}
570

    
571
function system_dhcpleases_configure() {
572
	global $config, $g;
573

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

    
576
	/* Start the monitoring process for dynamic dhcpclients. */
577
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
578
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
579
		/* Make sure we do not error out */
580
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
581
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
582
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
583
		}
584

    
585
		if (isset($config['unbound']['enable'])) {
586
			$dns_pid = "unbound.pid";
587
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
588
		} else {
589
			$dns_pid = "dnsmasq.pid";
590
			$unbound_conf = "";
591
		}
592

    
593
		if (isvalidpid($pidfile)) {
594
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
595
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
596
			if (intval($retval) == 0) {
597
				sigkillbypid($pidfile, "HUP");
598
				return;
599
			} else {
600
				sigkillbypid($pidfile, "TERM");
601
			}
602
		}
603

    
604
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
605
		if (is_process_running("dhcpleases")) {
606
			sigkillbyname('dhcpleases', "TERM");
607
		}
608
		@unlink($pidfile);
609
		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['etc_path']}/hosts");
610
	} elseif (isvalidpid($pidfile)) {
611
		sigkillbypid($pidfile, "TERM");
612
		@unlink($pidfile);
613
	}
614
}
615

    
616
function system_hostname_configure() {
617
	global $config, $g;
618
	if (isset($config['system']['developerspew'])) {
619
		$mt = microtime();
620
		echo "system_hostname_configure() being called $mt\n";
621
	}
622

    
623
	$syscfg = $config['system'];
624

    
625
	/* set hostname */
626
	$status = mwexec("/bin/hostname " .
627
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
628

    
629
	/* Setup host GUID ID.  This is used by ZFS. */
630
	mwexec("/etc/rc.d/hostid start");
631

    
632
	return $status;
633
}
634

    
635
function system_routing_configure($interface = "") {
636
	global $config, $g;
637

    
638
	if (isset($config['system']['developerspew'])) {
639
		$mt = microtime();
640
		echo "system_routing_configure() being called $mt\n";
641
	}
642

    
643
	$gatewayip = "";
644
	$interfacegw = "";
645
	$gatewayipv6 = "";
646
	$interfacegwv6 = "";
647
	$foundgw = false;
648
	$foundgwv6 = false;
649
	/* tack on all the hard defined gateways as well */
650
	if (is_array($config['gateways']['gateway_item'])) {
651
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
652
		foreach	($config['gateways']['gateway_item'] as $gateway) {
653
			if (isset($gateway['defaultgw'])) {
654
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
655
					if (strpos($gateway['gateway'], ":")) {
656
						continue;
657
					}
658
					if ($gateway['gateway'] == "dynamic") {
659
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
660
					}
661
					$gatewayip = $gateway['gateway'];
662
					$interfacegw = $gateway['interface'];
663
					if (!empty($gateway['interface'])) {
664
						$defaultif = get_real_interface($gateway['interface']);
665
						if ($defaultif) {
666
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
667
						}
668
					}
669
					$foundgw = true;
670
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
671
					if ($gateway['gateway'] == "dynamic") {
672
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
673
					}
674
					$gatewayipv6 = $gateway['gateway'];
675
					$interfacegwv6 = $gateway['interface'];
676
					if (!empty($gateway['interface'])) {
677
						$defaultifv6 = get_real_interface($gateway['interface']);
678
						if ($defaultifv6) {
679
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
680
						}
681
					}
682
					$foundgwv6 = true;
683
				}
684
			}
685
			if ($foundgw === true && $foundgwv6 === true) {
686
				break;
687
			}
688
		}
689
	}
690
	if ($foundgw == false) {
691
		$defaultif = get_real_interface("wan");
692
		$interfacegw = "wan";
693
		$gatewayip = get_interface_gateway("wan");
694
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
695
	}
696
	if ($foundgwv6 == false) {
697
		$defaultifv6 = get_real_interface("wan");
698
		$interfacegwv6 = "wan";
699
		$gatewayipv6 = get_interface_gateway_v6("wan");
700
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
701
	}
702
	$dont_add_route = false;
703
	/* if OLSRD is enabled, allow WAN to house DHCP. */
704
	if (is_array($config['installedpackages']['olsrd'])) {
705
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
706
			if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
707
				$dont_add_route = true;
708
				log_error(gettext("Not adding default route because OLSR dynamic gateway is enabled."));
709
				break;
710
			}
711
		}
712
	}
713

    
714
	$gateways_arr = return_gateways_array(false, true);
715
	foreach ($gateways_arr as $gateway) {
716
		// setup static interface routes for nonlocal gateways
717
		if (isset($gateway["nonlocalgateway"])) {
718
			$srgatewayip = $gateway['gateway'];
719
			$srinterfacegw = $gateway['interface'];
720
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
721
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
722
				route_add_or_change("{$inet} {$srgatewayip} " .
723
				    "-iface {$srinterfacegw}");
724
			}
725
		}
726
	}
727

    
728
	if ($dont_add_route == false) {
729
		if (!empty($interface) && $interface != $interfacegw) {
730
			;
731
		} else if (is_ipaddrv4($gatewayip)) {
732
			log_error(sprintf(gettext("ROUTING: setting default route to %s"), $gatewayip));
733
			route_add_or_change("-inet default {$gatewayip}");
734
		}
735

    
736
		if (!empty($interface) && $interface != $interfacegwv6) {
737
			;
738
		} else if (is_ipaddrv6($gatewayipv6)) {
739
			$ifscope = "";
740
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
741
				$ifscope = "%{$defaultifv6}";
742
			}
743
			log_error(sprintf(gettext("ROUTING: setting IPv6 default route to %s"), $gatewayipv6 . $ifscope));
744
			route_add_or_change("-inet6 default {$gatewayipv6}{$ifscope}");
745
		}
746
	}
747

    
748
	system_staticroutes_configure($interface, false);
749

    
750
	return 0;
751
}
752

    
753
function system_staticroutes_configure($interface = "", $update_dns = false) {
754
	global $config, $g, $aliastable;
755

    
756
	$filterdns_list = array();
757

    
758
	$static_routes = get_staticroutes(false, true);
759
	if (count($static_routes)) {
760
		$gateways_arr = return_gateways_array(false, true);
761

    
762
		foreach ($static_routes as $rtent) {
763
			if (empty($gateways_arr[$rtent['gateway']])) {
764
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
765
				continue;
766
			}
767
			$gateway = $gateways_arr[$rtent['gateway']];
768
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
769
				continue;
770
			}
771

    
772
			$gatewayip = $gateway['gateway'];
773
			$interfacegw = $gateway['interface'];
774

    
775
			$blackhole = "";
776
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
777
				$blackhole = "-blackhole";
778
			}
779

    
780
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
781
				continue;
782
			}
783

    
784
			$dnscache = array();
785
			if ($update_dns === true) {
786
				if (is_subnet($rtent['network'])) {
787
					continue;
788
				}
789
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
790
				if (empty($dnscache)) {
791
					continue;
792
				}
793
			}
794

    
795
			if (is_subnet($rtent['network'])) {
796
				$ips = array($rtent['network']);
797
			} else {
798
				if (!isset($rtent['disabled'])) {
799
					$filterdns_list[] = $rtent['network'];
800
				}
801
				$ips = add_hostname_to_watch($rtent['network']);
802
			}
803

    
804
			foreach ($dnscache as $ip) {
805
				if (in_array($ip, $ips)) {
806
					continue;
807
				}
808
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
809
				if (isset($config['system']['route-debug'])) {
810
					$mt = microtime();
811
					log_error("ROUTING debug: $mt - route delete $ip ");
812
				}
813
			}
814

    
815
			if (isset($rtent['disabled'])) {
816
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
817
				foreach ($ips as $ip) {
818
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
819
					if (isset($config['system']['route-debug'])) {
820
						$mt = microtime();
821
						log_error("ROUTING debug: $mt - route delete $ip ");
822
					}
823
				}
824
				continue;
825
			}
826

    
827
			foreach ($ips as $ip) {
828
				if (is_ipaddrv4($ip)) {
829
					$ip .= "/32";
830
				}
831
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
832

    
833
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
834

    
835
				$cmd = "{$inet} {$blackhole} {$ip} ";
836

    
837
				if (is_subnet($ip)) {
838
					if (is_ipaddr($gatewayip)) {
839
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
840
							// add interface scope for link local v6 routes
841
							$gatewayip .= "%$interfacegw";
842
						}
843
						route_add_or_change($cmd . $gatewayip);
844
					} else if (!empty($interfacegw)) {
845
						route_add_or_change($cmd . "-iface {$interfacegw}");
846
					}
847
				}
848
			}
849
		}
850
		unset($gateways_arr);
851
	}
852
	unset($static_routes);
853

    
854
	if ($update_dns === false) {
855
		if (count($filterdns_list)) {
856
			$interval = 60;
857
			$hostnames = "";
858
			array_unique($filterdns_list);
859
			foreach ($filterdns_list as $hostname) {
860
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
861
			}
862
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
863
			unset($hostnames);
864

    
865
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
866
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
867
			} else {
868
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
869
			}
870
		} else {
871
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
872
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
873
		}
874
	}
875
	unset($filterdns_list);
876

    
877
	return 0;
878
}
879

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

    
887
	set_sysctl(array(
888
		"net.inet.ip.forwarding" => "1",
889
		"net.inet6.ip6.forwarding" => "1"
890
	));
891

    
892
	return;
893
}
894

    
895
function system_syslogd_fixup_server($server) {
896
	/* If it's an IPv6 IP alone, encase it in brackets */
897
	if (is_ipaddrv6($server)) {
898
		return "[$server]";
899
	} else {
900
		return $server;
901
	}
902
}
903

    
904
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
905
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
906
	$facility .= " ".
907
	$remote_servers = "";
908
	$pad_to  = max(strlen($facility), 56);
909
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
910
	if (isset($syslogcfg['enable'])) {
911
		if ($syslogcfg['remoteserver']) {
912
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
913
		}
914
		if ($syslogcfg['remoteserver2']) {
915
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
916
		}
917
		if ($syslogcfg['remoteserver3']) {
918
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
919
		}
920
	}
921
	return $remote_servers;
922
}
923

    
924
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
925
	global $config, $g;
926
	if ($restart_syslogd) {
927
		exec("/usr/bin/killall syslogd");
928
	}
929
	if (isset($config['system']['disablesyslogclog'])) {
930
		unlink($logfile);
931
		touch($logfile);
932
	} else {
933
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
934
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
935
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
936
	}
937
	if ($restart_syslogd) {
938
		system_syslogd_start();
939
	}
940
	// Bug #6915
941
	if ($logfile == "/var/log/resolver.log") {
942
		services_unbound_configure(true);
943
	}
944
}
945

    
946
function clear_all_log_files($restart = false) {
947
	global $g;
948
	exec("/usr/bin/killall syslogd");
949

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

    
955
	if ($restart) {
956
		system_syslogd_start();
957
		killbyname("dhcpd");
958
		if (!function_exists('services_dhcpd_configure')) {
959
			require_once('services.inc');
960
		}
961
		services_dhcpd_configure();
962
		// Bug #6915
963
		services_unbound_configure(false);
964
	}
965
	return;
966
}
967

    
968
function system_syslogd_start() {
969
	global $config, $g;
970
	if (isset($config['system']['developerspew'])) {
971
		$mt = microtime();
972
		echo "system_syslogd_start() being called $mt\n";
973
	}
974

    
975
	mwexec("/etc/rc.d/hostid start");
976

    
977
	$syslogcfg = $config['syslog'];
978

    
979
	if (platform_booting()) {
980
		echo gettext("Starting syslog...");
981
	}
982

    
983
	// Which logging type are we using this week??
984
	if (isset($config['system']['disablesyslogclog'])) {
985
		$log_directive = "";
986
		$log_create_directive = "/usr/bin/touch ";
987
		$log_size = "";
988
	} else { // Defaults to CLOG
989
		$log_directive = "%";
990
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
991
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
992
	}
993

    
994
	$syslogd_extra = "";
995
	if (isset($syslogcfg)) {
996
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'olsrd', 'zebra', 'ospfd', 'bgpd', 'miniupnpd', 'filterlog');
997
		$syslogconf = "";
998
		if ($config['installedpackages']['package']) {
999
			foreach ($config['installedpackages']['package'] as $package) {
1000
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1001
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1002
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1003
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1004
					}
1005
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1006
				}
1007
			}
1008
		}
1009
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1010
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
1011
		if (!isset($syslogcfg['disablelocallogging'])) {
1012
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1013
		}
1014
		if (isset($syslogcfg['routing'])) {
1015
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1016
		}
1017

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

    
1026
		$syslogconf .= "!ppp\n";
1027
		if (!isset($syslogcfg['disablelocallogging'])) {
1028
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
1029
		}
1030
		if (isset($syslogcfg['ppp'])) {
1031
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1032
		}
1033

    
1034
		$syslogconf .= "!poes\n";
1035
		if (!isset($syslogcfg['disablelocallogging'])) {
1036
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
1037
		}
1038
		if (isset($syslogcfg['vpn'])) {
1039
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1040
		}
1041

    
1042
		$syslogconf .= "!l2tps\n";
1043
		if (!isset($syslogcfg['disablelocallogging'])) {
1044
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
1045
		}
1046
		if (isset($syslogcfg['vpn'])) {
1047
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1048
		}
1049

    
1050
		$syslogconf .= "!charon,ipsec_starter\n";
1051
		if (!isset($syslogcfg['disablelocallogging'])) {
1052
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
1053
		}
1054
		if (isset($syslogcfg['vpn'])) {
1055
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1056
		}
1057

    
1058
		$syslogconf .= "!openvpn\n";
1059
		if (!isset($syslogcfg['disablelocallogging'])) {
1060
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
1061
		}
1062
		if (isset($syslogcfg['vpn'])) {
1063
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1064
		}
1065

    
1066
		$syslogconf .= "!dpinger\n";
1067
		if (!isset($syslogcfg['disablelocallogging'])) {
1068
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
1069
		}
1070
		if (isset($syslogcfg['dpinger'])) {
1071
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1072
		}
1073

    
1074
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1075
		if (!isset($syslogcfg['disablelocallogging'])) {
1076
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1077
		}
1078
		if (isset($syslogcfg['resolver'])) {
1079
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1080
		}
1081

    
1082
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
1083
		if (!isset($syslogcfg['disablelocallogging'])) {
1084
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
1085
		}
1086
		if (isset($syslogcfg['dhcp'])) {
1087
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1088
		}
1089

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

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

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

    
1114
		$syslogconf .= "!-{$facilitylist}\n";
1115
		if (!isset($syslogcfg['disablelocallogging'])) {
1116
			$syslogconf .= <<<EOD
1117
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1118
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1119
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1120
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1121
*.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
1122
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1123
*.emerg								*
1124

    
1125
EOD;
1126
		}
1127
		if (isset($syslogcfg['vpn'])) {
1128
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1129
		}
1130
		if (isset($syslogcfg['portalauth'])) {
1131
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1132
		}
1133
		if (isset($syslogcfg['dhcp'])) {
1134
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1135
		}
1136
		if (isset($syslogcfg['system'])) {
1137
			$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");
1138
		}
1139
		if (isset($syslogcfg['logall'])) {
1140
			// Make everything mean everything, including facilities excluded above.
1141
			$syslogconf .= "!*\n";
1142
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1143
		}
1144

    
1145
		if (isset($syslogcfg['zmqserver'])) {
1146
				$syslogconf .= <<<EOD
1147
*.*								^{$syslogcfg['zmqserver']}
1148

    
1149
EOD;
1150
		}
1151
		/* write syslog.conf */
1152
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1153
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1154
			unset($syslogconf);
1155
			return 1;
1156
		}
1157
		unset($syslogconf);
1158

    
1159
		$sourceip = "";
1160
		if (!empty($syslogcfg['sourceip'])) {
1161
			if ($syslogcfg['ipproto'] == "ipv6") {
1162
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1163
				if (!is_ipaddr($ifaddr)) {
1164
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1165
				}
1166
			} else {
1167
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1168
				if (!is_ipaddr($ifaddr)) {
1169
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1170
				}
1171
			}
1172
			if (is_ipaddr($ifaddr)) {
1173
				$sourceip = "-b {$ifaddr}";
1174
			}
1175
		}
1176

    
1177
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1178
	}
1179

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

    
1182
	if (isset($config['installedpackages']['package'])) {
1183
		foreach ($config['installedpackages']['package'] as $package) {
1184
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1185
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1186
				$log_sockets[] = $package['logging']['logsocket'];
1187
			}
1188
		}
1189
	}
1190
	
1191
	$syslogd_sockets = "";
1192
	foreach ($log_sockets as $log_socket) {
1193
		// Ensure that the log directory exists
1194
		$logpath = dirname($log_socket);
1195
		safe_mkdir($logpath);
1196
		$syslogd_sockets .= " -l {$log_socket}";
1197
	}
1198

    
1199
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1200
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1201
		usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1202
	}
1203

    
1204
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1205
		// if it still hasn't responded to the TERM, KILL it.
1206
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1207
		usleep(100000);
1208
	}
1209

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

    
1212
	if (platform_booting()) {
1213
		echo gettext("done.") . "\n";
1214
	}
1215

    
1216
	return $retval;
1217
}
1218

    
1219
function system_webgui_create_certificate() {
1220
	global $config, $g;
1221

    
1222
	if (!is_array($config['ca'])) {
1223
		$config['ca'] = array();
1224
	}
1225
	$a_ca =& $config['ca'];
1226
	if (!is_array($config['cert'])) {
1227
		$config['cert'] = array();
1228
	}
1229
	$a_cert =& $config['cert'];
1230
	log_error(gettext("Creating SSL Certificate for this host"));
1231

    
1232
	$cert = array();
1233
	$cert['refid'] = uniqid();
1234
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1235

    
1236
	$dn = array(
1237
		'countryName' => "US",
1238
		'stateOrProvinceName' => "State",
1239
		'localityName' => "Locality",
1240
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1241
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1242
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
1243
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1244
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1245
		while ($ssl_err = openssl_error_string()) {
1246
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1247
		}
1248
		error_reporting($old_err_level);
1249
		return null;
1250
	}
1251
	error_reporting($old_err_level);
1252

    
1253
	$a_cert[] = $cert;
1254
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1255
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1256
	return $cert;
1257
}
1258

    
1259
function system_webgui_start() {
1260
	global $config, $g;
1261

    
1262
	if (platform_booting()) {
1263
		echo gettext("Starting webConfigurator...");
1264
	}
1265

    
1266
	chdir($g['www_path']);
1267

    
1268
	/* defaults */
1269
	$portarg = "80";
1270
	$crt = "";
1271
	$key = "";
1272
	$ca = "";
1273

    
1274
	/* non-standard port? */
1275
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1276
		$portarg = "{$config['system']['webgui']['port']}";
1277
	}
1278

    
1279
	if ($config['system']['webgui']['protocol'] == "https") {
1280
		// Ensure that we have a webConfigurator CERT
1281
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1282
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1283
			$cert = system_webgui_create_certificate();
1284
		}
1285
		$crt = base64_decode($cert['crt']);
1286
		$key = base64_decode($cert['prv']);
1287

    
1288
		if (!$config['system']['webgui']['port']) {
1289
			$portarg = "443";
1290
		}
1291
		$ca = ca_chain($cert);
1292
	}
1293

    
1294
	/* generate nginx configuration */
1295
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1296
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1297
		"cert.crt", "cert.key");
1298

    
1299
	/* kill any running nginx */
1300
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1301

    
1302
	sleep(1);
1303

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

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

    
1309
	if (platform_booting()) {
1310
		if ($res == 0) {
1311
			echo gettext("done.") . "\n";
1312
		} else {
1313
			echo gettext("failed!") . "\n";
1314
		}
1315
	}
1316

    
1317
	return $res;
1318
}
1319

    
1320
function system_generate_nginx_config($filename,
1321
	$cert,
1322
	$key,
1323
	$ca,
1324
	$pid_file,
1325
	$port = 80,
1326
	$document_root = "/usr/local/www/",
1327
	$cert_location = "cert.crt",
1328
	$key_location = "cert.key",
1329
	$captive_portal = false) {
1330

    
1331
	global $config, $g;
1332

    
1333
	if (isset($config['system']['developerspew'])) {
1334
		$mt = microtime();
1335
		echo "system_generate_nginx_config() being called $mt\n";
1336
	}
1337

    
1338
	if ($captive_portal !== false) {
1339
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1340
		$cp_hostcheck = "";
1341
		foreach ($cp_interfaces as $cpint) {
1342
			$cpint_ip = get_interface_ip($cpint);
1343
			if (is_ipaddr($cpint_ip)) {
1344
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1345
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1346
				$cp_hostcheck .= "\t\t}\n";
1347
			}
1348
		}
1349
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1350
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1351
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1352
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1353
			$cp_hostcheck .= "\t\t}\n";
1354
		}
1355
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1356
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1357
		$cp_rewrite .= "\t\t}\n";
1358

    
1359
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1360
		if (empty($maxprocperip)) {
1361
			$maxprocperip = 10;
1362
		}
1363
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1364
	}
1365

    
1366
	if (empty($port)) {
1367
		$nginx_port = "80";
1368
	} else {
1369
		$nginx_port = $port;
1370
	}
1371

    
1372
	$memory = get_memory();
1373
	$realmem = $memory[1];
1374

    
1375
	// Determine web GUI process settings and take into account low memory systems
1376
	if ($realmem < 255) {
1377
		$max_procs = 1;
1378
	} else {
1379
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1380
	}
1381

    
1382
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1383
	if ($captive_portal !== false) {
1384
		if ($realmem > 135 and $realmem < 256) {
1385
			$max_procs += 1; // 2 worker processes
1386
		} else if ($realmem > 255 and $realmem < 513) {
1387
			$max_procs += 2; // 3 worker processes
1388
		} else if ($realmem > 512) {
1389
			$max_procs += 4; // 6 worker processes
1390
		}
1391
	}
1392

    
1393
	$nginx_config = <<<EOD
1394
#
1395
# nginx configuration file
1396

    
1397
pid {$g['varrun_path']}/{$pid_file};
1398

    
1399
user  root wheel;
1400
worker_processes  {$max_procs};
1401

    
1402
EOD;
1403

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

    
1408
	$nginx_config .= <<<EOD
1409

    
1410
events {
1411
    worker_connections  1024;
1412
}
1413

    
1414
http {
1415
	include       /usr/local/etc/nginx/mime.types;
1416
	default_type  application/octet-stream;
1417
	add_header X-Frame-Options SAMEORIGIN;
1418
	server_tokens off;
1419

    
1420
	sendfile        on;
1421

    
1422
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1423

    
1424
EOD;
1425

    
1426
	if ($captive_portal !== false) {
1427
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1428
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1429
	} else {
1430
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1431
	}
1432

    
1433
	if ($cert <> "" and $key <> "") {
1434
		$nginx_config .= "\n";
1435
		$nginx_config .= "\tserver {\n";
1436
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1437
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1438
		$nginx_config .= "\n";
1439
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1440
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1441
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1442
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1443
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1444
		if ($captive_portal !== false) {
1445
			// leave TLSv1.0 for CP for now for compatibility
1446
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1447
		} else {
1448
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1449
		}
1450
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1451
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1452
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1453
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1454
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1455
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1456
	} else {
1457
		$nginx_config .= "\n";
1458
		$nginx_config .= "\tserver {\n";
1459
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1460
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1461
	}
1462

    
1463
	$nginx_config .= <<<EOD
1464

    
1465
		client_max_body_size 200m;
1466

    
1467
		gzip on;
1468
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1469

    
1470

    
1471
EOD;
1472

    
1473
	if ($captive_portal !== false) {
1474
		$nginx_config .= <<<EOD
1475
$captive_portal_maxprocperip
1476
$cp_hostcheck
1477
$cp_rewrite
1478
		log_not_found off;
1479

    
1480
EOD;
1481

    
1482
	}
1483

    
1484
	$nginx_config .= <<<EOD
1485
		root "{$document_root}";
1486
		location / {
1487
			index  index.php index.html index.htm;
1488
		}
1489

    
1490
		location ~ \.php$ {
1491
			try_files \$uri =404; #  This line closes a potential security hole
1492
			# ensuring users can't execute uploaded files
1493
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1494
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1495
			fastcgi_index  index.php;
1496
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1497
			# Fix httpoxy - https://httpoxy.org/#fix-now
1498
			fastcgi_param  HTTP_PROXY  "";
1499
			fastcgi_read_timeout 180;
1500
			include        /usr/local/etc/nginx/fastcgi_params;
1501
		}
1502
	}
1503

    
1504
EOD;
1505

    
1506
	$cert = str_replace("\r", "", $cert);
1507
	$key = str_replace("\r", "", $key);
1508

    
1509
	$cert = str_replace("\n\n", "\n", $cert);
1510
	$key = str_replace("\n\n", "\n", $key);
1511

    
1512
	if ($cert <> "" and $key <> "") {
1513
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1514
		if (!$fd) {
1515
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1516
			return 1;
1517
		}
1518
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1519
		if ($ca <> "") {
1520
			$cert_chain = $cert . "\n" . $ca;
1521
		} else {
1522
			$cert_chain = $cert;
1523
		}
1524
		fwrite($fd, $cert_chain);
1525
		fclose($fd);
1526
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1527
		if (!$fd) {
1528
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1529
			return 1;
1530
		}
1531
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1532
		fwrite($fd, $key);
1533
		fclose($fd);
1534
	}
1535

    
1536
	// Add HTTP to HTTPS redirect
1537
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1538
		if ($nginx_port != "443") {
1539
			$redirectport = ":{$nginx_port}";
1540
		}
1541
		$nginx_config .= <<<EOD
1542
	server {
1543
		listen 80;
1544
		listen [::]:80;
1545
		return 301 https://\$http_host$redirectport\$request_uri;
1546
	}
1547

    
1548
EOD;
1549
	}
1550

    
1551
	$nginx_config .= "}\n";
1552

    
1553
	$fd = fopen("{$filename}", "w");
1554
	if (!$fd) {
1555
		printf(gettext("Error: cannot open %s in system_generate_nginx_config().%s"), $filename, "\n");
1556
		return 1;
1557
	}
1558
	fwrite($fd, $nginx_config);
1559
	fclose($fd);
1560

    
1561
	/* nginx will fail to start if this directory does not exist. */
1562
	safe_mkdir("/var/tmp/nginx/");
1563

    
1564
	return 0;
1565

    
1566
}
1567

    
1568
function system_get_timezone_list() {
1569
	global $g;
1570

    
1571
	$file_list = array_merge(
1572
		glob("/usr/share/zoneinfo/[A-Z]*"),
1573
		glob("/usr/share/zoneinfo/*/*"),
1574
		glob("/usr/share/zoneinfo/*/*/*")
1575
	);
1576

    
1577
	if (empty($file_list)) {
1578
		$file_list[] = $g['default_timezone'];
1579
	} else {
1580
		/* Remove directories from list */
1581
		$file_list = array_filter($file_list, function($v) {
1582
			return !is_dir($v);
1583
		});
1584
	}
1585

    
1586
	/* Remove directory prefix */
1587
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1588

    
1589
	sort($file_list);
1590

    
1591
	return $file_list;
1592
}
1593

    
1594
function system_timezone_configure() {
1595
	global $config, $g;
1596
	if (isset($config['system']['developerspew'])) {
1597
		$mt = microtime();
1598
		echo "system_timezone_configure() being called $mt\n";
1599
	}
1600

    
1601
	$syscfg = $config['system'];
1602

    
1603
	if (platform_booting()) {
1604
		echo gettext("Setting timezone...");
1605
	}
1606

    
1607
	/* extract appropriate timezone file */
1608
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1609
	/* DO NOT remove \n otherwise tzsetup will fail */
1610
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1611
	mwexec("/usr/sbin/tzsetup -r");
1612

    
1613
	if (platform_booting()) {
1614
		echo gettext("done.") . "\n";
1615
	}
1616
}
1617

    
1618
function system_ntp_setup_gps($serialport) {
1619
	global $config, $g;
1620
	$gps_device = '/dev/gps0';
1621
	$serialport = '/dev/'.$serialport;
1622

    
1623
	if (!file_exists($serialport)) {
1624
		return false;
1625
	}
1626

    
1627
	// Create symlink that ntpd requires
1628
	unlink_if_exists($gps_device);
1629
	@symlink($serialport, $gps_device);
1630

    
1631
	$gpsbaud = '4800';
1632
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1633
		switch ($config['ntpd']['gps']['speed']) {
1634
			case '16':
1635
				$gpsbaud = '9600';
1636
				break;
1637
			case '32':
1638
				$gpsbaud = '19200';
1639
				break;
1640
			case '48':
1641
				$gpsbaud = '38400';
1642
				break;
1643
			case '64':
1644
				$gpsbaud = '57600';
1645
				break;
1646
			case '80':
1647
				$gpsbaud = '115200';
1648
				break;
1649
		}
1650
	}
1651

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

    
1655
	/* Send the following to the GPS port to initialize the GPS */
1656
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1657
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1658
	} else {
1659
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1660
	}
1661

    
1662
	/* XXX: Why not file_put_contents to the device */
1663
	@file_put_contents('/tmp/gps.init', $gps_init);
1664
	mwexec("cat /tmp/gps.init > {$serialport}");
1665

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

    
1671

    
1672
	return true;
1673
}
1674

    
1675
function system_ntp_setup_pps($serialport) {
1676
	global $config, $g;
1677

    
1678
	$pps_device = '/dev/pps0';
1679
	$serialport = '/dev/'.$serialport;
1680

    
1681
	if (!file_exists($serialport)) {
1682
		return false;
1683
	}
1684

    
1685
	// Create symlink that ntpd requires
1686
	unlink_if_exists($pps_device);
1687
	@symlink($serialport, $pps_device);
1688

    
1689

    
1690
	return true;
1691
}
1692

    
1693

    
1694
function system_ntp_configure() {
1695
	global $config, $g;
1696

    
1697
	$driftfile = "/var/db/ntpd.drift";
1698
	$statsdir = "/var/log/ntp";
1699
	$gps_device = '/dev/gps0';
1700

    
1701
	safe_mkdir($statsdir);
1702

    
1703
	if (!is_array($config['ntpd'])) {
1704
		$config['ntpd'] = array();
1705
	}
1706

    
1707
	$ntpcfg = "# \n";
1708
	$ntpcfg .= "# pfSense ntp configuration file \n";
1709
	$ntpcfg .= "# \n\n";
1710
	$ntpcfg .= "tinker panic 0 \n";
1711

    
1712
	/* Add Orphan mode */
1713
	$ntpcfg .= "# Orphan mode stratum\n";
1714
	$ntpcfg .= 'tos orphan ';
1715
	if (!empty($config['ntpd']['orphan'])) {
1716
		$ntpcfg .= $config['ntpd']['orphan'];
1717
	} else {
1718
		$ntpcfg .= '12';
1719
	}
1720
	$ntpcfg .= "\n";
1721

    
1722
	/* Add PPS configuration */
1723
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1724
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1725
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1726
		$ntpcfg .= "\n";
1727
		$ntpcfg .= "# PPS Setup\n";
1728
		$ntpcfg .= 'server 127.127.22.0';
1729
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1730
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1731
			$ntpcfg .= ' prefer';
1732
		}
1733
		if (!empty($config['ntpd']['pps']['noselect'])) {
1734
			$ntpcfg .= ' noselect ';
1735
		}
1736
		$ntpcfg .= "\n";
1737
		$ntpcfg .= 'fudge 127.127.22.0';
1738
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1739
			$ntpcfg .= ' time1 ';
1740
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1741
		}
1742
		if (!empty($config['ntpd']['pps']['flag2'])) {
1743
			$ntpcfg .= ' flag2 1';
1744
		}
1745
		if (!empty($config['ntpd']['pps']['flag3'])) {
1746
			$ntpcfg .= ' flag3 1';
1747
		} else {
1748
			$ntpcfg .= ' flag3 0';
1749
		}
1750
		if (!empty($config['ntpd']['pps']['flag4'])) {
1751
			$ntpcfg .= ' flag4 1';
1752
		}
1753
		if (!empty($config['ntpd']['pps']['refid'])) {
1754
			$ntpcfg .= ' refid ';
1755
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1756
		}
1757
		$ntpcfg .= "\n";
1758
	}
1759
	/* End PPS configuration */
1760

    
1761
	/* Add GPS configuration */
1762
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1763
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1764
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1765
		$ntpcfg .= "\n";
1766
		$ntpcfg .= "# GPS Setup\n";
1767
		$ntpcfg .= 'server 127.127.20.0 mode ';
1768
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1769
			if (!empty($config['ntpd']['gps']['nmea'])) {
1770
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1771
			}
1772
			if (!empty($config['ntpd']['gps']['speed'])) {
1773
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1774
			}
1775
			if (!empty($config['ntpd']['gps']['subsec'])) {
1776
				$ntpmode += 128;
1777
			}
1778
			$ntpcfg .= (string) $ntpmode;
1779
		} else {
1780
			$ntpcfg .= '0';
1781
		}
1782
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1783
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1784
			$ntpcfg .= ' prefer';
1785
		}
1786
		if (!empty($config['ntpd']['gps']['noselect'])) {
1787
			$ntpcfg .= ' noselect ';
1788
		}
1789
		$ntpcfg .= "\n";
1790
		$ntpcfg .= 'fudge 127.127.20.0';
1791
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1792
			$ntpcfg .= ' time1 ';
1793
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1794
		}
1795
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1796
			$ntpcfg .= ' time2 ';
1797
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1798
		}
1799
		if (!empty($config['ntpd']['gps']['flag1'])) {
1800
			$ntpcfg .= ' flag1 1';
1801
		} else {
1802
			$ntpcfg .= ' flag1 0';
1803
		}
1804
		if (!empty($config['ntpd']['gps']['flag2'])) {
1805
			$ntpcfg .= ' flag2 1';
1806
		}
1807
		if (!empty($config['ntpd']['gps']['flag3'])) {
1808
			$ntpcfg .= ' flag3 1';
1809
		} else {
1810
			$ntpcfg .= ' flag3 0';
1811
		}
1812
		if (!empty($config['ntpd']['gps']['flag4'])) {
1813
			$ntpcfg .= ' flag4 1';
1814
		}
1815
		if (!empty($config['ntpd']['gps']['refid'])) {
1816
			$ntpcfg .= ' refid ';
1817
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1818
		}
1819
		if (!empty($config['ntpd']['gps']['stratum'])) {
1820
			$ntpcfg .= ' stratum ';
1821
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1822
		}
1823
		$ntpcfg .= "\n";
1824
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1825
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1826
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1827
		/* This handles a 2.1 and earlier config */
1828
		$ntpcfg .= "# GPS Setup\n";
1829
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1830
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1831
		// Fall back to local clock if GPS is out of sync?
1832
		$ntpcfg .= "server 127.127.1.0\n";
1833
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1834
	}
1835
	/* End GPS configuration */
1836
	$auto_pool_suffix = "pool.ntp.org";
1837
	$have_pools = false;
1838
	$ntpcfg .= "\n\n# Upstream Servers\n";
1839
	/* foreach through ntp servers and write out to ntpd.conf */
1840
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1841
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1842
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1843
			$ntpcfg .= 'pool ';
1844
			$have_pools = true;
1845
		} else {
1846
			$ntpcfg .= 'server ';
1847
		}
1848

    
1849
		$ntpcfg .= "{$ts} iburst maxpoll 9";
1850
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1851
			$ntpcfg .= ' prefer';
1852
		}
1853
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1854
			$ntpcfg .= ' noselect';
1855
		}
1856
		$ntpcfg .= "\n";
1857
	}
1858
	unset($ts);
1859

    
1860
	$ntpcfg .= "\n\n";
1861
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1862
		$ntpcfg .= "enable stats\n";
1863
		$ntpcfg .= 'statistics';
1864
		if (!empty($config['ntpd']['clockstats'])) {
1865
			$ntpcfg .= ' clockstats';
1866
		}
1867
		if (!empty($config['ntpd']['loopstats'])) {
1868
			$ntpcfg .= ' loopstats';
1869
		}
1870
		if (!empty($config['ntpd']['peerstats'])) {
1871
			$ntpcfg .= ' peerstats';
1872
		}
1873
		$ntpcfg .= "\n";
1874
	}
1875
	$ntpcfg .= "statsdir {$statsdir}\n";
1876
	$ntpcfg .= 'logconfig =syncall +clockall';
1877
	if (!empty($config['ntpd']['logpeer'])) {
1878
		$ntpcfg .= ' +peerall';
1879
	}
1880
	if (!empty($config['ntpd']['logsys'])) {
1881
		$ntpcfg .= ' +sysall';
1882
	}
1883
	$ntpcfg .= "\n";
1884
	$ntpcfg .= "driftfile {$driftfile}\n";
1885

    
1886
	/* Default Access restrictions */
1887
	$ntpcfg .= 'restrict default';
1888
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1889
		$ntpcfg .= ' kod limited';
1890
	}
1891
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1892
		$ntpcfg .= ' nomodify';
1893
	}
1894
	if (!empty($config['ntpd']['noquery'])) {
1895
		$ntpcfg .= ' noquery';
1896
	}
1897
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1898
		$ntpcfg .= ' nopeer';
1899
	}
1900
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1901
		$ntpcfg .= ' notrap';
1902
	}
1903
	if (!empty($config['ntpd']['noserve'])) {
1904
		$ntpcfg .= ' noserve';
1905
	}
1906
	$ntpcfg .= "\nrestrict -6 default";
1907
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1908
		$ntpcfg .= ' kod limited';
1909
	}
1910
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1911
		$ntpcfg .= ' nomodify';
1912
	}
1913
	if (!empty($config['ntpd']['noquery'])) {
1914
		$ntpcfg .= ' noquery';
1915
	}
1916
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1917
		$ntpcfg .= ' nopeer';
1918
	}
1919
	if (!empty($config['ntpd']['noserve'])) {
1920
		$ntpcfg .= ' noserve';
1921
	}
1922
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1923
		$ntpcfg .= ' notrap';
1924
	}
1925

    
1926
	/* Pools require "restrict source" and cannot contain "nopeer". */
1927
	if ($have_pools) {
1928
		$ntpcfg .= "\nrestrict source";
1929
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1930
			$ntpcfg .= ' kod limited';
1931
		}
1932
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1933
			$ntpcfg .= ' nomodify';
1934
		}
1935
		if (!empty($config['ntpd']['noquery'])) {
1936
			$ntpcfg .= ' noquery';
1937
		}
1938
		if (!empty($config['ntpd']['noserve'])) {
1939
			$ntpcfg .= ' noserve';
1940
		}
1941
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1942
			$ntpcfg .= ' notrap';
1943
		}
1944
	}
1945

    
1946
	/* Custom Access Restrictions */
1947
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1948
		$networkacl = $config['ntpd']['restrictions']['row'];
1949
		foreach ($networkacl as $acl) {
1950
			$restrict = "";
1951
			if (is_ipaddrv6($acl['acl_network'])) {
1952
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1953
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1954
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
1955
			} else {
1956
				continue;
1957
			}
1958
			if (!empty($acl['kod'])) {
1959
				$restrict .= ' kod limited';
1960
			}
1961
			if (!empty($acl['nomodify'])) {
1962
				$restrict .= ' nomodify';
1963
			}
1964
			if (!empty($acl['noquery'])) {
1965
				$restrict .= ' noquery';
1966
			}
1967
			if (!empty($acl['nopeer'])) {
1968
				$restrict .= ' nopeer';
1969
			}
1970
			if (!empty($acl['noserve'])) {
1971
				$restrict .= ' noserve';
1972
			}
1973
			if (!empty($acl['notrap'])) {
1974
				$restrict .= ' notrap';
1975
			}
1976
			if (!empty($restrict)) {
1977
				$ntpcfg .= "\nrestrict {$restrict} ";
1978
			}
1979
		}
1980
	}
1981
	/* End Custom Access Restrictions */
1982

    
1983
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1984
	$ntpcfg .= "\n";
1985
	if (!empty($config['ntpd']['leapsec'])) {
1986
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1987
		file_put_contents('/var/db/leap-seconds', $leapsec);
1988
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1989
	}
1990

    
1991

    
1992
	if (empty($config['ntpd']['interface'])) {
1993
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
1994
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1995
		} else {
1996
			$interfaces = array();
1997
		}
1998
	} else {
1999
		$interfaces = explode(",", $config['ntpd']['interface']);
2000
	}
2001

    
2002
	if (is_array($interfaces) && count($interfaces)) {
2003
		$finterfaces = array();
2004
		$ntpcfg .= "interface ignore all\n";
2005
		foreach ($interfaces as $interface) {
2006
			$interface = get_real_interface($interface);
2007
			if (!empty($interface)) {
2008
				$finterfaces[] = $interface;
2009
			}
2010
		}
2011
		foreach ($finterfaces as $interface) {
2012
			$ntpcfg .= "interface listen {$interface}\n";
2013
		}
2014
	}
2015

    
2016
	/* open configuration for writing or bail */
2017
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2018
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2019
		return;
2020
	}
2021

    
2022
	/* if ntpd is running, kill it */
2023
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2024
		killbypid("{$g['varrun_path']}/ntpd.pid");
2025
	}
2026
	@unlink("{$g['varrun_path']}/ntpd.pid");
2027

    
2028
	/* if /var/empty does not exist, create it */
2029
	if (!is_dir("/var/empty")) {
2030
		mkdir("/var/empty", 0555, true);
2031
	}
2032

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

    
2036
	// Note that we are starting up
2037
	log_error("NTPD is starting up.");
2038
	return;
2039
}
2040

    
2041
function system_halt() {
2042
	global $g;
2043

    
2044
	system_reboot_cleanup();
2045

    
2046
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2047
}
2048

    
2049
function system_reboot() {
2050
	global $g;
2051

    
2052
	system_reboot_cleanup();
2053

    
2054
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2055
}
2056

    
2057
function system_reboot_sync($reroot=false) {
2058
	global $g;
2059

    
2060
	if ($reroot) {
2061
		$args = " -r ";
2062
	}
2063

    
2064
	system_reboot_cleanup();
2065

    
2066
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2067
}
2068

    
2069
function system_reboot_cleanup() {
2070
	global $config, $cpzone, $cpzoneid;
2071

    
2072
	mwexec("/usr/local/bin/beep.sh stop");
2073
	require_once("captiveportal.inc");
2074
	if (is_array($config['captiveportal'])) {
2075
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2076
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2077
			$cpzoneid = $cp[zoneid];
2078
			captiveportal_radius_stop_all(7); // Admin-Reboot
2079
			/* Send Accounting-Off packet to the RADIUS server */
2080
			captiveportal_send_server_accounting(true);
2081
		}
2082
	}
2083
	require_once("voucher.inc");
2084
	voucher_save_db_to_config();
2085
	require_once("pkg-utils.inc");
2086
	stop_packages();
2087
}
2088

    
2089
function system_do_shell_commands($early = 0) {
2090
	global $config, $g;
2091
	if (isset($config['system']['developerspew'])) {
2092
		$mt = microtime();
2093
		echo "system_do_shell_commands() being called $mt\n";
2094
	}
2095

    
2096
	if ($early) {
2097
		$cmdn = "earlyshellcmd";
2098
	} else {
2099
		$cmdn = "shellcmd";
2100
	}
2101

    
2102
	if (is_array($config['system'][$cmdn])) {
2103

    
2104
		/* *cmd is an array, loop through */
2105
		foreach ($config['system'][$cmdn] as $cmd) {
2106
			exec($cmd);
2107
		}
2108

    
2109
	} elseif ($config['system'][$cmdn] <> "") {
2110

    
2111
		/* execute single item */
2112
		exec($config['system'][$cmdn]);
2113

    
2114
	}
2115
}
2116

    
2117
function system_dmesg_save() {
2118
	global $g;
2119
	if (isset($config['system']['developerspew'])) {
2120
		$mt = microtime();
2121
		echo "system_dmesg_save() being called $mt\n";
2122
	}
2123

    
2124
	$dmesg = "";
2125
	$_gb = exec("/sbin/dmesg", $dmesg);
2126

    
2127
	/* find last copyright line (output from previous boots may be present) */
2128
	$lastcpline = 0;
2129

    
2130
	for ($i = 0; $i < count($dmesg); $i++) {
2131
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2132
			$lastcpline = $i;
2133
		}
2134
	}
2135

    
2136
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2137
	if (!$fd) {
2138
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2139
		return 1;
2140
	}
2141

    
2142
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2143
		fwrite($fd, $dmesg[$i] . "\n");
2144
	}
2145

    
2146
	fclose($fd);
2147
	unset($dmesg);
2148
	
2149
	// vm-bhyve expects dmesg.boot at the standard location
2150
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2151

    
2152
	return 0;
2153
}
2154

    
2155
function system_set_harddisk_standby() {
2156
	global $g, $config;
2157

    
2158
	if (isset($config['system']['developerspew'])) {
2159
		$mt = microtime();
2160
		echo "system_set_harddisk_standby() being called $mt\n";
2161
	}
2162

    
2163
	if (isset($config['system']['harddiskstandby'])) {
2164
		if (platform_booting()) {
2165
			echo gettext('Setting hard disk standby... ');
2166
		}
2167

    
2168
		$standby = $config['system']['harddiskstandby'];
2169
		// Check for a numeric value
2170
		if (is_numeric($standby)) {
2171
			// Get only suitable candidates for standby; using get_smart_drive_list()
2172
			// from utils.inc to get the list of drives.
2173
			$harddisks = get_smart_drive_list();
2174

    
2175
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2176
			// just in case of some weird pfSense platform installs.
2177
			if (count($harddisks) > 0) {
2178
				// Iterate disks and run the camcontrol command for each
2179
				foreach ($harddisks as $harddisk) {
2180
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2181
				}
2182
				if (platform_booting()) {
2183
					echo gettext("done.") . "\n";
2184
				}
2185
			} else if (platform_booting()) {
2186
				echo gettext("failed!") . "\n";
2187
			}
2188
		} else if (platform_booting()) {
2189
			echo gettext("failed!") . "\n";
2190
		}
2191
	}
2192
}
2193

    
2194
function system_setup_sysctl() {
2195
	global $config;
2196
	if (isset($config['system']['developerspew'])) {
2197
		$mt = microtime();
2198
		echo "system_setup_sysctl() being called $mt\n";
2199
	}
2200

    
2201
	activate_sysctls();
2202

    
2203
	if (isset($config['system']['sharednet'])) {
2204
		system_disable_arp_wrong_if();
2205
	}
2206
}
2207

    
2208
function system_disable_arp_wrong_if() {
2209
	global $config;
2210
	if (isset($config['system']['developerspew'])) {
2211
		$mt = microtime();
2212
		echo "system_disable_arp_wrong_if() being called $mt\n";
2213
	}
2214
	set_sysctl(array(
2215
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2216
		"net.link.ether.inet.log_arp_movements" => "0"
2217
	));
2218
}
2219

    
2220
function system_enable_arp_wrong_if() {
2221
	global $config;
2222
	if (isset($config['system']['developerspew'])) {
2223
		$mt = microtime();
2224
		echo "system_enable_arp_wrong_if() being called $mt\n";
2225
	}
2226
	set_sysctl(array(
2227
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2228
		"net.link.ether.inet.log_arp_movements" => "1"
2229
	));
2230
}
2231

    
2232
function enable_watchdog() {
2233
	global $config;
2234
	return;
2235
	$install_watchdog = false;
2236
	$supported_watchdogs = array("Geode");
2237
	$file = file_get_contents("/var/log/dmesg.boot");
2238
	foreach ($supported_watchdogs as $sd) {
2239
		if (stristr($file, "Geode")) {
2240
			$install_watchdog = true;
2241
		}
2242
	}
2243
	if ($install_watchdog == true) {
2244
		if (is_process_running("watchdogd")) {
2245
			mwexec("/usr/bin/killall watchdogd", true);
2246
		}
2247
		exec("/usr/sbin/watchdogd");
2248
	}
2249
}
2250

    
2251
function system_check_reset_button() {
2252
	global $g;
2253

    
2254
	$specplatform = system_identify_specific_platform();
2255

    
2256
	switch ($specplatform['name']) {
2257
		case 'alix':
2258
		case 'wrap':
2259
		case 'FW7541':
2260
		case 'APU':
2261
		case 'RCC-VE':
2262
		case 'RCC':
2263
		case 'RCC-DFF':
2264
			break;
2265
		default:
2266
			return 0;
2267
	}
2268

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

    
2271
	if ($retval == 99) {
2272
		/* user has pressed reset button for 2 seconds -
2273
		   reset to factory defaults */
2274
		echo <<<EOD
2275

    
2276
***********************************************************************
2277
* Reset button pressed - resetting configuration to factory defaults. *
2278
* All additional packages installed will be removed                   *
2279
* The system will reboot after this completes.                        *
2280
***********************************************************************
2281

    
2282

    
2283
EOD;
2284

    
2285
		reset_factory_defaults();
2286
		system_reboot_sync();
2287
		exit(0);
2288
	}
2289

    
2290
	return 0;
2291
}
2292

    
2293
function system_get_serial() {
2294
	unset($output);
2295
	$_gb = exec('/bin/kenv -q smbios.system.serial 2>/dev/null', $output);
2296
	$serial = $output[0];
2297

    
2298
	$vm_guest = get_single_sysctl('kern.vm_guest');
2299

    
2300
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2301
	    $vm_guest == 'none') {
2302
		return $serial;
2303
	}
2304

    
2305
	return get_single_sysctl('kern.hostuuid');
2306
}
2307

    
2308
/*
2309
 * attempt to identify the specific platform (for embedded systems)
2310
 * Returns an array with two elements:
2311
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2312
 * descr => human-readable description (e.g. "PC Engines WRAP")
2313
 */
2314
function system_identify_specific_platform() {
2315
	global $g;
2316

    
2317
	$hw_model = get_single_sysctl('hw.model');
2318

    
2319
	/* Try to guess from smbios strings */
2320
	unset($product);
2321
	unset($maker);
2322
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2323
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2324
	switch ($product[0]) {
2325
		case 'FW7541':
2326
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2327
			break;
2328
		case 'APU':
2329
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2330
			break;
2331
		case 'RCC-VE':
2332
			$result = array();
2333
			$result['name'] = 'RCC-VE';
2334

    
2335
			/* Detect specific models */
2336
			if (!function_exists('does_interface_exist')) {
2337
				require_once("interfaces.inc");
2338
			}
2339
			if (!does_interface_exist('igb4')) {
2340
				$result['model'] = 'SG-2440';
2341
			} elseif (strpos($hw_model, "C2558") !== false) {
2342
				$result['model'] = 'SG-4860';
2343
			} elseif (strpos($hw_model, "C2758") !== false) {
2344
				$result['model'] = 'SG-8860';
2345
			} else {
2346
				$result['model'] = 'RCC-VE';
2347
			}
2348
			$result['descr'] = 'Netgate ' . $result['model'];
2349
			return $result;
2350
			break;
2351
		case 'DFFv2':
2352
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2353
			break;
2354
		case 'RCC':
2355
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2356
			break;
2357
		case 'SYS-5018A-FTN4':
2358
		case 'A1SAi':
2359
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2360
			break;
2361
		case 'SYS-5018D-FN4T':
2362
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2363
			break;
2364
		case 'apu2':
2365
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2366
			break;
2367
		case 'Virtual Machine':
2368
			if ($maker[0] == "Microsoft Corporation") {
2369
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2370
			}
2371
			break;
2372
		case 'VMware Virtual Platform':
2373
			if ($maker[0] == "VMware, Inc.") {
2374
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2375
			}
2376
			break;
2377
	}
2378

    
2379
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2380
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2381
	}
2382

    
2383
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2384
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2385
	}
2386

    
2387
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2388
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2389
	}
2390

    
2391
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2392
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2393
	}
2394

    
2395
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2396
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2397
	}
2398

    
2399
	unset($hw_model);
2400

    
2401
	$dmesg_boot = system_get_dmesg_boot();
2402
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2403
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2404
	}
2405
	unset($dmesg_boot);
2406

    
2407
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2408
}
2409

    
2410
function system_get_dmesg_boot() {
2411
	global $g;
2412

    
2413
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2414
}
2415

    
2416
?>
(40-40/51)