Project

General

Profile

Download (70.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-2016 Rubicon Communications, LLC (Netgate)
7
 * All rights reserved.
8
 *
9
 * originally part of m0n0wall (http://m0n0.ch/wall)
10
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
11
 * All rights reserved.
12
 *
13
 * Licensed under the Apache License, Version 2.0 (the "License");
14
 * you may not use this file except in compliance with the License.
15
 * You may obtain a copy of the License at
16
 *
17
 * http://www.apache.org/licenses/LICENSE-2.0
18
 *
19
 * Unless required by applicable law or agreed to in writing, software
20
 * distributed under the License is distributed on an "AS IS" BASIS,
21
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
 * See the License for the specific language governing permissions and
23
 * limitations under the License.
24
 */
25

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

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

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

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

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

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

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

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

    
64
	return $output[0];
65
}
66

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

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

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

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

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

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

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

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

    
112
	set_sysctl($sysctls);
113
}
114

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

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

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

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

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

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

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

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

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

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

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

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

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

    
228
	unlock($dnslock);
229

    
230
	return 0;
231
}
232

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

    
236
	$master_list = array();
237

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

    
254
	return $master_list;
255
}
256

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

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

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

    
289
	return $master_list;
290
}
291

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

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

    
298
	$hosts = array();
299
	$hosts[] = array(
300
	    'ipaddr' => '127.0.0.1',
301
	    'fqdn' => 'localhost.' . $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 (!empty($host['name'])) {
553
			$hosts .= "{$host['name']} ";
554
		}
555
		$hosts .= "{$host['fqdn']}";
556
		$hosts .= "\n";
557
	}
558
	unset($hosts_array);
559

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

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

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

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

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

    
590
	return 0;
591
}
592

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

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

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

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

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

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

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

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

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

    
657
	return $status;
658
}
659

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

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

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

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

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

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

    
773
	system_staticroutes_configure($interface, false);
774

    
775
	return 0;
776
}
777

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

    
781
	$filterdns_list = array();
782

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
902
	return 0;
903
}
904

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

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

    
917
	return;
918
}
919

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

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

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

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

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

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

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

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

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

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

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

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

    
1028
	$syslogd_extra = "";
1029
	if (isset($syslogcfg)) {
1030
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'olsrd', 'zebra', 'ospfd', 'bgpd', 'miniupnpd', 'filterlog');
1031
		$syslogconf = "";
1032
		if ($config['installedpackages']['package']) {
1033
			foreach ($config['installedpackages']['package'] as $package) {
1034
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1035
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1036
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1037
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1038
					}
1039
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1040
				}
1041
			}
1042
		}
1043
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1044
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
1045
		if (!isset($syslogcfg['disablelocallogging'])) {
1046
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1047
		}
1048
		if (isset($syslogcfg['routing'])) {
1049
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1050
		}
1051

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1259
	return $retval;
1260
}
1261

    
1262
function system_webgui_create_certificate() {
1263
	global $config, $g;
1264

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

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

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

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

    
1304
function system_webgui_start() {
1305
	global $config, $g;
1306

    
1307
	if (platform_booting()) {
1308
		echo gettext("Starting webConfigurator...");
1309
	}
1310

    
1311
	chdir($g['www_path']);
1312

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

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

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

    
1333
		if (!$config['system']['webgui']['port']) {
1334
			$portarg = "443";
1335
		}
1336
		$ca = ca_chain($cert);
1337
	}
1338

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

    
1344
	/* kill any running nginx */
1345
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1346

    
1347
	sleep(1);
1348

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

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

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

    
1362
	return $res;
1363
}
1364

    
1365
function system_generate_nginx_config($filename,
1366
	$cert,
1367
	$key,
1368
	$ca,
1369
	$pid_file,
1370
	$port = 80,
1371
	$document_root = "/usr/local/www/",
1372
	$cert_location = "cert.crt",
1373
	$key_location = "cert.key",
1374
	$captive_portal = false) {
1375

    
1376
	global $config, $g;
1377

    
1378
	if (isset($config['system']['developerspew'])) {
1379
		$mt = microtime();
1380
		echo "system_generate_nginx_config() being called $mt\n";
1381
	}
1382

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

    
1404
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1405
		if (empty($maxprocperip)) {
1406
			$maxprocperip = 10;
1407
		}
1408
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1409
	}
