Project

General

Profile

Download (72.9 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
	foreach(get_dns_nameservers() as $dns_ns) {
126
		$resolvconf .= "nameserver $dns_ns\n";
127
	}
128

    
129
	if (isset($syscfg['dnsallowoverride'])) {
130
		/* get dynamically assigned DNS servers (if any) */
131
		$ns = array_unique(get_searchdomains());
132
		foreach ($ns as $searchserver) {
133
			if ($searchserver) {
134
				$resolvconf .= "search {$searchserver}\n";
135
			}
136
		}
137
	} else {
138
		$ns = array();
139
		// Do not create blank search/domain lines, it can break tools like dig.
140
		if ($syscfg['domain']) {
141
			$resolvconf .= "search {$syscfg['domain']}\n";
142
		}
143
	}
144

    
145
	// Add EDNS support
146
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
147
		$resolvconf .= "options edns0\n";
148
	}
149

    
150
	$dnslock = lock('resolvconf', LOCK_EX);
151

    
152
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
153
	if (!$fd) {
154
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
155
		unlock($dnslock);
156
		return 1;
157
	}
158

    
159
	fwrite($fd, $resolvconf);
160
	fclose($fd);
161

    
162
	// Prevent resolvconf(8) from rewriting our resolv.conf
163
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
164
	if (!$fd) {
165
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
166
		return 1;
167
	}
168
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
169
	fclose($fd);
170

    
171
	if (!platform_booting()) {
172
		/* restart dhcpd (nameservers may have changed) */
173
		if (!$dynupdate) {
174
			services_dhcpd_configure();
175
		}
176
	}
177

    
178
	/* setup static routes for DNS servers. */
179
	$dnscounter = 1;
180
	$dnsgw = "dns{$dnscounter}gw";
181
	while (isset($config['system'][$dnsgw])) {
182
		/* setup static routes for dns servers */
183
		if (!(empty($config['system'][$dnsgw]) ||
184
		    $config['system'][$dnsgw] == "none")) {
185
			$gwname = $config['system'][$dnsgw];
186
			$gatewayip = lookup_gateway_ip_by_name($gwname);
187
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
188
			/* dns server array starts at 0 */
189
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
190

    
191
			if (is_ipaddr($gatewayip)) {
192
				route_add_or_change("-host {$inet6}{$dnsserver} {$gatewayip}");
193
			} else {
194
				/* Remove old route when disable gw */
195
				mwexec("/sbin/route delete -host {$inet6}{$dnsserver}");
196
				if (isset($config['system']['route-debug'])) {
197
					$mt = microtime();
198
					log_error("ROUTING debug: $mt - route delete -host {$inet6}{$dnsserver}");
199
				}
200
			}
201
		}
202
		$dnscounter++;
203
		$dnsgw = "dns{$dnscounter}gw";
204
	}
205

    
206
	unlock($dnslock);
207

    
208
	return 0;
209
}
210

    
211
function get_searchdomains() {
212
	global $config, $g;
213

    
214
	$master_list = array();
215

    
216
	// Read in dhclient nameservers
217
	$search_list = glob("/var/etc/searchdomain_*");
218
	if (is_array($search_list)) {
219
		foreach ($search_list as $fdns) {
220
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
221
			if (!is_array($contents)) {
222
				continue;
223
			}
224
			foreach ($contents as $dns) {
225
				if (is_hostname($dns)) {
226
					$master_list[] = $dns;
227
				}
228
			}
229
		}
230
	}
231

    
232
	return $master_list;
233
}
234

    
235
function get_nameservers() {
236
	global $config, $g;
237
	$master_list = array();
238

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

    
255
	// Read in any extra nameservers
256
	if (file_exists("/var/etc/nameservers.conf")) {
257
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
258
		if (is_array($dns_s)) {
259
			foreach ($dns_s as $dns) {
260
				if (is_ipaddr($dns)) {
261
					$master_list[] = $dns;
262
				}
263
			}
264
		}
265
	}
266

    
267
	return $master_list;
268
}
269

    
270
/* Create localhost + local interfaces entries for /etc/hosts */
271
function system_hosts_local_entries() {
272
	global $config;
273

    
274
	$syscfg = $config['system'];
275

    
276
	$hosts = array();
277
	$hosts[] = array(
278
	    'ipaddr' => '127.0.0.1',
279
	    'fqdn' => 'localhost.' . $syscfg['domain'],
280
	    'name' => 'localhost',
281
	    'domain' => $syscfg['domain']
282
	);
283
	$hosts[] = array(
284
	    'ipaddr' => '::1',
285
	    'fqdn' => 'localhost.' . $syscfg['domain'],
286
	    'name' => 'localhost',
287
	    'domain' => $syscfg['domain']
288
	);
289

    
290
	if ($config['interfaces']['lan']) {
291
		$sysiflist = array('lan' => "lan");
292
	} else {
293
		$sysiflist = get_configured_interface_list();
294
	}
295

    
296
	$hosts_if_found = false;
297
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
298
	foreach ($sysiflist as $sysif) {
299
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
300
			continue;
301
		}
302
		$cfgip = get_interface_ip($sysif);
303
		if (is_ipaddrv4($cfgip)) {
304
			$hosts[] = array(
305
			    'ipaddr' => $cfgip,
306
			    'fqdn' => $local_fqdn,
307
			    'name' => $syscfg['hostname'],
308
			    'domain' => $syscfg['domain']
309
			);
310
			$hosts_if_found = true;
311
		}
312
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
313
			$cfgipv6 = get_interface_ipv6($sysif);
314
			if (is_ipaddrv6($cfgipv6)) {
315
				$hosts[] = array(
316
					'ipaddr' => $cfgipv6,
317
					'fqdn' => $local_fqdn,
318
					'name' => $syscfg['hostname'],
319
					'domain' => $syscfg['domain']
320
				);
321
				$hosts_if_found = true;
322
			}
323
		}
324
		if ($hosts_if_found == true) {
325
			break;
326
		}
327
	}
328

    
329
	return $hosts;
