Project

General

Profile

Download (68.2 KB) Statistics
| Branch: | Tag: | Revision:
1 5b237745 Scott Ullrich
<?php
2
/*
3 ac24dc24 Renato Botelho
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6 81299b5c Renato Botelho
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
7 ac24dc24 Renato Botelho
 * All rights reserved.
8
 *
9
 * originally part of m0n0wall (http://m0n0.ch/wall)
10 c5d81585 Renato Botelho
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
11 ac24dc24 Renato Botelho
 * All rights reserved.
12
 *
13 b12ea3fb Renato Botelho
 * 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 ac24dc24 Renato Botelho
 *
17 b12ea3fb Renato Botelho
 * http://www.apache.org/licenses/LICENSE-2.0
18 ac24dc24 Renato Botelho
 *
19 b12ea3fb Renato Botelho
 * 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 ac24dc24 Renato Botelho
 */
25 5b237745 Scott Ullrich
26 8e9fa41d Scott Ullrich
function activate_powerd() {
27
	global $config, $g;
28 6fa9f38c Renato Botelho
29 61e047a5 Phil Davis
	if (is_process_running("powerd")) {
30 53c210dd Cristian Feldman
		exec("/usr/bin/killall powerd");
31 61e047a5 Phil Davis
	}
32
	if (isset($config['system']['powerd_enable'])) {
33 a358eec2 N0YB
		$ac_mode = "hadp";
34 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_ac_mode'])) {
35 a358eec2 N0YB
			$ac_mode = $config['system']['powerd_ac_mode'];
36 61e047a5 Phil Davis
		}
37 a358eec2 N0YB
38
		$battery_mode = "hadp";
39 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_battery_mode'])) {
40 a358eec2 N0YB
			$battery_mode = $config['system']['powerd_battery_mode'];
41 61e047a5 Phil Davis
		}
42 a358eec2 N0YB
43 3d77cc35 Steven Selph
		$normal_mode = "hadp";
44 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_normal_mode'])) {
45 3d77cc35 Steven Selph
			$normal_mode = $config['system']['powerd_normal_mode'];
46 61e047a5 Phil Davis
		}
47 3d77cc35 Steven Selph
48
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode");
49 8e9fa41d Scott Ullrich
	}
50
}
51
52 3a35f55f Scott Ullrich
function get_default_sysctl_value($id) {
53
	global $sysctls;
54 f3c91cb5 Erik Fonnesbeck
55 61e047a5 Phil Davis
	if (isset($sysctls[$id])) {
56 f3c91cb5 Erik Fonnesbeck
		return $sysctls[$id];
57 61e047a5 Phil Davis
	}
58 3a35f55f Scott Ullrich
}
59
60 d87fcac9 Ermal
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 61e047a5 Phil Davis
		foreach ($config['sysctl']['item'] as $id => $tunable) {
74
			if ($tunable['value'] == "default") {
75 d87fcac9 Ermal
				$value = get_default_sysctl_value($tunable['tunable']);
76 61e047a5 Phil Davis
			} else {
77 d87fcac9 Ermal
				$value = $tunable['value'];
78 61e047a5 Phil Davis
			}
79 d87fcac9 Ermal
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 61e047a5 Phil Davis
		if (isset($disp_cache[$sysctl])) {
88 d87fcac9 Ermal
			continue;
89 61e047a5 Phil Davis
		}
90 d87fcac9 Ermal
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 6df9d7e3 Scott Ullrich
function activate_sysctls() {
98 c46f9695 Ermal
	global $config, $g, $sysctls;
99 971de1f9 Renato Botelho
100 d87fcac9 Ermal
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
101 61e047a5 Phil Davis
		foreach ($config['sysctl']['item'] as $tunable) {
102
			if ($tunable['value'] == "default") {
103 b2d0140c Scott Ullrich
				$value = get_default_sysctl_value($tunable['tunable']);
104 61e047a5 Phil Davis
			} else {
105 971de1f9 Renato Botelho
				$value = $tunable['value'];
106 61e047a5 Phil Davis
			}
107 971de1f9 Renato Botelho
108
			$sysctls[$tunable['tunable']] = $value;
109 d0b461f5 sullrich
		}
110
	}
111 971de1f9 Renato Botelho
112
	set_sysctl($sysctls);
113 6df9d7e3 Scott Ullrich
}
114
115 5b237745 Scott Ullrich
function system_resolvconf_generate($dynupdate = false) {
116 c3f535c0 Seth Mos
	global $config, $g;
117
118 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
119 c3f535c0 Seth Mos
		$mt = microtime();
120
		echo "system_resolvconf_generate() being called $mt\n";
121
	}
122 ef217c69 Scott Ullrich
123 30cee7b2 Scott Ullrich
	$syscfg = $config['system'];
124 ef217c69 Scott Ullrich
125 61e047a5 Phil Davis
	if ((((isset($config['dnsmasq']['enable'])) &&
126 e163952f jim-p
	      (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
127 61e047a5 Phil Davis
	      (empty($config['dnsmasq']['interface']) ||
128
	       in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
129
	     ((isset($config['unbound']['enable'])) &&
130 e163952f jim-p
	      (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
131 61e047a5 Phil Davis
	      (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 6c86a39f Ermal
		$resolvconf .= "nameserver 127.0.0.1\n";
136 61e047a5 Phil Davis
	}
137 8ac329da Ermal
138 30cee7b2 Scott Ullrich
	if (isset($syscfg['dnsallowoverride'])) {
139 c3f535c0 Seth Mos
		/* get dynamically assigned DNS servers (if any) */
140 86dcdfc9 Ermal
		$ns = array_unique(get_searchdomains());
141 61e047a5 Phil Davis
		foreach ($ns as $searchserver) {
142
			if ($searchserver) {
143 86dcdfc9 Ermal
				$resolvconf .= "search {$searchserver}\n";
144 61e047a5 Phil Davis
			}
145 86dcdfc9 Ermal
		}
146 c3f535c0 Seth Mos
		$ns = array_unique(get_nameservers());
147 61e047a5 Phil Davis
		foreach ($ns as $nameserver) {
148
			if ($nameserver) {
149 c3f535c0 Seth Mos
				$resolvconf .= "nameserver $nameserver\n";
150 61e047a5 Phil Davis
			}
151 c3f535c0 Seth Mos
		}
152 e8b5f724 Chris Buechler
	} else {
153 4ad1ddf2 Phil Davis
		$ns = array();
154 e8b5f724 Chris Buechler
		// Do not create blank search/domain lines, it can break tools like dig.
155 61e047a5 Phil Davis
		if ($syscfg['domain']) {
156 97383d2b Chris Buechler
			$resolvconf .= "search {$syscfg['domain']}\n";
157 61e047a5 Phil Davis
		}
158 30cee7b2 Scott Ullrich
	}
159 8e866217 Ermal
	if (is_array($syscfg['dnsserver'])) {
160 4ad1ddf2 Phil Davis
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
161 14a6c356 Phil Davis
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
162 4ad1ddf2 Phil Davis
				$resolvconf .= "nameserver $sys_dnsserver\n";
163 61e047a5 Phil Davis
			}
164 e180a6e3 Scott Ullrich
		}
165 c3f535c0 Seth Mos
	}
166 0f282d7a Scott Ullrich
167 3b95d9ec Warren Baker
	// Add EDNS support
168 61e047a5 Phil Davis
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
169 3b95d9ec Warren Baker
		$resolvconf .= "options edns0\n";
170 61e047a5 Phil Davis
	}
171 3b95d9ec Warren Baker
172 d97ff036 Ermal
	$dnslock = lock('resolvconf', LOCK_EX);
173
174 fc84b222 Renato Botelho
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
175 e1daff07 Ermal
	if (!$fd) {
176
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
177 d97ff036 Ermal
		unlock($dnslock);
178 e1daff07 Ermal
		return 1;
179
	}
180
181 30cee7b2 Scott Ullrich
	fwrite($fd, $resolvconf);
182
	fclose($fd);
183 0f282d7a Scott Ullrich
184 30501526 Warren Baker
	// Prevent resolvconf(8) from rewriting our resolv.conf
185 fc84b222 Renato Botelho
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
186 30501526 Warren Baker
	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 285ef132 Ermal LUÇI
	if (!platform_booting()) {
194 c3f535c0 Seth Mos
		/* restart dhcpd (nameservers may have changed) */
195 61e047a5 Phil Davis
		if (!$dynupdate) {
196 c3f535c0 Seth Mos
			services_dhcpd_configure();
197 61e047a5 Phil Davis
		}
198 30cee7b2 Scott Ullrich
	}
199 ef217c69 Scott Ullrich
200 c3f535c0 Seth Mos
	/* setup static routes for DNS servers. */
201 a2d23e88 Phil Davis
	$dnscounter = 1;
202
	$dnsgw = "dns{$dnscounter}gw";
203
	while (isset($config['system'][$dnsgw])) {
204 c3f535c0 Seth Mos
		/* setup static routes for dns servers */
205 a2d23e88 Phil Davis
		if (!(empty($config['system'][$dnsgw]) ||
206
		    $config['system'][$dnsgw] == "none")) {
207 c935003d Seth Mos
			$gwname = $config['system'][$dnsgw];
208 c6079517 Renato Botelho
			$gatewayip = lookup_gateway_ip_by_name($gwname);
209 138e4140 Renato Botelho
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
210
			/* dns server array starts at 0 */
211
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
212 c6079517 Renato Botelho
213
			if (is_ipaddr($gatewayip)) {
214 94bd7fb3 Renato Botelho
				route_add_or_change("-host {$inet6}{$dnsserver} {$gatewayip}");
215 138e4140 Renato Botelho
			} else {
216
				/* Remove old route when disable gw */
217 94bd7fb3 Renato Botelho
				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 b875f306 Scott Ullrich
			}
223 e180a6e3 Scott Ullrich
		}
224 a2d23e88 Phil Davis
		$dnscounter++;
225
		$dnsgw = "dns{$dnscounter}gw";
226 c3f535c0 Seth Mos
	}
227 d97ff036 Ermal
228
	unlock($dnslock);
229
230 c3f535c0 Seth Mos
	return 0;
231 5b237745 Scott Ullrich
}
232
233 86dcdfc9 Ermal
function get_searchdomains() {
234
	global $config, $g;
235
236
	$master_list = array();
237 61e047a5 Phil Davis
238 86dcdfc9 Ermal
	// Read in dhclient nameservers
239 e1daff07 Ermal
	$search_list = glob("/var/etc/searchdomain_*");
240 f4a4bcbc Renato Botelho
	if (is_array($search_list)) {
241 61e047a5 Phil Davis
		foreach ($search_list as $fdns) {
242 807fd6cd Ermal
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
243 61e047a5 Phil Davis
			if (!is_array($contents)) {
244 807fd6cd Ermal
				continue;
245 61e047a5 Phil Davis
			}
246 807fd6cd Ermal
			foreach ($contents as $dns) {
247 61e047a5 Phil Davis
				if (is_hostname($dns)) {
248 807fd6cd Ermal
					$master_list[] = $dns;
249 61e047a5 Phil Davis
				}
250 807fd6cd Ermal
			}
251 86dcdfc9 Ermal
		}
252
	}
253
254
	return $master_list;
255
}
256
257 3d00ccaa Scott Ullrich
function get_nameservers() {
258
	global $config, $g;
259
	$master_list = array();
260 61e047a5 Phil Davis
261 2a1226ad Scott Ullrich
	// Read in dhclient nameservers
262 e1daff07 Ermal
	$dns_lists = glob("/var/etc/nameserver_*");
263 1033de74 Ermal
	if (is_array($dns_lists)) {
264 61e047a5 Phil Davis
		foreach ($dns_lists as $fdns) {
265 807fd6cd Ermal
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
266 61e047a5 Phil Davis
			if (!is_array($contents)) {
267 807fd6cd Ermal
				continue;
268 61e047a5 Phil Davis
			}
269 807fd6cd Ermal
			foreach ($contents as $dns) {
270 61e047a5 Phil Davis
				if (is_ipaddr($dns)) {
271 807fd6cd Ermal
					$master_list[] = $dns;
272 61e047a5 Phil Davis
				}
273 807fd6cd Ermal
			}
274 60951398 Scott Ullrich
		}
275 3d00ccaa Scott Ullrich
	}
276 2a1226ad Scott Ullrich
277
	// Read in any extra nameservers
278 61e047a5 Phil Davis
	if (file_exists("/var/etc/nameservers.conf")) {
279 33818198 Ermal
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
280 61e047a5 Phil Davis
		if (is_array($dns_s)) {
281
			foreach ($dns_s as $dns) {
282
				if (is_ipaddr($dns)) {
283 1033de74 Ermal
					$master_list[] = $dns;
284 61e047a5 Phil Davis
				}
285
			}
286 e1daff07 Ermal
		}
287 2a1226ad Scott Ullrich
	}
288
289 3d00ccaa Scott Ullrich
	return $master_list;
290
}
291
292 2da0fc77 Renato Botelho
/* Create localhost + local interfaces entries for /etc/hosts */
293
function system_hosts_local_entries() {
294
	global $config;
295
296
	$syscfg = $config['system'];
297
298
	$hosts = array();
299
	$hosts[] = array(
300
	    'ipaddr' => '127.0.0.1',
301
	    'fqdn' => 'localhost',
302
	    'name' => 'localhost.' . $syscfg['domain']
303
	);
304
	$hosts[] = array(
305
	    'ipaddr' => '::1',
306
	    'fqdn' => 'localhost',
307
	    'name' => 'localhost.' . $syscfg['domain']
308
	);
309
310
	if ($config['interfaces']['lan']) {
311
		$sysiflist = array('lan' => "lan");
312
	} else {
313
		$sysiflist = get_configured_interface_list();
314
	}
315
316
	$hosts_if_found = false;
317
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
318
	foreach ($sysiflist as $sysif) {
319
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
320
			continue;
321
		}
322
		$cfgip = get_interface_ip($sysif);
323
		if (is_ipaddrv4($cfgip)) {
324
			$hosts[] = array(
325
			    'ipaddr' => $cfgip,
326
			    'fqdn' => $local_fqdn
327
			);
328
			$hosts_if_found = true;
329
		}
330
		$cfgipv6 = get_interface_ipv6($sysif);
331
		if (is_ipaddrv6($cfgipv6)) {
332
			$hosts[] = array(
333
			    'ipaddr' => $cfgipv6,
334
			    'fqdn' => $local_fqdn
335
			);
336
			$hosts_if_found = true;
337
		}
338
		if ($hosts_if_found == true) {
339
			break;
340
		}
341
	}
342
343
	return $hosts;
344
}
345
346 46ff0dee Renato Botelho
/* Read host override entries from dnsmasq or unbound */
347
function system_hosts_override_entries($dnscfg) {
348
	$hosts = array();
349
350 71e53a40 Renato Botelho
	if (!is_array($dnscfg) ||
351
	    !is_array($dnscfg['hosts']) ||
352
	    !isset($dnscfg['enable'])) {
353 46ff0dee Renato Botelho
		return $hosts;
354
	}
355
356
	foreach ($dnscfg['hosts'] as $host) {
357
		$fqdn = '';
358
		if ($host['host'] || $host['host'] == "0") {
359
			$fqdn .= "{$host['host']}.";
360
		}
361
		$fqdn .= $host['domain'];
362
363
		$hosts[] = array(
364
		    'ipaddr' => $host['ip'],
365
		    'fqdn' => $fqdn
366
		);
367
368
		if (!is_array($host['aliases']) ||
369
		    !is_array($host['aliases']['item'])) {
370
			continue;
371
		}
372
373
		foreach ($host['aliases']['item'] as $alias) {
374
			$fqdn = '';
375
			if ($alias['host'] || $alias['host'] == "0") {
376
				$fqdn .= "{$alias['host']}.";
377
			}
378
			$fqdn .= $alias['domain'];
379
380
			$hosts[] = array(
381
			    'ipaddr' => $host['ip'],
382
			    'fqdn' => $fqdn
383
			);
384
		}
385
	}
386
387
	return $hosts;
388
}
389
390 236d5816 Renato Botelho
/* Read all dhcpd/dhcpdv6 staticmap entries */
391
function system_hosts_dhcpd_entries() {
392
	global $config;
393
394
	$hosts = array();
395
	$syscfg = $config['system'];
396
397
	if (is_array($config['dhcpd'])) {
398
		$conf_dhcpd = $config['dhcpd'];
399
	} else {
400
		$conf_dhcpd = array();
401
	}
402
403
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
404
		if (!is_array($dhcpifconf['staticmap']) ||
405
		    !isset($dhcpifconf['enable'])) {
406
			continue;
407
		}
408
		foreach ($dhcpifconf['staticmap'] as $host) {
409
			if (!$host['ipaddr'] ||
410
			    !$host['hostname']) {
411
				continue;
412
			}
413
414
			$fqdn = $host['hostname'] . ".";
415
			if ($host['domain']) {
416
				$fqdn .= $host['domain'];
417
			} elseif ($dhcpifconf['domain']) {
418
				$fqdn .= $dhcpifconf['domain'];
419
			} else {
420
				$fqdn .= $syscfg['domain'];
421
			}
422
423
			$hosts[] = array(
424
			    'ipaddr' => $host['ipaddr'],
425
			    'fqdn' => $fqdn
426
			);
427
		}
428
	}
429
	unset($conf_dhcpd);
430
431
	if (is_array($config['dhcpdv6'])) {
432
		$conf_dhcpdv6 = $config['dhcpdv6'];
433
	} else {
434
		$conf_dhcpdv6 = array();
435
	}
436
437
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
438
		if (!is_array($dhcpifconf['staticmap']) ||
439
		    !isset($dhcpifconf['enable'])) {
440
			continue;
441
		}
442
443
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
444
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
445
		    'track6') {
446
			$isdelegated = true;
447
		} else {
448
			$isdelegated = false;
449
		}
450
451
		foreach ($dhcpifconf['staticmap'] as $host) {
452
			$ipaddrv6 = $host['ipaddrv6'];
453
454
			if (!$ipaddrv6 || !$host['hostname']) {
455
				continue;
456
			}
457
458
			if ($isdelegated) {
459
				/*
460
				 * We are always in an "end-user" subnet
461
				 * here, which all are /64 for IPv6.
462
				 */
463
				$ipaddrv6 = merge_ipv6_delegated_prefix(
464
				    get_interface_ipv6($dhcpif),
465
				    $ipaddrv6, 64);
466
			}
467
468
			$fqdn = $host['hostname'] . ".";
469
			if ($host['domain']) {
470
				$fqdn .= $host['domain'];
471
			} else if ($dhcpifconf['domain']) {
472
				$fqdn .= $dhcpifconf['domain'];
473
			} else {
474
				$fqdn .= $syscfg['domain'];
475
			}
476
477
			$hosts[] = array(
478
			    'ipaddr' => $ipaddrv6,
479
			    'fqdn' => $fqdn
480
			);
481
		}
482
	}
