Project

General

Profile

Download (31.7 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 = "wan" ) {
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
	$dyndnscfg = $config['dyndnses']['dyndns'];
446

    
447
        if (is_array($dyndnscfg)) {
448
                foreach ($dyndnscfg as $dyndns) {
449
                        if (!isset($dyndns['enable']))
450
                                continue;
451
			if ($dyndns['interface'] != $interface)
452
				continue;
453

    
454
                        services_dyndns_configure_client($dyndns);
455

    
456
                        sleep(1);
457
                }
458

    
459
        }
460

    
461
	return 0;
462
}
463

    
464
function services_dyndns_configure_client($conf) {
465

    
466
	/* determine interface name */
467
	$if = get_real_interface($conf['interface']);
468

    
469
	/* load up the dyndns.class */
470
	require_once("dyndns.class");
471

    
472
	log_error("DynDns: Running updatedns()");
473

    
474
	$dns = new updatedns($dnsService = $conf['type'],
475
		$dnsHost = $conf['host'],
476
		$dnsUser = $conf['username'],
477
		$dnsPass = $conf['password'],
478
		$dnsWilcard = $conf['wildcard'],
479
		$dnsMX = $conf['mx'], $dnsIf = "{$if}");
480

    
481
}
482

    
483
function services_dyndns_configure() {
484
	global $config, $g;
485
	if(isset($config['system']['developerspew'])) {
486
		$mt = microtime();
487
		echo "services_dyndns_configure() being called $mt\n";
488
	}
489

    
490
	$dyndnscfg = $config['dyndnses']['dyndns'];
491

    
492
	if (is_array($dyndnscfg)) {
493
		if ($g['booting']) 
494
			echo "Starting DynDNS clients...";
495

    
496
		foreach ($dyndnscfg as $dyndns) {
497
			if (!isset($dyndns['enable']))
498
				continue;
499

    
500
			services_dyndns_configure_client($dyndns);
501

    
502
			sleep(1);
503
		}
504

    
505
		if ($g['booting'])
506
			echo "done.\n";
507
	}
508

    
509
	return 0;
510
}
511

    
512
function services_dnsmasq_configure() {
513
	global $config, $g;
514
	$return = 0;
515
	
516
	if(isset($config['system']['developerspew'])) {
517
		$mt = microtime();
518
		echo "services_dnsmasq_configure() being called $mt\n";
519
	}
520

    
521
	/* kill any running dnsmasq */
522
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
523

    
524
	if (isset($config['dnsmasq']['enable'])) {
525

    
526
		if ($g['booting'])
527
			echo "Starting DNS forwarder...";
528
		else
529
			sleep(1);
530

    
531
		/* generate hosts file */
532
		if(system_hosts_generate()!=0)
533
			$return = 1;
534

    
535
		$args = "";
536

    
537
		if (isset($config['dnsmasq']['regdhcp'])) {
538

    
539
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
540
				" -s {$config['system']['domain']}";
541
		}
542

    
543
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
544
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
545
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
546
                        }
547
                }
548

    
549
		/* suppose that dnsmasq handles our domain and don't send
550
		requests for our local domain to upstream servers */
551
		//if (!empty($config['system']['domain'])) {
552
		//	$args .= sprintf(' --local=/%s/', $config['system']['domain']);
553
		//}
554

    
555
		/* run dnsmasq */
556
		mwexec("/usr/local/sbin/dnsmasq --cache-size=5000 {$args}");
557

    
558
		if ($g['booting'])
559
			echo "done.\n";
560
	}
561

    
562
	if (!$g['booting']) {
563
		if(services_dhcpd_configure()!=0)
564
			$return = 1;
565
	}
566

    
567
	return $return;
