Project

General

Profile

Download (71.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-2020 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" .
49
			" -b " . escapeshellarg($battery_mode) .
50
			" -a " . escapeshellarg($ac_mode) .
51
			" -n " . escapeshellarg($normal_mode));
52
	}
53
}
54

    
55
function get_default_sysctl_value($id) {
56
	global $sysctls;
57

    
58
	if (isset($sysctls[$id])) {
59
		return $sysctls[$id];
60
	}
61
}
62

    
63
function get_sysctl_descr($sysctl) {
64
	unset($output);
65
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
66

    
67
	return $output[0];
68
}
69

    
70
function system_get_sysctls() {
71
	global $config, $sysctls;
72

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

    
83
			$disp_sysctl[$id] = $tunable;
84
			$disp_sysctl[$id]['modified'] = true;
85
			$disp_cache[$tunable['tunable']] = 'set';
86
		}
87
	}
88

    
89
	foreach ($sysctls as $sysctl => $value) {
90
		if (isset($disp_cache[$sysctl])) {
91
			continue;
92
		}
93

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

    
100
function activate_sysctls() {
101
	global $config, $g, $sysctls;
102

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

    
111
			$sysctls[$tunable['tunable']] = $value;
112
		}
113
	}
114

    
115
	set_sysctl($sysctls);
116
}
117

    
118
function system_resolvconf_generate($dynupdate = false) {
119
	global $config, $g;
120

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

    
126
	$syscfg = $config['system'];
127

    
128
	foreach(get_dns_nameservers() as $dns_ns) {
129
		$resolvconf .= "nameserver $dns_ns\n";
130
	}
131

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

    
149
	// Add EDNS support
150
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
151
		$resolvconf .= "options edns0\n";
152
	}
153

    
154
	$dnslock = lock('resolvconf', LOCK_EX);
155

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

    
163
	fwrite($fd, $resolvconf);
164
	fclose($fd);
165

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

    
175
	if (!platform_booting()) {
176
		/* restart dhcpd (nameservers may have changed) */
177
		if (!$dynupdate) {
178
			services_dhcpd_configure();
179
		}
180
	}
181

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

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

    
210
	unlock($dnslock);
211

    
212
	return 0;
213
}
214

    
215
function get_searchdomains() {
216
	global $config, $g;
217

    
218
	$master_list = array();
219

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

    
236
	return $master_list;
237
}
238

    
239
function get_nameservers() {
240
	global $config, $g;
241
	$master_list = array();
242

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

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

    
271
	return $master_list;
272
}
273

    
274
/* Create localhost + local interfaces entries for /etc/hosts */
275
function system_hosts_local_entries() {
276
	global $config;
277

    
278
	$syscfg = $config['system'];
279

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

    
294
	if ($config['interfaces']['lan']) {
295
		$sysiflist = array('lan' => "lan");
296
	} else {
297
		$sysiflist = get_configured_interface_list();
298
	}
299

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

    
333
	return $hosts;
334
}
335

    
336
/* Read host override entries from dnsmasq or unbound */
337
function system_hosts_override_entries($dnscfg) {
338
	$hosts = array();
339

    
340
	if (!is_array($dnscfg) ||
341
	    !is_array($dnscfg['hosts']) ||
342
	    !isset($dnscfg['enable'])) {
343
		return $hosts;
344
	}
345

    
346
	foreach ($dnscfg['hosts'] as $host) {
347
		$fqdn = '';
348
		if ($host['host'] || $host['host'] == "0") {
349
			$fqdn .= "{$host['host']}.";
350
		}
351
		$fqdn .= $host['domain'];
352

    
353
		$hosts[] = array(
354
		    'ipaddr' => $host['ip'],
355
		    'fqdn' => $fqdn,
356
		    'name' => $host['host'],
357
		    'domain' => $host['domain']
358
		);
359

    
360
		if (!is_array($host['aliases']) ||
361
		    !is_array($host['aliases']['item'])) {
362
			continue;
363
		}
364

    
365
		foreach ($host['aliases']['item'] as $alias) {
366
			$fqdn = '';
367
			if ($alias['host'] || $alias['host'] == "0") {
368
				$fqdn .= "{$alias['host']}.";
369
			}
370
			$fqdn .= $alias['domain'];
371

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

    
381
	return $hosts;
382
}
383

    
384
/* Read all dhcpd/dhcpdv6 staticmap entries */
385
function system_hosts_dhcpd_entries() {
386
	global $config;
387

    
388
	$hosts = array();
389
	$syscfg = $config['system'];
390

    
391
	if (is_array($config['dhcpd'])) {
392
		$conf_dhcpd = $config['dhcpd'];
393
	} else {
394
		$conf_dhcpd = array();
395
	}
396

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

    
408
			$fqdn = $host['hostname'] . ".";
409
			$domain = "";
410
			if ($host['domain']) {
411
				$domain = $host['domain'];
412
			} elseif ($dhcpifconf['domain']) {
413
				$domain = $dhcpifconf['domain'];
414
			} else {
415
				$domain = $syscfg['domain'];
416
			}
417

    
418
			$hosts[] = array(
419
			    'ipaddr' => $host['ipaddr'],
420
			    'fqdn' => $fqdn . $domain,
421
			    'name' => $host['hostname'],
422
			    'domain' => $domain
423
			);
424
		}
425
	}
426
	unset($conf_dhcpd);
427

    
428
	if (is_array($config['dhcpdv6'])) {
429
		$conf_dhcpdv6 = $config['dhcpdv6'];
430
	} else {
431
		$conf_dhcpdv6 = array();
432
	}
433

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

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

    
448
		foreach ($dhcpifconf['staticmap'] as $host) {
449
			$ipaddrv6 = $host['ipaddrv6'];
450

    
451
			if (!$ipaddrv6 || !$host['hostname']) {
452
				continue;
453
			}
454

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

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

    
475
			$hosts[] = array(
476
			    'ipaddr' => $ipaddrv6,
477
			    'fqdn' => $fqdn . $domain,
478
			    'name' => $host['hostname'],
479
			    'domain' => $domain
480
			);
481
		}
482
	}
