Project

General

Profile

Download (37.1 KB) Statistics
| Branch: | Tag: | Revision:
1 7b2274cb Scott Ullrich
<?php
2 d884b49c Colin Smith
/****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) 2005 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 3a508fe2 Colin Smith
 *
23 d884b49c Colin Smith
 * 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 2265659b Colin Smith
/****f* pfsense-utils/log_error
37
 * NAME
38
 *   log_error - Sends a string to syslog.
39 25192408 Colin Smith
 * INPUTS
40
 *   $error	- string containing the syslog message.
41 2265659b Colin Smith
 * RESULT
42
 *   null
43
 ******/
44 7b2274cb Scott Ullrich
function log_error($error) {
45 98a8e831 Scott Ullrich
    syslog(LOG_WARNING, $error);
46 7b2274cb Scott Ullrich
    return;
47
}
48
49 25192408 Colin Smith
/****f* pfsense-utils/return_dir_as_array
50
 * NAME
51
 *   return_dir_as_array - Return a directory's contents as an array.
52
 * INPUTS
53
 *   $dir	- string containing the path to the desired directory.
54
 * RESULT
55 775433e7 Colin Smith
 *   $dir_array - array containing the directory's contents. This array will be empty if the path specified is invalid.
56 8e362784 Colin Smith
 ******/
57 622fa35a Scott Ullrich
function return_dir_as_array($dir) {
58 174861fd Scott Ullrich
    $dir_array = array();
59 622fa35a Scott Ullrich
    if (is_dir($dir)) {
60 775433e7 Colin Smith
	if ($dh = opendir($dir)) {
61 622fa35a Scott Ullrich
	    while (($file = readdir($dh)) !== false) {
62 174861fd Scott Ullrich
		$canadd = 0;
63
		if($file == ".") $canadd = 1;
64
		if($file == "..") $canadd = 1;
65
		if($canadd == 0)
66
		    array_push($dir_array, $file);
67 622fa35a Scott Ullrich
	    }
68
	    closedir($dh);
69
	}
70
    }
71
    return $dir_array;
72
}
73 7b2274cb Scott Ullrich
74 775433e7 Colin Smith
/****f* pfsense-utils/enable_hardware_offloading
75
 * NAME
76
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
77
 * INPUTS
78
 *   $interface	- string containing the physical interface to work on.
79
 * RESULT
80
 *   null
81
 * NOTES
82
 *   This function only supports the fxp driver's loadable microcode.
83
 ******/
84 ed059571 Scott Ullrich
function enable_hardware_offloading($interface) {
85 31a82233 Scott Ullrich
    global $config;
86
    global $g;
87
    if($g['booting']) {
88 775433e7 Colin Smith
		$supported_ints = array('fxp');
89
		foreach($supported_ints as $int) {
90
			if(stristr($interface,$int) != false) {
91
		    	mwexec("/sbin/ifconfig $interface link0");
92
			}
93
		}
94 c9b4da10 Scott Ullrich
    }
95 775433e7 Colin Smith
    return;
96 ed059571 Scott Ullrich
}
97
98 9f6b1429 Scott Ullrich
/****f* pfsense-utils/setup_microcode
99
 * NAME
100
 *   enumerates all interfaces and calls enable_hardware_offloading which
101
 *   enables a NIC's supported hardware features.
102
 * INPUTS
103
 *   
104
 * RESULT
105
 *   null
106
 * NOTES
107
 *   This function only supports the fxp driver's loadable microcode.
108
 ******/
109
function setup_microcode() {
110
   global $config;
111
    if($ip == "") return;
112
    $i = 0;
113
    $ifdescrs = array('wan', 'lan');
114
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
115
	$ifdescrs['opt' . $j] = "opt" . $j;
116
    }
117
    foreach($ifdescrs as $if)
118
	enable_hardware_offloading($if);
119
}
120
121 775433e7 Colin Smith
/****f* pfsense-utils/return_filename_as_array
122
 * NAME
123
 *   return_filename_as_array - Return a file's contents as an array.
124
 * INPUTS
125 158dd870 Colin Smith
 *   $filename	- string containing the path to the desired file.
126
 *   $strip	- array of characters to strip - default is '#'.
127 775433e7 Colin Smith
 * RESULT
128 158dd870 Colin Smith
 *   $file	- array containing the file's contents.
129 775433e7 Colin Smith
 * NOTES
130
 *   This function strips lines starting with '#' and leading/trailing whitespace by default.
131
 ******/
132
function return_filename_as_array($filename, $strip = array('#')) {
133
    if(file_exists($filename)) $file = file($filename);
134
    if(is_array($file)) {
135 b99a7892 Scott Ullrich
	foreach($file as $line) $line = trim($line);
136 775433e7 Colin Smith
        foreach($strip as $tostrip) $file = preg_grep("/^{$tostrip}/", $file, PREG_GREP_INVERT);
137 98b77940 Scott Ullrich
    }
138 0dd62c88 Bill Marquette
    return $file;
139 3ff9d424 Scott Ullrich
}
140
141 158dd870 Colin Smith
/****f* pfsense-utils/get_carp_status
142
 * NAME
143
 *   get_carp_status - Return whether CARP is enabled or disabled.
144
 * RESULT
145
 *   boolean	- true if CARP is enabled, false if otherwise.
146
 ******/
147 b1174d02 Scott Ullrich
function get_carp_status() {
148
    /* grab the current status of carp */
149 1a97d17c Scott Ullrich
    $status = `/sbin/sysctl net.inet.carp.allow | cut -d" " -f2`;
150
    if(intval($status) == "0") return false;
151 b1174d02 Scott Ullrich
    return true;
152
}
153
154 158dd870 Colin Smith
/****f* pfsense-utils/return_filename_as_string
155
 * NAME
156
 *   return_filename_as_string - Return a file's contents as a string.
157
 * INPUTS
158
 *   $filename  - string containing the path to the desired file.
159
 * RESULT
160
 *   $tmp	- string containing the file's contents.
161
 ******/
162 023c3cc0 Scott Ullrich
function return_filename_as_string($filename) {
163 158dd870 Colin Smith
    if(file_exists($filename)) {
164
        return file_get_contents($filename);
165
    } else {
166
        return false;
167 023c3cc0 Scott Ullrich
    }
168
}
169
170 158dd870 Colin Smith
/****f* pfsense-utils/is_carp_defined
171
 * NAME
172
 *   is_carp_defined - Return whether CARP is detected in the kernel.
173
 * RESULT
174
 *   boolean	- true if CARP is detected, false otherwise.
175
 ******/