330
}
331

    
332
/* Read host override entries from dnsmasq or unbound */
333
function system_hosts_override_entries($dnscfg) {
334
	$hosts = array();
335

    
336
	if (!is_array($dnscfg) ||
337
	    !is_array($dnscfg['hosts']) ||
338
	    !isset($dnscfg['enable'])) {
339
		return $hosts;
340
	}
341

    
342
	foreach ($dnscfg['hosts'] as $host) {
343
		$fqdn = '';
344
		if ($host['host'] || $host['host'] == "0") {
345
			$fqdn .= "{$host['host']}.";
346
		}
347
		$fqdn .= $host['domain'];
348

    
349
		$hosts[] = array(
350
		    'ipaddr' => $host['ip'],
351
		    'fqdn' => $fqdn,
352
		    'name' => $host['host'],
353
		    'domain' => $host['domain']
354
		);
355

    
356
		if (!is_array($host['aliases']) ||
357
		    !is_array($host['aliases']['item'])) {
358
			continue;
359
		}
360

    
361
		foreach ($host['aliases']['item'] as $alias) {
362
			$fqdn = '';
363
			if ($alias['host'] || $alias['host'] == "0") {
364
				$fqdn .= "{$alias['host']}.";
365
			}
366
			$fqdn .= $alias['domain'];
367

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

    
377
	return $hosts;
378
}
379

    
380
/* Read all dhcpd/dhcpdv6 staticmap entries */
381
function system_hosts_dhcpd_entries() {
382
	global $config;
383

    
384
	$hosts = array();
385
	$syscfg = $config['system'];
386

    
387
	if (is_array($config['dhcpd'])) {
388
		$conf_dhcpd = $config['dhcpd'];
389
	} else {
390
		$conf_dhcpd = array();
391
	}
392

    
393
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
394
		if (!is_array($dhcpifconf['staticmap']) ||
395
		    !isset($dhcpifconf['enable'])) {
396
			continue;
397
		}
398
		foreach ($dhcpifconf['staticmap'] as $host) {
399
			if (!$host['ipaddr'] ||
400
			    !$host['hostname']) {
401
				continue;
402
			}
403

    
404
			$fqdn = $host['hostname'] . ".";
405
			$domain = "";
406
			if ($host['domain']) {
407
				$domain = $host['domain'];
408
			} elseif ($dhcpifconf['domain']) {
409
				$domain = $dhcpifconf['domain'];
410
			} else {
411
				$domain = $syscfg['domain'];
412
			}
413

    
414
			$hosts[] = array(
415
			    'ipaddr' => $host['ipaddr'],
416
			    'fqdn' => $fqdn . $domain,
417
			    'name' => $host['hostname'],
418
			    'domain' => $domain
419
			);
420
		}
421
	}
422
	unset($conf_dhcpd);
423

    
424
	if (is_array($config['dhcpdv6'])) {
425
		$conf_dhcpdv6 = $config['dhcpdv6'];
426
	} else {
427
		$conf_dhcpdv6 = array();
428
	}
429

    
430
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
431
		if (!is_array($dhcpifconf['staticmap']) ||
432
		    !isset($dhcpifconf['enable'])) {
433
			continue;
434
		}
435

    
436
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
437
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
438
		    'track6') {
439
			$isdelegated = true;
440
		} else {
441
			$isdelegated = false;
442
		}
443

    
444
		foreach ($dhcpifconf['staticmap'] as $host) {
445
			$ipaddrv6 = $host['ipaddrv6'];
446

    
447
			if (!$ipaddrv6 || !$host['hostname']) {
448
				continue;
449
			}
450

    
451
			if ($isdelegated) {
452
				/*
453
				 * We are always in an "end-user" subnet
454
				 * here, which all are /64 for IPv6.
455
				 */
456
				$ipaddrv6 = merge_ipv6_delegated_prefix(
457
				    get_interface_ipv6($dhcpif),
458
				    $ipaddrv6, 64);
459
			}
460

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

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

    
481
	return $hosts;
482
}
483

    
484
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
485
function system_hosts_entries($dnscfg) {
486
	$local = array();
487
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
488
		$local = system_hosts_local_entries();
489
	}
490

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

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

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

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

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

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

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

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

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

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

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

    
569
	return 0;
570
}
571

    
572
function system_dhcpleases_configure() {
573
	global $config, $g;
574
	if (!function_exists('is_dhcp_server_enabled')) {
575
		require_once('pfsense-utils.inc');
576
	}
577
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
578

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

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

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

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

    
620
function system_hostname_configure() {
621
	global $config, $g;
622
	if (isset($config['system']['developerspew'])) {
623
		$mt = microtime();
624
		echo "system_hostname_configure() being called $mt\n";
625
	}
626

    
627
	$syscfg = $config['system'];
628

    
629
	/* set hostname */
630
	$status = mwexec("/bin/hostname " .
631
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
632

    
633
	/* Setup host GUID ID.  This is used by ZFS. */
634
	mwexec("/etc/rc.d/hostid start");
635

    
636
	return $status;
637
}
638

    
639
function system_routing_configure($interface = "") {
640
	global $config, $g;
641

    
642
	if (isset($config['system']['developerspew'])) {
643
		$mt = microtime();
644
		echo "system_routing_configure() being called $mt\n";
645
	}
646

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

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

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

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

    
752
	system_staticroutes_configure($interface, false);
753

    
754
	return 0;
755
}
756

    
757
function system_staticroutes_configure($interface = "", $update_dns = false) {
758
	global $config, $g, $aliastable;
759

    
760
	$filterdns_list = array();
761

    
762
	$static_routes = get_staticroutes(false, true);
763
	if (count($static_routes)) {
764
		$gateways_arr = return_gateways_array(false, true);
765

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

    
776
			$gatewayip = $gateway['gateway'];
777
			$interfacegw = $gateway['interface'];
778

    
779
			$blackhole = "";
780
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
781
				$blackhole = "-blackhole";
782
			}
783

    
784
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
785
				continue;
786
			}
787

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

    
799
			if (is_subnet($rtent['network'])) {
800
				$ips = array($rtent['network']);
801
			} else {
802
				if (!isset($rtent['disabled'])) {
803
					$filterdns_list[] = $rtent['network'];
804
				}
805
				$ips = add_hostname_to_watch($rtent['network']);
806
			}
807

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

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

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

    
837
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
838

    
839
				$cmd = "{$inet} {$blackhole} {$ip} ";
840

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

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

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

    
881
	return 0;
882
}
883

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

    
891
	set_sysctl(array(
892
		"net.inet.ip.forwarding" => "1",
893
		"net.inet6.ip6.forwarding" => "1"
894
	));
895

    
896
	return;
897
}
898

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

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

    
928
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
929
	global $config, $g;
930

    
931
	if ($restart_syslogd) {
932
		/* syslogd does not react well to clog rewriting the file while it is running. */
933
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
934
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
935
		}
936
	}
937
	if (isset($config['system']['disablesyslogclog'])) {
938
		unlink($logfile);
939
		touch($logfile);
940
	} else {
941
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
942
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
943
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
944
	}