483
	unset($conf_dhcpdv6);
484

    
485
	return $hosts;
486
}
487

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

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

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

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

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

    
526
	$syscfg = $config['system'];
527
	$hosts = "";
528
	$lhosts = "";
529
	$dhosts = "";
530

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

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

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

    
560
	fwrite($fd, $hosts);
561
	fclose($fd);
562

    
563
	if (isset($config['unbound']['enable'])) {
564
		require_once("unbound.inc");
565
		unbound_hosts_generate();
566
	}
567

    
568
	/* restart dhcpleases */
569
	if (!platform_booting()) {
570
		system_dhcpleases_configure();
571
	}
572

    
573
	return 0;
574
}
575

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

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

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

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

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

    
624
function system_hostname_configure() {
625
	global $config, $g;
626
	if (isset($config['system']['developerspew'])) {
627
		$mt = microtime();
628
		echo "system_hostname_configure() being called $mt\n";
629
	}
630

    
631
	$syscfg = $config['system'];
632

    
633
	/* set hostname */
634
	$status = mwexec("/bin/hostname " .
635
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
636

    
637
	/* Setup host GUID ID.  This is used by ZFS. */
638
	mwexec("/etc/rc.d/hostid start");
639

    
640
	return $status;
641
}
642

    
643
function system_routing_configure($interface = "") {
644
	global $config, $g;
645

    
646
	if (isset($config['system']['developerspew'])) {
647
		$mt = microtime();
648
		echo "system_routing_configure() being called $mt\n";
649
	}
650

    
651
	$gateways_arr = return_gateways_array(false, true);
652
	foreach ($gateways_arr as $gateway) {
653
		// setup static interface routes for nonlocal gateways
654
		if (isset($gateway["nonlocalgateway"])) {
655
			$srgatewayip = $gateway['gateway'];
656
			$srinterfacegw = $gateway['interface'];
657
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
658
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
659
				route_add_or_change("{$inet} {$srgatewayip} " .
660
				    "-iface {$srinterfacegw}");
661
			}
662
		}
663
	}
664

    
665
	$gateways_status = return_gateways_status(true);
666
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
667
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
668

    
669
	system_staticroutes_configure($interface, false);
670

    
671
	return 0;
672
}
673

    
674
function system_staticroutes_configure($interface = "", $update_dns = false) {
675
	global $config, $g, $aliastable;
676

    
677
	$filterdns_list = array();
678

    
679
	$static_routes = get_staticroutes(false, true);
680
	if (count($static_routes)) {
681
		$gateways_arr = return_gateways_array(false, true);
682

    
683
		foreach ($static_routes as $rtent) {
684
			if (empty($gateways_arr[$rtent['gateway']])) {
685
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
686
				continue;
687
			}
688
			$gateway = $gateways_arr[$rtent['gateway']];
689
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
690
				continue;
691
			}
692

    
693
			$gatewayip = $gateway['gateway'];
694
			$interfacegw = $gateway['interface'];
695

    
696
			$blackhole = "";
697
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
698
				$blackhole = "-blackhole";
699
			}
700

    
701
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
702
				continue;
703
			}
704

    
705
			$dnscache = array();
