Project

General

Profile

Download (41.7 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	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

    
20
	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
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/bin/netstat	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar	/bin/sync	/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit
38
	pfSense_MODULE:	utils
39
*/
40

    
41
function activate_powerd() {
42
	global $config, $g;
43
	if(isset($config['system']['powerd_enable'])) {
44
		exec("/usr/sbin/powerd -b adp -a adp");
45
	} else {
46
		if(is_process_running("powerd"))
47
			exec("/usr/bin/killall powerd");
48
	}
49
}
50

    
51
function get_default_sysctl_value($id) {
52
	global $sysctls;
53
	foreach($sysctls as $sysctl => $value) {
54
		if($sysctl == $id)
55
			return $value;
56
	}
57
}
58

    
59
function activate_sysctls() {
60
	global $config, $g;
61
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x00000001");
62
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
63
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000002");
64
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
65

    
66
	if(is_array($config['sysctl'])) {
67
		foreach($config['sysctl']['item'] as $tunable) {
68
			if($tunable['value'] == "default") {
69
				$value = get_default_sysctl_value($tunable['tunable']);
70
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"");
71
			} else { 
72
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"");
73
			}
74
		}
75
	}
76
}
77

    
78
function system_resolvconf_generate($dynupdate = false) {
79
	global $config, $g;
80

    
81
	if(isset($config['system']['developerspew'])) {
82
		$mt = microtime();
83
		echo "system_resolvconf_generate() being called $mt\n";
84
	}
85

    
86
	$syscfg = $config['system'];
87

    
88
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
89
	if (!$fd) {
90
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
91
		return 1;
92
	}
93

    
94
	$resolvconf = "domain {$syscfg['domain']}\n";
95

    
96
	$havedns = false;
97

    
98
	if (isset($syscfg['dnsallowoverride'])) {
99
		/* get dynamically assigned DNS servers (if any) */
100
		$ns = array_unique(get_nameservers());
101
		foreach($ns as $nameserver) {
102
			if($nameserver) {
103
				$resolvconf .= "nameserver $nameserver\n";
104
				$havedns = true;
105
			}
106
		}
107
	}
108
	if (!$havedns && is_array($syscfg['dnsserver'])) {
109
		foreach ($syscfg['dnsserver'] as $ns) {
110
			if ($ns) {
111
				$resolvconf .= "nameserver $ns\n";
112
				$havedns = true;
113
			}
114
		}
115
	}
116

    
117
	fwrite($fd, $resolvconf);
118
	fclose($fd);
119

    
120
	if (!$g['booting']) {
121
		/* restart dhcpd (nameservers may have changed) */
122
		if (!$dynupdate)
123
			services_dhcpd_configure();
124
	}
125

    
126
	/* setup static routes for DNS servers. */
127
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
128
		/* setup static routes for dns servers */
129
		$dnsgw = "dns{$dnscounter}gwint";
130
		if (isset($config['system'][$dnsgw])) {
131
			$interface = $config['system'][$dnsgw];
132
			if (($interface <> "") && ($interface <> "none")) {
133
				$gatewayip = get_interface_gateway($interface);
134
				if(is_ipaddr($gatewayip)) {
135
					/* dns server array starts at 0 */
136
					$dnscountermo = $dnscounter - 1;
137
					mwexec("route delete -host {$syscfg['dnsserver'][$dnscountermo]}", true);
138
					mwexec("route add -host {$syscfg['dnsserver'][$dnscountermo]} {$gatewayip}");
139
				}
140
			}
141
		}
142
	}
143
	
144
	return 0;
145
}
146

    
147
function get_nameservers() {
148
	global $config, $g;
149
	$master_list = array();
150
	
151
	// Read in dhclient nameservers
152
	$dns_lists = split("\n", `/bin/cat /var/etc/nameserver_* 2>/dev/null`);
153
	if (is_array($dns_lists)) {
154
		foreach($dns_lists as $dns) {
155
			if(is_ipaddr($dns)) 
156
				$master_list[] = $dns;
157
		}
158
	}
159

    
160
	// Read in any extra nameservers
161
	if(file_exists("/var/etc/nameservers.conf")) {
162
		$dns_lists = split("\n", `/bin/cat /var/etc/nameservers.conf`);
163
		if(is_array($dns_s))
164
			foreach($dns_s as $dns)
165
				if (is_ipaddr($dns))
166
					$master_list[] = $dns;
167
	}
168

    
169
	return $master_list;
170
}
171

    
172
function system_hosts_generate() {
173
	global $config, $g;
174
	if(isset($config['system']['developerspew'])) {
175
		$mt = microtime();
176
		echo "system_hosts_generate() being called $mt\n";
177
	}
178

    
179
	$syscfg = $config['system'];
180
	$dnsmasqcfg = $config['dnsmasq'];
181

    
182
	if (!is_array($dnsmasqcfg['hosts'])) {
183
		$dnsmasqcfg['hosts'] = array();
184
	}
185
	$hostscfg = $dnsmasqcfg['hosts'];
186

    
187
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
188
	if (!$fd) {
189
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
190
		return 1;
191
	}
192

    
193
	$hosts .= "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
194

    
195
	if ($config['interfaces']['lan']) {
196
		$cfgip = get_interface_ip("lan");
197
		if (is_ipaddr($cfgip))
198
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
199
	} else {
200
		$sysiflist = get_configured_interface_list();
201
		foreach ($sysiflist as $sysif) {
202
			if (!interface_has_gateway($sysif)) {
203
				$cfgip = get_interface_ip($sysif);
204
				if (is_ipaddr($cfgip)) {
205
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
206
					break;
207
				}
208
			}
209
		}
210
	}
211

    
212
	foreach ($hostscfg as $host) {
213
		if ($host['host'])
214
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
215
		else
216
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
217
	}
218
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
219
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
220
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
221
					foreach ($dhcpifconf['staticmap'] as $host)
222
						if ($host['ipaddr'] && $host['hostname'])
223
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
224
	}