1410

    
1411
	if (empty($port)) {
1412
		$nginx_port = "80";
1413
	} else {
1414
		$nginx_port = $port;
1415
	}
1416

    
1417
	$memory = get_memory();
1418
	$realmem = $memory[1];
1419

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

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

    
1438
	$nginx_config = <<<EOD
1439
#
1440
# nginx configuration file
1441

    
1442
pid {$g['varrun_path']}/{$pid_file};
1443

    
1444
user  root wheel;
1445
worker_processes  {$max_procs};
1446

    
1447
EOD;
1448

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

    
1453
	$nginx_config .= <<<EOD
1454

    
1455
events {
1456
    worker_connections  1024;
1457
}
1458

    
1459
http {
1460
	include       /usr/local/etc/nginx/mime.types;
1461
	default_type  application/octet-stream;
1462
	add_header X-Frame-Options SAMEORIGIN;
1463
	server_tokens off;
1464

    
1465
	sendfile        on;
1466

    
1467
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1468

    
1469
EOD;
1470

    
1471
	if ($captive_portal !== false) {
1472
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1473
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1474
	} else {
1475
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1476
	}
1477

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

    
1508
	$nginx_config .= <<<EOD
1509

    
1510
		client_max_body_size 200m;
1511

    
1512
		gzip on;
1513
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1514

    
1515

    
1516
EOD;
1517

    
1518
	if ($captive_portal !== false) {
1519
		$nginx_config .= <<<EOD
1520
$captive_portal_maxprocperip
1521
$cp_hostcheck
1522
$cp_rewrite
1523
		log_not_found off;
1524

    
1525
EOD;
1526

    
1527
	}
1528

    
1529
	$nginx_config .= <<<EOD
1530
		root "{$document_root}";
1531
		location / {
1532
			index  index.php index.html index.htm;
1533
		}
1534

    
1535
		location ~ \.php$ {
1536
			try_files \$uri =404; #  This line closes a potential security hole
1537
			# ensuring users can't execute uploaded files
1538
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1539
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1540
			fastcgi_index  index.php;
1541
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1542
			# Fix httpoxy - https://httpoxy.org/#fix-now
1543
			fastcgi_param  HTTP_PROXY  "";
1544
			fastcgi_read_timeout 180;
1545
			include        /usr/local/etc/nginx/fastcgi_params;
1546
		}
1547
	}
1548

    
1549
EOD;
1550

    
1551
	$cert = str_replace("\r", "", $cert);
1552
	$key = str_replace("\r", "", $key);
1553

    
1554
	$cert = str_replace("\n\n", "\n", $cert);
1555
	$key = str_replace("\n\n", "\n", $key);
1556

    
1557
	if ($cert <> "" and $key <> "") {
1558
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1559
		if (!$fd) {
1560
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1561
			return 1;
1562
		}
1563
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1564
		if ($ca <> "") {
1565
			$cert_chain = $cert . "\n" . $ca;
1566
		} else {
1567
			$cert_chain = $cert;
1568
		}
1569
		fwrite($fd, $cert_chain);
1570
		fclose($fd);
1571
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1572
		if (!$fd) {
1573
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1574
			return 1;
1575
		}
1576
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1577
		fwrite($fd, $key);
1578
		fclose($fd);
1579
	}
1580

    
1581
	// Add HTTP to HTTPS redirect
1582
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1583
		if ($nginx_port != "443") {
1584
			$redirectport = ":{$nginx_port}";
1585
		}
1586
		$nginx_config .= <<<EOD
1587
	server {
1588
		listen 80;
1589
		listen [::]:80;
1590
		return 301 https://\$http_host$redirectport\$request_uri;
1591
	}
1592

    
1593
EOD;
1594
	}
1595

    
1596
	$nginx_config .= "}\n";
1597

    
1598
	$fd = fopen("{$filename}", "w");
1599
	if (!$fd) {
1600
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1601
		return 1;
1602
	}
1603
	fwrite($fd, $nginx_config);
1604
	fclose($fd);
1605

    
1606
	/* nginx will fail to start if this directory does not exist. */
