Project

General

Profile

Download (56.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****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
 * Copyright (C) 2004-2007 Scott Ullrich (sullrich@gmail.com)
12
 * 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
/****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
	if(isAllowedPage($security_url, $allowed)) 
47
		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
	if(isAllowedPage($security_url, $allowed)) 
62
		return true;
63
	return false;
64
}
65

    
66
/****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
	if(isAllowedPage($security_url)) 
77
		return true;
78
	return false;
79
}
80

    
81
/****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
	$fd = fopen("$url","r");
91
	if($fd) {
92
		fclose($fd);
93
   		return true;    
94
	} else {
95
        return false;
96
	}
97
}
98

    
99
/****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
/****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
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
		usleep(1000);
171
		mwexec("/sbin/ifconfig carp{$x} delete");
172
		if($needed_carp_interfaces < $carp_counter) {
173
			$needed_carp_interfaces--;
174
			//log_error("Destroying carp interface.");
175
			//mwexec("/sbin/ifconfig carp{$x} destroy");
176
		}
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
		return;
227

    
228
	/* translate wan, lan, opt -> real interface if needed */
229
	$int = interface_translate_type_to_real($interface);
230
	if($int <> "") $interface = $int;
231
	$int_family = preg_split("/[0-9]+/", $int);
232
	$options = strtolower(`/sbin/ifconfig -m {$interface} | grep capabilities`);
233
	$supported_ints = array('fxp');
234
	if (in_array($int_family, $supported_ints)) {
235
        	if(isset($config['system']['do_not_use_nic_microcode']))
236
                        continue;
237
		mwexec("/sbin/ifconfig {$interface} link0");
238
        }
239

    
240
	/* skip vlans for checksumming and polling */
241
	if(stristr($interface, "vlan")) 
242
		return;
243

    
244
	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

    
256
	/* if the NIC supports polling *AND* it is enabled in the GUI */
257
	if(interface_supports_polling($interface)) {
258
		$polling = isset($config['system']['polling']);	
259
		if($polling) {
260
			mwexec("sysctl kern.polling.enable=1");
261
                        mwexec("/sbin/ifconfig {$interface} polling 2>/dev/null");
262
		} else {
263
			mwexec("sysctl kern.polling.enable=0");
264
		}
265
	}
266
	return;
267
}
268

    
269
/****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
		"vge",
292
		"re",
293
		"rl",
294
		"sf",
295
		"sis",
296
		"ste",
297
		"stge",    
298
		"vge",
299
		"vr",
300
		"xl");
301
	if(in_array($interface, $supported_ints))
302
		return true;
303
	return false;
304
}
305

    
306
/****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
	if(is_array($config['filter']['rule']))
322
		foreach($config['filter']['rule'] as $rule) {
323
			if($rule['source']['address'])
324
				if($rule['source']['address'] == $alias)
325
					return true;
326
			if($rule['destination']['address'])
327
				if($rule['destination']['address'] == $alias)
328
					return true;
329
		}
330
	/* 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
/****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
			if($rule['sched'] == $schedule)
359
				return true;
360
		}
361
	return false;
362
}
363

    
364
/****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
	$supported_ints = array('bge', 'dc', 'em', 'fwe', 'fwip', 'fxp', 'ixgb', 'ste', 'nge', 're', 'rl', 'sf', 'sis', 'ste', 'vge', 'vr', 'xl');
400

    
401
	/* if list */
402
	$iflist = get_configured_interface_list();
403

    
404
	foreach ($iflist as $ifent => $ifname) {
405
		$real_interface = convert_friendly_interface_to_real_interface_name($ifname);
406
		$ifdevice = substr($real_interface, 0, -1);
407
		if(!in_array($ifdevice, $supported_ints)) {
408
			continue;
409
        }
410
		if(isset($config['system']['polling'])) {
411
			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
	/* if list */
432
        $ifdescrs = get_configured_interface_list();
433

    
434
	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
		$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
		$carp_interface_count_cache = intval($tmp);
497
	}
498
	return $carp_interface_count_cache;
499
}
500

    
501
function link_carp_interface_to_parent($interface) {
502
	global $config;
503

    
504
	if ($interface == "")
505
		return;
506

    
507
	$carp_ip = find_interface_ip($interface);
508
	if (!is_ipaddr($carp_ip))
509
		return;
510

    
511
	/* if list */
512
        $ifdescrs = get_configured_interface_list();
513
	foreach ($ifdescrs as $ifdescr => $ifname) {
514
		$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
	}
520

    
521
	return "";
522
}
523

    
524
/****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
	if (!is_ipaddr($ip))
536
		return;
537

    
538
	$carp_ints = "";
539
	$num_carp_ints = find_number_of_created_carp_interfaces();
540
	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
	}
549
	
550
	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

    
574
 */
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
			return false;
597
		}
598
		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
		if(stristr($fci, $ip . " ") == true)
629
			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
function add_text_to_file($file, $text, $replace = false) {
664
	if(file_exists($file) and is_writable($file)) {
665
		$filecontents = file($file);
666
		$fout = fopen($file, "w");
667

    
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
		fwrite($fout, $file_text);
676
		fclose($fout);
677
		return true;
678
	} else {
679
		return false;
680
	}
681
}
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
		echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
744
	}
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
	}
798

    
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
	exec("/sbin/pfctl -vvsq", $stats_array);
809
	$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
 *  restore_config_section($section, new_contents): restore a configuration section,
855
 *                                                  and write the configuration out
856
 *                                                  to disk/cf.
857
 */
858
function restore_config_section($section, $new_contents) {
859
	global $config, $g;
860
	conf_mount_rw();
861
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
862
	fwrite($fout, $new_contents);
863
	fclose($fout);
864
	$section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
865
	$config[$section] = &$section_xml;
866
	unlink($g['tmp_path'] . "/tmpxml");
867
	write_config("Restored {$section} of config file (maybe from CARP partner)");
868
	conf_mount_ro();
869
	return;
870
}
871

    
872
/*
873
 *  merge_config_section($section, new_contents):   restore a configuration section,
874
 *                                                  and write the configuration out
875
 *                                                  to disk/cf.  But preserve the prior
876
 * 													structure if needed
877
 */
