Project

General

Profile

Download (72 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2018 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 -qnd {$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.' . $syscfg['domain'],
302
	    'name' => 'localhost',
303
	    'domain' => $syscfg['domain']
304
	);
305
	$hosts[] = array(
306
	    'ipaddr' => '::1',
307
	    'fqdn' => 'localhost.' . $syscfg['domain'],
308
	    'name' => 'localhost',
309
	    'domain' => $syscfg['domain']
310
	);
311

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

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

    
351
	return $hosts;
352
}
353

    
354
/* Read host override entries from dnsmasq or unbound */
355
function system_hosts_override_entries($dnscfg) {
356
	$hosts = array();
357

    
358
	if (!is_array($dnscfg) ||
359
	    !is_array($dnscfg['hosts']) ||
360
	    !isset($dnscfg['enable'])) {
361
		return $hosts;
362
	}
363

    
364
	foreach ($dnscfg['hosts'] as $host) {
365
		$fqdn = '';
366
		if ($host['host'] || $host['host'] == "0") {
367
			$fqdn .= "{$host['host']}.";
368
		}
369
		$fqdn .= $host['domain'];
370

    
371
		$hosts[] = array(
372
		    'ipaddr' => $host['ip'],
373
		    'fqdn' => $fqdn,
374
		    'name' => $host['host'],
375
		    'domain' => $host['domain']
376
		);
377

    
378
		if (!is_array($host['aliases']) ||
379
		    !is_array($host['aliases']['item'])) {
380
			continue;
381
		}
382

    
383
		foreach ($host['aliases']['item'] as $alias) {
384
			$fqdn = '';
385
			if ($alias['host'] || $alias['host'] == "0") {
386
				$fqdn .= "{$alias['host']}.";
387
			}
388
			$fqdn .= $alias['domain'];
389

    
390
			$hosts[] = array(
391
			    'ipaddr' => $host['ip'],
392
			    'fqdn' => $fqdn,
393
			    'name' => $alias['host'],
394
			    'domain' => $alias['domain']
395
			);
396
		}
397
	}
398

    
399
	return $hosts;
400
}
401

    
402
/* Read all dhcpd/dhcpdv6 staticmap entries */
403
function system_hosts_dhcpd_entries() {
404
	global $config;
405

    
406
	$hosts = array();
407
	$syscfg = $config['system'];
408

    
409
	if (is_array($config['dhcpd'])) {
410
		$conf_dhcpd = $config['dhcpd'];
411
	} else {
412
		$conf_dhcpd = array();
413
	}
414

    
415
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
416
		if (!is_array($dhcpifconf['staticmap']) ||
417
		    !isset($dhcpifconf['enable'])) {
418
			continue;
419
		}
420
		foreach ($dhcpifconf['staticmap'] as $host) {
421
			if (!$host['ipaddr'] ||
422
			    !$host['hostname']) {
423
				continue;
424
			}
425

    
426
			$fqdn = $host['hostname'] . ".";
427
			$domain = "";
428
			if ($host['domain']) {
429
				$domain = $host['domain'];
430
			} elseif ($dhcpifconf['domain']) {
431
				$domain = $dhcpifconf['domain'];
432
			} else {
433
				$domain = $syscfg['domain'];
434
			}
435

    
436
			$hosts[] = array(
437
			    'ipaddr' => $host['ipaddr'],
438
			    'fqdn' => $fqdn . $domain,
439
			    'name' => $host['hostname'],
440
			    'domain' => $domain
441
			);
442
		}
443
	}
444
	unset($conf_dhcpd);
445

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

    
452
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
453
		if (!is_array($dhcpifconf['staticmap']) ||
454
		    !isset($dhcpifconf['enable'])) {
455
			continue;
456
		}
457

    
458
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
459
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
460
		    'track6') {
461
			$isdelegated = true;
462
		} else {
463
			$isdelegated = false;
464
		}
465

    
466
		foreach ($dhcpifconf['staticmap'] as $host) {
467
			$ipaddrv6 = $host['ipaddrv6'];
468

    
469
			if (!$ipaddrv6 || !$host['hostname']) {
470
				continue;
471
			}
472

    
473
			if ($isdelegated) {
474
				/*
475
				 * We are always in an "end-user" subnet
476
				 * here, which all are /64 for IPv6.
477
				 */
478
				$ipaddrv6 = merge_ipv6_delegated_prefix(
479
				    get_interface_ipv6($dhcpif),
480
				    $ipaddrv6, 64);
481
			}
482

    
483
			$fqdn = $host['hostname'] . ".";
484
			$domain = "";
485
			if ($host['domain']) {
486
				$domain = $host['domain'];
487
			} elseif ($dhcpifconf['domain']) {
488
				$domain = $dhcpifconf['domain'];
489
			} else {
490
				$domain = $syscfg['domain'];
491
			}
492

    
493
			$hosts[] = array(
494
			    'ipaddr' => $ipaddrv6,
495
			    'fqdn' => $fqdn . $domain,
496
			    'name' => $host['hostname'],
497
			    'domain' => $domain
498
			);
499
		}
500
	}
501
	unset($conf_dhcpdv6);
502

    
503
	return $hosts;
504
}
505

    
506
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
507
function system_hosts_entries($dnscfg) {
508
	$local = array();
509
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
510
		$local = system_hosts_local_entries();
511
	}
512

    
513
	$dns = array();
514
	$dhcpd = array();
515
	if (isset($dnscfg['enable'])) {
516
		$dns = system_hosts_override_entries($dnscfg);
517
		if (isset($dnscfg['regdhcpstatic'])) {
518
			$dhcpd = system_hosts_dhcpd_entries();
519
		}
520
	}
521

    
522
	if (isset($dnscfg['dhcpfirst'])) {
523
		return array_merge($local, $dns, $dhcpd);
524
	} else {
525
		return array_merge($local, $dhcpd, $dns);
526
	}
527
}
528

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

    
536
	// prefer dnsmasq for hosts generation where it's enabled. It relies
537
	// on hosts for name resolution of its overrides, unbound does not.
538
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
539
		$dnsmasqcfg = $config['dnsmasq'];
540
	} else {
541
		$dnsmasqcfg = $config['unbound'];
542
	}
543

    
544
	$syscfg = $config['system'];
545
	$hosts = "";
546
	$lhosts = "";
547
	$dhosts = "";
548

    
549
	$hosts_array = system_hosts_entries($dnsmasqcfg);