568
}
569

    
570
function services_snmpd_configure() {
571
	global $config, $g;
572
	if(isset($config['system']['developerspew'])) {
573
		$mt = microtime();
574
		echo "services_snmpd_configure() being called $mt\n";
575
	}
576

    
577
	/* kill any running snmpd */
578
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
579
	if(is_process_running("bsnmpd")) 
580
		mwexec("/usr/bin/killall bsnmpd", true);
581

    
582
	if (isset($config['snmpd']['enable'])) {
583

    
584
		if ($g['booting'])
585
			echo "Starting SNMP daemon... ";
586

    
587
		/* generate snmpd.conf */
588
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
589
		if (!$fd) {
590
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
591
			return 1;
592
		}
593

    
594

    
595
		$snmpdconf = <<<EOD
596
location := "{$config['snmpd']['syslocation']}"
597
contact := "{$config['snmpd']['syscontact']}"
598
read := "{$config['snmpd']['rocommunity']}"
599

    
600
EOD;
601

    
602
/* No docs on what write strings do there for disable for now.
603
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
604
		    $snmpdconf .= <<<EOD
605
# write string
606
write := "{$config['snmpd']['rwcommunity']}"
607

    
608
EOD;
609
		}
610
*/
611

    
612

    
613
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
614
		    $snmpdconf .= <<<EOD
615
# SNMP Trap support.
616
traphost := {$config['snmpd']['trapserver']}
617
trapport := {$config['snmpd']['trapserverport']}
618
trap := "{$config['snmpd']['trapstring']}"
619

    
620

    
621
EOD;
622
		}
623

    
624

    
625
		$snmpdconf .= <<<EOD
626
system := 1     # pfSense
627
%snmpd
628
begemotSnmpdDebugDumpPdus       = 2
629
begemotSnmpdDebugSyslogPri      = 7
630
begemotSnmpdCommunityString.0.1 = $(read)
631

    
632
EOD;
633

    
634
/* No docs on what write strings do there for disable for now.
635
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
636
		    $snmpdconf .= <<<EOD
637
begemotSnmpdCommunityString.0.2 = $(write)
638

    
639
EOD;
640
		}
641
*/
642

    
643

    
644
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
645
		    $snmpdconf .= <<<EOD
646
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
647
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
648
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
649

    
650
EOD;
651
		}
652

    
653

    
654
		$snmpdconf .= <<<EOD
655
begemotSnmpdCommunityDisable    = 1
656

    
657
EOD;
658

    
659
		if(isset($config['snmpd']['bindlan'])) {
660
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
661
		} else {
662
			$bind_to_ip = "0.0.0.0";
663
		}
664

    
665
		if(is_port( $config['snmpd']['pollport'] )) {
666
		    $snmpdconf .= <<<EOD
667
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
668

    
669
EOD;
670

    
671
		}
672

    
673
		$snmpdconf .= <<<EOD
674
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
675
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
676

    
677
# These are bsnmp macros not php vars.
678
sysContact      = $(contact)
679
sysLocation     = $(location)
680
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
681

    
682
snmpEnableAuthenTraps = 2
683

    
684
EOD;
685

    
686
		if (is_array( $config['snmpd']['modules'] )) {
687
		    if(isset($config['snmpd']['modules']['mibii'])) {
688
			$snmpdconf .= <<<EOD
689
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
690

    
691
EOD;
692
		    }
693

    
694
		    if(isset($config['snmpd']['modules']['netgraph'])) {
695
			$snmpdconf .= <<<EOD
696
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
697
%netgraph
698
begemotNgControlNodeName = "snmpd"
699

    
700
EOD;
701
		    }
702

    
703
		    if(isset($config['snmpd']['modules']['pf'])) {
704
			$snmpdconf .= <<<EOD
705
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
706

    
707
EOD;
708
		    }
709

    
710
		    if(isset($config['snmpd']['modules']['hostres'])) {
711
			$snmpdconf .= <<<EOD
712
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
713

    
714
EOD;
715
		    }
716
		    if(isset($config['snmpd']['modules']['bridge'])) {
717
			$snmpdconf .= <<<EOD
718
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
719
# config must end with blank line
720

    
721

    
722
EOD;
723
		    }
724
		}
725

    
726
		fwrite($fd, $snmpdconf);
727
		fclose($fd);