706
			if ($update_dns === true) {
707
				if (is_subnet($rtent['network'])) {
708
					continue;
709
				}
710
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
711
				if (empty($dnscache)) {
712
					continue;
713
				}
714
			}
715

    
716
			if (is_subnet($rtent['network'])) {
717
				$ips = array($rtent['network']);
718
			} else {
719
				if (!isset($rtent['disabled'])) {
720
					$filterdns_list[] = $rtent['network'];
721
				}
722
				$ips = add_hostname_to_watch($rtent['network']);
723
			}
724

    
725
			foreach ($dnscache as $ip) {
726
				if (in_array($ip, $ips)) {
727
					continue;
728
				}
729
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
730
				if (isset($config['system']['route-debug'])) {
731
					$mt = microtime();
732
					log_error("ROUTING debug: $mt - route delete $ip ");
733
				}
734
			}
735

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

    
748
			foreach ($ips as $ip) {
749
				if (is_ipaddrv4($ip)) {
750
					$ip .= "/32";
751
				}
752
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
753

    
754
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
755

    
756
				$cmd = "{$inet} {$blackhole} {$ip} ";
757

    
758
				if (is_subnet($ip)) {
759
					if (is_ipaddr($gatewayip)) {
760
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
761
							// add interface scope for link local v6 routes
762
							$gatewayip .= "%$interfacegw";
763
						}
764
						route_add_or_change($cmd . $gatewayip);
765
					} else if (!empty($interfacegw)) {
766
						route_add_or_change($cmd . "-iface {$interfacegw}");
767
					}
768
				}
769
			}
770
		}
771
		unset($gateways_arr);
772
	}
773
	unset($static_routes);
774

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

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

    
798
	return 0;
799
}
800

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

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

    
813
	return;
814
}
815

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

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

    
845
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
846
	global $config, $g;
847

    
848
	if ($restart_syslogd) {
849
		/* syslogd does not react well to clog rewriting the file while it is running. */
850
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
851
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
852
		}
853
	}
854
	if (isset($config['system']['disablesyslogclog'])) {
855
		unlink($logfile);
856
		touch($logfile);
857
	} else {
858
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
859
		$log_size = ($log_size < (2**32)/2) ? $log_size : "511488";
860
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
861
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
862
	}
863
	if ($restart_syslogd) {
864
		system_syslogd_start();
865
	}
866
	// Bug #6915
867
	if ($logfile == "/var/log/resolver.log") {
868
		services_unbound_configure(true);
869
	}
870
}
871

    
872
function clear_all_log_files($restart = false) {
873
	global $g;
874
	if ($restart) {
875
		/* syslogd does not react well to clog rewriting the file while it is running. */
876
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
877
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
878
		}
879
	}
880

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

    
886
	if ($restart) {
887
		system_syslogd_start();
888
		killbyname("dhcpd");
889
		if (!function_exists('services_dhcpd_configure')) {
890
			require_once('services.inc');
891
		}
892
		services_dhcpd_configure();
893
		// Bug #6915
894
		services_unbound_configure(false);
895
	}
896
	return;
897
}
898

    
899
function system_syslogd_start($sighup = false) {
900
	global $config, $g;
901
	if (isset($config['system']['developerspew'])) {
902
		$mt = microtime();
903
		echo "system_syslogd_start() being called $mt\n";
904
	}
905

    
906
	mwexec("/etc/rc.d/hostid start");
907

    
908
	$syslogcfg = $config['syslog'];
909

    
910
	if (platform_booting()) {
911
		echo gettext("Starting syslog...");
912
	}
913

    
914
	// Which logging type are we using this week??
915
	if (isset($config['system']['disablesyslogclog'])) {
916
		$log_directive = "";
917
		$log_create_directive = "/usr/bin/touch ";
918
		$log_size = "";
919
	} else { // Defaults to CLOG
920
		$log_directive = "%";
921
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
922
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
923
	}
924

    
925
	$syslogd_extra = "";
926
	if (isset($syslogcfg)) {
927
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'zebra', 'ospfd', 'ospf6d', 'bgpd', 'miniupnpd', 'igmpproxy', 'filterlog');
928
		$syslogconf = "";
929
		if ($config['installedpackages']['package']) {
930
			foreach ($config['installedpackages']['package'] as $package) {
931
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
932
					array_push($separatelogfacilities, $package['logging']['facilityname']);
933
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
934
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
935
					}
936
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
937
				}
938
			}
939
		}
940
		$facilitylist = implode(',', array_unique($separatelogfacilities));
941
		$syslogconf .= "!radvd,routed,zebra,ospfd,ospf6d,bgpd,miniupnpd,igmpproxy\n";