1607
	safe_mkdir("/var/tmp/nginx/");
1608

    
1609
	return 0;
1610

    
1611
}
1612

    
1613
function system_get_timezone_list() {
1614
	global $g;
1615

    
1616
	$file_list = array_merge(
1617
		glob("/usr/share/zoneinfo/[A-Z]*"),
1618
		glob("/usr/share/zoneinfo/*/*"),
1619
		glob("/usr/share/zoneinfo/*/*/*")
1620
	);
1621

    
1622
	if (empty($file_list)) {
1623
		$file_list[] = $g['default_timezone'];
1624
	} else {
1625
		/* Remove directories from list */
1626
		$file_list = array_filter($file_list, function($v) {
1627
			return !is_dir($v);
1628
		});
1629
	}
1630

    
1631
	/* Remove directory prefix */
1632
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1633

    
1634
	sort($file_list);
1635

    
1636
	return $file_list;
1637
}
1638

    
1639
function system_timezone_configure() {
1640
	global $config, $g;
1641
	if (isset($config['system']['developerspew'])) {
1642
		$mt = microtime();
1643
		echo "system_timezone_configure() being called $mt\n";
1644
	}
1645

    
1646
	$syscfg = $config['system'];
1647

    
1648
	if (platform_booting()) {
1649
		echo gettext("Setting timezone...");
1650
	}
1651

    
1652
	/* extract appropriate timezone file */
1653
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1654
	/* DO NOT remove \n otherwise tzsetup will fail */
1655
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1656
	mwexec("/usr/sbin/tzsetup -r");
1657

    
1658
	if (platform_booting()) {
1659
		echo gettext("done.") . "\n";
1660
	}
1661
}
1662

    
1663
function system_ntp_setup_gps($serialport) {
1664
	global $config, $g;
1665
	$gps_device = '/dev/gps0';
1666
	$serialport = '/dev/'.$serialport;
1667

    
1668
	if (!file_exists($serialport)) {
1669
		return false;
1670
	}
1671

    
1672
	// Create symlink that ntpd requires
1673
	unlink_if_exists($gps_device);
1674
	@symlink($serialport, $gps_device);
1675

    
1676
	$gpsbaud = '4800';
1677
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1678
		switch ($config['ntpd']['gps']['speed']) {
1679
			case '16':
1680
				$gpsbaud = '9600';
1681
				break;
1682
			case '32':
1683
				$gpsbaud = '19200';
1684
				break;
1685
			case '48':
1686
				$gpsbaud = '38400';
1687
				break;
1688
			case '64':
1689
				$gpsbaud = '57600';
1690
				break;
1691
			case '80':
1692
				$gpsbaud = '115200';
1693
				break;
1694
		}
1695
	}
1696

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

    
1700
	/* Send the following to the GPS port to initialize the GPS */
1701
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1702
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1703
	} else {
1704
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1705
	}
1706

    
1707
	/* XXX: Why not file_put_contents to the device */
1708
	@file_put_contents('/tmp/gps.init', $gps_init);
1709
	mwexec("cat /tmp/gps.init > {$serialport}");
1710

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

    
1716

    
1717
	return true;
1718
}
1719

    
1720
function system_ntp_setup_pps($serialport) {
1721
	global $config, $g;
1722

    
1723
	$pps_device = '/dev/pps0';
1724
	$serialport = '/dev/'.$serialport;
1725

    
1726
	if (!file_exists($serialport)) {
1727
		return false;
1728
	}
1729

    
1730
	// Create symlink that ntpd requires
1731
	unlink_if_exists($pps_device);
1732
	@symlink($serialport, $pps_device);
1733

    
1734

    
1735
	return true;
1736
}
1737

    
1738

    
1739
function system_ntp_configure() {
1740
	global $config, $g;
1741

    
1742
	$driftfile = "/var/db/ntpd.drift";
1743
	$statsdir = "/var/log/ntp";
1744
	$gps_device = '/dev/gps0';
1745

    
1746
	safe_mkdir($statsdir);
1747

    
1748
	if (!is_array($config['ntpd'])) {
1749
		$config['ntpd'] = array();
1750
	}
1751

    
1752
	$ntpcfg = "# \n";
1753
	$ntpcfg .= "# pfSense ntp configuration file \n";
1754
	$ntpcfg .= "# \n\n";
1755
	$ntpcfg .= "tinker panic 0 \n";
1756

    
1757
	/* Add Orphan mode */
1758
	$ntpcfg .= "# Orphan mode stratum\n";
1759
	$ntpcfg .= 'tos orphan ';
1760
	if (!empty($config['ntpd']['orphan'])) {
1761
		$ntpcfg .= $config['ntpd']['orphan'];
1762
	} else {
1763
		$ntpcfg .= '12';
1764
	}
1765
	$ntpcfg .= "\n";
1766

    
1767
	/* Add PPS configuration */
1768
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1769
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1770
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1771
		$ntpcfg .= "\n";
1772
		$ntpcfg .= "# PPS Setup\n";
1773
		$ntpcfg .= 'server 127.127.22.0';
1774
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1775
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1776
			$ntpcfg .= ' prefer';
1777
		}
