Project

General

Profile

Download (62.4 KB) Statistics
| Branch: | Tag: | Revision:
1 5b237745 Scott Ullrich
<?php
2 307cd525 Bill Marquette
/* $Id$ */
3 5b237745 Scott Ullrich
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6 0f282d7a Scott Ullrich
7 5b237745 Scott Ullrich
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9 0f282d7a Scott Ullrich
10 5b237745 Scott Ullrich
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12 0f282d7a Scott Ullrich
13 5b237745 Scott Ullrich
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15 0f282d7a Scott Ullrich
16 5b237745 Scott Ullrich
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19 0f282d7a Scott Ullrich
20 5b237745 Scott Ullrich
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31
32 523855b0 Scott Ullrich
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34 b368b35a Ermal
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35 523855b0 Scott Ullrich
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36 fdfa8f43 jim-p
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/local/sbin/ntpdate
37 c3b13d60 jim-p
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38 356e86d4 Renato Botelho
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/filterdns
39 523855b0 Scott Ullrich
	pfSense_MODULE:	utils
40
*/
41 0f282d7a Scott Ullrich
42 8e9fa41d Scott Ullrich
function activate_powerd() {
43
	global $config, $g;
44 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
45
		return;
46 53c210dd Cristian Feldman
	if(is_process_running("powerd"))
47
		exec("/usr/bin/killall powerd");
48 8e9fa41d Scott Ullrich
	if(isset($config['system']['powerd_enable'])) {
49 c3b13d60 jim-p
		if ($g["platform"] == "nanobsd")
50
			exec("/sbin/kldload cpufreq");
51 a358eec2 N0YB
52
		$ac_mode = "hadp";
53
		if (!empty($config['system']['powerd_ac_mode']))
54
			$ac_mode = $config['system']['powerd_ac_mode'];
55
56
		$battery_mode = "hadp";
57
		if (!empty($config['system']['powerd_battery_mode']))
58
			$battery_mode = $config['system']['powerd_battery_mode'];
59
60
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode");
61 8e9fa41d Scott Ullrich
	}
62
}
63
64 3a35f55f Scott Ullrich
function get_default_sysctl_value($id) {
65
	global $sysctls;
66 f3c91cb5 Erik Fonnesbeck
67
	if (isset($sysctls[$id]))
68
		return $sysctls[$id];
69 3a35f55f Scott Ullrich
}
70
71 6df9d7e3 Scott Ullrich
function activate_sysctls() {
72
	global $config, $g;
73 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
74
		return;
75 050fd8ad Ermal
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x0001");
76
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x0001");
77 94395d86 Ermal
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x0002");
78
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x0002");
79 99e88aa0 Ermal Luçi
80 3a35f55f Scott Ullrich
	if(is_array($config['sysctl'])) {
81 cac19f50 Scott Ullrich
		foreach($config['sysctl']['item'] as $tunable) {
82 b2d0140c Scott Ullrich
			if($tunable['value'] == "default") {
83
				$value = get_default_sysctl_value($tunable['tunable']);
84 83e46727 Ermal
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"", true);
85 b2d0140c Scott Ullrich
			} else { 
86 83e46727 Ermal
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"", true);
87 b2d0140c Scott Ullrich
			}
88 d0b461f5 sullrich
		}
89
	}
90 6df9d7e3 Scott Ullrich
}
91
92 5b237745 Scott Ullrich
function system_resolvconf_generate($dynupdate = false) {
93 c3f535c0 Seth Mos
	global $config, $g;
94
95
	if(isset($config['system']['developerspew'])) {
96
		$mt = microtime();
97
		echo "system_resolvconf_generate() being called $mt\n";
98
	}
99 ef217c69 Scott Ullrich
100 30cee7b2 Scott Ullrich
	$syscfg = $config['system'];
101 ef217c69 Scott Ullrich
102 53bbbf04 Scott Ullrich
	// Do not create blank domain lines, it breaks tools like dig.
103
	if($syscfg['domain'])
104
		$resolvconf = "domain {$syscfg['domain']}\n";
105 ef217c69 Scott Ullrich
106 bd5737dc jim-p
	if (((isset($config['dnsmasq']['enable']) && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface']))))
107
		|| (isset($config['unbound']['enable'])) && (empty($config['unbound']['active_interface']) || in_array("lo0", explode(",", $config['unbound']['active_interface']))))
108
		&& !isset($config['system']['dnslocalhost']))
109 6c86a39f Ermal
		$resolvconf .= "nameserver 127.0.0.1\n";
110 8ac329da Ermal
111 30cee7b2 Scott Ullrich
	if (isset($syscfg['dnsallowoverride'])) {
112 c3f535c0 Seth Mos
		/* get dynamically assigned DNS servers (if any) */
113 86dcdfc9 Ermal
		$ns = array_unique(get_searchdomains());
114
		foreach($ns as $searchserver) {
115 8e866217 Ermal
			if($searchserver)
116 86dcdfc9 Ermal
				$resolvconf .= "search {$searchserver}\n";
117
		}
118 c3f535c0 Seth Mos
		$ns = array_unique(get_nameservers());
119
		foreach($ns as $nameserver) {
120 8e866217 Ermal
			if($nameserver)
121 c3f535c0 Seth Mos
				$resolvconf .= "nameserver $nameserver\n";
122
		}
123 30cee7b2 Scott Ullrich
	}
124 8e866217 Ermal
	if (is_array($syscfg['dnsserver'])) {
125 c3f535c0 Seth Mos
		foreach ($syscfg['dnsserver'] as $ns) {
126 8e866217 Ermal
			if ($ns)
127 c3f535c0 Seth Mos
				$resolvconf .= "nameserver $ns\n";
128 e180a6e3 Scott Ullrich
		}
129 c3f535c0 Seth Mos
	}
130 0f282d7a Scott Ullrich
131 3b95d9ec Warren Baker
	// Add EDNS support
132
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns']))
133
		$resolvconf .= "options edns0\n";
134
135 d97ff036 Ermal
	$dnslock = lock('resolvconf', LOCK_EX);
136
137 e1daff07 Ermal
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
138
	if (!$fd) {
139
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
140 d97ff036 Ermal
		unlock($dnslock);
141 e1daff07 Ermal
		return 1;
142
	}
143
144 30cee7b2 Scott Ullrich
	fwrite($fd, $resolvconf);
145
	fclose($fd);
146 0f282d7a Scott Ullrich
147 30cee7b2 Scott Ullrich
	if (!$g['booting']) {
148 c3f535c0 Seth Mos
		/* restart dhcpd (nameservers may have changed) */
149
		if (!$dynupdate)
150
			services_dhcpd_configure();
151 30cee7b2 Scott Ullrich
	}
152 ef217c69 Scott Ullrich
153 c3f535c0 Seth Mos
	/* setup static routes for DNS servers. */
154
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
155
		/* setup static routes for dns servers */
156 c935003d Seth Mos
		$dnsgw = "dns{$dnscounter}gw";
157 c3f535c0 Seth Mos
		if (isset($config['system'][$dnsgw])) {
158 c935003d Seth Mos
			$gwname = $config['system'][$dnsgw];
159
			if (($gwname <> "") && ($gwname <> "none")) {
160
				$gatewayip = lookup_gateway_ip_by_name($gwname);
161
				if (is_ipaddrv4($gatewayip)) {
162 c3f535c0 Seth Mos
					/* dns server array starts at 0 */
163 b875f306 Scott Ullrich
					$dnscountermo = $dnscounter - 1;
164 12f77b03 Ermal
					mwexec("/sbin/route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
165 b875f306 Scott Ullrich
				}
166 c935003d Seth Mos
				if (is_ipaddrv6($gatewayip)) {
167
					/* dns server array starts at 0 */
168
					$dnscountermo = $dnscounter - 1;
169 12f77b03 Ermal
					mwexec("/sbin/route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
170 c935003d Seth Mos
				}
171 b875f306 Scott Ullrich
			}
172 e180a6e3 Scott Ullrich
		}
173 c3f535c0 Seth Mos
	}
174 d97ff036 Ermal
175
	unlock($dnslock);
176
177 c3f535c0 Seth Mos
	return 0;
178 5b237745 Scott Ullrich
}
179
180 86dcdfc9 Ermal
function get_searchdomains() {
181
	global $config, $g;
182
183
	$master_list = array();
184
	
185
	// Read in dhclient nameservers
186 e1daff07 Ermal
	$search_list = glob("/var/etc/searchdomain_*");
187 f4a4bcbc Renato Botelho
	if (is_array($search_list)) {
188
		foreach($search_list as $fdns) {
189 807fd6cd Ermal
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
190
			if (!is_array($contents))
191
				continue;
192
			foreach ($contents as $dns) {
193
				if(is_hostname($dns)) 
194
					$master_list[] = $dns;
195
			}
196 86dcdfc9 Ermal
		}
197
	}
198
199
	return $master_list;
200
}
201
202 3d00ccaa Scott Ullrich
function get_nameservers() {
203
	global $config, $g;
204
	$master_list = array();
205 30cee7b2 Scott Ullrich
	
206 2a1226ad Scott Ullrich
	// Read in dhclient nameservers
207 e1daff07 Ermal
	$dns_lists = glob("/var/etc/nameserver_*");
208 1033de74 Ermal
	if (is_array($dns_lists)) {
209 807fd6cd Ermal
		foreach($dns_lists as $fdns) {
210
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
211
			if (!is_array($contents))
212
				continue;
213
			foreach ($contents as $dns) {
214
				if(is_ipaddr($dns)) 
215
					$master_list[] = $dns;
216
			}
217 60951398 Scott Ullrich
		}
218 3d00ccaa Scott Ullrich
	}
219 2a1226ad Scott Ullrich
220
	// Read in any extra nameservers
221
	if(file_exists("/var/etc/nameservers.conf")) {
222 33818198 Ermal
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
223 e1daff07 Ermal
		if(is_array($dns_s)) {
224 2a1226ad Scott Ullrich
			foreach($dns_s as $dns)
225 1033de74 Ermal
				if (is_ipaddr($dns))
226
					$master_list[] = $dns;
227 e1daff07 Ermal
		}
228 2a1226ad Scott Ullrich
	}
229
230 3d00ccaa Scott Ullrich
	return $master_list;
231
}
232
233 5b237745 Scott Ullrich
function system_hosts_generate() {
234 f19d3b7a Scott Ullrich
	global $config, $g;
235 f6248774 Warren Baker
	if (isset($config['system']['developerspew'])) {
236 58c7450e Scott Ullrich
		$mt = microtime();
237 dcf0598e Scott Ullrich
		echo "system_hosts_generate() being called $mt\n";
238 f19d3b7a Scott Ullrich
	}
239 0f282d7a Scott Ullrich
240 5b237745 Scott Ullrich
	$syscfg = $config['system'];
241
	$dnsmasqcfg = $config['dnsmasq'];
242
243 58db1fc4 Ermal
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
244 aa994814 Andrew Thompson
	$lhosts = "";
245
	$dhosts = "";
246 a55e9c70 Ermal Lu?i
247 e5995f9d Ermal
	if ($config['interfaces']['lan']) {
248
		$cfgip = get_interface_ip("lan");
249 f38f8062 Ermal
		if (is_ipaddr($cfgip))
250
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
251 e5995f9d Ermal
	} else {
252
		$sysiflist = get_configured_interface_list();
253
		foreach ($sysiflist as $sysif) {
254
			if (!interface_has_gateway($sysif)) {
255
				$cfgip = get_interface_ip($sysif);
256
				if (is_ipaddr($cfgip)) {
257
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
258
					break;
259
				}
260
			}
261
		}
262 f38f8062 Ermal
	}
263 0f282d7a Scott Ullrich
264 a80cb9ca PiBa-NL
	if (isset($dnsmasqcfg['enable'])) {
265 ea1aca13 Renato Botelho
		if (!is_array($dnsmasqcfg['hosts']))
266
			$dnsmasqcfg['hosts'] = array();
267
268
		foreach ($dnsmasqcfg['hosts'] as $host) {
269
			if ($host['host'])
270
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
271 5a2a8349 Lorenz Schori
			else
272 ea1aca13 Renato Botelho
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
273
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
274
				continue;
275
			foreach ($host['aliases']['item'] as $alias) {
276
				if ($alias['host'])
277
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
278
				else
279
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
280
			}
281
		}
282
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
283
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
284
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
285
						foreach ($dhcpifconf['staticmap'] as $host)
286 2ec52b3e Daniel Becker
							if ($host['ipaddr'] && $host['hostname'] && $host['domain'])
287
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
288
							else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain'])
289
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
290
							else if ($host['ipaddr'] && $host['hostname'])
291 ea1aca13 Renato Botelho
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
292
		}
293
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
294
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
295
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
296
						foreach ($dhcpifconf['staticmap'] as $host)
297 2ec52b3e Daniel Becker
							if ($host['ipaddrv6'] && $host['hostname'] && $host['domain'])
298
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
299
							else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain'])
300
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
301
							else if ($host['ipaddrv6'] && $host['hostname'])
302 ea1aca13 Renato Botelho
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
303 5a2a8349 Lorenz Schori
		}
304 58db1fc4 Ermal
305 ea1aca13 Renato Botelho
		if (isset($dnsmasqcfg['dhcpfirst']))
306
			$hosts .= $dhosts . $lhosts;
307
		else
308
			$hosts .= $lhosts . $dhosts;
309
	}
310 aa994814 Andrew Thompson
311 58db1fc4 Ermal
	/*
312
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
313
	 * killed before writing to hosts files.
314
	 */
315
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
316
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
317 ea1aca13 Renato Botelho
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
318 58db1fc4 Ermal
	}