550
	foreach ($hosts_array as $host) {
551
		$hosts .= "{$host['ipaddr']}\t";
552
		if ($host['name'] == "localhost") {
553
			$hosts .= "{$host['name']} {$host['fqdn']}";
554
		} else {
555
			$hosts .= "{$host['fqdn']} {$host['name']}";
556
		}
557
		$hosts .= "\n";
558
	}
559
	unset($hosts_array);
560

    
561
	$fd = fopen("{$g['etc_path']}/hosts", "w");
562
	if (!$fd) {
563
		log_error(gettext(
564
		    "Error: cannot open hosts file in system_hosts_generate()."
565
		    ));
566
		return 1;
567
	}
568

    
569
	/*
570
	 * Do not remove this because dhcpleases monitors with kqueue it needs
571
	 * to be killed before writing to hosts files.
572
	 */
573
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
574
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
575
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
576
	}
577

    
578
	fwrite($fd, $hosts);
579
	fclose($fd);
580

    
581
	if (isset($config['unbound']['enable'])) {
582
		require_once("unbound.inc");
583
		unbound_hosts_generate();
584
	}
585

    
586
	/* restart dhcpleases */
587
	if (!platform_booting()) {
588
		system_dhcpleases_configure();
589
	}
590

    
591
	return 0;
592
}
593

    
594
function system_dhcpleases_configure() {
595
	global $config, $g;
596
	if (!function_exists('is_dhcp_server_enabled')) {
597
		require_once('pfsense-utils.inc');
598
	}
599
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
600

    
601
	/* Start the monitoring process for dynamic dhcpclients. */
602
	if (((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
603
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) &&
604
	    (is_dhcp_server_enabled())) {
605
		/* Make sure we do not error out */
606
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
607
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
608
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
609
		}
610

    
611
		if (isset($config['unbound']['enable'])) {
612
			$dns_pid = "unbound.pid";
613
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
614
		} else {
615
			$dns_pid = "dnsmasq.pid";
616
			$unbound_conf = "";
617
		}
618

    
619
		if (isvalidpid($pidfile)) {
620
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
621
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
622
			if (intval($retval) == 0) {
623
				sigkillbypid($pidfile, "HUP");
624
				return;
625
			} else {
626
				sigkillbypid($pidfile, "TERM");
627
			}
628
		}
629

    
630
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
631
		if (is_process_running("dhcpleases")) {
632
			sigkillbyname('dhcpleases', "TERM");
633
		}
634
		@unlink($pidfile);
635
		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");
636
	} elseif (isvalidpid($pidfile)) {
637
		sigkillbypid($pidfile, "TERM");
638
		@unlink($pidfile);
639
	}
640
}
641

    
642
function system_hostname_configure() {
643
	global $config, $g;
644
	if (isset($config['system']['developerspew'])) {
645
		$mt = microtime();
646
		echo "system_hostname_configure() being called $mt\n";
647
	}
648

    
649
	$syscfg = $config['system'];
650

    
651
	/* set hostname */
652
	$status = mwexec("/bin/hostname " .
653
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
654

    
655
	/* Setup host GUID ID.  This is used by ZFS. */
656
	mwexec("/etc/rc.d/hostid start");
657

    
658
	return $status;
659
}
660

    
661
function system_routing_configure($interface = "") {
662
	global $config, $g;
663

    
664
	if (isset($config['system']['developerspew'])) {
665
		$mt = microtime();
666
		echo "system_routing_configure() being called $mt\n";
667
	}
668

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

    
740
	$gateways_arr = return_gateways_array(false, true);
741
	foreach ($gateways_arr as $gateway) {
742
		// setup static interface routes for nonlocal gateways
743
		if (isset($gateway["nonlocalgateway"])) {
744
			$srgatewayip = $gateway['gateway'];
745
			$srinterfacegw = $gateway['interface'];
746
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
747
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
748
				route_add_or_change("{$inet} {$srgatewayip} " .
749
				    "-iface {$srinterfacegw}");
750
			}
751
		}
752
	}
753

    
754
	if ($dont_add_route == false) {
755
		if (!empty($interface) && $interface != $interfacegw) {
756
			;
757
		} else if (is_ipaddrv4($gatewayip)) {
758
			log_error(sprintf(gettext("ROUTING: setting default route to %s"), $gatewayip));
759
			route_add_or_change("-inet default {$gatewayip}");
760
		}
761

    
762
		if (!empty($interface) && $interface != $interfacegwv6) {
763
			;
764
		} else if (is_ipaddrv6($gatewayipv6)) {
765
			$ifscope = "";
766
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
767
				$ifscope = "%{$defaultifv6}";
768
			}
769
			log_error(sprintf(gettext("ROUTING: setting IPv6 default route to %s"), $gatewayipv6 . $ifscope));
770
			route_add_or_change("-inet6 default {$gatewayipv6}{$ifscope}");
771
		}
772
	}
773

    
774
	system_staticroutes_configure($interface, false);
775

    
776
	return 0;
777
}
778

    
779
function system_staticroutes_configure($interface = "", $update_dns = false) {
780
	global $config, $g, $aliastable;
781

    
782
	$filterdns_list = array();
783

    
784
	$static_routes = get_staticroutes(false, true);
785
	if (count($static_routes)) {
786
		$gateways_arr = return_gateways_array(false, true);
787

    
788
		foreach ($static_routes as $rtent) {
789
			if (empty($gateways_arr[$rtent['gateway']])) {
790
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
791
				continue;
792
			}
793
			$gateway = $gateways_arr[$rtent['gateway']];
794
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
795
				continue;
796
			}
797

    
798
			$gatewayip = $gateway['gateway'];
799
			$interfacegw = $gateway['interface'];
800

    
801
			$blackhole = "";
802
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
803
				$blackhole = "-blackhole";
804
			}
805

    
806
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
807
				continue;
808
			}
809

    
810
			$dnscache = array();
811
			if ($update_dns === true) {
812
				if (is_subnet($rtent['network'])) {
813
					continue;
814
				}
815
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
816
				if (empty($dnscache)) {
817
					continue;
818
				}
819
			}
820

    
821
			if (is_subnet($rtent['network'])) {
822
				$ips = array($rtent['network']);
823
			} else {
824
				if (!isset($rtent['disabled'])) {
825
					$filterdns_list[] = $rtent['network'];
826
				}
827
				$ips = add_hostname_to_watch($rtent['network']);
828
			}
