Project

General

Profile

Download (31.4 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 services_dhcpd_configure() {
36
	global $config, $g;
37
	
38
	if($g['services_dhcp_server_enable'] == false) 
39
		return;
40

    
41
	if(isset($config['system']['developerspew'])) {
42
		$mt = microtime();
43
		echo "services_dhcpd_configure($if) being called $mt\n";
44
	}
45

    
46
	/* DHCP enabled on any interfaces? */
47
	if (!is_dhcp_server_enabled())
48
		return 0;
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", true);
79

    
80
	$syscfg = $config['system'];
81
	$dhcpdcfg = $config['dhcpd'];
82
	$Iflist = get_configured_interface_list();
83
		
84
	if ($g['booting'])
85
		echo "Starting DHCP service...";
86
	else
87
		sleep(1);
88

    
89
	/* write dhcpd.conf */
90
	$fd = fopen("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", "w");
91
	if (!$fd) {
92
		printf("Error: cannot open dhcpd.conf in services_dhcpd_configure().\n");
93
		return 1;
94
	}
95

    
96

    
97

    
98
	$dhcpdconf = <<<EOD
99
	
100
option domain-name "{$syscfg['domain']}";
101
option ldap-server code 95 = text;
102
option domain-search-list code 119 = text;
103
default-lease-time 7200;
104
max-lease-time 86400;
105
log-facility local7;
106
ddns-update-style none;
107
one-lease-per-client true;
108
deny duplicates;
109
ping-check true;
110

    
111
EOD;
112

    
113
	if(isset($dhcpifconf['alwaysbroadcast'])) 
114
		$dhcpdconf .= "always-broadcast on\n";
115

    
116
	$dhcpdifs = array();
117

    
118
	/*    loop through and deterimine if we need to setup
119
	 *    failover peer "bleh" entries
120
	 */
121
	$dhcpnum = 0;
122
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
123

    
124
		if (!isset($dhcpifconf['enable']))
125
			continue;
126

    
127
		if(!isset($dhcpifconf['disableauthoritative']))
128
			$dhcpdconf .= "authoritative;\n";
129

    
130
		if($dhcpifconf['failover_peerip'] <> "") {
131
			/*
132
			 *    yep, failover peer is defined.
133
			 *    does it match up to a defined vip?
134
			 */
135
			$skew = 110;
136
			$a_vip = &$config['virtualip']['vip'];
137
			if(is_array($a_vip)) {
138
				foreach ($a_vip as $vipent) {
139
					$int = guess_interface_from_ip($dhcpifconf['failover_peerip']);
140
					$intip = find_interface_ip($int);
141
					$real_dhcpif = convert_friendly_interface_to_real_interface_name($dhcpif);
142
					if($int == $real_dhcpif) {
143
						/* this is the interface! */
144
						if($vipent['advskew'] < "20")
145
							$skew = 0;
146
					}
147
				}
148
			} else {
149
				log_error("Warning!  DHCP Failover setup and no CARP virtual IP's defined!");
150
			}
151
			if($skew > 10) {
152
				$type = "secondary";
153
				$dhcpdconf_pri  = "mclt 600;\n";
154
				$my_port = "520";
155
				$peer_port = "519";
156
			} else {
157
				$my_port = "519";
158
				$peer_port = "520";
159
				$type = "primary";
160
				$dhcpdconf_pri  = "split 128;\n";
161
				$dhcpdconf_pri .= "  mclt 600;\n";
162
			}
163
			$dhcpdconf .= <<<EOPP
164
failover peer "dhcp{$dhcpnum}" {
165
  {$type};
166
  address {$intip};
167
  port {$my_port};
168
  peer address {$dhcpifconf['failover_peerip']};
169
  peer port {$peer_port};
170
  max-response-delay 10;
171
  max-unacked-updates 10;
172
  {$dhcpdconf_pri}
173
  load balance max seconds 3;
174
}
175

    
176
EOPP;
177
		$dhcpnum++;
178
		}
179
	}
180

    
181
	$dhcpnum = 0;
182

    
183
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
184

    
185
		$ifcfg = $config['interfaces'][$dhcpif];
186

    
187
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif]))
188
			continue;
189

    
190
		$subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']);
191
		$subnetmask = gen_subnet_mask($ifcfg['subnet']);
192

    
193
		if($is_olsr_enabled == true)