225
	fwrite($fd, $hosts);
226
	fclose($fd);
227

    
228
	return 0;
229
}
230

    
231
function system_hostname_configure() {
232
	global $config, $g;
233
	if(isset($config['system']['developerspew'])) {
234
		$mt = microtime();
235
		echo "system_hostname_configure() being called $mt\n";
236
	}
237

    
238
	$syscfg = $config['system'];
239

    
240
	/* set hostname */
241
	$status = mwexec("/bin/hostname " .
242
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
243

    
244
    /* Setup host GUID ID.  This is used by ZFS. */
245
	mwexec("/etc/rc.d/hostid start");
246

    
247
	return $status;
248
}
249

    
250
function system_routing_configure() {
251
	global $config, $g;
252
	if(isset($config['system']['developerspew'])) {
253
		$mt = microtime();
254
		echo "system_routing_configure() being called $mt\n";
255
	}
256

    
257
	/* Enable fast routing, if enabled */
258
	/* XXX: More checks need to be done for subsystems that are not compatibel with fast routing. */
259
	if(isset($config['staticroutes']['enablefastrouting']) && !isset($config['ipsec']['enable']))
260
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
261

    
262
	$gatewayip = "";
263
	$interfacegw = "";
264
	/* tack on all the hard defined gateways as well */
265
	if (is_array($config['gateways']['gateway_item'])) {
266
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw");
267
		$foundgw = false;
268
		foreach	($config['gateways']['gateway_item'] as $gateway) {
269
			if (isset($gateway['defaultgw'])) {
270
				if ($gateway['gateway'] == "dynamic")
271
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
272
				$gatewayip = $gateway['gateway'];
273
				$interfacegw = $gateway['interface'];
274
				if (!empty($interfacegw)) {
275
					$defaultif = get_real_interface($gateway['interface']);
276
					if ($defaultif)
277
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
278
				}
279
				$foundgw = true;
280
				break;
281
			}
282
		}
283
		if ($foundgw == false) {
284
			$defaultif = get_real_interface("wan");
285
			$interfacegw = "wan";
286
			$gatewayip = get_interface_gateway("wan");
287
			@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
288
		}	
289
	}
290
	$dont_add_route = false;
291
	/* if OLSRD is enabled, allow WAN to house DHCP. */
292
	if($config['installedpackages']['olsrd']) {
293
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
294
			if($olsrd['enabledyngw'] == "on") {
295
				$dont_add_route = true;
296
				break;
297
			}
298
		}
299
	}
300
	/* Create a array from the existing route table */
301
	exec("/usr/bin/netstat -rnf inet", $route_str);
302
	array_shift($route_str);
303
	array_shift($route_str);
304
	array_shift($route_str);
305
	array_shift($route_str);
306
	$route_arr = array();
307
	foreach($route_str as $routeline) {
308
		$items = preg_split("/[ ]+/i", $routeline);
309
		$route_arr[$item[0]] = array($items[0], $items[1], $items[5]);
310
	}
311

    
312
	if ($dont_add_route == false) {
313
		if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
314
			$action = "add";
315
			if(isset($route_arr['default'])) {
316
				$action = "change";
317
			}
318
			log_error("ROUTING: $action default route to $gatewayip");
319
			mwexec("/sbin/route {$action} default " . escapeshellarg($gatewayip));
320
		} else if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
321
			/* Adding gateway for 1.2-style configs without the new
322
		  	 * gateway setup configured.
323
		  	 * Force WAN to be default gateway because that is the 1.2 behavior.
324
			 */
325
			log_error("WARNING: There is no default gateway in the configuration.");
326
			$gatewayip = $config['interfaces']['wan']['gateway'];
327
			mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
328
		}
329
	}
330

    
331
	if (is_array($config['staticroutes']['route'])) {
332
		$gateways_arr = return_gateways_array();
333

    
334
		foreach ($config['staticroutes']['route'] as $rtent) {
335
			$gatewayip = "";
336
			if (isset($gateways_arr[$rtent['gateway']])) {
337
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
338
				$interfacegw = get_real_interface($rtent['interface']);
339
			} else if (is_ipaddr($rtent['gateway'])) {
340
				$gatewayip = $rtent['gateway'];
341
			} else {
342
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
343
				continue;
344
			}
345

    
346
			$action = "add";
347
			if (isset($route_arr[$rtent['network']]))
348
				$action = "change";
349

    
350
			if (is_ipaddr($gatewayip)) {
351
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
352
					" " . escapeshellarg($gatewayip));
353
			} else if (!empty($interfacegw)) {
354
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
355
					" -iface " . escapeshellarg($interfacegw));
356
			}
357
		}
358
	}
359

    
360
	return 0;