829

    
830
			foreach ($dnscache as $ip) {
831
				if (in_array($ip, $ips)) {
832
					continue;
833
				}
834
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
835
				if (isset($config['system']['route-debug'])) {
836
					$mt = microtime();
837
					log_error("ROUTING debug: $mt - route delete $ip ");
838
				}
839
			}
840

    
841
			if (isset($rtent['disabled'])) {
842
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
843
				foreach ($ips as $ip) {
844
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
845
					if (isset($config['system']['route-debug'])) {
846
						$mt = microtime();
847
						log_error("ROUTING debug: $mt - route delete $ip ");
848
					}
849
				}
850
				continue;
851
			}
852

    
853
			foreach ($ips as $ip) {
854
				if (is_ipaddrv4($ip)) {
855
					$ip .= "/32";
856
				}
857
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
858

    
859
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
860

    
861
				$cmd = "{$inet} {$blackhole} {$ip} ";
862

    
863
				if (is_subnet($ip)) {
864
					if (is_ipaddr($gatewayip)) {
865
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
866
							// add interface scope for link local v6 routes
867
							$gatewayip .= "%$interfacegw";
868
						}
869
						route_add_or_change($cmd . $gatewayip);
870
					} else if (!empty($interfacegw)) {
871
						route_add_or_change($cmd . "-iface {$interfacegw}");
872
					}
873
				}
874
			}
875
		}
876
		unset($gateways_arr);
877
	}
878
	unset($static_routes);
879

    
880
	if ($update_dns === false) {
881
		if (count($filterdns_list)) {
882
			$interval = 60;
883
			$hostnames = "";
884
			array_unique($filterdns_list);
885
			foreach ($filterdns_list as $hostname) {
886
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
887
			}
888
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
889
			unset($hostnames);
890

    
891
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
892
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
893
			} else {
894
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
895
			}
896
		} else {
897
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
898
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
899
		}
900
	}
901
	unset($filterdns_list);
902

    
903
	return 0;
904
}
905

    
906
function system_routing_enable() {
907
	global $config, $g;
908
	if (isset($config['system']['developerspew'])) {
909
		$mt = microtime();
910
		echo "system_routing_enable() being called $mt\n";
911
	}
912

    
913
	set_sysctl(array(
914
		"net.inet.ip.forwarding" => "1",
915
		"net.inet6.ip6.forwarding" => "1"
916
	));
917

    
918
	return;
919
}
920

    
921
function system_syslogd_fixup_server($server) {
922
	/* If it's an IPv6 IP alone, encase it in brackets */
923
	if (is_ipaddrv6($server)) {
924
		return "[$server]";
925
	} else {
926
		return $server;
927
	}
928
}
929

    
930
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
931
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
932
	$facility .= " ".
933
	$remote_servers = "";
934
	$pad_to  = max(strlen($facility), 56);
935
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
936
	if (isset($syslogcfg['enable'])) {
937
		if ($syslogcfg['remoteserver']) {
938
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
939
		}
940
		if ($syslogcfg['remoteserver2']) {
941
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
942
		}
943
		if ($syslogcfg['remoteserver3']) {
944
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
945
		}
946
	}
947
	return $remote_servers;
948
}
949

    
950
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
951
	global $config, $g;
952

    
953
	if ($restart_syslogd) {
954
		/* syslogd does not react well to clog rewriting the file while it is running. */
955
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
956
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
957
		}
958
	}
959
	if (isset($config['system']['disablesyslogclog'])) {
960
		unlink($logfile);
961
		touch($logfile);
962
	} else {
963
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
964
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
965
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
966
	}
967
	if ($restart_syslogd) {
968
		system_syslogd_start();
969
	}
970
	// Bug #6915
971
	if ($logfile == "/var/log/resolver.log") {
972
		services_unbound_configure(true);
973
	}
974
}
975

    
976
function clear_all_log_files($restart = false) {
977
	global $g;
978
	if ($restart) {
979
		/* syslogd does not react well to clog rewriting the file while it is running. */
980
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
981
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
982
		}
983
	}
984

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

    
990
	if ($restart) {
991
		system_syslogd_start();
992
		killbyname("dhcpd");
993
		if (!function_exists('services_dhcpd_configure')) {
994
			require_once('services.inc');
995
		}
996
		services_dhcpd_configure();
997
		// Bug #6915
998
		services_unbound_configure(false);
999
	}
1000
	return;
1001
}
1002

    
1003
function system_syslogd_start($sighup = false) {
1004
	global $config, $g;
1005
	if (isset($config['system']['developerspew'])) {
1006
		$mt = microtime();
1007
		echo "system_syslogd_start() being called $mt\n";
1008
	}
1009

    
1010
	mwexec("/etc/rc.d/hostid start");
1011

    
1012
	$syslogcfg = $config['syslog'];
1013

    
1014
	if (platform_booting()) {
1015
		echo gettext("Starting syslog...");
1016
	}
1017

    
1018
	// Which logging type are we using this week??
1019
	if (isset($config['system']['disablesyslogclog'])) {
1020
		$log_directive = "";
1021
		$log_create_directive = "/usr/bin/touch ";
1022
		$log_size = "";
1023
	} else { // Defaults to CLOG
1024
		$log_directive = "%";
1025
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
1026
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
1027
	}
1028

    
1029
	$syslogd_extra = "";
1030
	if (isset($syslogcfg)) {
1031
		$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', 'ospf6d', 'bgpd', 'miniupnpd', 'filterlog');
1032
		$syslogconf = "";
1033
		if ($config['installedpackages']['package']) {
1034
			foreach ($config['installedpackages']['package'] as $package) {
1035
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1036
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1037
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1038
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1039
					}
1040
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1041
				}
1042
			}
1043
		}
1044
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1045
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,ospf6d,bgpd,miniupnpd\n";
1046
		if (!isset($syslogcfg['disablelocallogging'])) {
1047
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1048
		}
1049
		if (isset($syslogcfg['routing'])) {
1050
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1051
		}
1052

    
1053
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
1054
		if (!isset($syslogcfg['disablelocallogging'])) {
1055
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
1056
		}
1057
		if (isset($syslogcfg['ntpd'])) {
1058
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1059
		}
1060

    
1061
		$syslogconf .= "!ppp\n";
1062
		if (!isset($syslogcfg['disablelocallogging'])) {
1063
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
1064
		}
1065
		if (isset($syslogcfg['ppp'])) {
1066
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1067
		}
1068

    
1069
		$syslogconf .= "!poes\n";
1070
		if (!isset($syslogcfg['disablelocallogging'])) {
1071
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
1072
		}
1073
		if (isset($syslogcfg['vpn'])) {
1074
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1075
		}