319
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
320
	if (!$fd) {
321
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
322
		return 1;
323
	}
324 5b237745 Scott Ullrich
	fwrite($fd, $hosts);
325
	fclose($fd);
326 0f282d7a Scott Ullrich
327 3f06e538 Warren Baker
	if (isset($config['unbound']['enable'])) {
328
		require_once("unbound.inc");
329 f6248774 Warren Baker
		unbound_hosts_generate();
330 3f06e538 Warren Baker
	}
331 f6248774 Warren Baker
332 24d619f5 Ermal
	system_dhcpleases_configure();
333
334
	return 0;
335
}
336
337
function system_dhcpleases_configure() {
338 15d456b9 gnhb
	global $config, $g;
339
	
340 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
341
		return;
342 956950de Ermal
	/* Start the monitoring process for dynamic dhcpclients. */
343 f6248774 Warren Baker
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) 
344
		|| (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
345 956950de Ermal
		/* Make sure we do not error out */
346 abdd01f5 Ermal
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
347
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
348
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
349
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
350
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
351 69e593c1 jim-p
		else {
352
			/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
353
			if (is_process_running("dhcpleases"))
354
				mwexec('/bin/pkill dhcpleases');
355
			@unlink("{$g['varrun_path']}/dhcpleases.pid");
356 15d456b9 gnhb
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
357 69e593c1 jim-p
		}
358 15d456b9 gnhb
	} else {
359
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
360
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
361
	}
362 5b237745 Scott Ullrich
}
363
364
function system_hostname_configure() {
365 f19d3b7a Scott Ullrich
	global $config, $g;
366 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
367
		$mt = microtime();
368 dcf0598e Scott Ullrich
		echo "system_hostname_configure() being called $mt\n";
369 333f8ef0 Scott Ullrich
	}
370 0f282d7a Scott Ullrich
371 5b237745 Scott Ullrich
	$syscfg = $config['system'];
372 0f282d7a Scott Ullrich
373 5b237745 Scott Ullrich
	/* set hostname */
374 6bfccde7 Scott Ullrich
	$status = mwexec("/bin/hostname " .
375 5b237745 Scott Ullrich
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
376 6bfccde7 Scott Ullrich
377
    /* Setup host GUID ID.  This is used by ZFS. */
378
	mwexec("/etc/rc.d/hostid start");
379
380
	return $status;
381 5b237745 Scott Ullrich
}
382
383 1ea67f2e Ermal
function system_routing_configure($interface = "") {
384 962625aa Ermal
	global $config, $g;
385 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
386
		return;
387 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
388
		$mt = microtime();
389 dcf0598e Scott Ullrich
		echo "system_routing_configure() being called $mt\n";
390 58c7450e Scott Ullrich
	}
391 333f8ef0 Scott Ullrich
392 a529aced Ermal
	$gatewayip = "";
393
	$interfacegw = "";
394 3cc07282 Ermal
	$foundgw = false;
395 5a5413bb Seth Mos
	$gatewayipv6 = "";
396
	$interfacegwv6 = "";
397
	$foundgwv6 = false;
398 a529aced Ermal
	/* tack on all the hard defined gateways as well */
399
	if (is_array($config['gateways']['gateway_item'])) {
400 873c1701 Renato Botelho
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
401 a529aced Ermal
		foreach	($config['gateways']['gateway_item'] as $gateway) {
402 f934af33 Ermal
			if (isset($gateway['defaultgw'])) {
403
				if ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
404
					if(strstr($gateway['gateway'], ":"))
405
						continue;
406
					if ($gateway['gateway'] == "dynamic")
407
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
408 9d595f6a Ermal
					$gatewayip = $gateway['gateway'];
409 03e96afb Renato Botelho
					$interfacegw = $gateway['interface'];
410 f934af33 Ermal
					if (!empty($gateway['interface'])) {
411
						$defaultif = get_real_interface($gateway['interface']);
412
						if ($defaultif)
413
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
414
					}
415
					$foundgw = true;
416 d07bc322 Renato Botelho
				} else if ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
417
					if ($gateway['gateway'] == "dynamic")
418 f934af33 Ermal
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
419 9d595f6a Ermal
					$gatewayipv6 = $gateway['gateway'];
420 03e96afb Renato Botelho
					$interfacegwv6 = $gateway['interface'];
421 f934af33 Ermal
					if (!empty($gateway['interface'])) {
422 c79f717a Ermal
						$defaultifv6 = get_real_interface($gateway['interface']);
423 f934af33 Ermal
						if ($defaultifv6)
424
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
425
					}
426
					$foundgwv6 = true;
427 924f202e Ermal
				}
428 a529aced Ermal
			}
429 f934af33 Ermal
			if ($foundgw === true && $foundgwv6 === true)
430 5a5413bb Seth Mos
				break;
431
		}
432 b24bda08 Scott Ullrich
	}
433 3cc07282 Ermal
	if ($foundgw == false) {
434
		$defaultif = get_real_interface("wan");
435
		$interfacegw = "wan";
436
		$gatewayip = get_interface_gateway("wan");
437
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
438
	}	
439 5a5413bb Seth Mos
	if ($foundgwv6 == false) {
440 c79f717a Ermal
		$defaultifv6 = get_real_interface("wan");
441 4f332466 Seth Mos
		$interfacegwv6 = "wan";
442
		$gatewayipv6 = get_interface_gateway_v6("wan");
443 5a5413bb Seth Mos
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
444 17a5b095 Seth Mos
	}
445 d173230c Seth Mos
	$dont_add_route = false;
446
	/* if OLSRD is enabled, allow WAN to house DHCP. */
447 f934af33 Ermal
	if (is_array($config['installedpackages']['olsrd'])) {
448 d173230c Seth Mos
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
449 f581cb10 Chris Buechler
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
450 d173230c Seth Mos
				$dont_add_route = true;
451 f581cb10 Chris Buechler
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
452 6e17413e Ermal Lu?i
				break;
453 d173230c Seth Mos
			}
454
		}
455
	}
456 07b54e8c smos
457 1ea67f2e Ermal
	if ($dont_add_route == false ) {
458 8d29cef4 Ermal
		if (!empty($interface) && $interface != $interfacegw)
459 1ea67f2e Ermal
			;
460 5a5413bb Seth Mos
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
461 b368b35a Ermal
			log_error("ROUTING: setting default route to $gatewayip");
462
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
463 d173230c Seth Mos
		}
464
465 17a5b095 Seth Mos
		if (!empty($interface) && $interface != $interfacegwv6)
466 5a5413bb Seth Mos
			;
467
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
468 8be135cd Ermal
			$ifscope = "";
469 be544a5e Ermal
			if (is_linklocal($gatewayipv6))
470 26ecc19c smos
				$ifscope = "%{$defaultifv6}";
471 ea91a8c0 smos
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
472 02091d23 smos
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
473 5a5413bb Seth Mos
		}
474
	}
475
476 2a2b9eea Renato Botelho
	system_staticroutes_configure($interface, false);
477
478
	return 0;