878
function merge_config_section($section, $new_contents) {
879
	global $config;
880
	conf_mount_rw();
881
	$fname = get_tmp_filename();
882
	$fout = fopen($fname, "w");
883
	fwrite($fout, $new_contents);
884
	fclose($fout);
885
	$section_xml = parse_xml_config($fname, $section);
886
	$config[$section] = $section_xml;
887
	unlink($fname);
888
	write_config("Restored {$section} of config file (maybe from CARP partner)");
889
	conf_mount_ro();
890
	return;
891
}
892

    
893
/*
894
 * http_post($server, $port, $url, $vars): does an http post to a web server
895
 *                                         posting the vars array.
896
 * written by nf@bigpond.net.au
897
 */
898
function http_post($server, $port, $url, $vars) {
899
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
900
	$urlencoded = "";
901
	while (list($key,$value) = each($vars))
902
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
903
	$urlencoded = substr($urlencoded,0,-1);
904
	$content_length = strlen($urlencoded);
905
	$headers = "POST $url HTTP/1.1
906
Accept: */*
907
Accept-Language: en-au
908
Content-Type: application/x-www-form-urlencoded
909
User-Agent: $user_agent
910
Host: $server
911
Connection: Keep-Alive
912
Cache-Control: no-cache
913
Content-Length: $content_length
914

    
915
";
916

    
917
	$errno = "";
918
	$errstr = "";
919
	$fp = fsockopen($server, $port, $errno, $errstr);
920
	if (!$fp) {
921
		return false;
922
	}
923

    
924
	fputs($fp, $headers);
925
	fputs($fp, $urlencoded);
926

    
927
	$ret = "";
928
	while (!feof($fp))
929
		$ret.= fgets($fp, 1024);
930
	fclose($fp);
931

    
932
	return $ret;
933
}
934

    
935
/*
936
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
937
 */
938
if (!function_exists('php_check_syntax')){
939
	function php_check_syntax($code_to_check, &$errormessage){
940
		return false;
941
		$fout = fopen("/tmp/codetocheck.php","w");
942
		$code = $_POST['content'];
943
		$code = str_replace("<?php", "", $code);
944
		$code = str_replace("?>", "", $code);
945
		fwrite($fout, "<?php\n\n");
946
		fwrite($fout, $code_to_check);
947
		fwrite($fout, "\n\n?>\n");
948
		fclose($fout);
949
		$command = "/usr/local/bin/php -l /tmp/codetocheck.php";
950
		$output = exec_command($command);
951
		if (stristr($output, "Errors parsing") == false) {
952
			echo "false\n";
953
			$errormessage = '';
954
			return(false);
955
		} else {
956
			$errormessage = $output;
957
			return(true);
958
		}
959
	}
960
}
961

    
962
/*
963
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
964
 */
965
if (!function_exists('php_check_syntax')){
966
	function php_check_syntax($code_to_check, &$errormessage){
967
		return false;
968
		$command = "/usr/local/bin/php -l " . $code_to_check;
969
		$output = exec_command($command);
970
		if (stristr($output, "Errors parsing") == false) {
971
			echo "false\n";
972
			$errormessage = '';
973
			return(false);
974
		} else {
975
			$errormessage = $output;
976
			return(true);
977
		}
978
	}
979
}
980

    
981
/*
982
 * rmdir_recursive($path,$follow_links=false)
983
 * Recursively remove a directory tree (rm -rf path)
984
 * This is for directories _only_
985
 */
986
function rmdir_recursive($path,$follow_links=false) {
987
	$to_do = glob($path);
988
	if(!is_array($to_do)) $to_do = array($to_do);
989
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
990
		if(file_exists($workingdir)) {
991
			if(is_dir($workingdir)) {
992
				$dir = opendir($workingdir);
993
				while ($entry = readdir($dir)) {
994
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
995
						unlink("$workingdir/$entry");
996
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
997
						rmdir_recursive("$workingdir/$entry");
998
				}
999
				closedir($dir);
1000
				rmdir($workingdir);
1001
			} elseif (is_file($workingdir)) {
1002
				unlink($workingdir);
1003
			}
1004
               	}
1005
	}
1006
	return;
1007
}
1008

    
1009
/*
1010
 * call_pfsense_method(): Call a method exposed by the pfsense.com XMLRPC server.
1011
 */
1012
function call_pfsense_method($method, $params, $timeout = 0) {
1013
	global $g, $config;
1014

    
1015
	$ip = gethostbyname($g['product_website']);
1016
	if($ip == $g['product_website'])
1017
		return false;
1018
	global $g, $config;
1019
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
1020
	$xmlrpc_path = $g['xmlrpcpath'];
1021
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
1022
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
1023
	$resp = $cli->send($msg, $timeout);
1024
	if(!$resp) {
1025
		log_error("XMLRPC communication error: " . $cli->errstr);
1026
		return false;
1027
	} elseif($resp->faultCode()) {
1028
		log_error("XMLRPC request failed with error " . $resp->faultCode() . ": " . $resp->faultString());
1029
		return false;
1030
	} else {
1031
		return XML_RPC_Decode($resp->value());
1032
	}
1033
}
1034

    
1035
/*
1036
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1037
 */
1038
function check_firmware_version($tocheck = "all", $return_php = true) {
1039
	global $g, $config;
1040
	$ip = gethostbyname($g['product_website']);
1041
	if($ip == $g['product_website'])
1042
		return false;
1043
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1044
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1045
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1046
		"platform" => trim(file_get_contents('/etc/platform'))
1047
		);
1048
	if($tocheck == "all") {
1049
		$params = $rawparams;
1050
	} else {
1051
		foreach($tocheck as $check) {
1052
			$params['check'] = $rawparams['check'];
1053
			$params['platform'] = $rawparams['platform'];
1054
		}
1055
	}
1056
	if($config['system']['firmware']['branch']) {
1057
		$params['branch'] = $config['system']['firmware']['branch'];
1058
	}
1059
	if(!$versions = call_pfsense_method('pfsense.get_firmware_version', $params)) {
1060
		return false;
1061
	} else {
1062
		$versions["current"] = $params;
1063
	}
1064
	return $versions;
1065
}
1066

    
1067
function get_disk_info() {
1068
	$diskout = "";
1069
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
1070
	return explode(' ', $diskout[0]);
1071
	// $size, $used, $avail, $cap
1072
}
1073

    
1074
/****f* pfsense-utils/display_top_tabs
1075
 * NAME
1076
 *   display_top_tabs - display tabs with rounded edges
1077
 * INPUTS
1078
 *   $text      - array of tabs
1079
 * RESULT
1080
 *   null
1081
 ******/