361
}
362

    
363
function system_routing_enable() {
364
	global $config, $g;
365
	if(isset($config['system']['developerspew'])) {
366
		$mt = microtime();
367
		echo "system_routing_enable() being called $mt\n";
368
	}
369

    
370
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
371
}
372

    
373
function system_syslogd_start() {
374
	global $config, $g;
375
	if(isset($config['system']['developerspew'])) {
376
		$mt = microtime();
377
		echo "system_syslogd_start() being called $mt\n";
378
	}
379

    
380
	$syslogcfg = $config['syslog'];
381

    
382
	if ($g['booting'])
383
		echo "Starting syslog...";
384
	else
385
		killbypid("{$g['varrun_path']}/syslog.pid");
386

    
387
	if(is_process_running("syslogd"))
388
		mwexec("/usr/bin/killall -9 syslogd");
389
	if(is_process_running("fifolog_writer"))
390
		mwexec("/usr/bin/killall -9 fifolog_writer");
391
	
392
	// Define carious commands for logging
393
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
394
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
395
	$clog_create = "/usr/sbin/clog -i -s ";
396
	$clog_log = "%";
397

    
398
	// Which logging type are we using this week??
399
	if(isset($config['system']['usefifolog'])) {
400
		$log_directive = $fifolog_log;
401
		$log_create_directive = $fifolog_create;		
402
	} else { // Defaults to CLOG
403
		$log_directive = $clog_log;
404
		$log_create_directive = $clog_create;
405
	}
406
	
407
	if (isset($syslogcfg)) {
408
		$separatelogfacilities = array('ntpd','racoon','openvpn');
409
		if($config['installedpackages']['package']) {
410
			foreach($config['installedpackages']['package'] as $package) {
411
				if($package['logging']) {
412
					$pkgfacilities[] = $package['logging']['facilityname'];
413
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
414
					$facilitylist = implode(',', $pkgfacilities);
415
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
416
					$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
417
				}
418
			}
419
		}
420
		$facilitylist = implode(',', array_unique($separatelogfacilities));
421
		/* write syslog.conf */		
422
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
423
		if (!$fd) {
424
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
425
			return 1;
426
		}
427
		$syslogconf .= "!ntpdate,!ntpd\n";
428
		if (!isset($syslogcfg['disablelocallogging'])) 
429
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
430
		$syslogconf .= "!ppp\n";
431
		if (!isset($syslogcfg['disablelocallogging'])) 
432
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ppp.log\n";
433
		$syslogconf .= "!pptp\n";
434
		if (!isset($syslogcfg['disablelocallogging'])) 
435
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pptp.log\n";
436
		$syslogconf .= "!pppoe\n";
437
		if (!isset($syslogcfg['disablelocallogging'])) 
438
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pppoe.log\n";
439
		$syslogconf .= "!l2tp\n";
440
		if (!isset($syslogcfg['disablelocallogging'])) 
441
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/l2tp.log\n";
442
		$syslogconf .= "!racoon\n";
443
		if (!isset($syslogcfg['disablelocallogging'])) 
444
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
445
		$syslogconf .= "!apinger\n";
446
		if (!isset($syslogcfg['disablelocallogging'])) 
447
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/slbd.log\n";
448
		if (isset($syslogcfg['vpn'])) {
449
			if($syslogcfg['remoteserver'])
450
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
451
			if($syslogcfg['remoteserver2'])
452
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver2']}\n";
453
			if($syslogcfg['remoteserver3'])
454
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
455
		}
456
		$syslogconf .= "!openvpn\n";
457
		if (!isset($syslogcfg['disablelocallogging'])) 
458
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
459
		if (isset($syslogcfg['vpn'])) {
460
			if($syslogcfg['remoteserver'])
461
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
462
			if($syslogcfg['remoteserver2'])
463
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
464
			if($syslogcfg['remoteserver3'])
465
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
466
		}
467
		$syslogconf .= "!-{$facilitylist}\n";
468
		if (!isset($syslogcfg['disablelocallogging'])) 
469
			$syslogconf .= <<<EOD
470
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
471
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
472
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
473
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
474
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
475
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
476
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
477
security.*										 {$log_directive}{$g['varlog_path']}/system.log
478
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
479
local1.*										 {$log_directive}{$g['varlog_path']}/relayd.log
480
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf
481
*.emerg											 *
482

    
483
EOD;
484
		if (isset($syslogcfg['filter'])) {
485
			if($syslogcfg['remoteserver'])
486
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
487
			if($syslogcfg['remoteserver2'])
488
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
489
			if($syslogcfg['remoteserver3'])
490
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
491

    
492
		}
493
		if (isset($syslogcfg['vpn'])) {
494
			if($syslogcfg['remoteserver'])
495
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
496
			if($syslogcfg['remoteserver2'])
497
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
498
			if($syslogcfg['remoteserver3'])
499
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
500
		}
501
		if (isset($syslogcfg['portalauth'])) {
502
			if($syslogcfg['remoteserver'])
503
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
504
			if($syslogcfg['remoteserver2'])
505
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
506
			if($syslogcfg['remoteserver3'])
507
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
508
		}
509
		if (isset($syslogcfg['dhcp'])) {
510
			if($syslogcfg['remoteserver'])
511
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
512
			if($syslogcfg['remoteserver2'])
513
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
514
			if($syslogcfg['remoteserver3'])
515
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
516
		}
517
		if (isset($syslogcfg['system'])) {
518
			if($syslogcfg['remoteserver'])
519
				$syslogconf .= <<<EOD
520
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
521
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
522
security.*										 @{$syslogcfg['remoteserver']}
523
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
524
*.emerg											 @{$syslogcfg['remoteserver']}
525

    
526
EOD;
527

    
528
		if (isset($syslogcfg['system'])) {
529
			if($syslogcfg['remoteserver2'])
530
				$syslogconf .= <<<EOD
531
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
532
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
533
security.*										 @{$syslogcfg['remoteserver2']}
534
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
535
*.emerg											 @{$syslogcfg['remoteserver2']}
536

    
537
EOD;
538

    
539
		if (isset($syslogcfg['system'])) {
540
			if($syslogcfg['remoteserver3'])
541
				$syslogconf .= <<<EOD
542
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
543
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
544
security.*										 @{$syslogcfg['remoteserver3']}
545
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
546
*.emerg											 @{$syslogcfg['remoteserver3']}
547

    
548
EOD;
549

    
550
}
551
		if (isset($syslogcfg['logall'])) {
552
			if($syslogcfg['remoteserver'])
553
				$syslogconf .= <<<EOD
554
*.*								@{$syslogcfg['remoteserver']}
555

    
556
EOD;
557

    
558
}
559
			if($syslogcfg['remoteserver2'])
560
				$syslogconf .= <<<EOD
561
*.*								@{$syslogcfg['remoteserver2']}
562

    
563
EOD;
564

    
565
}
566
			if($syslogcfg['remoteserver3'])
567
				$syslogconf .= <<<EOD
568
*.*								@{$syslogcfg['remoteserver3']}
569

    
570
EOD;
571

    
572
}
573
		fwrite($fd, $syslogconf);
574
		fclose($fd);
575
		// Are we logging to a least one remote server ?
576
		if(strpos($syslogconf, "@") != false)
577
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
578
		else
579
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
580

    
581
	} else {
582
		$retval = mwexec("/usr/sbin/syslogd -c");
583
	}
584

    
585
	if ($g['booting'])
586
		echo "done.\n";
587

    
588
	return $retval;
589
}
590

    
591
function system_pccard_start() {
592
	global $config, $g;
593
	if(isset($config['system']['developerspew'])) {
594
		$mt = microtime();
595
		echo "system_pccard_start() being called $mt\n";
596
	}
597

    
598
	if ($g['booting'])
599
		echo "Initializing PCMCIA...";
600

    
601
	/* kill any running pccardd */
602
	killbypid("{$g['varrun_path']}/pccardd.pid");
603

    
604
	/* fire up pccardd */
605
	$res = mwexec("/usr/sbin/pccardd -z -f {$g['etc_path']}/pccard.conf");
606

    
607
	if ($g['booting']) {
608
		if ($res == 0)
609
			echo "done.\n";
610
		else
611
			echo "failed!\n";
612
	}
613

    
614
	return $res;
615
}
616

    
617

    
618
function system_webgui_start() {
619
	global $config, $g;
620

    
621
	if ($g['booting'])
622
		echo "Starting webConfigurator...";
623

    
624
	/* kill any running lighttpd */
625
	killbypid("{$g['varrun_path']}/lighty-webConfigurator.pid");
626

    
627
	sleep(1);
628

    
629
	chdir($g['www_path']);
630

    
631
	/* defaults */
632
	$portarg = "80";
633
	$crt = "";
634
	$key = "";
635
	$ca = "";
636

    
637
	/* non-standard port? */
638
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
639
		$portarg = "{$config['system']['webgui']['port']}";
640

    
641
	if ($config['system']['webgui']['protocol'] == "https") {
642
		// Ensure that we have a webConfigurator CERT
643
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
644
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
645
			if (!is_array($config['system']['ca']))
646
				$config['system']['ca'] = array();
647
			$a_ca =& $config['system']['ca'];
648
			if (!is_array($config['system']['cert']))
649
				$config['system']['cert'] = array();
650
			$a_cert =& $config['system']['cert'];
651
			echo "Creating SSL Certificate... ";
652
			$cert = array();
653
			$cert['refid'] = uniqid();
654
			$cert['name'] = "webConfigurator default";
655
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
656
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
657
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
658
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
659
			unlink("{$g['tmp_path']}/ssl.key");
660
			unlink("{$g['tmp_path']}/ssl.crt");
661
			cert_import($cert, $crt, $key);
662
			$a_cert[] = $cert;
663
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
664
			write_config("Importing HTTPS certificate");
665
			if(!$config['system']['webgui']['port'])
666
				$portarg = "443";
667
			$ca = ca_chain($cert);
668
		} else {
669
			$crt = base64_decode($cert['crt']);
670
			$key = base64_decode($cert['prv']);
671
			if(!$config['system']['webgui']['port'])
672
				$portarg = "443";
673
			$ca = ca_chain($cert);
674
		}
675
	}