483
	unset($conf_dhcpdv6);
484
485
	return $hosts;
486
}
487
488 878b7736 Renato Botelho
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
489
function system_hosts_entries($dnscfg) {
490
	$local = system_hosts_local_entries();
491
492
	$dns = array();
493
	$dhcpd = array();
494
	if (isset($dnscfg['enable'])) {
495
		$dns = system_hosts_override_entries($dnscfg);
496
		if (isset($dnscfg['regdhcpstatic'])) {
497
			$dhcpd = system_hosts_dhcpd_entries();
498
		}
499
	}
500
501
	if (isset($dnscfg['dhcpfirst'])) {
502
		return array_merge($local, $dns, $dhcpd);
503
	} else {
504
		return array_merge($local, $dhcpd, $dns);
505
	}
506
}
507
508 5b237745 Scott Ullrich
function system_hosts_generate() {
509 f19d3b7a Scott Ullrich
	global $config, $g;
510 f6248774 Warren Baker
	if (isset($config['system']['developerspew'])) {
511 58c7450e Scott Ullrich
		$mt = microtime();
512 dcf0598e Scott Ullrich
		echo "system_hosts_generate() being called $mt\n";
513 f19d3b7a Scott Ullrich
	}
514 0f282d7a Scott Ullrich
515 d6fa0b47 Chris Buechler
	// prefer dnsmasq for hosts generation where it's enabled. It relies
516
	// on hosts for name resolution of its overrides, unbound does not.
517
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
518 21713b25 Renato Botelho
		$dnsmasqcfg = $config['dnsmasq'];
519 d6fa0b47 Chris Buechler
	} else {
520
		$dnsmasqcfg = $config['unbound'];
521 61e047a5 Phil Davis
	}
522 5b237745 Scott Ullrich
523 2da0fc77 Renato Botelho
	$syscfg = $config['system'];
524
	$hosts = "";
525 aa994814 Andrew Thompson
	$lhosts = "";
526
	$dhosts = "";
527 a55e9c70 Ermal Lu?i
528 878b7736 Renato Botelho
	$hosts_array = system_hosts_entries($dnsmasqcfg);
529 2da0fc77 Renato Botelho
	foreach ($hosts_array as $host) {
530
		$hosts .= "{$host['ipaddr']}\t{$host['fqdn']}";
531
		if (!empty($host['name'])) {
532
			$hosts .= " {$host['name']}";
533 e5995f9d Ermal
		}
534 2da0fc77 Renato Botelho
		$hosts .= "\n";
535 f38f8062 Ermal
	}
536 46ff0dee Renato Botelho
	unset($hosts_array);
537 0f282d7a Scott Ullrich
538 8cf97db3 Renato Botelho
	$fd = fopen("{$g['etc_path']}/hosts", "w");
539
	if (!$fd) {
540
		log_error(gettext(
541
		    "Error: cannot open hosts file in system_hosts_generate()."
542
		    ));
543
		return 1;
544
	}
545
546 58db1fc4 Ermal
	/*
547 d015d543 Renato Botelho
	 * Do not remove this because dhcpleases monitors with kqueue it needs
548
	 * to be killed before writing to hosts files.
549 58db1fc4 Ermal
	 */
550
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
551
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
552 ea1aca13 Renato Botelho
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
553 58db1fc4 Ermal
	}
554 509e9357 NewEraCracker
555 5b237745 Scott Ullrich
	fwrite($fd, $hosts);
556
	fclose($fd);
557 0f282d7a Scott Ullrich
558 3f06e538 Warren Baker
	if (isset($config['unbound']['enable'])) {
559
		require_once("unbound.inc");
560 f6248774 Warren Baker
		unbound_hosts_generate();
561 3f06e538 Warren Baker
	}
562 f6248774 Warren Baker
563 509e9357 NewEraCracker
	/* restart dhcpleases */
564
	if (!platform_booting()) {
565
		system_dhcpleases_configure();
566
	}
567
568 24d619f5 Ermal
	return 0;
569
}
570
571
function system_dhcpleases_configure() {
572 15d456b9 gnhb
	global $config, $g;
573 61e047a5 Phil Davis
574 4509abc3 NewEraCracker
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
575
576 956950de Ermal
	/* Start the monitoring process for dynamic dhcpclients. */
577 61e047a5 Phil Davis
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
578
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
579 956950de Ermal
		/* Make sure we do not error out */
580 abdd01f5 Ermal
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
581 61e047a5 Phil Davis
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
582 abdd01f5 Ermal
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
583 61e047a5 Phil Davis
		}
584 4dbcf2fb Renato Botelho
585 21713b25 Renato Botelho
		if (isset($config['unbound']['enable'])) {
586 4dbcf2fb Renato Botelho
			$dns_pid = "unbound.pid";
587 21713b25 Renato Botelho
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
588
		} else {
589 4dbcf2fb Renato Botelho
			$dns_pid = "dnsmasq.pid";
590 21713b25 Renato Botelho
			$unbound_conf = "";
591
		}
592 4dbcf2fb Renato Botelho
593
		if (isvalidpid($pidfile)) {
594
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
595
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
596
			if (intval($retval) == 0) {
597
				sigkillbypid($pidfile, "HUP");
598
				return;
599 61e047a5 Phil Davis
			} else {
600 4dbcf2fb Renato Botelho
				sigkillbypid($pidfile, "TERM");
601 61e047a5 Phil Davis
			}
602 69e593c1 jim-p
		}
603 4dbcf2fb Renato Botelho
604
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
605 61e047a5 Phil Davis
		if (is_process_running("dhcpleases")) {
606 21713b25 Renato Botelho
			sigkillbyname('dhcpleases', "TERM");
607 61e047a5 Phil Davis
		}
608 21713b25 Renato Botelho
		@unlink($pidfile);
609 fc84b222 Renato Botelho
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['etc_path']}/hosts");
610 4509abc3 NewEraCracker
	} elseif (isvalidpid($pidfile)) {
611 21713b25 Renato Botelho
		sigkillbypid($pidfile, "TERM");
612
		@unlink($pidfile);
613 15d456b9 gnhb
	}
614 5b237745 Scott Ullrich
}
615
616
function system_hostname_configure() {
617 f19d3b7a Scott Ullrich
	global $config, $g;
618 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
619 58c7450e Scott Ullrich
		$mt = microtime();
620 dcf0598e Scott Ullrich
		echo "system_hostname_configure() being called $mt\n";
621 333f8ef0 Scott Ullrich
	}
622 0f282d7a Scott Ullrich
623 5b237745 Scott Ullrich
	$syscfg = $config['system'];
624 0f282d7a Scott Ullrich
625 5b237745 Scott Ullrich
	/* set hostname */
626 6bfccde7 Scott Ullrich
	$status = mwexec("/bin/hostname " .
627 5b237745 Scott Ullrich
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
628 6bfccde7 Scott Ullrich
629 61e047a5 Phil Davis
	/* Setup host GUID ID.  This is used by ZFS. */
630 6bfccde7 Scott Ullrich
	mwexec("/etc/rc.d/hostid start");
631
632
	return $status;
633 5b237745 Scott Ullrich
}
634
635 1ea67f2e Ermal
function system_routing_configure($interface = "") {
636 962625aa Ermal
	global $config, $g;
637 6fa9f38c Renato Botelho
638 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
639 58c7450e Scott Ullrich
		$mt = microtime();
640 dcf0598e Scott Ullrich
		echo "system_routing_configure() being called $mt\n";
641 58c7450e Scott Ullrich
	}
642 333f8ef0 Scott Ullrich
643 a529aced Ermal
	$gatewayip = "";
644
	$interfacegw = "";
645 5a5413bb Seth Mos
	$gatewayipv6 = "";
646
	$interfacegwv6 = "";
647 d35dfaae Ermal
	$foundgw = false;
648 5a5413bb Seth Mos
	$foundgwv6 = false;
649 a529aced Ermal
	/* tack on all the hard defined gateways as well */