194
			if($dhcpifconf['netmask'])
195
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
196

    
197
		$dnscfg = "";
198

    
199
		if ($dhcpifconf['domain']) {
200
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
201
		}
202
		
203
    		if($dhcpifconf['domainsearchlist'] <> "") {
204
			$dnscfg .= "	option domain-search-list \"{$dhcpifconf['domainsearchlist']}\";\n";
205
    		}
206

    
207
		if (isset($dhcpifconf['ddnsupdate'])) {
208
			if($dhcpifconf['ddnsdomain'] <> "") {
209
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
210
			}
211
			$dnscfg .= "	ddns-update-style interim;\n";
212
		}
213

    
214
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
215
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
216
		} else if (isset($config['dnsmasq']['enable'])) {
217
			$dnscfg .= "	option domain-name-servers " . $ifcfg['ipaddr'] . ";";
218
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
219
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
220
		}
221

    
222
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
223
		$dhcpdconf .= "	pool {\n";
224

    
225
		/* is failover dns setup? */
226
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
227
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
228
			if($dhcpifconf['dnsserver'][1] <> "")
229
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
230
			$dhcpdconf .= ";\n";
231
		}
232

    
233
		if($dhcpifconf['failover_peerip'] <> "")
234
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
235

    
236
		if (isset($dhcpifconf['denyunknown']))
237
		   $dhcpdconf .= "		deny unknown clients;\n";
238

    
239
		if ($dhcpifconf['gateway'])
240
			$routers = $dhcpifconf['gateway'];
241
		else
242
			$routers = $ifcfg['ipaddr'];
243

    
244
		if($dhcpifconf['failover_peerip'] <> "") {
245
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
246
			$dhcpnum++;
247
		}
248

    
249
		$dhcpdconf .= <<<EOD
250
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
251
	}
252
	option routers {$routers};
253
$dnscfg
254

    
255
EOD;
256
    
257
    		if ($dhcpifconf['defaultleasetime'])
258
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
259
		if ($dhcpifconf['maxleasetime'])
260
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
261

    
262
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
263
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
264
			$dhcpdconf .= "	option netbios-node-type 8;\n";
265
		}
266

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

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

    
273
    if ($dhcpifconf['ldap'] <> "")
274
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
275

    
276
		if(isset($dhcpifconf['netboot'])) {
277
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
278
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
279
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
280
			}
281
			if ($dhcpifconf['rootpath'] <> "") {
282
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
283
      }
284
		}
285
		
286
		$dhcpdconf .= <<<EOD
287
}
288

    
289
EOD;
290

    
291
		/* add static mappings */
292
		if (is_array($dhcpifconf['staticmap'])) {
293

    
294
			$i = 0;
295
			foreach ($dhcpifconf['staticmap'] as $sm) {
296
				$dhcpdconf .= <<<EOD
297
host s_{$dhcpif}_{$i} {
298
	hardware ethernet {$sm['mac']};
299

    
300
EOD;
301
				if ($sm['ipaddr'])
302
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
303

    
304
				if ($sm['hostname'])
305
					$dhcpdconf .= "	option host-name {$sm['hostname']};\n";
306

    
307
				$dhcpdconf .= "}\n";
308
				$i++;
309
			}
310
		}
311

    
312
		$dhcpdifs[] = get_real_interface($dhcpif);
313
	}
314

    
315
	fwrite($fd, $dhcpdconf);
316
	fclose($fd);
317

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

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

    
325
	if ($g['booting']) {
326
		print "done.\n";
327
	}
328

    
329
	return 0;
330
}
331

    
332
function interfaces_staticarp_configure($if) {
333
	global $config, $g;
334
	if(isset($config['system']['developerspew'])) {
335
		$mt = microtime();
336
		echo "interfaces_staticarp_configure($if) being called $mt\n";
337
	}
338

    
339
        $ifcfg = $config['interfaces'][$if];
340

    
341
        /* Enable staticarp, if enabled */
342
        if(isset($config['dhcpd'][$if]['staticarp'])) {
343
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
344
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
345
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
346

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

    
350
                        }
351

    
352
                }
353
        } else {
354
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
355
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
356
        }
357

    
358
        return 0;
359
}
360

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

    
368
	/* kill any running dhcrelay */
369
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
370

    
371
	$dhcrelaycfg = $config['dhcrelay'];