942
		if (!isset($syslogcfg['disablelocallogging'])) {
943
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
944
		}
945
		if (isset($syslogcfg['routing'])) {
946
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
947
		}
948

    
949
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
950
		if (!isset($syslogcfg['disablelocallogging'])) {
951
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
952
		}
953
		if (isset($syslogcfg['ntpd'])) {
954
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
955
		}
956

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

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

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

    
981
		$syslogconf .= "!charon,ipsec_starter\n";
982
		if (!isset($syslogcfg['disablelocallogging'])) {
983
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
984
		}
985
		if (isset($syslogcfg['vpn'])) {
986
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
987
		}
988

    
989
		$syslogconf .= "!openvpn\n";
990
		if (!isset($syslogcfg['disablelocallogging'])) {
991
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
992
		}
993
		if (isset($syslogcfg['vpn'])) {
994
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
995
		}
996

    
997
		$syslogconf .= "!dpinger\n";
998
		if (!isset($syslogcfg['disablelocallogging'])) {
999
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
1000
		}
1001
		if (isset($syslogcfg['dpinger'])) {
1002
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1003
		}
1004

    
1005
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1006
		if (!isset($syslogcfg['disablelocallogging'])) {
1007
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1008
		}
1009
		if (isset($syslogcfg['resolver'])) {
1010
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1011
		}
1012

    
1013
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
1014
		if (!isset($syslogcfg['disablelocallogging'])) {
1015
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
1016
		}
1017
		if (isset($syslogcfg['dhcp'])) {
1018
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1019
		}
1020

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

    
1029
		$syslogconf .= "!hostapd\n";
1030
		if (!isset($syslogcfg['disablelocallogging'])) {
1031
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
1032
		}
1033
		if (isset($syslogcfg['hostapd'])) {
1034
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1035
		}
1036

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

    
1045
		$syslogconf .= "!-{$facilitylist}\n";
1046
		if (!isset($syslogcfg['disablelocallogging'])) {
1047
			$syslogconf .= <<<EOD
1048
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1049
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1050
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1051
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1052
*.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
1053
auth.info;authpriv.info 					|exec /usr/local/sbin/sshguard
1054
*.emerg								*
1055

    
1056
EOD;
1057
		}
1058
		if (isset($syslogcfg['vpn'])) {
1059
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1060
		}
1061
		if (isset($syslogcfg['portalauth'])) {
1062
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1063
		}
1064
		if (isset($syslogcfg['dhcp'])) {
1065
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1066
		}
1067
		if (isset($syslogcfg['system'])) {
1068
			$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");
1069
		}
1070
		if (isset($syslogcfg['logall'])) {
1071
			// Make everything mean everything, including facilities excluded above.
1072
			$syslogconf .= "!*\n";
1073
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1074
		}
1075

    
1076
		if (isset($syslogcfg['zmqserver'])) {
1077
				$syslogconf .= <<<EOD
1078
*.*								^{$syslogcfg['zmqserver']}
1079

    
1080
EOD;
1081
		}
1082
		/* write syslog.conf */
1083
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1084
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1085
			unset($syslogconf);
1086
			return 1;
1087
		}
1088
		unset($syslogconf);
1089

    
1090
		$sourceip = "";
1091
		if (!empty($syslogcfg['sourceip'])) {
1092
			if ($syslogcfg['ipproto'] == "ipv6") {
1093
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1094
				if (!is_ipaddr($ifaddr)) {
1095
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1096
				}
1097
			} else {
1098
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1099
				if (!is_ipaddr($ifaddr)) {
1100
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1101
				}
1102
			}
1103
			if (is_ipaddr($ifaddr)) {
1104
				$sourceip = "-b {$ifaddr}";
1105
			}
1106
		}
1107

    
1108
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1109
	}
1110

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

    
1113
	if (isset($config['installedpackages']['package'])) {
1114
		foreach ($config['installedpackages']['package'] as $package) {
1115
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1116
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1117
				$log_sockets[] = $package['logging']['logsocket'];
1118
			}
1119
		}
1120
	}
1121

    
1122
	$syslogd_sockets = "";
1123
	foreach ($log_sockets as $log_socket) {
1124
		// Ensure that the log directory exists
1125
		$logpath = dirname($log_socket);
1126
		safe_mkdir($logpath);
1127
		$syslogd_sockets .= " -l {$log_socket}";
1128
	}
1129

    
1130
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1131
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1132
		$sighup = false;
1133
	}
1134

    
1135
	$sshguard_whitelist = array();
1136
	if (!empty($config['system']['sshguard_whitelist'])) {
1137
		$sshguard_whitelist = explode(' ',
1138
		    $config['system']['sshguard_whitelist']);
1139
	}