1076

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

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

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

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

    
1109
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1110
		if (!isset($syslogcfg['disablelocallogging'])) {
1111
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1112
		}
1113
		if (isset($syslogcfg['resolver'])) {
1114
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1115
		}
1116

    
1117
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
1118
		if (!isset($syslogcfg['disablelocallogging'])) {
1119
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
1120
		}
1121
		if (isset($syslogcfg['dhcp'])) {
1122
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1123
		}
1124

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

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

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

    
1149
		$syslogconf .= "!-{$facilitylist}\n";
1150
		if (!isset($syslogcfg['disablelocallogging'])) {
1151
			$syslogconf .= <<<EOD
1152
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1153
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1154
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1155
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1156
*.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
1157
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1158
*.emerg								*
1159

    
1160
EOD;
1161
		}
1162
		if (isset($syslogcfg['vpn'])) {
1163
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1164
		}
1165
		if (isset($syslogcfg['portalauth'])) {
1166
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1167
		}
1168
		if (isset($syslogcfg['dhcp'])) {
1169
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1170
		}
1171
		if (isset($syslogcfg['system'])) {
1172
			$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");
1173
		}
1174
		if (isset($syslogcfg['logall'])) {
1175
			// Make everything mean everything, including facilities excluded above.
1176
			$syslogconf .= "!*\n";
1177
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1178
		}
1179

    
1180
		if (isset($syslogcfg['zmqserver'])) {
1181
				$syslogconf .= <<<EOD
1182
*.*								^{$syslogcfg['zmqserver']}
1183

    
1184
EOD;
1185
		}
1186
		/* write syslog.conf */
1187
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1188
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1189
			unset($syslogconf);
1190
			return 1;
1191
		}
1192
		unset($syslogconf);
1193

    
1194
		$sourceip = "";
1195
		if (!empty($syslogcfg['sourceip'])) {
1196
			if ($syslogcfg['ipproto'] == "ipv6") {
1197
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1198
				if (!is_ipaddr($ifaddr)) {
1199
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1200
				}
1201
			} else {
1202
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1203
				if (!is_ipaddr($ifaddr)) {
1204
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1205
				}
1206
			}
1207
			if (is_ipaddr($ifaddr)) {
1208
				$sourceip = "-b {$ifaddr}";
1209
			}
1210
		}
1211

    
1212
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1213
	}
1214

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

    
1217
	if (isset($config['installedpackages']['package'])) {
1218
		foreach ($config['installedpackages']['package'] as $package) {
1219
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1220
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1221
				$log_sockets[] = $package['logging']['logsocket'];
1222
			}
1223
		}
1224
	}
1225

    
1226
	$syslogd_sockets = "";
1227
	foreach ($log_sockets as $log_socket) {
1228
		// Ensure that the log directory exists
1229
		$logpath = dirname($log_socket);
1230
		safe_mkdir($logpath);
1231
		$syslogd_sockets .= " -l {$log_socket}";
1232
	}
1233

    
1234
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1235
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1236
		$sighup = false;
1237
	}
1238

    
1239
	if (!$sighup) {
1240
		sigkillbyname("sshlockout_pf", "TERM");
1241
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1242
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1243
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1244
		}
1245

    
1246
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1247
			// if it still hasn't responded to the TERM, KILL it.
1248
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1249
			usleep(100000);
1250
		}
1251

    
1252
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1253
	} else {
1254
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1255
	}
1256

    
1257
	if (platform_booting()) {
1258
		echo gettext("done.") . "\n";
1259
	}
1260

    
1261
	return $retval;
1262
}
1263

    
1264
function system_webgui_create_certificate() {
1265
	global $config, $g;
1266

    
1267
	if (!is_array($config['ca'])) {
1268
		$config['ca'] = array();
1269
	}
1270
	$a_ca =& $config['ca'];
1271
	if (!is_array($config['cert'])) {
1272
		$config['cert'] = array();
1273
	}
1274
	$a_cert =& $config['cert'];
1275
	log_error(gettext("Creating SSL Certificate for this host"));
1276

    
1277
	$cert = array();
1278
	$cert['refid'] = uniqid();
1279
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1280
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1281

    
1282
	$dn = array(
1283
		'countryName' => "US",
1284
		'stateOrProvinceName' => "State",
1285
		'localityName' => "Locality",
1286
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1287
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1288
		'commonName' => $cert_hostname,
1289
		'subjectAltName' => "DNS:{$cert_hostname}");
1290
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1291
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1292
		while ($ssl_err = openssl_error_string()) {
1293
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1294
		}
1295
		error_reporting($old_err_level);
1296
		return null;
1297
	}
1298
	error_reporting($old_err_level);
1299

    
1300
	$a_cert[] = $cert;
1301
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1302
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1303
	return $cert;
1304
}
1305

    
1306
function system_webgui_start() {
1307
	global $config, $g;
1308

    
1309
	if (platform_booting()) {
1310
		echo gettext("Starting webConfigurator...");
1311
	}
1312

    
1313
	chdir($g['www_path']);
1314

    
1315
	/* defaults */
1316
	$portarg = "80";
1317
	$crt = "";
1318
	$key = "";
1319
	$ca = "";
1320

    
1321
	/* non-standard port? */
1322
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1323
		$portarg = "{$config['system']['webgui']['port']}";
1324
	}
1325

    
1326
	if ($config['system']['webgui']['protocol'] == "https") {
1327
		// Ensure that we have a webConfigurator CERT
1328
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1329
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1330
			$cert = system_webgui_create_certificate();
1331
		}
1332
		$crt = base64_decode($cert['crt']);
1333
		$key = base64_decode($cert['prv']);
1334

    
1335
		if (!$config['system']['webgui']['port']) {
1336
			$portarg = "443";
1337
		}
1338
		$ca = ca_chain($cert);
1339
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1340
	}
1341

    
1342
	/* generate nginx configuration */
1343
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1344
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1345
		"cert.crt", "cert.key", false, $hsts);
1346

    
1347
	/* kill any running nginx */
1348
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1349

    
1350
	sleep(1);
1351

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

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

    
1357
	if (platform_booting()) {
1358
		if ($res == 0) {
1359
			echo gettext("done.") . "\n";
1360
		} else {
1361
			echo gettext("failed!") . "\n";
1362
		}
1363
	}
1364

    
1365
	return $res;