372

    
373
	/* DHCPRelay enabled on any interfaces? */
374
	$dhcrelayenable = false;
375
	if(is_array($dhcrelaycfg)) {
376
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
377
			if (isset($dhcrelayifconf['enable']) &&
378
				(($dhcrelayif == "lan") ||
379
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
380
				$config['interfaces'][$dhcrelayif]['if'] && (!link_interface_to_bridge($dhcrelayif)))))
381
				$dhcrelayenable = true;
382
		}
383
	}
384

    
385
	if (!$dhcrelayenable)
386
		return 0;
387

    
388
	if ($g['booting'])
389
		echo "Starting DHCP relay service...";
390
	else
391
		sleep(1);
392

    
393
	$dhcrelayifs = array();
394
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
395

    
396
		$ifcfg = $config['interfaces'][$dhcrelayif];
397

    
398
		if (!isset($dhcrelayifconf['enable']) ||
399
			(($dhcrelayif != "lan") &&
400
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || 
401
			link_interface_to_bridge($dhcrelayif))))
402
			continue;
403

    
404
		$dhcrelayifs[] = $ifcfg['if'];
405
	}
406

    
407
	/* In order for the relay to work, it needs to be active on the
408
	   interface in which the destination server sits */
409
	foreach ($config['interfaces'] as $ifname) {
410
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
411
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
412
			$destif = $ifname['if'];
413
	}
414

    
415
	if (!isset($destif))
416
		$destif = $config['interfaces']['wan']['if'];
417

    
418
	$dhcrelayifs[] = $destif;
419
	$dhcrelayifs = array_unique($dhcrelayifs);
420

    
421
	/* fire up dhcrelay */
422
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
423

    
424
	if (isset($dhcrelaycfg['agentoption']))
425
		$cmd .=  " -a -m replace";
426

    
427
	$cmd .= " {$dhcrelaycfg['server']}";
428
	mwexec($cmd);
429

    
430
	if (!$g['booting']) {
431
		/* set the reload filter dity flag */
432
		filter_configure();
433
	}
434

    
435
	return 0;
436
}
437

    
438
function services_dyndns_reset($interface, $dyndnsservice) {
439
	global $config, $g;
440
	if(isset($config['system']['developerspew'])) {
441
		$mt = microtime();
442
		echo "services_dyndns_reset() being called $mt\n";
443
	}
444

    
445
	conf_mount_rw();
446
	mwexec("rm {$g['conf_path']}/dyndns_{$interface}{$dyndnsservice}.cache");
447
	conf_mount_ro();
448

    
449
	return 0;
450
}
451

    
452
function services_dyndns_configure_client($conf) {
453

    
454
	/* determine interface name */
455
	$if = get_real_interface($conf['interface']);
456

    
457
	/* load up the dyndns.class */
458
	require_once("dyndns.class");
459

    
460
	log_error("DynDns: Running updatedns()");
461

    
462
	$dns = new updatedns($dnsService = $conf['type'],
463
		$dnsHost = $conf['host'],
464
		$dnsUser = $conf['username'],
465
		$dnsPass = $conf['password'],
466
		$dnsWilcard = $conf['wildcard'],
467
		$dnsMX = $conf['mx'], $dnsIf = "{$if}");
468

    
469
}
470

    
471
function services_dyndns_configure() {
472
	global $config, $g;
473
	if(isset($config['system']['developerspew'])) {
474
		$mt = microtime();
475
		echo "services_dyndns_configure() being called $mt\n";
476
	}
477

    
478
	$dyndnscfg = $config['dyndnses']['dyndns'];
479

    
480
	if (is_array($dyndnscfg)) {
481
		if ($g['booting']) 
482
			echo "Starting DynDNS clients...";
483

    
484
		foreach ($dyndnscfg as $dyndns) {
485
			if (!isset($dyndns['enable']))
486
				continue;
487

    
488
			services_dyndns_configure_client($dyndns);
489

    
490
			sleep(1);
491
		}
492

    
493
		if ($g['booting'])
494
			echo "done.\n";
495
	}
496

    
497
	return 0;
498
}
499

    
500
function services_dnsmasq_configure() {
501
	global $config, $g;
502
	$return = 0;
503
	
504
	if(isset($config['system']['developerspew'])) {
505
		$mt = microtime();
506
		echo "services_dnsmasq_configure() being called $mt\n";
507
	}
508

    
509
	/* kill any running dnsmasq */
510
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
511

    
512
	if (isset($config['dnsmasq']['enable'])) {
513

    
514
		if ($g['booting'])
515
			echo "Starting DNS forwarder...";
516
		else
517
			sleep(1);
518

    
519
		/* generate hosts file */
520
		if(system_hosts_generate()!=0)
521
			$return = 1;
522

    
523
		$args = "";
524

    
525
		if (isset($config['dnsmasq']['regdhcp'])) {
526

    
527
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
528
				" -s {$config['system']['domain']}";
529
		}
530

    
531
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
532
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
533
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
534
                        }
535
                }
