Project

General

Profile

Download (56.8 KB) Statistics
| Branch: | Tag: | Revision:
1 14227c51 Scott Ullrich
<?php
2 3076becf Scott Ullrich
/****h* pfSense/pfsense-utils
3
 * NAME
4
 *   pfsense-utils.inc - Utilities specific to pfSense
5
 * DESCRIPTION
6
 *   This include contains various pfSense specific functions.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11 69487053 Seth Mos
 * Copyright (C) 2004-2007 Scott Ullrich (sullrich@gmail.com)
12 3076becf Scott Ullrich
 * All rights reserved.
13
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are met:
15
 *
16
 * 1. Redistributions of source code must retain the above copyright notice,
17
 * this list of conditions and the following disclaimer.
18
 *
19
 * 2. Redistributions in binary form must reproduce the above copyright
20
 * notice, this list of conditions and the following disclaimer in the
21
 * documentation and/or other materials provided with the distribution.
22
 *
23
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
25
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 */
35
36 0397013a Scott Ullrich
/****f* pfsense-utils/have_natonetooneruleint_access
37
 * NAME
38
 *   have_natonetooneruleint_access
39
 * INPUTS
40
 *	 none
41
 * RESULT
42
 *   returns true if user has access to edit a specific firewall nat one to one interface
43
 ******/
44
function have_natonetooneruleint_access($if) {
45
	$security_url = "firewall_nat_1to1_edit.php?if=". strtolower($if);
46 45ee90ed Matthew Grooms
	if(isAllowedPage($security_url, $allowed)) 
47 0397013a Scott Ullrich
		return true;
48
	return false;
49
}
50
51
/****f* pfsense-utils/have_natpfruleint_access
52
 * NAME
53
 *   have_natpfruleint_access
54
 * INPUTS
55
 *	 none
56
 * RESULT
57
 *   returns true if user has access to edit a specific firewall nat port forward interface
58
 ******/
59
function have_natpfruleint_access($if) {
60
	$security_url = "firewall_nat_edit.php?if=". strtolower($if);
61 45ee90ed Matthew Grooms
	if(isAllowedPage($security_url, $allowed)) 
62 0397013a Scott Ullrich
		return true;
63
	return false;
64
}
65
66 b6742927 Scott Ullrich
/****f* pfsense-utils/have_ruleint_access
67
 * NAME
68
 *   have_ruleint_access
69
 * INPUTS
70
 *	 none
71
 * RESULT
72
 *   returns true if user has access to edit a specific firewall interface
73
 ******/
74
function have_ruleint_access($if) {
75
	$security_url = "firewall_rules.php?if=". strtolower($if);
76 45ee90ed Matthew Grooms
	if(isAllowedPage($security_url)) 
77
		return true;
78 b6742927 Scott Ullrich
	return false;
79
}
80
81 10387862 Scott Ullrich
/****f* pfsense-utils/does_url_exist
82
 * NAME
83
 *   does_url_exist
84
 * INPUTS
85
 *	 none
86
 * RESULT
87
 *   returns true if a url is available
88
 ******/
89
function does_url_exist($url) {
90 3264c13b Scott Ullrich
	$fd = fopen("$url","r");
91 10387862 Scott Ullrich
	if($fd) {
92 4cc6345e Scott Ullrich
		fclose($fd);
93 10387862 Scott Ullrich
   		return true;    
94
	} else {
95
        return false;
96
	}
97
}
98
99 5928bd75 Scott Ullrich
/****f* pfsense-utils/is_private_ip
100
 * NAME
101
 *   is_private_ip
102
 * INPUTS
103
 *	 none
104
 * RESULT
105
 *   returns true if an ip address is in a private range
106
 ******/
107
function is_private_ip($iptocheck) {
108
        $isprivate = false;
109
        $ip_private_list=array(
110
               "10.0.0.0/8",
111
               "172.16.0.0/12",
112
               "192.168.0.0/16",
113
               "99.0.0.0/8"
114
        );
115
        foreach($ip_private_list as $private) {
116
                if(ip_in_subnet($iptocheck,$private)==true)
117
                        $isprivate = true;
118
        }
119
        return $isprivate;
120
}
121
122 8cb370b9 Scott Ullrich
/****f* pfsense-utils/get_tmp_file
123
 * NAME
124
 *   get_tmp_file
125
 * INPUTS
126
 *	 none
127
 * RESULT
128
 *   returns a temporary filename
129
 ******/
130 3076becf Scott Ullrich
function get_tmp_file() {
131
	return "/tmp/tmp-" . time();
132
}
133
134
/****f* pfsense-utils/find_number_of_needed_carp_interfaces
135
 * NAME
136
 *   find_number_of_needed_carp_interfaces
137
 * INPUTS
138
 *   null
139
 * RESULT
140
 *   the number of needed carp interfacs
141
 ******/
142
function find_number_of_needed_carp_interfaces() {
143
	global $config, $g;
144
	$carp_counter=0;
145
	if(!$config['virtualip'])
146
		return 0;
147
	if(!$config['virtualip']['vip'])
148
		return 0;
149
	foreach($config['virtualip']['vip'] as $vip) {
150
		if($vip['mode'] == "carp")
151
			$carp_counter++;
152
	}
153
	return $carp_counter;
154
}
155
156
/****f* pfsense-utils/reset_carp
157
 * NAME
158
 *   reset_carp - resets carp after primary interface changes
159
 * INPUTS
160
 *   null
161
 * RESULT
162
 *   null
163
 ******/
164
function reset_carp() {
165
	$carp_counter=find_number_of_created_carp_interfaces();
166
	$needed_carp_interfaces = find_number_of_needed_carp_interfaces();
167
	mwexec("/sbin/sysctl net.inet.carp.allow=0");
168
	for($x=0; $x<$carp_counter; $x++) {
169
		mwexec("/sbin/ifconfig carp{$x} down");
170 cf79d727 Scott Ullrich
		usleep(1000);
171 3076becf Scott Ullrich
		mwexec("/sbin/ifconfig carp{$x} delete");
172
		if($needed_carp_interfaces < $carp_counter) {
173
			$needed_carp_interfaces--;
174 4587cb54 Scott Ullrich
			//log_error("Destroying carp interface.");
175
			//mwexec("/sbin/ifconfig carp{$x} destroy");
176 3076becf Scott Ullrich
		}
177
	}
178
	find_number_of_created_carp_interfaces(true);
179
	sleep(1);
180
	mwexec("/sbin/sysctl net.inet.carp.allow=1");
181
	interfaces_carp_configure();
182
}
183
184
/****f* pfsense-utils/get_dns_servers
185
 * NAME
186
 *   get_dns_servres - get system dns servers
187
 * INPUTS
188
 *   $dns_servers - an array of the dns servers
189
 * RESULT
190
 *   null
191
 ******/
192
function get_dns_servers() {
193
	$dns_servers = array();
194
	$dns = `cat /etc/resolv.conf`;
195
	$dns_s = split("\n", $dns);
196
	foreach($dns_s as $dns) {
197
		$matches = "";
198
		if (preg_match("/nameserver (.*)/", $dns, $matches))
199
			$dns_servers[] = $matches[1];
200
	}
201
	$dns_server_master = array();
202
	$lastseen = "";
203
	foreach($dns_servers as $t) {
204
		if($t <> $lastseen)
205
			if($t <> "")
206
				$dns_server_master[] = $t;
207
		$lastseen = $t;
208
	}
209
	return $dns_server_master;
210
}
211
212
/****f* pfsense-utils/enable_hardware_offloading
213
 * NAME
214
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
215
 * INPUTS
216
 *   $interface	- string containing the physical interface to work on.
217
 * RESULT
218
 *   null
219
 * NOTES
220
 *   This function only supports the fxp driver's loadable microcode.
221
 ******/
222
function enable_hardware_offloading($interface) {
223
	global $g, $config;
224
225
	if(stristr($interface,"lnc"))
226 d2eb5def Scott Ullrich
		return;
227 4d98f634 Scott Ullrich
228 3076becf Scott Ullrich
	/* translate wan, lan, opt -> real interface if needed */
229 532b0fb8 Ermal Lu?i
	$int = interface_translate_type_to_real($interface);
230 a7c6604c Chris Buechler
	if($int <> "") $interface = $int;
231 3076becf Scott Ullrich
	$int_family = preg_split("/[0-9]+/", $int);
232 a7c6604c Chris Buechler
	$options = strtolower(`/sbin/ifconfig -m {$interface} | grep capabilities`);
233 3076becf Scott Ullrich
	$supported_ints = array('fxp');
234 a7c6604c Chris Buechler
	if (in_array($int_family, $supported_ints)) {
235
        	if(isset($config['system']['do_not_use_nic_microcode']))
236
                        continue;
237 3076becf Scott Ullrich
		mwexec("/sbin/ifconfig {$interface} link0");
238 a7c6604c Chris Buechler
        }
239 3076becf Scott Ullrich
240 a7c6604c Chris Buechler
	/* skip vlans for checksumming and polling */
241
	if(stristr($interface, "vlan")) 
242 3076becf Scott Ullrich
		return;
243
244 a7c6604c Chris Buechler
	if($config['system']['disablechecksumoffloading']) {
245
                if(stristr($options, "txcsum") == true)
246
                        mwexec("/sbin/ifconfig {$interface} -txcsum 2>/dev/null");
247
                if(stristr($options, "rxcsum") == true)
248
                        mwexec("/sbin/ifconfig {$interface} -rxcsum 2>/dev/null");
249
	} else {
250
               	if(stristr($options, "txcsum") == true)
251
                        mwexec("/sbin/ifconfig {$interface} txcsum 2>/dev/null");
252
        	if(stristr($options, "rxcsum") == true)
253
                        mwexec("/sbin/ifconfig {$interface} rxcsum 2>/dev/null");
254
        }
255 4d98f634 Scott Ullrich
256
	/* if the NIC supports polling *AND* it is enabled in the GUI */
257 f7eb54e4 Scott Ullrich
	if(interface_supports_polling($interface)) {
258 4d98f634 Scott Ullrich
		$polling = isset($config['system']['polling']);	
259
		if($polling) {
260
			mwexec("sysctl kern.polling.enable=1");
261 a7c6604c Chris Buechler
                        mwexec("/sbin/ifconfig {$interface} polling 2>/dev/null");
262 4d98f634 Scott Ullrich
		} else {
263
			mwexec("sysctl kern.polling.enable=0");
264
		}
265 3076becf Scott Ullrich
	}
266
	return;
267
}
268
269 f7eb54e4 Scott Ullrich
/****f* pfsense-utils/interface_supports_polling
270
 * NAME
271
 *   checks to see if an interface supports polling according to man polling
272
 * INPUTS
273
 *
274
 * RESULT
275
 *   true or false
276
 * NOTES
277
 *
278
 ******/