176 a8ac6c98 Scott Ullrich
function is_carp_defined() {
177 0f66804f Scott Ullrich
    /* is carp compiled into the kernel and userland? */
178
    $command = "/sbin/sysctl -a | grep carp";
179
    $fd = popen($command . " 2>&1 ", "r");
180
    if(!$fd) {
181 ef4550f8 Scott Ullrich
	log_error("Warning, could not execute command {$command}");
182
	return 0;
183 0f66804f Scott Ullrich
    }
184
    while(!feof($fd)) {
185 ef4550f8 Scott Ullrich
	$tmp .= fread($fd,49);
186 0f66804f Scott Ullrich
    }
187
    fclose($fd);
188 a8ac6c98 Scott Ullrich
189 0f66804f Scott Ullrich
    if($tmp == "")
190 ef4550f8 Scott Ullrich
	return false;
191 0f66804f Scott Ullrich
    else
192 ef4550f8 Scott Ullrich
	return true;
193 a8ac6c98 Scott Ullrich
}
194
195 158dd870 Colin Smith
/****f* pfsense-utils/find_number_of_created_carp_interfaces
196
 * NAME
197
 *   find_number_of_created_carp_interfaces - Return the number of CARP interfaces.
198
 * RESULT
199
 *   $tmp	- Number of currently created CARP interfaces.
200
 ******/
201 ed059571 Scott Ullrich
function find_number_of_created_carp_interfaces() {
202 0f66804f Scott Ullrich
    $command = "/sbin/ifconfig | /usr/bin/grep \"carp*:\" | /usr/bin/wc -l";
203
    $fd = popen($command . " 2>&1 ", "r");
204
    if(!$fd) {
205 ef4550f8 Scott Ullrich
	log_error("Warning, could not execute command {$command}");
206
	return 0;
207 0f66804f Scott Ullrich
    }
208
    while(!feof($fd)) {
209 ef4550f8 Scott Ullrich
	$tmp .= fread($fd,49);
210 0f66804f Scott Ullrich
    }
211
    fclose($fd);
212
    $tmp = intval($tmp);
213
    return $tmp;
214 ed059571 Scott Ullrich
}
215
216 158dd870 Colin Smith
/****f* pfsense-utils/link_ip_to_carp_interface
217
 * NAME
218
 *   link_ip_to_carp_interface - Find where a CARP interface links to.
219
 * INPUTS
220
 *   $ip
221
 * RESULT
222
 *   $carp_ints
223 0c84aff0 Colin Smith
 ******/
224 fa65a62b Scott Ullrich
function link_ip_to_carp_interface($ip) {
225 0f66804f Scott Ullrich
    global $config;
226
    if($ip == "") return;
227
    $i = 0;
228 fa65a62b Scott Ullrich
229 0f66804f Scott Ullrich
    $ifdescrs = array('wan', 'lan');
230
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
231 ef4550f8 Scott Ullrich
	$ifdescrs['opt' . $j] = "opt" . $j;
232 0f66804f Scott Ullrich
    }
233 fa65a62b Scott Ullrich
234 0f66804f Scott Ullrich
    $ft = split("\.", $ip);
235
    $ft_ip = $ft[0] . "." . $ft[1] . "." . $ft[2] . ".";
236
237
    $carp_ints = "";
238
    $num_carp_ints = find_number_of_created_carp_interfaces();
239
    foreach ($ifdescrs as $ifdescr => $ifname) {
240 ef4550f8 Scott Ullrich
	for($x=0; $x<$num_carp_ints; $x++) {
241
	    $carp_int = "carp{$x}";
242
	    $carp_ip = find_interface_ip($carp_int);
243
	    $carp_ft = split("\.", $carp_ip);
244
	    $carp_ft_ip = $carp_ft[0] . "." . $carp_ft[1] . "." . $carp_ft[2] . ".";
245
	    $result = does_interface_exist($carp_int);
246
	    if($result <> true) break;
247
	    $interface = filter_opt_interface_to_real($ifname);
248
	    if($ft_ip == $carp_ft_ip)
249
		if(stristr($carp_ints,$carp_int) == false)
250
		    $carp_ints .= " " . $carp_int;
251
	}
252 0f66804f Scott Ullrich
    }
253
    return $carp_ints;
254 fa65a62b Scott Ullrich
}
255
256 158dd870 Colin Smith
/****f* pfsense-utils/exec_command
257
 * NAME
258
 *   exec_command - Execute a command and return a string of the result.
259
 * INPUTS
260
 *   $command	- String of the command to be executed.
261
 * RESULT
262
 *   String containing the command's result.
263
 * NOTES
264
 *   This function returns the command's stdout and stderr.
265
 ******/
266 5ccfea33 Scott Ullrich
function exec_command($command) {
267 158dd870 Colin Smith
    $output = array();
268
    exec($command . ' 2>&1 ', $output);
269
    return(implode("\n", $output));
270 5ccfea33 Scott Ullrich
}
271
272 fa65a62b Scott Ullrich
/*
273
 * does_interface_exist($interface): return true or false if a interface is detected.
274
 */
275
function does_interface_exist($interface) {
276
    $ints = exec_command("/sbin/ifconfig -l");
277 83661f77 Scott Ullrich
    if(stristr($ints, $interface) !== false)
278 fa65a62b Scott Ullrich
	return true;
279
    else
280
	return false;
281
}
282
283 5ccfea33 Scott Ullrich
/*
284
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
285
 */
286
function convert_ip_to_network_format($ip, $subnet) {
287
    $ipsplit = split('[.]', $ip);
288
    $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
289
    return $string;
290
}
291
292 b04a6ca4 Scott Ullrich
/*
293
 * find_interface_ip($interface): return the interface ip (first found)
294
 */
295
function find_interface_ip($interface) {
296 4983ed8c Scott Ullrich
    if(does_interface_exist($interface) == false) return;
297 e3939e20 Scott Ullrich
    $ip = exec_command("/sbin/ifconfig {$interface} | /usr/bin/grep -w \"inet\" | /usr/bin/cut -d\" \" -f 2");
298 e67f187a Scott Ullrich
    $ip = str_replace("\n","",$ip);
299 b04a6ca4 Scott Ullrich
    return $ip;
300
}
301
302 3314bb92 Scott Ullrich
function guess_interface_from_ip($ipaddress) {
303
    $ints = `/sbin/ifconfig -l`;
304
    $ints_split = split(" ", $ints);
305
    $ip_subnet_split = split("\.", $ipaddress);
306
    $ip_subnet = $ip_subnet_split[0] . "." . $ip_subnet_split[1] . "." . $ip_subnet_split[2] . ".";
307
    foreach($ints_split as $int) {
308
        $ip = find_interface_ip($int);
309
        $ip_split = split("\.", $ip);
310
        $ip_tocheck = $ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".";
311
        if(stristr($ip_tocheck, $ip_subnet) != false) return $int;
312
    }
313
}
314
315 fa65a62b Scott Ullrich
function filter_opt_interface_to_real($opt) {
316 0f66804f Scott Ullrich
    global $config;
317
    return $config['interfaces'][$opt]['if'];
318 fa65a62b Scott Ullrich
}
319
320
function filter_get_opt_interface_descr($opt) {
321 0f66804f Scott Ullrich
    global $config;
322
    return $config['interfaces'][$opt]['descr'];
323 fa65a62b Scott Ullrich
}
324
325 b73cc056 Scott Ullrich
function get_friendly_interface_list_as_array() {
326 0f66804f Scott Ullrich
    global $config;
327
    $ints = array();
328
    $i = 0;
329
    $ifdescrs = array('wan', 'lan');
330
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
331 ef4550f8 Scott Ullrich
	$ifdescrs['opt' . $j] = "opt" . $j;
332 0f66804f Scott Ullrich
    }