536

    
537
		/* suppose that dnsmasq handles our domain and don't send
538
		requests for our local domain to upstream servers */
539
		//if (!empty($config['system']['domain'])) {
540
		//	$args .= sprintf(' --local=/%s/', $config['system']['domain']);
541
		//}
542

    
543
		/* run dnsmasq */
544
		mwexec("/usr/local/sbin/dnsmasq --cache-size=5000 {$args}");
545

    
546
		if ($g['booting'])
547
			echo "done.\n";
548
	}
549

    
550
	if (!$g['booting']) {
551
		if(services_dhcpd_configure()!=0)
552
			$return = 1;
553
	}
554

    
555
	return $return;
556
}
557

    
558
function services_snmpd_configure() {
559
	global $config, $g;
560
	if(isset($config['system']['developerspew'])) {
561
		$mt = microtime();
562
		echo "services_snmpd_configure() being called $mt\n";
563
	}
564

    
565
	/* kill any running snmpd */
566
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
567
	if(is_process_running("bsnmpd")) 
568
		mwexec("/usr/bin/killall bsnmpd", true);
569

    
570
	if (isset($config['snmpd']['enable'])) {
571

    
572
		if ($g['booting'])
573
			echo "Starting SNMP daemon... ";
574

    
575
		/* generate snmpd.conf */
576
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
577
		if (!$fd) {
578
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
579
			return 1;
580
		}
581

    
582

    
583
		$snmpdconf = <<<EOD
584
location := "{$config['snmpd']['syslocation']}"
585
contact := "{$config['snmpd']['syscontact']}"
586
read := "{$config['snmpd']['rocommunity']}"
587

    
588
EOD;
589

    
590
/* No docs on what write strings do there for disable for now.
591
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
592
		    $snmpdconf .= <<<EOD
593
# write string
594
write := "{$config['snmpd']['rwcommunity']}"
595

    
596
EOD;
597
		}
598
*/
599

    
600

    
601
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
602
		    $snmpdconf .= <<<EOD
603
# SNMP Trap support.
604
traphost := {$config['snmpd']['trapserver']}
605
trapport := {$config['snmpd']['trapserverport']}
606
trap := "{$config['snmpd']['trapstring']}"
607

    
608

    
609
EOD;
610
		}
611

    
612

    
613
		$snmpdconf .= <<<EOD
614
system := 1     # pfSense
615
%snmpd
616
begemotSnmpdDebugDumpPdus       = 2
617
begemotSnmpdDebugSyslogPri      = 7
618
begemotSnmpdCommunityString.0.1 = $(read)
619

    
620
EOD;
621

    
622
/* No docs on what write strings do there for disable for now.
623
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
624
		    $snmpdconf .= <<<EOD
625
begemotSnmpdCommunityString.0.2 = $(write)
626

    
627
EOD;
628
		}
629
*/
630

    
631

    
632
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
633
		    $snmpdconf .= <<<EOD
634
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
635
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
636
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
637

    
638
EOD;
639
		}
640

    
641

    
642
		$snmpdconf .= <<<EOD
643
begemotSnmpdCommunityDisable    = 1
644

    
645
EOD;
646

    
647
		if(isset($config['snmpd']['bindlan'])) {
648
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
649
		} else {
650
			$bind_to_ip = "0.0.0.0";
651
		}
652

    
653
		if(is_port( $config['snmpd']['pollport'] )) {
654
		    $snmpdconf .= <<<EOD
655
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
656

    
657
EOD;
658

    
659
		}
660

    
661
		$snmpdconf .= <<<EOD