279
function interface_supports_polling($iface) {
280
	$pattern = '/([a-z].*)[0-9]/';
281
	preg_match($pattern, $iface, $iface2);
282
	$interface=$iface2[1];
283
	$supported_ints = array("bge",
284
		"dc",
285
		"em",
286
		"fwe",
287
		"fwip",
288
		"fxp",
289
		"ixgb",
290
		"nfe",
291 56c17018 Scott Ullrich
		"vge",
292 f7eb54e4 Scott Ullrich
		"re",
293
		"rl",
294
		"sf",
295 56c17018 Scott Ullrich
		"sis",
296 f7eb54e4 Scott Ullrich
		"ste",
297 56c17018 Scott Ullrich
		"stge",    
298
		"vge",
299 f7eb54e4 Scott Ullrich
		"vr",
300
		"xl");
301
	if(in_array($interface, $supported_ints))
302
		return true;
303
	return false;
304
}
305
306 3076becf Scott Ullrich
/****f* pfsense-utils/is_alias_inuse
307
 * NAME
308
 *   checks to see if an alias is currently in use by a rule
309
 * INPUTS
310
 *
311
 * RESULT
312
 *   true or false
313
 * NOTES
314
 *
315
 ******/
316
function is_alias_inuse($alias) {
317
	global $g, $config;
318
319
	if($alias == "") return false;
320
	/* loop through firewall rules looking for alias in use */
321 346e2e6b Scott Ullrich
	if(is_array($config['filter']['rule']))
322 3076becf Scott Ullrich
		foreach($config['filter']['rule'] as $rule) {
323 00eee841 Scott Ullrich
			if($rule['source']['address'])
324 3076becf Scott Ullrich
				if($rule['source']['address'] == $alias)
325 0c8c496e Scott Ullrich
					return true;
326 00eee841 Scott Ullrich
			if($rule['destination']['address'])
327 3076becf Scott Ullrich
				if($rule['destination']['address'] == $alias)
328 0c8c496e Scott Ullrich
					return true;
329
		}
330 3076becf Scott Ullrich
	/* loop through nat rules looking for alias in use */
331
	if(is_array($config['nat']['rule']))
332
		foreach($config['nat']['rule'] as $rule) {
333
			if($rule['target'] == $alias)
334
				return true;
335
			if($rule['external-address'] == $alias)
336
				return true;
337
		}
338
	return false;
339
}
340
341 63724b02 Scott Dale
/****f* pfsense-utils/is_schedule_inuse
342
 * NAME
343
 *   checks to see if a schedule is currently in use by a rule
344
 * INPUTS
345
 *
346
 * RESULT
347
 *   true or false
348
 * NOTES
349
 *
350
 ******/
351
function is_schedule_inuse($schedule) {
352
	global $g, $config;
353
354
	if($schedule == "") return false;
355
	/* loop through firewall rules looking for schedule in use */
356
	if(is_array($config['filter']['rule']))
357
		foreach($config['filter']['rule'] as $rule) {
358 591ceb32 Scott Dale
			if($rule['sched'] == $schedule)
359
				return true;
360 63724b02 Scott Dale
		}
361
	return false;
362
}
363
364 3076becf Scott Ullrich
/****f* pfsense-utils/setup_polling_defaults
365
 * NAME
366
 *   sets up sysctls for pollingS
367
 * INPUTS
368
 *
369
 * RESULT
370
 *   null
371
 * NOTES
372
 *
373
 ******/
