Project

General

Profile

Download (32.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	services.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
/* include all configuration functions */
33
require_once("functions.inc");
34

    
35
function load_balancer_use_sticky() {
36
	global $config, $g;
37
	if (isset ($config['system']['lb_use_sticky']))
38
		touch("/var/etc/use_pf_pool__stickyaddr");
39
	else
40
		unlink_if_exists("/var/etc/use_pf_pool__stickyaddr");
41
}
42

    
43
function services_dhcpd_configure() {
44
	global $config, $g;
45
	if(isset($config['system']['developerspew'])) {
46
		$mt = microtime();
47
		echo "services_dhcpd_configure($if) being called $mt\n";
48
	}
49

    
50
	/* if OLSRD is enabled, allow WAN to house DHCP. */
51
	if($config['installedpackages']['olsrd'])
52
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd)
53
				if($olsrd['enable'])
54
					$is_olsr_enabled = true;
55

    
56
	/* configure DHCPD chroot */
57
	$fd = fopen("/tmp/dhcpd.sh","w");
58
	$status = `mount | grep "{$g['dhcpd_chroot_path']}/dev"`;
59
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}\n");
60
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
61
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
62
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
63
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
64
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
65
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
66
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/run\n");
67
	fwrite($fd, "chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
68
	fwrite($fd, "cp /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
69
	fwrite($fd, "cp /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
70
	fwrite($fd, "chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
71
	if(!trim($status))
72
		fwrite($fd, "mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
73
	fclose($fd);
74
	mwexec("/bin/sh /tmp/dhcpd.sh");
75

    
76
	/* kill any running dhcpd */
77
	if(is_process_running("dhcpd"))
78
		mwexec("killall dhcpd");
79

    
80
	$syscfg = $config['system'];
81
	$dhcpdcfg = $config['dhcpd'];
82

    
83
	/* DHCP enabled on any interfaces? */
84
	$dhcpdenable = false;
85
	if(is_array($dhcpdcfg))
86
		foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
87
			if($dhcpif == "lan") 
88
				if(!$config['interfaces']['lan']) 	
89
					continue;
90
			if (isset($dhcpifconf['enable']) &&
91
				(($dhcpif == "lan") ||
92
				(isset($config['interfaces'][$dhcpif]['enable']) &&
93
				$config['interfaces'][$dhcpif]['if'] && (!link_int_to_bridge_interface($dhcpif)))))
94
				$dhcpdenable = true;
95
			if (isset($dhcpifconf['enable']) &&
96
				(($dhcpif == "wan") || (isset($config['interfaces'][$dhcpif]['enable']) &&
97
				$config['interfaces'][$dhcpif]['if'] && (!link_int_to_bridge_interface($dhcpif)))))
98
				$dhcpdenable = true;
99
		}
100

    
101
	if (!$dhcpdenable)
102
		return 0;
103

    
104
	if ($g['booting'])
105
		echo "Starting DHCP service...";
106
	else
107
		sleep(1);
108

    
109
	/* write dhcpd.conf */
110
	$fd = fopen("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", "w");
111
	if (!$fd) {
112
		printf("Error: cannot open dhcpd.conf in services_dhcpd_configure().\n");
113
		return 1;
114
	}
115

    
116

    
117

    
118
	$dhcpdconf = <<<EOD
119
	
120
option domain-name "{$syscfg['domain']}";
121
option ldap-server code 95 = text;
122
option domain-search-list code 119 = text;
123
default-lease-time 7200;
124
max-lease-time 86400;
125
log-facility local7;
126
ddns-update-style none;
127
one-lease-per-client true;
128
deny duplicates;
129
ping-check true;
130

    
131
EOD;
132

    
133
	if(isset($dhcpifconf['alwaysbroadcast'])) 
134
		$dhcpdconf .= "always-broadcast on\n";
135

    
136
	$dhcpdifs = array();
137

    
138
	/*    loop through and deterimine if we need to setup
139
	 *    failover peer "bleh" entries
140
	 */
141
	$dhcpnum = 0;
142
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
143

    
144
		if(!isset($dhcpifconf['disableauthoritative']))
145
			$dhcpdconf .= "authoritative;\n";
146

    
147
		if($dhcpifconf['failover_peerip'] <> "") {
148
			/*
149
			 *    yep, failover peer is defined.
150
			 *    does it match up to a defined vip?
151
			 */
152
			$skew = 110;
153
			$a_vip = &$config['virtualip']['vip'];
154
			if(is_array($a_vip)) {
155
				foreach ($a_vip as $vipent) {
156
					$int = guess_interface_from_ip($dhcpifconf['failover_peerip']);
157
					$intip = find_interface_ip($int);
158
					$real_dhcpif = convert_friendly_interface_to_real_interface_name($dhcpif);
159
					if($int == $real_dhcpif) {
160
						/* this is the interface! */
161
						if($vipent['advskew'] < "20")
162
							$skew = 0;
163
					}
164
				}
165
			} else {
166
				log_error("Warning!  DHCP Failover setup and no CARP virtual IP's defined!");
167
			}
168
			if($skew > 10) {
169
				$type = "secondary";
170
				$dhcpdconf_pri  = "mclt 600;\n";
171
				$my_port = "520";
172
				$peer_port = "519";
173
			} else {
174
				$my_port = "519";
175
				$peer_port = "520";
176
				$type = "primary";
177
				$dhcpdconf_pri  = "split 128;\n";
178
				$dhcpdconf_pri .= "  mclt 600;\n";
179
			}
180
			$dhcpdconf .= <<<EOPP
181
failover peer "dhcp{$dhcpnum}" {
182
  {$type};
183
  address {$intip};
184
  port {$my_port};
185
  peer address {$dhcpifconf['failover_peerip']};
186
  peer port {$peer_port};
187
  max-response-delay 10;
188
  max-unacked-updates 10;
189
  {$dhcpdconf_pri}
190
  load balance max seconds 3;
191
}
192

    
193
EOPP;
194
		$dhcpnum++;
195
		}
196
	}
197

    
198
	$dhcpnum = 0;
199

    
200
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
201

    
202
		$ifcfg = $config['interfaces'][$dhcpif];
203

    
204
		if (!isset($dhcpifconf['enable']) ||
205
			($ifcfg['ipaddr'] == "dhcp") ||
206
			(($dhcpif != "lan") &&
207
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || 
208
			link_int_to_bridge_interface($dhcpif))))
209
			continue;
210

    
211
		if($dhcpif == "lan" && link_int_to_bridge_interface($dhcpif))
212
			log_error("NOTE: DHCP Server on LAN is enabled.");
213

    
214
		$subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']);
215
		$subnetmask = gen_subnet_mask($ifcfg['subnet']);
216

    
217
		if($is_olsr_enabled == true)
218
			if($dhcpifconf['netmask'])
219
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
220

    
221
		$dnscfg = "";
222

    
223
		if ($dhcpifconf['domain']) {
224
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
225
		}
226
		
227
    if($dhcpifconf['domainsearchlist'] <> "") {
228
			$dnscfg .= "	option domain-search-list \"{$dhcpifconf['domainsearchlist']}\";\n";
229
    }
230

    
231
		if (isset($dhcpifconf['ddnsupdate'])) {
232
			if($dhcpifconf['ddnsdomain'] <> "") {
233
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
234
			}
235
			$dnscfg .= "	ddns-update-style interim;\n";
236
		}
237

    
238
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
239
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
240
		} else if (isset($config['dnsmasq']['enable'])) {
241
			$dnscfg .= "	option domain-name-servers " . $ifcfg['ipaddr'] . ";";
242
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
243
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
244
		}
245

    
246
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
247
		$dhcpdconf .= "	pool {\n";
248

    
249
		/* is failover dns setup? */
250
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
251
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
252
			if($dhcpifconf['dnsserver'][1] <> "")
253
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
254
			$dhcpdconf .= ";\n";
255
		}