1778
		if (!empty($config['ntpd']['pps']['noselect'])) {
1779
			$ntpcfg .= ' noselect ';
1780
		}
1781
		$ntpcfg .= "\n";
1782
		$ntpcfg .= 'fudge 127.127.22.0';
1783
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1784
			$ntpcfg .= ' time1 ';
1785
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1786
		}
1787
		if (!empty($config['ntpd']['pps']['flag2'])) {
1788
			$ntpcfg .= ' flag2 1';
1789
		}
1790
		if (!empty($config['ntpd']['pps']['flag3'])) {
1791
			$ntpcfg .= ' flag3 1';
1792
		} else {
1793
			$ntpcfg .= ' flag3 0';
1794
		}
1795
		if (!empty($config['ntpd']['pps']['flag4'])) {
1796
			$ntpcfg .= ' flag4 1';
1797
		}
1798
		if (!empty($config['ntpd']['pps']['refid'])) {
1799
			$ntpcfg .= ' refid ';
1800
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1801
		}
1802
		$ntpcfg .= "\n";
1803
	}
1804
	/* End PPS configuration */
1805

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

    
1897
		$ntpcfg .= "{$ts} iburst maxpoll 9";
1898
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1899
			$ntpcfg .= ' prefer';
1900
		}
1901
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1902
			$ntpcfg .= ' noselect';
1903
		}
1904
		$ntpcfg .= "\n";
1905
	}
1906
	unset($ts);
1907

    
1908
	$ntpcfg .= "\n\n";
1909
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1910
		$ntpcfg .= "enable stats\n";
1911
		$ntpcfg .= 'statistics';
1912
		if (!empty($config['ntpd']['clockstats'])) {
1913
			$ntpcfg .= ' clockstats';
1914
		}
1915
		if (!empty($config['ntpd']['loopstats'])) {
1916
			$ntpcfg .= ' loopstats';
1917
		}
1918
		if (!empty($config['ntpd']['peerstats'])) {
1919
			$ntpcfg .= ' peerstats';
1920
		}
1921
		$ntpcfg .= "\n";
1922
	}
1923
	$ntpcfg .= "statsdir {$statsdir}\n";
1924
	$ntpcfg .= 'logconfig =syncall +clockall';
1925
	if (!empty($config['ntpd']['logpeer'])) {
1926
		$ntpcfg .= ' +peerall';
1927
	}
1928
	if (!empty($config['ntpd']['logsys'])) {
1929
		$ntpcfg .= ' +sysall';
1930
	}
1931
	$ntpcfg .= "\n";
1932
	$ntpcfg .= "driftfile {$driftfile}\n";
1933

    
1934
	/* Default Access restrictions */
1935
	$ntpcfg .= 'restrict default';
1936
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1937
		$ntpcfg .= ' kod limited';
1938
	}
1939
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1940
		$ntpcfg .= ' nomodify';
1941
	}
1942
	if (!empty($config['ntpd']['noquery'])) {
1943
		$ntpcfg .= ' noquery';
1944
	}
1945
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1946
		$ntpcfg .= ' nopeer';
1947
	}
1948
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1949
		$ntpcfg .= ' notrap';
1950
	}
1951
	if (!empty($config['ntpd']['noserve'])) {
1952
		$ntpcfg .= ' noserve';
1953
	}