479
}
480
481
function system_staticroutes_configure($interface = "", $update_dns = false) {
482
	global $config, $g, $aliastable;
483
484 356e86d4 Renato Botelho
	$filterdns_list = array();
485
486 e47d24e4 Renato Botelho
	$static_routes = get_staticroutes(false, true);
487 f898c1a9 jim-p
	if (count($static_routes)) {
488 6fdea6a2 smos
		$gateways_arr = return_gateways_array(false, true);
489 0f282d7a Scott Ullrich
490 f898c1a9 jim-p
		foreach ($static_routes as $rtent) {
491 a02708b1 Ermal
			if (empty($gateways_arr[$rtent['gateway']])) {
492 4a896b86 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
493 a529aced Ermal
				continue;
494
			}
495 a02708b1 Ermal
			$gateway = $gateways_arr[$rtent['gateway']];
496 1801c223 Ermal
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
497 a02708b1 Ermal
				continue;
498 9740fad8 Seth Mos
499 a02708b1 Ermal
			$gatewayip = $gateway['gateway'];
500
			$interfacegw = $gateway['interface'];
501 a529aced Ermal
502 1e5f47bb smos
			$blackhole = "";
503 8be135cd Ermal
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
504 1e5f47bb smos
				$blackhole = "-blackhole";
505
506 e47d24e4 Renato Botelho
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
507 2a2b9eea Renato Botelho
				continue;
508 046583c3 Renato Botelho
509 e47d24e4 Renato Botelho
			$dnscache = array();
510
			if ($update_dns === true) {
511
				if (is_subnet($rtent['network']))
512 2a2b9eea Renato Botelho
					continue;
513 e47d24e4 Renato Botelho
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
514
				if (empty($dnscache))
515
					continue;
516
			}
517 046583c3 Renato Botelho
518 e47d24e4 Renato Botelho
			if (is_subnet($rtent['network']))
519
				$ips = array($rtent['network']);
520
			else {
521
				if (!isset($rtent['disabled']))
522
					$filterdns_list[] = $rtent['network'];
523
				$ips = add_hostname_to_watch($rtent['network']);
524
			}
525 2a2b9eea Renato Botelho
526 e47d24e4 Renato Botelho
			foreach ($dnscache as $ip) {
527
				if (in_array($ip, $ips))
528
					continue;
529
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
530
			}
531 2a2b9eea Renato Botelho
532 e47d24e4 Renato Botelho
			if (isset($rtent['disabled'])) {
533
				/* XXX: This is a bit dangerous in case of routing daemons!? */
534
				foreach ($ips as $ip)
535 2a2b9eea Renato Botelho
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
536 e47d24e4 Renato Botelho
				continue;
537
			}
538 2a2b9eea Renato Botelho
539 e47d24e4 Renato Botelho
			foreach ($ips as $ip) {
540
				if (is_ipaddrv4($ip))
541
					$ip .= "/32";
542
				else if (is_ipaddrv6($ip))
543
					$ip .= "/128";
544 2a2b9eea Renato Botelho
545 e47d24e4 Renato Botelho
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
546 2a2b9eea Renato Botelho
547 e47d24e4 Renato Botelho
				$cmd = "/sbin/route change {$inet} {$blackhole} " . escapeshellarg($ip) . " ";
548
549
				if (is_subnet($ip))
550
					if (is_ipaddr($gatewayip))
551
						mwexec($cmd . escapeshellarg($gatewayip));
552
					else if (!empty($interfacegw))
553
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
554 2a2b9eea Renato Botelho
			}
555 5b237745 Scott Ullrich
		}
556 6a205b6a Ermal
		unset($gateways_arr);
557 5b237745 Scott Ullrich
	}
558 6a205b6a Ermal
	unset($static_routes);
559 67ee1ec5 Ermal Luçi
560 e47d24e4 Renato Botelho
	if ($update_dns === false) {
561
		if (count($filterdns_list)) {
562
			$interval = 60;
563
			$hostnames = "";
564
			array_unique($filterdns_list);
565
			foreach ($filterdns_list as $hostname)
566
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
567
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
568
			unset($hostnames);
569
570
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
571
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
572
			else
573
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
574
		} else {
575
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
576
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
577
		}
578 356e86d4 Renato Botelho
	}
579 e47d24e4 Renato Botelho
	unset($filterdns_list);
580 356e86d4 Renato Botelho
581 b9c501ea Seth Mos
	return 0;
582 5b237745 Scott Ullrich
}
583
584
function system_routing_enable() {
585 f19d3b7a Scott Ullrich
	global $config, $g;
586 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
587
		$mt = microtime();
588 dcf0598e Scott Ullrich
		echo "system_routing_enable() being called $mt\n";
589 58c7450e Scott Ullrich
	}
590 0f282d7a Scott Ullrich
591 6da3df4e Seth Mos
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
592
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
593
	return;
594 5b237745 Scott Ullrich
}
595
596 bd29bb7b jim-p
function system_syslogd_fixup_server($server) {
597
	/* If it's an IPv6 IP alone, encase it in brackets */
598
	if (is_ipaddrv6($server))
599
		return "[$server]";
600
	else
601
		return $server;
602
}
603
604 236524c2 jim-p
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
605
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
606
	$facility .= " ".
607
	$remote_servers = "";
608
	$pad_to  = 56;
609
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
610
	if($syslogcfg['remoteserver'])
611 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
612 236524c2 jim-p
	if($syslogcfg['remoteserver2'])
613 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
614 236524c2 jim-p
	if($syslogcfg['remoteserver3'])
615 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
616 236524c2 jim-p
	return $remote_servers;
617
}
618
619 5b237745 Scott Ullrich
function system_syslogd_start() {
620 f19d3b7a Scott Ullrich
	global $config, $g;
621 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
622
		$mt = microtime();
623 dcf0598e Scott Ullrich
		echo "system_syslogd_start() being called $mt\n";
624 58c7450e Scott Ullrich
	}
625 0f282d7a Scott Ullrich
626 1fd3fe31 Scott Ullrich
	mwexec("/etc/rc.d/hostid start");
627
628 5b237745 Scott Ullrich
	$syslogcfg = $config['syslog'];
629
630 0f282d7a Scott Ullrich
	if ($g['booting'])
631 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting syslog...");
632 0f282d7a Scott Ullrich
633 100f3e71 Ermal
	if (is_process_running("fifolog_writer"))
634 236524c2 jim-p
		mwexec('/bin/pkill fifolog_writer');
635 7ee97cb3 Scott Ullrich
636
	// Which logging type are we using this week??
637 100f3e71 Ermal
	if (isset($config['system']['disablesyslogclog'])) {
638
		$log_directive = "";
639
		$log_create_directive = "/usr/bin/touch ";
640
		$log_size = "";
641
	} else if (isset($config['system']['usefifolog'])) {
642
		$log_directive = "|/usr/sbin/fifolog_writer ";
643 c7a3356e jim-p
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
644 100f3e71 Ermal
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
645 7ee97cb3 Scott Ullrich
	} else { // Defaults to CLOG
646 100f3e71 Ermal
		$log_directive = "%";
647 c7a3356e jim-p
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
648 2a50fd8a Renato Botelho
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
649 7ee97cb3 Scott Ullrich
	}
650 66201c96 Ermal
651
	$syslogd_extra = "";
652 88ebd635 Scott Ullrich
	if (isset($syslogcfg)) {
653 ebf45d96 Ermal
		$separatelogfacilities = array('ntp','ntpd','ntpdate','charon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog');
654 344016a8 Ermal
		$syslogconf = "";
655 a728d2ea Colin Smith
		if($config['installedpackages']['package']) {
656 0d9d2a1b Scott Ullrich
			foreach($config['installedpackages']['package'] as $package) {
657
				if($package['logging']) {
658 d589cccf Warren Baker
					array_push($separatelogfacilities, $package['logging']['facilityname']);
659 100f3e71 Ermal
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
660 eeb52fea Warren Baker
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
661 a728d2ea Colin Smith
				}
662 0d9d2a1b Scott Ullrich
			}
663
		}
664 d2834563 Scott Ullrich
		$facilitylist = implode(',', array_unique($separatelogfacilities));
665 5c8cbb26 jim-p
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
666 e0c45357 jim-p
		if (!isset($syslogcfg['disablelocallogging']))
667
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
668
669
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
670 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
671 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
672
673 295e19dd Scott Ullrich
		$syslogconf .= "!ppp\n";
674
		if (!isset($syslogcfg['disablelocallogging'])) 
675 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
676
677 a6607b5f jim-p
		$syslogconf .= "!pptps\n";
678 328efaba Ermal
		if (!isset($syslogcfg['disablelocallogging'])) 
679 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
680
681 a6607b5f jim-p
		$syslogconf .= "!poes\n";
682 328efaba Ermal
		if (!isset($syslogcfg['disablelocallogging'])) 
683 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
684
685 a6607b5f jim-p
		$syslogconf .= "!l2tps\n";
686 328efaba Ermal
		if (!isset($syslogcfg['disablelocallogging'])) 
687 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
688
689 7335fa53 Ermal
		$syslogconf .= "!charon\n";
690 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
691 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
692
		if (isset($syslogcfg['vpn']))
693
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
694
695 d2834563 Scott Ullrich
		$syslogconf .= "!openvpn\n";
696 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
697 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
698
		if (isset($syslogcfg['vpn']))
699
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
700
701 7bc41b19 jim-p
		$syslogconf .= "!apinger\n";
702
		if (!isset($syslogcfg['disablelocallogging']))
703 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
704
		if (isset($syslogcfg['apinger']))
705
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
706
707 a89b7342 jim-p
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
708 e0977fed smos
		if (!isset($syslogcfg['disablelocallogging']))
709
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
710
711 5c8cbb26 jim-p
		$syslogconf .= "!dhcpd,dhcrelay,dhclient\n";
712 e0977fed smos
		if (!isset($syslogcfg['disablelocallogging']))
713
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
714 80571c81 Phil Davis
		if (isset($syslogcfg['dhcp']))
715 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
716
717 087a89f8 Chris Buechler
		$syslogconf .= "!relayd\n";
718 236524c2 jim-p
		if (!isset($syslogcfg['disablelocallogging']))
719
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
720
		if (isset($syslogcfg['relayd']))
721
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
722
723 689eaa4d jim-p
		$syslogconf .= "!hostapd\n";
724 236524c2 jim-p
		if (!isset($syslogcfg['disablelocallogging']))
725
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
726
		if (isset($syslogcfg['hostapd']))
727
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
728
729 686777c4 Ermal
		$syslogconf .= "!filterlog\n";
730
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
731
		if (isset($syslogcfg['filter']))
732
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
733
734 d2834563 Scott Ullrich
		$syslogconf .= "!-{$facilitylist}\n";
735 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
736 5b237745 Scott Ullrich
			$syslogconf .= <<<EOD
737 236524c2 jim-p
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
738
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
739
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
740 2ba3ea05 Renato Botelho
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
741 236524c2 jim-p
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
742
local7.none							{$log_directive}{$g['varlog_path']}/system.log
743
security.*							{$log_directive}{$g['varlog_path']}/system.log
744
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
745
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
746
*.emerg								*
747 be5d59d7 Scott Ullrich
748
EOD;
749 236524c2 jim-p
		if (isset($syslogcfg['vpn']))
750
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
751
		if (isset($syslogcfg['portalauth']))
752
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
753
		if (isset($syslogcfg['dhcp']))
754
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
755 be5d59d7 Scott Ullrich
		if (isset($syslogcfg['system'])) {
756 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
757
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
758
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
759
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
760
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
761
		}
762 4ef2d703 Chris Buechler
		if (isset($syslogcfg['logall'])) {
763 236524c2 jim-p
			// Make everything mean everything, including facilities excluded above.
764
			$syslogconf .= "!*\n";
765
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
766
		}
767 be5d59d7 Scott Ullrich
768 a213ad18 Andrew Thompson
		if (isset($syslogcfg['zmqserver'])) {
769
				$syslogconf .= <<<EOD
770
*.*								^{$syslogcfg['zmqserver']}
771
772
EOD;
773
		}
774 344016a8 Ermal
		/* write syslog.conf */		
775
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
776
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
777
			unset($syslogconf);
778
			return 1;
779
		}