1082
function display_top_tabs(& $tab_array) {
1083
	global $HTTP_SERVER_VARS;
1084
	global $config;
1085
	global $g;
1086

    
1087
	/*  does the user have access to this tab?
1088
	 *  master user has access to everything.
1089
	 *  if the user does not have access, simply
1090
	 *  unset the tab item.
1091
	 */
1092

    
1093
	$tab_temp = array ();
1094
	foreach ($tab_array as $ta)
1095
		if(isAllowedPage($ta[2]))
1096
			$tab_temp[] = $ta;
1097
	/*
1098
		// FIXME :	if the checks are not good enough
1099
		//			in isAllowedPage, it needs to be
1100
		//			fixed instead of kludging here
1101

    
1102
		// TODO: humm what shall we do with pkg_edit.php and pkg.php?
1103
		if ((strpos($link, "pkg.php")) !== false || (strpos($link, "pkg_edit.php")) !== false) {
1104
			$pos_equal = strpos($link, "=");
1105
			$pos_xmlsuffix = strpos($link, ".xml");
1106
			// do we match an absolute url including ?xml= foo
1107
			if(!isAllowedPage($link, $allowed))
1108
				$link = substr($link, $pos_equal +1, ($pos_xmlsuffix - $pos_equal +3));
1109
		}
1110
		// next check - what if the basename contains a query string?
1111
		if ((strpos($link, "?")) !== false) {
1112
			$pos_qmark = strpos($link, "?");
1113
			$link = substr($link, 0, $pos_qmark);
1114
		}
1115
		$authorized_text = print_r($allowed, true);
1116
		if(is_array($authorized))
1117
			if (in_array(basename($link), $authorized))
1118
	*/
1119

    
1120
	unset ($tab_array);
1121
	$tab_array = & $tab_temp;
1122

    
1123
	$tab_active_bg   = "#EEEEEE";
1124
	$tab_inactive_bg = "#777777";
1125
	$nifty_tabs_corners = "#FFF";
1126
	$font_color = "white";
1127
	
1128
	/* if tabcontrols.php exist for a theme, allow it to be overriden */
1129
	$themename = $config['theme'];
1130
	$filename = "/usr/local/www/themes/{$themename}/tabcontrols.php";
1131
	if(file_exists($filename)) {
1132
		$eval_code = file_get_contents($filename);
1133
		eval($eval_code);
1134
	}
1135
	
1136
	$tabcharcount = 0;
1137
	foreach ($tab_array as $ta) 
1138
		$tabcharcount = $tabcharcount + strlen($ta[0]);
1139

    
1140
	// If the character count of the tab names is > 670
1141
	// then show a select item dropdown menubox.
1142
	if($tabcharcount > 82) {
1143
		echo "Currently viewing: ";
1144
		echo "<select name='TabSelect'>\n";
1145
		foreach ($tab_array as $ta) {
1146
			if($ta[1]=="true")	
1147
				$selected = " SELECTED";
1148
			else 
1149
				$selected = "";
1150
			echo "<option onClick=\"document.location='{$ta[2]}';\"{$selected}>{$ta['0']}</option>\n";
1151
		}
1152
		echo "</select>\n<p/>";
1153
	}  else {
1154
		echo "<table cellpadding='0' cellspacing='0'>\n";
1155
		echo " <tr>\n";
1156
		$tabscounter = 0;
1157
		foreach ($tab_array as $ta) {
1158
			if ($ta[1] == true) {
1159
				echo "  <td bgcolor='{$tab_active_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"><div id='tabactive'></div></td>\n";
1160
			} else {
1161
				echo "  <td bgcolor='{$tab_inactive_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
1162
			}
1163
			$tabscounter++;
1164
		}
1165
		echo "</tr>\n<tr>\n";
1166
		foreach ($tab_array as $ta) {
1167
			if ($ta[1] == true) {
1168
				echo "  <td height=\"15\" valign=\"middle\" bgcolor='{$tab_active_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
1169
				echo "&nbsp;&nbsp;&nbsp;";
1170
				echo "<font size='-12'>&nbsp;</font></B></td>\n";
1171
			} else {
1172
				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]}'>";
1173
				echo "<font color='{$font_color}'>{$ta[0]}</font></a>&nbsp;&nbsp;&nbsp;";
1174
				echo "<font size='-12'>&nbsp;</font></B></td>\n";
1175
			}
1176
		}
1177
		echo "</tr>\n<tr>\n";
1178
		foreach ($tab_array as $ta) {
1179
			if ($ta[1] == true) {
1180
				echo "  <td bgcolor='{$tab_active_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"></td>\n";
1181
			} else {
1182
				echo "  <td bgcolor='{$tab_inactive_bg}' onClick=\"document.location='{$ta[2]}'\" style=\"cursor: pointer;\"></td>\n";
1183
			}
1184
			$tabscounter++;
1185
		}
1186
		echo " </tr>\n";
1187
		echo "</table>\n";
1188
		echo "<script type=\"text/javascript\">";
1189
		echo "NiftyCheck();\n";
1190
		echo "Rounded(\"div#tabactive\",\"top\",\"{$nifty_tabs_corners}\",\"{$tab_active_bg}\",\"smooth\");\n";
1191
		for ($x = 0; $x < $tabscounter; $x++)
1192
			echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"{$nifty_tabs_corners}\",\"{$tab_inactive_bg}\",\"smooth\");\n";
1193
		echo "</script>";
1194
	}
1195
}
1196

    
1197

    
1198
/****f* pfsense-utils/display_topbar
1199
 * NAME
1200
 *   display_topbar - top a table off with rounded edges
1201
 * INPUTS
1202
 *   $text	- (optional) Text to include in bar
1203
 * RESULT
1204
 *   null
1205
 ******/