650
	if (is_array($config['gateways']['gateway_item'])) {
651 873c1701 Renato Botelho
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
652 a529aced Ermal
		foreach	($config['gateways']['gateway_item'] as $gateway) {
653 f934af33 Ermal
			if (isset($gateway['defaultgw'])) {
654 d35dfaae Ermal
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
655 61e047a5 Phil Davis
					if (strpos($gateway['gateway'], ":")) {
656 f934af33 Ermal
						continue;
657 61e047a5 Phil Davis
					}
658
					if ($gateway['gateway'] == "dynamic") {
659 f934af33 Ermal
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
660 61e047a5 Phil Davis
					}
661 9d595f6a Ermal
					$gatewayip = $gateway['gateway'];
662 03e96afb Renato Botelho
					$interfacegw = $gateway['interface'];
663 f934af33 Ermal
					if (!empty($gateway['interface'])) {
664
						$defaultif = get_real_interface($gateway['interface']);
665 61e047a5 Phil Davis
						if ($defaultif) {
666 f934af33 Ermal
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
667 61e047a5 Phil Davis
						}
668 f934af33 Ermal
					}
669
					$foundgw = true;
670 d35dfaae Ermal
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
671 61e047a5 Phil Davis
					if ($gateway['gateway'] == "dynamic") {
672 f934af33 Ermal
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
673 61e047a5 Phil Davis
					}
674 9d595f6a Ermal
					$gatewayipv6 = $gateway['gateway'];
675 03e96afb Renato Botelho
					$interfacegwv6 = $gateway['interface'];
676 f934af33 Ermal
					if (!empty($gateway['interface'])) {
677 c79f717a Ermal
						$defaultifv6 = get_real_interface($gateway['interface']);
678 61e047a5 Phil Davis
						if ($defaultifv6) {
679 f934af33 Ermal
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
680 61e047a5 Phil Davis
						}
681 f934af33 Ermal
					}
682
					$foundgwv6 = true;
683 924f202e Ermal
				}
684 a529aced Ermal
			}
685 61e047a5 Phil Davis
			if ($foundgw === true && $foundgwv6 === true) {
686 5a5413bb Seth Mos
				break;
687 61e047a5 Phil Davis
			}
688 5a5413bb Seth Mos
		}
689 b24bda08 Scott Ullrich
	}
690 3cc07282 Ermal
	if ($foundgw == false) {
691
		$defaultif = get_real_interface("wan");
692
		$interfacegw = "wan";
693
		$gatewayip = get_interface_gateway("wan");
694 d35dfaae Ermal
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
695 61e047a5 Phil Davis
	}
696 5a5413bb Seth Mos
	if ($foundgwv6 == false) {
697 c79f717a Ermal
		$defaultifv6 = get_real_interface("wan");
698 4f332466 Seth Mos
		$interfacegwv6 = "wan";
699
		$gatewayipv6 = get_interface_gateway_v6("wan");
700 d35dfaae Ermal
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
701 17a5b095 Seth Mos
	}
702 d173230c Seth Mos
	$dont_add_route = false;
703
	/* if OLSRD is enabled, allow WAN to house DHCP. */
704 f934af33 Ermal
	if (is_array($config['installedpackages']['olsrd'])) {
705 61e047a5 Phil Davis
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
706
			if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
707 d173230c Seth Mos
				$dont_add_route = true;
708 e8c516a0 Phil Davis
				log_error(gettext("Not adding default route because OLSR dynamic gateway is enabled."));
709 6e17413e Ermal Lu?i
				break;
710 d173230c Seth Mos
			}
711
		}
712
	}
713 07b54e8c smos
714 de34f1fc PiBa-NL
	$gateways_arr = return_gateways_array(false, true);
715 4e322e2c Phil Davis
	foreach ($gateways_arr as $gateway) {
716 de34f1fc PiBa-NL
		// setup static interface routes for nonlocal gateways
717
		if (isset($gateway["nonlocalgateway"])) {
718
			$srgatewayip = $gateway['gateway'];
719
			$srinterfacegw = $gateway['interface'];
720
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
721
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
722 94bd7fb3 Renato Botelho
				route_add_or_change("{$inet} {$srgatewayip} " .
723
				    "-iface {$srinterfacegw}");
724 de34f1fc PiBa-NL
			}
725
		}
726
	}
727
728 61e047a5 Phil Davis
	if ($dont_add_route == false) {
729
		if (!empty($interface) && $interface != $interfacegw) {
730 1ea67f2e Ermal
			;
731 61e047a5 Phil Davis
		} else if (is_ipaddrv4($gatewayip)) {
732 e8c516a0 Phil Davis
			log_error(sprintf(gettext("ROUTING: setting default route to %s"), $gatewayip));
733 94bd7fb3 Renato Botelho
			route_add_or_change("-inet default {$gatewayip}");
734 d173230c Seth Mos
		}
735
736 61e047a5 Phil Davis
		if (!empty($interface) && $interface != $interfacegwv6) {
737 5a5413bb Seth Mos
			;
738 61e047a5 Phil Davis
		} else if (is_ipaddrv6($gatewayipv6)) {
739 8be135cd Ermal
			$ifscope = "";
740 61e047a5 Phil Davis
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
741 26ecc19c smos
				$ifscope = "%{$defaultifv6}";
742 61e047a5 Phil Davis
			}
743 e8c516a0 Phil Davis
			log_error(sprintf(gettext("ROUTING: setting IPv6 default route to %s"), $gatewayipv6 . $ifscope));
744 94bd7fb3 Renato Botelho
			route_add_or_change("-inet6 default {$gatewayipv6}{$ifscope}");
745 5a5413bb Seth Mos
		}
746
	}
747
748 2a2b9eea Renato Botelho
	system_staticroutes_configure($interface, false);
749
750
	return 0;
751
}
752
753
function system_staticroutes_configure($interface = "", $update_dns = false) {
754
	global $config, $g, $aliastable;
755
756 356e86d4 Renato Botelho
	$filterdns_list = array();
757
758 e47d24e4 Renato Botelho
	$static_routes = get_staticroutes(false, true);
759 f898c1a9 jim-p
	if (count($static_routes)) {
760 6fdea6a2 smos
		$gateways_arr = return_gateways_array(false, true);
761 0f282d7a Scott Ullrich
762 f898c1a9 jim-p
		foreach ($static_routes as $rtent) {
763 a02708b1 Ermal
			if (empty($gateways_arr[$rtent['gateway']])) {
764 4a896b86 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
765 a529aced Ermal
				continue;
766
			}
767 a02708b1 Ermal
			$gateway = $gateways_arr[$rtent['gateway']];
768 61e047a5 Phil Davis
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
769 a02708b1 Ermal
				continue;
770 61e047a5 Phil Davis
			}
771 9740fad8 Seth Mos
772 a02708b1 Ermal
			$gatewayip = $gateway['gateway'];
773
			$interfacegw = $gateway['interface'];
774 a529aced Ermal
775 1e5f47bb smos
			$blackhole = "";
776 580bef1e phroggie
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
777 1e5f47bb smos
				$blackhole = "-blackhole";
778 61e047a5 Phil Davis
			}
779 1e5f47bb smos
780 61e047a5 Phil Davis
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
781 2a2b9eea Renato Botelho
				continue;
782 61e047a5 Phil Davis
			}
783 046583c3 Renato Botelho
784 e47d24e4 Renato Botelho
			$dnscache = array();
785
			if ($update_dns === true) {
786 61e047a5 Phil Davis
				if (is_subnet($rtent['network'])) {
787 2a2b9eea Renato Botelho
					continue;
788 61e047a5 Phil Davis
				}
789 e47d24e4 Renato Botelho
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
790 61e047a5 Phil Davis
				if (empty($dnscache)) {
791 e47d24e4 Renato Botelho
					continue;
792 61e047a5 Phil Davis
				}
793 e47d24e4 Renato Botelho
			}
794 046583c3 Renato Botelho
795 61e047a5 Phil Davis
			if (is_subnet($rtent['network'])) {
796 e47d24e4 Renato Botelho
				$ips = array($rtent['network']);
797 61e047a5 Phil Davis
			} else {
798
				if (!isset($rtent['disabled'])) {
799 e47d24e4 Renato Botelho
					$filterdns_list[] = $rtent['network'];
800 61e047a5 Phil Davis
				}
801 e47d24e4 Renato Botelho
				$ips = add_hostname_to_watch($rtent['network']);
802
			}
803 2a2b9eea Renato Botelho
804 e47d24e4 Renato Botelho
			foreach ($dnscache as $ip) {
805 61e047a5 Phil Davis
				if (in_array($ip, $ips)) {
806 e47d24e4 Renato Botelho
					continue;
807 61e047a5 Phil Davis
				}
808 e47d24e4 Renato Botelho
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
809 7bd413eb Chris Buechler
				if (isset($config['system']['route-debug'])) {
810
					$mt = microtime();
811
					log_error("ROUTING debug: $mt - route delete $ip ");
812
				}
813 e47d24e4 Renato Botelho
			}
814 2a2b9eea Renato Botelho
815 e47d24e4 Renato Botelho
			if (isset($rtent['disabled'])) {
816 1f4ad8f4 Chris Buechler
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
817 7bd413eb Chris Buechler
				foreach ($ips as $ip) {
818 2a2b9eea Renato Botelho
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
819 7bd413eb Chris Buechler
					if (isset($config['system']['route-debug'])) {
820
						$mt = microtime();
821
						log_error("ROUTING debug: $mt - route delete $ip ");
822
					}
823
				}
824 e47d24e4 Renato Botelho
				continue;
825
			}
826 2a2b9eea Renato Botelho
827 e47d24e4 Renato Botelho
			foreach ($ips as $ip) {
828 61e047a5 Phil Davis
				if (is_ipaddrv4($ip)) {
829 e47d24e4 Renato Botelho
					$ip .= "/32";
830 61e047a5 Phil Davis
				}
831 e78509cc Chris Buechler
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
832 61e047a5 Phil Davis
833 e47d24e4 Renato Botelho
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
834 2a2b9eea Renato Botelho
835 94bd7fb3 Renato Botelho
				$cmd = "{$inet} {$blackhole} {$ip} ";
836 e47d24e4 Renato Botelho
837 61e047a5 Phil Davis
				if (is_subnet($ip)) {
838 7bd413eb Chris Buechler
					if (is_ipaddr($gatewayip)) {
839 eea84f0a Chris Buechler
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
840
							// add interface scope for link local v6 routes
841
							$gatewayip .= "%$interfacegw";
842
						}
843 94bd7fb3 Renato Botelho
						route_add_or_change($cmd . $gatewayip);
844 7bd413eb Chris Buechler
					} else if (!empty($interfacegw)) {
845 94bd7fb3 Renato Botelho
						route_add_or_change($cmd . "-iface {$interfacegw}");
846 7bd413eb Chris Buechler
					}
847 61e047a5 Phil Davis
				}
848 2a2b9eea Renato Botelho
			}
849 5b237745 Scott Ullrich
		}
850 6a205b6a Ermal
		unset($gateways_arr);
851 5b237745 Scott Ullrich
	}
852 6a205b6a Ermal
	unset($static_routes);
853 67ee1ec5 Ermal Luçi
854 e47d24e4 Renato Botelho
	if ($update_dns === false) {
855
		if (count($filterdns_list)) {
856
			$interval = 60;
857
			$hostnames = "";
858
			array_unique($filterdns_list);
859 61e047a5 Phil Davis
			foreach ($filterdns_list as $hostname) {
860 e47d24e4 Renato Botelho
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
861 61e047a5 Phil Davis
			}
862 e47d24e4 Renato Botelho
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
863
			unset($hostnames);
864
865 61e047a5 Phil Davis
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
866 e47d24e4 Renato Botelho
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
867 61e047a5 Phil Davis
			} else {
868 e47d24e4 Renato Botelho
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
869 61e047a5 Phil Davis
			}
870 e47d24e4 Renato Botelho
		} else {
871
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
872
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
873
		}
874 356e86d4 Renato Botelho
	}
875 e47d24e4 Renato Botelho
	unset($filterdns_list);
876 356e86d4 Renato Botelho
877 b9c501ea Seth Mos
	return 0;
878 5b237745 Scott Ullrich
}
879
880
function system_routing_enable() {
881 f19d3b7a Scott Ullrich
	global $config, $g;
882 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
883 58c7450e Scott Ullrich
		$mt = microtime();
884 dcf0598e Scott Ullrich
		echo "system_routing_enable() being called $mt\n";
885 58c7450e Scott Ullrich
	}
886 0f282d7a Scott Ullrich
887 971de1f9 Renato Botelho
	set_sysctl(array(
888
		"net.inet.ip.forwarding" => "1",
889
		"net.inet6.ip6.forwarding" => "1"
890
	));
891
892 6da3df4e Seth Mos
	return;
893 5b237745 Scott Ullrich
}
894
895 bd29bb7b jim-p
function system_syslogd_fixup_server($server) {
896
	/* If it's an IPv6 IP alone, encase it in brackets */
897 61e047a5 Phil Davis
	if (is_ipaddrv6($server)) {
898 bd29bb7b jim-p
		return "[$server]";
899 61e047a5 Phil Davis
	} else {
900 bd29bb7b jim-p
		return $server;
901 61e047a5 Phil Davis
	}
902 bd29bb7b jim-p
}
903
904 236524c2 jim-p
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
905
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
906
	$facility .= " ".
907
	$remote_servers = "";
908 7d4d7822 Phil Davis
	$pad_to  = max(strlen($facility), 56);
909 236524c2 jim-p
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
910 6c301424 Chris Buechler
	if (isset($syslogcfg['enable'])) {
911
		if ($syslogcfg['remoteserver']) {
912
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
913
		}
914
		if ($syslogcfg['remoteserver2']) {
915
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
916
		}
917
		if ($syslogcfg['remoteserver3']) {
918
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
919
		}
920 61e047a5 Phil Davis
	}
921 236524c2 jim-p
	return $remote_servers;
