Project

General

Profile

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