1206
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {
1207
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1208
	echo "       <tr height='1'>\n";
1209
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1210
	echo "		<div id='topbar'></div></td>\n";
1211
	echo "       </tr>\n";
1212
	echo "       <tr height='1'>\n";
1213
	if ($text != "")
1214
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1215
	else
1216
		echo "         <td height='1' class='listtopic'></td>\n";
1217
	echo "       </tr>\n";
1218
	echo "     </table>";
1219
	echo "<script type=\"text/javascript\">";
1220
	echo "NiftyCheck();\n";
1221
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1222
	echo "</script>";
1223
}
1224

    
1225
/****f* pfsense-utils/strncpy
1226
 * NAME
1227
 *   strncpy - copy strings
1228
 * INPUTS
1229
 *   &$dst, $src, $length
1230
 * RESULT
1231
 *   none
1232
 ******/
1233
function strncpy(&$dst, $src, $length) {
1234
	if (strlen($src) > $length) {
1235
		$dst = substr($src, 0, $length);
1236
	} else {
1237
		$dst = $src;
1238
	}
1239
}
1240

    
1241
/****f* pfsense-utils/reload_interfaces_sync
1242
 * NAME
1243
 *   reload_interfaces - reload all interfaces
1244
 * INPUTS
1245
 *   none
1246
 * RESULT
1247
 *   none
1248
 ******/
1249
function reload_interfaces_sync() {
1250
	global $config, $g;
1251

    
1252
	$shutdown_webgui_needed = false;
1253

    
1254
	touch("{$g['tmp_path']}/reloading_all");
1255

    
1256
	if($g['debug'])
1257
		log_error("reload_interfaces_sync() is starting.");
1258

    
1259
	if(file_exists("{$g['tmp_path']}/config.cache"))
1260
		unlink("{$g['tmp_path']}/config.cache");
1261

    
1262
	/* parse config.xml again */
1263
	$config = parse_config(true);
1264

    
1265
	$wan_if = $config['interfaces']['wan']['if'];
1266
	if (isset($config['interfaces']['lan']))
1267
                $lan_if = $config['interfaces']['lan']['if'];
1268
        else
1269
                $lan_if = "";
1270

    
1271
	if($g['debug'])
1272
		log_error("Cleaning up Interfaces");
1273

    
1274
	/* if list */
1275
        $iflist = get_configured_interface_list(true);
1276

    
1277
	foreach ($iflist as $ifent => $ifname) {
1278
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1279

    
1280
		if(stristr($ifname, "lo0") == true)
1281
			continue;
1282
		/* do not process wan interface, its mandatory */
1283
                if(stristr($ifname, "$wan_if") == true)
1284
                        continue;
1285
                /* do not process lan interface, its mandatory */
1286
                if(stristr($ifname, "$lan_if") == true)
1287
                        continue;
1288
		if($g['debug'])
1289
			log_error("Downing and deleting $ifname_real - $ifname");
1290
		mwexec("/sbin/ifconfig {$ifname_real} down");
1291
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1292
	}
1293

    
1294
	/* set up interfaces */
1295
	interfaces_configure();
1296

    
1297
	/* set up static routes */
1298
	if($g['debug'])
1299
		log_error("Configuring system Routing");
1300
	system_routing_configure();
1301

    
1302
	/* enable routing */
1303
	if($g['debug'])
1304
		log_error("Enabling system routing");
1305
	system_routing_enable();
1306

    
1307
	/* setup captive portal if needed */
1308
	if($g['debug'])
1309
		log_error("Configuring Captive portal");
1310
	captiveportal_configure();
1311

    
1312
	/* restart webConfigurator if needed */
1313
	if($shutdown_webgui_needed == true)
1314
		touch("/tmp/restart_webgui");
1315

    
1316
	/* start devd back up */
1317
	mwexec("/bin/rm /tmp/reload*");
1318

    
1319
	/* remove reloading_all trigger */
1320
	if($g['debug'])
1321
		log_error("Removing {$g['tmp_path']}/reloading_all");
1322
	unlink_if_exists("{$g['tmp_path']}/reloading_all");
1323
}
1324

    
1325
/****f* pfsense-utils/reload_all
1326
 * NAME
1327
 *   reload_all - triggers a reload of all settings
1328
 *   * INPUTS
1329
 *   none
1330
 * RESULT
1331
 *   none
1332
 ******/
1333
function reload_all() {
1334
	touch("/tmp/reload_all");
1335
}
1336

    
1337
/****f* pfsense-utils/reload_interfaces
1338
 * NAME
1339
 *   reload_interfaces - triggers a reload of all interfaces
1340
 * INPUTS
1341
 *   none
1342
 * RESULT
1343
 *   none
1344
 ******/
1345
function reload_interfaces() {
1346
	touch("/tmp/reload_interfaces");
1347
}
1348

    
1349
/****f* pfsense-utils/reload_all_sync
1350
 * NAME
1351
 *   reload_all - reload all settings
1352
 *   * INPUTS
1353
 *   none
1354
 * RESULT
1355
 *   none
1356
 ******/