333
    $ifdescrs = get_interface_list();
334
    foreach ($ifdescrs as $ifdescr => $ifname) {
335
	array_push($ints,$ifdescr);
336
    }
337
    return $ints;
338 b73cc056 Scott Ullrich
}
339
340 5ccfea33 Scott Ullrich
/*
341
 * find_ip_interface($ip): return the interface where an ip is defined
342
 */
343
function find_ip_interface($ip) {
344 0f66804f Scott Ullrich
    global $config;
345
    $i = 0;
346
    $ifdescrs = array('wan', 'lan');
347
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
348 ef4550f8 Scott Ullrich
	$ifdescrs['opt' . $j] = "opt" . $j;
349 0f66804f Scott Ullrich
    }
350
    foreach ($ifdescrs as $ifdescr => $ifname) {
351
	$int = filter_translate_type_to_real_interface($ifname);
352
	$ifconfig = exec_command("/sbin/ifconfig {$int}");
353
	if(stristr($ifconfig,$ip) <> false)
354
	    return $int;
355
    }
356
    return false;
357 5ccfea33 Scott Ullrich
}
358
359 bc5d2a26 Scott Ullrich
/*
360
 *  filter_translate_type_to_real_interface($interface): returns the real interface name
361
 *                                                       for a friendly interface.  ie: wan
362
 */
363
function filter_translate_type_to_real_interface($interface) {
364 ef4550f8 Scott Ullrich
    global $config;
365
    return $config['interfaces'][$interface]['if'];
366 bc5d2a26 Scott Ullrich
}
367
368 591afdfd Scott Ullrich
/*
369
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
370
 */
371
function get_carp_interface_status($carpinterface) {
372 962f7d25 Scott Ullrich
    $result = does_interface_exist($carpinterface);
373 83661f77 Scott Ullrich
    if($result <> true) return false;
374 e3939e20 Scott Ullrich
    $status = exec_command("/sbin/ifconfig {$carpinterface} | /usr/bin/grep \"carp:\" | /usr/bin/cut -d\" \" -f2");
375 591afdfd Scott Ullrich
    return $status;
376
}
377
378 167bcf84 Scott Ullrich
/*
379
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
380
 */
381
function get_pfsync_interface_status($pfsyncinterface) {
382 962f7d25 Scott Ullrich
    $result = does_interface_exist($pfsyncinterface);
383 4983ed8c Scott Ullrich
    if($result <> true) return;
384 e3939e20 Scott Ullrich
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
385 167bcf84 Scott Ullrich
    return $status;
386
}
387
388 5ccfea33 Scott Ullrich
/*
389
 * find_carp_interface($ip): return the carp interface where an ip is defined
390
 */
391
function find_carp_interface($ip) {
392 ed059571 Scott Ullrich
    $num_carp_ints = find_number_of_created_carp_interfaces();
393
    for($x=0; $x<$num_carp_ints; $x++) {
394 962f7d25 Scott Ullrich
        $result = does_interface_exist("carp{$x}");
395
	if($result <> true) return;
396 f8269a6f Scott Ullrich
	$ifconfig = exec_command("/sbin/ifconfig carp{$x}");
397
	if(stristr($ifconfig,$ip))
398 5ccfea33 Scott Ullrich
	    return "carp" . $x;
399
    }
400
}
401
402
/*
403
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
404
 */
405 a35f1242 Scott Ullrich
function add_rule_to_anchor($anchor, $rule, $label) {
406 8c8e6792 Scott Ullrich
    mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
407 5ccfea33 Scott Ullrich
}
408
409 06e2627e Scott Ullrich
/*
410
 * remove_text_from_file
411
 * remove $text from file $file
412
 */
413
function remove_text_from_file($file, $text) {
414
    global $fd_log;
415
    fwrite($fd_log, "Adding needed text items:\n");
416
    $filecontents = exec_command_and_return_text("cat " . $file);
417
    $textTMP = str_replace($text, "", $filecontents);
418
    $text .= $textTMP;
419
    fwrite($fd_log, $text . "\n");
420
    $fd = fopen($file, "w");
421
    fwrite($fd, $text);
422
    fclose($fd);
423
}
424
425 87362af3 Scott Ullrich
/*
426 ffee1c4d Scott Ullrich
 *  is_package_installed($packagename): returns 1 if a package is installed, 0 otherwise.
427 87362af3 Scott Ullrich
 */
428
function is_package_installed($packagename) {
429
    global $config;
430 ffee1c4d Scott Ullrich
    if($config['installedpackages']['package'] <> "")
431
	foreach ($config['installedpackages']['package'] as $pkg) {
432
	    if($pkg['name'] == $packagename) return 1;
433
	}
434 87362af3 Scott Ullrich
    return 0;
435
}
436
437 06e2627e Scott Ullrich
/*
438
 * lookup pkg array id#
439
 */
440
function get_pkg_id($pkg_name) {
441 0f66804f Scott Ullrich
    global $config;
442
    global $pkg_config;
443 7be9819f Colin Smith
    if(is_array($config['installedpackages']['package'])) {
444
	$i = 0;
445 c2eb36d9 Scott Ullrich
	foreach ($config['installedpackages']['package'] as $pkg) {
446
	    if($pkg['name'] == $pkg_name) return $i;
447
	    $i++;
448
	}
449 7be9819f Colin Smith
	return $i;
450
    }
451 0f66804f Scott Ullrich
    return -1;
452 06e2627e Scott Ullrich
}
453
454 3a003406 Scott Ullrich
/*
455 0f0c5a98 Colin Smith
 *  get_latest_package_version($pkgname): Get current version of a package. Returns latest package version or false
456 1aefe104 Colin Smith
 *  					  if package isn't defined in the currently used pkg_config.xml.
457 3a003406 Scott Ullrich
 */