662
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
663
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
664

    
665
# These are bsnmp macros not php vars.
666
sysContact      = $(contact)
667
sysLocation     = $(location)
668
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
669

    
670
snmpEnableAuthenTraps = 2
671

    
672
EOD;
673

    
674
		if (is_array( $config['snmpd']['modules'] )) {
675
		    if(isset($config['snmpd']['modules']['mibii'])) {
676
			$snmpdconf .= <<<EOD
677
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
678

    
679
EOD;
680
		    }
681

    
682
		    if(isset($config['snmpd']['modules']['netgraph'])) {
683
			$snmpdconf .= <<<EOD
684
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
685
%netgraph
686
begemotNgControlNodeName = "snmpd"
687

    
688
EOD;
689
		    }
690

    
691
		    if(isset($config['snmpd']['modules']['pf'])) {
692
			$snmpdconf .= <<<EOD
693
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
694

    
695
EOD;
696
		    }
697

    
698
		    if(isset($config['snmpd']['modules']['hostres'])) {
699
			$snmpdconf .= <<<EOD
700
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
701

    
702
EOD;
703
		    }
704
		    if(isset($config['snmpd']['modules']['bridge'])) {
705
			$snmpdconf .= <<<EOD
706
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
707
# config must end with blank line
708

    
709

    
710
EOD;
711
		    }
712
		}
713

    
714
		fwrite($fd, $snmpdconf);
715
		fclose($fd);
716

    
717
		if (isset($config['snmpd']['bindlan'])) {
718
			$bindlan = "";
719
		}
720

    
721
		/* run bsnmpd */
722
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
723
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
724

    
725
		if ($g['booting'])
726
			echo "done.\n";
727
	}
728

    
729
	return 0;
730
}
731

    
732
function services_proxyarp_configure() {
733
	global $config, $g;
734
	if(isset($config['system']['developerspew'])) {
735
		$mt = microtime();
736
		echo "services_proxyarp_configure() being called $mt\n";
737
	}
738

    
739
	/* kill any running choparp */
740
	killbyname("choparp");
741

    
742
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
743
		$paa = array();
744

    
745
		/* group by interface */
746
		foreach ($config['virtualip']['vip'] as $vipent) {
747
			if ($vipent['mode'] === "proxyarp") {
748
				if ($vipent['interface'])
749
					$if = $vipent['interface'];
750
				else
751
					$if = "wan";
752

    
753
				if (!is_array($paa[$if]))
754
					$paa[$if] = array();
755

    
756
				$paa[$if][] = $vipent;
757
			}
758
		}
759

    
760
		if (count($paa))
761
		foreach ($paa as $paif => $paents) {
762
			if (!(is_ipaddr($config['interfaces'][$paif]['ipaddr'])))
763
                               continue;
764

    
765
			$args = $config['interfaces'][$paif]['if'] . " auto";
766

    
767
			foreach ($paents as $paent) {
768

    
769
				if (isset($paent['subnet']))
770
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
771
				else if (isset($paent['range']))
772
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
773
						$paent['range']['to']);
774
			}
775

    
776
			mwexec_bg("/usr/local/sbin/choparp " . $args);
777
		}
778
	}