256

    
257
		if($dhcpifconf['failover_peerip'] <> "")
258
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
259

    
260
		if (isset($dhcpifconf['denyunknown']))
261
		   $dhcpdconf .= "		deny unknown clients;\n";
262

    
263
		if ($dhcpifconf['gateway'])
264
			$routers = $dhcpifconf['gateway'];
265
		else
266
			$routers = $ifcfg['ipaddr'];
267

    
268
		if($dhcpifconf['failover_peerip'] <> "") {
269
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
270
			$dhcpnum++;
271
		}
272

    
273
		$dhcpdconf .= <<<EOD
274
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
275
	}
276
	option routers {$routers};
277
$dnscfg
278

    
279
EOD;
280
    
281
    if ($dhcpifconf['defaultleasetime'])
282
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
283
		if ($dhcpifconf['maxleasetime'])
284
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
285

    
286
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
287
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
288
			$dhcpdconf .= "	option netbios-node-type 8;\n";
289
		}
290

    
291
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0])
292
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
293

    
294
		if ($dhcpifconf['tftp'] <> "")
295
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
296

    
297
    if ($dhcpifconf['ldap'] <> "")
298
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
299

    
300
		if(isset($dhcpifconf['netboot'])) {
301
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
302
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
303
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
304
			}
305
			if ($dhcpifconf['rootpath'] <> "") {
306
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
307
      }
308
		}
309
		
310
		$dhcpdconf .= <<<EOD
311
}
312

    
313
EOD;
314

    
315
		/* add static mappings */