1954
	$ntpcfg .= "\nrestrict -6 default";
1955
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1956
		$ntpcfg .= ' kod limited';
1957
	}
1958
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1959
		$ntpcfg .= ' nomodify';
1960
	}
1961
	if (!empty($config['ntpd']['noquery'])) {
1962
		$ntpcfg .= ' noquery';
1963
	}
1964
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1965
		$ntpcfg .= ' nopeer';
1966
	}
1967
	if (!empty($config['ntpd']['noserve'])) {
1968
		$ntpcfg .= ' noserve';
1969
	}
1970
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1971
		$ntpcfg .= ' notrap';
1972
	}
1973

    
1974
	/* Pools require "restrict source" and cannot contain "nopeer". */
1975
	if ($have_pools) {
1976
		$ntpcfg .= "\nrestrict source";
1977
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1978
			$ntpcfg .= ' kod limited';
1979
		}
1980
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1981
			$ntpcfg .= ' nomodify';
1982
		}
1983
		if (!empty($config['ntpd']['noquery'])) {
1984
			$ntpcfg .= ' noquery';
1985
		}
1986
		if (!empty($config['ntpd']['noserve'])) {
1987
			$ntpcfg .= ' noserve';
1988
		}
1989
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1990
			$ntpcfg .= ' notrap';
1991
		}
1992
	}
1993

    
1994
	/* Custom Access Restrictions */
1995
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1996
		$networkacl = $config['ntpd']['restrictions']['row'];
1997
		foreach ($networkacl as $acl) {
1998
			$restrict = "";
1999
			if (is_ipaddrv6($acl['acl_network'])) {
2000
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2001
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2002
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2003
			} else {
2004
				continue;
2005
			}
2006
			if (!empty($acl['kod'])) {
2007
				$restrict .= ' kod limited';
2008
			}
2009
			if (!empty($acl['nomodify'])) {
2010
				$restrict .= ' nomodify';
2011
			}
2012
			if (!empty($acl['noquery'])) {
2013
				$restrict .= ' noquery';
2014
			}
2015
			if (!empty($acl['nopeer'])) {
2016
				$restrict .= ' nopeer';
2017
			}
2018
			if (!empty($acl['noserve'])) {
2019
				$restrict .= ' noserve';
2020
			}
2021
			if (!empty($acl['notrap'])) {
2022
				$restrict .= ' notrap';
2023
			}
2024
			if (!empty($restrict)) {
2025
				$ntpcfg .= "\nrestrict {$restrict} ";
2026
			}
2027
		}
2028
	}
2029
	/* End Custom Access Restrictions */
2030

    
2031
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2032
	$ntpcfg .= "\n";
2033
	if (!empty($config['ntpd']['leapsec'])) {
2034
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2035
		file_put_contents('/var/db/leap-seconds', $leapsec);
2036
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2037
	}
2038

    
2039

    
2040
	if (empty($config['ntpd']['interface'])) {
2041
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2042
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2043
		} else {
2044
			$interfaces = array();
2045
		}
2046
	} else {
2047
		$interfaces = explode(",", $config['ntpd']['interface']);
2048
	}
2049

    
2050
	if (is_array($interfaces) && count($interfaces)) {
2051
		$finterfaces = array();
2052
		$ntpcfg .= "interface ignore all\n";
2053
		foreach ($interfaces as $interface) {
2054
			$interface = get_real_interface($interface);
2055
			if (!empty($interface)) {
2056
				$finterfaces[] = $interface;
2057
			}
2058
		}
2059
		foreach ($finterfaces as $interface) {
2060
			$ntpcfg .= "interface listen {$interface}\n";
2061
		}
2062
	}
2063

    
2064
	/* open configuration for writing or bail */
2065
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2066
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2067
		return;
2068
	}
2069

    
2070
	/* if ntpd is running, kill it */
2071
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2072
		killbypid("{$g['varrun_path']}/ntpd.pid");
2073
	}
2074
	@unlink("{$g['varrun_path']}/ntpd.pid");
2075

    
2076
	/* if /var/empty does not exist, create it */
2077
	if (!is_dir("/var/empty")) {
2078
		mkdir("/var/empty", 0555, true);
2079
	}