1140

    
1141
	$sshguard_config = array();
1142
	$sshguard_config[] = 'BACKEND="/usr/local/libexec/sshg-fw-pf"' . "\n";
1143
	if (!empty($config['system']['sshguard_threshold'])) {
1144
		$sshguard_config[] = 'THRESHOLD=' .
1145
		    $config['system']['sshguard_threshold'] . "\n";
1146
	}
1147
	if (!empty($config['system']['sshguard_blocktime'])) {
1148
		$sshguard_config[] = 'BLOCK_TIME=' .
1149
		    $config['system']['sshguard_blocktime'] . "\n";
1150
	}
1151
	if (!empty($config['system']['sshguard_detection_time'])) {
1152
		$sshguard_config[] = 'DETECTION_TIME=' .
1153
		    $config['system']['sshguard_detection_time'] . "\n";
1154
	}
1155
	if (!empty($sshguard_whitelist)) {
1156
		@file_put_contents("/usr/local/etc/sshguard.whitelist",
1157
		    implode(PHP_EOL, $sshguard_whitelist));
1158
		$sshguard_config[] =
1159
		    'WHITELIST_FILE=/usr/local/etc/sshguard.whitelist' . "\n";
1160
	} else {
1161
		unlink_if_exists("/usr/local/etc/sshguard.whitelist");
1162
	}
1163
	file_put_contents("/usr/local/etc/sshguard.conf", $sshguard_config);
1164

    
1165
	if (!$sighup) {
1166
		sigkillbyname("sshguard", "TERM");
1167
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1168
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1169
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1170
		}
1171

    
1172
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1173
			// if it still hasn't responded to the TERM, KILL it.
1174
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1175
			usleep(100000);
1176
		}
1177

    
1178
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1179
	} else {
1180
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1181
	}
1182

    
1183
	if (platform_booting()) {
1184
		echo gettext("done.") . "\n";
1185
	}
1186

    
1187
	return $retval;
1188
}
1189

    
1190
function system_webgui_create_certificate() {
1191
	global $config, $g;
1192

    
1193
	init_config_arr(array('ca'));
1194
	$a_ca = &$config['ca'];
1195
	init_config_arr(array('cert'));
1196
	$a_cert = &$config['cert'];
1197
	log_error(gettext("Creating SSL Certificate for this host"));
1198

    
1199
	$cert = array();
1200
	$cert['refid'] = uniqid();
1201
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1202
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1203

    
1204
	$dn = array(
1205
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1206
		'commonName' => $cert_hostname,
1207
		'subjectAltName' => "DNS:{$cert_hostname}");
1208
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1209
	if (!cert_create($cert, null, 2048, 825, $dn, "self-signed", "sha256")) {
1210
		while ($ssl_err = openssl_error_string()) {
1211
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1212
		}
1213
		error_reporting($old_err_level);
1214
		return null;
1215
	}
1216
	error_reporting($old_err_level);
1217

    
1218
	$a_cert[] = $cert;
1219
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1220
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1221
	return $cert;
1222
}
1223

    
1224
function system_webgui_start() {
1225
	global $config, $g;
1226

    
1227
	if (platform_booting()) {
1228
		echo gettext("Starting webConfigurator...");
1229
	}
1230

    
1231
	chdir($g['www_path']);
1232

    
1233
	/* defaults */
1234
	$portarg = "80";
1235
	$crt = "";
1236
	$key = "";
1237
	$ca = "";
1238

    
1239
	/* non-standard port? */
1240
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1241
		$portarg = "{$config['system']['webgui']['port']}";
1242
	}
1243

    
1244
	if ($config['system']['webgui']['protocol'] == "https") {
1245
		// Ensure that we have a webConfigurator CERT
1246
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1247
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1248
			$cert = system_webgui_create_certificate();
1249
		}
1250
		$crt = base64_decode($cert['crt']);
1251
		$key = base64_decode($cert['prv']);
1252

    
1253
		if (!$config['system']['webgui']['port']) {
1254
			$portarg = "443";
1255
		}
1256
		$ca = ca_chain($cert);
1257
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1258
	}
1259

    
1260
	/* generate nginx configuration */
1261
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1262
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1263
		"cert.crt", "cert.key", false, $hsts);
1264

    
1265
	/* kill any running nginx */
1266
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1267

    
1268
	sleep(1);
1269

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

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

    
1275
	if (platform_booting()) {
1276
		if ($res == 0) {
1277
			echo gettext("done.") . "\n";
1278
		} else {
1279
			echo gettext("failed!") . "\n";
1280
		}
1281
	}
1282

    
1283
	return $res;