316
		if (is_array($dhcpifconf['staticmap'])) {
317

    
318
			$i = 0;
319
			foreach ($dhcpifconf['staticmap'] as $sm) {
320
				$dhcpdconf .= <<<EOD
321
host s_{$dhcpif}_{$i} {
322
	hardware ethernet {$sm['mac']};
323

    
324
EOD;
325
				if ($sm['ipaddr'])
326
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
327

    
328
				if ($sm['hostname'])
329
					$dhcpdconf .= "	option host-name {$sm['hostname']};\n";
330

    
331
				$dhcpdconf .= "}\n";
332
				$i++;
333
			}
334
		}
335

    
336
		$dhcpdifs[] = $ifcfg['if'];
337
	}
338

    
339
	fwrite($fd, $dhcpdconf);
340
	fclose($fd);
341

    
342
	/* create an empty leases database */
343
	touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
344

    
345
	/* fire up dhcpd in a chroot */
346
	mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf {$g['dhcpd_chroot_path']}/etc/dhcpd.conf " .
347
		join(" ", $dhcpdifs));
348

    
349
	if ($g['booting']) {
350
		print "done.\n";
351
	}
352

    
353
	return 0;
354
}
355

    
356
function interfaces_staticarp_configure($if) {
357
	global $config, $g;
358
	if(isset($config['system']['developerspew'])) {
359
		$mt = microtime();
360
		echo "interfaces_staticarp_configure($if) being called $mt\n";
361
	}
362

    
363
        $ifcfg = $config['interfaces'][$if];
364

    
365
        /* Enable staticarp, if enabled */
366
        if(isset($config['dhcpd'][$if]['staticarp'])) {
367
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
368
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
369
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
370

    
371
                        foreach ($config['dhcpd'][$if]['staticmap'] as $arpent) {
372
                                mwexec("/usr/sbin/arp -s " . escapeshellarg($arpent['ipaddr']) . " " . escapeshellarg($arpent['mac']));
373

    
374
                        }
375

    
376
                }
377
        } else {
378
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
379
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
380
        }
381

    
382
        return 0;
383
}
384

    
385
function services_dhcrelay_configure() {
386
	global $config, $g;
387
	if(isset($config['system']['developerspew'])) {
388
		$mt = microtime();
389
		echo "services_dhcrelay_configure() being called $mt\n";
390
	}
391

    
392
	/* kill any running dhcrelay */
393
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
394

    
395
	$dhcrelaycfg = $config['dhcrelay'];
396

    
397
	/* DHCPRelay enabled on any interfaces? */
398
	$dhcrelayenable = false;
399
	if(is_array($dhcrelaycfg)) {
400
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
401
			if (isset($dhcrelayifconf['enable']) &&
402
				(($dhcrelayif == "lan") ||
403
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
404
				$config['interfaces'][$dhcrelayif]['if'] && (!link_int_to_bridge_interface($dhcrelayif)))))
405
				$dhcrelayenable = true;
406
		}
407
	}
408

    
409
	if (!$dhcrelayenable)
410
		return 0;
411

    
412
	if ($g['booting'])
413
		echo "Starting DHCP relay service...";
414
	else
415
		sleep(1);
416

    
417
	$dhcrelayifs = array();
418
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
419

    
420
		$ifcfg = $config['interfaces'][$dhcrelayif];
421

    
422
		if (!isset($dhcrelayifconf['enable']) ||
423
			(($dhcrelayif != "lan") &&
424
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || 
425
			link_int_to_bridge_interface($dhcrelayif))))
426
			continue;
427

    
428
		$dhcrelayifs[] = $ifcfg['if'];
429
	}
430

    
431
	/* In order for the relay to work, it needs to be active on the
432
	   interface in which the destination server sits */
433
	foreach ($config['interfaces'] as $ifname) {
434
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
435
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
436
			$destif = $ifname['if'];
437
	}
438

    
439
	if (!isset($destif))
440
		$destif = $config['interfaces']['wan']['if'];
441

    
442
	$dhcrelayifs[] = $destif;
443
	$dhcrelayifs = array_unique($dhcrelayifs);
444

    
445
	/* fire up dhcrelay */
446
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
447

    
448
	if (isset($dhcrelaycfg['agentoption']))
449
		$cmd .=  " -a -m replace";
450

    
451
	$cmd .= " {$dhcrelaycfg['server']}";
452
	mwexec($cmd);
453

    
454
	if (!$g['booting']) {
455
		/* set the reload filter dity flag */
456
		touch("{$g['tmp_path']}/filter_dirty");
457
	}
458

    
459
	return 0;