2080

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

    
2084
	// Note that we are starting up
2085
	log_error("NTPD is starting up.");
2086
	return;
2087
}
2088

    
2089
function system_halt() {
2090
	global $g;
2091

    
2092
	system_reboot_cleanup();
2093

    
2094
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2095
}
2096

    
2097
function system_reboot() {
2098
	global $g;
2099

    
2100
	system_reboot_cleanup();
2101

    
2102
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2103
}
2104

    
2105
function system_reboot_sync($reroot=false) {
2106
	global $g;
2107

    
2108
	if ($reroot) {
2109
		$args = " -r ";
2110
	}
2111

    
2112
	system_reboot_cleanup();
2113

    
2114
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2115
}
2116

    
2117
function system_reboot_cleanup() {
2118
	global $config, $cpzone, $cpzoneid;
2119

    
2120
	mwexec("/usr/local/bin/beep.sh stop");
2121
	require_once("captiveportal.inc");
2122
	if (is_array($config['captiveportal'])) {
2123
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2124
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2125
			$cpzoneid = $cp[zoneid];
2126
			captiveportal_radius_stop_all(7); // Admin-Reboot
2127
			/* Send Accounting-Off packet to the RADIUS server */
2128
			captiveportal_send_server_accounting(true);
2129
		}
2130
	}
2131
	require_once("voucher.inc");
2132
	voucher_save_db_to_config();
2133
	require_once("pkg-utils.inc");
2134
	stop_packages();
2135
}
2136

    
2137
function system_do_shell_commands($early = 0) {
2138
	global $config, $g;
2139
	if (isset($config['system']['developerspew'])) {
2140
		$mt = microtime();
2141
		echo "system_do_shell_commands() being called $mt\n";
2142
	}
2143

    
2144
	if ($early) {
2145
		$cmdn = "earlyshellcmd";
2146
	} else {
2147
		$cmdn = "shellcmd";
2148
	}
2149

    
2150
	if (is_array($config['system'][$cmdn])) {
2151

    
2152
		/* *cmd is an array, loop through */
2153
		foreach ($config['system'][$cmdn] as $cmd) {
2154
			exec($cmd);
2155
		}
2156

    
2157
	} elseif ($config['system'][$cmdn] <> "") {
2158

    
2159
		/* execute single item */
2160
		exec($config['system'][$cmdn]);
2161

    
2162
	}
2163
}
2164

    
2165
function system_dmesg_save() {
2166
	global $g;
2167
	if (isset($config['system']['developerspew'])) {
2168
		$mt = microtime();
2169
		echo "system_dmesg_save() being called $mt\n";
2170
	}
2171

    
2172
	$dmesg = "";
2173
	$_gb = exec("/sbin/dmesg", $dmesg);
2174

    
2175
	/* find last copyright line (output from previous boots may be present) */
2176
	$lastcpline = 0;
2177

    
2178
	for ($i = 0; $i < count($dmesg); $i++) {
2179
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2180
			$lastcpline = $i;
2181
		}
2182
	}
2183

    
2184
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2185
	if (!$fd) {
2186
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2187
		return 1;
2188
	}
2189

    
2190
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2191
		fwrite($fd, $dmesg[$i] . "\n");
2192
	}
2193

    
2194
	fclose($fd);
2195
	unset($dmesg);
2196

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

    
2200
	return 0;
