Project

General

Profile

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