922
}
923
924 41df62c1 jim-p
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
925
	global $config, $g;
926
	if ($restart_syslogd) {
927
		exec("/usr/bin/killall syslogd");
928
	}
929
	if (isset($config['system']['disablesyslogclog'])) {
930
		unlink($logfile);
931
		touch($logfile);
932
	} else {
933
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
934
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
935
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
936
	}
937
	if ($restart_syslogd) {
938
		system_syslogd_start();
939
	}
940 4aefa6f2 doktornotor
	// Bug #6915
941
	if ($logfile == "/var/log/resolver.log") {
942
		services_unbound_configure(true);
943
	}
944 41df62c1 jim-p
}
945
946
function clear_all_log_files($restart = false) {
947
	global $g;
948
	exec("/usr/bin/killall syslogd");
949
950 8acd1331 jim-p
	$log_files = array("system", "filter", "dhcpd", "vpn", "poes", "l2tps", "openvpn", "portalauth", "ipsec", "ppp", "relayd", "wireless", "nginx", "ntpd", "gateways", "resolver", "routing");
951 41df62c1 jim-p
	foreach ($log_files as $lfile) {
952
		clear_log_file("{$g['varlog_path']}/{$lfile}.log", false);
953
	}
954
955
	if ($restart) {
956
		system_syslogd_start();
957
		killbyname("dhcpd");
958 12094fd5 doktornotor
		if (!function_exists('services_dhcpd_configure')) {
959
			require_once('services.inc');
960
		}
961 41df62c1 jim-p
		services_dhcpd_configure();
962 4aefa6f2 doktornotor
		// Bug #6915
963 ef72cd5c doktornotor
		services_unbound_configure(false);
964 41df62c1 jim-p
	}
965
	return;
966
}
967
968 5b237745 Scott Ullrich
function system_syslogd_start() {
969 f19d3b7a Scott Ullrich
	global $config, $g;
970 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
971 58c7450e Scott Ullrich
		$mt = microtime();
972 dcf0598e Scott Ullrich
		echo "system_syslogd_start() being called $mt\n";
973 58c7450e Scott Ullrich
	}
974 0f282d7a Scott Ullrich
975 1fd3fe31 Scott Ullrich
	mwexec("/etc/rc.d/hostid start");
976
977 5b237745 Scott Ullrich
	$syslogcfg = $config['syslog'];
978
979 61e047a5 Phil Davis
	if (platform_booting()) {
980 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting syslog...");
981 61e047a5 Phil Davis
	}
982 0f282d7a Scott Ullrich
983 7ee97cb3 Scott Ullrich
	// Which logging type are we using this week??
984 100f3e71 Ermal
	if (isset($config['system']['disablesyslogclog'])) {
985
		$log_directive = "";
986
		$log_create_directive = "/usr/bin/touch ";
987
		$log_size = "";
988 7ee97cb3 Scott Ullrich
	} else { // Defaults to CLOG
989 100f3e71 Ermal
		$log_directive = "%";
990 c7a3356e jim-p
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
991 2a50fd8a Renato Botelho
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
992 7ee97cb3 Scott Ullrich
	}
993 66201c96 Ermal
994
	$syslogd_extra = "";
995 88ebd635 Scott Ullrich
	if (isset($syslogcfg)) {
996 957ec89e doktornotor
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'olsrd', 'zebra', 'ospfd', 'bgpd', 'miniupnpd', 'filterlog');
997 344016a8 Ermal
		$syslogconf = "";
998 61e047a5 Phil Davis
		if ($config['installedpackages']['package']) {
999
			foreach ($config['installedpackages']['package'] as $package) {
1000 ab31acb9 k-paulius
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
1001 d589cccf Warren Baker
					array_push($separatelogfacilities, $package['logging']['facilityname']);
1002 086cf944 Phil Davis
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
1003 6587e2af Robert Nelson
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
1004 086cf944 Phil Davis
					}
1005 eeb52fea Warren Baker
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
1006 a728d2ea Colin Smith
				}
1007 0d9d2a1b Scott Ullrich
			}
1008
		}
1009 d2834563 Scott Ullrich
		$facilitylist = implode(',', array_unique($separatelogfacilities));
1010 5c8cbb26 jim-p
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
1011 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1012 e0c45357 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
1013 61e047a5 Phil Davis
		}
1014 d2013d12 jim-p
		if (isset($syslogcfg['routing'])) {
1015
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1016
		}
1017 e0c45357 jim-p
1018
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
1019 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1020 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
1021 61e047a5 Phil Davis
		}
1022 d2013d12 jim-p
		if (isset($syslogcfg['ntpd'])) {
1023
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1024
		}
1025 236524c2 jim-p
1026 295e19dd Scott Ullrich
		$syslogconf .= "!ppp\n";
1027 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1028 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
1029 61e047a5 Phil Davis
		}
1030 d2013d12 jim-p
		if (isset($syslogcfg['ppp'])) {
1031
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1032
		}
1033 236524c2 jim-p
1034 a6607b5f jim-p
		$syslogconf .= "!poes\n";
1035 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1036 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
1037 61e047a5 Phil Davis
		}
1038 d2013d12 jim-p
		if (isset($syslogcfg['vpn'])) {
1039
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1040
		}
1041 236524c2 jim-p
1042 a6607b5f jim-p
		$syslogconf .= "!l2tps\n";
1043 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1044 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
1045 61e047a5 Phil Davis
		}
1046 d2013d12 jim-p
		if (isset($syslogcfg['vpn'])) {
1047
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1048
		}
1049 236524c2 jim-p
1050 20a95904 Ermal
		$syslogconf .= "!charon,ipsec_starter\n";
1051 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1052 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
1053 61e047a5 Phil Davis
		}
1054
		if (isset($syslogcfg['vpn'])) {
1055 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1056 61e047a5 Phil Davis
		}
1057 236524c2 jim-p
1058 d2834563 Scott Ullrich
		$syslogconf .= "!openvpn\n";
1059 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1060 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
1061 61e047a5 Phil Davis
		}
1062
		if (isset($syslogcfg['vpn'])) {
1063 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1064 61e047a5 Phil Davis
		}
1065 236524c2 jim-p
1066 69eefb50 Renato Botelho
		$syslogconf .= "!dpinger\n";
1067 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1068 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
1069 61e047a5 Phil Davis
		}
1070 69eefb50 Renato Botelho
		if (isset($syslogcfg['dpinger'])) {
1071 e0977fed smos
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1072 61e047a5 Phil Davis
		}
1073 e0977fed smos
1074 957ec89e doktornotor
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1075 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1076 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1077 61e047a5 Phil Davis
		}
1078 d2013d12 jim-p
		if (isset($syslogcfg['resolver'])) {
1079
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1080
		}
1081 e0977fed smos
1082 08acb038 Chris Buechler
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
1083 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1084 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
1085 61e047a5 Phil Davis
		}
1086
		if (isset($syslogcfg['dhcp'])) {
1087 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1088 61e047a5 Phil Davis
		}
1089 236524c2 jim-p
1090 087a89f8 Chris Buechler
		$syslogconf .= "!relayd\n";
1091 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1092 236524c2 jim-p
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
1093 61e047a5 Phil Davis
		}
1094
		if (isset($syslogcfg['relayd'])) {
1095 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1096 61e047a5 Phil Davis
		}
1097 236524c2 jim-p
1098 689eaa4d jim-p
		$syslogconf .= "!hostapd\n";
1099 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1100 236524c2 jim-p
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
1101 61e047a5 Phil Davis
		}
1102
		if (isset($syslogcfg['hostapd'])) {
1103 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1104 61e047a5 Phil Davis
		}
1105 236524c2 jim-p
1106 686777c4 Ermal
		$syslogconf .= "!filterlog\n";
1107 54bbb646 Chris Buechler
		if (!isset($syslogcfg['disablelocallogging'])) {
1108
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
1109
		}
1110 61e047a5 Phil Davis
		if (isset($syslogcfg['filter'])) {
1111 686777c4 Ermal
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1112 61e047a5 Phil Davis
		}
1113 686777c4 Ermal
1114 d2834563 Scott Ullrich
		$syslogconf .= "!-{$facilitylist}\n";
1115 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
1116 5b237745 Scott Ullrich
			$syslogconf .= <<<EOD
1117 236524c2 jim-p
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1118
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1119 be6da8a4 Chris Buechler
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1120 236524c2 jim-p
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1121 7d4d7822 Phil Davis
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;news.err;local0.none;local3.none;local4.none;local7.none;security.*;auth.info;authpriv.info;daemon.info	{$log_directive}{$g['varlog_path']}/system.log
1122 236524c2 jim-p
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
1123
*.emerg								*
1124 be5d59d7 Scott Ullrich
1125
EOD;
1126 61e047a5 Phil Davis
		}
1127
		if (isset($syslogcfg['vpn'])) {
1128 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1129 61e047a5 Phil Davis
		}
1130
		if (isset($syslogcfg['portalauth'])) {
1131 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1132 61e047a5 Phil Davis
		}
1133
		if (isset($syslogcfg['dhcp'])) {
1134 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1135 61e047a5 Phil Davis
		}
1136 be5d59d7 Scott Ullrich
		if (isset($syslogcfg['system'])) {
1137 7d4d7822 Phil Davis
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg;*.notice;kern.debug;lpr.info;mail.crit;news.err;local0.none;local3.none;local7.none;security.*;auth.info;authpriv.info;daemon.info");
1138 236524c2 jim-p
		}
1139 4ef2d703 Chris Buechler
		if (isset($syslogcfg['logall'])) {
1140 236524c2 jim-p
			// Make everything mean everything, including facilities excluded above.
1141
			$syslogconf .= "!*\n";
1142
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1143
		}
1144 be5d59d7 Scott Ullrich
1145 a213ad18 Andrew Thompson
		if (isset($syslogcfg['zmqserver'])) {
1146
				$syslogconf .= <<<EOD
1147
*.*								^{$syslogcfg['zmqserver']}
1148
1149
EOD;
1150
		}
1151 61e047a5 Phil Davis
		/* write syslog.conf */
1152 fc84b222 Renato Botelho
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1153 344016a8 Ermal
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1154
			unset($syslogconf);
1155
			return 1;
1156
		}
1157
		unset($syslogconf);
1158 42ee8bde Scott Ullrich
1159 cbe12b8d jim-p
		$sourceip = "";
1160
		if (!empty($syslogcfg['sourceip'])) {
1161
			if ($syslogcfg['ipproto'] == "ipv6") {
1162
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1163 61e047a5 Phil Davis
				if (!is_ipaddr($ifaddr)) {
1164 cbe12b8d jim-p
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1165 61e047a5 Phil Davis
				}
1166 cbe12b8d jim-p
			} else {
1167
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1168 61e047a5 Phil Davis
				if (!is_ipaddr($ifaddr)) {
1169 cbe12b8d jim-p
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1170 61e047a5 Phil Davis
				}
1171 cbe12b8d jim-p
			}
1172
			if (is_ipaddr($ifaddr)) {
1173
				$sourceip = "-b {$ifaddr}";
1174
			}
1175
		}
1176
1177 fc84b222 Renato Botelho
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1178 5b237745 Scott Ullrich
	}
1179 0f282d7a Scott Ullrich
1180 b2836666 k-paulius
	$log_sockets = array("{$g['dhcpd_chroot_path']}/var/run/log");
1181 ab31acb9 k-paulius
1182
	if (isset($config['installedpackages']['package'])) {
1183
		foreach ($config['installedpackages']['package'] as $package) {
1184 b2836666 k-paulius
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1185
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1186 ab31acb9 k-paulius
				$log_sockets[] = $package['logging']['logsocket'];
1187
			}
1188
		}
1189
	}
1190 4406922e PiBa-NL
	
1191 ab31acb9 k-paulius
	$syslogd_sockets = "";
1192
	foreach ($log_sockets as $log_socket) {
1193 4406922e PiBa-NL
		// Ensure that the log directory exists
1194
		$logpath = dirname($log_socket);
1195
		safe_mkdir($logpath);
1196 ab31acb9 k-paulius
		$syslogd_sockets .= " -l {$log_socket}";
1197
	}
1198
1199 209ba3aa Chris Buechler
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1200 f1905a3e Chris Buechler
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1201 209ba3aa Chris Buechler
		usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1202
	}
1203 61e047a5 Phil Davis
1204 209ba3aa Chris Buechler
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1205 61e047a5 Phil Davis
		// if it still hasn't responded to the TERM, KILL it.
1206 209ba3aa Chris Buechler
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1207 61e047a5 Phil Davis
		usleep(100000);
1208 209ba3aa Chris Buechler
	}
1209
1210 ab31acb9 k-paulius
	$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1211 66201c96 Ermal
1212 61e047a5 Phil Davis
	if (platform_booting()) {
1213 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1214 61e047a5 Phil Davis
	}
1215 0f282d7a Scott Ullrich
1216 5b237745 Scott Ullrich
	return $retval;