2201
}
2202

    
2203
function system_set_harddisk_standby() {
2204
	global $g, $config;
2205

    
2206
	if (isset($config['system']['developerspew'])) {
2207
		$mt = microtime();
2208
		echo "system_set_harddisk_standby() being called $mt\n";
2209
	}
2210

    
2211
	if (isset($config['system']['harddiskstandby'])) {
2212
		if (platform_booting()) {
2213
			echo gettext('Setting hard disk standby... ');
2214
		}
2215

    
2216
		$standby = $config['system']['harddiskstandby'];
2217
		// Check for a numeric value
2218
		if (is_numeric($standby)) {
2219
			// Get only suitable candidates for standby; using get_smart_drive_list()
2220
			// from utils.inc to get the list of drives.
2221
			$harddisks = get_smart_drive_list();
2222

    
2223
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2224
			// just in case of some weird pfSense platform installs.
2225
			if (count($harddisks) > 0) {
2226
				// Iterate disks and run the camcontrol command for each
2227
				foreach ($harddisks as $harddisk) {
2228
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2229
				}
2230
				if (platform_booting()) {
2231
					echo gettext("done.") . "\n";
2232
				}
2233
			} else if (platform_booting()) {
2234
				echo gettext("failed!") . "\n";
2235
			}
2236
		} else if (platform_booting()) {
2237
			echo gettext("failed!") . "\n";
2238
		}
2239
	}
2240
}
2241

    
2242
function system_setup_sysctl() {
2243
	global $config;
2244
	if (isset($config['system']['developerspew'])) {
2245
		$mt = microtime();
2246
		echo "system_setup_sysctl() being called $mt\n";
2247
	}
2248

    
2249
	activate_sysctls();
2250

    
2251
	if (isset($config['system']['sharednet'])) {
2252
		system_disable_arp_wrong_if();
2253
	}
2254
}
2255

    
2256
function system_disable_arp_wrong_if() {
2257
	global $config;
2258
	if (isset($config['system']['developerspew'])) {
2259
		$mt = microtime();
2260
		echo "system_disable_arp_wrong_if() being called $mt\n";
2261
	}
2262
	set_sysctl(array(
2263
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2264
		"net.link.ether.inet.log_arp_movements" => "0"
2265
	));
2266
}
2267

    
2268
function system_enable_arp_wrong_if() {
2269
	global $config;
2270
	if (isset($config['system']['developerspew'])) {
2271
		$mt = microtime();
2272
		echo "system_enable_arp_wrong_if() being called $mt\n";
2273
	}
2274
	set_sysctl(array(
2275
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2276
		"net.link.ether.inet.log_arp_movements" => "1"
2277
	));
2278
}
2279

    
2280
function enable_watchdog() {
2281
	global $config;
2282
	return;
2283
	$install_watchdog = false;
2284
	$supported_watchdogs = array("Geode");
2285
	$file = file_get_contents("/var/log/dmesg.boot");
2286
	foreach ($supported_watchdogs as $sd) {
2287
		if (stristr($file, "Geode")) {
2288
			$install_watchdog = true;
2289
		}
2290
	}
2291
	if ($install_watchdog == true) {
2292
		if (is_process_running("watchdogd")) {
2293
			mwexec("/usr/bin/killall watchdogd", true);
2294
		}
2295
		exec("/usr/sbin/watchdogd");
2296
	}
2297
}
2298

    
2299
function system_check_reset_button() {
2300
	global $g;
2301

    
2302
	$specplatform = system_identify_specific_platform();
2303

    
2304
	switch ($specplatform['name']) {
2305
		case 'alix':
2306
		case 'wrap':
2307
		case 'FW7541':
2308
		case 'APU':
2309
		case 'RCC-VE':
2310
		case 'RCC':
2311
		case 'RCC-DFF':
2312
			break;
2313
		default:
2314
			return 0;
2315
	}
2316

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

    
2319
	if ($retval == 99) {
2320
		/* user has pressed reset button for 2 seconds -
2321
		   reset to factory defaults */
2322
		echo <<<EOD
2323

    
2324
***********************************************************************
2325
* Reset button pressed - resetting configuration to factory defaults. *
2326
* All additional packages installed will be removed                   *
2327
* The system will reboot after this completes.                        *
2328
***********************************************************************
2329

    
2330

    
2331
EOD;
2332

    
2333
		reset_factory_defaults();
2334
		system_reboot_sync();
2335
		exit(0);
2336
	}
2337

    
2338
	return 0;
2339
}
2340

    
2341
function system_get_serial() {
2342
	$platform = system_identify_specific_platform();
2343

    
2344
	unset($output);
2345
	if ($platform['name'] == 'Turbot Dual-E') {
2346
		$if_info = pfSense_get_interface_addresses('igb0');
2347
		if (!empty($if_info['hwaddr'])) {
2348
			$serial = str_replace(":", "", $if_info['hwaddr']);
2349
		}
2350
	} else {
2351
		$_gb = exec('/bin/kenv smbios.system.serial 2>/dev/null', $output);
2352
		$serial = $output[0];
2353
	}
2354

    
2355
	$vm_guest = get_single_sysctl('kern.vm_guest');
2356

    
2357
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2358
	    $vm_guest == 'none') {
2359
		return $serial;
2360
	}