374
function setup_polling_defaults() {
375
	global $g, $config;
376
	if($config['system']['polling_each_burst'])
377
		mwexec("sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
378
	if($config['system']['polling_burst_max'])
379
		mwexec("sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
380
	if($config['system']['polling_user_frac'])
381
		mwexec("sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");
382
}
383
384
/****f* pfsense-utils/setup_polling
385
 * NAME
386
 *   sets up polling
387
 * INPUTS
388
 *
389
 * RESULT
390
 *   null
391
 * NOTES
392
 *
393
 ******/
394
function setup_polling() {
395
	global $g, $config;
396
397
	setup_polling_defaults();
398
399 eff8869e Chris Buechler
	$supported_ints = array('bge', 'dc', 'em', 'fwe', 'fwip', 'fxp', 'ixgb', 'ste', 'nge', 're', 'rl', 'sf', 'sis', 'ste', 'vge', 'vr', 'xl');
400 3076becf Scott Ullrich
401 3a4ce87d Ermal Luçi
	/* if list */
402 eff8869e Chris Buechler
	$iflist = get_configured_interface_list();
403 3076becf Scott Ullrich
404
	foreach ($iflist as $ifent => $ifname) {
405
		$real_interface = convert_friendly_interface_to_real_interface_name($ifname);
406 eff8869e Chris Buechler
		$ifdevice = substr($real_interface, 0, -1);
407
		if(!in_array($ifdevice, $supported_ints)) {
408 ccaf2def Seth Mos
			continue;
409 eff8869e Chris Buechler
        }
410 ccaf2def Seth Mos
		if(isset($config['system']['polling'])) {
411 3076becf Scott Ullrich
			mwexec("/sbin/ifconfig {$real_interface} polling");
412
		} else {
413
			mwexec("/sbin/ifconfig {$real_interface} -polling");
414
		}
415
	}
416
}
417
418
/****f* pfsense-utils/setup_microcode
419
 * NAME
420
 *   enumerates all interfaces and calls enable_hardware_offloading which
421
 *   enables a NIC's supported hardware features.
422
 * INPUTS
423
 *
424
 * RESULT
425
 *   null
426
 * NOTES
427
 *   This function only supports the fxp driver's loadable microcode.
428
 ******/
429
function setup_microcode() {
430
431 3a4ce87d Ermal Luçi
	/* if list */
432
        $ifdescrs = get_configured_interface_list();
433 e8df4c2f Scott Ullrich
434 3076becf Scott Ullrich
	foreach($ifdescrs as $if)
435
		enable_hardware_offloading($if);
436
}
437
438
/****f* pfsense-utils/get_carp_status
439
 * NAME
440
 *   get_carp_status - Return whether CARP is enabled or disabled.
441
 * RESULT
442
 *   boolean	- true if CARP is enabled, false if otherwise.
443
 ******/
444
function get_carp_status() {
445
    /* grab the current status of carp */
446
    $status = `/sbin/sysctl net.inet.carp.allow | cut -d" " -f2`;
447
    if(intval($status) == "0") return false;
448
    return true;
449
}
450
451
/****f* pfsense-utils/is_carp_defined
452
 * NAME
453
 *   is_carp_defined - Return whether CARP is detected in the kernel.
454
 * RESULT
455
 *   boolean	- true if CARP is detected, false otherwise.
456
 ******/
457
function is_carp_defined() {
458
	/* is carp compiled into the kernel and userland? */
459
	$command = "/sbin/sysctl -a | grep carp";
460
	$fd = popen($command . " 2>&1 ", "r");
461
	if(!$fd) {
462
		log_error("Warning, could not execute command {$command}");
463
		return 0;
464
	}
465
	while(!feof($fd)) {
466
		$tmp .= fread($fd,49);
467
	}
468
	fclose($fd);
469
470
	if($tmp == "")
471
		return false;
472
	else
473
		return true;
474
}
475
476
/****f* pfsense-utils/find_number_of_created_carp_interfaces
477
 * NAME
478
 *   find_number_of_created_carp_interfaces - Return the number of CARP interfaces.
479
 * RESULT
480
 *   $tmp	- Number of currently created CARP interfaces.
481
 ******/
482
function find_number_of_created_carp_interfaces($flush = false) {
483
	global $carp_interface_count_cache;
484
485
	if (!isset($carp_interface_count_cache) or $flush) {
486
		$command = "/sbin/ifconfig | /usr/bin/grep \"carp*:\" | /usr/bin/wc -l";
487 7b2d4769 Bill Marquette
		$fd = popen($command . " 2>&1 ", "r");
488
		if(!$fd) {
489
			log_error("Warning, could not execute command {$command}");
490
			return 0;
491
		}
492
		while(!feof($fd)) {
493
			$tmp .= fread($fd,49);
494
		}
495
		fclose($fd);
496 3076becf Scott Ullrich
		$carp_interface_count_cache = intval($tmp);
497
	}
498
	return $carp_interface_count_cache;
499
}
500
501 357cde41 Scott Ullrich
function link_carp_interface_to_parent($interface) {
502
	global $config;
503
504 e88fbe50 Ermal Lu?i
	if ($interface == "")
505
		return;
506 357cde41 Scott Ullrich
507 037b51b3 Seth Mos
	$carp_ip = find_interface_ip($interface);
508 e88fbe50 Ermal Lu?i
	if (!is_ipaddr($carp_ip))
509
		return;
510 037b51b3 Seth Mos
511 e88fbe50 Ermal Lu?i
	/* if list */
512
        $ifdescrs = get_configured_interface_list();
513 357cde41 Scott Ullrich
	foreach ($ifdescrs as $ifdescr => $ifname) {
514 e88fbe50 Ermal Lu?i
		$interfaceip = get_interface_ip($ifname);
515
		$subnet_bits = get_interface_subnet($ifname);
516
		$subnet_ip = gen_subnet("{$interfaceip}", "{$subnet_bits}");
517
		if(ip_in_subnet($carp_ip, "{$subnet_ip}/{$subnet_bits}"))
518
			return $ifname;
519 357cde41 Scott Ullrich
	}
520 e88fbe50 Ermal Lu?i
521
	return "";
522 357cde41 Scott Ullrich
}
523
524 3076becf Scott Ullrich
/****f* pfsense-utils/link_ip_to_carp_interface
525
 * NAME
526
 *   link_ip_to_carp_interface - Find where a CARP interface links to.
527
 * INPUTS
528
 *   $ip
529
 * RESULT
530
 *   $carp_ints
531
 ******/
532
function link_ip_to_carp_interface($ip) {
533
	global $config;
534
535 e88fbe50 Ermal Lu?i
	if (!is_ipaddr($ip))
536
		return;
537 3076becf Scott Ullrich
538
	$carp_ints = "";
539
	$num_carp_ints = find_number_of_created_carp_interfaces();
540 e88fbe50 Ermal Lu?i
	for ($x=0; $x<$num_carp_ints; $x++) {
541
		$carp_int = "carp{$x}";
542
		$carp_ip = find_interface_ip($carp_int);
543
		$carp_subnet = find_virtual_ip_netmask($carp_ip);
544
		$starting_ip = gen_subnet("{$carp_ip}", "{$carp_subnet}");
545
		if (ip_in_subnet($ip, "{$starting_ip}/{$carp_subnet}"))
546
			if(!stristr($carp_ints, $carp_int))
547
				$carp_ints .= " " . $carp_int;
548 3076becf Scott Ullrich
	}
549 e88fbe50 Ermal Lu?i
	
550 3076becf Scott Ullrich
	return $carp_ints;
551
}
552
553
/****f* pfsense-utils/find_virtual_ip_netmask
554
 * NAME
555
 *   find_virtual_ip_netmask - Finds a virtual ip's subnet mask'
556
 * INPUTS
557
 *   $ip - ip address to locate subnet mask of
558
 * RESULT
559
 *   String containing the command's result.
560
 * NOTES
561
 *   This function returns the command's stdout and stderr.
562
 ******/
563
function find_virtual_ip_netmask($ip) {
564
        global $config;
565
        foreach($config['virtualip']['vip'] as $vip) {
566
                if($ip == $vip['subnet'])
567
                        return $vip['subnet_bits'];
568
        }
569
}
570
571
/*
572
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
573 52947718 Ermal Lu?i
574 3076becf Scott Ullrich
 */
575
function convert_ip_to_network_format($ip, $subnet) {
576
	$ipsplit = split('[.]', $ip);
577
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
578
	return $string;
579
}
580
581
/*
582
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
583
 */
584
function get_carp_interface_status($carpinterface) {
585
	/* basically cache the contents of ifconfig statement
586
	to speed up this routine */
587
	global $carp_query;
588
	if($carp_query == "")
589
	$carp_query = split("\n", `/sbin/ifconfig | /usr/bin/grep carp`);
590
	$found_interface = 0;
591
	foreach($carp_query as $int) {
592
		if($found_interface == 1) {
593
			if(stristr($int, "MASTER")) return "MASTER";
594
			if(stristr($int, "BACKUP")) return "BACKUP";
595
			if(stristr($int, "INIT")) return "INIT";
596 0c8c496e Scott Ullrich
			return false;
597
		}
598 3076becf Scott Ullrich
		if(stristr($int, $carpinterface) == true)
599
		$found_interface=1;
600
	}
601
	return;
602
}
603
604
/*
605
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
606
 */
607
function get_pfsync_interface_status($pfsyncinterface) {
608
    $result = does_interface_exist($pfsyncinterface);
609
    if($result <> true) return;
610
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
611
    return $status;
612
}
613
614
/*
615
 * find_carp_interface($ip): return the carp interface where an ip is defined
616
 */
617
function find_carp_interface($ip) {
618
	global $find_carp_ifconfig;
619
	if($find_carp_ifconfig == "") {
620
		$find_carp_ifconfig = array();
621
		$num_carp_ints = find_number_of_created_carp_interfaces();
622
		for($x=0; $x<$num_carp_ints; $x++) {
623
			$find_carp_ifconfig[$x] = exec_command("/sbin/ifconfig carp{$x}");
624
		}
625
	}
626
	$carps = 0;
627
	foreach($find_carp_ifconfig as $fci) {
628 7e9547cf jim-p
		if(stristr($fci, $ip . " ") == true)
629 3076becf Scott Ullrich
			return "carp{$carps}";
630
		$carps++;
631
	}
632
}
633
634
/*
635
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
636
 */
637
function add_rule_to_anchor($anchor, $rule, $label) {
638
	mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
639
}
640
641
/*
642
 * remove_text_from_file
643
 * remove $text from file $file
644
 */
645
function remove_text_from_file($file, $text) {
646
	global $fd_log;
647
	if($fd_log)
648
		fwrite($fd_log, "Adding needed text items:\n");
649
	$filecontents = file_get_contents($file);
650
	$textTMP = str_replace($text, "", $filecontents);
651
	$text = $textTMP;
652
	if($fd_log)
653
		fwrite($fd_log, $text);
654
	$fd = fopen($file, "w");
655
	fwrite($fd, $text);
656
	fclose($fd);
657
}
658
659
/*
660
 * add_text_to_file($file, $text): adds $text to $file.
661
 * replaces the text if it already exists.
662
 */
663 5a6f3ca0 Scott Ullrich
function add_text_to_file($file, $text, $replace = false) {
664 3076becf Scott Ullrich
	if(file_exists($file) and is_writable($file)) {
665 5a6f3ca0 Scott Ullrich
		$filecontents = file($file);
666 3076becf Scott Ullrich
		$fout = fopen($file, "w");
667 5a6f3ca0 Scott Ullrich
668
		$filecontents = array_map('rtrim', $filecontents);
669
		array_push($filecontents, $text);
670
		if ($replace)
671
			$filecontents = array_unique($filecontents);
672
673
		$file_text = implode("\n", $filecontents);
674
675 3076becf Scott Ullrich
		fwrite($fout, $file_text);
676
		fclose($fout);
677
		return true;
678
	} else {
679
		return false;
680 0c8c496e Scott Ullrich
	}
681 3076becf Scott Ullrich
}
682
683
/*
684
 *   after_sync_bump_adv_skew(): create skew values by 1S
685
 */
686
function after_sync_bump_adv_skew() {
687
	global $config, $g;
688
	$processed_skew = 1;
689
	$a_vip = &$config['virtualip']['vip'];
690
	foreach ($a_vip as $vipent) {
691
		if($vipent['advskew'] <> "") {
692
			$processed_skew = 1;
693
			$vipent['advskew'] = $vipent['advskew']+1;
694
		}
695
	}
696
	if($processed_skew == 1)
697
		write_config("After synch increase advertising skew");
698
}
699
700
/*
701
 * get_filename_from_url($url): converts a url to its filename.
702
 */
703
function get_filename_from_url($url) {
704
	return basename($url);
705
}
706
707
/*
708
 *   update_output_window: update bottom textarea dynamically.
709
 */
710
function update_output_window($text) {
711
	global $pkg_interface;
712
	$log = ereg_replace("\n", "\\n", $text);
713
	if($pkg_interface == "console") {
714
		/* too chatty */
715
	} else {
716
		echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
717
	}
718
	/* ensure that contents are written out */
719
	ob_flush();
720
}
721
722
/*
723
 *   get_dir: return an array of $dir
724
 */
725
function get_dir($dir) {
726
	$dir_array = array();
727
	$d = dir($dir);
728
	while (false !== ($entry = $d->read())) {
729
		array_push($dir_array, $entry);
730
	}
731
	$d->close();
732
	return $dir_array;
733
}
734
735
/*
736
 *   update_output_window: update top textarea dynamically.
737
 */
738
function update_status($status) {
739
	global $pkg_interface;
740
	if($pkg_interface == "console") {
741
		echo $status . "\n";
742
	} else {
743 5fbefa5b Bill Marquette
		echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
744 3076becf Scott Ullrich
	}
745
	/* ensure that contents are written out */
746
	ob_flush();
747
}
748
749
/*
750
 * update_progress_bar($percent): updates the javascript driven progress bar.
751
 */
752
function update_progress_bar($percent) {
753
	global $pkg_interface;
754
	if($percent > 100) $percent = 1;
755
	if($pkg_interface <> "console") {
756
		echo "\n<script type=\"text/javascript\" language=\"javascript\">";
757
		echo "\ndocument.progressbar.style.width='" . $percent . "%';";
758
		echo "\n</script>";
759
	} else {
760
		echo " {$percent}%";
761
	}
762
}
763
764
/****f* pfsense-utils/WakeOnLan
765
 * NAME
766
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
767
 * RESULT
768
 *   true/false - true if the operation was successful
769
 ******/
770
function WakeOnLan($addr, $mac)
771
{
772
	$addr_byte = explode(':', $mac);
773
	$hw_addr = '';
774
775
	for ($a=0; $a < 6; $a++)
776
		$hw_addr .= chr(hexdec($addr_byte[$a]));
777
778
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
779
780
	for ($a = 1; $a <= 16; $a++)
781
		$msg .= $hw_addr;
782
783
	// send it to the broadcast address using UDP
784
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
785
	if ($s == false) {
786
		log_error("Error creating socket!");
787
		log_error("Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s)));
788
	} else {
789
		// setting a broadcast option to socket:
790
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
791
		if($opt_ret < 0)
792
			log_error("setsockopt() failed, error: " . strerror($opt_ret));
793
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
794
		socket_close($s);
795
		log_error("Magic Packet sent ({$e}) to {$addr} MAC={$mac}");
796
		return true;
797 0c8c496e Scott Ullrich
	}
798 3076becf Scott Ullrich
799
	return false;
800
}
801
802
/*
803
 * gather_altq_queue_stats():  gather altq queue stats and return an array that
804
 *                             is queuename|qlength|measured_packets
805
 *                             NOTE: this command takes 5 seconds to run
806
 */
807
function gather_altq_queue_stats($dont_return_root_queues) {
808 f2b8daad Ermal Lu?i
	exec("/sbin/pfctl -vvsq", $stats_array);
809 3076becf Scott Ullrich
	$queue_stats = array();
810
	foreach ($stats_array as $stats_line) {
811
		$match_array = "";
812
		if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
813
			$queue_name = $match_array[1][0];
814
		if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
815
			$speed = $match_array[1][0];
816
		if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
817
			$borrows = $match_array[1][0];
818
		if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
819
			$suspends = $match_array[1][0];
820
		if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
821
			$drops = $match_array[1][0];
822
		if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
823
			$measured = $match_array[1][0];
824
			if($dont_return_root_queues == true)
825
				if(stristr($queue_name,"root_") == false)
826
					array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
827
		}
828
	}
829
	return $queue_stats;
830
}
831
832
/*
833
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
834
 *					 Useful for finding paths and stripping file extensions.
835
 */
836
function reverse_strrchr($haystack, $needle) {
837
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
838
}
839
840
/*
841
 *  backup_config_section($section): returns as an xml file string of
842
 *                                   the configuration section
843
 */
844
function backup_config_section($section) {
845
	global $config;
846
	$new_section = &$config[$section];
847
	/* generate configuration XML */
848
	$xmlconfig = dump_xml_config($new_section, $section);
849
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
850
	return $xmlconfig;
851
}
852
853
/*
854
 *  backup_vip_config_section($section): returns as an xml file string of
855
 *                                   the configuration section
856
 */
857
function backup_vip_config_section() {
858
	global $config;
859
	$new_section = &$config['virtualip'];
860
	foreach($new_section['vip'] as $section) {
861
		if($section['mode'] == "proxyarp") {
862
			unset($section);
863
		}
864
		if($section['advskew'] <> "") {
865
			$section_val = intval($section['advskew']);
866
			$section_val=$section_val+100;
867
			if($section_val > 255)
868
				$section_val = 255;
869
			$section['advskew'] = $section_val;
870
		}
871
		$temp['vip'][] = $section;
872
   }
873
   return $temp;
874
}
875
876
/*
877
 *  restore_config_section($section, new_contents): restore a configuration section,
878
 *                                                  and write the configuration out
879
 *                                                  to disk/cf.
880
 */
881
function restore_config_section($section, $new_contents) {
882
	global $config, $g;
883
	conf_mount_rw();
884
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
885
	fwrite($fout, $new_contents);
886
	fclose($fout);
887
	$section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
888
	$config[$section] = &$section_xml;
889
	unlink($g['tmp_path'] . "/tmpxml");
890
	write_config("Restored {$section} of config file (maybe from CARP partner)");
891
	conf_mount_ro();
892
	return;
893
}
894
895
/*
896
 *  merge_config_section($section, new_contents):   restore a configuration section,
897
 *                                                  and write the configuration out
898
 *                                                  to disk/cf.  But preserve the prior
899
 * 													structure if needed
900
 */
901
function merge_config_section($section, $new_contents) {
902
	global $config;
903
	conf_mount_rw();
904
	$fname = get_tmp_filename();
905
	$fout = fopen($fname, "w");
906
	fwrite($fout, $new_contents);
907
	fclose($fout);
908
	$section_xml = parse_xml_config($fname, $section);
909
	$config[$section] = $section_xml;
910
	unlink($fname);
911
	write_config("Restored {$section} of config file (maybe from CARP partner)");
912
	conf_mount_ro();
913
	return;
914
}
915
916
/*
917
 * http_post($server, $port, $url, $vars): does an http post to a web server
918
 *                                         posting the vars array.
919
 * written by nf@bigpond.net.au
920
 */
921
function http_post($server, $port, $url, $vars) {
922
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
923
	$urlencoded = "";
924
	while (list($key,$value) = each($vars))
925
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
926
	$urlencoded = substr($urlencoded,0,-1);
927
	$content_length = strlen($urlencoded);
928
	$headers = "POST $url HTTP/1.1
929
Accept: */*
930
Accept-Language: en-au
931
Content-Type: application/x-www-form-urlencoded
932
User-Agent: $user_agent
933
Host: $server
934
Connection: Keep-Alive
935
Cache-Control: no-cache
936
Content-Length: $content_length
937
938
";
939
940
	$errno = "";
941
	$errstr = "";
942
	$fp = fsockopen($server, $port, $errno, $errstr);
943
	if (!$fp) {
944 0c8c496e Scott Ullrich
		return false;
945
	}
946 3076becf Scott Ullrich
947
	fputs($fp, $headers);
948
	fputs($fp, $urlencoded);
949
950
	$ret = "";
951
	while (!feof($fp))
952
		$ret.= fgets($fp, 1024);
953
	fclose($fp);
954
955
	return $ret;
956
}
957
958
/*
959
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
960
 */
961
if (!function_exists('php_check_syntax')){
962
	function php_check_syntax($code_to_check, &$errormessage){
963
		return false;
964
		$fout = fopen("/tmp/codetocheck.php","w");
965
		$code = $_POST['content'];
966
		$code = str_replace("<?php", "", $code);
967
		$code = str_replace("?>", "", $code);
968
		fwrite($fout, "<?php\n\n");
969
		fwrite($fout, $code_to_check);
970
		fwrite($fout, "\n\n?>\n");
971 0c8c496e Scott Ullrich
		fclose($fout);
972 3076becf Scott Ullrich
		$command = "/usr/local/bin/php -l /tmp/codetocheck.php";
973
		$output = exec_command($command);
974
		if (stristr($output, "Errors parsing") == false) {
975
			echo "false\n";
976
			$errormessage = '';
977
			return(false);
978
		} else {
979
			$errormessage = $output;
980
			return(true);
981 0c8c496e Scott Ullrich
		}
982
	}
983 3076becf Scott Ullrich
}
984
985
/*
986
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
987
 */
988
if (!function_exists('php_check_syntax')){
989
	function php_check_syntax($code_to_check, &$errormessage){
990
		return false;
991
		$command = "/usr/local/bin/php -l " . $code_to_check;
992
		$output = exec_command($command);
993
		if (stristr($output, "Errors parsing") == false) {
994
			echo "false\n";
995
			$errormessage = '';
996
			return(false);
997
		} else {
998
			$errormessage = $output;
999
			return(true);
1000
		}
1001
	}
1002
}
1003
1004
/*
1005
 * rmdir_recursive($path,$follow_links=false)
1006
 * Recursively remove a directory tree (rm -rf path)
1007
 * This is for directories _only_
1008
 */
1009
function rmdir_recursive($path,$follow_links=false) {
1010
	$to_do = glob($path);
1011
	if(!is_array($to_do)) $to_do = array($to_do);
1012
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
1013
		if(file_exists($workingdir)) {
1014
			if(is_dir($workingdir)) {
1015
				$dir = opendir($workingdir);
1016
				while ($entry = readdir($dir)) {
1017
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
1018
						unlink("$workingdir/$entry");
1019
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
1020
						rmdir_recursive("$workingdir/$entry");
1021 6613a031 Scott Ullrich
				}
1022 3076becf Scott Ullrich
				closedir($dir);
1023
				rmdir($workingdir);
1024
			} elseif (is_file($workingdir)) {
1025
				unlink($workingdir);
1026
			}
1027
               	}
1028
	}
1029
	return;
1030
}
1031
1032
/*
1033
 * call_pfsense_method(): Call a method exposed by the pfsense.com XMLRPC server.
1034
 */
1035
function call_pfsense_method($method, $params, $timeout = 0) {
1036 cfceefc6 Scott Ullrich
	global $g, $config;
1037
1038 36d0358b Scott Ullrich
	$ip = gethostbyname($g['product_website']);
1039
	if($ip == $g['product_website'])
1040 3076becf Scott Ullrich
		return false;
1041
	global $g, $config;
1042
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
1043
	$xmlrpc_path = $g['xmlrpcpath'];
1044
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
1045
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
1046
	$resp = $cli->send($msg, $timeout);
1047
	if(!$resp) {
1048
		log_error("XMLRPC communication error: " . $cli->errstr);
1049
		return false;
1050
	} elseif($resp->faultCode()) {
1051
		log_error("XMLRPC request failed with error " . $resp->faultCode() . ": " . $resp->faultString());
1052
		return false;
1053
	} else {
1054
		return XML_RPC_Decode($resp->value());
1055
	}
1056
}
1057
1058
/*
1059
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1060
 */
1061
function check_firmware_version($tocheck = "all", $return_php = true) {
1062
	global $g, $config;
1063 36d0358b Scott Ullrich
	$ip = gethostbyname($g['product_website']);
1064
	if($ip == $g['product_website'])
1065 3076becf Scott Ullrich
		return false;
1066
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1067
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1068
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1069
		"platform" => trim(file_get_contents('/etc/platform'))
1070
		);
1071
	if($tocheck == "all") {
1072
		$params = $rawparams;
1073
	} else {
1074
		foreach($tocheck as $check) {
1075
			$params['check'] = $rawparams['check'];
1076
			$params['platform'] = $rawparams['platform'];
1077
		}
1078
	}
1079
	if($config['system']['firmware']['branch']) {
1080
		$params['branch'] = $config['system']['firmware']['branch'];
1081
	}
1082
	if(!$versions = call_pfsense_method('pfsense.get_firmware_version', $params)) {
1083
		return false;
1084
	} else {
1085
		$versions["current"] = $params;
1086
	}
1087
	return $versions;
1088
}
1089
1090
function get_disk_info() {
1091
	$diskout = "";
1092
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
1093
	return explode(' ', $diskout[0]);
1094
	// $size, $used, $avail, $cap
1095
}
1096
1097
/****f* pfsense-utils/display_top_tabs
1098
 * NAME
1099
 *   display_top_tabs - display tabs with rounded edges
1100
 * INPUTS
1101 4adfb2df Scott Ullrich
 *   $text      - array of tabs
1102 3076becf Scott Ullrich
 * RESULT
1103
 *   null
1104
 ******/
1105 4adfb2df Scott Ullrich
function display_top_tabs(& $tab_array) {
1106
	global $HTTP_SERVER_VARS;
1107
	global $config;
1108 3aae364d Scott Ullrich
	global $g;
1109 4adfb2df Scott Ullrich
1110 45ee90ed Matthew Grooms
	/*  does the user have access to this tab?
1111
	 *  master user has access to everything.
1112
	 *  if the user does not have access, simply
1113
	 *  unset the tab item.
1114
	 */
1115
1116
	$tab_temp = array ();
1117
	foreach ($tab_array as $ta)
1118
		if(isAllowedPage($ta[2]))
1119
			$tab_temp[] = $ta;
1120
	/*
1121
		// FIXME :	if the checks are not good enough
1122
		//			in isAllowedPage, it needs to be
1123
		//			fixed instead of kludging here
1124
1125
		// TODO: humm what shall we do with pkg_edit.php and pkg.php?
1126
		if ((strpos($link, "pkg.php")) !== false || (strpos($link, "pkg_edit.php")) !== false) {
1127
			$pos_equal = strpos($link, "=");
1128
			$pos_xmlsuffix = strpos($link, ".xml");
1129
			// do we match an absolute url including ?xml= foo
1130
			if(!isAllowedPage($link, $allowed))
1131
				$link = substr($link, $pos_equal +1, ($pos_xmlsuffix - $pos_equal +3));
1132 4adfb2df Scott Ullrich
		}
1133 45ee90ed Matthew Grooms
		// next check - what if the basename contains a query string?
1134
		if ((strpos($link, "?")) !== false) {
1135
			$pos_qmark = strpos($link, "?");
1136
			$link = substr($link, 0, $pos_qmark);
1137
		}
1138
		$authorized_text = print_r($allowed, true);
1139
		if(is_array($authorized))
1140
			if (in_array(basename($link), $authorized))
1141
	*/
1142
1143
	unset ($tab_array);
1144
	$tab_array = & $tab_temp;
1145 4adfb2df Scott Ullrich
1146 fe39586a Scott Ullrich
	$tab_active_bg   = "#EEEEEE";
1147
	$tab_inactive_bg = "#777777";
1148
	$nifty_tabs_corners = "#FFF";
1149
	$font_color = "white";
1150
	
1151
	/* if tabcontrols.php exist for a theme, allow it to be overriden */
1152
	$themename = $config['theme'];
1153
	$filename = "/usr/local/www/themes/{$themename}/tabcontrols.php";
1154 37f36cda Scott Ullrich
	if(file_exists($filename)) {
1155
		$eval_code = file_get_contents($filename);
1156
		eval($eval_code);
1157
	}
1158
	
1159 4316a60a Scott Ullrich
	$tabcharcount = 0;
1160
	foreach ($tab_array as $ta) 
1161
		$tabcharcount = $tabcharcount + strlen($ta[0]);
1162
1163 53b67506 Scott Ullrich
	// If the character count of the tab names is > 670
1164 4316a60a Scott Ullrich
	// then show a select item dropdown menubox.
1165 d4e6c445 Scott Ullrich
	if($tabcharcount > 82) {
1166 4316a60a Scott Ullrich
		echo "Currently viewing: ";
1167
		echo "<select name='TabSelect'>\n";
1168
		foreach ($tab_array as $ta) {
1169
			if($ta[1]=="true")	
1170
				$selected = " SELECTED";
1171
			else 
1172
				$selected = "";
1173
			echo "<option onClick=\"document.location='{$ta[2]}';\"{$selected}>{$ta['0']}</option>\n";
1174
		}
1175
		echo "</select>\n<p/>";
1176
	}  else {
1177
		echo "<table cellpadding='0' cellspacing='0'>\n";
1178
		echo " <tr>\n";
1179
		$tabscounter = 0;
1180
		foreach ($tab_array as $ta) {
1181
			if ($ta[1] == true) {
1182
				echo "  <td bgcolor='{$tab_active_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"><div id='tabactive'></div></td>\n";
1183
			} else {
1184
				echo "  <td bgcolor='{$tab_inactive_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
1185
			}
1186
			$tabscounter++;
1187
		}
1188
		echo "</tr>\n<tr>\n";
1189
		foreach ($tab_array as $ta) {
1190
			if ($ta[1] == true) {
1191
				echo "  <td height=\"15\" valign=\"middle\" bgcolor='{$tab_active_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
1192
				echo "&nbsp;&nbsp;&nbsp;";
1193
				echo "<font size='-12'>&nbsp;</font></B></td>\n";
1194
			} else {
1195
				echo "  <td height=\"15\" valign=\"middle\" bgcolor='{$tab_inactive_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"><B>&nbsp;&nbsp;&nbsp;<a href='{$ta[2]}'>";
1196
				echo "<font color='{$font_color}'>{$ta[0]}</font></a>&nbsp;&nbsp;&nbsp;";
1197
				echo "<font size='-12'>&nbsp;</font></B></td>\n";
1198
			}
1199 0c8c496e Scott Ullrich
		}
1200 4316a60a Scott Ullrich
		echo "</tr>\n<tr>\n";
1201
		foreach ($tab_array as $ta) {
1202
			if ($ta[1] == true) {
1203
				echo "  <td bgcolor='{$tab_active_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"></td>\n";
1204
			} else {
1205
				echo "  <td bgcolor='{$tab_inactive_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"></td>\n";
1206
			}
1207
			$tabscounter++;
1208 3076becf Scott Ullrich
		}
1209 4316a60a Scott Ullrich
		echo " </tr>\n";
1210
		echo "</table>\n";
1211
		echo "<script type=\"text/javascript\">";
1212
		echo "NiftyCheck();\n";
1213
		echo "Rounded(\"div#tabactive\",\"top\",\"{$nifty_tabs_corners}\",\"{$tab_active_bg}\",\"smooth\");\n";
1214
		for ($x = 0; $x < $tabscounter; $x++)
1215
			echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"{$nifty_tabs_corners}\",\"{$tab_inactive_bg}\",\"smooth\");\n";
1216
		echo "</script>";
1217 3076becf Scott Ullrich
	}
1218
}
1219
1220
1221
/****f* pfsense-utils/display_topbar
1222
 * NAME
1223
 *   display_topbar - top a table off with rounded edges
1224
 * INPUTS
1225
 *   $text	- (optional) Text to include in bar
1226
 * RESULT
1227
 *   null
1228
 ******/
1229
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {
1230
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1231
	echo "       <tr height='1'>\n";
1232
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1233
	echo "		<div id='topbar'></div></td>\n";
1234
	echo "       </tr>\n";
1235
	echo "       <tr height='1'>\n";
1236
	if ($text != "")
1237
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1238
	else
1239
		echo "         <td height='1' class='listtopic'></td>\n";
1240
	echo "       </tr>\n";
1241
	echo "     </table>";
1242
	echo "<script type=\"text/javascript\">";
1243
	echo "NiftyCheck();\n";
1244
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1245
	echo "</script>";
1246
}
1247
1248
/****f* pfsense-utils/strncpy
1249
 * NAME
1250
 *   strncpy - copy strings
1251
 * INPUTS
1252
 *   &$dst, $src, $length
1253
 * RESULT
1254
 *   none
1255
 ******/
1256
function strncpy(&$dst, $src, $length) {
1257
	if (strlen($src) > $length) {
1258
		$dst = substr($src, 0, $length);
1259
	} else {
1260
		$dst = $src;
1261
	}
1262
}
1263
1264
/****f* pfsense-utils/reload_interfaces_sync
1265
 * NAME
1266
 *   reload_interfaces - reload all interfaces
1267
 * INPUTS
1268
 *   none
1269
 * RESULT
1270
 *   none
1271
 ******/
1272
function reload_interfaces_sync() {
1273 c0836064 Ermal Luçi
	global $config, $g;
1274 3076becf Scott Ullrich
1275
	$shutdown_webgui_needed = false;
1276
1277
	touch("{$g['tmp_path']}/reloading_all");
1278
1279 c0836064 Ermal Luçi
	if($g['debug'])
1280 3076becf Scott Ullrich
		log_error("reload_interfaces_sync() is starting.");
1281
1282
	if(file_exists("{$g['tmp_path']}/config.cache"))
1283
		unlink("{$g['tmp_path']}/config.cache");
1284
1285
	/* parse config.xml again */
1286
	$config = parse_config(true);
1287
1288
	$wan_if = $config['interfaces']['wan']['if'];
1289 c0836064 Ermal Luçi
	if (isset($config['interfaces']['lan']))
1290
                $lan_if = $config['interfaces']['lan']['if'];
1291
        else
1292
                $lan_if = "";
1293 3076becf Scott Ullrich
1294 c0836064 Ermal Luçi
	if($g['debug'])
1295 3076becf Scott Ullrich
		log_error("Cleaning up Interfaces");
1296
1297 3a4ce87d Ermal Luçi
	/* if list */
1298 67ee1ec5 Ermal Luçi
        $iflist = get_configured_interface_list(true);
1299 3076becf Scott Ullrich
1300
	foreach ($iflist as $ifent => $ifname) {
1301
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1302 3a4ce87d Ermal Luçi
1303 3076becf Scott Ullrich
		if(stristr($ifname, "lo0") == true)
1304
			continue;
1305
		/* do not process wan interface, its mandatory */
1306 67ee1ec5 Ermal Luçi
                if(stristr($ifname, "$wan_if") == true)
1307
                        continue;
1308
                /* do not process lan interface, its mandatory */
1309
                if(stristr($ifname, "$lan_if") == true)
1310
                        continue;
1311 c0836064 Ermal Luçi
		if($g['debug'])
1312 3076becf Scott Ullrich
			log_error("Downing and deleting $ifname_real - $ifname");
1313
		mwexec("/sbin/ifconfig {$ifname_real} down");
1314
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1315
	}
1316
1317 67ee1ec5 Ermal Luçi
	/* set up interfaces */
1318
	interfaces_configure();
1319 3076becf Scott Ullrich
1320
	/* set up static routes */
1321 c0836064 Ermal Luçi
	if($g['debug'])
1322 3076becf Scott Ullrich
		log_error("Configuring system Routing");
1323
	system_routing_configure();
1324
1325
	/* enable routing */
1326 c0836064 Ermal Luçi
	if($g['debug'])
1327 3076becf Scott Ullrich
		log_error("Enabling system routing");
1328
	system_routing_enable();
1329
1330
	/* setup captive portal if needed */
1331 c0836064 Ermal Luçi
	if($g['debug'])
1332 3076becf Scott Ullrich
		log_error("Configuring Captive portal");
1333
	captiveportal_configure();
1334
1335
	/* restart webConfigurator if needed */
1336
	if($shutdown_webgui_needed == true)
1337
		touch("/tmp/restart_webgui");
1338
1339
	/* start devd back up */
1340
	mwexec("/bin/rm /tmp/reload*");
1341
1342
	/* remove reloading_all trigger */
1343 c0836064 Ermal Luçi
	if($g['debug'])
1344 3076becf Scott Ullrich
		log_error("Removing {$g['tmp_path']}/reloading_all");
1345
	unlink_if_exists("{$g['tmp_path']}/reloading_all");
1346
}
1347
1348
/****f* pfsense-utils/reload_all
1349
 * NAME
1350
 *   reload_all - triggers a reload of all settings
1351
 *   * INPUTS
1352
 *   none
1353
 * RESULT
1354
 *   none
1355
 ******/
1356
function reload_all() {
1357
	touch("/tmp/reload_all");
1358
}
1359
1360
/****f* pfsense-utils/reload_interfaces
1361
 * NAME
1362
 *   reload_interfaces - triggers a reload of all interfaces
1363
 * INPUTS
1364
 *   none
1365
 * RESULT
1366
 *   none
1367
 ******/
1368
function reload_interfaces() {
1369
	touch("/tmp/reload_interfaces");
1370
}
1371
1372
/****f* pfsense-utils/reload_all_sync
1373
 * NAME
1374
 *   reload_all - reload all settings
1375
 *   * INPUTS
1376
 *   none
1377
 * RESULT
1378
 *   none
1379
 ******/
1380
function reload_all_sync() {
1381
	global $config, $g;
1382
1383
	$g['booting'] = false;
1384
1385
	touch("{$g['tmp_path']}/reloading_all");
1386
1387
	$shutdown_webgui_needed = false;
1388
1389
	if(file_exists("{$g['tmp_path']}/config.cache"))
1390
		unlink("{$g['tmp_path']}/config.cache");
1391
1392
	/* parse config.xml again */
1393
	$config = parse_config(true);
1394
1395
	/* set up our timezone */
1396
	system_timezone_configure();
1397
1398
	/* set up our hostname */
1399
	system_hostname_configure();
1400
1401
	/* make hosts file */
1402
	system_hosts_generate();
1403
1404
	/* generate resolv.conf */
1405
	system_resolvconf_generate();
1406
1407 ae84328e Seth Mos
	/* Set up our loopback interface */
1408
	interfaces_loopback_configure();
1409
1410 3076becf Scott Ullrich
	$wan_if = $config['interfaces']['wan']['if'];
1411 c0836064 Ermal Luçi
	if (isset($config['interfaces']['lan']))
1412
		$lan_if = $config['interfaces']['lan']['if'];
1413
	else
1414
		$lan_if = "";
1415 3076becf Scott Ullrich
1416 3a4ce87d Ermal Luçi
	/* if list */
1417
	$iflist = get_configured_interface_list();
1418 3076becf Scott Ullrich
1419
	foreach ($iflist as $ifent => $ifname) {
1420
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1421
		if(stristr($ifname, "lo0") == true)
1422
			continue;
1423
		/* do not process wan interface, its mandatory */
1424
		if($wan_if == $ifname_real)
1425
			continue;
1426
		/* do not process lan interface, its mandatory */
1427
		if($lan_if == $ifname_real)
1428
			continue;
1429
		mwexec("/sbin/ifconfig {$ifname_real} down");
1430
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1431
	}
1432
1433 67ee1ec5 Ermal Luçi
	/* set up interfaces */
1434
	interfaces_configure();
1435 3076becf Scott Ullrich
1436
	/* set up static routes */
1437
	system_routing_configure();
1438
1439
	/* enable routing */
1440
	system_routing_enable();
1441
1442
	/* ensure passwords are sync'd */
1443 659fa7f2 Matthew Grooms
//	system_password_configure();
1444 3076becf Scott Ullrich
1445
	/* start dnsmasq service */
1446
	services_dnsmasq_configure();
1447
1448
	/* start dyndns service */
1449
	services_dyndns_configure();
1450
1451
	/* start DHCP service */
1452
	services_dhcpd_configure();
1453
1454
	/* configure cron service */
1455
	configure_cron();
1456
1457
	/* start the NTP client */
1458
	system_ntp_configure();
1459
1460
	/* start the captive portal */
1461
	captiveportal_configure();
1462
1463
        /* reload the filter */
1464
	filter_configure_sync();
1465
1466
	/* sync pw database */
1467
	conf_mount_rw();
1468
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1469
	conf_mount_ro();
1470
1471
	/* restart sshd */
1472
	touch("/tmp/start_sshd");
1473
1474
	/* restart webConfigurator if needed */
1475
	if($shutdown_webgui_needed == true)
1476
		touch("/tmp/restart_webgui");
1477
1478
	mwexec("/bin/rm /tmp/reload*");
1479
1480
	unlink_if_exists("{$g['tmp_path']}/reloading_all");
1481
1482
}
1483
1484
function auto_login($status) {
1485
	$gettytab = file_get_contents("/etc/gettytab");
1486
	$getty_split = split("\n", $gettytab);
1487
	conf_mount_rw();
1488
	$fd = fopen("/etc/gettytab", "w");
1489
	foreach($getty_split as $gs) {
1490
		if(stristr($gs, ":ht:np:sp#115200") ) {
1491
			if($status == true) {
1492
				fwrite($fd, "	:ht:np:sp#115200:al=root:\n");
1493
			} else {
1494
				fwrite($fd, "	:ht:np:sp#115200:\n");
1495 ca8e4ed2 Scott Ullrich
			}
1496 0c8c496e Scott Ullrich
		} else {
1497 3076becf Scott Ullrich
			fwrite($fd, "{$gs}\n");
1498
		}
1499
	}
1500
	fclose($fd);
1501
	conf_mount_ro();
1502
}
1503
1504
function setup_serial_port() {
1505
	global $g, $config;
1506
	conf_mount_rw();
1507
	/* serial console - write out /boot.config */
1508
	if(file_exists("/boot.config"))
1509
		$boot_config = file_get_contents("/boot.config");
1510
	else
1511
		$boot_config = "";
1512
1513
	if($g['platform'] <> "cdrom") {
1514
		$boot_config_split = split("\n", $boot_config);
1515
		$fd = fopen("/boot.config","w");
1516
		if($fd) {
1517
			foreach($boot_config_split as $bcs) {
1518
				if(stristr($bcs, "-D")) {
1519
					/* DONT WRITE OUT, WE'LL DO IT LATER */
1520
				} else {
1521
					if($bcs <> "")
1522
						fwrite($fd, "{$bcs}\n");
1523
				}
1524 0c8c496e Scott Ullrich
			}
1525 3076becf Scott Ullrich
			if(isset($config['system']['enableserial'])) {
1526
				fwrite($fd, "-D");
1527 0c8c496e Scott Ullrich
			}
1528 3076becf Scott Ullrich
			fclose($fd);
1529 0c8c496e Scott Ullrich
		}
1530 3076becf Scott Ullrich
		/* serial console - write out /boot/loader.conf */
1531
		$boot_config = file_get_contents("/boot/loader.conf");
1532
		$boot_config_split = split("\n", $boot_config);
1533
		$fd = fopen("/boot/loader.conf","w");
1534
		if($fd) {
1535
			foreach($boot_config_split as $bcs) {
1536
				if(stristr($bcs, "console")) {
1537
					/* DONT WRITE OUT, WE'LL DO IT LATER */
1538
				} else {
1539
					if($bcs <> "")
1540
						fwrite($fd, "{$bcs}\n");
1541
				}
1542 0c8c496e Scott Ullrich
			}
1543 3076becf Scott Ullrich
			if(isset($config['system']['enableserial'])) {
1544
				fwrite($fd, "console=\"comconsole\"\n");
1545 ca8e4ed2 Scott Ullrich
			}
1546 3076becf Scott Ullrich
			fclose($fd);
1547 0c8c496e Scott Ullrich
		}
1548
	}
1549 3076becf Scott Ullrich
	$ttys = file_get_contents("/etc/ttys");
1550
	$ttys_split = split("\n", $ttys);
1551
	$fd = fopen("/etc/ttys", "w");
1552
	foreach($ttys_split as $tty) {
1553
		if(stristr($tty, "ttyd0")) {
1554
			if(isset($config['system']['enableserial'])) {
1555
				fwrite($fd, "ttyd0	\"/usr/libexec/getty bootupcli\"	dialup	on	secure\n");
1556
			} else {
1557
				fwrite($fd, "ttyd0	\"/usr/libexec/getty bootupcli\"	dialup	off	secure\n");
1558 ca8e4ed2 Scott Ullrich
			}
1559 3076becf Scott Ullrich
		} else {
1560
			fwrite($fd, $tty . "\n");
1561
		}
1562
	}
1563
	fclose($fd);
1564
	if(isset($config['system']['disableconsolemenu'])) {
1565
		auto_login(false);
1566
	} else {
1567
		auto_login(true);
1568
	}
1569
	conf_mount_ro();
1570
	return;
1571
}
1572
1573
function print_value_list($list, $count = 10, $separator = ",") {
1574
	$list = implode($separator, array_slice($list, 0, $count));
1575
	if(count($list) < $count) {
1576
		$list .= ".";
1577
	} else {
1578
		$list .= "...";
1579
	}
1580
	return $list;
1581
}
1582
1583 bfe776f0 Ermal Luçi
/* DHCP enabled on any interfaces? */
1584
function is_dhcp_server_enabled() 
1585
{
1586 db9fabf3 Ermal Luçi
	global $config;
1587 bfe776f0 Ermal Luçi
1588 3076becf Scott Ullrich
	$dhcpdenable = false;
1589 bfe776f0 Ermal Luçi
	
1590
	if (!is_array($config['dhcpd']))
1591
		return false;
1592
1593 db9fabf3 Ermal Luçi
	$Iflist = get_configured_interface_list();
1594
1595 bfe776f0 Ermal Luçi
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1596 db9fabf3 Ermal Luçi
		if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1597 3076becf Scott Ullrich
			$dhcpdenable = true;
1598 db9fabf3 Ermal Luçi
			break;
1599
		}
1600 3076becf Scott Ullrich
	}