1357
function reload_all_sync() {
1358
	global $config, $g;
1359

    
1360
	$g['booting'] = false;
1361

    
1362
	touch("{$g['tmp_path']}/reloading_all");
1363

    
1364
	$shutdown_webgui_needed = false;
1365

    
1366
	if(file_exists("{$g['tmp_path']}/config.cache"))
1367
		unlink("{$g['tmp_path']}/config.cache");
1368

    
1369
	/* parse config.xml again */
1370
	$config = parse_config(true);
1371

    
1372
	/* set up our timezone */
1373
	system_timezone_configure();
1374

    
1375
	/* set up our hostname */
1376
	system_hostname_configure();
1377

    
1378
	/* make hosts file */
1379
	system_hosts_generate();
1380

    
1381
	/* generate resolv.conf */
1382
	system_resolvconf_generate();
1383

    
1384
	/* Set up our loopback interface */
1385
	interfaces_loopback_configure();
1386

    
1387
	$wan_if = $config['interfaces']['wan']['if'];
1388
	if (isset($config['interfaces']['lan']))
1389
		$lan_if = $config['interfaces']['lan']['if'];
1390
	else
1391
		$lan_if = "";
1392

    
1393
	/* if list */
1394
	$iflist = get_configured_interface_list();
1395

    
1396
	foreach ($iflist as $ifent => $ifname) {
1397
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1398
		if(stristr($ifname, "lo0") == true)
1399
			continue;
1400
		/* do not process wan interface, its mandatory */
1401
		if($wan_if == $ifname_real)
1402
			continue;
1403
		/* do not process lan interface, its mandatory */
1404
		if($lan_if == $ifname_real)
1405
			continue;
1406
		mwexec("/sbin/ifconfig {$ifname_real} down");
1407
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1408
	}
1409

    
1410
	/* set up interfaces */
1411
	interfaces_configure();
1412

    
1413
	/* set up static routes */
1414
	system_routing_configure();
1415

    
1416
	/* enable routing */
1417
	system_routing_enable();
1418

    
1419
	/* ensure passwords are sync'd */
1420
//	system_password_configure();
1421

    
1422
	/* start dnsmasq service */
1423
	services_dnsmasq_configure();
1424

    
1425
	/* start dyndns service */
1426
	services_dyndns_configure();
1427

    
1428
	/* start DHCP service */
1429
	services_dhcpd_configure();
1430

    
1431
	/* configure cron service */
1432
	configure_cron();
1433

    
1434
	/* start the NTP client */
1435
	system_ntp_configure();
1436

    
1437
	/* start the captive portal */
1438
	captiveportal_configure();
1439

    
1440
        /* reload the filter */
1441
	filter_configure_sync();
1442

    
1443
	/* sync pw database */
1444
	conf_mount_rw();
1445
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1446
	conf_mount_ro();
1447

    
1448
	/* restart sshd */
1449
	touch("/tmp/start_sshd");
1450

    
1451
	/* restart webConfigurator if needed */
1452
	if($shutdown_webgui_needed == true)
1453
		touch("/tmp/restart_webgui");
1454

    
1455
	mwexec("/bin/rm /tmp/reload*");
1456

    
1457
	unlink_if_exists("{$g['tmp_path']}/reloading_all");
1458

    
1459
}
1460

    
1461
function auto_login($status) {
1462
	$gettytab = file_get_contents("/etc/gettytab");
1463
	$getty_split = split("\n", $gettytab);
1464
	conf_mount_rw();
1465
	$fd = fopen("/etc/gettytab", "w");
1466
	foreach($getty_split as $gs) {
1467
		if(stristr($gs, ":ht:np:sp#115200") ) {
1468
			if($status == true) {
1469
				fwrite($fd, "	:ht:np:sp#115200:al=root:\n");
1470
			} else {
1471
				fwrite($fd, "	:ht:np:sp#115200:\n");
1472
			}
1473
		} else {
1474
			fwrite($fd, "{$gs}\n");
1475
		}
1476
	}
1477
	fclose($fd);
1478
	conf_mount_ro();
1479
}
1480

    
1481
function setup_serial_port() {
1482
	global $g, $config;
1483
	conf_mount_rw();
1484
	/* serial console - write out /boot.config */
1485
	if(file_exists("/boot.config"))
1486
		$boot_config = file_get_contents("/boot.config");
1487
	else
1488
		$boot_config = "";
1489

    
1490
	if($g['platform'] <> "cdrom") {
1491
		$boot_config_split = split("\n", $boot_config);
1492
		$fd = fopen("/boot.config","w");
1493
		if($fd) {
1494
			foreach($boot_config_split as $bcs) {
1495
				if(stristr($bcs, "-D")) {
1496
					/* DONT WRITE OUT, WE'LL DO IT LATER */
1497
				} else {
1498
					if($bcs <> "")
1499
						fwrite($fd, "{$bcs}\n");
1500
				}
1501
			}
1502
			if(isset($config['system']['enableserial'])) {
1503
				fwrite($fd, "-D");
1504
			}
1505
			fclose($fd);
1506
		}
1507
		/* serial console - write out /boot/loader.conf */
1508
		$boot_config = file_get_contents("/boot/loader.conf");
1509
		$boot_config_split = split("\n", $boot_config);
1510
		$fd = fopen("/boot/loader.conf","w");
1511
		if($fd) {
1512
			foreach($boot_config_split as $bcs) {
1513
				if(stristr($bcs, "console")) {
1514
					/* DONT WRITE OUT, WE'LL DO IT LATER */
1515
				} else {
1516
					if($bcs <> "")
1517
						fwrite($fd, "{$bcs}\n");
1518
				}
1519
			}
1520
			if(isset($config['system']['enableserial'])) {
1521
				fwrite($fd, "console=\"comconsole\"\n");
1522
			}
1523
			fclose($fd);
1524
		}
1525
	}
1526
	$ttys = file_get_contents("/etc/ttys");
1527
	$ttys_split = split("\n", $ttys);
1528
	$fd = fopen("/etc/ttys", "w");
1529
	foreach($ttys_split as $tty) {
1530
		if(stristr($tty, "ttyd0")) {
1531
			if(isset($config['system']['enableserial'])) {
1532
				fwrite($fd, "ttyd0	\"/usr/libexec/getty bootupcli\"	dialup	on	secure\n");
1533
			} else {
1534
				fwrite($fd, "ttyd0	\"/usr/libexec/getty bootupcli\"	dialup	off	secure\n");
1535
			}
1536
		} else {
1537
			fwrite($fd, $tty . "\n");
1538
		}
1539
	}
1540
	fclose($fd);
1541
	if(isset($config['system']['disableconsolemenu'])) {
1542
		auto_login(false);
1543
	} else {
1544
		auto_login(true);
1545
	}
1546
	conf_mount_ro();
1547
	return;
1548
}
1549

    
1550
function print_value_list($list, $count = 10, $separator = ",") {
1551
	$list = implode($separator, array_slice($list, 0, $count));
1552
	if(count($list) < $count) {
1553
		$list .= ".";
1554
	} else {
1555
		$list .= "...";
1556
	}
1557
	return $list;
1558
}
1559

    
1560
/* DHCP enabled on any interfaces? */
1561
function is_dhcp_server_enabled() 
1562
{
1563
	global $config;
1564

    
1565
	$dhcpdenable = false;
1566
	
1567
	if (!is_array($config['dhcpd']))
1568
		return false;
1569

    
1570
	$Iflist = get_configured_interface_list();
1571

    
1572
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1573
		if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1574
			$dhcpdenable = true;
1575
			break;
1576
		}
1577
	}
1578

    
1579
	return $dhcpdenable;
1580
}
1581

    
1582
/****f* pfsense-utils/isAjax
1583
 * NAME
1584
 *   isAjax - reports if the request is driven from prototype
1585
 * INPUTS
1586
 *   none
1587
 * RESULT
1588
 *   true/false
1589
 ******/