1284
}
1285

    
1286
function get_dns_nameservers($add_v6_brackets = false) {
1287
	global $config;
1288

    
1289
	$dns_nameservers = array();
1290

    
1291
	if (isset($config['system']['developerspew'])) {
1292
		$mt = microtime();
1293
		echo "get_dns_nameservers() being called $mt\n";
1294
	}
1295

    
1296
	$syscfg = $config['system'];
1297
	if ((((isset($config['dnsmasq']['enable'])) &&
1298
   		(empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1299
	      	(empty($config['dnsmasq']['interface']) ||
1300
	       	in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1301
	     	((isset($config['unbound']['enable'])) &&
1302
	      	(empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1303
	      	(empty($config['unbound']['active_interface']) ||
1304
	       	in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1305
	       	in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1306
	     	(!isset($config['system']['dnslocalhost']))) {
1307
			$dns_nameservers[] = "127.0.0.1";
1308
	}
1309
	/* get dynamically assigned DNS servers (if any) */
1310
	$ns = array_unique(get_nameservers());
1311
	if (isset($syscfg['dnsallowoverride'])) {
1312
		if(!is_array($ns)) {
1313
			$ns = array();
1314
		}
1315
		foreach ($ns as $nameserver) {
1316
			if ($nameserver) {
1317
				if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1318
					$nameserver = "[{$nameserver}]";
1319
				}
1320
				$dns_nameservers[] = $nameserver;
1321
			}
1322
		}
1323
	} else {
1324
		/* If override is disallowed, ignore the dynamic NS entries
1325
		 * https://redmine.pfsense.org/issues/9963 */
1326
		$ns = array();
1327
	}
1328
	if (is_array($syscfg['dnsserver'])) {
1329
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1330
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
1331
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1332
					$sys_dnsserver = "[{$sys_dnsserver}]";
1333
				}
1334
				$dns_nameservers[] = $sys_dnsserver;
1335
			}
1336
		}
1337
	}
1338
	return array_unique($dns_nameservers);
1339
}
1340

    
1341
function system_generate_nginx_config($filename,
1342
	$cert,
1343
	$key,
1344
	$ca,
1345
	$pid_file,
1346
	$port = 80,
1347
	$document_root = "/usr/local/www/",
1348
	$cert_location = "cert.crt",
1349
	$key_location = "cert.key",
1350
	$captive_portal = false,
1351
	$hsts = true) {
1352

    
1353
	global $config, $g;
1354

    
1355
	if (isset($config['system']['developerspew'])) {
1356
		$mt = microtime();
1357
		echo "system_generate_nginx_config() being called $mt\n";
1358
	}
1359

    
1360
	if ($captive_portal !== false) {
1361
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1362
		$cp_hostcheck = "";
1363
		foreach ($cp_interfaces as $cpint) {
1364
			$cpint_ip = get_interface_ip($cpint);
1365
			if (is_ipaddr($cpint_ip)) {
1366
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1367
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1368
				$cp_hostcheck .= "\t\t}\n";
1369
			}
1370
		}
1371
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1372
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1373
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1374
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1375
			$cp_hostcheck .= "\t\t}\n";
1376
		}
1377
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1378
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1379
		$cp_rewrite .= "\t\t}\n";
1380

    
1381
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1382
		if (empty($maxprocperip)) {
1383
			$maxprocperip = 10;
1384
		}
1385
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1386
	}
1387

    
1388
	if (empty($port)) {
1389
		$nginx_port = "80";
1390
	} else {
1391
		$nginx_port = $port;
1392
	}
1393

    
1394
	$memory = get_memory();
1395
	$realmem = $memory[1];
1396

    
1397
	// Determine web GUI process settings and take into account low memory systems
1398
	if ($realmem < 255) {
1399
		$max_procs = 1;
1400
	} else {
1401
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1402
	}
1403

    
1404
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1405
	if ($captive_portal !== false) {
1406
		if ($realmem > 135 and $realmem < 256) {
1407
			$max_procs += 1; // 2 worker processes
1408
		} else if ($realmem > 255 and $realmem < 513) {
1409
			$max_procs += 2; // 3 worker processes
1410
		} else if ($realmem > 512) {
1411
			$max_procs += 4; // 6 worker processes
1412
		}
1413
	}
1414

    
1415
	$nginx_config = <<<EOD
1416
#
1417
# nginx configuration file
1418

    
1419
pid {$g['varrun_path']}/{$pid_file};
1420

    
1421
user  root wheel;
1422
worker_processes  {$max_procs};
1423

    
1424
EOD;
1425

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

    
1430
	$nginx_config .= <<<EOD
1431

    
1432
events {
1433
    worker_connections  1024;
1434
}
1435

    
1436
http {
1437
	include       /usr/local/etc/nginx/mime.types;
1438
	default_type  application/octet-stream;
1439
	add_header X-Frame-Options SAMEORIGIN;
1440
	server_tokens off;
1441

    
1442
	sendfile        on;
1443

    
1444
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1445

    
1446
EOD;
1447

    
1448
	if ($captive_portal !== false) {
1449
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1450
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1451
	} else {
1452
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1453
	}
1454

    
1455
	if ($cert <> "" and $key <> "") {
1456
		$nginx_config .= "\n";
1457
		$nginx_config .= "\tserver {\n";
1458
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1459
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1460
		$nginx_config .= "\n";
1461
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1462
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1463
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1464
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1465
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1466
		if ($captive_portal !== false) {
1467
			// leave TLSv1.0 for CP for now for compatibility
1468
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1469
		} else {
1470
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1471
		}
1472
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1473
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1474
		if ($captive_portal === false && $hsts !== false) {
1475
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1476
		}
1477
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1478
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1479
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1480
		$cert_temp = lookup_cert($config['system']['webgui']['ssl-certref']);
1481
		if (($config['system']['webgui']['ocsp-staple'] == true) or
1482
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1483
			$nginx_config .= "\t\tssl_stapling on;\n";
1484
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1485
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1486
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1487
		}
1488
	} else {
1489
		$nginx_config .= "\n";
1490
		$nginx_config .= "\tserver {\n";
1491
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1492
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1493
	}
1494

    
1495
	$nginx_config .= <<<EOD
1496

    
1497
		client_max_body_size 200m;
1498

    
1499
		gzip on;
1500
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1501

    
1502

    
1503
EOD;
1504

    
1505
	if ($captive_portal !== false) {
1506
		$nginx_config .= <<<EOD
1507
$captive_portal_maxprocperip
1508
$cp_hostcheck
1509
$cp_rewrite
1510
		log_not_found off;
1511

    
1512
EOD;
1513

    
1514
	}
1515

    
1516
	$nginx_config .= <<<EOD
1517
		root "{$document_root}";
1518
		location / {
1519
			index  index.php index.html index.htm;
1520
		}
1521
		location ~ \.inc$ {
1522
			deny all;
1523
			return 403;
1524
		}
1525
		location ~ \.php$ {
1526
			try_files \$uri =404; #  This line closes a potential security hole
1527
			# ensuring users can't execute uploaded files
1528
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1529
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1530
			fastcgi_index  index.php;
1531
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1532
			# Fix httpoxy - https://httpoxy.org/#fix-now
1533
			fastcgi_param  HTTP_PROXY  "";
1534
			fastcgi_read_timeout 180;
1535
			include        /usr/local/etc/nginx/fastcgi_params;
1536
		}
1537
		location ~ (^/status$) {
1538
			allow 127.0.0.1;
1539
			deny all;
1540
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1541
			fastcgi_index  index.php;
1542
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1543
			# Fix httpoxy - https://httpoxy.org/#fix-now
1544
			fastcgi_param  HTTP_PROXY  "";
1545
			fastcgi_read_timeout 360;
1546
			include        /usr/local/etc/nginx/fastcgi_params;
1547
		}
1548
	}
1549

    
1550
EOD;
1551

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

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

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

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

    
1594
EOD;
1595
	}
1596

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

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

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

    
1610
	return 0;
1611

    
1612
}
1613

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

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

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

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

    
1635
	sort($file_list);
1636

    
1637
	return $file_list;
1638
}
1639

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1717

    
1718
	return true;