460
}
461

    
462
function services_dyndns_reset($interface, $dyndnsservice) {
463
	global $config, $g;
464
	if(isset($config['system']['developerspew'])) {
465
		$mt = microtime();
466
		echo "services_dyndns_reset() being called $mt\n";
467
	}
468

    
469
	conf_mount_rw();
470
	mwexec("rm {$g['conf_path']}/dyndns_{$interface}{$dyndnsservice}.cache");
471
	conf_mount_ro();
472

    
473
	return 0;
474
}
475

    
476
function services_dyndns_configure_client($conf) {
477

    
478
	/* determine interface name */
479
	$if = get_real_wan_interface($conf['interface']);
480

    
481
	/* load up the dyndns.class */
482
	require_once("dyndns.class");
483

    
484
	log_error("DynDns: Running updatedns()");
485

    
486
	$dns = new updatedns($dnsService = $conf['type'],
487
		$dnsHost = $conf['host'],
488
		$dnsUser = $conf['username'],
489
		$dnsPass = $conf['password'],
490
		$dnsWilcard = $conf['wildcard'],
491
		$dnsMX = $conf['mx'], $dnsIf = "{$if}");
492

    
493
}
494

    
495
function services_dyndns_configure() {
496
	global $config, $g;
497
	if(isset($config['system']['developerspew'])) {
498
		$mt = microtime();
499
		echo "services_dyndns_configure() being called $mt\n";
500
	}
501

    
502
	$dyndnscfg = $config['dyndnses']['dyndns'];
503

    
504
	if (is_array($dyndnscfg)) {
505
		if ($g['booting']) 
506
			echo "Starting DynDNS clients...";
507

    
508
		foreach ($dyndnscfg as $dyndns) {
509
			if (!isset($dyndns['enable']))
510
				continue;
511

    
512
			services_dyndns_configure_client($dyndns);
513

    
514
			sleep(1);
515
		}
516

    
517
		if ($g['booting'])
518
			echo "done.\n";
519
	}
520

    
521
	return 0;
522
}
523

    
524
function services_dnsmasq_configure() {
525
	global $config, $g;
526
	$return = 0;
527
	
528
	if(isset($config['system']['developerspew'])) {
529
		$mt = microtime();
530
		echo "services_dnsmasq_configure() being called $mt\n";
531
	}
532

    
533
	/* kill any running dnsmasq */
534
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
535

    
536
	if (isset($config['dnsmasq']['enable'])) {
537

    
538
		if ($g['booting'])
539
			echo "Starting DNS forwarder...";
540
		else
541
			sleep(1);
542

    
543
		/* generate hosts file */
544
		if(system_hosts_generate()!=0)
545
			$return = 1;
546

    
547
		$args = "";
548

    
549
		if (isset($config['dnsmasq']['regdhcp'])) {
550

    
551
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
552
				" -s {$config['system']['domain']}";
553
		}
554

    
555
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
556
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
557
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
558
                        }
559
                }
560

    
561
		/* suppose that dnsmasq handles our domain and don't send
562
		requests for our local domain to upstream servers */
563
		//if (!empty($config['system']['domain'])) {
564
		//	$args .= sprintf(' --local=/%s/', $config['system']['domain']);
565
		//}
566

    
567
		/* run dnsmasq */
568
		mwexec("/usr/local/sbin/dnsmasq --cache-size=5000 {$args}");
569

    
570
		if ($g['booting'])
571
			echo "done.\n";
572
	}
573

    
574
	if (!$g['booting']) {
575
		if(services_dhcpd_configure()!=0)
576
			$return = 1;
577
	}
578

    
579
	return $return;
580
}
581

    
582
function services_snmpd_configure() {
583
	global $config, $g;
584
	if(isset($config['system']['developerspew'])) {
585
		$mt = microtime();
586
		echo "services_snmpd_configure() being called $mt\n";
587
	}
588

    
589
	/* kill any running snmpd */
590
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
591
	if(is_process_running("bsnmpd")) 
592
		exec("/usr/bin/killall bsnmpd");
593

    
594
	if (isset($config['snmpd']['enable'])) {
595

    
596
		if ($g['booting'])
597
			echo "Starting SNMP daemon... ";
598

    
599
		/* generate snmpd.conf */
600
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
601
		if (!$fd) {
602
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
603
			return 1;
604
		}
605

    
606

    
607
		$snmpdconf = <<<EOD
608
location := "{$config['snmpd']['syslocation']}"
609
contact := "{$config['snmpd']['syscontact']}"
610
read := "{$config['snmpd']['rocommunity']}"
611

    
612
EOD;
613

    
614
/* No docs on what write strings do there for disable for now.
615
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
616
		    $snmpdconf .= <<<EOD
617
# write string
618
write := "{$config['snmpd']['rwcommunity']}"
619

    
620
EOD;
621
		}
622
*/
623

    
624

    
625
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
626
		    $snmpdconf .= <<<EOD
627
# SNMP Trap support.
628
traphost := {$config['snmpd']['trapserver']}
629
trapport := {$config['snmpd']['trapserverport']}
630
trap := "{$config['snmpd']['trapstring']}"
631

    
632

    
633
EOD;
634
		}
635

    
636

    
637
		$snmpdconf .= <<<EOD
638
system := 1     # pfSense
639
%snmpd
640
begemotSnmpdDebugDumpPdus       = 2
641
begemotSnmpdDebugSyslogPri      = 7
642
begemotSnmpdCommunityString.0.1 = $(read)
643

    
644
EOD;
645

    
646
/* No docs on what write strings do there for disable for now.
647
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
648
		    $snmpdconf .= <<<EOD
649
begemotSnmpdCommunityString.0.2 = $(write)
650

    
651
EOD;
652
		}
653
*/
654

    
655

    
656
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
657
		    $snmpdconf .= <<<EOD
658
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
659
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
660
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
661

    
662
EOD;
663
		}