1590
function isAjax() {
1591
	return isset ($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
1592
}
1593

    
1594
//returns interface information
1595
function get_interface_info($ifdescr) {
1596
	global $config, $linkinfo, $netstatrninfo;
1597

    
1598
	$ifinfo = array();
1599
	/* if list */
1600
	$iflist = get_configured_interface_with_descr(false,true);
1601
	
1602
	$found = false;
1603
    	foreach ($iflist as $if => $ifname) {
1604
    	if ($ifdescr == $if || $ifdescr == $ifname) {
1605
			$ifinfo['hwif'] = $config['interfaces'][$if]['if'];
1606
			$ifinfo['if'] = get_real_interface($if);
1607
			$found = true;
1608
			break;
1609
		}
1610
	}
1611
	if ($found == false)
1612
		return;
1613

    
1614
	/* run netstat to determine link info */
1615

    
1616
	unset($linkinfo);
1617
	if ($ifinfo['if'] != $ifinfo['hwif'])
1618
		$chkif = $ifinfo['hwif'];
1619
	else
1620
		$chkif = $ifinfo['if'];
1621

    
1622
	exec("/usr/bin/netstat -I {$chkif} -nWb -f link", $linkinfo);
1623

    
1624
	$linkinfo = preg_split("/\s+/", $linkinfo[1]);
1625
	if ("{$chkif}*" == $linkinfo[0])
1626
		$ifinfo['status'] = "down";
1627
	else if ($chkif == $linkinfo[0])
1628
		$ifinfo['status'] = "up";
1629
	else
1630
		$ifinfo['status'] = "down";
1631

    
1632
	if (preg_match("/^enc|^tun|^ppp|^pptp|^ovpn/i", $ifinfo['if'])) {
1633
		$ifinfo['inpkts'] = $linkinfo[3];
1634
		$ifinfo['outpkts'] = $linkinfo[6];
1635
	} else {
1636
		$ifinfo['macaddr'] = $linkinfo[3];
1637
		$ifinfo['inerrs'] = $linkinfo[5];
1638
		$ifinfo['outerrs'] = $linkinfo[8];
1639
		$ifinfo['collisions'] = $linkinfo[10];
1640
	}
1641

    
1642
	/* Use pfctl for non wrapping 64 bit counters */
1643
	/* Pass */
1644
	exec("/sbin/pfctl -vvsI -i {$ifinfo['if']}", $pfctlstats);
1645
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1646
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1647
	$in4_pass = $pf_in4_pass[5];
1648
	$out4_pass = $pf_out4_pass[5];
1649
	$in4_pass_packets = $pf_in4_pass[3];
1650
	$out4_pass_packets = $pf_out4_pass[3];
1651
	$ifinfo['inbytespass'] = $in4_pass;
1652
	$ifinfo['outbytespass'] = $out4_pass;
1653
	$ifinfo['inpktspass'] = $in4_pass_packets;
1654
	$ifinfo['outpktspass'] = $out4_pass_packets;
1655

    
1656
	/* Block */
1657
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1658
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1659
	$in4_block = $pf_in4_block[5];
1660
	$out4_block = $pf_out4_block[5];
1661
	$in4_block_packets = $pf_in4_block[3];
1662
	$out4_block_packets = $pf_out4_block[3];
1663
	$ifinfo['inbytesblock'] = $in4_block;
1664
	$ifinfo['outbytesblock'] = $out4_block;
1665
	$ifinfo['inpktsblock'] = $in4_block_packets;
1666
	$ifinfo['outpktsblock'] = $out4_block_packets;
1667

    
1668
	$ifinfo['inbytes'] = $in4_pass + $in4_block;
1669
	$ifinfo['outbytes'] = $out4_pass + $out4_block;
1670
	$ifinfo['inpkts'] = $in4_pass_packets + $in4_block_packets;
1671
	$ifinfo['outpkts'] = $in4_pass_packets + $out4_block_packets;
1672
		
1673
	$ifconfiginfo = "";
1674
	unset($ifconfiginfo, $link0);
1675
	exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1676
	foreach ($ifconfiginfo as $ici) {
1677
		if (preg_match("/inet (\S+)/", $ici, $matches)) {
1678
			$ifinfo['ipaddr'] = $matches[1];
1679
		}
1680
		if (preg_match("/netmask (\S+)/", $ici, $matches)) {
1681
			if (preg_match("/^0x/", $matches[1])) {
1682
				$ifinfo['subnet'] = long2ip(hexdec($matches[1]));
1683
			}
1684
		}
1685
		if (strpos($ici, 'LINK0') !== false) {
1686
			$link0 = "down";
1687
		}
1688
	}
1689

    
1690
	switch ($config['interfaces'][$if]['ipaddr']) {
1691
	/* DHCP? -> see if dhclient is up */
1692
	case "dhcp":
1693
		/* see if dhclient is up */
1694
		if (is_dhcp_running($ifinfo['if']) == true)
1695
			$ifinfo['dhcplink'] = "up";
1696
		else
1697
			$ifinfo['dhcplink'] = "down";
1698

    
1699
		break;
1700
	case "carpdev-dhcp":
1701
		/* see if dhclient is up */
1702
		if (is_dhcp_running($ifinfo['if']) == true)
1703
			$ifinfo['dhcplink'] = "up";
1704
		else
1705
			$ifinfo['dhcplink'] = "down";
1706

    
1707
		break;
1708
	/* PPPoE interface? -> get status from virtual interface */
1709
	case "pppoe":
1710
		unset($linkinfo);
1711
		exec("/usr/bin/netstat -I " . $ifinfo['if'] . " -nWb -f link", $linkinfo);
1712
		$linkinfo = preg_split("/\s+/", $linkinfo[1]);
1713
		if ("{$ifinfo['if']}*" == $linkinfo[0])
1714
			$ifinfo['pppoelink'] = "down";
1715
		else if ($ifinfo['if'] == $linkinfo[0] && !isset($link0))
1716
			/* get PPPoE link status for dial on demand */
1717
			$ifinfo['pppoelink'] = "up";
1718
		else
1719
			$ifinfo['pppoelink'] = "down";
1720

    
1721
		break;
1722
	/* PPTP interface? -> get status from virtual interface */
1723
	case "pptp":
1724
		unset($linkinfo);
1725
		exec("/usr/bin/netstat -I " . $ifinfo['if'] . " -nWb -f link", $linkinfo);
1726
		$linkinfo = preg_split("/\s+/", $linkinfo[1]);
1727
		if ("{$ifinfo['if']}*" == $linkinfo[0])
1728
			$ifinfo['pptplink'] = "down";
1729
		else if ($ifinfo['if'] == $linkinfo[0] && !isset($link0))
1730
			/* get PPTP link status for dial on demand */
1731
			$ifinfo['pptplink'] = "up";
1732
		else
1733
			$ifinfo['pptplink'] = "down";
1734

    
1735
		break;
1736
	default:
1737
		break;
1738
	}
1739

    
1740
	if ($ifinfo['status'] == "up") {
1741
		/* try to determine media with ifconfig */
1742
		unset($ifconfiginfo);
1743
		exec("/sbin/ifconfig " . $ifinfo['hwif'], $ifconfiginfo);
1744
		$matches = "";
1745
		foreach ($ifconfiginfo as $ici) {
1746

    
1747
			/* don't list media/speed for wireless cards, as it always
1748
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1749
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1750
				$ifinfo['media'] = $matches[1];
1751
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1752
				$ifinfo['media'] = $matches[1];
1753
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1754
				$ifinfo['media'] = $matches[1];
1755
			}
1756

    
1757
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1758
				if ($matches[1] != "active")
1759
					$ifinfo['status'] = $matches[1];
1760
			}
1761
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1762
				$ifinfo['channel'] = $matches[1];
1763
			}
1764
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1765
				if ($matches[1][0] == '"')
1766
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1767
				else
1768
					$ifinfo['ssid'] = $matches[1];
1769
			}
1770
		}
1771
		/* lookup the gateway */
1772
		if (interface_has_gateway($if)) 
1773
			$ifinfo['gateway'] = get_interface_gateway($if);
1774
	}
1775

    
1776
	$bridge = "";
1777
	$bridge = link_interface_to_bridge($ifdescr);
1778
	if($bridge) {
1779
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1780
		if(stristr($bridge_text, "blocking") <> false) {
1781
			$ifinfo['bridge'] = "<b><font color='red'>blocking</font></b> - check for ethernet loops";
1782
			$ifinfo['bridgeint'] = $bridge;
1783
		} else if(stristr($bridge_text, "learning") <> false) {
1784
			$ifinfo['bridge'] = "learning";
1785
			$ifinfo['bridgeint'] = $bridge;
1786
		} else if(stristr($bridge_text, "forwarding") <> false) {
1787
			$ifinfo['bridge'] = "forwarding";
1788
			$ifinfo['bridgeint'] = $bridge;
1789
		}
1790
	}
1791

    
1792
	return $ifinfo;
1793
}
1794

    
1795
//returns cpu speed of processor. Good for determining capabilities of machine
1796
function get_cpu_speed() {
1797
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1798
}
1799

    
1800
/* check if the wan interface is up
1801
 * Wait for a maximum of 10 seconds
1802
 * If the interface is up before then continue
1803
 */
1804
function is_wan_interface_up($interface) {
1805
	global $g;
1806
	global $config;
1807
	$i = 0;
1808
	while($i < 10) {
1809
		if(get_interface_gateway($interface)) {
1810
			return true;
1811
		} else {
1812
			sleep(1);
1813
		}
1814
		$i++;
1815
	}
1816
	return false;
1817
}
1818

    
1819
function add_hostname_to_watch($hostname) {
1820
	if(!is_dir("/var/db/dnscache")) {
1821
		mkdir("/var/db/dnscache");
1822
	}
1823
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1824
		$domrecords = array();
1825
		$domips = array();
1826
		exec("host -t A $hostname", $domrecords, $rethost);
1827
		if($rethost == 0) {
1828
			foreach($domrecords as $domr) {
1829
				$doml = explode(" ", $domr);
1830
				$domip = $doml[3];
1831
				/* fill array with domain ip addresses */
1832
				if(is_ipaddr($domip)) {
1833
					$domips[] = $domip;
1834
				}
1835
			}
1836
		}
1837
		sort($domips);
1838
		$contents = "";
1839
		if(! empty($domips)) {
1840
			foreach($domips as $ip) {
1841
				$contents .= "$ip\n";
1842
			}
1843
		}
1844
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1845
	}
1846
}
1847

    
1848
function find_dns_aliases() {
1849
	global $config, $g;
1850
	foreach((array) $config['aliases']['alias'] as $alias) {
1851
		$alias_value = $alias['address'];
1852
		$alias_name = $alias['name'];
1853
		if(stristr($alias_value, " ")) {
1854
			$alias_split = split(" ", $alias_value);
1855
			foreach($alias_split as $as) {
1856
				if(is_fqdn($as)) 
1857
					add_hostname_to_watch($as);			
1858
			}
1859
		} else {
1860
			if(is_fqdn($alias_value)) 
1861
				add_hostname_to_watch($alias_value);
1862
		}
1863
	}
1864
}
1865

    
1866
function is_fqdn($fqdn) {
1867
	$hostname = false;
1868
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1869
		$hostname = true;
1870
	}
1871
	if(preg_match("/\.\./", $fqdn)) {
1872
		$hostname = false;
1873
	}
1874
	if(preg_match("/^\./i", $fqdn)) { 
1875
		$hostname = false;
1876
	}
1877
	if(preg_match("/\//i", $fqdn)) {
1878
		$hostname = false;
1879
	}
1880
	return($hostname);
1881
}
1882

    
1883
function pfsense_default_state_size() {
1884
  /* get system memory amount */
1885
  $memory = get_memory();
1886
  $avail = $memory[0];
1887
  /* Be cautious and only allocate 10% of system memory to the state table */
1888
  $max_states = (int) ($avail/10)*1000;
1889
  return $max_states;
1890
}
1891

    
1892
function rule_popup($src,$srcport,$dst,$dstport){
1893
global $config;
1894
$aliases_array = array();
1895
if($config['aliases']['alias'] <> "" and is_array($config['aliases']['alias']))
1896
{
1897
$span_begin = "";
1898
		$alias_src_span_begin = "";
1899
		$alias_src_span_end = "";
1900
		$alias_src_port_span_begin = "";
1901
		$alias_src_port_span_end = "";
1902
		$alias_dst_span_begin = "";
1903
		$alias_dst_span_end = "";
1904
		$alias_dst_port_span_begin = "";
1905
		$alias_dst_port_span_end = "";
1906
		$alias_content_text = "";
1907
	foreach($config['aliases']['alias'] as $alias_name) 
1908
	{	
1909
	 	$alias_addresses = explode (" ", $alias_name['address']);
1910
	 	$alias_details = explode ("||", $alias_name['detail']);
1911
	 	$alias_objects_with_details = "";
1912
	 	$counter = 0;
1913
	 	foreach($alias_addresses as $alias_ports_address)
1914
	 	{
1915
			$alias_objects_with_details .= $alias_addresses[$counter];
1916
			$alias_detail_default = strpos ($alias_details[$counter],"Entry added");
1917
			if ($alias_details[$counter] != "" && $alias_detail_default === False){
1918
				$alias_objects_with_details .=" - " . $alias_details[$counter];
1919
			}  
1920
			$alias_objects_with_details .= "<br>";
1921
			$counter++;
1922
		}			
1923
		//max character length for caption field
1924
		$maxlength = 60;
1925
		
1926
		$alias_descr_substr = $alias_name['descr'];
1927
		$alias_content_text = htmlspecialchars($alias_objects_with_details);
1928
		$alias_caption = htmlspecialchars($alias_descr_substr . ":");
1929
		$strlength = strlen ($alias_caption);
1930
		if ($strlength >= $maxlength) 
1931
			$alias_caption = substr($alias_caption, 0, $maxlength) . "...";		
1932
						
1933
		$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>";
1934
		
1935
		
1936
		if ($alias_name['name'] == $src)
1937
	 	{										
1938
			$alias_src_span_begin = $span_begin;
1939
		}
1940
	 	if ($alias_name['name'] == $srcport)
1941
	 	{									
1942
			$alias_src_port_span_begin = $span_begin;					
1943
		}
1944
		if ($alias_name['name'] == $dst)
1945
	 	{										
1946
			$alias_dst_span_begin = $span_begin;									
1947
		}
1948
		if ($alias_name['name'] == $dstport)
1949
	 	{											
1950
			$alias_dst_port_span_begin = $span_begin;											
1951
		}										
1952
		
1953
	}
1954
	$descriptions = array ();
1955
	$descriptions['src'] = $alias_src_span_begin;
1956
	$descriptions['srcport'] = $alias_src_port_span_begin;
1957
	$descriptions['dst'] = $alias_dst_span_begin;
1958
	$descriptions['dstport'] = $alias_dst_port_span_begin;
1959
	return $descriptions; 
1960
  }
1961
}
1962
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body') {
1963
	global $ch, $fout, $file_size, $downloaded;