945
	if ($restart_syslogd) {
946
		system_syslogd_start();
947
	}
948
	// Bug #6915
949
	if ($logfile == "/var/log/resolver.log") {
950
		services_unbound_configure(true);
951
	}
952
}
953

    
954
function clear_all_log_files($restart = false) {
955
	global $g;
956
	if ($restart) {
957
		/* syslogd does not react well to clog rewriting the file while it is running. */
958
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
959
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
960
		}
961
	}
962

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

    
968
	if ($restart) {
969
		system_syslogd_start();
970
		killbyname("dhcpd");
971
		if (!function_exists('services_dhcpd_configure')) {
972
			require_once('services.inc');
973
		}
974
		services_dhcpd_configure();
975
		// Bug #6915
976
		services_unbound_configure(false);
977
	}
978
	return;
979
}
980

    
981
function system_syslogd_start($sighup = false) {
982
	global $config, $g;
983
	if (isset($config['system']['developerspew'])) {
984
		$mt = microtime();
985
		echo "system_syslogd_start() being called $mt\n";
986
	}
987

    
988
	mwexec("/etc/rc.d/hostid start");
989

    
990
	$syslogcfg = $config['syslog'];
991

    
992
	if (platform_booting()) {
993
		echo gettext("Starting syslog...");
994
	}
995

    
996
	// Which logging type are we using this week??
997
	if (isset($config['system']['disablesyslogclog'])) {
998
		$log_directive = "";
999
		$log_create_directive = "/usr/bin/touch ";
1000
		$log_size = "";
1001
	} else { // Defaults to CLOG
1002
		$log_directive = "%";
1003
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
1004
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
1005
	}
1006

    
1007
	$syslogd_extra = "";
1008
	if (isset($syslogcfg)) {
1009
		$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');
1010
		$syslogconf = "";
1011
		if ($config['installedpackages']['package']) {
1012
			foreach ($config['installedpackages']['package'] as $package) {
1013
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1014
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1015
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1016
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1017
					}
1018
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1019
				}
1020
			}
1021
		}
1022
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1023
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,ospf6d,bgpd,miniupnpd\n";
1024
		if (!isset($syslogcfg['disablelocallogging'])) {
1025
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1026
		}
1027
		if (isset($syslogcfg['routing'])) {
1028
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1029
		}
1030

    
1031
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
1032
		if (!isset($syslogcfg['disablelocallogging'])) {
1033
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
1034
		}
1035
		if (isset($syslogcfg['ntpd'])) {
1036
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1037
		}
1038

    
1039
		$syslogconf .= "!ppp\n";
1040
		if (!isset($syslogcfg['disablelocallogging'])) {
1041
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
1042
		}
1043
		if (isset($syslogcfg['ppp'])) {
1044
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1045
		}
1046

    
1047
		$syslogconf .= "!poes\n";
1048
		if (!isset($syslogcfg['disablelocallogging'])) {
1049
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
1050
		}
1051
		if (isset($syslogcfg['vpn'])) {
1052
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1053
		}
1054

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

    
1063
		$syslogconf .= "!charon,ipsec_starter\n";
1064
		if (!isset($syslogcfg['disablelocallogging'])) {
1065
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
1066
		}
1067
		if (isset($syslogcfg['vpn'])) {
1068
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1069
		}
1070

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

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

    
1087
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1088
		if (!isset($syslogcfg['disablelocallogging'])) {
1089
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1090
		}
1091
		if (isset($syslogcfg['resolver'])) {
1092
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1093
		}
1094

    
1095
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
1096
		if (!isset($syslogcfg['disablelocallogging'])) {
1097
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
1098
		}
1099
		if (isset($syslogcfg['dhcp'])) {
1100
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1101
		}
1102

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

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

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

    
1127
		$syslogconf .= "!-{$facilitylist}\n";
1128
		if (!isset($syslogcfg['disablelocallogging'])) {
1129
			$syslogconf .= <<<EOD
1130
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1131
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1132
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1133
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1134
*.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
1135
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1136
*.emerg								*
1137

    
1138
EOD;
1139
		}
1140
		if (isset($syslogcfg['vpn'])) {
1141
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1142
		}
1143
		if (isset($syslogcfg['portalauth'])) {
1144
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1145
		}
1146
		if (isset($syslogcfg['dhcp'])) {
1147
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1148
		}
1149
		if (isset($syslogcfg['system'])) {
1150
			$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");
1151
		}
1152
		if (isset($syslogcfg['logall'])) {
1153
			// Make everything mean everything, including facilities excluded above.
1154
			$syslogconf .= "!*\n";
1155
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1156
		}
1157

    
1158
		if (isset($syslogcfg['zmqserver'])) {
1159
				$syslogconf .= <<<EOD
1160
*.*								^{$syslogcfg['zmqserver']}
1161

    
1162
EOD;
1163
		}
1164
		/* write syslog.conf */
1165
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1166
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1167
			unset($syslogconf);
1168
			return 1;
1169
		}
1170
		unset($syslogconf);
1171

    
1172
		$sourceip = "";
1173
		if (!empty($syslogcfg['sourceip'])) {
1174
			if ($syslogcfg['ipproto'] == "ipv6") {
1175
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1176
				if (!is_ipaddr($ifaddr)) {
1177
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1178
				}
1179
			} else {
1180
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1181
				if (!is_ipaddr($ifaddr)) {
1182
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1183
				}
1184
			}
1185
			if (is_ipaddr($ifaddr)) {
1186
				$sourceip = "-b {$ifaddr}";
1187
			}
1188
		}
1189

    
1190
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1191
	}
1192

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

    
1195
	if (isset($config['installedpackages']['package'])) {
1196
		foreach ($config['installedpackages']['package'] as $package) {
1197
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1198
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1199
				$log_sockets[] = $package['logging']['logsocket'];
1200
			}
1201
		}
1202
	}
1203

    
1204
	$syslogd_sockets = "";
1205
	foreach ($log_sockets as $log_socket) {
1206
		// Ensure that the log directory exists
1207
		$logpath = dirname($log_socket);
1208
		safe_mkdir($logpath);
1209
		$syslogd_sockets .= " -l {$log_socket}";
1210
	}
1211

    
1212
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1213
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1214
		$sighup = false;
1215
	}
1216

    
1217
	if (!$sighup) {
1218
		sigkillbyname("sshlockout_pf", "TERM");
1219
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1220
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1221
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1222
		}
1223

    
1224
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1225
			// if it still hasn't responded to the TERM, KILL it.