779
}
780

    
781
function services_dnsupdate_process() {
782
	global $config, $g;
783
	if(isset($config['system']['developerspew'])) {
784
		$mt = microtime();
785
		echo "services_dnsupdate_process() being called $mt\n";
786
	}
787

    
788
	/* Dynamic DNS updating active? */
789
	if (is_array($config['dnsupdates']['dnsupdate'])) {
790
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
791
		if (!isset($dyndns['enable']))
792
				continue;
793
			/* determine interface name */
794
			if ($dyndns['interface'] == "wan")
795
				$if = get_real_interface();
796
			else
797
				$if = convert_friendly_interface_to_real_interface_name($dyndns['interface']);
798

    
799
			$wanip = get_interface_ip($if);
800
			if ($wanip) {
801

    
802
				$keyname = $dnsupdate['keyname'];
803
				/* trailing dot */
804
				if (substr($keyname, -1) != ".")
805
					$keyname .= ".";
806

    
807
				$hostname = $dnsupdate['host'];
808
				/* trailing dot */
809
				if (substr($hostname, -1) != ".")
810
					$hostname .= ".";
811

    
812
				/* write private key file
813
				   this is dumb - public and private keys are the same for HMAC-MD5,
814
				   but nsupdate insists on having both */
815
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
816
				$privkey .= <<<EOD
817
Private-key-format: v1.2
818
Algorithm: 157 (HMAC)
819
Key: {$dnsupdate['keydata']}
820

    
821
EOD;
822
				fwrite($fd, $privkey);
823
				fclose($fd);
824

    
825
				/* write public key file */
826
				if ($dnsupdate['keytype'] == "zone") {
827
					$flags = 257;
828
					$proto = 3;
829
				} else if ($dnsupdate['keytype'] == "host") {
830
					$flags = 513;
831
					$proto = 3;
832
				} else if ($dnsupdate['keytype'] == "user") {
833
					$flags = 0;
834
					$proto = 2;
835
				}
836

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

    
841
				/* generate update instructions */
842
				$upinst = "";
843
				if (!empty($dnsupdate['server']))
844
					$upinst .= "server {$dnsupdate['server']}\n";
845
				$upinst .= "update delete {$dnsupdate['host']} A\n";
846
				$upinst .= "update add {$dnsupdate['host']} {$dnsupdate['ttl']} A {$wanip}\n";
847
				$upinst .= "\n";	/* mind that trailing newline! */
848

    
849
				$fd = fopen("{$g['varetc_path']}/nsupdatecmds{$i}", "w");
850
				fwrite($fd, $upinst);
851
				fclose($fd);
852

    
853
				/* invoke nsupdate */
854
				$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
855
				if (isset($dnsupdate['usetcp']))
856
					$cmd .= " -v";
857
				$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
858
	
859
				mwexec_bg($cmd);
860
			}
861
		}
862
	}
863

    
864
	return 0;
865
}
866

    
867
function setup_wireless_olsr() {
868
	global $config, $g;
869
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
870
		return;
871
	if(isset($config['system']['developerspew'])) {
872
		$mt = microtime();
873
		echo "setup_wireless_olsr($interface) being called $mt\n";
874
	}
875
	conf_mount_rw();
876
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
877
		$olsr_enable = $olsrd['enable'];
878
		if($olsr_enable <> "on")
879
			return;
880
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
881

    
882
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
883
			$enableannounce .= "\nHna4\n";
884
			$enableannounce .= "{\n";
885
		if($olsrd['announcedynamicroute'])
886
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
887
		if($olsrd['enableannounce'] == "on")
888
			$enableannounce .= "0.0.0.0 0.0.0.0";
889
			$enableannounce .= "\n}\n";
890
		} else {
891
			$enableannounce = "";
892
		}
893

    
894
		$olsr .= <<<EODA