458
function get_latest_package_version($pkg_name) {
459 5f48ff22 Bill Marquette
    global $g;
460 3a003406 Scott Ullrich
    fetch_latest_pkg_config();
461
    $pkg_config = parse_xml_config_pkg("{$g['tmp_path']}/pkg_config.xml", "pfsensepkgs");
462 5f48ff22 Bill Marquette
    foreach($pkg_config['packages']['package'] as $pkg) {
463 2b246073 Colin Smith
	if($pkg['name'] == $pkg_name) {
464
	    return $pkg['version'];
465 3a003406 Scott Ullrich
	}
466
    }
467 0f0c5a98 Colin Smith
    return false;
468 3a003406 Scott Ullrich
}
469 0025d774 Scott Ullrich
470
/*
471
 * Lookup pkg_id in pkg_config.xml
472
 */
473
function get_available_pkg_id($pkg_name) {
474 c52c9894 Scott Ullrich
    global $pkg_config, $g;
475 7be9819f Colin Smith
    if(!is_array($pkg_config)) {
476
	fetch_latest_pkg_config();
477
    }
478 64663962 Scott Ullrich
    $pkg_config = parse_xml_config_pkg("{$g['tmp_path']}/pkg_config.xml", "pfsensepkgs");
479 0025d774 Scott Ullrich
    $id = 0;
480 c279a6b1 Scott Ullrich
    foreach($pkg_config['packages']['package'] as $pkg) {
481
	if($pkg['name'] == $pkg_name) {
482 0025d774 Scott Ullrich
	    return $id;
483
	}
484
	$id++;
485
    }
486
    return;
487
}
488
489
/*
490
 * fetch_latest_pkg_config: download the latest pkg_config.xml to /tmp/ directory
491
 */
492
function fetch_latest_pkg_config() {
493 5f9b482f Scott Ullrich
    global $g;
494 14be378c Colin Smith
    global $config;
495 5f48ff22 Bill Marquette
    if(!file_exists("{$g['tmp_path']}/pkg_config.xml")) {
496 14be378c Colin Smith
	$pkg_config_location = $g['pkg_config_location'];
497
	$pkg_config_base_url = $g['pkg_config_base_url'];
498
	if(isset($config['system']['alt_pkgconfig_url']['enabled'])) {
499
	    $pkg_config_location = $config['system']['alt_pkgconfig_url']['pkgconfig_base_url'] . $config['system']['alt_pkgconfig_url']['pkgconfig_filename'];
500
	    $pkg_config_base_url = $config['system']['alt_pkgconfig_url']['pkgconfig_base_url'];
501 2ba6bed1 Bill Marquette
	}
502 14be378c Colin Smith
	mwexec("/usr/bin/fetch -o {$g['tmp_path']}/pkg_config.xml {$pkg_config_location}");
503 0025d774 Scott Ullrich
	if(!file_exists("{$g['tmp_path']}/pkg_config.xml")) {
504 563461bc Colin Smith
	    print_info_box_np("Could not download pkg_config.xml from " . $pkg_config_base_url . ". Check your DNS settings.");
505 0025d774 Scott Ullrich
	    die;
506 a9d49723 Colin Smith
    	}
507 0025d774 Scott Ullrich
    }
508
    return;
509
}
510
511 06e2627e Scott Ullrich
/*
512
 * add_text_to_file($file, $text): adds $text to $file.
513
 * replaces the text if it already exists.
514
 */
515
function add_text_to_file($file, $text) {
516
    global $fd_log;
517
    fwrite($fd_log, "Adding needed text items:\n");
518
    $filecontents = exec_command_and_return_text("cat " . $file);
519
    $filecontents = str_replace($text, "", $filecontents);
520
    $text = $filecontents . $text;
521
    fwrite($fd_log, $text . "\n");
522
    $fd = fopen($file, "w");
523
    fwrite($fd, $text . "\n");
524
    fclose($fd);
525
}
526
527
/*
528
 * get_filename_from_url($url): converts a url to its filename.
529
 */
530
function get_filename_from_url($url) {
531 0f66804f Scott Ullrich
    $filenamesplit = split("/", $url);
532
    foreach($filenamesplit as $fn) $filename = $fn;
533
    return $filename;
534 06e2627e Scott Ullrich
}
535
536
/*
537
 *   update_output_window: update bottom textarea dynamically.
538
 */
539
function update_output_window($text) {
540 0f66804f Scott Ullrich
    $log = ereg_replace("\n", "\\n", $text);
541
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
542 06e2627e Scott Ullrich
}
543
544
/*
545
 *   get_dir: return an array of $dir
546
 */
547
function get_dir($dir) {
548 0f66804f Scott Ullrich
    $dir_array = array();
549
    $d = dir($dir);
550
    while (false !== ($entry = $d->read())) {
551 ef4550f8 Scott Ullrich
	array_push($dir_array, $entry);
552 0f66804f Scott Ullrich
    }
553
    $d->close();
554
    return $dir_array;
555 06e2627e Scott Ullrich
}
556
557
/*
558
 *   update_output_window: update top textarea dynamically.
559
 */
560
function update_status($status) {
561 ef4550f8 Scott Ullrich
    echo "\n<script language=\"JavaScript\">document.forms[0].status.value=\"" . $status . "\";</script>";
562 06e2627e Scott Ullrich
}
563
564
/*
565
 *   exec_command_and_return_text_array: execute command and return output
566
 */
567
function exec_command_and_return_text_array($command) {
568 0f66804f Scott Ullrich
    $counter = 0;
569
    $fd = popen($command . " 2>&1 ", "r");
570
    while(!feof($fd)) {
571 ef4550f8 Scott Ullrich
	$tmp .= fread($fd,49);
572 0f66804f Scott Ullrich
    }
573
    fclose($fd);
574
    $temp_array = split("\n", $tmp);
575
    return $tmp_array;
576 06e2627e Scott Ullrich
}
577
578
/*
579
 *   exec_command_and_return_text: execute command and return output
580
 */
581
function exec_command_and_return_text($command) {
582 ef4550f8 Scott Ullrich
    return exec_command($command);
583 06e2627e Scott Ullrich
}
584
585
/*
586
 *   exec_command_and_return_text: execute command and update output window dynamically
587
 */
588
function execute_command_return_output($command) {
589
    global $fd_log;
590
    $fd = popen($command . " 2>&1 ", "r");
591
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
592
    $counter = 0;
593
    $counter2 = 0;
594
    while(!feof($fd)) {
595
	$tmp = fread($fd, 50);
596
	$tmp1 = ereg_replace("\n","\\n", $tmp);
597
	$text = ereg_replace("\"","'", $tmp1);
598
	if($lasttext == "..") {
599
	    $text = "";
600
	    $lasttext = "";
601
	    $counter=$counter-2;
602
	} else {
603
	    $lasttext .= $text;
604
	}
605
	if($counter > 51) {
606
	    $counter = 0;
607
	    $extrabreak = "\\n";
608
	} else {
609
	    $extrabreak = "";
610
	    $counter++;
611
	}
612
	if($counter2 > 600) {
613
	    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
614
	    $counter2 = 0;
615
	} else
616
	    $counter2++;
617
	echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = this.document.forms[0].output.value + \"" . $text . $extrabreak .  "\"; f('output'); </script>";
618
    }
619
    fclose($fd);
620
}
621
622 55be70e6 Scott Ullrich
/*
623
 * convert_friendly_interface_to_real_interface_name($interface): convert WAN to FXP0
624
 */
