Project

General

Profile

Download (33 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	services.inc
5
	part of the pfSense project (http://www.pfsense.com)
6

    
7
	originally part of m0n0wall (http://m0n0.ch/wall)
8
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
9
	All rights reserved.
10

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

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

    
17
	2. Redistributions in binary form must reproduce the above copyright
18
	   notice, this list of conditions and the following disclaimer in the
19
	   documentation and/or other materials provided with the distribution.
20

    
21
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
22
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
23
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
25
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
	POSSIBILITY OF SUCH DAMAGE.
31
*/
32

    
33
/*
34
	pfSense_BUILDER_BINARIES:	/usr/bin/killall	/bin/sh	/usr/local/sbin/dhcpd	/usr/local/sbin/igmpproxy
35
	pfSense_BUILDER_BINARIES:	/sbin/ifconfig	/usr/sbin/arp	/sbin/ifconfig	/usr/local/sbin/dnsmasq
36
	pfSense_BUILDER_BINARIES:	/usr/sbin/bsnmpd	/sbin/route	/usr/local/sbin/olsrd
37
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/miniupnpd	
38
	pfSense_MODULE:	utils
39
*/
40

    
41
function services_dhcpd_configure() {
42
	global $config, $g;
43
	
44
	if($g['services_dhcp_server_enable'] == false) 
45
		return;
46

    
47
	if(isset($config['system']['developerspew'])) {
48
		$mt = microtime();
49
		echo "services_dhcpd_configure($if) being called $mt\n";
50
	}
51
	
52
	/* kill any running dhcpd */
53
	if(is_process_running("dhcpd"))
54
		mwexec("killall dhcpd", true);
55

    
56
	/* DHCP enabled on any interfaces? */
57
	if (!is_dhcp_server_enabled())
58
		return 0;
59

    
60
	/* if OLSRD is enabled, allow WAN to house DHCP. */
61
	if($config['installedpackages']['olsrd'])
62
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd)
63
				if($olsrd['enable'])
64
					$is_olsr_enabled = true;
65

    
66
	/* configure DHCPD chroot */
67
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh","w");
68
	$status = `mount | grep "{$g['dhcpd_chroot_path']}/dev"`;
69
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}\n");
70
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
71
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
72
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
73
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
74
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");	
75
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
76
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
77
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/run\n");
78
	fwrite($fd, "chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
79
	fwrite($fd, "cp /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
80
	fwrite($fd, "cp /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
81
	fwrite($fd, "chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
82
	if(!trim($status))
83
		fwrite($fd, "mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
84
	fclose($fd);
85
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
86

    
87
	$syscfg = $config['system'];
88
	$dhcpdcfg = $config['dhcpd'];
89
	$Iflist = get_configured_interface_list();
90
		
91
	if ($g['booting'])
92
		echo "Starting DHCP service...";
93
	else
94
		sleep(1);
95

    
96
	/* write dhcpd.conf */
97
	$fd = fopen("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", "w");
98
	if (!$fd) {
99
		printf("Error: cannot open dhcpd.conf in services_dhcpd_configure().\n");
100
		return 1;
101
	}
102

    
103
	$custoptions = "";
104
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {	
105
		if(is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
106
			foreach($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
107
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = text;\n";
108
			}
109
		}
110
	}
111

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

    
126
EOD;
127

    
128
	if(isset($dhcpifconf['alwaysbroadcast'])) 
129
		$dhcpdconf .= "always-broadcast on\n";
130

    
131
	$dhcpdifs = array();
132

    
133
	/*    loop through and determine if we need to setup
134
	 *    failover peer "bleh" entries
135
	 */
136
	$dhcpnum = 0;
137
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
138

    
139
		if (!isset($dhcpifconf['enable']))
140
			continue;
141

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

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

    
191
EOPP;
192
		$dhcpnum++;
193
		}
194
	}
195

    
196
	$dhcpnum = 0;
197

    
198
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
199

    
200
		$ifcfg = $config['interfaces'][$dhcpif];
201

    
202
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif]))
203
			continue;
204
		$ifcfgip = get_interface_ip($dhcpif);
205
		$ifcfgsn = get_interface_subnet($dhcpif);
206
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
207
		$subnetmask = gen_subnet_mask($ifcfgsn);
208

    
209
		if($is_olsr_enabled == true)
210
			if($dhcpifconf['netmask'])
211
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
212

    
213
		$dnscfg = "";
214

    
215
		if ($dhcpifconf['domain']) {
216
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
217
		}
218
		
219
    		if($dhcpifconf['domainsearchlist'] <> "") {
220
			$dnscfg .= "	option domain-search-list \"{$dhcpifconf['domainsearchlist']}\";\n";
221
    		}
222

    
223
		if (isset($dhcpifconf['ddnsupdate'])) {
224
			if($dhcpifconf['ddnsdomain'] <> "") {
225
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
226
			}
227
			$dnscfg .= "	ddns-update-style interim;\n";
228
		}
229

    
230
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
231
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
232
		} else if (isset($config['dnsmasq']['enable'])) {
233
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
234
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
235
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
236
		}
237

    
238
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
239
		$dhcpdconf .= "	pool {\n";
240

    
241
		/* is failover dns setup? */
242
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
243
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
244
			if($dhcpifconf['dnsserver'][1] <> "")
245
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
246
			$dhcpdconf .= ";\n";
247
		}