1366
}
1367

    
1368
function system_generate_nginx_config($filename,
1369
	$cert,
1370
	$key,
1371
	$ca,
1372
	$pid_file,
1373
	$port = 80,
1374
	$document_root = "/usr/local/www/",
1375
	$cert_location = "cert.crt",
1376
	$key_location = "cert.key",
1377
	$captive_portal = false,
1378
	$hsts = true) {
1379

    
1380
	global $config, $g;
1381

    
1382
	if (isset($config['system']['developerspew'])) {
1383
		$mt = microtime();
1384
		echo "system_generate_nginx_config() being called $mt\n";
1385
	}
1386

    
1387
	if ($captive_portal !== false) {
1388
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1389
		$cp_hostcheck = "";
1390
		foreach ($cp_interfaces as $cpint) {
1391
			$cpint_ip = get_interface_ip($cpint);
1392
			if (is_ipaddr($cpint_ip)) {
1393
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1394
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1395
				$cp_hostcheck .= "\t\t}\n";
1396
			}
1397
		}
1398
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1399
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1400
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1401
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1402
			$cp_hostcheck .= "\t\t}\n";
1403
		}
1404
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1405
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1406
		$cp_rewrite .= "\t\t}\n";
1407

    
1408
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1409
		if (empty($maxprocperip)) {
1410
			$maxprocperip = 10;
1411
		}
1412
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1413
	}
1414

    
1415
	if (empty($port)) {
1416
		$nginx_port = "80";
1417
	} else {
1418
		$nginx_port = $port;
1419
	}
1420

    
1421
	$memory = get_memory();
1422
	$realmem = $memory[1];
1423

    
1424
	// Determine web GUI process settings and take into account low memory systems
1425
	if ($realmem < 255) {
1426
		$max_procs = 1;
1427
	} else {
1428
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1429
	}
1430

    
1431
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1432
	if ($captive_portal !== false) {
1433
		if ($realmem > 135 and $realmem < 256) {
1434
			$max_procs += 1; // 2 worker processes
1435
		} else if ($realmem > 255 and $realmem < 513) {
1436
			$max_procs += 2; // 3 worker processes
1437
		} else if ($realmem > 512) {
1438
			$max_procs += 4; // 6 worker processes
1439
		}
1440
	}
1441

    
1442
	$nginx_config = <<<EOD
1443
#
1444
# nginx configuration file
1445

    
1446
pid {$g['varrun_path']}/{$pid_file};
1447

    
1448
user  root wheel;
1449
worker_processes  {$max_procs};
1450

    
1451
EOD;
1452

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

    
1457
	$nginx_config .= <<<EOD
1458

    
1459
events {
1460
    worker_connections  1024;
1461
}
1462

    
1463
http {
1464
	include       /usr/local/etc/nginx/mime.types;
1465
	default_type  application/octet-stream;
1466
	add_header X-Frame-Options SAMEORIGIN;
1467
	server_tokens off;
1468

    
1469
	sendfile        on;
1470

    
1471
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1472

    
1473
EOD;
1474

    
1475
	if ($captive_portal !== false) {
1476
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1477
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1478
	} else {
1479
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1480
	}
1481

    
1482
	if ($cert <> "" and $key <> "") {
1483
		$nginx_config .= "\n";
1484
		$nginx_config .= "\tserver {\n";
1485
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1486
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1487
		$nginx_config .= "\n";
1488
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1489
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1490
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1491
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1492
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1493
		if ($captive_portal !== false) {
1494
			// leave TLSv1.0 for CP for now for compatibility
1495
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1496
		} else {
1497
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1498
		}
1499
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1500
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1501
		if ($captive_portal === false && $hsts !== false) {
1502
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1503
		}
1504
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1505
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1506
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1507
	} else {
1508
		$nginx_config .= "\n";
1509
		$nginx_config .= "\tserver {\n";
1510
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1511
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1512
	}
1513

    
1514
	$nginx_config .= <<<EOD
1515

    
1516
		client_max_body_size 200m;
1517

    
1518
		gzip on;
1519
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1520

    
1521

    
1522
EOD;
1523

    
1524
	if ($captive_portal !== false) {
1525
		$nginx_config .= <<<EOD
1526
$captive_portal_maxprocperip
1527
$cp_hostcheck
1528
$cp_rewrite
1529
		log_not_found off;
1530

    
1531
EOD;
1532

    
1533
	}
1534

    
1535
	$nginx_config .= <<<EOD
1536
		root "{$document_root}";
1537
		location / {
1538
			index  index.php index.html index.htm;
1539
		}
1540
		location ~ \.inc$ {
1541
			deny all;
1542
			return 403;
1543
		}
1544
		location ~ \.php$ {
1545
			try_files \$uri =404; #  This line closes a potential security hole
1546
			# ensuring users can't execute uploaded files
1547
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1548
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1549
			fastcgi_index  index.php;
1550
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1551
			# Fix httpoxy - https://httpoxy.org/#fix-now
1552
			fastcgi_param  HTTP_PROXY  "";
1553
			fastcgi_read_timeout 180;
1554
			include        /usr/local/etc/nginx/fastcgi_params;
1555
		}
1556
		location ~ (^/status$) {
1557
			allow 127.0.0.1;
1558
			deny all;
1559
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1560
			fastcgi_index  index.php;
1561
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1562
			# Fix httpoxy - https://httpoxy.org/#fix-now
1563
			fastcgi_param  HTTP_PROXY  "";
1564
			fastcgi_read_timeout 360;
1565
			include        /usr/local/etc/nginx/fastcgi_params;
1566
		}
1567
	}
1568

    
1569
EOD;
1570

    
1571
	$cert = str_replace("\r", "", $cert);
1572
	$key = str_replace("\r", "", $key);
1573

    
1574
	$cert = str_replace("\n\n", "\n", $cert);
1575
	$key = str_replace("\n\n", "\n", $key);
1576

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

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

    
1613
EOD;
1614
	}
1615

    
1616
	$nginx_config .= "}\n";
1617

    
1618
	$fd = fopen("{$filename}", "w");
1619
	if (!$fd) {
1620
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1621
		return 1;
1622
	}
1623
	fwrite($fd, $nginx_config);
1624
	fclose($fd);
1625

    
1626
	/* nginx will fail to start if this directory does not exist. */
1627
	safe_mkdir("/var/tmp/nginx/");
1628

    
1629
	return 0;