625
function convert_friendly_interface_to_real_interface_name($interface) {
626 54f4caed Scott Ullrich
    global $config;
627 a7f5febb Scott Ullrich
    $lc_interface = strtolower($interface);
628 303831c6 Scott Ullrich
    if($lc_interface == "lan") return $config['interfaces']['lan']['if'];
629
    if($lc_interface == "wan") return $config['interfaces']['wan']['if'];
630 401e59a9 Scott Ullrich
    $i = 0;
631 303831c6 Scott Ullrich
    $ifdescrs = array();
632
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
633
	$ifdescrs['opt' . $j] = "opt" . $j;
634 401e59a9 Scott Ullrich
    foreach ($ifdescrs as $ifdescr => $ifname) {
635 303831c6 Scott Ullrich
	if(strtolower($ifname) == $lc_interface)
636
	    return $config['interfaces'][$ifname]['if'];
637
	if(strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)
638 401e59a9 Scott Ullrich
	    return $config['interfaces'][$ifname]['if'];
639
    }
640
    return $interface;
641 55be70e6 Scott Ullrich
}
642
643 cc869478 Scott Ullrich
/*
644
 * convert_real_interface_to_friendly_interface_name($interface): convert fxp0 -> wan, etc.
645
 */
646
function convert_real_interface_to_friendly_interface_name($interface) {
647 0f66804f Scott Ullrich
    global $config;
648
    $i = 0;
649
    $ifdescrs = array('wan', 'lan');
650
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
651
	$ifdescrs['opt' . $j] = "opt" . $j;
652
    foreach ($ifdescrs as $ifdescr => $ifname) {
653
	$int = filter_translate_type_to_real_interface($ifname);
654
	if($ifname == $interface) return $ifname;
655
	if($int == $interface) return $ifname;
656
    }
657
    return $interface;
658 cc869478 Scott Ullrich
}
659
660 06e2627e Scott Ullrich
/*
661
 * update_progress_bar($percent): updates the javascript driven progress bar.
662
 */
663
function update_progress_bar($percent) {
664 0f66804f Scott Ullrich
    if($percent > 100) $percent = 1;
665
    echo "\n<script type=\"text/javascript\" language=\"javascript\">";
666
    echo "\ndocument.progressbar.style.width='" . $percent . "%';";
667
    echo "\n</script>";
668 06e2627e Scott Ullrich
}
669
670 238f6962 Colin Smith
/*
671 cdd1d57e Colin Smith
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
672
 * This function may also print output to the terminal indicating progress.
673 238f6962 Colin Smith
 */
674 07a5ca20 Colin Smith
function resync_all_package_configs($show_message = false) {
675 0f66804f Scott Ullrich
    global $config;
676
    $i = 0;
677
    log_error("Resyncing configuration for all packages.");
678
    if(!$config['installedpackages']['package']) return;
679
    if($show_message == true) print "Syncing packages:";
680
    foreach($config['installedpackages']['package'] as $package) {
681 ef4550f8 Scott Ullrich
	if($show_message == true) print " " . $package['name'];
682
	sync_package($i, true, true);
683
	$i++;
684 0f66804f Scott Ullrich
    }
685
    if($show_message == true) print ".\n";
686 e0f91f5f Scott Ullrich
}
687
688 b7c502bb Colin Smith
/*
689 fbc24b62 Colin Smith
 * sweep_package_processes(): Periodically kill a package's unnecessary processes
690
 *			      that may still be running (a server that does not automatically timeout, for example)
691 b7c502bb Colin Smith
 */
692
function sweep_package_processes() {
693
    global $config;
694
    if(!$config['installedpackages']['package']) return;
695
    foreach($config['installedpackages']['package'] as $package) {
696
        $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
697
        if($pkg_config['swept_processes'] <> "") {
698 ef4550f8 Scott Ullrich
            mwexec("/usr/bin/killall " . $pkg_config['swept_processes']);
699
            log_error("Killed " . $package['name'] . "'s unnecessary processes.");
700 fa35df12 Scott Ullrich
        }
701 b7c502bb Colin Smith
    }
702 fa35df12 Scott Ullrich
}
703 b7c502bb Colin Smith
704 b45ea709 Scott Ullrich
/*
705 76177335 Scott Ullrich
 * gather_altq_queue_stats():  gather alq queue stats and return an array that
706 b45ea709 Scott Ullrich
 *                             is queuename|qlength|measured_packets
707 fbc24b62 Colin Smith
 *                             NOTE: this command takes 5 seconds to run
708 b45ea709 Scott Ullrich
 */
709 6a153733 Scott Ullrich
function gather_altq_queue_stats($dont_return_root_queues) {
710 e90bc39f Scott Ullrich
    mwexec("/usr/bin/killall -9 pfctl");
711 9c0ad35c Scott Ullrich
    $stats = `/sbin/pfctl -vvsq & /bin/sleep 5;/usr/bin/killall pfctl 2>/dev/null`;
712 b45ea709 Scott Ullrich
    $stats_array = split("\n", $stats);
713
    $queue_stats = array();
714
    foreach ($stats_array as $stats_line) {
715
        if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
716
            $queue_name = $match_array[1][0];
717 fccb044c Scott Ullrich
        if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
718
            $speed = $match_array[1][0];
719 e90bc39f Scott Ullrich
        if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
720
            $borrows = $match_array[1][0];
721 4bed294c Bill Marquette
        if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
722
            $suspends = $match_array[1][0];
723 04e6e7b7 Bill Marquette
        if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
724
            $drops = $match_array[1][0];
725 b45ea709 Scott Ullrich
        if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
726
            $measured = $match_array[1][0];
727 6a153733 Scott Ullrich
	    if($dont_return_root_queues == true)
728
		if(stristr($queue_name,"root_") == false)
729 122a9c39 Scott Ullrich
		    array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
730 b45ea709 Scott Ullrich
        }
731
    }
732
    return $queue_stats;
733
}
734 fa35df12 Scott Ullrich
735 fbc24b62 Colin Smith
/*
736 0ad0f98c Scott Ullrich
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
737 fbc24b62 Colin Smith
 *					 Useful for finding paths and stripping file extensions.
738
 */