728

    
729
		if (isset($config['snmpd']['bindlan'])) {
730
			$bindlan = "";
731
		}
732

    
733
		/* run bsnmpd */
734
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
735
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
736

    
737
		if ($g['booting'])
738
			echo "done.\n";
739
	}
740

    
741
	return 0;
742
}
743

    
744
function services_proxyarp_configure() {
745
	global $config, $g;
746
	if(isset($config['system']['developerspew'])) {
747
		$mt = microtime();
748
		echo "services_proxyarp_configure() being called $mt\n";
749
	}
750

    
751
	/* kill any running choparp */
752
	killbyname("choparp");
753

    
754
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
755
		$paa = array();
756

    
757
		/* group by interface */
758
		foreach ($config['virtualip']['vip'] as $vipent) {
759
			if ($vipent['mode'] === "proxyarp") {
760
				if ($vipent['interface'])
761
					$if = $vipent['interface'];
762
				else
763
					$if = "wan";
764

    
765
				if (!is_array($paa[$if]))
766
					$paa[$if] = array();
767

    
768
				$paa[$if][] = $vipent;
769
			}
770
		}
771

    
772
		if (count($paa))
773
		foreach ($paa as $paif => $paents) {
774
			if (!(is_ipaddr($config['interfaces'][$paif]['ipaddr'])))
775
                               continue;
776

    
777
			$args = $config['interfaces'][$paif]['if'] . " auto";
778

    
779
			foreach ($paents as $paent) {
780

    
781
				if (isset($paent['subnet']))
782
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
783
				else if (isset($paent['range']))
784
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
785
						$paent['range']['to']);
786
			}
787

    
788
			mwexec_bg("/usr/local/sbin/choparp " . $args);
789
		}
790
	}
791
}
792

    
793
function services_dnsupdate_process() {
794
	global $config, $g;
795
	if(isset($config['system']['developerspew'])) {
796
		$mt = microtime();
797
		echo "services_dnsupdate_process() being called $mt\n";
798
	}
799

    
800
	/* Dynamic DNS updating active? */
801
	if (is_array($config['dnsupdates']['dnsupdate'])) {
802
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
803
		if (!isset($dyndns['enable']))
804
				continue;
805
			/* determine interface name */
806
			if ($dyndns['interface'] == "wan")
807
				$if = get_real_interface();
808
			else
809
				$if = convert_friendly_interface_to_real_interface_name($dyndns['interface']);
810

    
811
			$wanip = get_interface_ip($if);
812
			if ($wanip) {
813

    
814
				$keyname = $dnsupdate['keyname'];
815
				/* trailing dot */
816
				if (substr($keyname, -1) != ".")
817
					$keyname .= ".";
818

    
819
				$hostname = $dnsupdate['host'];
820
				/* trailing dot */
821
				if (substr($hostname, -1) != ".")
822
					$hostname .= ".";
823

    
824
				/* write private key file
825
				   this is dumb - public and private keys are the same for HMAC-MD5,
826
				   but nsupdate insists on having both */
827
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
828
				$privkey .= <<<EOD
829
Private-key-format: v1.2
830
Algorithm: 157 (HMAC)
831
Key: {$dnsupdate['keydata']}
832

    
833
EOD;
834
				fwrite($fd, $privkey);
835
				fclose($fd);
836

    
837
				/* write public key file */
838
				if ($dnsupdate['keytype'] == "zone") {
839
					$flags = 257;
840
					$proto = 3;
841
				} else if ($dnsupdate['keytype'] == "host") {
842
					$flags = 513;
843
					$proto = 3;
844
				} else if ($dnsupdate['keytype'] == "user") {
845
					$flags = 0;
846
					$proto = 2;
847
				}
848

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

    
853
				/* generate update instructions */
854
				$upinst = "";
855
				if (!empty($dnsupdate['server']))
856
					$upinst .= "server {$dnsupdate['server']}\n";
857
				$upinst .= "update delete {$dnsupdate['host']} A\n";
858
				$upinst .= "update add {$dnsupdate['host']} {$dnsupdate['ttl']} A {$wanip}\n";
859
				$upinst .= "\n";	/* mind that trailing newline! */
860

    
861
				$fd = fopen("{$g['varetc_path']}/nsupdatecmds{$i}", "w");
862
				fwrite($fd, $upinst);
863
				fclose($fd);
864

    
865
				/* invoke nsupdate */
866
				$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
867
				if (isset($dnsupdate['usetcp']))
868
					$cmd .= " -v";
869
				$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
870
	
871
				mwexec_bg($cmd);
872
			}
873
		}
874
	}