664

    
665

    
666
		$snmpdconf .= <<<EOD
667
begemotSnmpdCommunityDisable    = 1
668

    
669
EOD;
670

    
671
		if(isset($config['snmpd']['bindlan'])) {
672
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
673
		} else {
674
			$bind_to_ip = "0.0.0.0";
675
		}
676

    
677
		if(is_port( $config['snmpd']['pollport'] )) {
678
		    $snmpdconf .= <<<EOD
679
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
680

    
681
EOD;
682

    
683
		}
684

    
685
		$snmpdconf .= <<<EOD
686
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
687
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
688

    
689
# These are bsnmp macros not php vars.
690
sysContact      = $(contact)
691
sysLocation     = $(location)
692
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
693

    
694
snmpEnableAuthenTraps = 2
695

    
696
EOD;
697

    
698
		if (is_array( $config['snmpd']['modules'] )) {
699
		    if(isset($config['snmpd']['modules']['mibii'])) {
700
			$snmpdconf .= <<<EOD
701
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
702

    
703
EOD;
704
		    }
705

    
706
		    if(isset($config['snmpd']['modules']['netgraph'])) {
707
			$snmpdconf .= <<<EOD
708
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
709
%netgraph
710
begemotNgControlNodeName = "snmpd"
711

    
712
EOD;
713
		    }
714

    
715
		    if(isset($config['snmpd']['modules']['pf'])) {
716
			$snmpdconf .= <<<EOD
717
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
718

    
719
EOD;
720
		    }
721

    
722
		    if(isset($config['snmpd']['modules']['hostres'])) {
723
			$snmpdconf .= <<<EOD
724
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
725

    
726
EOD;
727
		    }
728
		    if(isset($config['snmpd']['modules']['bridge'])) {
729
			$snmpdconf .= <<<EOD
730
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
731
# config must end with blank line
732

    
733

    
734
EOD;
735
		    }
736
		}
737

    
738
		fwrite($fd, $snmpdconf);
739
		fclose($fd);
740

    
741
		if (isset($config['snmpd']['bindlan'])) {
742
			$bindlan = "";
743
		}
744

    
745
		/* run bsnmpd */
746
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
747
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
748

    
749
		if ($g['booting'])
750
			echo "done.\n";
751
	}
752

    
753
	return 0;
754
}
755

    
756
function services_proxyarp_configure() {
757
	global $config, $g;
758
	if(isset($config['system']['developerspew'])) {
759
		$mt = microtime();
760
		echo "services_proxyarp_configure() being called $mt\n";
761
	}
762

    
763
	/* kill any running choparp */
764
	killbyname("choparp");
765

    
766
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
767
		$paa = array();
768

    
769
		/* group by interface */
770
		foreach ($config['virtualip']['vip'] as $vipent) {
771
			if ($vipent['mode'] === "proxyarp") {
772
				if ($vipent['interface'])
773
					$if = $vipent['interface'];
774
				else
775
					$if = "wan";
776

    
777
				if (!is_array($paa[$if]))
778
					$paa[$if] = array();
779

    
780
				$paa[$if][] = $vipent;
781
			}
782
		}
783

    
784
		if (count($paa))
785
		foreach ($paa as $paif => $paents) {
786
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
787
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
788
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
789
                               continue;
790

    
791
			$args = $config['interfaces'][$paif]['if'] . " auto";
792

    
793
			foreach ($paents as $paent) {
794

    
795
				if (isset($paent['subnet']))
796
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
797
				else if (isset($paent['range']))
798
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
799
						$paent['range']['to']);
800
			}
801

    
802
			mwexec_bg("/usr/local/sbin/choparp " . $args);
803
		}
804
	}