248

    
249
		if($dhcpifconf['failover_peerip'] <> "")
250
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
251

    
252
		if (isset($dhcpifconf['denyunknown']))
253
		   $dhcpdconf .= "		deny unknown clients;\n";
254

    
255
		if ($dhcpifconf['gateway'])
256
			$routers = $dhcpifconf['gateway'];
257
		else
258
			$routers = $ifcfgip;
259

    
260
		if($dhcpifconf['failover_peerip'] <> "") {
261
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
262
			$dhcpnum++;
263
		}
264

    
265
		$dhcpdconf .= <<<EOD
266
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
267
	}
268
	option routers {$routers};
269
$dnscfg
270

    
271
EOD;
272
    
273
		// default-lease-time
274
		if ($dhcpifconf['defaultleasetime'])
275
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
276

    
277
		// max-lease-time
278
		if ($dhcpifconf['maxleasetime'])
279
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
280

    
281
		// netbios-name*
282
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
283
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
284
			$dhcpdconf .= "	option netbios-node-type 8;\n";
285
		}
286

    
287
		// ntp-servers
288
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0])
289
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
290

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

    
295
		// Handle option, number rowhelper values
296
		$dhcpdconf .= "\n";
297
		if($dhcpifconf['numberoptions']['item']) {
298
			foreach($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
299
				$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item['value']}\";\n";
300
			}
301
		}
302

    
303
		// ldap-server
304
		if ($dhcpifconf['ldap'] <> "")
305
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
306

    
307
		// net boot information
308
		if(isset($dhcpifconf['netboot'])) {
309
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
310
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
311
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
312
			}
313
			if ($dhcpifconf['rootpath'] <> "") {
314
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
315
      		}
316
		}
317
		
318
		$dhcpdconf .= <<<EOD
319
}
320

    
321
EOD;
322

    
323
		/* add static mappings */
324
		if (is_array($dhcpifconf['staticmap'])) {
325

    
326
			$i = 0;
327
			foreach ($dhcpifconf['staticmap'] as $sm) {
328
				$dhcpdconf .= <<<EOD
329
host s_{$dhcpif}_{$i} {
330
	hardware ethernet {$sm['mac']};
331

    
332
EOD;
333
				if ($sm['ipaddr'])
334
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
335

    
336
				if ($sm['hostname']) {
337
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
338
					$dhhostname = str_replace(".", "_", $dhhostname);
339
					$dhcpdconf .= "	option host-name {$dhhostname};\n";
340
				}
341

    
342
				$dhcpdconf .= "}\n";
343
				$i++;
344
			}
345
		}
346

    
347
		$dhcpdifs[] = get_real_interface($dhcpif);
348
	}
349

    
350
	fwrite($fd, $dhcpdconf);
351
	fclose($fd);
352

    
353
	/* create an empty leases database */
354
	touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
355
	touch("{$g['varrun_path']}/dhcpd.pid");
356
	
357

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

    
362
	if ($g['booting']) {
363
		print "done.\n";
364
	}
365

    
366
	return 0;