739 29c3c942 Colin Smith
function reverse_strrchr($haystack, $needle)
740
{
741
               return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
742 fbc24b62 Colin Smith
}
743
744
/*
745 ade51705 Colin Smith
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
746 2bccc5fc Colin Smith
 *
747
 * $filetype = "all" || ".xml", ".tgz", etc.
748 0d34044c Colin Smith
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
749 5f9be1c6 Colin Smith
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
750 2bccc5fc Colin Smith
 *
751 fbc24b62 Colin Smith
 */
752 5f9be1c6 Colin Smith
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
753 0f66804f Scott Ullrich
    global $config;
754
    if(!is_numeric($pkg_name)) {
755 ef4550f8 Scott Ullrich
	$pkg_name = get_pkg_id($pkg_name);
756
	if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
757 0f66804f Scott Ullrich
    } else {
758 ef4550f8 Scott Ullrich
	if(!isset($config['installedpackages']['package'][$pkg_id])) return; // No package belongs to the pkg_id passed to this function.
759 0f66804f Scott Ullrich
    }
760
    $package = $config['installedpackages']['package'][$pkg_id];
761
    print '$package done.';
762
    if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { // If the package's config file doesn't exist, log an error and fetch it.
763 ef4550f8 Scott Ullrich
	log_error("Fetching missing configuration XML for " . $package['name']);
764
	mwexec("/usr/bin/fetch -o /usr/local/pkg/" . $package['configurationfile'] . " http://www.pfsense.com/packages/config/" . $package['configurationfile']);
765 0f66804f Scott Ullrich
    }
766
    $pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
767
    if($pkg_xml['additional_files_needed'] != "") {
768 ef4550f8 Scott Ullrich
	foreach($pkg_xml['additional_files_needed'] as $item) {
769
	    if (($return_nosync == 0) && (isset($item['nosync']))) continue; // Do not return depends with nosync set if not required.
770
	    $depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
771
	    $depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
772
	    if (($filetype != "all") && (!preg_match("/${filetype}/i", $depend_file))) continue;
773
	    if ($item['prefix'] != "") {
774
		$prefix = $item['prefix'];
775
	    } else {
776
		$prefix = "/usr/local/pkg/";
777
	    }
778
	    if(!file_exists($prefix . $pkg_name)) {
779
		log_error("Fetching missing dependency (" . $depend_name . ") for " . $pkg_name);
780
		mwexec("/usr/local/bin/fetch -o " . $prefix . $depend_file . " " . $item['name']['0']);
781 4d321b3a Bill Marquette
		if($item['chmod'] != "")
782
		    chmod($prefix . $depend_file, $item['chmod']); // Handle chmods.
783 ef4550f8 Scott Ullrich
	    }
784
	    switch ($format) {
785
	    case "files":
786
		$depends[] = $depend_file;
787
		break;
788
	    case "names":
789
		switch ($filetype) {
790
		case "all":
791
		    if(preg_match("/\.xml/i", $depend_file)) {
792
			$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
793
			$depends[] = $depend_xml['name'];
794
			break;
795 0f66804f Scott Ullrich
		    } else {
796 ef4550f8 Scott Ullrich
			$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
797
			break;
798 0f66804f Scott Ullrich
		    }
799 ef4550f8 Scott Ullrich
		case ".xml":
800
		    $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
801
		    $depends[] = $depend_xml['name'];
802
		    break;
803
		default:
804
		    $depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
805
		    break;
806
		}
807 0f66804f Scott Ullrich
	    }
808 ef4550f8 Scott Ullrich
	}
809 0f66804f Scott Ullrich
	return $depends;
810
    }
811 fbc24b62 Colin Smith
}
812
813 44dc32e4 Scott Ullrich
/*
814
 * is_service_running($service_name): checks to see if a service is running.
815
 *                                    if the service is running returns 1.
816
 */
817
function is_service_running($service_name) {
818 7ebb7114 Colin Smith
    $status = `/bin/ps ax | grep {$service_name} | grep -v grep`;
819 44dc32e4 Scott Ullrich
    $status_split = split("\n", $service_name);
820
    $counter = 0;
821 257ff0ff Scott Ullrich
    foreach ($status_split as $ss) $counter++;
822 7ebb7114 Colin Smith
    if($counter > 0) return 1;
823 44dc32e4 Scott Ullrich
    return 0;
824
}
825 f8891a0f Scott Ullrich
826
/*
827 832f1b83 Scott Ullrich
 *  backup_config_section($section): returns as an xml file string of
828
 *                                   the configuration section
829 f8891a0f Scott Ullrich
 */
830
function backup_config_section($section) {
831
    global $config;
832 6d501961 Scott Ullrich
    $new_section = &$config[$section];
833 832f1b83 Scott Ullrich
    /* generate configuration XML */
834
    $xmlconfig = dump_xml_config($new_section, $section);
835 8602b9f6 Scott Ullrich
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
836 014beac3 Scott Ullrich
    return $xmlconfig;
837 f8891a0f Scott Ullrich
}
838
839
/*
840
 *  restore_config_section($section, new_contents): restore a configuration section,
841
 *                                                  and write the configuration out
842
 *                                                  to disk/cf.
843
 */
844
function restore_config_section($section, $new_contents) {
845
    global $config;
846 832f1b83 Scott Ullrich
    $fout = fopen("{$g['tmp_path']}/tmpxml","w");
847 014beac3 Scott Ullrich
    fwrite($fout, $new_contents);
848 832f1b83 Scott Ullrich
    fclose($fout);
849 014beac3 Scott Ullrich
    $section_xml = parse_xml_config_pkg($g['tmp_path'] . "/tmpxml", $section);
850 832f1b83 Scott Ullrich
    $config[$section] = &$section_xml;
851
    unlink($g['tmp_path'] . "/tmpxml");
852 782c32a7 Bill Marquette
    write_config("Restored {$section} of config file (maybe from CARP partner)");
853 46624b94 Scott Ullrich
    return;
854 f8891a0f Scott Ullrich
}
855
856 e99d11e3 Scott Ullrich
/*
857 c70c4e8a Colin Smith
 * http_post($server, $port, $url, $vars): does an http post to a web server
858
 *                                         posting the vars array.
859 e99d11e3 Scott Ullrich
 * written by nf@bigpond.net.au
860
 */