676

    
677
	/* generate lighttpd configuration */
678
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
679
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
680

    
681
	/* attempt to start lighthttpd */
682
	$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-webConfigurator.conf");
683

    
684
	/* fetch page to preload apc cache */
685
	$proto = "http";
686
	if ($config['system']['webgui']['protocol'])
687
		$proto = $config['system']['webgui']['protocol'];
688
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
689

    
690
	if ($g['booting']) {
691
		if ($res == 0)
692
			echo "done.\n";
693
		else
694
			echo "failed!\n";
695
	}
696

    
697
	return $res;
698
}
699

    
700
function system_generate_lighty_config($filename,
701
	$cert,
702
	$key,
703
	$ca,
704
	$pid_file,
705
	$port = 80,
706
	$document_root = "/usr/local/www/",
707
	$cert_location = "cert.pem",
708
	$ca_location = "ca.pem",
709
	$max_procs = 2,
710
	$max_requests = "1",
711
	$fast_cgi_enable = true,
712
	$captive_portal = false) {
713

    
714
	global $config, $g;
715

    
716
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
717
		mkdir("{$g['tmp_path']}/lighttpdcompress");
718

    
719
	if(isset($config['system']['developerspew'])) {
720
		$mt = microtime();
721
		echo "system_generate_lighty_config() being called $mt\n";
722
	}
723

    
724
	if($captive_portal == true)  {
725
		$captiveportal = ",\"mod_rewrite\"";
726
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
727
		$captive_portal_module = "\"mod_accesslog\", ";
728
		$maxprocperip = $config['captiveportal']['maxprocperip'];
729
		if(!$maxprocperip and $maxprocperip > 0)
730
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
731
		else
732
			$captive_portal_mod_evasive = "";
733
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
734
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
735
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
736
		$server_max_request_size = "server.max-request-size    = 384";
737
	} else {
738
		$captiveportal = "";
739
		$captive_portal_rewrite = "";
740
		$captive_portal_module = "";
741
		$captive_portal_mod_evasive = "";
742
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
743
		$server_max_request_size = "server.max-request-size    = 2097152";
744
	}
745
	
746
	if($port <> "")
747
		$lighty_port = $port;
748
	else
749
		$lighty_port = "80";
750

    
751
	$memory = get_memory();
752
	$avail = $memory[0];
753

    
754
	if($avail > 0 and $avail < 65) {
755
		$fast_cgi_enable = false;
756
	}
757

    
758
	if($avail > 65 and $avail < 98) {
759
		$max_procs = 1;
760
	}
761

    
762
	if($avail > 97 and $avail < 128) {
763
		$max_procs = 2;
764
	}
765

    
766
	if($avail > 127 and $avail < 256) {
767
		$max_procs = 3;
768
	}
769

    
770
	if($avail > 255 and $avail < 384) {
771
		$max_procs = 4;
772
	}
773

    
774
	if($avail > 383) {
775
		$max_procs = 5;
776
	}
777

    
778
	if($captive_portal == true)  {	
779
		$bin_environment =  <<<EOC
780
        "bin-environment" => (
781
           "PHP_FCGI_CHILDREN" => "$max_procs",
782
           "PHP_FCGI_MAX_REQUESTS" => "500"
783
        ), 
784
EOC;
785

    
786
	} else if ($avail > 0 and $avail < 128) {
787
		$bin_environment = <<<EOC
788
		"bin-environment" => (
789
			"PHP_FCGI_CHILDREN" => "$max_procs",
790
			"PHP_FCGI_MAX_REQUESTS" => "2",
791
	),
792

    
793
EOC;
794
	} else
795
		$bin_environment =  <<<EOC
796
        "bin-environment" => (
797
           "PHP_FCGI_CHILDREN" => "$max_procs",
798
           "PHP_FCGI_MAX_REQUESTS" => "500"
799
        ), 
800
EOC;
801

    
802
	if($fast_cgi_enable == true) {
803
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
804
		$cgi_config = "";
805
		$fastcgi_config = <<<EOD
806
#### fastcgi module
807
## read fastcgi.txt for more info
808
fastcgi.server = ( ".php" =>
809
	( "localhost" =>
810
		(
811
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
812
			"min-procs" => 0,
813
			"max-procs" => {$max_procs},
814
			{$bin_environment}			
815
			"bin-path" => "/usr/local/bin/php"
816
		)
817
	)
818
)
819

    
820
#### CGI module
821
cgi.assign                 = ( ".cgi" => "" )
822

    
823
EOD;
824
	} else {
825
		$fastcgi_config = "";
826
		$module = "\"mod_cgi\"";
827
		$cgi_config = <<<EOD
828
#### CGI module
829
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
830
                               ".cgi" => "" )
831

    
832
EOD;
833
	}