1630

    
1631
}
1632

    
1633
function system_get_timezone_list() {
1634
	global $g;
1635

    
1636
	$file_list = array_merge(
1637
		glob("/usr/share/zoneinfo/[A-Z]*"),
1638
		glob("/usr/share/zoneinfo/*/*"),
1639
		glob("/usr/share/zoneinfo/*/*/*")
1640
	);
1641

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

    
1651
	/* Remove directory prefix */
1652
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1653

    
1654
	sort($file_list);
1655

    
1656
	return $file_list;
1657
}
1658

    
1659
function system_timezone_configure() {
1660
	global $config, $g;
1661
	if (isset($config['system']['developerspew'])) {
1662
		$mt = microtime();
1663
		echo "system_timezone_configure() being called $mt\n";
1664
	}
1665

    
1666
	$syscfg = $config['system'];
1667

    
1668
	if (platform_booting()) {
1669
		echo gettext("Setting timezone...");
1670
	}
1671

    
1672
	/* extract appropriate timezone file */
1673
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1674
	/* DO NOT remove \n otherwise tzsetup will fail */
1675
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1676
	mwexec("/usr/sbin/tzsetup -r");
1677

    
1678
	if (platform_booting()) {
1679
		echo gettext("done.") . "\n";
1680
	}
1681
}
1682

    
1683
function system_ntp_setup_gps($serialport) {
1684
	global $config, $g;
1685
	$gps_device = '/dev/gps0';
1686
	$serialport = '/dev/'.$serialport;
1687

    
1688
	if (!file_exists($serialport)) {
1689
		return false;
1690
	}
1691

    
1692
	// Create symlink that ntpd requires
1693
	unlink_if_exists($gps_device);
1694
	@symlink($serialport, $gps_device);
1695

    
1696
	$gpsbaud = '4800';
1697
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1698
		switch ($config['ntpd']['gps']['speed']) {
1699
			case '16':
1700
				$gpsbaud = '9600';
1701
				break;
1702
			case '32':
1703
				$gpsbaud = '19200';
1704
				break;
1705
			case '48':
1706
				$gpsbaud = '38400';
1707
				break;
1708
			case '64':
1709
				$gpsbaud = '57600';
1710
				break;
1711
			case '80':
1712
				$gpsbaud = '115200';
1713
				break;
1714
		}
1715
	}
1716

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

    
1720
	/* Send the following to the GPS port to initialize the GPS */
1721
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1722
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1723
	} else {
1724
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1725
	}
1726

    
1727
	/* XXX: Why not file_put_contents to the device */
1728
	@file_put_contents('/tmp/gps.init', $gps_init);
1729
	mwexec("cat /tmp/gps.init > {$serialport}");
1730

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

    
1736

    
1737
	return true;
1738
}
1739

    
1740
function system_ntp_setup_pps($serialport) {
1741
	global $config, $g;
1742

    
1743
	$pps_device = '/dev/pps0';
1744
	$serialport = '/dev/'.$serialport;
1745

    
1746
	if (!file_exists($serialport)) {
1747
		return false;
1748
	}
1749

    
1750
	// Create symlink that ntpd requires
1751
	unlink_if_exists($pps_device);
1752
	@symlink($serialport, $pps_device);
1753

    
1754

    
1755
	return true;
1756
}
1757

    
1758

    
1759
function system_ntp_configure() {
1760
	global $config, $g;
1761

    
1762
	$driftfile = "/var/db/ntpd.drift";
1763
	$statsdir = "/var/log/ntp";
1764
	$gps_device = '/dev/gps0';
1765

    
1766
	safe_mkdir($statsdir);
1767

    
1768
	if (!is_array($config['ntpd'])) {
1769
		$config['ntpd'] = array();
1770
	}
1771

    
1772
	$ntpcfg = "# \n";
1773
	$ntpcfg .= "# pfSense ntp configuration file \n";
1774
	$ntpcfg .= "# \n\n";
1775
	$ntpcfg .= "tinker panic 0 \n";
1776

    
1777
	/* Add Orphan mode */
1778
	$ntpcfg .= "# Orphan mode stratum\n";
1779
	$ntpcfg .= 'tos orphan ';
1780
	if (!empty($config['ntpd']['orphan'])) {
1781
		$ntpcfg .= $config['ntpd']['orphan'];
1782
	} else {
1783
		$ntpcfg .= '12';
1784
	}
1785
	$ntpcfg .= "\n";
1786

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

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

    
1917
		$ntpcfg .= "{$ts} iburst maxpoll 9";
1918
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1919
			$ntpcfg .= ' prefer';
1920
		}
1921
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1922
			$ntpcfg .= ' noselect';
1923
		}
1924
		$ntpcfg .= "\n";
1925
	}
1926
	unset($ts);
1927

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

    
1954
	/* Default Access restrictions */
1955
	$ntpcfg .= 'restrict default';
1956
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1957
		$ntpcfg .= ' kod limited';
1958
	}
1959
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1960
		$ntpcfg .= ' nomodify';
1961
	}
1962
	if (!empty($config['ntpd']['noquery'])) {
1963
		$ntpcfg .= ' noquery';
1964
	}
1965
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1966
		$ntpcfg .= ' nopeer';
1967
	}
1968
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1969
		$ntpcfg .= ' notrap';
1970
	}
1971
	if (!empty($config['ntpd']['noserve'])) {
1972
		$ntpcfg .= ' noserve';
1973
	}
1974
	$ntpcfg .= "\nrestrict -6 default";
1975
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1976
		$ntpcfg .= ' kod limited';
1977
	}
1978
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1979
		$ntpcfg .= ' nomodify';
1980
	}
1981
	if (!empty($config['ntpd']['noquery'])) {
1982
		$ntpcfg .= ' noquery';
1983
	}
1984
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1985
		$ntpcfg .= ' nopeer';
1986
	}
1987
	if (!empty($config['ntpd']['noserve'])) {
1988
		$ntpcfg .= ' noserve';
1989
	}
1990
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1991
		$ntpcfg .= ' notrap';
1992
	}
1993

    
1994
	/* Pools require "restrict source" and cannot contain "nopeer". */
1995
	if ($have_pools) {
1996
		$ntpcfg .= "\nrestrict source";
1997
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1998
			$ntpcfg .= ' kod limited';
1999
		}
2000
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2001
			$ntpcfg .= ' nomodify';
2002
		}
2003
		if (!empty($config['ntpd']['noquery'])) {
2004
			$ntpcfg .= ' noquery';
2005
		}
2006
		if (!empty($config['ntpd']['noserve'])) {
2007
			$ntpcfg .= ' noserve';
2008
		}
2009
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2010
			$ntpcfg .= ' notrap';
2011
		}
2012
	}
2013

    
2014
	/* Custom Access Restrictions */