1226
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1227
			usleep(100000);
1228
		}
1229

    
1230
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1231
	} else {
1232
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1233
	}
1234

    
1235
	if (platform_booting()) {
1236
		echo gettext("done.") . "\n";
1237
	}
1238

    
1239
	return $retval;
1240
}
1241

    
1242
function system_webgui_create_certificate() {
1243
	global $config, $g;
1244

    
1245
	if (!is_array($config['ca'])) {
1246
		$config['ca'] = array();
1247
	}
1248
	$a_ca =& $config['ca'];
1249
	if (!is_array($config['cert'])) {
1250
		$config['cert'] = array();
1251
	}
1252
	$a_cert =& $config['cert'];
1253
	log_error(gettext("Creating SSL Certificate for this host"));
1254

    
1255
	$cert = array();
1256
	$cert['refid'] = uniqid();
1257
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1258
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1259

    
1260
	$dn = array(
1261
		'countryName' => "US",
1262
		'stateOrProvinceName' => "State",
1263
		'localityName' => "Locality",
1264
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1265
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1266
		'commonName' => $cert_hostname,
1267
		'subjectAltName' => "DNS:{$cert_hostname}");
1268
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1269
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1270
		while ($ssl_err = openssl_error_string()) {
1271
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1272
		}
1273
		error_reporting($old_err_level);
1274
		return null;
1275
	}
1276
	error_reporting($old_err_level);
1277

    
1278
	$a_cert[] = $cert;
1279
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1280
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1281
	return $cert;
1282
}
1283

    
1284
function system_webgui_start() {
1285
	global $config, $g;
1286

    
1287
	if (platform_booting()) {
1288
		echo gettext("Starting webConfigurator...");
1289
	}
1290

    
1291
	chdir($g['www_path']);
1292

    
1293
	/* defaults */
1294
	$portarg = "80";
1295
	$crt = "";
1296
	$key = "";
1297
	$ca = "";
1298

    
1299
	/* non-standard port? */
1300
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1301
		$portarg = "{$config['system']['webgui']['port']}";
1302
	}
1303

    
1304
	if ($config['system']['webgui']['protocol'] == "https") {
1305
		// Ensure that we have a webConfigurator CERT
1306
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1307
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1308
			$cert = system_webgui_create_certificate();
1309
		}
1310
		$crt = base64_decode($cert['crt']);
1311
		$key = base64_decode($cert['prv']);
1312

    
1313
		if (!$config['system']['webgui']['port']) {
1314
			$portarg = "443";
1315
		}
1316
		$ca = ca_chain($cert);
1317
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1318
	}
1319

    
1320
	/* generate nginx configuration */
1321
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1322
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1323
		"cert.crt", "cert.key", false, $hsts);
1324

    
1325
	/* kill any running nginx */
1326
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1327

    
1328
	sleep(1);
1329

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

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

    
1335
	if (platform_booting()) {
1336
		if ($res == 0) {
1337
			echo gettext("done.") . "\n";
1338
		} else {
1339
			echo gettext("failed!") . "\n";
1340
		}
1341
	}
1342

    
1343
	return $res;