1217
}
1218
1219 7c4c77ee jim-p
function system_webgui_create_certificate() {
1220
	global $config, $g;
1221
1222 61e047a5 Phil Davis
	if (!is_array($config['ca'])) {
1223 7c4c77ee jim-p
		$config['ca'] = array();
1224 61e047a5 Phil Davis
	}
1225 7c4c77ee jim-p
	$a_ca =& $config['ca'];
1226 61e047a5 Phil Davis
	if (!is_array($config['cert'])) {
1227 7c4c77ee jim-p
		$config['cert'] = array();
1228 61e047a5 Phil Davis
	}
1229 7c4c77ee jim-p
	$a_cert =& $config['cert'];
1230 e8c516a0 Phil Davis
	log_error(gettext("Creating SSL Certificate for this host"));
1231 7c4c77ee jim-p
1232
	$cert = array();
1233
	$cert['refid'] = uniqid();
1234 e8c516a0 Phil Davis
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1235 7c4c77ee jim-p
1236
	$dn = array(
1237
		'countryName' => "US",
1238
		'stateOrProvinceName' => "State",
1239
		'localityName' => "Locality",
1240
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1241
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1242 2cf2c62b jim-p
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
1243 f416763b Phil Davis
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1244 61e047a5 Phil Davis
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1245
		while ($ssl_err = openssl_error_string()) {
1246 e8c516a0 Phil Davis
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1247 7c4c77ee jim-p
		}
1248
		error_reporting($old_err_level);
1249
		return null;
1250
	}
1251
	error_reporting($old_err_level);
1252
1253
	$a_cert[] = $cert;
1254
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1255 e8c516a0 Phil Davis
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1256 7c4c77ee jim-p
	return $cert;
1257
}
1258
1259 5b237745 Scott Ullrich
function system_webgui_start() {
1260 f19d3b7a Scott Ullrich
	global $config, $g;
1261 877ac35d Scott Ullrich
1262 61e047a5 Phil Davis
	if (platform_booting()) {
1263 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting webConfigurator...");
1264 61e047a5 Phil Davis
	}
1265 877ac35d Scott Ullrich
1266
	chdir($g['www_path']);
1267
1268 fb1266d3 Matthew Grooms
	/* defaults */
1269
	$portarg = "80";
1270
	$crt = "";
1271
	$key = "";
1272 2cf6ddcb Nigel Graham
	$ca = "";
1273 fb1266d3 Matthew Grooms
1274 877ac35d Scott Ullrich
	/* non-standard port? */
1275 61e047a5 Phil Davis
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1276 528df9a7 Scott Ullrich
		$portarg = "{$config['system']['webgui']['port']}";
1277 61e047a5 Phil Davis
	}
1278 877ac35d Scott Ullrich
1279
	if ($config['system']['webgui']['protocol'] == "https") {
1280 02b383fe sullrich
		// Ensure that we have a webConfigurator CERT
1281 fb1266d3 Matthew Grooms
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1282 61e047a5 Phil Davis
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1283 7c4c77ee jim-p
			$cert = system_webgui_create_certificate();
1284 61e047a5 Phil Davis
		}
1285 0a8dd27b Renato Botelho
		$crt = base64_decode($cert['crt']);
1286
		$key = base64_decode($cert['prv']);
1287 7c4c77ee jim-p
1288 61e047a5 Phil Davis
		if (!$config['system']['webgui']['port']) {
1289 7c4c77ee jim-p
			$portarg = "443";
1290 61e047a5 Phil Davis
		}
1291 6c07db48 Phil Davis
		$ca = ca_chain($cert);
1292 877ac35d Scott Ullrich
	}
1293
1294 1e8599e5 Chris Buechler
	/* generate nginx configuration */
1295
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1296 257fdefe Chris Buechler
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1297 1e8599e5 Chris Buechler
		"cert.crt", "cert.key");
1298 877ac35d Scott Ullrich
1299 1e8599e5 Chris Buechler
	/* kill any running nginx */
1300
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1301 a11bc497 Ermal
1302
	sleep(1);
1303
1304 1e8599e5 Chris Buechler
	@unlink("{$g['varrun_path']}/nginx-webConfigurator.pid");
1305 a11bc497 Ermal
1306 1e8599e5 Chris Buechler
	/* start nginx */
1307
	$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-webConfigurator.conf");
1308 877ac35d Scott Ullrich
1309 285ef132 Ermal LUÇI
	if (platform_booting()) {
1310 61e047a5 Phil Davis
		if ($res == 0) {
1311 4a896b86 Carlos Eduardo Ramos
			echo gettext("done.") . "\n";
1312 61e047a5 Phil Davis
		} else {
1313 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
1314 61e047a5 Phil Davis
		}
1315 877ac35d Scott Ullrich
	}
1316
1317
	return $res;
1318
}
1319
1320 1e8599e5 Chris Buechler
function system_generate_nginx_config($filename,
1321 eb0f441c Scott Ullrich
	$cert,
1322
	$key,
1323 257fdefe Chris Buechler
	$ca,
1324 eb0f441c Scott Ullrich
	$pid_file,
1325
	$port = 80,
1326
	$document_root = "/usr/local/www/",
1327 1e8599e5 Chris Buechler
	$cert_location = "cert.crt",
1328
	$key_location = "cert.key",
1329 eb0f441c Scott Ullrich
	$captive_portal = false) {
1330 58c7450e Scott Ullrich
1331 f19d3b7a Scott Ullrich
	global $config, $g;
1332
1333 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1334 58c7450e Scott Ullrich
		$mt = microtime();
1335 1e8599e5 Chris Buechler
		echo "system_generate_nginx_config() being called $mt\n";
1336 58c7450e Scott Ullrich
	}
1337
1338 6c07db48 Phil Davis
	if ($captive_portal !== false) {
1339 1d0c3a10 Chris Buechler
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1340
		$cp_hostcheck = "";
1341
		foreach ($cp_interfaces as $cpint) {
1342
			$cpint_ip = get_interface_ip($cpint);
1343
			if (is_ipaddr($cpint_ip)) {
1344 8f10bc95 Chris Buechler
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1345 1d0c3a10 Chris Buechler
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1346 d1f9426a Renato Botelho
				$cp_hostcheck .= "\t\t}\n";
1347 1d0c3a10 Chris Buechler
			}
1348
		}
1349 716d10e0 Renato Botelho
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1350
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1351 8f10bc95 Chris Buechler
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1352 1d0c3a10 Chris Buechler
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1353
			$cp_hostcheck .= "\t\t}\n";
1354
		}
1355
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1356 d47fe949 Chris Buechler
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1357 1d0c3a10 Chris Buechler
		$cp_rewrite .= "\t\t}\n";
1358
1359 6844896c bcyrill
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1360 61e047a5 Phil Davis
		if (empty($maxprocperip)) {
1361 f7bddb24 Ermal
			$maxprocperip = 10;
1362 61e047a5 Phil Davis
		}
1363 f225cb92 Chris Buechler
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1364 d1f9426a Renato Botelho
	}
1365 61e047a5 Phil Davis
1366
	if (empty($port)) {
1367 1e8599e5 Chris Buechler
		$nginx_port = "80";
1368 61e047a5 Phil Davis
	} else {
1369 1e8599e5 Chris Buechler
		$nginx_port = $port;
1370 61e047a5 Phil Davis
	}
1371 3d77d4c4 Scott Ullrich
1372
	$memory = get_memory();
1373 6b0739ac Phil Davis
	$realmem = $memory[1];
1374 3d77d4c4 Scott Ullrich
1375 98f20e35 Irving Popovetsky
	// Determine web GUI process settings and take into account low memory systems
1376 61e047a5 Phil Davis
	if ($realmem < 255) {
1377 a96f2d3d Ermal
		$max_procs = 1;
1378 61e047a5 Phil Davis
	} else {
1379 98f20e35 Irving Popovetsky
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1380 61e047a5 Phil Davis
	}
1381 f4ebc84a Scott Ullrich
1382 61e047a5 Phil Davis
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1383 6c07db48 Phil Davis
	if ($captive_portal !== false) {
1384 6b0739ac Phil Davis
		if ($realmem > 135 and $realmem < 256) {
1385 98f20e35 Irving Popovetsky
			$max_procs += 1; // 2 worker processes
1386 6b0739ac Phil Davis
		} else if ($realmem > 255 and $realmem < 513) {
1387 a96f2d3d Ermal
			$max_procs += 2; // 3 worker processes
1388 6b0739ac Phil Davis
		} else if ($realmem > 512) {
1389 98f20e35 Irving Popovetsky
			$max_procs += 4; // 6 worker processes
1390 70cc6249 Scott Ullrich
		}
1391 d1f9426a Renato Botelho
	}
1392 980df75c Scott Ullrich
1393 1e8599e5 Chris Buechler
	$nginx_config = <<<EOD
1394 28cae949 Scott Ullrich
#
1395 1e8599e5 Chris Buechler
# nginx configuration file
1396 a632cf43 Scott Ullrich
1397 1e8599e5 Chris Buechler
pid {$g['varrun_path']}/{$pid_file};
1398 096261af Scott Ullrich
1399 1e8599e5 Chris Buechler
user  root wheel;
1400
worker_processes  {$max_procs};
1401 28cae949 Scott Ullrich
1402 f77f43ff Chris Buechler
EOD;
1403
1404 8e2090a1 Jose Luis Duran
	if (!isset($config['syslog']['nolognginx'])) {
1405
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1406
	}
1407 f77f43ff Chris Buechler
1408 8e2090a1 Jose Luis Duran
	$nginx_config .= <<<EOD
1409 1e8599e5 Chris Buechler
1410
events {
1411
    worker_connections  1024;
1412
}
1413 a632cf43 Scott Ullrich
1414 1e8599e5 Chris Buechler
http {
1415
	include       /usr/local/etc/nginx/mime.types;
1416
	default_type  application/octet-stream;
1417
	add_header X-Frame-Options SAMEORIGIN;
1418
	server_tokens off;
1419 a632cf43 Scott Ullrich
1420 1e8599e5 Chris Buechler
	sendfile        on;
1421 a632cf43 Scott Ullrich
1422 be6da8a4 Chris Buechler
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1423 2400f545 Jose Luis Duran
1424 f225cb92 Chris Buechler
EOD;
1425
1426 8e2090a1 Jose Luis Duran
	if ($captive_portal !== false) {
1427
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1428 754f7091 Chris Buechler
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1429
	} else {
1430
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1431 8e2090a1 Jose Luis Duran
	}
1432 9cb94dd4 Ermal
1433 61e047a5 Phil Davis
	if ($cert <> "" and $key <> "") {
1434 8e2090a1 Jose Luis Duran
		$nginx_config .= "\n";
1435
		$nginx_config .= "\tserver {\n";
1436
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1437
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1438
		$nginx_config .= "\n";
1439 1e8599e5 Chris Buechler
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1440
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1441 d1f9426a Renato Botelho
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1442
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1443 66a962cb Chris Buechler
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1444 677f0a18 Chris Buechler
		if ($captive_portal !== false) {
1445
			// leave TLSv1.0 for CP for now for compatibility
1446
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1447
		} else {
1448
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1449
		}
1450 1e8599e5 Chris Buechler
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1451
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1452 657cb0db Jose Luis Duran
		$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1453 1e8599e5 Chris Buechler
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1454
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1455 02ba2c97 Chris Buechler
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1456 8e2090a1 Jose Luis Duran
	} else {
1457 1e8599e5 Chris Buechler
		$nginx_config .= "\n";
1458 8e2090a1 Jose Luis Duran
		$nginx_config .= "\tserver {\n";
1459
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1460
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1461 1e8599e5 Chris Buechler
	}
1462
1463 8e2090a1 Jose Luis Duran
	$nginx_config .= <<<EOD
1464
1465
		client_max_body_size 200m;
1466
1467
		gzip on;
1468
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1469
1470
1471
EOD;
1472
1473 1d0c3a10 Chris Buechler
	if ($captive_portal !== false) {
1474
		$nginx_config .= <<<EOD
1475 f225cb92 Chris Buechler
$captive_portal_maxprocperip
1476 1d0c3a10 Chris Buechler
$cp_hostcheck
1477
$cp_rewrite
1478 2f004405 Chris Buechler
		log_not_found off;
1479 1d0c3a10 Chris Buechler
1480
EOD;
1481
1482
	}
1483
1484 1e8599e5 Chris Buechler
	$nginx_config .= <<<EOD
1485
		root "{$document_root}";
1486
		location / {
1487 3a643eb8 Chris Buechler
			index  index.php index.html index.htm;
1488 1e8599e5 Chris Buechler
		}
1489
1490
		location ~ \.php$ {
1491
			try_files \$uri =404; #  This line closes a potential security hole
1492 d1f9426a Renato Botelho
			# ensuring users can't execute uploaded files
1493
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1494 1e8599e5 Chris Buechler
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1495
			fastcgi_index  index.php;
1496
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1497 2039a3c1 Renato Botelho
			# Fix httpoxy - https://httpoxy.org/#fix-now
1498
			fastcgi_param  HTTP_PROXY  "";
1499 3fafb89b Chris Buechler
			fastcgi_read_timeout 180;
1500 1e8599e5 Chris Buechler
			include        /usr/local/etc/nginx/fastcgi_params;
1501 61e047a5 Phil Davis
		}
1502 543ecd59 Seth Mos
	}
1503 569f47e9 Scott Ullrich
1504 a632cf43 Scott Ullrich
EOD;
1505
1506 7aae518a Scott Ullrich
	$cert = str_replace("\r", "", $cert);
1507 333f8ef0 Scott Ullrich
	$key = str_replace("\r", "", $key);
1508 7aae518a Scott Ullrich
1509
	$cert = str_replace("\n\n", "\n", $cert);
1510 333f8ef0 Scott Ullrich
	$key = str_replace("\n\n", "\n", $key);