1964
	$file_size  = 1;
1965
	$downloaded = 1;
1966
	/* open destination file */
1967
	$fout = fopen($destination_file, "wb");
1968

    
1969
	/*
1970
	 *	Originally by Author: Keyvan Minoukadeh
1971
	 *	Modified by Scott Ullrich to return Content-Length size
1972
         */
1973

    
1974
	$ch = curl_init();
1975
	curl_setopt($ch, CURLOPT_URL, $url_file);
1976
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1977
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1978
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1979
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '5');
1980
	curl_setopt($ch, CURLOPT_TIMEOUT, 0);
1981
	
1982
	curl_exec($ch);
1983
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1984
	if($fout)
1985
		fclose($fout);
1986
	curl_close($ch);
1987
	return ($http_code == 200) ? true : $http_code;
1988
}
1989

    
1990
function read_header($ch, $string) {
1991
	global $file_size, $fout;
1992
	$length = strlen($string);
1993
	$regs = "";
1994
	ereg("(Content-Length:) (.*)", $string, $regs);
1995
	if($regs[2] <> "") {
1996
		$file_size = intval($regs[2]);
1997
	}
1998
	ob_flush();
1999
	return $length;
2000
}
2001

    
2002
function read_body($ch, $string) {
2003
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
2004
	$length = strlen($string);
2005
	$downloaded += intval($length);
2006
	$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
2007
	$downloadProgress = 100 - $downloadProgress;
2008
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
2009
		if($sendto == "status") {
2010
			$tostatus = $static_status . $downloadProgress . "%";
2011
			update_status($tostatus);
2012
		} else {
2013
			$tooutput = $static_output . $downloadProgress . "%";
2014
			update_output_window($tooutput);
2015
		}
2016
		update_progress_bar($downloadProgress);
2017
		$lastseen = $downloadProgress;
2018
	}