834

    
835
	$lighty_config = "";
836
	$lighty_config .= <<<EOD
837
#
838
# lighttpd configuration file
839
#
840
# use a it as base for lighttpd 1.0.0 and above
841
#
842
############ Options you really have to take care of ####################
843

    
844
## FreeBSD!
845
server.event-handler	= "freebsd-kqueue"
846
server.network-backend 	= "writev"
847

    
848
## modules to load
849
server.modules              =   (
850
									{$captive_portal_module}
851
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
852
									{$module}{$captiveportal}
853
								)
854

    
855
## Unused modules
856
#                               "mod_setenv",
857
#                               "mod_rewrite",
858
#                               "mod_ssi",
859
#                               "mod_usertrack",
860
#                               "mod_expire",
861
#                               "mod_secdownload",
862
#                               "mod_rrdtool",
863
#                               "mod_auth",
864
#                               "mod_status",
865
#                               "mod_alias",
866
#                               "mod_proxy",
867
#                               "mod_simple_vhost",
868
#                               "mod_evhost",
869
#                               "mod_userdir",
870
#                               "mod_cgi",
871

    
872
server.max-keep-alive-requests = 15
873
server.max-keep-alive-idle = 30
874

    
875
## a static document-root, for virtual-hosting take look at the
876
## server.virtual-* options
877
server.document-root        = "{$document_root}"
878
{$captive_portal_rewrite}
879

    
880
# Maximum idle time with nothing being written (php downloading)
881
server.max-write-idle = 999
882

    
883
## where to send error-messages to
884
server.errorlog             = "/var/log/lighttpd.error.log"
885

    
886
# files to check for if .../ is requested
887
server.indexfiles           = ( "index.php", "index.html",
888
                                "index.htm", "default.htm" )