780
		unset($syslogconf);
781 42ee8bde Scott Ullrich
782
		// Ensure that the log directory exists
783 344016a8 Ermal
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
784 42ee8bde Scott Ullrich
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
785
786 cbe12b8d jim-p
		$sourceip = "";
787
		if (!empty($syslogcfg['sourceip'])) {
788
			if ($syslogcfg['ipproto'] == "ipv6") {
789
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
790
				if (!is_ipaddr($ifaddr))
791
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
792
			} else {
793
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
794
				if (!is_ipaddr($ifaddr))
795
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
796
			}
797
			if (is_ipaddr($ifaddr)) {
798
				$sourceip = "-b {$ifaddr}";
799
			}
800
		}
801
802 66201c96 Ermal
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
803 5b237745 Scott Ullrich
	}
804 0f282d7a Scott Ullrich
805 66201c96 Ermal
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
806
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
807
	else
808
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
809
810 5b237745 Scott Ullrich
	if ($g['booting'])
811 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
812 0f282d7a Scott Ullrich
813 5b237745 Scott Ullrich
	return $retval;
814
}
815
816
function system_webgui_start() {
817 f19d3b7a Scott Ullrich
	global $config, $g;
818 877ac35d Scott Ullrich
819
	if ($g['booting'])
820 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting webConfigurator...");
821 877ac35d Scott Ullrich
822
	chdir($g['www_path']);
823
824 fb1266d3 Matthew Grooms
	/* defaults */
825
	$portarg = "80";
826
	$crt = "";
827
	$key = "";
828 2cf6ddcb Nigel Graham
	$ca = "";
829 fb1266d3 Matthew Grooms
830 877ac35d Scott Ullrich
	/* non-standard port? */
831 f4875d35 Ermal Lu?i
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
832 528df9a7 Scott Ullrich
		$portarg = "{$config['system']['webgui']['port']}";
833 877ac35d Scott Ullrich
834
	if ($config['system']['webgui']['protocol'] == "https") {
835 02b383fe sullrich
		// Ensure that we have a webConfigurator CERT
836 fb1266d3 Matthew Grooms
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
837 02b383fe sullrich
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
838 1e332e98 jim-p
			if (!is_array($config['ca']))
839
				$config['ca'] = array();
840
			$a_ca =& $config['ca'];
841
			if (!is_array($config['cert']))
842
				$config['cert'] = array();
843
			$a_cert =& $config['cert'];
844 e9954aef Scott Ullrich
			log_error("Creating SSL Certificate for this host");
845 aab4ca82 Scott Ullrich
			$cert = array();
846
			$cert['refid'] = uniqid();
847 4816e5ca Renato Botelho
			$cert['descr'] = gettext("webConfigurator default");
848 2ec95f1f Renato Botelho
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
849
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
850 6955830f Ermal Lu?i
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
851
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
852
			unlink("{$g['tmp_path']}/ssl.key");
853
			unlink("{$g['tmp_path']}/ssl.crt");
854 aab4ca82 Scott Ullrich
			cert_import($cert, $crt, $key);
855
			$a_cert[] = $cert;
856
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
857 4a896b86 Carlos Eduardo Ramos
			write_config(gettext("Importing HTTPS certificate"));
858 aab4ca82 Scott Ullrich
			if(!$config['system']['webgui']['port'])
859
				$portarg = "443";
860
			$ca = ca_chain($cert);
861 edc8a9f8 jim-p
		} else {
862 fb1266d3 Matthew Grooms
			$crt = base64_decode($cert['crt']);
863
			$key = base64_decode($cert['prv']);
864
			if(!$config['system']['webgui']['port'])
865
				$portarg = "443";
866 2cf6ddcb Nigel Graham
			$ca = ca_chain($cert);
867 edc8a9f8 jim-p
		}
868 877ac35d Scott Ullrich
	}
869
870
	/* generate lighttpd configuration */
871
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
872 c41602e1 jim-p
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
873 98f20e35 Irving Popovetsky
		"cert.pem", "ca.pem");
874 877ac35d Scott Ullrich
875 a11bc497 Ermal
	/* kill any running lighttpd */
876
	killbypid("{$g['varrun_path']}/lighty-webConfigurator.pid");
877
878
	sleep(1);
879
880
	@unlink("{$g['varrun_path']}/lighty-webConfigurator.pid");
881
882 877ac35d Scott Ullrich
	/* attempt to start lighthttpd */
883
	$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-webConfigurator.conf");
884
885
	if ($g['booting']) {
886
		if ($res == 0)
887 4a896b86 Carlos Eduardo Ramos
			echo gettext("done.") . "\n";
888 877ac35d Scott Ullrich
		else
889 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
890 877ac35d Scott Ullrich
	}
891
892
	return $res;
893
}
894
895 eb0f441c Scott Ullrich
function system_generate_lighty_config($filename,
896
	$cert,
897
	$key,
898 2cf6ddcb Nigel Graham
	$ca,
899 eb0f441c Scott Ullrich
	$pid_file,
900
	$port = 80,
901
	$document_root = "/usr/local/www/",
902
	$cert_location = "cert.pem",
903 2cf6ddcb Nigel Graham
	$ca_location = "ca.pem",
904 eb0f441c Scott Ullrich
	$captive_portal = false) {
905 58c7450e Scott Ullrich
906 f19d3b7a Scott Ullrich
	global $config, $g;
907
908 6955830f Ermal Lu?i
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
909
		mkdir("{$g['tmp_path']}/lighttpdcompress");
910 570ef08c sullrich
911 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
912
		$mt = microtime();
913 dcf0598e Scott Ullrich
		echo "system_generate_lighty_config() being called $mt\n";
914 58c7450e Scott Ullrich
	}
915
916 a96f2d3d Ermal
	if ($captive_portal !== false)  {
917 f7bddb24 Ermal
		$captiveportal = ",\"mod_rewrite\",\"mod_evasive\"";
918 b4792bf8 Ermal
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
919 74a4edc3 Ermal
920 6844896c bcyrill
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
921 a96f2d3d Ermal
		if (empty($maxprocperip))
922 f7bddb24 Ermal
			$maxprocperip = 10;
923 74a4edc3 Ermal
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
924
925 6955830f Ermal Lu?i
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
926 6240ba7b Phil Davis
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
927 e570f0eb Ermal
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
928 775556ab Scott Ullrich
		$server_max_request_size = "server.max-request-size    = 384";
929 b35fdb17 Ermal
		$cgi_config = "";
930 b0bdc06e Scott Ullrich
	} else {
931 b35fdb17 Ermal
		$captiveportal = ",\"mod_cgi\"";
932 3435dc35 Ermal Lu?i
		$captive_portal_rewrite = "";
933 b0bdc06e Scott Ullrich
		$captive_portal_mod_evasive = "";
934 6955830f Ermal Lu?i
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
935 775556ab Scott Ullrich
		$server_max_request_size = "server.max-request-size    = 2097152";
936 b35fdb17 Ermal
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
937 eb0f441c Scott Ullrich
	}
938 3306a341 Scott Ullrich
	
939 a96f2d3d Ermal
	if (empty($port))
940 28cae949 Scott Ullrich
		$lighty_port = "80";
941 a96f2d3d Ermal
	else
942
		$lighty_port = $port;
943 3d77d4c4 Scott Ullrich
944
	$memory = get_memory();
945 6b0739ac Phil Davis
	$realmem = $memory[1];
946 3d77d4c4 Scott Ullrich
947 98f20e35 Irving Popovetsky
	// Determine web GUI process settings and take into account low memory systems
948 6b0739ac Phil Davis
	if ($realmem < 255)
949 a96f2d3d Ermal
		$max_procs = 1;
950
	else
951 98f20e35 Irving Popovetsky
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
952 f4ebc84a Scott Ullrich
953 98f20e35 Irving Popovetsky
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
954 70e454e1 Ermal
	if ($captive_portal !== false)  {
955 6b0739ac Phil Davis
		if ($realmem > 135 and $realmem < 256) {
956 98f20e35 Irving Popovetsky
			$max_procs += 1; // 2 worker processes
957 6b0739ac Phil Davis
		} else if ($realmem > 255 and $realmem < 513) {
958 a96f2d3d Ermal
			$max_procs += 2; // 3 worker processes
959 6b0739ac Phil Davis
		} else if ($realmem > 512) {
960 98f20e35 Irving Popovetsky
			$max_procs += 4; // 6 worker processes
961 70cc6249 Scott Ullrich
		}
962 a96f2d3d Ermal
		if ($max_procs > 1)
963
			$max_php_children = intval($max_procs/2);
964
		else
965
			$max_php_children = 1;
966
967 e384f16e Ermal
	} else {
968 6b0739ac Phil Davis
		if ($realmem < 78)
969 e384f16e Ermal
			$max_php_children = 0;
970
		else
971
			$max_php_children = 1;
972
	}
973 980df75c Scott Ullrich
974 1cf24f0a jim-p
	if(!isset($config['syslog']['nologlighttpd'])) {
975
		$lighty_use_syslog = <<<EOD
976
## where to send error-messages to
977
server.errorlog-use-syslog="enable"
978
EOD;
979
	}