805
}
806

    
807
function services_dnsupdate_process() {
808
	global $config, $g;
809
	if(isset($config['system']['developerspew'])) {
810
		$mt = microtime();
811
		echo "services_dnsupdate_process() being called $mt\n";
812
	}
813

    
814
	/* Dynamic DNS updating active? */
815
	if (is_array($config['dnsupdates']['dnsupdate'])) {
816
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
817
		if (!isset($dyndns['enable']))
818
				continue;
819
			/* determine interface name */
820
			if ($dyndns['interface'] == "wan")
821
				$if = get_real_wan_interface();
822
			else
823
				$if = convert_friendly_interface_to_real_interface_name($dyndns['interface']);
824

    
825
			$wanip = get_current_wan_address($if);
826
			if ($wanip) {
827

    
828
				$keyname = $dnsupdate['keyname'];
829
				/* trailing dot */
830
				if (substr($keyname, -1) != ".")
831
					$keyname .= ".";
832

    
833
				$hostname = $dnsupdate['host'];
834
				/* trailing dot */
835
				if (substr($hostname, -1) != ".")
836
					$hostname .= ".";
837

    
838
				/* write private key file
839
				   this is dumb - public and private keys are the same for HMAC-MD5,
840
				   but nsupdate insists on having both */
841
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
842
				$privkey .= <<<EOD
843
Private-key-format: v1.2
844
Algorithm: 157 (HMAC)
845
Key: {$dnsupdate['keydata']}
846

    
847
EOD;
848
				fwrite($fd, $privkey);
849
				fclose($fd);
850

    
851
				/* write public key file */
852
				if ($dnsupdate['keytype'] == "zone") {
853
					$flags = 257;
854
					$proto = 3;
855
				} else if ($dnsupdate['keytype'] == "host") {
856
					$flags = 513;
857
					$proto = 3;
858
				} else if ($dnsupdate['keytype'] == "user") {
859
					$flags = 0;
860
					$proto = 2;
861
				}
862

    
863
				$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.key", "w");
864
				fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 {$dnsupdate['keydata']}\n");
865
				fclose($fd);
866

    
867
				/* generate update instructions */
868
				$upinst = "";
869
				if (!empty($dnsupdate['server']))
870
					$upinst .= "server {$dnsupdate['server']}\n";
871
				$upinst .= "update delete {$dnsupdate['host']} A\n";
872
				$upinst .= "update add {$dnsupdate['host']} {$dnsupdate['ttl']} A {$wanip}\n";
873
				$upinst .= "\n";	/* mind that trailing newline! */
874

    
875
				$fd = fopen("{$g['varetc_path']}/nsupdatecmds{$i}", "w");
876
				fwrite($fd, $upinst);
877
				fclose($fd);
878

    
879
				/* invoke nsupdate */
880
				$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
881
				if (isset($dnsupdate['usetcp']))
882
					$cmd .= " -v";
883
				$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
884
	
885
				mwexec_bg($cmd);
886
			}
887
		}
888
	}
889

    
890
	return 0;
891
}
892

    
893
function setup_wireless_olsr() {
894
	global $config, $g;
895
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
896
		return;
897
	if(isset($config['system']['developerspew'])) {
898
		$mt = microtime();
899
		echo "setup_wireless_olsr($interface) being called $mt\n";
900
	}
901
	conf_mount_rw();
902
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
903
		$olsr_enable = $olsrd['enable'];
904
		if($olsr_enable <> "on")
905
			return;
906
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
907

    
908
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
909
			$enableannounce .= "\nHna4\n";
910
			$enableannounce .= "{\n";
911
		if($olsrd['announcedynamicroute'])
912
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
913
		if($olsrd['enableannounce'] == "on")
914
			$enableannounce .= "0.0.0.0 0.0.0.0";
915
			$enableannounce .= "\n}\n";
916
		} else {
917
			$enableannounce = "";
918
		}
919

    
920
		$olsr .= <<<EODA
