Project

General

Profile

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