980
981
982 4aea91d8 Ermal
	if ($captive_portal !== false) {
983
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
984
		$fastcgi_config = <<<EOD
985 4edb490d Scott Ullrich
#### fastcgi module
986
## read fastcgi.txt for more info
987 b0bdc06e Scott Ullrich
fastcgi.server = ( ".php" =>
988 a96f2d3d Ermal
	( "localhost" =>
989
		(
990
			"socket" => "{$fast_cgi_path}",
991
			"max-procs" => {$max_procs},
992 70e454e1 Ermal
			"bin-environment" => (
993
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
994
				"PHP_FCGI_MAX_REQUESTS" => "500"
995
			),
996 a96f2d3d Ermal
			"bin-path" => "/usr/local/bin/php"
997
		)
998 b0bdc06e Scott Ullrich
	)
999
)
1000 333f8ef0 Scott Ullrich
1001 4edb490d Scott Ullrich
EOD;
1002 4aea91d8 Ermal
	} else {
1003
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1004
		$fastcgi_config = <<<EOD
1005
#### fastcgi module
1006
## read fastcgi.txt for more info
1007
fastcgi.server = ( ".php" =>
1008
	( "localhost" =>
1009
		(
1010
			"socket" => "{$fast_cgi_path}",
1011
			"broken-scriptfilename" => "enable"
1012
		)
1013
	)
1014
)
1015
1016
EOD;
1017
	}
1018
1019 333f8ef0 Scott Ullrich
1020 a96f2d3d Ermal
	$lighty_config = <<<EOD
1021 28cae949 Scott Ullrich
#
1022 a632cf43 Scott Ullrich
# lighttpd configuration file
1023
#
1024
# use a it as base for lighttpd 1.0.0 and above
1025 28cae949 Scott Ullrich
#
1026 a632cf43 Scott Ullrich
############ Options you really have to take care of ####################
1027
1028 770b4b9c Scott Ullrich
## FreeBSD!
1029 60ff6204 Scott Ullrich
server.event-handler	= "freebsd-kqueue"
1030
server.network-backend 	= "writev"
1031 543ecd59 Seth Mos
#server.use-ipv6 = "enable"
1032 096261af Scott Ullrich
1033 a632cf43 Scott Ullrich
## modules to load
1034 f7bddb24 Ermal
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1035
	{$captiveportal}, "mod_fastcgi"
1036 a41c5253 Seth Mos
)
1037 28cae949 Scott Ullrich
1038 d9acea75 Scott Ullrich
server.max-keep-alive-requests = 15
1039
server.max-keep-alive-idle = 30
1040
1041 a632cf43 Scott Ullrich
## a static document-root, for virtual-hosting take look at the
1042
## server.virtual-* options
1043 332b4ac0 Scott Ullrich
server.document-root        = "{$document_root}"
1044 eb0f441c Scott Ullrich
{$captive_portal_rewrite}
1045 a632cf43 Scott Ullrich
1046 38a9a1ab Scott Ullrich
# Maximum idle time with nothing being written (php downloading)
1047
server.max-write-idle = 999
1048
1049 1cf24f0a jim-p
{$lighty_use_syslog}
1050 a632cf43 Scott Ullrich
1051
# files to check for if .../ is requested
1052
server.indexfiles           = ( "index.php", "index.html",
1053
                                "index.htm", "default.htm" )
1054
1055
# mimetype mapping
1056
mimetype.assign             = (
1057
  ".pdf"          =>      "application/pdf",
1058
  ".sig"          =>      "application/pgp-signature",
1059
  ".spl"          =>      "application/futuresplash",
1060
  ".class"        =>      "application/octet-stream",
1061
  ".ps"           =>      "application/postscript",
1062
  ".torrent"      =>      "application/x-bittorrent",
1063
  ".dvi"          =>      "application/x-dvi",
1064
  ".gz"           =>      "application/x-gzip",
1065
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1066
  ".swf"          =>      "application/x-shockwave-flash",
1067
  ".tar.gz"       =>      "application/x-tgz",
1068
  ".tgz"          =>      "application/x-tgz",
1069
  ".tar"          =>      "application/x-tar",
1070
  ".zip"          =>      "application/zip",
1071
  ".mp3"          =>      "audio/mpeg",
1072
  ".m3u"          =>      "audio/x-mpegurl",
1073
  ".wma"          =>      "audio/x-ms-wma",
1074
  ".wax"          =>      "audio/x-ms-wax",
1075
  ".ogg"          =>      "audio/x-wav",
1076
  ".wav"          =>      "audio/x-wav",
1077
  ".gif"          =>      "image/gif",
1078
  ".jpg"          =>      "image/jpeg",
1079
  ".jpeg"         =>      "image/jpeg",
1080
  ".png"          =>      "image/png",
1081
  ".xbm"          =>      "image/x-xbitmap",
1082
  ".xpm"          =>      "image/x-xpixmap",
1083
  ".xwd"          =>      "image/x-xwindowdump",
1084
  ".css"          =>      "text/css",
1085
  ".html"         =>      "text/html",
1086
  ".htm"          =>      "text/html",
1087
  ".js"           =>      "text/javascript",
1088
  ".asc"          =>      "text/plain",
1089
  ".c"            =>      "text/plain",
1090
  ".conf"         =>      "text/plain",
1091
  ".text"         =>      "text/plain",
1092
  ".txt"          =>      "text/plain",
1093
  ".dtd"          =>      "text/xml",
1094
  ".xml"          =>      "text/xml",
1095
  ".mpeg"         =>      "video/mpeg",
1096
  ".mpg"          =>      "video/mpeg",
1097
  ".mov"          =>      "video/quicktime",
1098
  ".qt"           =>      "video/quicktime",
1099
  ".avi"          =>      "video/x-msvideo",
1100
  ".asf"          =>      "video/x-ms-asf",
1101
  ".asx"          =>      "video/x-ms-asf",
1102
  ".wmv"          =>      "video/x-ms-wmv",
1103
  ".bz2"          =>      "application/x-bzip",
1104
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1105
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1106
 )
1107
1108
# Use the "Content-Type" extended attribute to obtain mime type if possible
1109
#mimetypes.use-xattr        = "enable"
1110
1111
## deny access the file-extensions
1112
#
1113
# ~    is for backupfiles from vi, emacs, joe, ...
1114
# .inc is often used for code includes which should in general not be part
1115
#      of the document-root
1116
url.access-deny             = ( "~", ".inc" )
1117
1118
1119
######### Options that are good to be but not neccesary to be changed #######
1120
1121
## bind to port (default: 80)
1122 9cb94dd4 Ermal
1123
EOD;
1124
1125 6839a678 Ermal
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1126
	$lighty_config .= "server.port  = {$lighty_port}\n";
1127
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1128
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1129
	if($cert <> "" and $key <> "") {
1130
		$lighty_config .= "\n";
1131
		$lighty_config .= "## ssl configuration\n";
1132
		$lighty_config .= "ssl.engine = \"enable\"\n";
1133
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1134
		if($ca <> "")
1135
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1136 543ecd59 Seth Mos
	}
1137 6839a678 Ermal
	$lighty_config .= " }\n";
1138 543ecd59 Seth Mos
1139 9cb94dd4 Ermal
1140
	$lighty_config .= <<<EOD
1141 a632cf43 Scott Ullrich
1142
## error-handler for status 404
1143
#server.error-handler-404   = "/error-handler.html"
1144
#server.error-handler-404   = "/error-handler.php"
1145
1146
## to help the rc.scripts
1147 e141ea70 Ermal
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1148 a632cf43 Scott Ullrich
1149
## virtual directory listings
1150 28cae949 Scott Ullrich
server.dir-listing         = "disable"
1151 a632cf43 Scott Ullrich
1152
## enable debugging
1153 28cae949 Scott Ullrich
debug.log-request-header   = "disable"
1154
debug.log-response-header  = "disable"
1155
debug.log-request-handling = "disable"
1156
debug.log-file-not-found   = "disable"
1157 a632cf43 Scott Ullrich
1158 570ef08c sullrich
# gzip compression
1159 6955830f Ermal Lu?i
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1160 570ef08c sullrich
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1161
1162 3306a341 Scott Ullrich
{$server_upload_dirs}
1163 1ef7b568 Scott Ullrich
1164 a6e8af9c Scott Ullrich
{$server_max_request_size}
1165 ee959dc4 Scott Ullrich
1166 4edb490d Scott Ullrich
{$fastcgi_config}
1167
1168 b35fdb17 Ermal
{$cgi_config}
1169
1170 b0bdc06e Scott Ullrich
{$captive_portal_mod_evasive}
1171
1172 569f47e9 Scott Ullrich
expire.url = (
1173 05a5e5c5 Scott Ullrich
				"" => "access 50 hours",	
1174 569f47e9 Scott Ullrich
        )
1175
1176 a632cf43 Scott Ullrich
EOD;
1177
1178 7aae518a Scott Ullrich
	$cert = str_replace("\r", "", $cert);
1179 333f8ef0 Scott Ullrich
	$key = str_replace("\r", "", $key);
1180 2cf6ddcb Nigel Graham
	$ca = str_replace("\r", "", $ca);
1181 7aae518a Scott Ullrich
1182
	$cert = str_replace("\n\n", "\n", $cert);
1183 333f8ef0 Scott Ullrich
	$key = str_replace("\n\n", "\n", $key);
1184 2cf6ddcb Nigel Graham
	$ca = str_replace("\n\n", "\n", $ca);
1185 7aae518a Scott Ullrich
1186 a632cf43 Scott Ullrich
	if($cert <> "" and $key <> "") {
1187 3a66b621 Scott Ullrich
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1188 5b237745 Scott Ullrich
		if (!$fd) {
1189 4a896b86 Carlos Eduardo Ramos
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1190 5b237745 Scott Ullrich
			return 1;
1191
		}
1192 3a66b621 Scott Ullrich
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1193 5b237745 Scott Ullrich
		fwrite($fd, $cert);
1194
		fwrite($fd, "\n");
1195
		fwrite($fd, $key);
1196
		fclose($fd);
1197 546f30ca jim-p
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1198 2cf6ddcb Nigel Graham
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1199
			if (!$fd) {
1200 4a896b86 Carlos Eduardo Ramos
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1201 2cf6ddcb Nigel Graham
				return 1;
1202
			}
1203
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1204
			fwrite($fd, $ca);
1205
			fclose($fd);
1206
		}
1207 5e041d5f Scott Ullrich
		$lighty_config .= "\n";
1208 4a896b86 Carlos Eduardo Ramos
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1209 a632cf43 Scott Ullrich
		$lighty_config .= "ssl.engine = \"enable\"\n";
1210 333f8ef0 Scott Ullrich
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1211 673ee7b1 Scott Ullrich
1212
		// Harden SSL a bit for PCI conformance testing
1213
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1214 dce51b01 jim-p
1215
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1216
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1217
		if ($fd) {
1218
			while (!feof($fd)) {
1219
				$dmesgl = fgets($fd);
1220
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1221
						unset($config['system']['webgui']['beast_protection']);
1222
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1223
					break;
1224
				}
1225
			}