895
#
896
# olsr.org OLSR daemon config file
897
#
898
# Lines starting with a # are discarded
899
#
900
# This file was generated by setup_wireless_olsr() in services.inc
901
#
902

    
903
# This file is an example of a typical
904
# configuration for a mostly static
905
# network(regarding mobility) using
906
# the LQ extention
907

    
908
# Debug level(0-9)
909
# If set to 0 the daemon runs in the background
910

    
911
DebugLevel	2
912

    
913
# IP version to use (4 or 6)
914

    
915
IpVersion	4
916

    
917
# Clear the screen each time the internal state changes
918

    
919
ClearScreen     yes
920

    
921
{$enableannounce}
922

    
923
# Should olsrd keep on running even if there are
924
# no interfaces available? This is a good idea
925
# for a PCMCIA/USB hotswap environment.
926
# "yes" OR "no"
927

    
928
AllowNoInt	yes
929

    
930
# TOS(type of service) value for
931
# the IP header of control traffic.
932
# If not set it will default to 16
933

    
934
#TosValue	16
935

    
936
# The fixed willingness to use(0-7)
937
# If not set willingness will be calculated
938
# dynamically based on battery/power status
939
# if such information is available
940

    
941
#Willingness    	4
942

    
943
# Allow processes like the GUI front-end
944
# to connect to the daemon.
945

    
946
IpcConnect
947
{
948
     # Determines how many simultaneously
949
     # IPC connections that will be allowed
950
     # Setting this to 0 disables IPC
951

    
952
     MaxConnections  0
953

    
954
     # By default only 127.0.0.1 is allowed
955
     # to connect. Here allowed hosts can
956
     # be added
957

    
958
     Host            127.0.0.1
959
     #Host            10.0.0.5
960

    
961
     # You can also specify entire net-ranges
962
     # that are allowed to connect. Multiple
963
     # entries are allowed
964

    
965
     #Net             192.168.1.0 255.255.255.0
966
}
967

    
968
# Wether to use hysteresis or not
969
# Hysteresis adds more robustness to the
970
# link sensing but delays neighbor registration.
971
# Used by default. 'yes' or 'no'
972

    
973
UseHysteresis	no
974

    
975
# Hysteresis parameters
976
# Do not alter these unless you know
977
# what you are doing!
978
# Set to auto by default. Allowed
979
# values are floating point values
980
# in the interval 0,1
981
# THR_LOW must always be lower than
982
# THR_HIGH.
983

    
984
#HystScaling	0.50
985
#HystThrHigh	0.80
986
#HystThrLow	0.30
987

    
988

    
989
# Link quality level
990
# 0 = do not use link quality
991
# 1 = use link quality for MPR selection
992
# 2 = use link quality for MPR selection and routing
993
# Defaults to 0
994

    
995
LinkQualityLevel	{$olsrd['enablelqe']}
996

    
997
# Link quality window size
998
# Defaults to 10
999

    
1000
LinkQualityWinSize	10
1001

    
1002
# Polling rate in seconds(float).
1003
# Default value 0.05 sec
1004

    
1005
Pollrate	0.05
1006

    
1007

    
1008
# TC redundancy
1009
# Specifies how much neighbor info should
1010
# be sent in TC messages
1011
# Possible values are:
1012
# 0 - only send MPR selectors
1013
# 1 - send MPR selectors and MPRs
1014
# 2 - send all neighbors
1015
#
1016
# defaults to 0
1017

    
1018
TcRedundancy	2
1019

    
1020
#
1021
# MPR coverage
1022
# Specifies how many MPRs a node should
1023
# try select to reach every 2 hop neighbor
1024
#
1025
# Can be set to any integer >0
1026
#
1027
# defaults to 1
1028

    
1029
MprCoverage	3
1030

    
1031
# Example plugin entry with parameters:
1032

    
1033
EODA;
1034

    
1035
if($olsrd['enablehttpinfo'] == "on") {
1036
	$olsr .= <<<EODB
1037

    
1038
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1039
{
1040
    PlParam     "port"   "{$olsrd['port']}"
1041
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1042
}
1043

    
1044
EODB;
1045

    
1046
}
1047

    
1048
if($olsrd['enabledsecure'] == "on") {
1049
	$olsr .= <<<EODC
1050

    
1051
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1052
{
1053
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1054
}
1055

    
1056
EODC;
1057

    
1058
}
1059

    
1060
if($olsrd['enabledyngw'] == "on") {
1061

    
1062
	/* unset default route, olsr auto negotiates */
1063
	mwexec("/sbin/route delete default");
1064

    
1065
	$olsr .= <<<EODE
1066

    
1067
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1068
{
1069
    # how often to look for a inet gw, in seconds
1070
    # defaults to 5 secs, if commented out
1071
    PlParam     "Interval"   "{$olsrd['polling']}"
1072

    
1073
    # if one or more IPv4 addresses are given, do a ping on these in
1074
    # descending order to validate that there is not only an entry in
1075
    # routing table, but also a real internet connection. If any of
1076
    # these addresses could be pinged successfully, the test was
1077
    # succesful, i.e. if the ping on the 1st address was successful,the
1078
    # 2nd won't be pinged
1079
    PlParam     "Ping"       "{$olsrd['ping']}"
1080
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1081
}
1082

    
1083
EODE;
1084

    
1085
}
1086

    
1087
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1088
	$interfaces = explode(',', $conf['iface_array']);