1601 bfe776f0 Ermal Luçi
1602 3076becf Scott Ullrich
	return $dhcpdenable;
1603
}
1604
1605 fab7ff44 Bill Marquette
/****f* pfsense-utils/isAjax
1606
 * NAME
1607
 *   isAjax - reports if the request is driven from prototype
1608
 * INPUTS
1609
 *   none
1610
 * RESULT
1611
 *   true/false
1612
 ******/
1613
function isAjax() {
1614
	return isset ($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
1615
}
1616
1617 6189988d Scott Dale
//returns interface information
1618
function get_interface_info($ifdescr) {
1619
	global $config, $linkinfo, $netstatrninfo;
1620
1621
	$ifinfo = array();
1622 67ee1ec5 Ermal Luçi
	/* if list */
1623
	$iflist = get_configured_interface_with_descr(false,true);
1624
	
1625
	$found = false;
1626
    	foreach ($iflist as $if => $ifname) {
1627
    	if ($ifdescr == $if || $ifdescr == $ifname) {
1628
			$ifinfo['hwif'] = $config['interfaces'][$if]['if'];
1629 85a5da13 Ermal Luçi
			$ifinfo['if'] = get_real_interface($if);
1630 67ee1ec5 Ermal Luçi
			$found = true;
1631
			break;
1632
		}
1633
	}
1634
	if ($found == false)
1635
		return;
1636 6189988d Scott Dale
1637
	/* run netstat to determine link info */
1638
1639
	unset($linkinfo);
1640 20c79427 Ermal Lu?i
	if ($ifinfo['if'] != $ifinfo['hwif'])
1641
		$chkif = $ifinfo['hwif'];
1642
	else
1643
		$chkif = $ifinfo['if'];
1644
1645
	exec("/usr/bin/netstat -I {$chkif} -nWb -f link", $linkinfo);
1646 56e1d16e Ermal Lu?i
1647 6189988d Scott Dale
	$linkinfo = preg_split("/\s+/", $linkinfo[1]);
1648 20c79427 Ermal Lu?i
	if ("{$chkif}*" == $linkinfo[0])
1649 6189988d Scott Dale
		$ifinfo['status'] = "down";
1650 20c79427 Ermal Lu?i
	else if ($chkif == $linkinfo[0])
1651 6189988d Scott Dale
		$ifinfo['status'] = "up";
1652 20c79427 Ermal Lu?i
	else
1653 56e1d16e Ermal Lu?i
		$ifinfo['status'] = "down";
1654 6189988d Scott Dale
1655 fb707f4a Ermal Luçi
	if (preg_match("/^enc|^tun|^ppp|^pptp|^ovpn/i", $ifinfo['if'])) {
1656
		$ifinfo['inpkts'] = $linkinfo[3];
1657 01385b0c Scott Ullrich
		$ifinfo['outpkts'] = $linkinfo[6];
1658 fb707f4a Ermal Luçi
	} else {
1659 6189988d Scott Dale
		$ifinfo['macaddr'] = $linkinfo[3];
1660
		$ifinfo['inerrs'] = $linkinfo[5];
1661
		$ifinfo['outerrs'] = $linkinfo[8];
1662
		$ifinfo['collisions'] = $linkinfo[10];
1663
	}
1664
1665 01385b0c Scott Ullrich
	/* Use pfctl for non wrapping 64 bit counters */
1666 b5a8483c Seth Mos
	/* Pass */
1667 ea1f7b42 Seth Mos
	exec("/sbin/pfctl -vvsI -i {$ifinfo['if']}", $pfctlstats);
1668 971eaab5 Seth Mos
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1669
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1670
	$in4_pass = $pf_in4_pass[5];
1671
	$out4_pass = $pf_out4_pass[5];
1672
	$in4_pass_packets = $pf_in4_pass[3];
1673
	$out4_pass_packets = $pf_out4_pass[3];
1674
	$ifinfo['inbytespass'] = $in4_pass;
1675
	$ifinfo['outbytespass'] = $out4_pass;
1676
	$ifinfo['inpktspass'] = $in4_pass_packets;
1677
	$ifinfo['outpktspass'] = $out4_pass_packets;
1678 01385b0c Scott Ullrich
1679 971eaab5 Seth Mos
	/* Block */
1680
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1681
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1682
	$in4_block = $pf_in4_block[5];
1683
	$out4_block = $pf_out4_block[5];
1684
	$in4_block_packets = $pf_in4_block[3];
1685
	$out4_block_packets = $pf_out4_block[3];
1686
	$ifinfo['inbytesblock'] = $in4_block;
1687
	$ifinfo['outbytesblock'] = $out4_block;
1688
	$ifinfo['inpktsblock'] = $in4_block_packets;
1689
	$ifinfo['outpktsblock'] = $out4_block_packets;
1690
1691
	$ifinfo['inbytes'] = $in4_pass + $in4_block;
1692
	$ifinfo['outbytes'] = $out4_pass + $out4_block;
1693
	$ifinfo['inpkts'] = $in4_pass_packets + $in4_block_packets;
1694
	$ifinfo['outpkts'] = $in4_pass_packets + $out4_block_packets;
1695 01385b0c Scott Ullrich
		
1696 63161b3f Ermal Luçi
	$ifconfiginfo = "";
1697 20c79427 Ermal Lu?i
	unset($ifconfiginfo, $link0);
1698 63161b3f Ermal Luçi
	exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1699
	foreach ($ifconfiginfo as $ici) {
1700 b9064a4d Seth Mos
		if (preg_match("/inet (\S+)/", $ici, $matches)) {
1701 63161b3f Ermal Luçi
			$ifinfo['ipaddr'] = $matches[1];
1702 b9064a4d Seth Mos
		}
1703
		if (preg_match("/netmask (\S+)/", $ici, $matches)) {
1704
			if (preg_match("/^0x/", $matches[1])) {
1705 63161b3f Ermal Luçi
				$ifinfo['subnet'] = long2ip(hexdec($matches[1]));
1706 b9064a4d Seth Mos
			}
1707
		}
1708
		if (strpos($ici, 'LINK0') !== false) {
1709 20c79427 Ermal Lu?i
			$link0 = "down";
1710 b9064a4d Seth Mos
		}
1711 63161b3f Ermal Luçi
	}
1712
1713 67ee1ec5 Ermal Luçi
	switch ($config['interfaces'][$if]['ipaddr']) {
1714 6189988d Scott Dale
	/* DHCP? -> see if dhclient is up */
1715 67ee1ec5 Ermal Luçi
	case "dhcp":
1716 f2a5b5e4 Chris Buechler
		/* see if dhclient is up */
1717
		if (is_dhcp_running($ifinfo['if']) == true)
1718
			$ifinfo['dhcplink'] = "up";
1719
		else
1720
			$ifinfo['dhcplink'] = "down";
1721
1722
		break;
1723 67ee1ec5 Ermal Luçi
	case "carpdev-dhcp":
1724 20c79427 Ermal Lu?i
		/* see if dhclient is up */
1725
		if (is_dhcp_running($ifinfo['if']) == true)
1726
			$ifinfo['dhcplink'] = "up";
1727
		else
1728
			$ifinfo['dhcplink'] = "down";
1729 63161b3f Ermal Luçi
1730 67ee1ec5 Ermal Luçi
		break;
1731 6189988d Scott Dale
	/* PPPoE interface? -> get status from virtual interface */
1732 67ee1ec5 Ermal Luçi
	case "pppoe":
1733 6189988d Scott Dale
		unset($linkinfo);
1734
		exec("/usr/bin/netstat -I " . $ifinfo['if'] . " -nWb -f link", $linkinfo);
1735
		$linkinfo = preg_split("/\s+/", $linkinfo[1]);
1736 20c79427 Ermal Lu?i
		if ("{$ifinfo['if']}*" == $linkinfo[0])
1737 6189988d Scott Dale
			$ifinfo['pppoelink'] = "down";
1738 20c79427 Ermal Lu?i
		else if ($ifinfo['if'] == $linkinfo[0] && !isset($link0))
1739 6189988d Scott Dale
			/* get PPPoE link status for dial on demand */
1740
			$ifinfo['pppoelink'] = "up";
1741 20c79427 Ermal Lu?i
		else
1742
			$ifinfo['pppoelink'] = "down";
1743 6189988d Scott Dale
1744 67ee1ec5 Ermal Luçi
		break;
1745 6189988d Scott Dale
	/* PPTP interface? -> get status from virtual interface */
1746 67ee1ec5 Ermal Luçi
	case "pptp":
1747 6189988d Scott Dale
		unset($linkinfo);
1748
		exec("/usr/bin/netstat -I " . $ifinfo['if'] . " -nWb -f link", $linkinfo);
1749
		$linkinfo = preg_split("/\s+/", $linkinfo[1]);
1750 20c79427 Ermal Lu?i
		if ("{$ifinfo['if']}*" == $linkinfo[0])
1751 6189988d Scott Dale
			$ifinfo['pptplink'] = "down";
1752 20c79427 Ermal Lu?i
		else if ($ifinfo['if'] == $linkinfo[0] && !isset($link0))
1753 6189988d Scott Dale
			/* get PPTP link status for dial on demand */
1754
			$ifinfo['pptplink'] = "up";
1755 20c79427 Ermal Lu?i
		else
1756
			$ifinfo['pptplink'] = "down";
1757 6189988d Scott Dale
1758 67ee1ec5 Ermal Luçi
		break;
1759 63161b3f Ermal Luçi
	default:
1760
		break;
1761 6189988d Scott Dale
	}
1762
1763
	if ($ifinfo['status'] == "up") {
1764
		/* try to determine media with ifconfig */
1765
		unset($ifconfiginfo);
1766
		exec("/sbin/ifconfig " . $ifinfo['hwif'], $ifconfiginfo);
1767
		$matches = "";
1768
		foreach ($ifconfiginfo as $ici) {
1769
1770
			/* don't list media/speed for wireless cards, as it always
1771
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1772
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1773
				$ifinfo['media'] = $matches[1];
1774
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1775
				$ifinfo['media'] = $matches[1];
1776
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1777
				$ifinfo['media'] = $matches[1];
1778
			}
1779
1780
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1781
				if ($matches[1] != "active")
1782
					$ifinfo['status'] = $matches[1];
1783
			}
1784
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1785
				$ifinfo['channel'] = $matches[1];
1786
			}
1787
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1788
				if ($matches[1][0] == '"')
1789
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1790
				else
1791
					$ifinfo['ssid'] = $matches[1];
1792
			}
1793
		}
1794 67ee1ec5 Ermal Luçi
		/* lookup the gateway */
1795
		if (interface_has_gateway($if)) 
1796
			$ifinfo['gateway'] = get_interface_gateway($if);
1797 6189988d Scott Dale
	}
1798
1799
	$bridge = "";
1800 7ec05d27 Ermal Luçi
	$bridge = link_interface_to_bridge($ifdescr);
1801 6189988d Scott Dale
	if($bridge) {
1802
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1803
		if(stristr($bridge_text, "blocking") <> false) {
1804
			$ifinfo['bridge'] = "<b><font color='red'>blocking</font></b> - check for ethernet loops";
1805
			$ifinfo['bridgeint'] = $bridge;
1806
		} else if(stristr($bridge_text, "learning") <> false) {
1807
			$ifinfo['bridge'] = "learning";
1808
			$ifinfo['bridgeint'] = $bridge;
1809
		} else if(stristr($bridge_text, "forwarding") <> false) {
1810
			$ifinfo['bridge'] = "forwarding";
1811
			$ifinfo['bridgeint'] = $bridge;
1812
		}
1813
	}
1814
1815
	return $ifinfo;
1816
}
1817
1818
//returns cpu speed of processor. Good for determining capabilities of machine
1819
function get_cpu_speed() {
1820
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1821
}
1822 fab7ff44 Bill Marquette
1823 fe80446f Seth Mos
/* check if the wan interface is up
1824
 * Wait for a maximum of 10 seconds
1825
 * If the interface is up before then continue
1826
 */
1827
function is_wan_interface_up($interface) {
1828
	global $g;
1829
	global $config;
1830
	$i = 0;
1831
	while($i < 10) {
1832
		if(get_interface_gateway($interface)) {
1833
			return true;
1834
		} else {
1835
			sleep(1);
1836
		}
1837
		$i++;
1838
	}
1839
	return false;
1840
}
1841 a5f94f14 Scott Ullrich
1842
function add_hostname_to_watch($hostname) {
1843 c941ea1c Seth Mos
	if(!is_dir("/var/db/dnscache")) {
1844
		mkdir("/var/db/dnscache");
1845
	}
1846 5f31bf01 Seth Mos
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1847 581e772e Seth Mos
		$domrecords = array();
1848
		$domips = array();
1849
		exec("host -t A $hostname", $domrecords, $rethost);
1850
		if($rethost == 0) {
1851
			foreach($domrecords as $domr) {
1852
				$doml = explode(" ", $domr);
1853
				$domip = $doml[3];
1854
				/* fill array with domain ip addresses */
1855
				if(is_ipaddr($domip)) {
1856
					$domips[] = $domip;
1857
				}
1858
			}
1859
		}
1860
		sort($domips);
1861
		$contents = "";
1862
		if(! empty($domips)) {
1863 162c059e Seth Mos
			foreach($domips as $ip) {
1864
				$contents .= "$ip\n";
1865
			}
1866 581e772e Seth Mos
		}
1867
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1868 a5f94f14 Scott Ullrich
	}
1869
}
1870
1871 91cb6ca6 Scott Ullrich
function find_dns_aliases() {
1872
	global $config, $g;
1873 aa0b6f36 Bill Marquette
	foreach((array) $config['aliases']['alias'] as $alias) {
1874 683ba905 Scott Ullrich
		$alias_value = $alias['address'];
1875
		$alias_name = $alias['name'];
1876
		if(stristr($alias_value, " ")) {
1877
			$alias_split = split(" ", $alias_value);
1878 91cb6ca6 Scott Ullrich
			foreach($alias_split as $as) {
1879 f79f62d0 Seth Mos
				if(is_fqdn($as)) 
1880 91cb6ca6 Scott Ullrich
					add_hostname_to_watch($as);			
1881
			}
1882
		} else {
1883 f79f62d0 Seth Mos
			if(is_fqdn($alias_value)) 
1884 683ba905 Scott Ullrich
				add_hostname_to_watch($alias_value);
1885 91cb6ca6 Scott Ullrich
		}
1886
	}
1887
}
1888
1889 5ed54b93 Seth Mos
function is_fqdn($fqdn) {
1890
	$hostname = false;
1891
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1892
		$hostname = true;
1893
	}
1894
	if(preg_match("/\.\./", $fqdn)) {
1895
		$hostname = false;
1896
	}
1897 3aae364d Scott Ullrich
	if(preg_match("/^\./i", $fqdn)) { 
1898 5ed54b93 Seth Mos
		$hostname = false;
1899
	}
1900 c941ea1c Seth Mos
	if(preg_match("/\//i", $fqdn)) {
1901
		$hostname = false;
1902
	}
1903 5ed54b93 Seth Mos
	return($hostname);
1904
}
1905
1906 639aaa95 Bill Marquette
function pfsense_default_state_size() {
1907
  /* get system memory amount */
1908
  $memory = get_memory();
1909
  $avail = $memory[0];
1910
  /* Be cautious and only allocate 10% of system memory to the state table */
1911
  $max_states = (int) ($avail/10)*1000;
1912
  return $max_states;
1913
}
1914
1915 2a9db752 Scott Dale
function rule_popup($src,$srcport,$dst,$dstport){
1916
global $config;
1917
$aliases_array = array();
1918
if($config['aliases']['alias'] <> "" and is_array($config['aliases']['alias']))
1919
{
1920
$span_begin = "";
1921
		$alias_src_span_begin = "";
1922
		$alias_src_span_end = "";
1923
		$alias_src_port_span_begin = "";
1924
		$alias_src_port_span_end = "";
1925
		$alias_dst_span_begin = "";
1926
		$alias_dst_span_end = "";
1927
		$alias_dst_port_span_begin = "";
1928
		$alias_dst_port_span_end = "";
1929
		$alias_content_text = "";
1930
	foreach($config['aliases']['alias'] as $alias_name) 
1931
	{	
1932
	 	$alias_addresses = explode (" ", $alias_name['address']);
1933
	 	$alias_details = explode ("||", $alias_name['detail']);
1934
	 	$alias_objects_with_details = "";
1935
	 	$counter = 0;
1936
	 	foreach($alias_addresses as $alias_ports_address)
1937
	 	{
1938
			$alias_objects_with_details .= $alias_addresses[$counter];
1939
			$alias_detail_default = strpos ($alias_details[$counter],"Entry added");
1940
			if ($alias_details[$counter] != "" && $alias_detail_default === False){
1941
				$alias_objects_with_details .=" - " . $alias_details[$counter];
1942
			}  
1943
			$alias_objects_with_details .= "<br>";
1944
			$counter++;
1945
		}			
1946
		//max character length for caption field
1947
		$maxlength = 60;
1948
		
1949
		$alias_descr_substr = $alias_name['descr'];
1950
		$alias_content_text = htmlspecialchars($alias_objects_with_details);
1951
		$alias_caption = htmlspecialchars($alias_descr_substr . ":");
1952
		$strlength = strlen ($alias_caption);
1953
		if ($strlength >= $maxlength) 
1954
			$alias_caption = substr($alias_caption, 0, $maxlength) . "...";		
1955
						
1956
		$span_begin = "<span style=\"cursor: help;\" onmouseover=\"domTT_activate(this, event, 'content', '<h1>$alias_caption</h1><p>$alias_content_text</p>', 'trail', true, 'delay', 0, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle');\" onmouseout=\"this.style.color = ''; domTT_mouseout(this, event);\"><U>";
1957
		
1958
		
1959
		if ($alias_name['name'] == $src)
1960
	 	{										
1961
			$alias_src_span_begin = $span_begin;
1962
		}
1963
	 	if ($alias_name['name'] == $srcport)
1964
	 	{									
1965
			$alias_src_port_span_begin = $span_begin;					
1966
		}
1967
		if ($alias_name['name'] == $dst)
1968
	 	{										
1969
			$alias_dst_span_begin = $span_begin;									
1970
		}
1971
		if ($alias_name['name'] == $dstport)
1972
	 	{											
1973
			$alias_dst_port_span_begin = $span_begin;											
1974
		}										
1975
		
1976
	}
1977
	$descriptions = array ();
1978
	$descriptions['src'] = $alias_src_span_begin;
1979
	$descriptions['srcport'] = $alias_src_port_span_begin;
1980
	$descriptions['dst'] = $alias_dst_span_begin;
1981
	$descriptions['dstport'] = $alias_dst_port_span_begin;
1982
	return $descriptions; 
1983
  }
1984
}
1985 9140757d Bill Marquette
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body') {
1986
	global $ch, $fout, $file_size, $downloaded;