921
#
922
# olsr.org OLSR daemon config file
923
#
924
# Lines starting with a # are discarded
925
#
926
# This file was generated by setup_wireless_olsr() in services.inc
927
#
928

    
929
# This file is an example of a typical
930
# configuration for a mostly static
931
# network(regarding mobility) using
932
# the LQ extention
933

    
934
# Debug level(0-9)
935
# If set to 0 the daemon runs in the background
936

    
937
DebugLevel	2
938

    
939
# IP version to use (4 or 6)
940

    
941
IpVersion	4
942

    
943
# Clear the screen each time the internal state changes
944

    
945
ClearScreen     yes
946

    
947
{$enableannounce}
948

    
949
# Should olsrd keep on running even if there are
950
# no interfaces available? This is a good idea
951
# for a PCMCIA/USB hotswap environment.
952
# "yes" OR "no"
953

    
954
AllowNoInt	yes
955

    
956
# TOS(type of service) value for
957
# the IP header of control traffic.
958
# If not set it will default to 16
959

    
960
#TosValue	16
961

    
962
# The fixed willingness to use(0-7)
963
# If not set willingness will be calculated
964
# dynamically based on battery/power status
965
# if such information is available
966

    
967
#Willingness    	4
968

    
969
# Allow processes like the GUI front-end
970
# to connect to the daemon.
971

    
972
IpcConnect
973
{
974
     # Determines how many simultaneously
975
     # IPC connections that will be allowed
976
     # Setting this to 0 disables IPC
977

    
978
     MaxConnections  0
979

    
980
     # By default only 127.0.0.1 is allowed
981
     # to connect. Here allowed hosts can
982
     # be added
983

    
984
     Host            127.0.0.1
985
     #Host            10.0.0.5
986

    
987
     # You can also specify entire net-ranges
988
     # that are allowed to connect. Multiple
989
     # entries are allowed
990

    
991
     #Net             192.168.1.0 255.255.255.0
992
}
993

    
994
# Wether to use hysteresis or not
995
# Hysteresis adds more robustness to the
996
# link sensing but delays neighbor registration.
997
# Used by default. 'yes' or 'no'
998

    
999
UseHysteresis	no
1000

    
1001
# Hysteresis parameters
1002
# Do not alter these unless you know
1003
# what you are doing!
1004
# Set to auto by default. Allowed
1005
# values are floating point values
1006
# in the interval 0,1
1007
# THR_LOW must always be lower than
1008
# THR_HIGH.
1009

    
1010
#HystScaling	0.50
1011
#HystThrHigh	0.80
1012
#HystThrLow	0.30
1013

    
1014

    
1015
# Link quality level
1016
# 0 = do not use link quality
1017
# 1 = use link quality for MPR selection
1018
# 2 = use link quality for MPR selection and routing
1019
# Defaults to 0
1020

    
1021
LinkQualityLevel	{$olsrd['enablelqe']}
1022

    
1023
# Link quality window size
1024
# Defaults to 10
1025

    
1026
LinkQualityWinSize	10
1027

    
1028
# Polling rate in seconds(float).
1029
# Default value 0.05 sec
1030

    
1031
Pollrate	0.05
1032

    
1033

    
1034
# TC redundancy
1035
# Specifies how much neighbor info should
1036
# be sent in TC messages
1037
# Possible values are:
1038
# 0 - only send MPR selectors
1039
# 1 - send MPR selectors and MPRs
1040
# 2 - send all neighbors
1041
#
1042
# defaults to 0
1043

    
1044
TcRedundancy	2
1045

    
1046
#
1047
# MPR coverage
1048
# Specifies how many MPRs a node should
1049
# try select to reach every 2 hop neighbor
1050
#
1051
# Can be set to any integer >0
1052
#
1053
# defaults to 1
1054

    
1055
MprCoverage	3
1056

    
1057
# Example plugin entry with parameters:
1058

    
1059
EODA;
1060

    
1061
if($olsrd['enablehttpinfo'] == "on") {
1062
	$olsr .= <<<EODB
1063

    
1064
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1065
{
1066
    PlParam     "port"   "{$olsrd['port']}"
1067
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1068
}
1069

    
1070
EODB;
1071

    
1072
}
1073

    
1074
if($olsrd['enabledsecure'] == "on") {
1075
	$olsr .= <<<EODC
1076

    
1077
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1078
{
1079
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1080
}
1081

    
1082
EODC;
1083

    
1084
}
1085

    
1086
if($olsrd['enabledyngw'] == "on") {
1087

    
1088
	/* unset default route, olsr auto negotiates */
1089
	mwexec("/sbin/route delete default");
1090

    
1091
	$olsr .= <<<EODE
1092

    
1093
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1094
{
1095
    # how often to look for a inet gw, in seconds
1096
    # defaults to 5 secs, if commented out
1097
    PlParam     "Interval"   "{$olsrd['polling']}"
1098

    
1099
    # if one or more IPv4 addresses are given, do a ping on these in
1100
    # descending order to validate that there is not only an entry in
1101
    # routing table, but also a real internet connection. If any of
1102
    # these addresses could be pinged successfully, the test was
1103
    # succesful, i.e. if the ping on the 1st address was successful,the
1104
    # 2nd won't be pinged
1105
    PlParam     "Ping"       "{$olsrd['ping']}"
1106
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1107
}
1108

    
1109
EODE;
1110

    
1111
}
1112

    
1113
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1114
	$interfaces = explode(',', $conf['iface_array']);