1719
}
1720

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

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

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

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

    
1735

    
1736
	return true;
1737
}
1738

    
1739

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

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

    
1747
	safe_mkdir($statsdir);
1748

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

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

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

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

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

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

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

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

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

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

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

    
2040

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

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

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

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

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

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

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

    
2091
function system_halt() {
2092
	global $g;
2093

    
2094
	system_reboot_cleanup();
2095

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

    
2099
function system_reboot() {
2100
	global $g;
2101

    
2102
	system_reboot_cleanup();
2103

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

    
2107
function system_reboot_sync($reroot=false) {
2108
	global $g;
2109

    
2110
	if ($reroot) {
2111
		$args = " -r ";
2112
	}
2113

    
2114
	system_reboot_cleanup();
2115

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

    
2119
function system_reboot_cleanup() {
2120
	global $config, $cpzone, $cpzoneid;
2121

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

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

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

    
2152
	if (is_array($config['system'][$cmdn])) {
2153

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

    
2159
	} elseif ($config['system'][$cmdn] <> "") {
2160

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

    
2164
	}
2165
}
2166

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

    
2174
	$dmesg = "";
2175
	$_gb = exec("/sbin/dmesg", $dmesg);
2176

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

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

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

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

    
2196
	fclose($fd);
2197
	unset($dmesg);
2198

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

    
2202
	return 0;
2203
}
2204

    
2205
function system_set_harddisk_standby() {
2206
	global $g, $config;
2207

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

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

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

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

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

    
2251
	activate_sysctls();
2252

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

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

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

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

    
2301
function system_check_reset_button() {
2302
	global $g;
2303

    
2304
	$specplatform = system_identify_specific_platform();
2305

    
2306
	switch ($specplatform['name']) {
2307
		case 'SG-2220':
2308
			$binprefix = "RCC-DFF";
2309
			break;
2310
		case 'alix':
2311
		case 'wrap':
2312
		case 'FW7541':
2313
		case 'APU':
2314
		case 'RCC-VE':
2315
		case 'RCC':
2316
			$binprefix = $specplatform['name'];
2317
			break;
2318
		default:
2319
			return 0;
2320
	}
2321

    
2322
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2323

    
2324
	if ($retval == 99) {
2325
		/* user has pressed reset button for 2 seconds -
2326
		   reset to factory defaults */
2327
		echo <<<EOD
2328

    
2329
***********************************************************************
2330
* Reset button pressed - resetting configuration to factory defaults. *
2331
* All additional packages installed will be removed                   *
2332
* The system will reboot after this completes.                        *
2333
***********************************************************************
2334

    
2335

    
2336
EOD;
2337

    
2338
		reset_factory_defaults();
2339
		system_reboot_sync();
2340
		exit(0);
2341
	}
2342

    
2343
	return 0;
2344
}
2345

    
2346
function system_get_serial() {
2347
	$platform = system_identify_specific_platform();
2348

    
2349
	unset($output);
2350
	if ($platform['name'] == 'Turbot Dual-E') {
2351
		$if_info = pfSense_get_interface_addresses('igb0');
2352
		if (!empty($if_info['hwaddr'])) {
2353
			$serial = str_replace(":", "", $if_info['hwaddr']);
2354
		}
2355
	} else {
2356
		foreach (array('system', 'planar', 'chassis') as $key) {
2357
			unset($output);
2358
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2359
			    $output);
2360
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2361
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2362
				$serial = $output[0];
2363
				break;
2364
			}
2365
		}
2366
	}
2367

    
2368
	$vm_guest = get_single_sysctl('kern.vm_guest');
2369

    
2370
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2371
	    $vm_guest == 'none') {
2372
		return $serial;
2373
	}
2374

    
2375
	return "";
2376
}
2377

    
2378
function system_get_uniqueid() {
2379
	global $g;
2380

    
2381
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2382

    
2383
	if (empty($g['uniqueid'])) {
2384
		if (!file_exists($uniqueid_file)) {
2385
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2386
			    "2>/dev/null");
2387
		}
2388
		if (file_exists($uniqueid_file)) {
2389
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2390
		}
2391
	}