1987
	$file_size  = 1;
1988
	$downloaded = 1;
1989
	/* open destination file */
1990
	$fout = fopen($destination_file, "wb");
1991
1992
	/*
1993
	 *	Originally by Author: Keyvan Minoukadeh
1994
	 *	Modified by Scott Ullrich to return Content-Length size
1995
         */
1996
1997
	$ch = curl_init();
1998
	curl_setopt($ch, CURLOPT_URL, $url_file);
1999
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
2000
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
2001
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
2002
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '5');
2003 ed241396 Scott Ullrich
	curl_setopt($ch, CURLOPT_TIMEOUT, 0);
2004
	
2005 9140757d Bill Marquette
	curl_exec($ch);
2006
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2007
	if($fout)
2008
		fclose($fout);
2009
	curl_close($ch);
2010
	return ($http_code == 200) ? true : $http_code;
2011
}
2012
2013
function read_header($ch, $string) {
2014
	global $file_size, $fout;
2015
	$length = strlen($string);
2016
	$regs = "";
2017
	ereg("(Content-Length:) (.*)", $string, $regs);
2018
	if($regs[2] <> "") {
2019
		$file_size = intval($regs[2]);
2020
	}
2021
	ob_flush();
2022
	return $length;
2023
}
2024
2025
function read_body($ch, $string) {
2026
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
2027
	$length = strlen($string);
2028
	$downloaded += intval($length);
2029
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
2030
	$downloadProgress = 100 - $downloadProgress;
2031
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
2032
		if($sendto == "status") {
2033
			$tostatus = $static_status . $downloadProgress . "%";
2034
			update_status($tostatus);
2035
		} else {
2036
			$tooutput = $static_output . $downloadProgress . "%";
2037
			update_output_window($tooutput);
2038
		}
2039
		update_progress_bar($downloadProgress);
2040
		$lastseen = $downloadProgress;
2041
	}