1344
}
1345

    
1346
function get_dns_nameservers() {
1347
	global $config;
1348
	
1349
	$dns_nameservers = array();
1350
	
1351
	if (isset($config['system']['developerspew'])) {
1352
		$mt = microtime();
1353
		echo "get_dns_nameservers() being called $mt\n";
1354
	}
1355
	
1356
	$syscfg = $config['system'];
1357
	if ((((isset($config['dnsmasq']['enable'])) &&
1358
   		(empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1359
	      	(empty($config['dnsmasq']['interface']) ||
1360
	       	in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1361
	     	((isset($config['unbound']['enable'])) &&
1362
	      	(empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1363
	      	(empty($config['unbound']['active_interface']) ||
1364
	       	in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1365
	       	in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1366
	     	(!isset($config['system']['dnslocalhost']))) {
1367
			$dns_nameservers[] = "127.0.0.1";
1368
	}
1369
	if (isset($syscfg['dnsallowoverride'])) {
1370
	/* get dynamically assigned DNS servers (if any) */
1371
		$ns = array_unique(get_nameservers());
1372
		foreach ($ns as $nameserver) {
1373
			if ($nameserver) {
1374
				$dns_nameservers[] = "$nameserver";
1375
			}
1376
		}
1377
	}
1378
	if (is_array($syscfg['dnsserver'])) {
1379
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1380
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
1381
				$dns_nameservers[] = "$sys_dnsserver";
1382
			}
1383
		}
1384
	}
1385
	return array_unique($dns_nameservers);
1386
}
1387

    
1388
function system_generate_nginx_config($filename,
1389
	$cert,
1390
	$key,
1391
	$ca,
1392
	$pid_file,
1393
	$port = 80,
1394
	$document_root = "/usr/local/www/",
1395
	$cert_location = "cert.crt",
1396
	$key_location = "cert.key",
1397
	$captive_portal = false,
1398
	$hsts = true) {
1399

    
1400
	global $config, $g;
1401

    
1402
	if (isset($config['system']['developerspew'])) {
1403
		$mt = microtime();
1404
		echo "system_generate_nginx_config() being called $mt\n";
1405
	}
1406

    
1407
	if ($captive_portal !== false) {
1408
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1409
		$cp_hostcheck = "";
1410
		foreach ($cp_interfaces as $cpint) {
1411
			$cpint_ip = get_interface_ip($cpint);
1412
			if (is_ipaddr($cpint_ip)) {
1413
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1414
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1415
				$cp_hostcheck .= "\t\t}\n";
1416
			}
1417
		}
1418
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1419
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1420
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1421
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1422
			$cp_hostcheck .= "\t\t}\n";
1423
		}
1424
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1425
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1426
		$cp_rewrite .= "\t\t}\n";
1427

    
1428
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1429
		if (empty($maxprocperip)) {
1430
			$maxprocperip = 10;
1431
		}
1432
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1433
	}
1434

    
1435
	if (empty($port)) {
1436
		$nginx_port = "80";
1437
	} else {
1438
		$nginx_port = $port;
1439
	}
1440

    
1441
	$memory = get_memory();
1442
	$realmem = $memory[1];
1443

    
1444
	// Determine web GUI process settings and take into account low memory systems
1445
	if ($realmem < 255) {
1446
		$max_procs = 1;
1447
	} else {
1448
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1449
	}
1450

    
1451
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1452
	if ($captive_portal !== false) {
1453
		if ($realmem > 135 and $realmem < 256) {
1454
			$max_procs += 1; // 2 worker processes
1455
		} else if ($realmem > 255 and $realmem < 513) {
1456
			$max_procs += 2; // 3 worker processes
1457
		} else if ($realmem > 512) {
1458
			$max_procs += 4; // 6 worker processes
1459
		}
1460
	}
1461

    
1462
	$nginx_config = <<<EOD
1463
#
1464
# nginx configuration file
1465

    
1466
pid {$g['varrun_path']}/{$pid_file};
1467

    
1468
user  root wheel;
1469
worker_processes  {$max_procs};
1470

    
1471
EOD;
1472

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

    
1477
	$nginx_config .= <<<EOD
1478

    
1479
events {
1480
    worker_connections  1024;
1481
}
1482

    
1483
http {
1484
	include       /usr/local/etc/nginx/mime.types;
1485
	default_type  application/octet-stream;
1486
	add_header X-Frame-Options SAMEORIGIN;
1487
	server_tokens off;
1488

    
1489
	sendfile        on;
1490

    
1491
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1492

    
1493
EOD;
1494

    
1495
	if ($captive_portal !== false) {
1496
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1497
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1498
	} else {
1499
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1500
	}
1501

    
1502
	if ($cert <> "" and $key <> "") {
1503
		$nginx_config .= "\n";
1504
		$nginx_config .= "\tserver {\n";
1505
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1506
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1507
		$nginx_config .= "\n";
1508
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1509
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1510
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1511
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1512
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1513
		if ($captive_portal !== false) {
1514
			// leave TLSv1.0 for CP for now for compatibility
1515
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1516
		} else {
1517
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1518
		}
1519
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1520
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1521
		if ($captive_portal === false && $hsts !== false) {
1522
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1523
		}
1524
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1525
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1526
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1527
		$cert_temp = lookup_cert($config['system']['webgui']['ssl-certref']);
1528
		if (($config['system']['webgui']['ocsp-staple'] == true) or
1529
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1530
			$nginx_config .= "\t\tssl_stapling on;\n";
1531
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1532
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers()) . " valid=300s;\n";
1533
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1534
		}
1535
	} else {
1536
		$nginx_config .= "\n";
1537
		$nginx_config .= "\tserver {\n";
1538
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1539
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1540
	}
1541

    
1542
	$nginx_config .= <<<EOD
1543

    
1544
		client_max_body_size 200m;
1545

    
1546
		gzip on;
1547
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1548

    
1549

    
1550
EOD;
1551

    
1552
	if ($captive_portal !== false) {
1553
		$nginx_config .= <<<EOD
1554
$captive_portal_maxprocperip
1555
$cp_hostcheck
1556
$cp_rewrite
1557
		log_not_found off;
1558

    
1559
EOD;
1560

    
1561
	}
1562

    
1563
	$nginx_config .= <<<EOD
1564
		root "{$document_root}";
1565
		location / {
1566
			index  index.php index.html index.htm;
1567
		}
1568
		location ~ \.inc$ {
1569
			deny all;
1570
			return 403;
1571
		}
1572
		location ~ \.php$ {
1573
			try_files \$uri =404; #  This line closes a potential security hole
1574
			# ensuring users can't execute uploaded files
1575
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1576
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1577
			fastcgi_index  index.php;
1578
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1579
			# Fix httpoxy - https://httpoxy.org/#fix-now
1580
			fastcgi_param  HTTP_PROXY  "";
1581
			fastcgi_read_timeout 180;
1582
			include        /usr/local/etc/nginx/fastcgi_params;
1583
		}
1584
		location ~ (^/status$) {
1585
			allow 127.0.0.1;
1586
			deny all;
1587
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1588
			fastcgi_index  index.php;
1589
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1590
			# Fix httpoxy - https://httpoxy.org/#fix-now
1591
			fastcgi_param  HTTP_PROXY  "";
1592
			fastcgi_read_timeout 360;
1593
			include        /usr/local/etc/nginx/fastcgi_params;
1594
		}
1595
	}
1596

    
1597
EOD;
1598

    
1599
	$cert = str_replace("\r", "", $cert);
1600
	$key = str_replace("\r", "", $key);
1601

    
1602
	$cert = str_replace("\n\n", "\n", $cert);
1603
	$key = str_replace("\n\n", "\n", $key);
1604

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

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

    
1641
EOD;
1642
	}
1643

    
1644
	$nginx_config .= "}\n";
1645

    
1646
	$fd = fopen("{$filename}", "w");
1647
	if (!$fd) {
1648
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1649
		return 1;
1650
	}
1651
	fwrite($fd, $nginx_config);
1652
	fclose($fd);
1653

    
1654
	/* nginx will fail to start if this directory does not exist. */
1655
	safe_mkdir("/var/tmp/nginx/");
1656

    
1657
	return 0;
1658

    
1659
}
1660

    
1661
function system_get_timezone_list() {
1662
	global $g;
1663

    
1664
	$file_list = array_merge(
1665
		glob("/usr/share/zoneinfo/[A-Z]*"),
1666
		glob("/usr/share/zoneinfo/*/*"),
1667
		glob("/usr/share/zoneinfo/*/*/*")
1668
	);
1669

    
1670
	if (empty($file_list)) {
1671
		$file_list[] = $g['default_timezone'];
1672
	} else {
1673
		/* Remove directories from list */
1674
		$file_list = array_filter($file_list, function($v) {
1675
			return !is_dir($v);
1676
		});
1677
	}
1678

    
1679
	/* Remove directory prefix */
1680
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1681

    
1682
	sort($file_list);
1683

    
1684
	return $file_list;
1685
}
1686

    
1687
function system_timezone_configure() {
1688
	global $config, $g;
1689
	if (isset($config['system']['developerspew'])) {
1690
		$mt = microtime();
1691
		echo "system_timezone_configure() being called $mt\n";
1692
	}
1693

    
1694
	$syscfg = $config['system'];
1695

    
1696
	if (platform_booting()) {
1697
		echo gettext("Setting timezone...");
1698
	}
1699

    
1700
	/* extract appropriate timezone file */
1701
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1702
	/* DO NOT remove \n otherwise tzsetup will fail */
1703
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1704
	mwexec("/usr/sbin/tzsetup -r");
1705

    
1706
	if (platform_booting()) {
1707
		echo gettext("done.") . "\n";
1708
	}
1709
}
1710

    
1711
function system_ntp_setup_gps($serialport) {
1712
	global $config, $g;
1713
	$gps_device = '/dev/gps0';
1714
	$serialport = '/dev/'.$serialport;
1715

    
1716
	if (!file_exists($serialport)) {
1717
		return false;
1718
	}
1719

    
1720
	// Create symlink that ntpd requires
1721
	unlink_if_exists($gps_device);
1722
	@symlink($serialport, $gps_device);
1723

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

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

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

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

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

    
1764

    
1765
	return true;
1766
}
1767

    
1768
function system_ntp_setup_pps($serialport) {
1769
	global $config, $g;
1770

    
1771
	$pps_device = '/dev/pps0';
1772
	$serialport = '/dev/'.$serialport;
1773

    
1774
	if (!file_exists($serialport)) {
1775
		return false;
1776
	}
1777

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

    
1782

    
1783
	return true;
1784
}
1785

    
1786

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

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

    
1794
	safe_mkdir($statsdir);
1795

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

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

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

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

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

    
1945
		$ntpcfg .= "{$ts} iburst maxpoll 9";
1946
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1947
			$ntpcfg .= ' prefer';
1948
		}
1949
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1950
			$ntpcfg .= ' noselect';
1951
		}