2392

    
2393
	return ($g['uniqueid'] ?: '');
2394
}
2395

    
2396
/*
2397
 * attempt to identify the specific platform (for embedded systems)
2398
 * Returns an array with two elements:
2399
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2400
 * descr => human-readable description (e.g. "PC Engines WRAP")
2401
 */
2402
function system_identify_specific_platform() {
2403
	global $g;
2404

    
2405
	$hw_model = get_single_sysctl('hw.model');
2406
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2407

    
2408
	/* Try to guess from smbios strings */
2409
	unset($product);
2410
	unset($maker);
2411
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2412
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2413
	switch ($product[0]) {
2414
		case 'FW7541':
2415
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2416
			break;
2417
		case 'APU':
2418
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2419
			break;
2420
		case 'RCC-VE':
2421
			$result = array();
2422
			$result['name'] = 'RCC-VE';
2423

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

    
2505
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2506
	    $planar_product);
2507
	if (isset($planar_product[0]) &&
2508
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2509
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2510
	}
2511

    
2512
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2513
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2514
	}
2515

    
2516
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2517
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2518
	}
2519

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

    
2524
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2525
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2526
	}
2527

    
2528
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2529
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2530
	}
2531

    
2532
	unset($hw_model);
2533

    
2534
	$dmesg_boot = system_get_dmesg_boot();
2535
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2536
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2537
	}
2538
	unset($dmesg_boot);
2539

    
2540
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2541
}
2542

    
2543
function system_get_dmesg_boot() {
2544
	global $g;
2545

    
2546
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2547
}
2548

    
2549
?>
(48-48/60)