1115
	foreach($interfaces as $interface) {
1116
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1117
$olsr .= <<<EODAD
1118
Interface "{$realinterface}"
1119
{
1120

    
1121
    # Hello interval in seconds(float)
1122
    HelloInterval    2.0
1123

    
1124
    # HELLO validity time
1125
    HelloValidityTime	20.0
1126

    
1127
    # TC interval in seconds(float)
1128
    TcInterval        5.0
1129

    
1130
    # TC validity time
1131
    TcValidityTime	30.0
1132

    
1133
    # MID interval in seconds(float)
1134
    MidInterval	5.0
1135

    
1136
    # MID validity time
1137
    MidValidityTime	30.0
1138

    
1139
    # HNA interval in seconds(float)
1140
    HnaInterval	5.0
1141

    
1142
    # HNA validity time
1143
    HnaValidityTime 	30.0
1144

    
1145
    # When multiple links exist between hosts
1146
    # the weight of interface is used to determine
1147
    # the link to use. Normally the weight is
1148
    # automatically calculated by olsrd based
1149
    # on the characteristics of the interface,
1150
    # but here you can specify a fixed value.
1151
    # Olsrd will choose links with the lowest value.
1152

    
1153
    # Weight 0
1154

    
1155

    
1156
}
1157

    
1158
EODAD;
1159

    
1160
	}
1161
	break;
1162
}
1163
		fwrite($fd, $olsr);
1164
		fclose($fd);
1165
	}
1166

    
1167
	if(is_process_running("olsrd"))
1168
		mwexec("/usr/bin/killall olsrd");
1169

    
1170
	sleep(2);
1171

    
1172
	mwexec_bg("/usr/local/sbin/olsrd -f {$g['varetc_path']}/olsr.conf");
1173

    
1174
	conf_mount_ro();
1175
}
1176

    
1177
/* configure cron service */
1178
function configure_cron() {
1179
	global $g, $config;
1180
	conf_mount_rw();
1181
	/* preserve existing crontab entries */
1182
	$crontab_contents = file_get_contents("/etc/crontab");
1183
	$crontab_contents_a = split("\n", $crontab_contents);
1184
	
1185
	for ($i = 0; $i < count($crontab_contents_a); $i++) {
1186
		$item =& $crontab_contents_a[$i];
1187
		if (strpos($item, "# pfSense specific crontab entries") !== false) {
1188
			array_splice($crontab_contents_a, $i - 1);
1189
			break;
1190
		}
1191
	}
1192
	$crontab_contents = implode("\n", $crontab_contents_a) . "\n";
1193
	
1194
	
1195
	if (is_array($config['cron']['item'])) {
1196
		$crontab_contents .= "#\n";
1197
		$crontab_contents .= "# pfSense specific crontab entries\n";
1198
		$crontab_contents .= "# Created: " . date("F j, Y, g:i a") . "\n";
1199
		$crontab_contents .= "#\n";
1200

    
1201
		foreach ($config['cron']['item'] as $item) {
1202
			$crontab_contents .= "\n{$item['minute']}\t";
1203
			$crontab_contents .= "{$item['hour']}\t";
1204
			$crontab_contents .= "{$item['mday']}\t";
1205
			$crontab_contents .= "{$item['month']}\t";
1206
			$crontab_contents .= "{$item['wday']}\t";
1207
			$crontab_contents .= "{$item['who']}\t";
1208
			$crontab_contents .= "{$item['command']}";
1209
		}
1210
    
1211
		$crontab_contents .= "\n#\n";
1212
		$crontab_contents .= "# If possible do not add items to this file manually.\n";
1213
		$crontab_contents .= "# If you do so, this file must be terminated with a blank line (e.g. new line)\n";
1214
		$crontab_contents .= "#\n\n";
1215
	}
1216
	
1217
	/* please maintain the newline at the end of file */
1218
	file_put_contents("/etc/crontab", $crontab_contents);
1219
	
1220
	if (!$g['booting'])
1221
		conf_mount_ro();
1222
}
1223

    
1224
function upnp_action ($action) {
1225
	switch($action) {
1226
		case "start":
1227
			if(file_exists('/var/etc/miniupnpd.conf'))
1228
				mwexec_bg('/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf');
1229
			break;
1230
		case "stop":
1231
			while((int)exec("pgrep miniupnpd | wc -l") > 0)
1232
				mwexec('killall miniupnpd 2>/dev/null');
1233
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
1234
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
1235
			break;
1236
		case "restart":
1237
			upnp_action('stop');
1238
			upnp_action('start');
1239
			break;
1240
	}
1241
}
1242

    
1243
function upnp_start() {
1244
	global $config, $g;
1245
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1246
		if($g['booting']) {
1247
			echo "Starting UPnP service... ";
1248
			include('/usr/local/pkg/miniupnpd.inc');
1249
			sync_package_miniupnpd();
1250
			echo "done.\n";
1251
		}
1252
		else {
1253
			upnp_action('start');
1254
		}
1255
	}
1256
}
1257

    
1258
?>
(27-27/37)