1511 7aae518a Scott Ullrich
1512 61e047a5 Phil Davis
	if ($cert <> "" and $key <> "") {
1513 3a66b621 Scott Ullrich
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1514 5b237745 Scott Ullrich
		if (!$fd) {
1515 1e8599e5 Chris Buechler
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1516 5b237745 Scott Ullrich
			return 1;
1517
		}
1518 3a66b621 Scott Ullrich
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1519 32818dd9 Chris Buechler
		if ($ca <> "") {
1520
			$cert_chain = $cert . "\n" . $ca;
1521
		} else {
1522
			$cert_chain = $cert;
1523
		}
1524
		fwrite($fd, $cert_chain);
1525 5b237745 Scott Ullrich
		fclose($fd);
1526 1e8599e5 Chris Buechler
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1527
		if (!$fd) {
1528
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1529
			return 1;
1530 61e047a5 Phil Davis
		}
1531 1e8599e5 Chris Buechler
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1532
		fwrite($fd, $key);
1533
		fclose($fd);
1534 5b237745 Scott Ullrich
	}
1535 a978a0ff Chris Buechler
1536 61e047a5 Phil Davis
	// Add HTTP to HTTPS redirect
1537 6839a678 Ermal
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1538 1e8599e5 Chris Buechler
		if ($nginx_port != "443") {
1539
			$redirectport = ":{$nginx_port}";
1540 61e047a5 Phil Davis
		}
1541 1e8599e5 Chris Buechler
		$nginx_config .= <<<EOD
1542
	server {
1543
		listen 80;
1544
		listen [::]:80;
1545 8e2090a1 Jose Luis Duran
		return 301 https://\$http_host$redirectport\$request_uri;
1546 64a2da80 Chris Buechler
	}
1547 1e8599e5 Chris Buechler
1548 d7e230ae Chris Buechler
EOD;
1549
	}
1550 d1f9426a Renato Botelho
1551 1e8599e5 Chris Buechler
	$nginx_config .= "}\n";
1552 0f282d7a Scott Ullrich
1553 4f3756f3 Scott Ullrich
	$fd = fopen("{$filename}", "w");
1554 a632cf43 Scott Ullrich
	if (!$fd) {
1555 1e8599e5 Chris Buechler
		printf(gettext("Error: cannot open %s in system_generate_nginx_config().%s"), $filename, "\n");
1556 a632cf43 Scott Ullrich
		return 1;
1557 5b237745 Scott Ullrich
	}
1558 1e8599e5 Chris Buechler
	fwrite($fd, $nginx_config);
1559 a632cf43 Scott Ullrich
	fclose($fd);
1560
1561 ab4e9539 jim-p
	/* nginx will fail to start if this directory does not exist. */
1562
	safe_mkdir("/var/tmp/nginx/");
1563
1564 a632cf43 Scott Ullrich
	return 0;
1565 0f282d7a Scott Ullrich
1566 5b237745 Scott Ullrich
}
1567
1568 60ff91f1 Renato Botelho
function system_get_timezone_list() {
1569
	global $g;
1570
1571 fc3bec29 Renato Botelho
	$file_list = array_merge(
1572
		glob("/usr/share/zoneinfo/[A-Z]*"),
1573 97433447 jim-p
		glob("/usr/share/zoneinfo/*/*"),
1574
		glob("/usr/share/zoneinfo/*/*/*")
1575 fc3bec29 Renato Botelho
	);
1576 60ff91f1 Renato Botelho
1577
	if (empty($file_list)) {
1578
		$file_list[] = $g['default_timezone'];
1579 fc3bec29 Renato Botelho
	} else {
1580
		/* Remove directories from list */
1581
		$file_list = array_filter($file_list, function($v) {
1582
			return !is_dir($v);
1583
		});
1584 60ff91f1 Renato Botelho
	}
1585
1586 fc3bec29 Renato Botelho
	/* Remove directory prefix */
1587
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1588
1589
	sort($file_list);
1590
1591
	return $file_list;
1592 60ff91f1 Renato Botelho
}
1593
1594 5b237745 Scott Ullrich
function system_timezone_configure() {
1595 f19d3b7a Scott Ullrich
	global $config, $g;
1596 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1597 58c7450e Scott Ullrich
		$mt = microtime();
1598 dcf0598e Scott Ullrich
		echo "system_timezone_configure() being called $mt\n";
1599 333f8ef0 Scott Ullrich
	}
1600 5b237745 Scott Ullrich
1601
	$syscfg = $config['system'];
1602
1603 61e047a5 Phil Davis
	if (platform_booting()) {
1604 4a896b86 Carlos Eduardo Ramos
		echo gettext("Setting timezone...");
1605 61e047a5 Phil Davis
	}
1606 5b237745 Scott Ullrich
1607
	/* extract appropriate timezone file */
1608 60ff91f1 Renato Botelho
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1609 c9ab2622 Chris Buechler
	/* DO NOT remove \n otherwise tzsetup will fail */
1610 60ff91f1 Renato Botelho
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1611
	mwexec("/usr/sbin/tzsetup -r");
1612 34febcde Scott Ullrich
1613 61e047a5 Phil Davis
	if (platform_booting()) {
1614 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1615 61e047a5 Phil Davis
	}
1616 5b237745 Scott Ullrich
}
1617
1618 5c8843d5 jim-p
function system_ntp_setup_gps($serialport) {
1619 142f7393 nagyrobi
	global $config, $g;
1620 5c8843d5 jim-p
	$gps_device = '/dev/gps0';
1621
	$serialport = '/dev/'.$serialport;
1622
1623 61e047a5 Phil Davis
	if (!file_exists($serialport)) {
1624 5c8843d5 jim-p
		return false;
1625 61e047a5 Phil Davis
	}
1626 5c8843d5 jim-p
1627
	// Create symlink that ntpd requires
1628
	unlink_if_exists($gps_device);
1629 11caacf6 Ermal LUÇI
	@symlink($serialport, $gps_device);
1630 5c8843d5 jim-p
1631 1e329241 Robert Noland
	$gpsbaud = '4800';
1632
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1633
		switch ($config['ntpd']['gps']['speed']) {
1634
			case '16':
1635
				$gpsbaud = '9600';
1636
				break;
1637
			case '32':
1638
				$gpsbaud = '19200';
1639
				break;
1640
			case '48':
1641
				$gpsbaud = '38400';
1642
				break;
1643
			case '64':
1644
				$gpsbaud = '57600';
1645
				break;
1646
			case '80':
1647
				$gpsbaud = '115200';
1648
				break;
1649
		}
1650
	}
1651
1652
	/* Configure the serial port for raw IO and set the speed */
1653 417008f7 Renato Botelho
	mwexec("stty -f {$serialport}.init raw speed {$gpsbaud}");
1654 1e329241 Robert Noland
1655 5c8843d5 jim-p
	/* Send the following to the GPS port to initialize the GPS */
1656 ec7bc948 Ermal
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1657 142f7393 nagyrobi
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1658 61e047a5 Phil Davis
	} else {
1659 142f7393 nagyrobi
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1660
	}
1661 ec7bc948 Ermal
1662
	/* XXX: Why not file_put_contents to the device */
1663
	@file_put_contents('/tmp/gps.init', $gps_init);
1664 417008f7 Renato Botelho
	mwexec("cat /tmp/gps.init > {$serialport}");
1665 5c8843d5 jim-p
1666
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1667 ec7bc948 Ermal
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1668 0771de32 jim-p
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:\n", FILE_APPEND);
1669 ec7bc948 Ermal
	}
1670 5c8843d5 jim-p
1671
1672
	return true;
1673
}
1674
1675 142f7393 nagyrobi
function system_ntp_setup_pps($serialport) {
1676
	global $config, $g;
1677 ec7bc948 Ermal
1678 142f7393 nagyrobi
	$pps_device = '/dev/pps0';
1679
	$serialport = '/dev/'.$serialport;
1680
1681 61e047a5 Phil Davis
	if (!file_exists($serialport)) {
1682 142f7393 nagyrobi
		return false;
1683 61e047a5 Phil Davis
	}
1684 142f7393 nagyrobi
1685
	// Create symlink that ntpd requires
1686
	unlink_if_exists($pps_device);
1687 ec7bc948 Ermal
	@symlink($serialport, $pps_device);
1688 142f7393 nagyrobi
1689
1690
	return true;
1691
}
1692
1693
1694 2dced82f Renato Botelho
function system_ntp_configure() {
1695 f19d3b7a Scott Ullrich
	global $config, $g;
1696 ec7bc948 Ermal
1697 42135f07 jim-p
	$driftfile = "/var/db/ntpd.drift";
1698 5c8843d5 jim-p
	$statsdir = "/var/log/ntp";
1699
	$gps_device = '/dev/gps0';
1700 5b237745 Scott Ullrich
1701 5c8843d5 jim-p
	safe_mkdir($statsdir);
1702
1703 61e047a5 Phil Davis
	if (!is_array($config['ntpd'])) {
1704 ec7bc948 Ermal
		$config['ntpd'] = array();
1705 61e047a5 Phil Davis
	}
1706 ec7bc948 Ermal
1707 b2305621 Ermal
	$ntpcfg = "# \n";
1708 42135f07 jim-p
	$ntpcfg .= "# pfSense ntp configuration file \n";
1709 b2305621 Ermal
	$ntpcfg .= "# \n\n";
1710 362c9bb0 jim-p
	$ntpcfg .= "tinker panic 0 \n";
1711 0f282d7a Scott Ullrich
1712 142f7393 nagyrobi
	/* Add Orphan mode */
1713
	$ntpcfg .= "# Orphan mode stratum\n";
1714
	$ntpcfg .= 'tos orphan ';
1715
	if (!empty($config['ntpd']['orphan'])) {
1716
		$ntpcfg .= $config['ntpd']['orphan'];
1717 61e047a5 Phil Davis
	} else {
1718 142f7393 nagyrobi
		$ntpcfg .= '12';
1719
	}
1720
	$ntpcfg .= "\n";
1721
1722
	/* Add PPS configuration */
1723 61e047a5 Phil Davis
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1724
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1725
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1726 142f7393 nagyrobi
		$ntpcfg .= "\n";
1727
		$ntpcfg .= "# PPS Setup\n";
1728
		$ntpcfg .= 'server 127.127.22.0';
1729
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1730
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1731 61e047a5 Phil Davis
			$ntpcfg .= ' prefer';
1732 142f7393 nagyrobi
		}
1733
		if (!empty($config['ntpd']['pps']['noselect'])) {
1734
			$ntpcfg .= ' noselect ';
1735
		}
1736
		$ntpcfg .= "\n";
1737
		$ntpcfg .= 'fudge 127.127.22.0';
1738
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1739
			$ntpcfg .= ' time1 ';
1740
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1741
		}
1742
		if (!empty($config['ntpd']['pps']['flag2'])) {
1743
			$ntpcfg .= ' flag2 1';
1744
		}
1745
		if (!empty($config['ntpd']['pps']['flag3'])) {
1746
			$ntpcfg .= ' flag3 1';
1747 61e047a5 Phil Davis
		} else {
1748 142f7393 nagyrobi
			$ntpcfg .= ' flag3 0';
1749
		}
1750
		if (!empty($config['ntpd']['pps']['flag4'])) {
1751
			$ntpcfg .= ' flag4 1';
1752
		}
1753
		if (!empty($config['ntpd']['pps']['refid'])) {
1754
			$ntpcfg .= ' refid ';
1755
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1756
		}
1757
		$ntpcfg .= "\n";
1758
	}
1759
	/* End PPS configuration */
1760
1761
	/* Add GPS configuration */
1762 61e047a5 Phil Davis
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1763
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1764
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1765 142f7393 nagyrobi
		$ntpcfg .= "\n";
1766
		$ntpcfg .= "# GPS Setup\n";
1767
		$ntpcfg .= 'server 127.127.20.0 mode ';
1768
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1769
			if (!empty($config['ntpd']['gps']['nmea'])) {
1770
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1771
			}
1772
			if (!empty($config['ntpd']['gps']['speed'])) {
1773
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1774
			}
1775
			if (!empty($config['ntpd']['gps']['subsec'])) {
1776
				$ntpmode += 128;
1777
			}
1778
			$ntpcfg .= (string) $ntpmode;
1779 61e047a5 Phil Davis
		} else {
1780 142f7393 nagyrobi
			$ntpcfg .= '0';
1781
		}
1782
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1783
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1784 61e047a5 Phil Davis
			$ntpcfg .= ' prefer';
1785 142f7393 nagyrobi
		}
1786
		if (!empty($config['ntpd']['gps']['noselect'])) {
1787
			$ntpcfg .= ' noselect ';
1788
		}
1789
		$ntpcfg .= "\n";
1790
		$ntpcfg .= 'fudge 127.127.20.0';
1791
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1792
			$ntpcfg .= ' time1 ';
1793
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1794
		}
1795
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1796
			$ntpcfg .= ' time2 ';
1797
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1798
		}
1799
		if (!empty($config['ntpd']['gps']['flag1'])) {
1800
			$ntpcfg .= ' flag1 1';
1801 61e047a5 Phil Davis
		} else {
1802 142f7393 nagyrobi
			$ntpcfg .= ' flag1 0';
1803
		}
1804
		if (!empty($config['ntpd']['gps']['flag2'])) {
1805
			$ntpcfg .= ' flag2 1';
1806
		}
1807
		if (!empty($config['ntpd']['gps']['flag3'])) {
1808
			$ntpcfg .= ' flag3 1';
1809 61e047a5 Phil Davis
		} else {
1810 142f7393 nagyrobi
			$ntpcfg .= ' flag3 0';
1811
		}
1812
		if (!empty($config['ntpd']['gps']['flag4'])) {
1813
			$ntpcfg .= ' flag4 1';
1814
		}
1815
		if (!empty($config['ntpd']['gps']['refid'])) {
1816
			$ntpcfg .= ' refid ';
1817
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1818
		}
1819 66937f5c Jean Cyr
		if (!empty($config['ntpd']['gps']['stratum'])) {
1820
			$ntpcfg .= ' stratum ';
1821
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1822
		}