2042
	if($fout)
2043
		fwrite($fout, $string);
2044
	ob_flush();
2045
	return $length;
2046
}
2047
2048 7723c7e0 Seth Mos
/* Compare the current hostname DNS to the DNS cache we made
2049
 * if it has changed we return the old records
2050
 * if no change we return true */
2051
function compare_hostname_to_dnscache($hostname) {
2052
	if(!is_dir("/var/db/dnscache")) {
2053
		mkdir("/var/db/dnscache");
2054
	}
2055
	$hostname = trim($hostname);
2056
	if(is_readable("/var/db/dnscache/{$hostname}")) {
2057
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
2058
	} else {
2059
		$oldcontents = "";
2060
	}
2061
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
2062
		$domrecords = array();
2063
		$domips = array();
2064
		exec("host -t A $hostname", $domrecords, $rethost);
2065
		if($rethost == 0) {
2066
			foreach($domrecords as $domr) {
2067
				$doml = explode(" ", $domr);
2068
				$domip = $doml[3];
2069
				/* fill array with domain ip addresses */
2070
				if(is_ipaddr($domip)) {
2071
					$domips[] = $domip;
2072
				}
2073
			}
2074
		}
2075
		sort($domips);
2076
		$contents = "";
2077
		if(! empty($domips)) {
2078
			foreach($domips as $ip) {
2079
				$contents .= "$ip\n";
2080
			}
2081
		}
2082
	}
2083
2084
	if(trim($oldcontents) != trim($contents)) {
2085
		log_error("DNSCACHE: Found old IP {$oldcontents} and new IP {$contents}");
2086
		return ($oldcontents);
2087
	} else {
2088
		return false;
2089
	}
2090
}
2091
2092 afb2de1b Ermal Lu?i
?>