1952
		$ntpcfg .= "\n";
1953
	}
1954
	unset($ts);
1955

    
1956
	$ntpcfg .= "\n\n";
1957
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1958
		$ntpcfg .= "enable stats\n";
1959
		$ntpcfg .= 'statistics';
1960
		if (!empty($config['ntpd']['clockstats'])) {
1961
			$ntpcfg .= ' clockstats';
1962
		}
1963
		if (!empty($config['ntpd']['loopstats'])) {
1964
			$ntpcfg .= ' loopstats';
1965
		}
1966
		if (!empty($config['ntpd']['peerstats'])) {
1967
			$ntpcfg .= ' peerstats';
1968
		}
1969
		$ntpcfg .= "\n";
1970
	}
1971
	$ntpcfg .= "statsdir {$statsdir}\n";
1972
	$ntpcfg .= 'logconfig =syncall +clockall';
1973
	if (!empty($config['ntpd']['logpeer'])) {
1974
		$ntpcfg .= ' +peerall';
1975
	}
1976
	if (!empty($config['ntpd']['logsys'])) {
1977
		$ntpcfg .= ' +sysall';
1978
	}
1979
	$ntpcfg .= "\n";
1980
	$ntpcfg .= "driftfile {$driftfile}\n";
1981

    
1982
	/* Default Access restrictions */
1983
	$ntpcfg .= 'restrict default';
1984
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1985
		$ntpcfg .= ' kod limited';
1986
	}
1987
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1988
		$ntpcfg .= ' nomodify';
1989
	}
1990
	if (!empty($config['ntpd']['noquery'])) {
1991
		$ntpcfg .= ' noquery';
1992
	}
1993
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1994
		$ntpcfg .= ' nopeer';
1995
	}
1996
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1997
		$ntpcfg .= ' notrap';
1998
	}
1999
	if (!empty($config['ntpd']['noserve'])) {
2000
		$ntpcfg .= ' noserve';
2001
	}
2002
	$ntpcfg .= "\nrestrict -6 default";
2003
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2004
		$ntpcfg .= ' kod limited';
2005
	}
2006
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2007
		$ntpcfg .= ' nomodify';
2008
	}
2009
	if (!empty($config['ntpd']['noquery'])) {
2010
		$ntpcfg .= ' noquery';
2011
	}
2012
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2013
		$ntpcfg .= ' nopeer';
2014
	}
2015
	if (!empty($config['ntpd']['noserve'])) {
2016
		$ntpcfg .= ' noserve';
2017
	}
2018
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2019
		$ntpcfg .= ' notrap';
2020
	}
2021

    
2022
	/* Pools require "restrict source" and cannot contain "nopeer". */
2023
	if ($have_pools) {
2024
		$ntpcfg .= "\nrestrict source";
2025
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2026
			$ntpcfg .= ' kod limited';
2027
		}
2028
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2029
			$ntpcfg .= ' nomodify';
2030
		}
2031
		if (!empty($config['ntpd']['noquery'])) {
2032
			$ntpcfg .= ' noquery';
2033
		}
2034
		if (!empty($config['ntpd']['noserve'])) {
2035
			$ntpcfg .= ' noserve';
2036
		}
2037
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2038
			$ntpcfg .= ' notrap';
2039
		}
2040
	}
2041

    
2042
	/* Custom Access Restrictions */
2043
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2044
		$networkacl = $config['ntpd']['restrictions']['row'];
2045
		foreach ($networkacl as $acl) {
2046
			$restrict = "";
2047
			if (is_ipaddrv6($acl['acl_network'])) {
2048
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2049
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2050
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2051
			} else {
2052
				continue;
2053
			}
2054
			if (!empty($acl['kod'])) {
2055
				$restrict .= ' kod limited';
2056
			}
2057
			if (!empty($acl['nomodify'])) {
2058
				$restrict .= ' nomodify';
2059
			}
2060
			if (!empty($acl['noquery'])) {
2061
				$restrict .= ' noquery';
2062
			}
2063
			if (!empty($acl['nopeer'])) {
2064
				$restrict .= ' nopeer';
2065
			}
2066
			if (!empty($acl['noserve'])) {
2067
				$restrict .= ' noserve';
2068
			}
2069
			if (!empty($acl['notrap'])) {
2070
				$restrict .= ' notrap';
2071
			}
2072
			if (!empty($restrict)) {
2073
				$ntpcfg .= "\nrestrict {$restrict} ";
2074
			}
2075
		}
2076
	}
2077
	/* End Custom Access Restrictions */
2078

    
2079
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2080
	$ntpcfg .= "\n";
2081
	if (!empty($config['ntpd']['leapsec'])) {
2082
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2083
		file_put_contents('/var/db/leap-seconds', $leapsec);
2084
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2085
	}
2086

    
2087

    
2088
	if (empty($config['ntpd']['interface'])) {
2089
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2090
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2091
		} else {
2092
			$interfaces = array();
2093
		}
2094
	} else {
2095
		$interfaces = explode(",", $config['ntpd']['interface']);
2096
	}
2097

    
2098
	if (is_array($interfaces) && count($interfaces)) {
2099
		$finterfaces = array();
2100
		$ntpcfg .= "interface ignore all\n";
2101
		$ntpcfg .= "interface ignore wildcard\n";
2102
		foreach ($interfaces as $interface) {
2103
			$interface = get_real_interface($interface);
2104
			if (!empty($interface)) {
2105
				$finterfaces[] = $interface;
2106
			}
2107
		}
2108
		foreach ($finterfaces as $interface) {
2109
			$ntpcfg .= "interface listen {$interface}\n";
2110
		}
2111
	}