861
function http_post($server, $port, $url, $vars) {
862 0f66804f Scott Ullrich
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
863
    $urlencoded = "";
864
    while (list($key,$value) = each($vars))
865 ef4550f8 Scott Ullrich
	$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
866 0f66804f Scott Ullrich
    $urlencoded = substr($urlencoded,0,-1);
867 e99d11e3 Scott Ullrich
868 0f66804f Scott Ullrich
    $content_length = strlen($urlencoded);
869 e99d11e3 Scott Ullrich
870 0f66804f Scott Ullrich
    $headers = "POST $url HTTP/1.1
871 e99d11e3 Scott Ullrich
Accept: */*
872
Accept-Language: en-au
873
Content-Type: application/x-www-form-urlencoded
874
User-Agent: $user_agent
875
Host: $server
876
Connection: Keep-Alive
877
Cache-Control: no-cache
878
Content-Length: $content_length
879
880
";
881
882 0f66804f Scott Ullrich
    $fp = fsockopen($server, $port, $errno, $errstr);
883
    if (!$fp) {
884 ef4550f8 Scott Ullrich
	return false;
885 0f66804f Scott Ullrich
    }
886 e99d11e3 Scott Ullrich
887 0f66804f Scott Ullrich
    fputs($fp, $headers);
888
    fputs($fp, $urlencoded);
889 e99d11e3 Scott Ullrich
890 0f66804f Scott Ullrich
    $ret = "";
891
    while (!feof($fp))
892 ef4550f8 Scott Ullrich
	$ret.= fgets($fp, 1024);
893 e99d11e3 Scott Ullrich
894 0f66804f Scott Ullrich
    fclose($fp);
895 e99d11e3 Scott Ullrich
896 0f66804f Scott Ullrich
    return $ret;
897 e99d11e3 Scott Ullrich
898
}
899 f8891a0f Scott Ullrich
900 ee8f4a58 Scott Ullrich
/*
901
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
902
 */
903
if (!function_exists('php_check_syntax')){
904
   function php_check_syntax($code_to_check, &$errormessage){
905 c177d6ad Scott Ullrich
	return false;
906 7197df7d Scott Ullrich
        $fout = fopen("/tmp/codetocheck.php","w");
907
        $code = $_POST['content'];
908
        $code = str_replace("<?php", "", $code);
909
        $code = str_replace("?>", "", $code);
910
        fwrite($fout, "<?php\n\n");
911
        fwrite($fout, $code);
912
        fwrite($fout, "\n\n?>\n");
913
        fclose($fout);
914
        $command = "/usr/local/bin/php -l /tmp/codetocheck.php";
915
        $output = exec_command($command);
916
        if (stristr($output, "Errors parsing") == false) {
917
            echo "false\n";
918
            $errormessage = '';
919
            return(false);
920
        } else {
921
            $errormessage = $output;
922
            return(true);
923
        }
924 ee8f4a58 Scott Ullrich
    }
925
}
926
927
/*
928
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
929
 */
930 7197df7d Scott Ullrich
if (!function_exists('php_check_syntax')){
931
   function php_check_syntax($code_to_check, &$errormessage){
932 c177d6ad Scott Ullrich
	return false;
933 7197df7d Scott Ullrich
        $command = "/usr/local/bin/php -l " . $code_to_check;
934
        $output = exec_command($command);
935
        if (stristr($output, "Errors parsing") == false) {
936
            echo "false\n";
937
            $errormessage = '';
938
            return(false);
939
        } else {
940
            $errormessage = $output;
941
            return(true);
942
        }
943
    }
944 ee8f4a58 Scott Ullrich
}
945
946 5c52313f Colin Smith
/*
947 068b8784 Colin Smith
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
948 5c52313f Colin Smith
 */
949 f01a0942 Colin Smith
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
950 0f66804f Scott Ullrich
    global $config;
951 0b739f1b Scott Ullrich
952 244e3102 Scott Ullrich
    if(!file_exists("/usr/local/pkg")) mwexec("/bin/mkdir -p /usr/local/pkg/pf");
953 0f66804f Scott Ullrich
    if(!$config['installedpackages']['package']) return;
954
    if(!is_numeric($pkg_name)) {
955 ef4550f8 Scott Ullrich
	$pkg_id = get_pkg_id($pkg_name);
956
	if($pkg_id == -1) return -1; // This package doesn't really exist - exit the function.
957 0f66804f Scott Ullrich
    } else {
958 ef4550f8 Scott Ullrich
	$pkg_id = $pkg_name;
959
	if(!isset($config['installedpackages']['package'][$pkg_id]))
960
	    return;  // No package belongs to the pkg_id passed to this function.
961 0f66804f Scott Ullrich
    }
962
    $package = $config['installedpackages']['package'][$pkg_id];
963
    if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
964 ef4550f8 Scott Ullrich
	//if($show_message == true) print "(f)"; Don't mess with this until the package system has settled.
965
	log_error("Fetching missing configuration XML for " . $package['name']);
966
	mwexec("/usr/bin/fetch -o /usr/local/pkg/" . $package['configurationfile'] . " http://www.pfsense.com/packages/config/" . $package['configurationfile']);
967 0f66804f Scott Ullrich
    }
968
    $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
969
    if(isset($pkg_config['nosync'])) continue;
970
    //if($show_message == true) print "Syncing " . $pkg_name;
971 194b4e0a Colin Smith
    if($pkg['custom_php_global_functions'] <> "")
972
        eval($pkg['custom_php_global_functions']);
973 ef4550f8 Scott Ullrich
    if($pkg_config['custom_php_command_before_form'] <> "")
974
	eval($pkg_config['custom_php_command_before_form']);
975
    if($pkg_config['custom_php_resync_config_command'] <> "")
976
	eval($pkg_config['custom_php_resync_config_command']);
977 0f66804f Scott Ullrich
    if($sync_depends == true) {
978 ef4550f8 Scott Ullrich
	$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
979
	if(is_array($depends)) {
980
	    foreach($depends as $item) {
981
		$item_config = parse_xml_config_pkg("/usr/local/pkg/" . $item, "packagegui");
982
		if(isset($item_config['nosync'])) continue;
983
		if($item_config['custom_php_command_before_form'] <> "") {
984
		    eval($item_config['custom_php_command_before_form']);
985
		    print "Evaled dependency.";
986
		}
987
		if($item_config['custom_php_resync_config_command'] <> "") {
988
		    eval($item_config['custom_php_resync_config_command']);
989
		    print "Evaled dependency.";
990
		}
991
		if($show_message == true) print " " . $item_config['name'];
992 0f66804f Scott Ullrich
	    }
993 ef4550f8 Scott Ullrich
	}
994 0f66804f Scott Ullrich
    }
995
    // if($show_message == true) print ".";
996 5c52313f Colin Smith
}
997 bebb9d4d Bill Marquette
998
/*
999 7eb2e498 Colin Smith
 * rmdir_recursive($path,$follow_links=false)
1000 6f2e9d7f Bill Marquette
 * Recursively remove a directory tree (rm -rf path)
1001
 * This is for directories _only_
1002
 */