2019
	if($fout)
2020
		fwrite($fout, $string);
2021
	ob_flush();
2022
	return $length;
2023
}
2024

    
2025
/* Compare the current hostname DNS to the DNS cache we made
2026
 * if it has changed we return the old records
2027
 * if no change we return true */
2028
function compare_hostname_to_dnscache($hostname) {
2029
	if(!is_dir("/var/db/dnscache")) {
2030
		mkdir("/var/db/dnscache");
2031
	}
2032
	$hostname = trim($hostname);
2033
	if(is_readable("/var/db/dnscache/{$hostname}")) {
2034
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
2035
	} else {
2036
		$oldcontents = "";
2037
	}
2038
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
2039
		$domrecords = array();
2040
		$domips = array();
2041
		exec("host -t A $hostname", $domrecords, $rethost);
2042
		if($rethost == 0) {
2043
			foreach($domrecords as $domr) {
2044
				$doml = explode(" ", $domr);
2045
				$domip = $doml[3];
2046
				/* fill array with domain ip addresses */
2047
				if(is_ipaddr($domip)) {
2048
					$domips[] = $domip;
2049
				}
2050
			}
2051
		}
2052
		sort($domips);
2053
		$contents = "";
2054
		if(! empty($domips)) {
2055
			foreach($domips as $ip) {
2056
				$contents .= "$ip\n";
2057
			}
2058
		}
2059
	}
2060

    
2061
	if(trim($oldcontents) != trim($contents)) {
2062
		log_error("DNSCACHE: Found old IP {$oldcontents} and new IP {$contents}");
2063
		return ($oldcontents);
2064
	} else {
2065
		return false;
2066
	}
2067
}
2068

    
2069
?>
(22-22/40)