1226
			fclose($fd);
1227
		}
1228
1229
		if (isset($config['system']['webgui']['beast_protection'])) {
1230
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1231
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1232
		} else {
1233
			$lighty_config .= "ssl.cipher-list = \"DHE-RSA-CAMELLIA256-SHA:DHE-DSS-CAMELLIA256-SHA:CAMELLIA256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:DHE-RSA-CAMELLIA128-SHA:DHE-DSS-CAMELLIA128-SHA:CAMELLIA128-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:RC4-SHA:RC4-MD5:!aNULL:!eNULL:!3DES:@STRENGTH\"\n";
1234
		}
1235 673ee7b1 Scott Ullrich
1236 75e9ed89 jim-p
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1237 2cf6ddcb Nigel Graham
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1238 5b237745 Scott Ullrich
	}
1239 a978a0ff Chris Buechler
1240
	// Add HTTP to HTTPS redirect	
1241 6839a678 Ermal
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1242 7921e8e5 Chris Buechler
		if($lighty_port != "443") 
1243
			$redirectport = ":{$lighty_port}";
1244 d7e230ae Chris Buechler
		$lighty_config .= <<<EOD
1245
\$SERVER["socket"] == ":80" {
1246
	\$HTTP["host"] =~ "(.*)" {
1247 7921e8e5 Chris Buechler
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1248 d7e230ae Chris Buechler
	}
1249
}
1250
EOD;
1251
	}
1252 0f282d7a Scott Ullrich
1253 4f3756f3 Scott Ullrich
	$fd = fopen("{$filename}", "w");
1254 a632cf43 Scott Ullrich
	if (!$fd) {
1255 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1256 a632cf43 Scott Ullrich
		return 1;
1257 5b237745 Scott Ullrich
	}
1258 a632cf43 Scott Ullrich
	fwrite($fd, $lighty_config);
1259
	fclose($fd);
1260
1261
	return 0;
1262 0f282d7a Scott Ullrich
1263 5b237745 Scott Ullrich
}
1264
1265
function system_timezone_configure() {
1266 f19d3b7a Scott Ullrich
	global $config, $g;
1267 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1268
		$mt = microtime();
1269 dcf0598e Scott Ullrich
		echo "system_timezone_configure() being called $mt\n";
1270 333f8ef0 Scott Ullrich
	}
1271 5b237745 Scott Ullrich
1272
	$syscfg = $config['system'];
1273
1274
	if ($g['booting'])
1275 4a896b86 Carlos Eduardo Ramos
		echo gettext("Setting timezone...");
1276 5b237745 Scott Ullrich
1277
	/* extract appropriate timezone file */
1278
	$timezone = $syscfg['timezone'];
1279 add913b1 Renato Botelho
	if ($timezone) {
1280
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1281
		foreach ($tzs as $tz) {
1282
			if (preg_match(",{$timezone}$,", $tz))
1283
				break;
1284
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1285
				$timezone = $matches[1];
1286
				break;
1287
			}
1288
		}
1289
	} else
1290 5b237745 Scott Ullrich
		$timezone = "Etc/UTC";
1291 0f282d7a Scott Ullrich
1292 34febcde Scott Ullrich
	conf_mount_rw();
1293
1294 029d1a71 Scott Ullrich
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1295 5b237745 Scott Ullrich
		escapeshellarg($timezone) . " > /etc/localtime");
1296
1297 4efd4885 Scott Ullrich
	mwexec("sync");
1298 27150275 Scott Ullrich
	conf_mount_ro();
1299 34febcde Scott Ullrich
1300 5b237745 Scott Ullrich
	if ($g['booting'])
1301 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1302 5b237745 Scott Ullrich
}
1303
1304 5c8843d5 jim-p
function system_ntp_setup_gps($serialport) {
1305 142f7393 nagyrobi
	global $config, $g;
1306 5c8843d5 jim-p
	$gps_device = '/dev/gps0';
1307
	$serialport = '/dev/'.$serialport;
1308
1309
	if (!file_exists($serialport))
1310
		return false;
1311
1312
	conf_mount_rw();
1313
	// Create symlink that ntpd requires
1314
	unlink_if_exists($gps_device);
1315
	symlink($serialport, $gps_device);
1316
1317
	/* Send the following to the GPS port to initialize the GPS */
1318 ec7bc948 Ermal
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1319 142f7393 nagyrobi
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1320
	}else{
1321
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1322
	}
1323 ec7bc948 Ermal
1324
	/* XXX: Why not file_put_contents to the device */
1325
	@file_put_contents('/tmp/gps.init', $gps_init);
1326 18080a21 jim-p
	`cat /tmp/gps.init > $serialport`;
1327 5c8843d5 jim-p
1328
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1329 ec7bc948 Ermal
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1330 142f7393 nagyrobi
		$gpsbaud = '4800';
1331 ec7bc948 Ermal
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1332 142f7393 nagyrobi
			switch($config['ntpd']['gps']['speed']) {
1333
				case '16':
1334
					$gpsbaud = '9600';
1335
					break;
1336
				case '32':
1337
					$gpsbaud = '19200';
1338
					break;
1339
				case '48':
1340
					$gpsbaud = '38400';
1341
					break;
1342
				case '64':
1343
					$gpsbaud = '57600';
1344
					break;
1345
				case '80':
1346
					$gpsbaud = '115200';
1347
					break;
1348
			}
1349
		}
1350 ec7bc948 Ermal
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1351
	}
1352 5c8843d5 jim-p
1353
	conf_mount_ro();
1354
1355
	return true;
1356
}
1357
1358 142f7393 nagyrobi
function system_ntp_setup_pps($serialport) {
1359
	global $config, $g;
1360 ec7bc948 Ermal
1361 142f7393 nagyrobi
	$pps_device = '/dev/pps0';
1362
	$serialport = '/dev/'.$serialport;
1363
1364
	if (!file_exists($serialport))
1365
		return false;
1366
1367
	conf_mount_rw();
1368
	// Create symlink that ntpd requires
1369
	unlink_if_exists($pps_device);
1370 ec7bc948 Ermal
	@symlink($serialport, $pps_device);
1371 142f7393 nagyrobi
1372
	conf_mount_ro();
1373
1374
	return true;
1375
}
1376
1377
1378 0b8e9d38 jim-p
function system_ntp_configure($start_ntpd=true) {
1379 f19d3b7a Scott Ullrich
	global $config, $g;
1380 ec7bc948 Ermal
1381 42135f07 jim-p
	$driftfile = "/var/db/ntpd.drift";
1382 5c8843d5 jim-p
	$statsdir = "/var/log/ntp";
1383
	$gps_device = '/dev/gps0';
1384 5b237745 Scott Ullrich
1385 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
1386
		return;
1387
1388 5c8843d5 jim-p
	safe_mkdir($statsdir);
1389
1390 ec7bc948 Ermal
	if (!is_array($config['ntpd']))
1391
		$config['ntpd'] = array();
1392
1393 b2305621 Ermal
	$ntpcfg = "# \n";
1394 42135f07 jim-p
	$ntpcfg .= "# pfSense ntp configuration file \n";
1395 b2305621 Ermal
	$ntpcfg .= "# \n\n";
1396 362c9bb0 jim-p
	$ntpcfg .= "tinker panic 0 \n";
1397 0f282d7a Scott Ullrich
1398 142f7393 nagyrobi
	/* Add Orphan mode */
1399
	$ntpcfg .= "# Orphan mode stratum\n";
1400
	$ntpcfg .= 'tos orphan ';
1401
	if (!empty($config['ntpd']['orphan'])) {
1402
		$ntpcfg .= $config['ntpd']['orphan'];
1403
	}else{
1404
		$ntpcfg .= '12';
1405
	}
1406
	$ntpcfg .= "\n";
1407
1408
	/* Add PPS configuration */
1409
	if (!empty($config['ntpd']['pps'])
1410
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1411
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1412
		$ntpcfg .= "\n";
1413
		$ntpcfg .= "# PPS Setup\n";
1414
		$ntpcfg .= 'server 127.127.22.0';
1415
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1416
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1417
			$ntpcfg .= ' prefer'; 
1418
		}
1419
		if (!empty($config['ntpd']['pps']['noselect'])) {
1420
			$ntpcfg .= ' noselect ';
1421
		}
1422
		$ntpcfg .= "\n";
1423
		$ntpcfg .= 'fudge 127.127.22.0';
1424
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1425
			$ntpcfg .= ' time1 ';
1426
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1427
		}
1428
		if (!empty($config['ntpd']['pps']['flag2'])) {
1429
			$ntpcfg .= ' flag2 1';
1430
		}
1431
		if (!empty($config['ntpd']['pps']['flag3'])) {
1432
			$ntpcfg .= ' flag3 1';
1433
		}else{
1434
			$ntpcfg .= ' flag3 0';
1435
		}
1436
		if (!empty($config['ntpd']['pps']['flag4'])) {
1437
			$ntpcfg .= ' flag4 1';
1438
		}
1439
		if (!empty($config['ntpd']['pps']['refid'])) {
1440
			$ntpcfg .= ' refid ';
1441
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1442
		}
1443
		$ntpcfg .= "\n";
1444
	}
1445
	/* End PPS configuration */
1446
1447
	/* Add GPS configuration */
1448
	if (!empty($config['ntpd']['gps'])
1449
		&& file_exists('/dev/'.$config['ntpd']['gps']['port'])
1450
		&& system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1451
		$ntpcfg .= "\n";
1452
		$ntpcfg .= "# GPS Setup\n";
1453
		$ntpcfg .= 'server 127.127.20.0 mode ';
1454
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1455
			if (!empty($config['ntpd']['gps']['nmea'])) {
1456
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1457
			}
1458
			if (!empty($config['ntpd']['gps']['speed'])) {
1459
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1460
			}
1461
			if (!empty($config['ntpd']['gps']['subsec'])) {
1462
				$ntpmode += 128;
1463
			}
1464
			$ntpcfg .= (string) $ntpmode;
1465
		}else{
1466
			$ntpcfg .= '0';
1467
		}
1468
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1469
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1470
			$ntpcfg .= ' prefer'; 
1471
		}
1472
		if (!empty($config['ntpd']['gps']['noselect'])) {
1473
			$ntpcfg .= ' noselect ';
1474
		}
1475
		$ntpcfg .= "\n";
1476
		$ntpcfg .= 'fudge 127.127.20.0';
1477
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1478
			$ntpcfg .= ' time1 ';
1479
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1480
		}
1481
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1482
			$ntpcfg .= ' time2 ';
1483
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1484
		}