875

    
876
	return 0;
877
}
878

    
879
function setup_wireless_olsr() {
880
	global $config, $g;
881
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
882
		return;
883
	if(isset($config['system']['developerspew'])) {
884
		$mt = microtime();
885
		echo "setup_wireless_olsr($interface) being called $mt\n";
886
	}
887
	conf_mount_rw();
888
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
889
		$olsr_enable = $olsrd['enable'];
890
		if($olsr_enable <> "on")
891
			return;
892
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
893

    
894
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
895
			$enableannounce .= "\nHna4\n";
896
			$enableannounce .= "{\n";
897
		if($olsrd['announcedynamicroute'])
898
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
899
		if($olsrd['enableannounce'] == "on")
900
			$enableannounce .= "0.0.0.0 0.0.0.0";
901
			$enableannounce .= "\n}\n";
902
		} else {
903
			$enableannounce = "";
904
		}
905

    
906
		$olsr .= <<<EODA
907
#
908
# olsr.org OLSR daemon config file
909
#
910
# Lines starting with a # are discarded
911
#
912
# This file was generated by setup_wireless_olsr() in services.inc
913
#
914

    
915
# This file is an example of a typical
916
# configuration for a mostly static
917
# network(regarding mobility) using
918
# the LQ extention
919

    
920
# Debug level(0-9)
921
# If set to 0 the daemon runs in the background
922

    
923
DebugLevel	2
924

    
925
# IP version to use (4 or 6)
926

    
927
IpVersion	4
928

    
929
# Clear the screen each time the internal state changes
930

    
931
ClearScreen     yes
932

    
933
{$enableannounce}
934

    
935
# Should olsrd keep on running even if there are
936
# no interfaces available? This is a good idea
937
# for a PCMCIA/USB hotswap environment.
938
# "yes" OR "no"
939

    
940
AllowNoInt	yes
941

    
942
# TOS(type of service) value for
943
# the IP header of control traffic.
944
# If not set it will default to 16
945

    
946
#TosValue	16
947

    
948
# The fixed willingness to use(0-7)
949
# If not set willingness will be calculated
950
# dynamically based on battery/power status
951
# if such information is available
952

    
953
#Willingness    	4
954

    
955
# Allow processes like the GUI front-end
956
# to connect to the daemon.
957

    
958
IpcConnect
959
{
960
     # Determines how many simultaneously
961
     # IPC connections that will be allowed
962
     # Setting this to 0 disables IPC
963

    
964
     MaxConnections  0
965

    
966
     # By default only 127.0.0.1 is allowed
967
     # to connect. Here allowed hosts can
968
     # be added
969

    
970
     Host            127.0.0.1
971
     #Host            10.0.0.5
972

    
973
     # You can also specify entire net-ranges
974
     # that are allowed to connect. Multiple
975
     # entries are allowed
976

    
977
     #Net             192.168.1.0 255.255.255.0
978
}
979

    
980
# Wether to use hysteresis or not
981
# Hysteresis adds more robustness to the
982
# link sensing but delays neighbor registration.
983
# Used by default. 'yes' or 'no'
984

    
985
UseHysteresis	no
986

    
987
# Hysteresis parameters
988
# Do not alter these unless you know
989
# what you are doing!
990
# Set to auto by default. Allowed
991
# values are floating point values
992
# in the interval 0,1
993
# THR_LOW must always be lower than
994
# THR_HIGH.
995

    
996
#HystScaling	0.50
997
#HystThrHigh	0.80
998
#HystThrLow	0.30
999

    
1000

    
1001
# Link quality level
1002
# 0 = do not use link quality
1003
# 1 = use link quality for MPR selection
1004
# 2 = use link quality for MPR selection and routing
1005
# Defaults to 0
1006

    
1007
LinkQualityLevel	{$olsrd['enablelqe']}
1008

    
1009
# Link quality window size
1010
# Defaults to 10
1011

    
1012
LinkQualityWinSize	10
1013

    
1014
# Polling rate in seconds(float).
1015
# Default value 0.05 sec
1016

    
1017
Pollrate	0.05
1018

    
1019

    
1020
# TC redundancy
1021
# Specifies how much neighbor info should
1022
# be sent in TC messages
1023
# Possible values are:
1024
# 0 - only send MPR selectors
1025
# 1 - send MPR selectors and MPRs
1026
# 2 - send all neighbors
1027
#
1028
# defaults to 0
1029

    
1030
TcRedundancy	2
1031

    
1032
#
1033
# MPR coverage
1034
# Specifies how many MPRs a node should
1035
# try select to reach every 2 hop neighbor
1036
#
1037
# Can be set to any integer >0
1038
#
1039
# defaults to 1
1040

    
1041
MprCoverage	3
1042

    
1043
# Example plugin entry with parameters:
1044

    
1045
EODA;
1046

    
1047
if($olsrd['enablehttpinfo'] == "on") {
1048
	$olsr .= <<<EODB
1049

    
1050
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1051
{
1052
    PlParam     "port"   "{$olsrd['port']}"
1053
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1054
}
1055

    
1056
EODB;
1057

    
1058
}
1059

    
1060
if($olsrd['enabledsecure'] == "on") {
1061
	$olsr .= <<<EODC
1062

    
1063
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1064
{
1065
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1066
}
1067

    
1068
EODC;
1069

    
1070
}
1071

    
1072
if($olsrd['enabledyngw'] == "on") {
1073

    
1074
	/* unset default route, olsr auto negotiates */
1075
	mwexec("/sbin/route delete default");
1076

    
1077
	$olsr .= <<<EODE
1078

    
1079
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1080
{
1081
    # how often to look for a inet gw, in seconds
1082
    # defaults to 5 secs, if commented out
1083
    PlParam     "Interval"   "{$olsrd['polling']}"
1084

    
1085
    # if one or more IPv4 addresses are given, do a ping on these in
1086
    # descending order to validate that there is not only an entry in
1087
    # routing table, but also a real internet connection. If any of
1088
    # these addresses could be pinged successfully, the test was
1089
    # succesful, i.e. if the ping on the 1st address was successful,the
1090
    # 2nd won't be pinged
1091
    PlParam     "Ping"       "{$olsrd['ping']}"
1092
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1093
}
1094

    
1095
EODE;
1096

    
1097
}
1098

    
1099
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1100
	$interfaces = explode(',', $conf['iface_array']);