2015
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2016
		$networkacl = $config['ntpd']['restrictions']['row'];
2017
		foreach ($networkacl as $acl) {
2018
			$restrict = "";
2019
			if (is_ipaddrv6($acl['acl_network'])) {
2020
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2021
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2022
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2023
			} else {
2024
				continue;
2025
			}
2026
			if (!empty($acl['kod'])) {
2027
				$restrict .= ' kod limited';
2028
			}
2029
			if (!empty($acl['nomodify'])) {
2030
				$restrict .= ' nomodify';
2031
			}
2032
			if (!empty($acl['noquery'])) {
2033
				$restrict .= ' noquery';
2034
			}
2035
			if (!empty($acl['nopeer'])) {
2036
				$restrict .= ' nopeer';
2037
			}
2038
			if (!empty($acl['noserve'])) {
2039
				$restrict .= ' noserve';
2040
			}
2041
			if (!empty($acl['notrap'])) {
2042
				$restrict .= ' notrap';
2043
			}
2044
			if (!empty($restrict)) {
2045
				$ntpcfg .= "\nrestrict {$restrict} ";
2046
			}
2047
		}
2048
	}
2049
	/* End Custom Access Restrictions */
2050

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

    
2059

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

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

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

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

    
2097
	/* if /var/empty does not exist, create it */
2098
	if (!is_dir("/var/empty")) {
2099
		mkdir("/var/empty", 0555, true);
2100
	}
2101

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

    
2105
	// Note that we are starting up
2106
	log_error("NTPD is starting up.");
2107
	return;
2108
}
2109

    
2110
function system_halt() {
2111
	global $g;
2112

    
2113
	system_reboot_cleanup();
2114

    
2115
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2116
}
2117

    
2118
function system_reboot() {
2119
	global $g;
2120

    
2121
	system_reboot_cleanup();
2122

    
2123
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2124
}
2125

    
2126
function system_reboot_sync($reroot=false) {
2127
	global $g;
2128

    
2129
	if ($reroot) {
2130
		$args = " -r ";
2131
	}
2132

    
2133
	system_reboot_cleanup();
2134

    
2135
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2136
}
2137

    
2138
function system_reboot_cleanup() {
2139
	global $config, $cpzone, $cpzoneid;
2140

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

    
2158
function system_do_shell_commands($early = 0) {
2159
	global $config, $g;
2160
	if (isset($config['system']['developerspew'])) {
2161
		$mt = microtime();
2162
		echo "system_do_shell_commands() being called $mt\n";
2163
	}
2164

    
2165
	if ($early) {
2166
		$cmdn = "earlyshellcmd";
2167
	} else {
2168
		$cmdn = "shellcmd";
2169
	}
2170

    
2171
	if (is_array($config['system'][$cmdn])) {
2172

    
2173
		/* *cmd is an array, loop through */
2174
		foreach ($config['system'][$cmdn] as $cmd) {
2175
			exec($cmd);
2176
		}
2177

    
2178
	} elseif ($config['system'][$cmdn] <> "") {
2179

    
2180
		/* execute single item */
2181
		exec($config['system'][$cmdn]);
2182

    
2183
	}
2184
}
2185

    
2186
function system_dmesg_save() {
2187
	global $g;
2188
	if (isset($config['system']['developerspew'])) {
2189
		$mt = microtime();
2190
		echo "system_dmesg_save() being called $mt\n";
2191
	}
2192

    
2193
	$dmesg = "";
2194
	$_gb = exec("/sbin/dmesg", $dmesg);
2195

    
2196
	/* find last copyright line (output from previous boots may be present) */
2197
	$lastcpline = 0;
2198

    
2199
	for ($i = 0; $i < count($dmesg); $i++) {
2200
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2201
			$lastcpline = $i;
2202
		}
2203
	}
2204

    
2205
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2206
	if (!$fd) {
2207
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2208
		return 1;
2209
	}
2210

    
2211
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2212
		fwrite($fd, $dmesg[$i] . "\n");
2213
	}
2214

    
2215
	fclose($fd);
2216
	unset($dmesg);
2217

    
2218
	// vm-bhyve expects dmesg.boot at the standard location
2219
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2220

    
2221
	return 0;