2112

    
2113
	/* open configuration for writing or bail */
2114
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2115
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2116
		return;
2117
	}
2118

    
2119
	/* if ntpd is running, kill it */
2120
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2121
		killbypid("{$g['varrun_path']}/ntpd.pid");
2122
	}
2123
	@unlink("{$g['varrun_path']}/ntpd.pid");
2124

    
2125
	/* if /var/empty does not exist, create it */
2126
	if (!is_dir("/var/empty")) {
2127
		mkdir("/var/empty", 0555, true);
2128
	}
2129

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

    
2133
	// Note that we are starting up
2134
	log_error("NTPD is starting up.");
2135
	return;
2136
}
2137

    
2138
function system_halt() {
2139
	global $g;
2140

    
2141
	system_reboot_cleanup();
2142

    
2143
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2144
}
2145

    
2146
function system_reboot() {
2147
	global $g;
2148

    
2149
	system_reboot_cleanup();
2150

    
2151
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2152
}
2153

    
2154
function system_reboot_sync($reroot=false) {
2155
	global $g;
2156

    
2157
	if ($reroot) {
2158
		$args = " -r ";
2159
	}
2160

    
2161
	system_reboot_cleanup();
2162

    
2163
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2164
}
2165

    
2166
function system_reboot_cleanup() {
2167
	global $config, $cpzone, $cpzoneid;
2168

    
2169
	mwexec("/usr/local/bin/beep.sh stop");
2170
	require_once("captiveportal.inc");
2171
	if (is_array($config['captiveportal'])) {
2172
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2173
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2174
			$cpzoneid = $cp[zoneid];
2175
			captiveportal_radius_stop_all(7); // Admin-Reboot
2176
			/* Send Accounting-Off packet to the RADIUS server */
2177
			captiveportal_send_server_accounting(true);
2178
		}
2179
	}
2180
	require_once("voucher.inc");
2181
	voucher_save_db_to_config();
2182
	require_once("pkg-utils.inc");
2183
	stop_packages();
2184
}
2185

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

    
2193
	if ($early) {
2194
		$cmdn = "earlyshellcmd";
2195
	} else {
2196
		$cmdn = "shellcmd";
2197
	}
2198

    
2199
	if (is_array($config['system'][$cmdn])) {
2200

    
2201
		/* *cmd is an array, loop through */
2202
		foreach ($config['system'][$cmdn] as $cmd) {
2203
			exec($cmd);
2204
		}
2205

    
2206
	} elseif ($config['system'][$cmdn] <> "") {
2207

    
2208
		/* execute single item */
2209
		exec($config['system'][$cmdn]);
2210

    
2211
	}
2212
}
2213

    
2214
function system_dmesg_save() {
2215
	global $g;
2216
	if (isset($config['system']['developerspew'])) {
2217
		$mt = microtime();
2218
		echo "system_dmesg_save() being called $mt\n";
2219
	}
2220

    
2221
	$dmesg = "";
2222
	$_gb = exec("/sbin/dmesg", $dmesg);
2223

    
2224
	/* find last copyright line (output from previous boots may be present) */
2225
	$lastcpline = 0;
2226

    
2227
	for ($i = 0; $i < count($dmesg); $i++) {
2228
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2229
			$lastcpline = $i;
2230
		}
2231
	}
2232

    
2233
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2234
	if (!$fd) {
2235
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2236
		return 1;
2237
	}
2238

    
2239
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2240
		fwrite($fd, $dmesg[$i] . "\n");
2241
	}
2242

    
2243
	fclose($fd);
2244
	unset($dmesg);
2245

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

    
2249
	return 0;
2250
}
2251

    
2252
function system_set_harddisk_standby() {
2253
	global $g, $config;
2254

    
2255
	if (isset($config['system']['developerspew'])) {
2256
		$mt = microtime();
2257
		echo "system_set_harddisk_standby() being called $mt\n";
2258
	}
2259

    
2260
	if (isset($config['system']['harddiskstandby'])) {
2261
		if (platform_booting()) {
2262
			echo gettext('Setting hard disk standby... ');
2263
		}
2264

    
2265
		$standby = $config['system']['harddiskstandby'];
2266
		// Check for a numeric value
2267
		if (is_numeric($standby)) {
2268
			// Get only suitable candidates for standby; using get_smart_drive_list()
2269
			// from utils.inc to get the list of drives.
2270
			$harddisks = get_smart_drive_list();
2271

    
2272
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2273
			// just in case of some weird pfSense platform installs.
2274
			if (count($harddisks) > 0) {
2275
				// Iterate disks and run the camcontrol command for each
2276
				foreach ($harddisks as $harddisk) {
2277
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2278
				}
2279
				if (platform_booting()) {
2280
					echo gettext("done.") . "\n";
2281
				}
2282
			} else if (platform_booting()) {
2283
				echo gettext("failed!") . "\n";
2284
			}
2285
		} else if (platform_booting()) {
2286
			echo gettext("failed!") . "\n";
2287
		}
2288
	}
2289
}
2290

    
2291
function system_setup_sysctl() {
2292
	global $config;
2293
	if (isset($config['system']['developerspew'])) {
2294
		$mt = microtime();
2295
		echo "system_setup_sysctl() being called $mt\n";
2296
	}
2297

    
2298
	activate_sysctls();
2299

    
2300
	if (isset($config['system']['sharednet'])) {
2301
		system_disable_arp_wrong_if();
2302
	}
2303
}
2304

    
2305
function system_disable_arp_wrong_if() {
2306
	global $config;
2307
	if (isset($config['system']['developerspew'])) {
2308
		$mt = microtime();
2309
		echo "system_disable_arp_wrong_if() being called $mt\n";
2310
	}
2311
	set_sysctl(array(
2312
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2313
		"net.link.ether.inet.log_arp_movements" => "0"
2314
	));
2315
}
2316

    
2317
function system_enable_arp_wrong_if() {
2318
	global $config;
2319
	if (isset($config['system']['developerspew'])) {
2320
		$mt = microtime();
2321
		echo "system_enable_arp_wrong_if() being called $mt\n";
2322
	}
2323
	set_sysctl(array(
2324
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2325
		"net.link.ether.inet.log_arp_movements" => "1"
2326
	));
2327
}
2328

    
2329
function enable_watchdog() {
2330
	global $config;
2331
	return;
2332
	$install_watchdog = false;
2333
	$supported_watchdogs = array("Geode");
2334
	$file = file_get_contents("/var/log/dmesg.boot");
2335
	foreach ($supported_watchdogs as $sd) {
2336
		if (stristr($file, "Geode")) {
2337
			$install_watchdog = true;
2338
		}
2339
	}
2340
	if ($install_watchdog == true) {
2341
		if (is_process_running("watchdogd")) {
2342
			mwexec("/usr/bin/killall watchdogd", true);
2343
		}
2344
		exec("/usr/sbin/watchdogd");
2345
	}
2346
}
2347

    
2348
function system_check_reset_button() {
2349
	global $g;
2350

    
2351
	$specplatform = system_identify_specific_platform();
2352

    
2353
	switch ($specplatform['name']) {
2354
		case 'alix':
2355
		case 'wrap':
2356
		case 'FW7541':
2357
		case 'APU':
2358
		case 'RCC-VE':
2359
		case 'RCC':
2360
		case 'SG-2220':
2361
			break;
2362
		default:
2363
			return 0;
2364
	}
2365

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

    
2368
	if ($retval == 99) {
2369
		/* user has pressed reset button for 2 seconds -
2370
		   reset to factory defaults */
2371
		echo <<<EOD
2372

    
2373
***********************************************************************
2374
* Reset button pressed - resetting configuration to factory defaults. *
2375
* All additional packages installed will be removed                   *
2376
* The system will reboot after this completes.                        *
2377
***********************************************************************
2378

    
2379

    
2380
EOD;
2381

    
2382
		reset_factory_defaults();
2383
		system_reboot_sync();
2384
		exit(0);
2385
	}
2386

    
2387
	return 0;
2388
}
2389

    
2390
function system_get_serial() {
2391
	$platform = system_identify_specific_platform();
2392

    
2393
	unset($output);
2394
	if ($platform['name'] == 'Turbot Dual-E') {
2395
		$if_info = pfSense_get_interface_addresses('igb0');
2396
		if (!empty($if_info['hwaddr'])) {
2397
			$serial = str_replace(":", "", $if_info['hwaddr']);
2398
		}
2399
	} else {
2400
		$_gb = exec('/bin/kenv smbios.system.serial 2>/dev/null', $output);
2401
		$serial = $output[0];
2402
	}
2403

    
2404
	$vm_guest = get_single_sysctl('kern.vm_guest');
2405

    
2406
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2407
	    $vm_guest == 'none') {
2408
		return $serial;
2409
	}