367
}
368

    
369
function services_igmpproxy_configure() {
370
        global $config, $g;
371

    
372
        $iflist = get_configured_interface_list();
373

    
374
        /* kill any running igmpproxy */
375
        killbyname("igmpproxy");
376

    
377
	if (!is_array($config['igmpproxy']['igmpentry']))
378
		return 1;
379

    
380
        $igmpconf = <<<EOD
381

    
382
##------------------------------------------------------
383
## Enable Quickleave mode (Sends Leave instantly)
384
##------------------------------------------------------
385
quickleave
386

    
387
EOD;
388

    
389
        foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
390
                unset($iflist[$igmpcf['ifname']]);
391
                $realif = get_real_interface($igmpcf['ifname']);
392
                if (empty($igmpcf['threshold']))
393
                        $threshld = 1;
394
                else
395
                        $threshld = $igmpcf['threshold'];
396
                $igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
397

    
398
                if ($igmpcf['address'] <> "") {
399
                        $item = explode(" ", $igmpcf['address']);
400
                        foreach($item as $iww)
401
                                $igmpconf .= "altnet {$iww}\n";
402
                }
403
                $igmpconf .= "\n";
404
        }
405
        foreach ($iflist as $ifn) {
406
                $realif = get_real_interface($ifn);
407
                $igmpconf .= "phyint {$realif} disabled\n";
408
        }
409

    
410
        $igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w");
411
        if (!$igmpfl) {
412
                log_error("Could not write Igmpproxy configuration file!");
413
                return;
414
        }
415
        fwrite($igmpfl, $igmpconf);
416
        fclose($igmpfl);
417

    
418
        mwexec("/usr/local/sbin/igmpproxy -c " . $g['tmp_path'] . "/igmpproxy.conf");
419
        log_error("Started Igmpproxy service sucsesfully.");
420

    
421
        return 0;
422
}
423

    
424
function interfaces_staticarp_configure($if) {
425
	global $config, $g;
426
	if(isset($config['system']['developerspew'])) {
427
		$mt = microtime();
428
		echo "interfaces_staticarp_configure($if) being called $mt\n";
429
	}
430

    
431
        $ifcfg = $config['interfaces'][$if];
432

    
433
        /* Enable staticarp, if enabled */
434
        if(isset($config['dhcpd'][$if]['staticarp'])) {
435
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
436
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
437
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
438

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

    
442
                        }
443

    
444
                }
445
        } else {
446
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
447
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
448
        }
449

    
450
        return 0;
451
}
452

    
453
function services_dhcrelay_configure() {
454
	global $config, $g;
455
	if(isset($config['system']['developerspew'])) {
456
		$mt = microtime();
457
		echo "services_dhcrelay_configure() being called $mt\n";
458
	}
459

    
460
	/* kill any running dhcrelay */
461
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
462

    
463
	$dhcrelaycfg = $config['dhcrelay'];
464

    
465
	/* DHCPRelay enabled on any interfaces? */
466
	$dhcrelayenable = false;
467
	if(is_array($dhcrelaycfg)) {
468
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
469
			if (isset($dhcrelayifconf['enable']) &&
470
				(($dhcrelayif == "lan") ||
471
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
472
				$config['interfaces'][$dhcrelayif]['if'] && (!link_interface_to_bridge($dhcrelayif)))))
473
				$dhcrelayenable = true;
474
		}
475
	}
476

    
477
	if (!$dhcrelayenable)
478
		return 0;
479

    
480
	if ($g['booting'])
481
		echo "Starting DHCP relay service...";
482
	else
483
		sleep(1);
484

    
485
	$dhcrelayifs = array();
486
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
487

    
488
		$ifcfg = $config['interfaces'][$dhcrelayif];
489

    
490
		if (!isset($dhcrelayifconf['enable']) ||
491
			(($dhcrelayif != "lan") &&
492
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || 
493
			link_interface_to_bridge($dhcrelayif))))
494
			continue;
495

    
496
		$dhcrelayifs[] = get_real_interface($dhcrelayif);
497
	}
498

    
499
	/* In order for the relay to work, it needs to be active on the
500
	   interface in which the destination server sits */
501
	$iflist = get_configured_interface_list();
502
	foreach ($iflist as $ifname) {
503
		$subnet = get_interface_ip($ifname) . "/" . get_interface_subnet($ifname);
504
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
505
			$destif = get_real_interface($ifname);
506
	}
507

    
508
	if (!isset($destif))
509
		$destif = $config['interfaces']['wan']['if'];
510

    
511
	$dhcrelayifs[] = $destif;
512
	$dhcrelayifs = array_unique($dhcrelayifs);
513

    
514
	/* fire up dhcrelay */
515
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
516

    
517
	if (isset($dhcrelaycfg['agentoption']))
518
		$cmd .=  " -a -m replace";
519

    
520
	$cmd .= " {$dhcrelaycfg['server']}";
521
	mwexec($cmd);
522

    
523
	return 0;