1485
		if (!empty($config['ntpd']['gps']['flag1'])) {
1486
			$ntpcfg .= ' flag1 1';
1487
		}else{
1488
			$ntpcfg .= ' flag1 0';
1489
		}
1490
		if (!empty($config['ntpd']['gps']['flag2'])) {
1491
			$ntpcfg .= ' flag2 1';
1492
		}
1493
		if (!empty($config['ntpd']['gps']['flag3'])) {
1494
			$ntpcfg .= ' flag3 1';
1495
		}else{
1496
			$ntpcfg .= ' flag3 0';
1497
		}
1498
		if (!empty($config['ntpd']['gps']['flag4'])) {
1499
			$ntpcfg .= ' flag4 1';
1500
		}
1501
		if (!empty($config['ntpd']['gps']['refid'])) {
1502
			$ntpcfg .= ' refid ';
1503
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1504
		}
1505
		$ntpcfg .= "\n";
1506
	}elseif (!empty($config['ntpd']['gpsport'])
1507 5c8843d5 jim-p
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1508
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1509 142f7393 nagyrobi
		/* This handles a 2.1 and earlier config */
1510 5c8843d5 jim-p
		$ntpcfg .= "# GPS Setup\n";
1511
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1512
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1513
		// Fall back to local clock if GPS is out of sync?
1514
		$ntpcfg .= "server 127.127.1.0\n";
1515
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1516
	}
1517 142f7393 nagyrobi
	/* End GPS configuration */
1518
	
1519 5c8843d5 jim-p
	$ntpcfg .= "\n\n# Upstream Servers\n";
1520 142f7393 nagyrobi
	/* foreach through ntp servers and write out to ntpd.conf */
1521
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1522
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1523
		if (substr_count($config['ntpd']['prefer'], $ts)) $ntpcfg .= ' prefer';
1524
		if (substr_count($config['ntpd']['noselect'], $ts)) $ntpcfg .= ' noselect';
1525
		$ntpcfg .= "\n";
1526
	}
1527
	unset($ts);
1528
1529
	$ntpcfg .= "\n\n";
1530 e1a456e6 Chris Buechler
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see https://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1531 142f7393 nagyrobi
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1532
		$ntpcfg .= "enable stats\n";
1533
		$ntpcfg .= 'statistics';
1534
		if (!empty($config['ntpd']['clockstats'])) {
1535
			$ntpcfg .= ' clockstats';
1536
		}
1537
		if (!empty($config['ntpd']['loopstats'])) {
1538
			$ntpcfg .= ' loopstats';
1539
		}
1540
		if (!empty($config['ntpd']['peerstats'])) {
1541
			$ntpcfg .= ' peerstats';
1542
		}
1543
		$ntpcfg .= "\n";
1544
	}
1545 5c8843d5 jim-p
	$ntpcfg .= "statsdir {$statsdir}\n";
1546 142f7393 nagyrobi
	$ntpcfg .= 'logconfig =syncall +clockall';
1547
	if (!empty($config['ntpd']['logpeer'])) {
1548
		$ntpcfg .= ' +peerall';
1549
	}
1550
	if (!empty($config['ntpd']['logsys'])) {
1551
		$ntpcfg .= ' +sysall';
1552
	}
1553
	$ntpcfg .= "\n";
1554 42135f07 jim-p
	$ntpcfg .= "driftfile {$driftfile}\n";
1555 142f7393 nagyrobi
	/* Access restrictions */
1556
	$ntpcfg .= 'restrict default';
1557
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1558
		$ntpcfg .= ' kod limited'; 
1559
	}
1560
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1561
		$ntpcfg .= ' nomodify'; 
1562
	}
1563
	if (!empty($config['ntpd']['noquery'])) {
1564
		$ntpcfg .= ' noquery';
1565
	}
1566
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1567
		$ntpcfg .= ' nopeer'; 
1568
	}
1569
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1570
		$ntpcfg .= ' notrap'; 
1571
	}
1572
	if (!empty($config['ntpd']['noserve'])) {
1573
		$ntpcfg .= ' noserve';
1574
	}
1575
	$ntpcfg .= "\nrestrict -6 default";
1576
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1577
		$ntpcfg .= ' kod limited'; 
1578
	}
1579
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1580
		$ntpcfg .= ' nomodify'; 
1581
	}
1582
	if (!empty($config['ntpd']['noquery'])) {
1583
		$ntpcfg .= ' noquery';
1584
	}
1585
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1586
		$ntpcfg .= ' nopeer'; 
1587
	}
1588
	if (!empty($config['ntpd']['noserve'])) {
1589
		$ntpcfg .= ' noserve';
1590
	}
1591
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1592
		$ntpcfg .= ' notrap'; 
1593
	}
1594
	$ntpcfg .= "\n";
1595
1596
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1597
	$ntpcfg .= "\n";
1598
	if (!empty($config['ntpd']['leapsec'])) {
1599
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1600
		file_put_contents('/var/db/leap-seconds', $leapsec);
1601
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1602
	}
1603
	
1604 95594e5a Scott Ullrich
1605 cf180ccc jim-p
	if (empty($config['ntpd']['interface']))
1606 e43d53b4 Phil Davis
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1607 cf180ccc jim-p
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1608
		else
1609
			$interfaces = array();
1610
	else
1611
		$interfaces = explode(",", $config['ntpd']['interface']);
1612
1613
	if (is_array($interfaces) && count($interfaces)) {
1614
		$ntpcfg .= "interface ignore all\n";
1615
		foreach ($interfaces as $interface) {
1616
			if (!is_ipaddr($interface)) {
1617
				$interface = get_real_interface($interface);
1618
			}
1619 8b650e57 jim-p
			if (!empty($interface))
1620
				$ntpcfg .= "interface listen {$interface}\n";
1621 cf180ccc jim-p
		}
1622
	}
1623
1624 b2305621 Ermal
	/* open configuration for wrting or bail */
1625 b9f29f84 Ermal
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1626 b2305621 Ermal
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1627
		return;
1628
	}
1629 20b90e0a Scott Ullrich
1630 0b8e9d38 jim-p
	/* At bootup we just want to write out the config. */
1631
	if (!$start_ntpd)
1632
		return;
1633
1634 42135f07 jim-p
	/* if ntpd is running, kill it */
1635 df40755d Ermal
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1636 b9f29f84 Ermal
		killbypid("{$g['varrun_path']}/ntpd.pid");
1637 5f3e1f12 Scott Ullrich
	}
1638 b9f29f84 Ermal
	@unlink("{$g['varrun_path']}/ntpd.pid");
1639 5f3e1f12 Scott Ullrich
1640
	/* if /var/empty does not exist, create it */
1641
	if(!is_dir("/var/empty"))
1642 0fd64e94 nagyrobi
		mkdir("/var/empty", 0775, true);
1643 5f3e1f12 Scott Ullrich
1644 20b90e0a Scott Ullrich
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1645 0fd64e94 nagyrobi
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1646 83eb4567 Scott Ullrich
	
1647
	// Note that we are starting up
1648 42135f07 jim-p
	log_error("NTPD is starting up.");
1649 0b8e9d38 jim-p
	return;
1650 5b237745 Scott Ullrich
}
1651
1652 652cf082 Seth Mos
function sync_system_time() {
1653
	global $config, $g;
1654
1655
	if ($g['booting'])
1656 4a896b86 Carlos Eduardo Ramos
		echo gettext("Syncing system time before startup...");
1657 652cf082 Seth Mos
1658
	/* foreach through servers and write out to ntpd.conf */
1659 b2305621 Ermal
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1660 fdfa8f43 jim-p
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1661 652cf082 Seth Mos
	}
1662 4582b281 Scott Ullrich
	
1663
	if ($g['booting'])
1664 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1665 4582b281 Scott Ullrich
	
1666 652cf082 Seth Mos
}
1667
1668 405e5de0 Scott Ullrich
function system_halt() {
1669
	global $g;
1670
1671
	system_reboot_cleanup();
1672
1673 523855b0 Scott Ullrich
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1674 405e5de0 Scott Ullrich
}
1675
1676 5b237745 Scott Ullrich
function system_reboot() {
1677
	global $g;
1678 0f282d7a Scott Ullrich
1679 5b237745 Scott Ullrich
	system_reboot_cleanup();
1680 0f282d7a Scott Ullrich
1681 5b237745 Scott Ullrich
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1682
}
1683
1684
function system_reboot_sync() {
1685
	global $g;
1686 0f282d7a Scott Ullrich
1687 5b237745 Scott Ullrich
	system_reboot_cleanup();
1688 0f282d7a Scott Ullrich
1689 5b237745 Scott Ullrich
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1690
}
1691
1692
function system_reboot_cleanup() {
1693 62f20eab Michael Newton
	global $config, $cpzone;
1694
1695 97d4e30b Seth Mos
	mwexec("/usr/local/bin/beep.sh stop");
1696 04967d99 jim-p
	require_once("captiveportal.inc");
1697 52034432 Renato Botelho
	if (is_array($config['captiveportal'])) {
1698 34cb8645 Jean Cyr
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1699
			captiveportal_radius_stop_all();
1700
			captiveportal_send_server_accounting(true);
1701
		}
1702 62f20eab Michael Newton
	}
1703 336e3c1c Charlie
	require_once("voucher.inc");
1704
	voucher_save_db_to_config();
1705 60dd7649 jim-p
	require_once("pkg-utils.inc");
1706
	stop_packages();
1707 5b237745 Scott Ullrich
}
1708
1709
function system_do_shell_commands($early = 0) {
1710 f19d3b7a Scott Ullrich
	global $config, $g;
1711 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1712
		$mt = microtime();
1713 dcf0598e Scott Ullrich
		echo "system_do_shell_commands() being called $mt\n";
1714 58c7450e Scott Ullrich
	}
1715 0f282d7a Scott Ullrich
1716 5b237745 Scott Ullrich
	if ($early)
1717
		$cmdn = "earlyshellcmd";
1718
	else
1719
		$cmdn = "shellcmd";
1720 0f282d7a Scott Ullrich
1721 5b237745 Scott Ullrich
	if (is_array($config['system'][$cmdn])) {
1722 333f8ef0 Scott Ullrich
1723 245388b4 Scott Ullrich
		/* *cmd is an array, loop through */
1724 5b237745 Scott Ullrich
		foreach ($config['system'][$cmdn] as $cmd) {
1725
			exec($cmd);
1726
		}
1727 245388b4 Scott Ullrich
1728
	} elseif($config['system'][$cmdn] <> "") {
1729 333f8ef0 Scott Ullrich
1730 245388b4 Scott Ullrich
		/* execute single item */
1731
		exec($config['system'][$cmdn]);
1732
1733 5b237745 Scott Ullrich
	}