2410

    
2411
	return "";
2412
}
2413

    
2414
function system_get_uniqueid() {
2415
	global $g;
2416

    
2417
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2418

    
2419
	if (empty($g['uniqueid'])) {
2420
		if (!file_exists($uniqueid_file)) {
2421
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2422
			    "2>/dev/null");
2423
		}
2424
		if (file_exists($uniqueid_file)) {
2425
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2426
		}
2427
	}
2428

    
2429
	return ($g['uniqueid'] ?: '');
2430
}
2431

    
2432
/*
2433
 * attempt to identify the specific platform (for embedded systems)
2434
 * Returns an array with two elements:
2435
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2436
 * descr => human-readable description (e.g. "PC Engines WRAP")
2437
 */
2438
function system_identify_specific_platform() {
2439
	global $g;
2440

    
2441
	$hw_model = get_single_sysctl('hw.model');
2442
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2443

    
2444
	/* Try to guess from smbios strings */
2445
	unset($product);
2446
	unset($maker);
2447
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2448
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2449
	switch ($product[0]) {
2450
		case 'FW7541':
2451
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2452
			break;
2453
		case 'APU':
2454
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2455
			break;
2456
		case 'RCC-VE':
2457
			$result = array();
2458
			$result['name'] = 'RCC-VE';
2459

    
2460
			/* Detect specific models */
2461
			if (!function_exists('does_interface_exist')) {
2462
				require_once("interfaces.inc");
2463
			}
2464
			if (!does_interface_exist('igb4')) {
2465
				$result['model'] = 'SG-2440';
2466
			} elseif (strpos($hw_model, "C2558") !== false) {
2467
				$result['model'] = 'SG-4860';
2468
			} elseif (strpos($hw_model, "C2758") !== false) {
2469
				$result['model'] = 'SG-8860';
2470
			} else {
2471
				$result['model'] = 'RCC-VE';
2472
			}
2473
			$result['descr'] = 'Netgate ' . $result['model'];
2474
			return $result;
2475
			break;
2476
		case 'DFFv2':
2477
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2478
			break;
2479
		case 'RCC':
2480
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2481
			break;
2482
		case 'Minnowboard Turbot D0 PLATFORM':
2483
			$result = array();
2484
			$result['name'] = 'Turbot Dual-E';
2485
			/* Detect specific model */
2486
			switch ($hw_ncpu) {
2487
			case '4':
2488
				$result['model'] = 'SG-2340';
2489
				break;
2490
			case '2':
2491
				$result['model'] = 'SG-2320';
2492
				break;
2493
			default:
2494
				$result['model'] = $result['name'];
2495
				break;
2496
			}
2497
			$result['descr'] = 'Netgate ' . $result['model'];
2498
			return $result;
2499
			break;
2500
		case 'SYS-5018A-FTN4':
2501
		case 'A1SAi':
2502
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2503
			break;
2504
		case 'SYS-5018D-FN4T':
2505
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2506
			break;
2507
		case 'apu2':
2508
		case 'APU2':
2509
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2510
			break;
2511
		case 'VirtualBox':
2512
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2513
			break;
2514
		case 'Virtual Machine':
2515
			if ($maker[0] == "Microsoft Corporation") {
2516
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2517
			}
2518
			break;
2519
		case 'VMware Virtual Platform':
2520
			if ($maker[0] == "VMware, Inc.") {
2521
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2522
			}
2523
			break;
2524
	}
2525

    
2526
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2527
	    $planar_product);
2528
	if (isset($planar_product[0]) &&
2529
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2530
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2531
	}
2532

    
2533
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2534
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2535
	}
2536

    
2537
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2538
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2539
	}
2540

    
2541
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2542
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2543
	}
2544

    
2545
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2546
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2547
	}
2548

    
2549
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2550
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2551
	}
2552

    
2553
	unset($hw_model);
2554

    
2555
	$dmesg_boot = system_get_dmesg_boot();
2556
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2557
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2558
	}
2559
	unset($dmesg_boot);
2560

    
2561
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2562
}
2563

    
2564
function system_get_dmesg_boot() {
2565
	global $g;
2566

    
2567
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2568
}
2569

    
2570
?>
(48-48/60)