524
}
525

    
526
function services_dyndns_configure_client($conf) {
527

    
528
	if (!isset($conf['enable']))
529
		continue;
530

    
531
	/* load up the dyndns.class */
532
	require_once("dyndns.class");
533

    
534
	log_error("DynDns: Running updatedns()");
535

    
536
	$dns = new updatedns($dnsService = $conf['type'],
537
		$dnsHost = $conf['host'],
538
		$dnsUser = $conf['username'],
539
		$dnsPass = $conf['password'],
540
		$dnsWilcard = $conf['wildcard'],
541
		$dnsMX = $conf['mx'], 
542
		$dnsIf = "{$conf['interface']}");
543

    
544
}
545

    
546
function services_dyndns_configure($int = "") {
547
	global $config, $g;
548
	if(isset($config['system']['developerspew'])) {
549
		$mt = microtime();
550
		echo "services_dyndns_configure() being called $mt\n";
551
	}
552

    
553
	$dyndnscfg = $config['dyndnses']['dyndns'];
554

    
555
	if (is_array($dyndnscfg)) {
556
		if ($g['booting']) 
557
			echo "Starting DynDNS clients...";
558

    
559
		foreach ($dyndnscfg as $dyndns) {
560
			if (!empty($int) && $int != $dyndns['interface'])
561
				continue;
562

    
563
			services_dyndns_configure_client($dyndns);
564

    
565
			sleep(1);
566

    
567
			if (!empty($int))
568
				break;
569
		}
570

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

    
575
	return 0;
576
}
577

    
578
function services_dnsmasq_configure() {
579
	global $config, $g;
580
	$return = 0;
581
	
582
	if(isset($config['system']['developerspew'])) {
583
		$mt = microtime();
584
		echo "services_dnsmasq_configure() being called $mt\n";
585
	}
586

    
587
	/* kill any running dnsmasq */
588
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
589

    
590
	if (isset($config['dnsmasq']['enable'])) {
591

    
592
		if ($g['booting'])
593
			echo "Starting DNS forwarder...";
594
		else
595
			sleep(1);
596

    
597
		/* generate hosts file */
598
		if(system_hosts_generate()!=0)
599
			$return = 1;
600

    
601
		$args = "";
602

    
603
		if (isset($config['dnsmasq']['regdhcp'])) {
604
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
605
		}
606

    
607
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
608
			foreach($config['dnsmasq']['domainoverrides'] as $override) {
609
			        $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
610
			}
611
		}
612

    
613
		/* suppose that dnsmasq handles our domain and don't send
614
		requests for our local domain to upstream servers */
615
		//if (!empty($config['system']['domain'])) {
616
		//	$args .= sprintf(' --local=/%s/', $config['system']['domain']);
617
		//}
618

    
619
		/* run dnsmasq */
620
		mwexec("/usr/local/sbin/dnsmasq --local-ttl 1 --all-servers --dns-forward-max=5000 --cache-size=10000 {$args}");
621

    
622
		if ($g['booting'])
623
			echo "done.\n";
624
	}
625

    
626
	if (!$g['booting']) {
627
		if(services_dhcpd_configure()!=0)
628
			$return = 1;
629
	}
630

    
631
	return $return;
632
}
633

    
634
function services_snmpd_configure() {
635
	global $config, $g;
636
	if(isset($config['system']['developerspew'])) {
637
		$mt = microtime();
638
		echo "services_snmpd_configure() being called $mt\n";
639
	}
640

    
641
	/* kill any running snmpd */
642
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
643
	if(is_process_running("bsnmpd")) 
644
		mwexec("/usr/bin/killall bsnmpd", true);
645

    
646
	if (isset($config['snmpd']['enable'])) {
647

    
648
		if ($g['booting'])
649
			echo "Starting SNMP daemon... ";
650

    
651
		/* generate snmpd.conf */
652
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
653
		if (!$fd) {
654
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
655
			return 1;
656
		}
657

    
658

    
659
		$snmpdconf = <<<EOD
660
location := "{$config['snmpd']['syslocation']}"
661
contact := "{$config['snmpd']['syscontact']}"
662
read := "{$config['snmpd']['rocommunity']}"
663

    
664
EOD;
665

    
666
/* No docs on what write strings do there for disable for now.
667
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
668
		    $snmpdconf .= <<<EOD
669
# write string
670
write := "{$config['snmpd']['rwcommunity']}"
671

    
672
EOD;
673
		}
674
*/
675

    
676

    
677
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
678
		    $snmpdconf .= <<<EOD
679
# SNMP Trap support.
680
traphost := {$config['snmpd']['trapserver']}
681
trapport := {$config['snmpd']['trapserverport']}
682
trap := "{$config['snmpd']['trapstring']}"
683

    
684

    
685
EOD;
686
		}
687

    
688

    
689
		$snmpdconf .= <<<EOD
690
system := 1     # pfSense
691
%snmpd
692
begemotSnmpdDebugDumpPdus       = 2
693
begemotSnmpdDebugSyslogPri      = 7
694
begemotSnmpdCommunityString.0.1 = $(read)
695

    
696
EOD;
697

    
698
/* No docs on what write strings do there for disable for now.
699
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
700
		    $snmpdconf .= <<<EOD
701
begemotSnmpdCommunityString.0.2 = $(write)
702

    
703
EOD;
704
		}
705
*/
706

    
707

    
708
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
709
		    $snmpdconf .= <<<EOD
710
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
711
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
712
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
713

    
714
EOD;
715
		}