889

    
890
# mimetype mapping
891
mimetype.assign             = (
892
  ".pdf"          =>      "application/pdf",
893
  ".sig"          =>      "application/pgp-signature",
894
  ".spl"          =>      "application/futuresplash",
895
  ".class"        =>      "application/octet-stream",
896
  ".ps"           =>      "application/postscript",
897
  ".torrent"      =>      "application/x-bittorrent",
898
  ".dvi"          =>      "application/x-dvi",
899
  ".gz"           =>      "application/x-gzip",
900
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
901
  ".swf"          =>      "application/x-shockwave-flash",
902
  ".tar.gz"       =>      "application/x-tgz",
903
  ".tgz"          =>      "application/x-tgz",
904
  ".tar"          =>      "application/x-tar",
905
  ".zip"          =>      "application/zip",
906
  ".mp3"          =>      "audio/mpeg",
907
  ".m3u"          =>      "audio/x-mpegurl",
908
  ".wma"          =>      "audio/x-ms-wma",
909
  ".wax"          =>      "audio/x-ms-wax",
910
  ".ogg"          =>      "audio/x-wav",
911
  ".wav"          =>      "audio/x-wav",
912
  ".gif"          =>      "image/gif",
913
  ".jpg"          =>      "image/jpeg",
914
  ".jpeg"         =>      "image/jpeg",
915
  ".png"          =>      "image/png",
916
  ".xbm"          =>      "image/x-xbitmap",
917
  ".xpm"          =>      "image/x-xpixmap",
918
  ".xwd"          =>      "image/x-xwindowdump",
919
  ".css"          =>      "text/css",
920
  ".html"         =>      "text/html",
921
  ".htm"          =>      "text/html",
922
  ".js"           =>      "text/javascript",
923
  ".asc"          =>      "text/plain",
924
  ".c"            =>      "text/plain",
925
  ".conf"         =>      "text/plain",
926
  ".text"         =>      "text/plain",
927
  ".txt"          =>      "text/plain",
928
  ".dtd"          =>      "text/xml",
929
  ".xml"          =>      "text/xml",
930
  ".mpeg"         =>      "video/mpeg",
931
  ".mpg"          =>      "video/mpeg",
932
  ".mov"          =>      "video/quicktime",
933
  ".qt"           =>      "video/quicktime",
934
  ".avi"          =>      "video/x-msvideo",
935
  ".asf"          =>      "video/x-ms-asf",
936
  ".asx"          =>      "video/x-ms-asf",
937
  ".wmv"          =>      "video/x-ms-wmv",
938
  ".bz2"          =>      "application/x-bzip",
939
  ".tbz"          =>      "application/x-bzip-compressed-tar",
940
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
941
 )
942

    
943
# Use the "Content-Type" extended attribute to obtain mime type if possible
944
#mimetypes.use-xattr        = "enable"
945

    
946
#### accesslog module
947
#accesslog.filename          = "/dev/null"
948

    
949
## deny access the file-extensions
950
#
951
# ~    is for backupfiles from vi, emacs, joe, ...
952
# .inc is often used for code includes which should in general not be part
953
#      of the document-root
954
url.access-deny             = ( "~", ".inc" )
955

    
956

    
957
######### Options that are good to be but not neccesary to be changed #######
958

    
959
## bind to port (default: 80)
960
server.port                = {$lighty_port}
961

    
962
## error-handler for status 404
963
#server.error-handler-404   = "/error-handler.html"
964
#server.error-handler-404   = "/error-handler.php"
965

    
966
## to help the rc.scripts
967
server.pid-file            = "/var/run/{$pid_file}"
968

    
969
## virtual directory listings
970
server.dir-listing         = "disable"
971

    
972
## enable debugging
973
debug.log-request-header   = "disable"
974
debug.log-response-header  = "disable"
975
debug.log-request-handling = "disable"
976
debug.log-file-not-found   = "disable"
977

    
978
# gzip compression
979
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
980
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
981

    
982
{$server_upload_dirs}
983

    
984
{$server_max_request_size}
985

    
986
{$fastcgi_config}
987

    
988
{$cgi_config}
989

    
990
{$captive_portal_mod_evasive}
991

    
992
expire.url = (
993
				"" => "access 50 hours",	
994
        )
995

    
996
EOD;
997

    
998
	$cert = str_replace("\r", "", $cert);
999
	$key = str_replace("\r", "", $key);
1000
	$ca = str_replace("\r", "", $ca);
1001

    
1002
	$cert = str_replace("\n\n", "\n", $cert);
1003
	$key = str_replace("\n\n", "\n", $key);
1004
	$ca = str_replace("\n\n", "\n", $ca);
1005

    
1006
	if($cert <> "" and $key <> "") {
1007
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1008
		if (!$fd) {
1009
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1010
			return 1;
1011
		}
1012
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1013
		fwrite($fd, $cert);
1014
		fwrite($fd, "\n");
1015
		fwrite($fd, $key);
1016
		fclose($fd);
1017
		if($ca <> "") {
1018
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1019
			if (!$fd) {
1020
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1021
				return 1;
1022
			}
1023
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1024
			fwrite($fd, $ca);
1025
			fclose($fd);
1026
		}
1027
		$lighty_config .= "\n";
1028
		$lighty_config .= "## ssl configuration\n";
1029
		$lighty_config .= "ssl.engine = \"enable\"\n";
1030
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1031
		if($ca <> "")
1032
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1033
	}
1034

    
1035
	// Add HTTP to HTTPS redirect	
1036
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1037
		if($lighty_port != "443") 
1038
			$redirectport = ":{$lighty_port}";
1039
		$lighty_config .= <<<EOD
1040
\$SERVER["socket"] == ":80" {
1041
	\$HTTP["host"] =~ "(.*)" {
1042
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1043
	}
1044
}
1045
EOD;
1046
	}
1047

    
1048
	$fd = fopen("{$filename}", "w");
1049
	if (!$fd) {
1050
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1051
		return 1;
1052
	}
1053
	fwrite($fd, $lighty_config);