1101
	foreach($interfaces as $interface) {
1102
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1103
$olsr .= <<<EODAD
1104
Interface "{$realinterface}"
1105
{
1106

    
1107
    # Hello interval in seconds(float)
1108
    HelloInterval    2.0
1109

    
1110
    # HELLO validity time
1111
    HelloValidityTime	20.0
1112

    
1113
    # TC interval in seconds(float)
1114
    TcInterval        5.0
1115

    
1116
    # TC validity time
1117
    TcValidityTime	30.0
1118

    
1119
    # MID interval in seconds(float)
1120
    MidInterval	5.0
1121

    
1122
    # MID validity time
1123
    MidValidityTime	30.0
1124

    
1125
    # HNA interval in seconds(float)
1126
    HnaInterval	5.0
1127

    
1128
    # HNA validity time
1129
    HnaValidityTime 	30.0
1130

    
1131
    # When multiple links exist between hosts
1132
    # the weight of interface is used to determine
1133
    # the link to use. Normally the weight is
1134
    # automatically calculated by olsrd based
1135
    # on the characteristics of the interface,
1136
    # but here you can specify a fixed value.
1137
    # Olsrd will choose links with the lowest value.
1138

    
1139
    # Weight 0
1140

    
1141

    
1142
}
1143

    
1144
EODAD;
1145

    
1146
	}