716

    
717

    
718
		$snmpdconf .= <<<EOD
719
begemotSnmpdCommunityDisable    = 1
720

    
721
EOD;
722

    
723
		if(isset($config['snmpd']['bindlan'])) {
724
			$bind_to_ip = get_interface_ip("lan");
725
		} else {
726
			$bind_to_ip = "0.0.0.0";
727
		}
728

    
729
		if(is_port( $config['snmpd']['pollport'] )) {
730
		    $snmpdconf .= <<<EOD
731
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
732

    
733
EOD;
734

    
735
		}
736

    
737
		$snmpdconf .= <<<EOD
738
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
739
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
740

    
741
# These are bsnmp macros not php vars.
742
sysContact      = $(contact)
743
sysLocation     = $(location)
744
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
745

    
746
snmpEnableAuthenTraps = 2
747

    
748
EOD;
749

    
750
		if (is_array( $config['snmpd']['modules'] )) {
751
		    if(isset($config['snmpd']['modules']['mibii'])) {
752
			$snmpdconf .= <<<EOD
753
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
754

    
755
EOD;
756
		    }
757

    
758
		    if(isset($config['snmpd']['modules']['netgraph'])) {
759
			$snmpdconf .= <<<EOD
760
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
761
%netgraph
762
begemotNgControlNodeName = "snmpd"
763

    
764
EOD;
765
		    }
766

    
767
		    if(isset($config['snmpd']['modules']['pf'])) {
768
			$snmpdconf .= <<<EOD
769
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
770

    
771
EOD;
772
		    }
773

    
774
		    if(isset($config['snmpd']['modules']['hostres'])) {
775
			$snmpdconf .= <<<EOD
776
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
777

    
778
EOD;
779
		    }
780
		    if(isset($config['snmpd']['modules']['bridge'])) {
781
			$snmpdconf .= <<<EOD
782
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
783
# config must end with blank line
784

    
785

    
786
EOD;
787
		    }
788
		}
789

    
790
		fwrite($fd, $snmpdconf);
791
		fclose($fd);
792

    
793
		if (isset($config['snmpd']['bindlan'])) {
794
			$bindlan = "";
795
		}
796

    
797
		/* run bsnmpd */
798
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
799
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
800

    
801
		if ($g['booting'])
802
			echo "done.\n";
803
	}
804

    
805
	return 0;
806
}
807

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

    
815
	/* Dynamic DNS updating active? */
816
	if (is_array($config['dnsupdates']['dnsupdate'])) {
817
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
818
			if (!isset($dnsupdate['enable']))
819
				continue;
820
			if (!empty($int) && $int != $dnsupdate['interface'])
821
				continue;
822

    
823
			/* determine interface name */
824
			$if = get_real_interface($dnsupdate['interface']);
825
			$wanip = get_interface_ip($dnsupdate['interface']);
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{$i}{$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", true);
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
	conf_mount_ro();
1221
}
1222

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

    
1242
function upnp_start() {
1243
	global $config, $g;
1244

    
1245
	if(!isset($config['installedpackages']['miniupnpd']['config']))
1246
		return;
1247

    
1248
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1249
		if($g['booting']) {
1250
			echo "Starting UPnP service... ";
1251
			require_once('/usr/local/pkg/miniupnpd.inc');
1252
			sync_package_miniupnpd();
1253
			echo "done.\n";
1254
		}
1255
		else {
1256
			upnp_action('start');
1257
		}
1258
	}
1259
}
1260

    
1261
?>
(36-36/50)