1003
function rmdir_recursive($path,$follow_links=false) {
1004 7eb2e498 Colin Smith
	$to_do = glob($path);
1005
	if(!is_array($to_do)) {
1006 0fdf1eaa Colin Smith
		if(file_exists($to_do)) {
1007
			$dir = opendir($path);
1008 7eb2e498 Colin Smith
			while ($entry = readdir($dir)) {
1009 0fdf1eaa Colin Smith
				if (is_file("$path/$entry") || ((!$follow_links) && is_link("$path/$entry")))
1010
					unlink("$path/$entry");
1011
      	 			elseif (is_dir("$path/$entry") && $entry!='.' && $entry!='..')
1012
					rmdir_recursive("$path/$entry");
1013 7eb2e498 Colin Smith
			}
1014
			closedir($dir);
1015 0fdf1eaa Colin Smith
			rmdir($path);
1016
			return;
1017
		}
1018
	} else {
1019
		foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
1020
			if(file_exists($workingdir)) {
1021
				$dir = opendir($workingdir);
1022
				while ($entry = readdir($dir)) {
1023
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
1024
					unlink("$workingdir/$entry");
1025
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
1026
					rmdir_recursive("$workingdir/$entry");
1027
				}
1028
				closedir($dir);
1029
				rmdir($workingdir);
1030
                	}
1031
		}
1032 0a44a421 Colin Smith
		return;
1033 6f2e9d7f Bill Marquette
	}
1034 0a44a421 Colin Smith
	return;
1035 6f2e9d7f Bill Marquette
}
1036
1037 1682dc1e Bill Marquette
/*
1038
 * safe_mkdir($path, $mode = 0755)
1039
 * create directory if it doesn't already exist and isn't a file!
1040
 */
1041
function safe_mkdir($path, $mode=0755) {
1042
	if (!is_file($path) && !is_dir($path))
1043
		return mkdir($path, $mode);
1044
	else
1045
		return false;
1046
}
1047
1048
/*
1049
 * make_dirs($path, $mode = 0755)
1050
 * create directory tree recursively (mkdir -p)
1051
 */
1052
function make_dirs($path, $mode = 0755)
1053
{
1054
	return is_dir($path) || (make_dirs(dirname($path), $mode) && safe_mkdir($path, $mode));
1055
}
1056
1057 d884b49c Colin Smith
/****f* pfsense-utils/auto_upgrade
1058
 * NAME
1059
 *   auto_upgrade - pfSense autoupdate handler.
1060
 * FUNCTION
1061
 *   Begin the pfSense autoupdate process. This function calls check_firmware_version to get
1062
 *   a list of current versions and then loops through them, applying binary diffs etc.
1063
 * RESULT
1064
 *   null
1065
 * BUGS
1066
 *   This function needs to have logic in place to automatically switch over to full updates
1067
 *   if a certain amount of binary diffs do not apply successfully.
1068
 * SEE ALSO
1069
 *   pfsense.utils/check_firmware_version
1070
 ******/
1071 f5ff6e0a Colin Smith
function auto_upgrade() {
1072 02b8eb37 Scott Ullrich
        global $config, $g;
1073 13f1a01d Colin Smith
	if (isset($config['system']['alt_firmware_url']['enabled'])) {
1074
                $firmwareurl=$config['system']['alt_firmware_url']['firmware_base_url'];
1075
                $firmwarepath=$config['system']['alt_firmware_url']['firmware_filename'];
1076
        } else {
1077
                $firmwareurl=$g['firmwarebaseurl'];
1078
                $firmwarepath=$g['firmwarefilename'];
1079
        }
1080 5e6e5d49 Scott Ullrich
        if($config['system']['proxy_auth_username'] <> "")
1081
	    $http_auth_username = $config['system']['proxy_auth_username'];
1082
        if($config['system']['proxy_auth_password'] <> "")
1083
	    $http_auth_password = $config['system']['proxy_auth_password'];
1084 f5ff6e0a Colin Smith
        if (isset($config['system']['alt_firmware_url']['enabled'])) {
1085
                $firmwareurl=$config['system']['alt_firmware_url']['firmware_base_url'];
1086
                $firmwarename=$config['system']['alt_firmware_url']['firmware_filename'];
1087
        } else {
1088
                $firmwareurl=$g['firmwarebaseurl'];
1089
                $firmwarename=$g['firmwarefilename'];
1090
        }
1091
        exec_rc_script_async("/etc/rc.firmware_auto {$firmwareurl} {$firmwarename} {$http_auth_username} {$http_auth_password}");
1092 56fda621 Colin Smith
	return;
1093 f5ff6e0a Colin Smith
}
1094
1095 c7934653 Colin Smith
/*
1096
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1097
 */
1098 bd21e2b7 Colin Smith
function check_firmware_version($tocheck = "all", $return_php = true) {
1099 c7934653 Colin Smith
        global $g;
1100 13f1a01d Colin Smith
	$versioncheck_base_url = $g['versioncheckbaseurl'];
1101 c7934653 Colin Smith
        $versioncheck_path = $g['versioncheckpath'];
1102
        if(isset($config['system']['alt_firmware_url']['enabled']) and isset($config['system']['alt_firmware_url']['versioncheck_base_url'])) {
1103
                $versioncheck_base_url = $config['system']['alt_firmware_url']['versioncheck_base_url'];
1104 13f1a01d Colin Smith
	}
1105 bd21e2b7 Colin Smith
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1106 79020a5e Colin Smith
			"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1107
			"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1108
			"platform" => trim(file_get_contents('/etc/platform'))
1109
		);
1110 bd21e2b7 Colin Smith
	if($tocheck = "all") {
1111
		$params = $rawparams;
1112
	} else {
1113
		foreach($tocheck as $check) {
1114
			$params['check'] = $rawparams['check'];
1115
			$params['platform'] = $rawparams['platform'];
1116
		}
1117
	}
1118 52621d32 Colin Smith
	if(isset($config['system']['firmwarebranch'])) {
1119 bd21e2b7 Colin Smith
		$params['branch'] = $config['system']['firmwarebranch'];
1120 52621d32 Colin Smith
	}
1121 79020a5e Colin Smith
	$xmlparams = php_value_to_xmlrpc($params);
1122
        $msg = new XML_RPC_Message('pfsense.get_firmware_version', array($xmlparams));
1123 c54f8fa8 Colin Smith
        $cli = new XML_RPC_Client($versioncheck_path, $versioncheck_base_url);
1124 8ac0a4de Colin Smith
	$resp = $cli->send($msg, 10);
1125
	if(!$resp or $resp->faultCode()) {
1126
		$raw_versions = false;
1127
	} else {
1128
		$raw_versions = xmlrpc_value_to_php($resp->value());
1129
		$raw_versions["current"] = $params;
1130
	}
1131 79020a5e Colin Smith
	return $raw_versions;
1132 c7934653 Colin Smith
}
1133
1134 bd21e2b7 Colin Smith
?>