1823 142f7393 nagyrobi
		$ntpcfg .= "\n";
1824 61e047a5 Phil Davis
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1825
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1826
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1827 142f7393 nagyrobi
		/* This handles a 2.1 and earlier config */
1828 5c8843d5 jim-p
		$ntpcfg .= "# GPS Setup\n";
1829
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1830
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1831
		// Fall back to local clock if GPS is out of sync?
1832
		$ntpcfg .= "server 127.127.1.0\n";
1833
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1834
	}
1835 142f7393 nagyrobi
	/* End GPS configuration */
1836 fbb652ed jim-p
	$auto_pool_suffix = "pool.ntp.org";
1837
	$have_pools = false;
1838 5c8843d5 jim-p
	$ntpcfg .= "\n\n# Upstream Servers\n";
1839 142f7393 nagyrobi
	/* foreach through ntp servers and write out to ntpd.conf */
1840
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1841 fbb652ed jim-p
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1842
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1843
			$ntpcfg .= 'pool ';
1844
			$have_pools = true;
1845
		} else {
1846
			$ntpcfg .= 'server ';
1847
		}
1848
1849
		$ntpcfg .= "{$ts} iburst maxpoll 9";
1850 61e047a5 Phil Davis
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1851
			$ntpcfg .= ' prefer';
1852
		}
1853
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1854
			$ntpcfg .= ' noselect';
1855
		}
1856 142f7393 nagyrobi
		$ntpcfg .= "\n";
1857
	}
1858
	unset($ts);
1859
1860
	$ntpcfg .= "\n\n";
1861
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1862
		$ntpcfg .= "enable stats\n";
1863
		$ntpcfg .= 'statistics';
1864
		if (!empty($config['ntpd']['clockstats'])) {
1865
			$ntpcfg .= ' clockstats';
1866
		}
1867
		if (!empty($config['ntpd']['loopstats'])) {
1868
			$ntpcfg .= ' loopstats';
1869
		}
1870
		if (!empty($config['ntpd']['peerstats'])) {
1871
			$ntpcfg .= ' peerstats';
1872
		}
1873
		$ntpcfg .= "\n";
1874
	}
1875 5c8843d5 jim-p
	$ntpcfg .= "statsdir {$statsdir}\n";
1876 142f7393 nagyrobi
	$ntpcfg .= 'logconfig =syncall +clockall';
1877
	if (!empty($config['ntpd']['logpeer'])) {
1878
		$ntpcfg .= ' +peerall';
1879
	}
1880
	if (!empty($config['ntpd']['logsys'])) {
1881
		$ntpcfg .= ' +sysall';
1882
	}
1883
	$ntpcfg .= "\n";
1884 42135f07 jim-p
	$ntpcfg .= "driftfile {$driftfile}\n";
1885 31b15180 jim-p
1886
	/* Default Access restrictions */
1887 142f7393 nagyrobi
	$ntpcfg .= 'restrict default';
1888
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1889 61e047a5 Phil Davis
		$ntpcfg .= ' kod limited';
1890 142f7393 nagyrobi
	}
1891
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1892 61e047a5 Phil Davis
		$ntpcfg .= ' nomodify';
1893 142f7393 nagyrobi
	}
1894
	if (!empty($config['ntpd']['noquery'])) {
1895
		$ntpcfg .= ' noquery';
1896
	}
1897
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1898 61e047a5 Phil Davis
		$ntpcfg .= ' nopeer';
1899 142f7393 nagyrobi
	}
1900
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1901 61e047a5 Phil Davis
		$ntpcfg .= ' notrap';
1902 142f7393 nagyrobi
	}
1903
	if (!empty($config['ntpd']['noserve'])) {
1904
		$ntpcfg .= ' noserve';
1905
	}
1906
	$ntpcfg .= "\nrestrict -6 default";
1907
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1908 61e047a5 Phil Davis
		$ntpcfg .= ' kod limited';
1909 142f7393 nagyrobi
	}
1910
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1911 61e047a5 Phil Davis
		$ntpcfg .= ' nomodify';
1912 142f7393 nagyrobi
	}
1913
	if (!empty($config['ntpd']['noquery'])) {
1914
		$ntpcfg .= ' noquery';
1915
	}
1916
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1917 61e047a5 Phil Davis
		$ntpcfg .= ' nopeer';
1918 142f7393 nagyrobi
	}
1919
	if (!empty($config['ntpd']['noserve'])) {
1920
		$ntpcfg .= ' noserve';
1921
	}
1922
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1923 61e047a5 Phil Davis
		$ntpcfg .= ' notrap';
1924 142f7393 nagyrobi
	}
1925 fbb652ed jim-p
1926
	/* Pools require "restrict source" and cannot contain "nopeer". */
1927
	if ($have_pools) {
1928
		$ntpcfg .= "\nrestrict source";
1929
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1930
			$ntpcfg .= ' kod limited';
1931
		}
1932
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1933
			$ntpcfg .= ' nomodify';
1934
		}
1935
		if (!empty($config['ntpd']['noquery'])) {
1936
			$ntpcfg .= ' noquery';
1937
		}
1938
		if (!empty($config['ntpd']['noserve'])) {
1939
			$ntpcfg .= ' noserve';
1940
		}
1941
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1942
			$ntpcfg .= ' notrap';
1943
		}
1944
	}
1945
1946 31b15180 jim-p
	/* Custom Access Restrictions */
1947
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1948
		$networkacl = $config['ntpd']['restrictions']['row'];
1949
		foreach ($networkacl as $acl) {
1950 d90beba6 jim-p
			$restrict = "";
1951 31b15180 jim-p
			if (is_ipaddrv6($acl['acl_network'])) {
1952 d90beba6 jim-p
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1953 31b15180 jim-p
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1954 d90beba6 jim-p
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
1955 31b15180 jim-p
			} else {
1956
				continue;
1957
			}
1958
			if (!empty($acl['kod'])) {
1959 d90beba6 jim-p
				$restrict .= ' kod limited';
1960 31b15180 jim-p
			}
1961
			if (!empty($acl['nomodify'])) {
1962 d90beba6 jim-p
				$restrict .= ' nomodify';
1963 31b15180 jim-p
			}
1964
			if (!empty($acl['noquery'])) {
1965 d90beba6 jim-p
				$restrict .= ' noquery';
1966 31b15180 jim-p
			}
1967
			if (!empty($acl['nopeer'])) {
1968 d90beba6 jim-p
				$restrict .= ' nopeer';
1969 31b15180 jim-p
			}
1970
			if (!empty($acl['noserve'])) {
1971 d90beba6 jim-p
				$restrict .= ' noserve';
1972 31b15180 jim-p
			}
1973
			if (!empty($acl['notrap'])) {
1974 d90beba6 jim-p
				$restrict .= ' notrap';
1975
			}
1976
			if (!empty($restrict)) {
1977
				$ntpcfg .= "\nrestrict {$restrict} ";
1978 31b15180 jim-p
			}
1979
		}
1980
	}
1981
	/* End Custom Access Restrictions */
1982 142f7393 nagyrobi
1983
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1984
	$ntpcfg .= "\n";
1985
	if (!empty($config['ntpd']['leapsec'])) {
1986
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1987
		file_put_contents('/var/db/leap-seconds', $leapsec);
1988
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1989
	}
1990 61e047a5 Phil Davis
1991 95594e5a Scott Ullrich
1992 51e76899 Ermal LUÇI
	if (empty($config['ntpd']['interface'])) {
1993 61e047a5 Phil Davis
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
1994 cf180ccc jim-p
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1995 61e047a5 Phil Davis
		} else {
1996 cf180ccc jim-p
			$interfaces = array();
1997 61e047a5 Phil Davis
		}
1998
	} else {
1999 cf180ccc jim-p
		$interfaces = explode(",", $config['ntpd']['interface']);
2000 61e047a5 Phil Davis
	}
2001 cf180ccc jim-p
2002
	if (is_array($interfaces) && count($interfaces)) {
2003 2a5960b0 Luiz Otavio O Souza
		$finterfaces = array();
2004 cf180ccc jim-p
		$ntpcfg .= "interface ignore all\n";
2005
		foreach ($interfaces as $interface) {
2006 2a5960b0 Luiz Otavio O Souza
			$interface = get_real_interface($interface);
2007 d9901ff4 Chris Buechler
			if (!empty($interface)) {
2008 2a5960b0 Luiz Otavio O Souza
				$finterfaces[] = $interface;
2009 d9901ff4 Chris Buechler
			}
2010 2a5960b0 Luiz Otavio O Souza
		}
2011
		foreach ($finterfaces as $interface) {
2012
			$ntpcfg .= "interface listen {$interface}\n";
2013 cf180ccc jim-p
		}
2014
	}
2015
2016 f416763b Phil Davis
	/* open configuration for writing or bail */
2017 b9f29f84 Ermal
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2018 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2019 b2305621 Ermal
		return;
2020
	}
2021 20b90e0a Scott Ullrich
2022 42135f07 jim-p
	/* if ntpd is running, kill it */
2023 df40755d Ermal
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2024 b9f29f84 Ermal
		killbypid("{$g['varrun_path']}/ntpd.pid");
2025 5f3e1f12 Scott Ullrich
	}
2026 b9f29f84 Ermal
	@unlink("{$g['varrun_path']}/ntpd.pid");
2027 5f3e1f12 Scott Ullrich
2028
	/* if /var/empty does not exist, create it */
2029 61e047a5 Phil Davis
	if (!is_dir("/var/empty")) {
2030 c01bdca9 Renato Botelho
		mkdir("/var/empty", 0555, true);
2031 61e047a5 Phil Davis
	}
2032 5f3e1f12 Scott Ullrich
2033 20b90e0a Scott Ullrich
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
2034 0fd64e94 nagyrobi
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
2035 61e047a5 Phil Davis
2036 83eb4567 Scott Ullrich
	// Note that we are starting up
2037 42135f07 jim-p
	log_error("NTPD is starting up.");
2038 0b8e9d38 jim-p
	return;
2039 5b237745 Scott Ullrich
}
2040
2041 405e5de0 Scott Ullrich
function system_halt() {
2042
	global $g;
2043
2044
	system_reboot_cleanup();
2045
2046 523855b0 Scott Ullrich
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2047 405e5de0 Scott Ullrich
}
2048
2049 5b237745 Scott Ullrich
function system_reboot() {
2050
	global $g;
2051 0f282d7a Scott Ullrich
2052 5b237745 Scott Ullrich
	system_reboot_cleanup();
2053 0f282d7a Scott Ullrich
2054 5b237745 Scott Ullrich
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2055
}
2056
2057 a2c453fd jim-p
function system_reboot_sync($reroot=false) {
2058 5b237745 Scott Ullrich
	global $g;
2059 0f282d7a Scott Ullrich
2060 a2c453fd jim-p
	if ($reroot) {
2061
		$args = " -r ";
2062
	}
2063
2064 5b237745 Scott Ullrich
	system_reboot_cleanup();
2065 0f282d7a Scott Ullrich
2066 a2c453fd jim-p
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2067 5b237745 Scott Ullrich
}
2068
2069
function system_reboot_cleanup() {
2070 3ece6d54 plumbeo
	global $config, $cpzone, $cpzoneid;
2071 62f20eab Michael Newton
2072 97d4e30b Seth Mos
	mwexec("/usr/local/bin/beep.sh stop");
2073 04967d99 jim-p
	require_once("captiveportal.inc");
2074 52034432 Renato Botelho
	if (is_array($config['captiveportal'])) {
2075 34cb8645 Jean Cyr
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2076 3ece6d54 plumbeo
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2077
			$cpzoneid = $cp[zoneid];
2078
			captiveportal_radius_stop_all(7); // Admin-Reboot
2079
			/* Send Accounting-Off packet to the RADIUS server */
2080 34cb8645 Jean Cyr
			captiveportal_send_server_accounting(true);
2081
		}
2082 62f20eab Michael Newton
	}
2083 336e3c1c Charlie
	require_once("voucher.inc");
2084
	voucher_save_db_to_config();
2085 60dd7649 jim-p
	require_once("pkg-utils.inc");
2086
	stop_packages();
2087 5b237745 Scott Ullrich
}
2088
2089
function system_do_shell_commands($early = 0) {
2090 f19d3b7a Scott Ullrich
	global $config, $g;
2091 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2092 58c7450e Scott Ullrich
		$mt = microtime();
2093 dcf0598e Scott Ullrich
		echo "system_do_shell_commands() being called $mt\n";
2094 58c7450e Scott Ullrich
	}
2095 0f282d7a Scott Ullrich
2096 61e047a5 Phil Davis
	if ($early) {
2097 5b237745 Scott Ullrich
		$cmdn = "earlyshellcmd";
2098 61e047a5 Phil Davis
	} else {
2099 5b237745 Scott Ullrich
		$cmdn = "shellcmd";
2100 61e047a5 Phil Davis
	}
2101 0f282d7a Scott Ullrich
2102 5b237745 Scott Ullrich
	if (is_array($config['system'][$cmdn])) {
2103 333f8ef0 Scott Ullrich
2104 245388b4 Scott Ullrich
		/* *cmd is an array, loop through */
2105 5b237745 Scott Ullrich
		foreach ($config['system'][$cmdn] as $cmd) {
2106
			exec($cmd);
2107
		}
2108 245388b4 Scott Ullrich
2109 61e047a5 Phil Davis
	} elseif ($config['system'][$cmdn] <> "") {
2110 333f8ef0 Scott Ullrich
2111 245388b4 Scott Ullrich
		/* execute single item */
2112
		exec($config['system'][$cmdn]);
2113
2114 5b237745 Scott Ullrich
	}