1089
	foreach($interfaces as $interface) {
1090
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1091
$olsr .= <<<EODAD
1092
Interface "{$realinterface}"
1093
{
1094

    
1095
    # Hello interval in seconds(float)
1096
    HelloInterval    2.0
1097

    
1098
    # HELLO validity time
1099
    HelloValidityTime	20.0
1100

    
1101
    # TC interval in seconds(float)
1102
    TcInterval        5.0
1103

    
1104
    # TC validity time
1105
    TcValidityTime	30.0
1106

    
1107
    # MID interval in seconds(float)
1108
    MidInterval	5.0
1109

    
1110
    # MID validity time
1111
    MidValidityTime	30.0
1112

    
1113
    # HNA interval in seconds(float)
1114
    HnaInterval	5.0
1115

    
1116
    # HNA validity time
1117
    HnaValidityTime 	30.0
1118

    
1119
    # When multiple links exist between hosts
1120
    # the weight of interface is used to determine
1121
    # the link to use. Normally the weight is
1122
    # automatically calculated by olsrd based
1123
    # on the characteristics of the interface,
1124
    # but here you can specify a fixed value.
1125
    # Olsrd will choose links with the lowest value.
1126

    
1127
    # Weight 0
1128

    
1129

    
1130
}
1131

    
1132
EODAD;
1133

    
1134
	}
1135
	break;
1136
}
1137
		fwrite($fd, $olsr);
1138
		fclose($fd);
1139
	}
1140

    
1141
	if(is_process_running("olsrd"))
1142
		mwexec("/usr/bin/killall olsrd", true);
1143

    
1144
	sleep(2);
1145

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

    
1148
	conf_mount_ro();
1149
}
1150

    
1151
/* configure cron service */
1152
function configure_cron() {
1153
	global $g, $config;
1154
	conf_mount_rw();
1155
	/* preserve existing crontab entries */
1156
	$crontab_contents = file_get_contents("/etc/crontab");
1157
	$crontab_contents_a = split("\n", $crontab_contents);
1158
	
1159
	for ($i = 0; $i < count($crontab_contents_a); $i++) {
1160
		$item =& $crontab_contents_a[$i];
1161
		if (strpos($item, "# pfSense specific crontab entries") !== false) {
1162
			array_splice($crontab_contents_a, $i - 1);
1163
			break;
1164
		}
1165
	}
1166
	$crontab_contents = implode("\n", $crontab_contents_a) . "\n";
1167
	
1168
	
1169
	if (is_array($config['cron']['item'])) {
1170
		$crontab_contents .= "#\n";
1171
		$crontab_contents .= "# pfSense specific crontab entries\n";
1172
		$crontab_contents .= "# Created: " . date("F j, Y, g:i a") . "\n";
1173
		$crontab_contents .= "#\n";
1174

    
1175
		foreach ($config['cron']['item'] as $item) {
1176
			$crontab_contents .= "\n{$item['minute']}\t";
1177
			$crontab_contents .= "{$item['hour']}\t";
1178
			$crontab_contents .= "{$item['mday']}\t";
1179
			$crontab_contents .= "{$item['month']}\t";
1180
			$crontab_contents .= "{$item['wday']}\t";
1181
			$crontab_contents .= "{$item['who']}\t";
1182
			$crontab_contents .= "{$item['command']}";
1183
		}
1184
    
1185
		$crontab_contents .= "\n#\n";
1186
		$crontab_contents .= "# If possible do not add items to this file manually.\n";
1187
		$crontab_contents .= "# If you do so, this file must be terminated with a blank line (e.g. new line)\n";
1188
		$crontab_contents .= "#\n\n";
1189
	}
1190
	
1191
	/* please maintain the newline at the end of file */
1192
	file_put_contents("/etc/crontab", $crontab_contents);
1193
	
1194
	if (!$g['booting'])
1195
		conf_mount_ro();
1196
}
1197

    
1198
function upnp_action ($action) {
1199
	switch($action) {
1200
		case "start":
1201
			if(file_exists('/var/etc/miniupnpd.conf'))
1202
				mwexec_bg('/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf');
1203
			break;
1204
		case "stop":
1205
			while((int)exec("pgrep miniupnpd | wc -l") > 0)
1206
				mwexec('killall miniupnpd 2>/dev/null', true);
1207
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
1208
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
1209
			break;
1210
		case "restart":
1211
			upnp_action('stop');
1212
			upnp_action('start');
1213
			break;
1214
	}
1215
}
1216

    
1217
function upnp_start() {
1218
	global $config, $g;
1219
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1220
		if($g['booting']) {
1221
			echo "Starting UPnP service... ";
1222
			include('/usr/local/pkg/miniupnpd.inc');
1223
			sync_package_miniupnpd();
1224
			echo "done.\n";
1225
		}
1226
		else {
1227
			upnp_action('start');
1228
		}
1229
	}
1230
}
1231

    
1232
?>
(27-27/37)