2361

    
2362
	return get_single_sysctl('kern.hostuuid');
2363
}
2364

    
2365
function system_get_uniqueid() {
2366
	global $g;
2367

    
2368
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2369

    
2370
	if (empty($g['uniqueid'])) {
2371
		if (!file_exists($uniqueid_file)) {
2372
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2373
			    "2>/dev/null");
2374
		}
2375
		if (file_exists($uniqueid_file)) {
2376
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2377
		}
2378
	}
2379

    
2380
	return ($g['uniqueid'] ?: '');
2381
}
2382

    
2383
/*
2384
 * attempt to identify the specific platform (for embedded systems)
2385
 * Returns an array with two elements:
2386
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2387
 * descr => human-readable description (e.g. "PC Engines WRAP")
2388
 */
2389
function system_identify_specific_platform() {
2390
	global $g;
2391

    
2392
	$hw_model = get_single_sysctl('hw.model');
2393
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2394

    
2395
	/* Try to guess from smbios strings */
2396
	unset($product);
2397
	unset($maker);
2398
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2399
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2400
	switch ($product[0]) {
2401
		case 'FW7541':
2402
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2403
			break;
2404
		case 'APU':
2405
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2406
			break;
2407
		case 'RCC-VE':
2408
			$result = array();
2409
			$result['name'] = 'RCC-VE';
2410

    
2411
			/* Detect specific models */
2412
			if (!function_exists('does_interface_exist')) {
2413
				require_once("interfaces.inc");
2414
			}
2415
			if (!does_interface_exist('igb4')) {
2416
				$result['model'] = 'SG-2440';
2417
			} elseif (strpos($hw_model, "C2558") !== false) {
2418
				$result['model'] = 'SG-4860';
2419
			} elseif (strpos($hw_model, "C2758") !== false) {
2420
				$result['model'] = 'SG-8860';
2421
			} else {
2422
				$result['model'] = 'RCC-VE';
2423
			}
2424
			$result['descr'] = 'Netgate ' . $result['model'];
2425
			return $result;
2426
			break;
2427
		case 'DFFv2':
2428
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2429
			break;
2430
		case 'RCC':
2431
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2432
			break;
2433
		case 'Minnowboard Turbot D0 PLATFORM':
2434
			$result = array();
2435
			$result['name'] = 'Turbot Dual-E';
2436
			/* Detect specific model */
2437
			switch ($hw_ncpu) {
2438
			case '4':
2439
				$result['model'] = 'SG-2340';
2440
				break;
2441
			case '2':
2442
				$result['model'] = 'SG-2320';
2443
				break;
2444
			default:
2445
				$result['model'] = $result['name'];
2446
				break;
2447
			}
2448
			$result['descr'] = 'Netgate ' . $result['model'];
2449
			return $result;
2450
			break;
2451
		case 'SYS-5018A-FTN4':
2452
		case 'A1SAi':
2453
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2454
			break;
2455
		case 'SYS-5018D-FN4T':
2456
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2457
			break;
2458
		case 'apu2':
2459
		case 'APU2':
2460
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2461
			break;
2462
		case 'Virtual Machine':
2463
			if ($maker[0] == "Microsoft Corporation") {
2464
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2465
			}
2466
			break;
2467
		case 'VMware Virtual Platform':
2468
			if ($maker[0] == "VMware, Inc.") {
2469
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2470
			}
2471
			break;
2472
	}
2473

    
2474
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2475
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2476
	}
2477

    
2478
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2479
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2480
	}
2481

    
2482
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2483
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2484
	}
2485

    
2486
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2487
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2488
	}
2489

    
2490
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2491
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2492
	}
2493

    
2494
	unset($hw_model);
2495

    
2496
	$dmesg_boot = system_get_dmesg_boot();
2497
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2498
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2499
	}
2500
	unset($dmesg_boot);
2501

    
2502
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2503
}
2504

    
2505
function system_get_dmesg_boot() {
2506
	global $g;
2507

    
2508
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2509
}
2510

    
2511
?>
(43-43/54)