1054
	fclose($fd);
1055

    
1056
	return 0;
1057

    
1058
}
1059

    
1060
function system_timezone_configure() {
1061
	global $config, $g;
1062
	if(isset($config['system']['developerspew'])) {
1063
		$mt = microtime();
1064
		echo "system_timezone_configure() being called $mt\n";
1065
	}
1066

    
1067
	$syscfg = $config['system'];
1068

    
1069
	if ($g['booting'])
1070
		echo "Setting timezone...";
1071

    
1072
	/* extract appropriate timezone file */
1073
	$timezone = $syscfg['timezone'];
1074
	if (!$timezone)
1075
		$timezone = "Etc/UTC";
1076

    
1077
	conf_mount_rw();
1078

    
1079
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1080
		escapeshellarg($timezone) . " > /etc/localtime");
1081

    
1082
	mwexec("sync");
1083
	conf_mount_ro();
1084

    
1085
	if ($g['booting'])
1086
		echo "done.\n";
1087
}
1088

    
1089
function system_ntp_configure() {
1090
	global $config, $g;
1091

    
1092
	$syscfg = $config['system'];
1093

    
1094
	/* open configuration for wrting or bail */
1095
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1096
	if(!$fd) {
1097
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1098
		return;
1099
	}
1100

    
1101
	fwrite($fd, "# \n");
1102
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1103
	fwrite($fd, "# \n\n");
1104

    
1105
	/* foreach through servers and write out to ntpd.conf */
1106
	foreach (explode(' ', $syscfg['timeservers']) as $ts)
1107
		fwrite($fd, "servers {$ts}\n");
1108

    
1109
	/* Setup listener(s) if the user has configured one */
1110
        if ($config['installedpackages']['openntpd']) {
1111
    		/* server config is in coregui1 */
1112
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1113
		if ($xmlsettings['enable'] == 'on') {
1114
			$ifaces = explode(',', $xmlsettings['interface']);
1115
			$ifaces = array_map('get_real_interface', $ifaces);
1116
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1117
			$ips = array_map('find_interface_ip', $ifaces);
1118
			foreach ($ips as $ip) {
1119
				if (is_ipaddr($ip))
1120
					fwrite($fd, "listen on $ip\n");
1121
			}
1122
		}
1123
	}
1124

    
1125
	fwrite($fd, "\n");
1126

    
1127
	/* slurp! */
1128
	fclose($fd);
1129

    
1130
	/* if openntpd is running, kill it */
1131
	while(is_process_running("ntpd")) {
1132
		mwexec("/usr/bin/killall ntpd", true);
1133
	}
1134

    
1135
	/* if /var/empty does not exist, create it */
1136
	if(!is_dir("/var/empty"))
1137
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1138

    
1139
	if($g['booting'])
1140
		return;
1141
	
1142
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1143
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1144
	
1145
	// Note that we are starting up
1146
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1147

    
1148
}
1149

    
1150
function sync_system_time() {
1151
	global $config, $g;
1152

    
1153
	$syscfg = $config['system'];
1154

    
1155
	if ($g['booting'])
1156
		echo "Syncing system time before startup...";
1157

    
1158
	/* foreach through servers and write out to ntpd.conf */
1159
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1160
		mwexec("/usr/sbin/ntpdate -s $ts");
1161
	}
1162
	
1163
	if ($g['booting'])
1164
		echo "done.\n";
1165
	
1166
}
1167

    
1168
function system_halt() {
1169
	global $g;
1170

    
1171
	system_reboot_cleanup();
1172

    
1173
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1174
}
1175

    
1176
function system_reboot() {
1177
	global $g;
1178

    
1179
	system_reboot_cleanup();
1180

    
1181
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1182
}
1183

    
1184
function system_reboot_sync() {
1185
	global $g;
1186

    
1187
	system_reboot_cleanup();
1188

    
1189
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1190
}
1191

    
1192
function system_reboot_cleanup() {
1193
	mwexec("/usr/local/bin/beep.sh stop");
1194
	require_once("captiveportal.inc");
1195
	captiveportal_radius_stop_all();
1196
	require_once("voucher.inc");
1197
	voucher_save_db_to_config();
1198
}
1199

    
1200
function system_do_shell_commands($early = 0) {
1201
	global $config, $g;
1202
	if(isset($config['system']['developerspew'])) {
1203
		$mt = microtime();
1204
		echo "system_do_shell_commands() being called $mt\n";
1205
	}
1206

    
1207
	if ($early)
1208
		$cmdn = "earlyshellcmd";
1209
	else
1210
		$cmdn = "shellcmd";
1211

    
1212
	if (is_array($config['system'][$cmdn])) {
1213

    
1214
		/* *cmd is an array, loop through */
1215
		foreach ($config['system'][$cmdn] as $cmd) {
1216
			exec($cmd);
1217
		}
1218

    
1219
	} elseif($config['system'][$cmdn] <> "") {
1220

    
1221
		/* execute single item */
1222
		exec($config['system'][$cmdn]);
1223

    
1224
	}
1225
}
1226

    
1227
function system_console_configure() {
1228
	global $config, $g;
1229
	if(isset($config['system']['developerspew'])) {
1230
		$mt = microtime();
1231
		echo "system_console_configure() being called $mt\n";
1232
	}
1233

    
1234
	if (isset($config['system']['disableconsolemenu'])) {
1235
		touch("{$g['varetc_path']}/disableconsole");
1236
	} else {
1237
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1238
	}
1239
}
1240

    
1241
function system_dmesg_save() {
1242
	global $g;
1243
	if(isset($config['system']['developerspew'])) {
1244
		$mt = microtime();
1245
		echo "system_dmesg_save() being called $mt\n";
1246
	}
1247

    
1248
	$dmesg = "";
1249
	exec("/sbin/dmesg", $dmesg);
1250

    
1251
	/* find last copyright line (output from previous boots may be present) */
1252
	$lastcpline = 0;
1253

    
1254
	for ($i = 0; $i < count($dmesg); $i++) {
1255
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1256
			$lastcpline = $i;
1257
	}
1258

    
1259
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1260
	if (!$fd) {
1261
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1262
		return 1;
1263
	}
1264

    
1265
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1266
		fwrite($fd, $dmesg[$i] . "\n");
1267

    
1268
	fclose($fd);
1269

    
1270
	return 0;
1271
}
1272

    
1273
function system_set_harddisk_standby() {
1274
	global $g, $config;
1275
	if(isset($config['system']['developerspew'])) {
1276
		$mt = microtime();
1277
		echo "system_set_harddisk_standby() being called $mt\n";
1278
	}
1279

    
1280
	if (isset($config['system']['harddiskstandby'])) {
1281
		if ($g['booting']) {
1282
			echo 'Setting hard disk standby... ';
1283
		}
1284

    
1285
		$standby = $config['system']['harddiskstandby'];
1286
		// Check for a numeric value
1287
		if (is_numeric($standby)) {
1288
			// Sync the disk(s)
1289
			mwexec('/bin/sync');
1290
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1291
				// Reinitialize ATA-drives
1292
				mwexec('/usr/local/sbin/atareinit');
1293
				if ($g['booting']) {
1294
					echo "done.\n";
1295
				}
1296
			} else if ($g['booting']) {
1297
				echo "failed!\n";
1298
			}
1299
		} else if ($g['booting']) {
1300
			echo "failed!\n";
1301
		}
1302
	}