1147
	break;
1148
}
1149
		fwrite($fd, $olsr);
1150
		fclose($fd);
1151
	}
1152

    
1153
	if(is_process_running("olsrd"))
1154
		mwexec("/usr/bin/killall olsrd", true);
1155

    
1156
	sleep(2);
1157

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

    
1160
	conf_mount_ro();
1161
}
1162

    
1163
/* configure cron service */
1164
function configure_cron() {
1165
	global $g, $config;
1166
	conf_mount_rw();
1167
	/* preserve existing crontab entries */
1168
	$crontab_contents = file_get_contents("/etc/crontab");
1169
	$crontab_contents_a = split("\n", $crontab_contents);
1170
	
1171
	for ($i = 0; $i < count($crontab_contents_a); $i++) {
1172
		$item =& $crontab_contents_a[$i];
1173
		if (strpos($item, "# pfSense specific crontab entries") !== false) {
1174
			array_splice($crontab_contents_a, $i - 1);
1175
			break;
1176
		}
1177
	}
1178
	$crontab_contents = implode("\n", $crontab_contents_a) . "\n";
1179
	
1180
	
1181
	if (is_array($config['cron']['item'])) {
1182
		$crontab_contents .= "#\n";
1183
		$crontab_contents .= "# pfSense specific crontab entries\n";
1184
		$crontab_contents .= "# Created: " . date("F j, Y, g:i a") . "\n";
1185
		$crontab_contents .= "#\n";
1186

    
1187
		foreach ($config['cron']['item'] as $item) {
1188
			$crontab_contents .= "\n{$item['minute']}\t";
1189
			$crontab_contents .= "{$item['hour']}\t";
1190
			$crontab_contents .= "{$item['mday']}\t";
1191
			$crontab_contents .= "{$item['month']}\t";
1192
			$crontab_contents .= "{$item['wday']}\t";
1193
			$crontab_contents .= "{$item['who']}\t";
1194
			$crontab_contents .= "{$item['command']}";
1195
		}
1196
    
1197
		$crontab_contents .= "\n#\n";
1198
		$crontab_contents .= "# If possible do not add items to this file manually.\n";
1199
		$crontab_contents .= "# If you do so, this file must be terminated with a blank line (e.g. new line)\n";
1200
		$crontab_contents .= "#\n\n";
1201
	}
1202
	
1203
	/* please maintain the newline at the end of file */
1204
	file_put_contents("/etc/crontab", $crontab_contents);
1205
	
1206
	if (!$g['booting'])
1207
		conf_mount_ro();
1208
}
1209

    
1210
function upnp_action ($action) {
1211
	switch($action) {
1212
		case "start":
1213
			if(file_exists('/var/etc/miniupnpd.conf'))
1214
				mwexec_bg('/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf');
1215
			break;
1216
		case "stop":
1217
			while((int)exec("pgrep miniupnpd | wc -l") > 0)
1218
				mwexec('killall miniupnpd 2>/dev/null', true);
1219
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
1220
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
1221
			break;
1222
		case "restart":
1223
			upnp_action('stop');
1224
			upnp_action('start');
1225
			break;
1226
	}
1227
}
1228

    
1229
function upnp_start() {
1230
	global $config, $g;
1231
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1232
		if($g['booting']) {
1233
			echo "Starting UPnP service... ";
1234
			include('/usr/local/pkg/miniupnpd.inc');
1235
			sync_package_miniupnpd();
1236
			echo "done.\n";
1237
		}
1238
		else {
1239
			upnp_action('start');
1240
		}
1241
	}
1242
}
1243

    
1244
?>
(27-27/37)