2115
}
2116
2117
function system_dmesg_save() {
2118 f19d3b7a Scott Ullrich
	global $g;
2119 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2120 58c7450e Scott Ullrich
		$mt = microtime();
2121 dcf0598e Scott Ullrich
		echo "system_dmesg_save() being called $mt\n";
2122 f19d3b7a Scott Ullrich
	}
2123 0f282d7a Scott Ullrich
2124 767a716e Scott Ullrich
	$dmesg = "";
2125 703b1ce1 Ermal
	$_gb = exec("/sbin/dmesg", $dmesg);
2126 0f282d7a Scott Ullrich
2127 5b237745 Scott Ullrich
	/* find last copyright line (output from previous boots may be present) */
2128
	$lastcpline = 0;
2129 0f282d7a Scott Ullrich
2130 5b237745 Scott Ullrich
	for ($i = 0; $i < count($dmesg); $i++) {
2131 61e047a5 Phil Davis
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2132 5b237745 Scott Ullrich
			$lastcpline = $i;
2133 61e047a5 Phil Davis
		}
2134 5b237745 Scott Ullrich
	}
2135 0f282d7a Scott Ullrich
2136 5b237745 Scott Ullrich
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2137
	if (!$fd) {
2138 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2139 5b237745 Scott Ullrich
		return 1;
2140
	}
2141 0f282d7a Scott Ullrich
2142 61e047a5 Phil Davis
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2143 5b237745 Scott Ullrich
		fwrite($fd, $dmesg[$i] . "\n");
2144 61e047a5 Phil Davis
	}
2145 0f282d7a Scott Ullrich
2146 5b237745 Scott Ullrich
	fclose($fd);
2147 703b1ce1 Ermal
	unset($dmesg);
2148 25ff3fc9 doktornotor
	
2149
	// vm-bhyve expects dmesg.boot at the standard location
2150 2e6883c5 doktornotor
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2151 0f282d7a Scott Ullrich
2152 5b237745 Scott Ullrich
	return 0;
2153
}
2154
2155
function system_set_harddisk_standby() {
2156 f19d3b7a Scott Ullrich
	global $g, $config;
2157 3e4f8fc4 doktornotor
2158 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2159 58c7450e Scott Ullrich
		$mt = microtime();
2160 dcf0598e Scott Ullrich
		echo "system_set_harddisk_standby() being called $mt\n";
2161 58c7450e Scott Ullrich
	}
2162 5b237745 Scott Ullrich
2163
	if (isset($config['system']['harddiskstandby'])) {
2164 285ef132 Ermal LUÇI
		if (platform_booting()) {
2165 4a896b86 Carlos Eduardo Ramos
			echo gettext('Setting hard disk standby... ');
2166 5b237745 Scott Ullrich
		}
2167
2168
		$standby = $config['system']['harddiskstandby'];
2169
		// Check for a numeric value
2170
		if (is_numeric($standby)) {
2171 0357ecfc doktornotor
			// Get only suitable candidates for standby; using get_smart_drive_list()
2172
			// from utils.inc to get the list of drives.
2173
			$harddisks = get_smart_drive_list();
2174
2175 3e4f8fc4 doktornotor
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2176
			// just in case of some weird pfSense platform installs.
2177
			if (count($harddisks) > 0) {
2178
				// Iterate disks and run the camcontrol command for each
2179
				foreach ($harddisks as $harddisk) {
2180
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2181
				}
2182 285ef132 Ermal LUÇI
				if (platform_booting()) {
2183 4a896b86 Carlos Eduardo Ramos
					echo gettext("done.") . "\n";
2184 5b237745 Scott Ullrich
				}
2185 285ef132 Ermal LUÇI
			} else if (platform_booting()) {
2186 4a896b86 Carlos Eduardo Ramos
				echo gettext("failed!") . "\n";
2187 5b237745 Scott Ullrich
			}
2188 285ef132 Ermal LUÇI
		} else if (platform_booting()) {
2189 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
2190 5b237745 Scott Ullrich
		}
2191
	}
2192
}
2193
2194 3ff9d424 Scott Ullrich
function system_setup_sysctl() {
2195 f19d3b7a Scott Ullrich
	global $config;
2196 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2197 58c7450e Scott Ullrich
		$mt = microtime();
2198 dcf0598e Scott Ullrich
		echo "system_setup_sysctl() being called $mt\n";
2199 58c7450e Scott Ullrich
	}
2200 243aa7b9 Scott Ullrich
2201 61e047a5 Phil Davis
	activate_sysctls();
2202 6df9d7e3 Scott Ullrich
2203 243aa7b9 Scott Ullrich
	if (isset($config['system']['sharednet'])) {
2204
		system_disable_arp_wrong_if();
2205
	}
2206
}
2207
2208
function system_disable_arp_wrong_if() {
2209 f19d3b7a Scott Ullrich
	global $config;
2210 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2211 58c7450e Scott Ullrich
		$mt = microtime();
2212 dcf0598e Scott Ullrich
		echo "system_disable_arp_wrong_if() being called $mt\n";
2213 333f8ef0 Scott Ullrich
	}
2214 971de1f9 Renato Botelho
	set_sysctl(array(
2215
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2216
		"net.link.ether.inet.log_arp_movements" => "0"
2217
	));
2218 3ff9d424 Scott Ullrich
}
2219
2220 243aa7b9 Scott Ullrich
function system_enable_arp_wrong_if() {
2221 f19d3b7a Scott Ullrich
	global $config;
2222 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2223 58c7450e Scott Ullrich
		$mt = microtime();
2224 dcf0598e Scott Ullrich
		echo "system_enable_arp_wrong_if() being called $mt\n";
2225 58c7450e Scott Ullrich
	}
2226 971de1f9 Renato Botelho
	set_sysctl(array(
2227
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2228
		"net.link.ether.inet.log_arp_movements" => "1"
2229
	));
2230 243aa7b9 Scott Ullrich
}
2231
2232 a199b93e Scott Ullrich
function enable_watchdog() {
2233
	global $config;
2234 1a479479 Scott Ullrich
	return;
2235 a199b93e Scott Ullrich
	$install_watchdog = false;
2236
	$supported_watchdogs = array("Geode");
2237
	$file = file_get_contents("/var/log/dmesg.boot");
2238 61e047a5 Phil Davis
	foreach ($supported_watchdogs as $sd) {
2239
		if (stristr($file, "Geode")) {
2240 a199b93e Scott Ullrich
			$install_watchdog = true;
2241
		}
2242
	}
2243 61e047a5 Phil Davis
	if ($install_watchdog == true) {
2244
		if (is_process_running("watchdogd")) {
2245 e0b4e47f Seth Mos
			mwexec("/usr/bin/killall watchdogd", true);
2246 61e047a5 Phil Davis
		}
2247 333f8ef0 Scott Ullrich
		exec("/usr/sbin/watchdogd");
2248 a199b93e Scott Ullrich
	}
2249
}
2250 15f14889 Scott Ullrich
2251
function system_check_reset_button() {
2252 fa83737d Scott Ullrich
	global $g;
2253 15f14889 Scott Ullrich
2254 31c9379c Scott Ullrich
	$specplatform = system_identify_specific_platform();
2255
2256 365fc95d Renato Botelho
	switch ($specplatform['name']) {
2257 61e047a5 Phil Davis
		case 'alix':
2258
		case 'wrap':
2259
		case 'FW7541':
2260
		case 'APU':
2261 80e47bb0 Chris Buechler
		case 'RCC-VE':
2262 bf648a15 Chris Buechler
		case 'RCC':
2263 ba8c6e37 Renato Botelho
		case 'RCC-DFF':
2264 61e047a5 Phil Davis
			break;
2265
		default:
2266
			return 0;
2267 365fc95d Renato Botelho
	}
2268 15f14889 Scott Ullrich
2269
	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");
2270
2271
	if ($retval == 99) {
2272 61e047a5 Phil Davis
		/* user has pressed reset button for 2 seconds -
2273 15f14889 Scott Ullrich
		   reset to factory defaults */
2274
		echo <<<EOD
2275
2276
***********************************************************************
2277
* Reset button pressed - resetting configuration to factory defaults. *
2278 7222324e Renato Botelho
* All additional packages installed will be removed                   *
2279 15f14889 Scott Ullrich
* The system will reboot after this completes.                        *
2280
***********************************************************************
2281
2282
2283
EOD;
2284 61e047a5 Phil Davis
2285 15f14889 Scott Ullrich
		reset_factory_defaults();
2286
		system_reboot_sync();
2287
		exit(0);
2288
	}
2289
2290
	return 0;
2291
}
2292
2293 884914ce Renato Botelho
function system_get_serial() {
2294
	unset($output);
2295 411f439a Renato Botelho
	$_gb = exec('/bin/kenv -q smbios.system.serial 2>/dev/null', $output);
2296 884914ce Renato Botelho
	$serial = $output[0];
2297
2298
	$vm_guest = get_single_sysctl('kern.vm_guest');
2299
2300
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2301
	    $vm_guest == 'none') {
2302
		return $serial;
2303
	}
2304
2305
	return get_single_sysctl('kern.hostuuid');
2306
}
2307
2308 d1f9426a Renato Botelho
/*
2309
 * attempt to identify the specific platform (for embedded systems)
2310
 * Returns an array with two elements:
2311
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2312
 * descr => human-readable description (e.g. "PC Engines WRAP")
2313
 */
2314 31c9379c Scott Ullrich
function system_identify_specific_platform() {
2315
	global $g;
2316 61e047a5 Phil Davis
2317 042326a3 Renato Botelho
	$hw_model = get_single_sysctl('hw.model');
2318
2319 5a8519bb Chris Buechler
	/* Try to guess from smbios strings */
2320 b4594d39 Chris Buechler
	unset($product);
2321
	unset($maker);
2322 411f439a Renato Botelho
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2323
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2324 b4594d39 Chris Buechler
	switch ($product[0]) {
2325 61e047a5 Phil Davis
		case 'FW7541':
2326
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2327
			break;
2328
		case 'APU':
2329
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2330
			break;
2331
		case 'RCC-VE':
2332 042326a3 Renato Botelho
			$result = array();
2333
			$result['name'] = 'RCC-VE';
2334
2335
			/* Detect specific models */
2336
			if (!function_exists('does_interface_exist')) {
2337
				require_once("interfaces.inc");
2338
			}
2339
			if (!does_interface_exist('igb4')) {
2340
				$result['model'] = 'SG-2440';
2341
			} elseif (strpos($hw_model, "C2558") !== false) {
2342
				$result['model'] = 'SG-4860';
2343
			} elseif (strpos($hw_model, "C2758") !== false) {
2344
				$result['model'] = 'SG-8860';
2345
			} else {
2346
				$result['model'] = 'RCC-VE';
2347
			}
2348
			$result['descr'] = 'Netgate ' . $result['model'];
2349
			return $result;
2350 61e047a5 Phil Davis
			break;
2351 ba8c6e37 Renato Botelho
		case 'DFFv2':
2352
			return (array('name' => 'RCC-DFF', 'descr' => 'Netgate RCC-DFF'));
2353
			break;
2354 bf648a15 Chris Buechler
		case 'RCC':
2355 2ae79c20 Chris Buechler
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2356 bf648a15 Chris Buechler
			break;
2357 be2191af Jeremy Porter
		case 'SYS-5018A-FTN4':
2358 bc09b90a Renato Botelho
		case 'A1SAi':
2359
			return (array('name' => 'C2758', 'descr' => 'Super Micro C2758'));
2360
			break;
2361 47b09af7 Matt Smith
		case 'SYS-5018D-FN4T':
2362 bf648a15 Chris Buechler
			return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2363 47b09af7 Matt Smith
			break;
2364 ffda0181 Brett Keller
		case 'apu2':
2365
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2366
			break;
2367 b4594d39 Chris Buechler
		case 'Virtual Machine':
2368
			if ($maker[0] == "Microsoft Corporation") {
2369
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2370
			}
2371
			break;
2372 9a548240 jim-p
		case 'VMware Virtual Platform':
2373
			if ($maker[0] == "VMware, Inc.") {
2374
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2375
			}
2376
			break;
2377 5a8519bb Chris Buechler
	}
2378
2379 24d4fdde Renato Botelho
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2380 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2381 61e047a5 Phil Davis
	}
2382
2383 24d4fdde Renato Botelho
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2384 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2385 61e047a5 Phil Davis
	}
2386 31c9379c Scott Ullrich
2387 24d4fdde Renato Botelho
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2388 31c9379c Scott Ullrich
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2389 61e047a5 Phil Davis
	}
2390
2391 24d4fdde Renato Botelho
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2392 31c9379c Scott Ullrich
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2393 61e047a5 Phil Davis
	}
2394
2395 24d4fdde Renato Botelho
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2396 31c9379c Scott Ullrich
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2397 61e047a5 Phil Davis
	}
2398 1f97f379 Renato Botelho
2399 24d4fdde Renato Botelho
	unset($hw_model);
2400 1f97f379 Renato Botelho
2401
	$dmesg_boot = system_get_dmesg_boot();
2402 61e047a5 Phil Davis
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2403 1f97f379 Renato Botelho
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2404 61e047a5 Phil Davis
	}
2405 1f97f379 Renato Botelho
	unset($dmesg_boot);
2406
2407 dc61252a Renato Botelho
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2408 31c9379c Scott Ullrich
}
2409
2410
function system_get_dmesg_boot() {
2411
	global $g;
2412 61e047a5 Phil Davis
2413 31c9379c Scott Ullrich
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2414
}
2415
2416 bc09b90a Renato Botelho
?>