1734
}
1735
1736
function system_console_configure() {
1737 f19d3b7a Scott Ullrich
	global $config, $g;
1738 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1739
		$mt = microtime();
1740 dcf0598e Scott Ullrich
		echo "system_console_configure() being called $mt\n";
1741 333f8ef0 Scott Ullrich
	}
1742 0f282d7a Scott Ullrich
1743 5b237745 Scott Ullrich
	if (isset($config['system']['disableconsolemenu'])) {
1744
		touch("{$g['varetc_path']}/disableconsole");
1745
	} else {
1746
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1747
	}
1748
}
1749
1750
function system_dmesg_save() {
1751 f19d3b7a Scott Ullrich
	global $g;
1752 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1753
		$mt = microtime();
1754 dcf0598e Scott Ullrich
		echo "system_dmesg_save() being called $mt\n";
1755 f19d3b7a Scott Ullrich
	}
1756 0f282d7a Scott Ullrich
1757 767a716e Scott Ullrich
	$dmesg = "";
1758 703b1ce1 Ermal
	$_gb = exec("/sbin/dmesg", $dmesg);
1759 0f282d7a Scott Ullrich
1760 5b237745 Scott Ullrich
	/* find last copyright line (output from previous boots may be present) */
1761
	$lastcpline = 0;
1762 0f282d7a Scott Ullrich
1763 5b237745 Scott Ullrich
	for ($i = 0; $i < count($dmesg); $i++) {
1764
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1765
			$lastcpline = $i;
1766
	}
1767 0f282d7a Scott Ullrich
1768 5b237745 Scott Ullrich
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1769
	if (!$fd) {
1770 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1771 5b237745 Scott Ullrich
		return 1;
1772
	}
1773 0f282d7a Scott Ullrich
1774 5b237745 Scott Ullrich
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1775
		fwrite($fd, $dmesg[$i] . "\n");
1776 0f282d7a Scott Ullrich
1777 5b237745 Scott Ullrich
	fclose($fd);
1778 703b1ce1 Ermal
	unset($dmesg);
1779 0f282d7a Scott Ullrich
1780 5b237745 Scott Ullrich
	return 0;
1781
}
1782
1783
function system_set_harddisk_standby() {
1784 f19d3b7a Scott Ullrich
	global $g, $config;
1785 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1786
		$mt = microtime();
1787 dcf0598e Scott Ullrich
		echo "system_set_harddisk_standby() being called $mt\n";
1788 58c7450e Scott Ullrich
	}
1789 5b237745 Scott Ullrich
1790
	if (isset($config['system']['harddiskstandby'])) {
1791
		if ($g['booting']) {
1792 4a896b86 Carlos Eduardo Ramos
			echo gettext('Setting hard disk standby... ');
1793 5b237745 Scott Ullrich
		}
1794
1795
		$standby = $config['system']['harddiskstandby'];
1796
		// Check for a numeric value
1797
		if (is_numeric($standby)) {
1798
			// Sync the disk(s)
1799 5ba5a8de Scott Ullrich
			pfSense_sync();
1800 5b237745 Scott Ullrich
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1801
				// Reinitialize ATA-drives
1802
				mwexec('/usr/local/sbin/atareinit');
1803
				if ($g['booting']) {
1804 4a896b86 Carlos Eduardo Ramos
					echo gettext("done.") . "\n";
1805 5b237745 Scott Ullrich
				}
1806
			} else if ($g['booting']) {
1807 4a896b86 Carlos Eduardo Ramos
				echo gettext("failed!") . "\n";
1808 5b237745 Scott Ullrich
			}
1809
		} else if ($g['booting']) {
1810 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
1811 5b237745 Scott Ullrich
		}
1812
	}
1813
}
1814
1815 3ff9d424 Scott Ullrich
function system_setup_sysctl() {
1816 f19d3b7a Scott Ullrich
	global $config;
1817 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1818
		$mt = microtime();
1819 dcf0598e Scott Ullrich
		echo "system_setup_sysctl() being called $mt\n";
1820 58c7450e Scott Ullrich
	}
1821 243aa7b9 Scott Ullrich
1822 6df9d7e3 Scott Ullrich
	activate_sysctls();	
1823
1824 243aa7b9 Scott Ullrich
	if (isset($config['system']['sharednet'])) {
1825
		system_disable_arp_wrong_if();
1826
	}
1827
}
1828
1829
function system_disable_arp_wrong_if() {
1830 f19d3b7a Scott Ullrich
	global $config;
1831 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1832
		$mt = microtime();
1833 dcf0598e Scott Ullrich
		echo "system_disable_arp_wrong_if() being called $mt\n";
1834 333f8ef0 Scott Ullrich
	}
1835 6cb438cf Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1836 89f4b6a3 Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1837 3ff9d424 Scott Ullrich
}
1838
1839 243aa7b9 Scott Ullrich
function system_enable_arp_wrong_if() {
1840 f19d3b7a Scott Ullrich
	global $config;
1841 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1842
		$mt = microtime();
1843 dcf0598e Scott Ullrich
		echo "system_enable_arp_wrong_if() being called $mt\n";
1844 58c7450e Scott Ullrich
	}
1845 243aa7b9 Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1846 89f4b6a3 Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1847 243aa7b9 Scott Ullrich
}
1848
1849 a199b93e Scott Ullrich
function enable_watchdog() {
1850
	global $config;
1851 1a479479 Scott Ullrich
	return;
1852 a199b93e Scott Ullrich
	$install_watchdog = false;
1853
	$supported_watchdogs = array("Geode");
1854
	$file = file_get_contents("/var/log/dmesg.boot");
1855
	foreach($supported_watchdogs as $sd) {
1856
		if(stristr($file, "Geode")) {
1857
			$install_watchdog = true;
1858
		}
1859
	}
1860
	if($install_watchdog == true) {
1861 2e44fb05 Scott Ullrich
		if(is_process_running("watchdogd"))
1862 e0b4e47f Seth Mos
			mwexec("/usr/bin/killall watchdogd", true);
1863 333f8ef0 Scott Ullrich
		exec("/usr/sbin/watchdogd");
1864 a199b93e Scott Ullrich
	}
1865
}
1866 15f14889 Scott Ullrich
1867
function system_check_reset_button() {
1868 fa83737d Scott Ullrich
	global $g;
1869 223ef06a Scott Ullrich
	if($g['platform'] != "nanobsd")
1870 fa83737d Scott Ullrich
		return 0;
1871 15f14889 Scott Ullrich
1872 31c9379c Scott Ullrich
	$specplatform = system_identify_specific_platform();
1873
1874 15f14889 Scott Ullrich
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1875
		return 0;
1876
1877
	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");
1878
1879
	if ($retval == 99) {
1880
		/* user has pressed reset button for 2 seconds - 
1881
		   reset to factory defaults */
1882
		echo <<<EOD
1883
1884
***********************************************************************
1885
* Reset button pressed - resetting configuration to factory defaults. *
1886
* The system will reboot after this completes.                        *
1887
***********************************************************************
1888
1889
1890
EOD;
1891
		
1892
		reset_factory_defaults();
1893
		system_reboot_sync();
1894
		exit(0);
1895
	}
1896
1897
	return 0;
1898
}
1899
1900 31c9379c Scott Ullrich
/* attempt to identify the specific platform (for embedded systems)
1901
   Returns an array with two elements:
1902
	name => platform string (e.g. 'wrap', 'alix' etc.)
1903
	descr => human-readable description (e.g. "PC Engines WRAP")
1904
*/
1905
function system_identify_specific_platform() {
1906
	global $g;
1907
	
1908
	if ($g['platform'] == 'generic-pc')
1909 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1910 31c9379c Scott Ullrich
	
1911
	if ($g['platform'] == 'generic-pc-cdrom')
1912 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1913 31c9379c Scott Ullrich
	
1914
	/* the rest of the code only deals with 'embedded' platforms */
1915 1a2911a7 Scott Ullrich
	if ($g['platform'] != 'nanobsd')
1916 31c9379c Scott Ullrich
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1917 f0014c64 Ermal
1918 703b1ce1 Ermal
	unset($output);
1919 f0014c64 Ermal
	$_gb = exec('/sbin/sysctl -n hw.model', $output);
1920 703b1ce1 Ermal
	$dmesg = $output[0];
1921 f0014c64 Ermal
1922 31c9379c Scott Ullrich
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1923 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1924 31c9379c Scott Ullrich
	
1925
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1926 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1927 31c9379c Scott Ullrich
1928
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1929
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1930
	
1931
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1932
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1933
		
1934
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1935
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1936
	
1937
	/* unknown embedded platform */
1938 4a896b86 Carlos Eduardo Ramos
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1939 31c9379c Scott Ullrich
}
1940
1941
function system_get_dmesg_boot() {
1942
	global $g;
1943 d16af75d Scott Ullrich
		
1944 31c9379c Scott Ullrich
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1945
}
1946
1947 81448ffa jim-p
function get_possible_listen_ips($include_ipv6_link_local=false) {
1948 7401c8c4 jim-p
	$interfaces = get_configured_interface_with_descr();
1949
	$carplist = get_configured_carp_interface_list();
1950
	$listenips = array();
1951
	foreach ($carplist as $cif => $carpip)
1952
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1953
	$aliaslist = get_configured_ip_aliases_list();
1954
	foreach ($aliaslist as $aliasip => $aliasif)
1955
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1956
	foreach ($interfaces as $iface => $ifacename) {
1957
		$tmp["name"]  = $ifacename;
1958
		$tmp["value"] = $iface;
1959
		$listenips[] = $tmp;
1960 81448ffa jim-p
		if ($include_ipv6_link_local) {
1961
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1962
			if (!empty($llip)) {
1963
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1964
				$tmp["value"] = $llip;
1965
				$listenips[] = $tmp;
1966
			}
1967
		}
1968 7401c8c4 jim-p
	}
1969
	$tmp["name"]  = "Localhost";
1970
	$tmp["value"] = "lo0";
1971
	$listenips[] = $tmp;
1972
	return $listenips;
1973
}
1974 943994ff Scott Ullrich
1975 81448ffa jim-p
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1976 0d56c06b jim-p
	global $config;
1977 81448ffa jim-p
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1978 0d56c06b jim-p
	foreach (array('server', 'client') as $mode) {
1979
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1980
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1981
				if (!isset($setting['disable'])) {
1982
					$vpn = array();
1983
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1984
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1985
					$sourceips[] = $vpn;
1986
				}
1987
			}
1988
		}
1989
	}
1990
	return $sourceips;
1991
}
1992 3b8a17a1 Ermal
?>