2222
}
2223

    
2224
function system_set_harddisk_standby() {
2225
	global $g, $config;
2226

    
2227
	if (isset($config['system']['developerspew'])) {
2228
		$mt = microtime();
2229
		echo "system_set_harddisk_standby() being called $mt\n";
2230
	}
2231

    
2232
	if (isset($config['system']['harddiskstandby'])) {
2233
		if (platform_booting()) {
2234
			echo gettext('Setting hard disk standby... ');
2235
		}
2236

    
2237
		$standby = $config['system']['harddiskstandby'];
2238
		// Check for a numeric value
2239
		if (is_numeric($standby)) {
2240
			// Get only suitable candidates for standby; using get_smart_drive_list()
2241
			// from utils.inc to get the list of drives.
2242
			$harddisks = get_smart_drive_list();
2243

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

    
2263
function system_setup_sysctl() {
2264
	global $config;
2265
	if (isset($config['system']['developerspew'])) {
2266
		$mt = microtime();
2267
		echo "system_setup_sysctl() being called $mt\n";
2268
	}
2269

    
2270
	activate_sysctls();
2271

    
2272
	if (isset($config['system']['sharednet'])) {
2273
		system_disable_arp_wrong_if();
2274
	}
2275
}
2276

    
2277
function system_disable_arp_wrong_if() {
2278
	global $config;
2279
	if (isset($config['system']['developerspew'])) {
2280
		$mt = microtime();
2281
		echo "system_disable_arp_wrong_if() being called $mt\n";
2282
	}
2283
	set_sysctl(array(
2284
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2285
		"net.link.ether.inet.log_arp_movements" => "0"
2286
	));
2287
}
2288

    
2289
function system_enable_arp_wrong_if() {
2290
	global $config;
2291
	if (isset($config['system']['developerspew'])) {
2292
		$mt = microtime();
2293
		echo "system_enable_arp_wrong_if() being called $mt\n";
2294
	}
2295
	set_sysctl(array(
2296
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2297
		"net.link.ether.inet.log_arp_movements" => "1"
2298
	));
2299
}
2300

    
2301
function enable_watchdog() {
2302
	global $config;
2303
	return;
2304
	$install_watchdog = false;
2305
	$supported_watchdogs = array("Geode");
2306
	$file = file_get_contents("/var/log/dmesg.boot");
2307
	foreach ($supported_watchdogs as $sd) {
2308
		if (stristr($file, "Geode")) {
2309
			$install_watchdog = true;
2310
		}
2311
	}
2312
	if ($install_watchdog == true) {
2313
		if (is_process_running("watchdogd")) {
2314
			mwexec("/usr/bin/killall watchdogd", true);
2315
		}
2316
		exec("/usr/sbin/watchdogd");
2317
	}
2318
}
2319

    
2320
function system_check_reset_button() {
2321
	global $g;
2322

    
2323
	$specplatform = system_identify_specific_platform();
2324

    
2325
	switch ($specplatform['name']) {
2326
		case 'alix':
2327
		case 'wrap':
2328
		case 'FW7541':
2329
		case 'APU':
2330
		case 'RCC-VE':
2331
		case 'RCC':
2332
		case 'RCC-DFF':
2333
			break;
2334
		default:
2335
			return 0;
2336
	}
2337

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

    
2340
	if ($retval == 99) {
2341
		/* user has pressed reset button for 2 seconds -
2342
		   reset to factory defaults */
2343
		echo <<<EOD
2344

    
2345
***********************************************************************
2346
* Reset button pressed - resetting configuration to factory defaults. *
2347
* All additional packages installed will be removed                   *
2348
* The system will reboot after this completes.                        *
2349
***********************************************************************
2350

    
2351

    
2352
EOD;
2353

    
2354
		reset_factory_defaults();
2355
		system_reboot_sync();
2356
		exit(0);
2357
	}
2358

    
2359
	return 0;
2360
}
2361

    
2362
function system_get_serial() {
2363
	$platform = system_identify_specific_platform();
2364

    
2365
	unset($output);
2366
	if ($platform['name'] == 'Turbot Dual-E') {
2367
		$if_info = pfSense_get_interface_addresses('igb0');
2368
		if (!empty($if_info['hwaddr'])) {
2369
			$serial = str_replace(":", "", $if_info['hwaddr']);
2370
		}
2371
	} else {
2372
		$_gb = exec('/bin/kenv smbios.system.serial 2>/dev/null', $output);
2373
		$serial = $output[0];
2374
	}
2375

    
2376
	$vm_guest = get_single_sysctl('kern.vm_guest');
2377

    
2378
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2379
	    $vm_guest == 'none') {
2380
		return $serial;
2381
	}
2382

    
2383
	return "";
2384
}
2385

    
2386
function system_get_uniqueid() {
2387
	global $g;
2388

    
2389
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2390

    
2391
	if (empty($g['uniqueid'])) {
2392
		if (!file_exists($uniqueid_file)) {
2393
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2394
			    "2>/dev/null");
2395
		}
2396
		if (file_exists($uniqueid_file)) {
2397
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2398
		}
2399
	}
2400

    
2401
	return ($g['uniqueid'] ?: '');
2402
}
2403

    
2404
/*
2405
 * attempt to identify the specific platform (for embedded systems)
2406
 * Returns an array with two elements:
2407
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2408
 * descr => human-readable description (e.g. "PC Engines WRAP")
2409
 */
2410
function system_identify_specific_platform() {
2411
	global $g;
2412

    
2413
	$hw_model = get_single_sysctl('hw.model');
2414
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2415

    
2416
	/* Try to guess from smbios strings */
2417
	unset($product);
2418
	unset($maker);
2419
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2420
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2421
	switch ($product[0]) {
2422
		case 'FW7541':
2423
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2424
			break;
2425
		case 'APU':
2426
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2427
			break;
2428
		case 'RCC-VE':
2429
			$result = array();
2430
			$result['name'] = 'RCC-VE';
2431

    
2432
			/* Detect specific models */
2433
			if (!function_exists('does_interface_exist')) {
2434
				require_once("interfaces.inc");
2435
			}
2436
			if (!does_interface_exist('igb4')) {
2437
				$result['model'] = 'SG-2440';
2438
			} elseif (strpos($hw_model, "C2558") !== false) {
2439
				$result['model'] = 'SG-4860';
2440
			} elseif (strpos($hw_model, "C2758") !== false) {
2441
				$result['model'] = 'SG-8860';
2442
			} else {
2443
				$result['model'] = 'RCC-VE';
2444
			}
2445
			$result['descr'] = 'Netgate ' . $result['model'];
2446
			return $result;
2447
			break;
2448
		case 'DFFv2':
2449
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2450
			break;
2451
		case 'RCC':
2452
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2453
			break;
2454
		case 'Minnowboard Turbot D0 PLATFORM':
2455
			$result = array();
2456
			$result['name'] = 'Turbot Dual-E';
2457
			/* Detect specific model */
2458
			switch ($hw_ncpu) {
2459
			case '4':
2460
				$result['model'] = 'SG-2340';
2461
				break;
2462
			case '2':
2463
				$result['model'] = 'SG-2320';
2464
				break;
2465
			default:
2466
				$result['model'] = $result['name'];
2467
				break;
2468
			}
2469
			$result['descr'] = 'Netgate ' . $result['model'];
2470
			return $result;
2471
			break;
2472
		case 'SYS-5018A-FTN4':
2473
		case 'A1SAi':
2474
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2475
			break;
2476
		case 'SYS-5018D-FN4T':
2477
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2478
			break;
2479
		case 'apu2':
2480
		case 'APU2':
2481
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2482
			break;
2483
		case 'VirtualBox':
2484
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2485
			break;
2486
		case 'Virtual Machine':
2487
			if ($maker[0] == "Microsoft Corporation") {
2488
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2489
			}
2490
			break;
2491
		case 'VMware Virtual Platform':
2492
			if ($maker[0] == "VMware, Inc.") {
2493
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2494
			}
2495
			break;
2496
	}
2497

    
2498
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2499
	    $planar_product);
2500
	if (isset($planar_product[0]) &&
2501
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2502
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2503
	}
2504

    
2505
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2506
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2507
	}
2508

    
2509
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2510
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2511
	}
2512

    
2513
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2514
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2515
	}
2516

    
2517
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2518
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2519
	}
2520

    
2521
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2522
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2523
	}
2524

    
2525
	unset($hw_model);
2526

    
2527
	$dmesg_boot = system_get_dmesg_boot();
2528
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2529
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2530
	}
2531
	unset($dmesg_boot);
2532

    
2533
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2534
}
2535

    
2536
function system_get_dmesg_boot() {
2537
	global $g;
2538

    
2539
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2540
}
2541

    
2542
?>
(46-46/58)