1303
}
1304

    
1305
function system_setup_sysctl() {
1306
	global $config;
1307
	if(isset($config['system']['developerspew'])) {
1308
		$mt = microtime();
1309
		echo "system_setup_sysctl() being called $mt\n";
1310
	}
1311

    
1312
	activate_sysctls();	
1313

    
1314
	if (isset($config['system']['sharednet'])) {
1315
		system_disable_arp_wrong_if();
1316
	}
1317
}
1318

    
1319
function system_disable_arp_wrong_if() {
1320
	global $config;
1321
	if(isset($config['system']['developerspew'])) {
1322
		$mt = microtime();
1323
		echo "system_disable_arp_wrong_if() being called $mt\n";
1324
	}
1325
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1326
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1327
}
1328

    
1329
function system_enable_arp_wrong_if() {
1330
	global $config;
1331
	if(isset($config['system']['developerspew'])) {
1332
		$mt = microtime();
1333
		echo "system_enable_arp_wrong_if() being called $mt\n";
1334
	}
1335
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1336
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1337
}
1338

    
1339
function enable_watchdog() {
1340
	global $config;
1341
	return;
1342
	$install_watchdog = false;
1343
	$supported_watchdogs = array("Geode");
1344
	$file = file_get_contents("/var/log/dmesg.boot");
1345
	foreach($supported_watchdogs as $sd) {
1346
		if(stristr($file, "Geode")) {
1347
			$install_watchdog = true;
1348
		}
1349
	}
1350
	if($install_watchdog == true) {
1351
		if(is_process_running("watchdogd"))
1352
			mwexec("/usr/bin/killall watchdogd", true);
1353
		exec("/usr/sbin/watchdogd");
1354
	}
1355
}
1356

    
1357
function system_check_reset_button() {
1358
	global $g;
1359
	if($g['platform'] != "nanobsd")
1360
		return 0;
1361

    
1362
	$specplatform = system_identify_specific_platform();
1363

    
1364
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1365
		return 0;
1366

    
1367
	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");
1368

    
1369
	if ($retval == 99) {
1370
		/* user has pressed reset button for 2 seconds - 
1371
		   reset to factory defaults */
1372
		echo <<<EOD
1373

    
1374
***********************************************************************
1375
* Reset button pressed - resetting configuration to factory defaults. *
1376
* The system will reboot after this completes.                        *
1377
***********************************************************************
1378

    
1379

    
1380
EOD;
1381
		
1382
		reset_factory_defaults();
1383
		system_reboot_sync();
1384
		exit(0);
1385
	}
1386

    
1387
	return 0;
1388
}
1389

    
1390
/* attempt to identify the specific platform (for embedded systems)
1391
   Returns an array with two elements:
1392
	name => platform string (e.g. 'wrap', 'alix' etc.)
1393
	descr => human-readable description (e.g. "PC Engines WRAP")
1394
*/
1395
function system_identify_specific_platform() {
1396
	global $g;
1397
	
1398
	if ($g['platform'] == 'generic-pc')
1399
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1400
	
1401
	if ($g['platform'] == 'generic-pc-cdrom')
1402
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1403
	
1404
	/* the rest of the code only deals with 'embedded' platforms */
1405
	if ($g['platform'] != 'nanobsd')
1406
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1407
	
1408
	$dmesg = system_get_dmesg_boot();
1409
	
1410
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1411
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1412
	
1413
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1414
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1415

    
1416
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1417
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1418
	
1419
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1420
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1421
		
1422
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1423
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1424
	
1425
	/* unknown embedded platform */
1426
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1427
}
1428

    
1429
function system_get_dmesg_boot() {
1430
	global $g;
1431
		
1432
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1433
}
1434

    
1435
?>
(39-39/50)