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
			$int = guess_interface_from_ip($dhcpifconf['failover_peerip']);
147
			$intip = find_interface_ip($int);
148
			$real_dhcpif = convert_friendly_interface_to_real_interface_name($dhcpif);
149
			/*
150
			 *    yep, failover peer is defined.
151
			 *    does it match up to a defined vip?
152
			 */
153
			$skew = 110;
154
			$a_vip = &$config['virtualip']['vip'];
155
			if(is_array($a_vip)) {
156
				foreach ($a_vip as $vipent) {
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
		//--rebind-localhost-ok
621
		mwexec("/usr/local/sbin/dnsmasq  --stop-dns-rebind --local-ttl 1 --all-servers --dns-forward-max=5000 --cache-size=10000 {$args}");
622

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

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

    
632
	return $return;
633
}
634

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

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

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

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

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

    
659

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

    
665
EOD;
666

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

    
673
EOD;
674
		}
675
*/
676

    
677

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

    
685

    
686
EOD;
687
		}
688

    
689

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

    
697
EOD;
698

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

    
704
EOD;
705
		}
706
*/
707

    
708

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

    
715
EOD;
716
		}
717

    
718

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

    
722
EOD;
723

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

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

    
734
EOD;
735

    
736
		}
737

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

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

    
747
snmpEnableAuthenTraps = 2
748

    
749
EOD;
750

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

    
756
EOD;
757
		    }
758

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

    
765
EOD;
766
		    }
767

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

    
772
EOD;
773
		    }
774

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

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

    
786

    
787
EOD;
788
		    }
789
		}
790

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

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

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

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

    
806
	return 0;
807
}
808

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

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

    
824
			/* determine interface name */
825
			$if = get_real_interface($dnsupdate['interface']);
826
			$wanip = get_interface_ip($dnsupdate['interface']);
827
			if ($wanip) {
828

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

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

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

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

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

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

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

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

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

    
891
	return 0;
892
}
893

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

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

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

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

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

    
938
DebugLevel	2
939

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

    
942
IpVersion	4
943

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

    
946
ClearScreen     yes
947

    
948
{$enableannounce}
949

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

    
955
AllowNoInt	yes
956

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

    
961
#TosValue	16
962

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

    
968
#Willingness    	4
969

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

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

    
979
     MaxConnections  0
980

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

    
985
     Host            127.0.0.1
986
     #Host            10.0.0.5
987

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

    
992
     #Net             192.168.1.0 255.255.255.0
993
}
994

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

    
1000
UseHysteresis	no
1001

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

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

    
1015

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

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

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

    
1027
LinkQualityWinSize	10
1028

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

    
1032
Pollrate	0.05
1033

    
1034

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

    
1045
TcRedundancy	2
1046

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

    
1056
MprCoverage	3
1057

    
1058
# Example plugin entry with parameters:
1059

    
1060
EODA;
1061

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

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

    
1071
EODB;
1072

    
1073
}
1074

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

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

    
1083
EODC;
1084

    
1085
}
1086

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

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

    
1092
	$olsr .= <<<EODE
1093

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

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

    
1110
EODE;
1111

    
1112
}
1113

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

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

    
1125
    # HELLO validity time
1126
    HelloValidityTime	20.0
1127

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

    
1131
    # TC validity time
1132
    TcValidityTime	30.0
1133

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

    
1137
    # MID validity time
1138
    MidValidityTime	30.0
1139

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

    
1143
    # HNA validity time
1144
    HnaValidityTime 	30.0
1145

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

    
1154
    # Weight 0
1155

    
1156

    
1157
}
1158

    
1159
EODAD;
1160

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

    
1168
	if(is_process_running("olsrd"))
1169
		mwexec("/usr/bin/killall olsrd", true);
1170

    
1171
	sleep(2);
1172

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

    
1175
	conf_mount_ro();
1176
}
1177

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

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

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

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

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

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

    
1262
?>
(36-36/50)