Project

General

Profile

Download (56.8 KB) Statistics
| Branch: | Tag: | Revision:
1 7597c8e8 Colin Smith
<?php
2 8c6516d1 Colin Smith
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6 33b7cc0d Colin Smith
 *   This file contains various functions used by the pfSense package system.
7 8c6516d1 Colin Smith
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11 a70cdb73 Phil Davis
 * Copyright (C) 2010 Ermal Luci
12 0e16b9ca Scott Ullrich
 * Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
13 8c6516d1 Colin Smith
 * All rights reserved.
14
 * Redistribution and use in source and binary forms, with or without
15
 * modification, are permitted provided that the following conditions are met:
16
 *
17
 * 1. Redistributions of source code must retain the above copyright notice,
18
 * this list of conditions and the following disclaimer.
19
 *
20
 * 2. Redistributions in binary form must reproduce the above copyright
21
 * notice, this list of conditions and the following disclaimer in the
22
 * documentation and/or other materials provided with the distribution.
23
 *
24
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
26
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
28
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
 * POSSIBILITY OF SUCH DAMAGE.
34
 *
35
 */
36 523855b0 Scott Ullrich
37
/*
38 b098343a Ermal
	pfSense_BUILDER_BINARIES:	/usr/bin/cd	/usr/bin/tar	/usr/sbin/fifolog_create	/bin/chmod
39
	pfSense_BUILDER_BINARIES:	/usr/sbin/pkg_add	/usr/sbin/pkg_info	/usr/sbin/pkg_delete	/bin/rm
40 523855b0 Scott Ullrich
	pfSense_MODULE:	pkg
41
*/
42
43 01a6e665 Ermal
require_once("globals.inc");
44 33b7cc0d Colin Smith
require_once("xmlrpc.inc");
45 7eea4407 Ermal
require_once("service-utils.inc");
46 093bcebc Scott Ullrich
if(file_exists("/cf/conf/use_xmlreader"))
47
	require_once("xmlreader.inc");
48
else
49
	require_once("xmlparse.inc");
50 7597c8e8 Colin Smith
require_once("pfsense-utils.inc");
51 33b7cc0d Colin Smith
52 f041d58b Scott Ullrich
if(!function_exists("update_status")) {
53
	function update_status($status) {
54
		echo $status . "\n";
55 b47833cc Scott Ullrich
	}
56
}
57 762cb660 Scott Ullrich
if(!function_exists("update_output_window")) {
58
	function update_output_window($status) {
59
		echo $status . "\n";
60
	}
61
}
62 b47833cc Scott Ullrich
63 eab543ed Ermal
if (!function_exists("pkg_debug")) {
64
	/* set up logging if needed */
65
	function pkg_debug($msg) {
66
		global $g, $debug, $fd_log;
67
68
		if (!$debug)
69
			return;
70
71
		if (!$fd_log) {
72
			if (!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w"))
73
				update_output_window("Warning, could not open log for writing.");
74
		}
75
		@fwrite($fd_log, $msg);
76
	}
77
}
78
79 1b28121f Ermal
$vardb = "/var/db/pkg";
80
safe_mkdir($vardb);
81 eab543ed Ermal
$g['platform'] = trim(file_get_contents("/etc/platform"));
82 7955cde8 Scott Ullrich
83 43ad432c Ermal Lu?i
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
84 a70cdb73 Phil Davis
	conf_mount_rw();
85 d3c02149 Scott Ullrich
	safe_mkdir("/usr/local/pkg");
86 7955cde8 Scott Ullrich
	safe_mkdir("/usr/local/pkg/pf");	
87 a70cdb73 Phil Davis
	conf_mount_ro();
88 e7405fbf Scott Ullrich
}
89 33b7cc0d Colin Smith
90 645f2fa8 Phil Davis
// Use a longer (30 second) connect timeout when trying to download each package file.
91
// Package installs are not holding up general boot and routing/firewall functionality,
92
// so it is nicer to wait a while if necessary rather than abort.
93
define('PKG_FILE_DOWNLOAD_CONNECT_TIMEOUT', '30');
94
95 31e7e1bc Scott Ullrich
/****f* pkg-utils/remove_package
96
 * NAME
97
 *   remove_package - Removes package from FreeBSD if it exists
98
 * INPUTS
99
 *   $packagestring	- name/string to check for
100
 * RESULT
101
 *   none
102
 * NOTES
103
 *   
104
 ******/
105
function remove_freebsd_package($packagestring) {
106 8059acb5 Phil Davis
	// The packagestring passed in must be the full PBI package name, 
107
	// as displayed by the pbi_info utility. e.g. "package-1.2.3_4-i386" 
108
	// It must NOT have ".pbi" on the end.
109 3cc28680 Renato Botelho
	$links = get_pbi_binaries(escapeshellarg($packagestring));
110
	foreach($links as $link)
111
		if (is_link("/usr/local/{$link['link_name']}"))
112
			@unlink("/usr/local/{$link['link_name']}");
113 384e2647 Renato Botelho
	exec("/usr/local/sbin/pbi_delete " . escapeshellarg($packagestring) . " 2>>/tmp/pbi_delete_errors.txt");
114 31e7e1bc Scott Ullrich
}
115
116 33b7cc0d Colin Smith
/****f* pkg-utils/is_package_installed
117
 * NAME
118
 *   is_package_installed - Check whether a package is installed.
119
 * INPUTS
120
 *   $packagename	- name of the package to check
121
 * RESULT
122
 *   boolean	- true if the package is installed, false otherwise
123
 * NOTES
124
 *   This function is deprecated - get_pkg_id() can already check for installation.
125
 ******/
126 8c6516d1 Colin Smith
function is_package_installed($packagename) {
127 33b7cc0d Colin Smith
	$pkg = get_pkg_id($packagename);
128 b2a66231 Ermal
	if($pkg == -1)
129
		return false;
130 33b7cc0d Colin Smith
	return true;
131 8c6516d1 Colin Smith
}
132 43db85f8 Scott Ullrich
133 33b7cc0d Colin Smith
/****f* pkg-utils/get_pkg_id
134
 * NAME
135
 *   get_pkg_id - Find a package's numeric ID.
136
 * INPUTS
137
 *   $pkg_name	- name of the package to check
138
 * RESULT
139
 *   integer    - -1 if package is not found, >-1 otherwise
140
 ******/
141 8c6516d1 Colin Smith
function get_pkg_id($pkg_name) {
142 e65a287f Scott Ullrich
	global $config;
143
144 2addd5b2 Ermal
	if (is_array($config['installedpackages']['package'])) {
145
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
146 b2a66231 Ermal
			if($pkg['name'] == $pkg_name)
147 2addd5b2 Ermal
				return $idx;
148 e65a287f Scott Ullrich
		}
149
	}
150
	return -1;
151 8c6516d1 Colin Smith
}
152
153 75a01a7c Phil Davis
/****f* pkg-utils/get_pkg_internal_name
154
 * NAME
155
 *   get_pkg_internal_name - Find a package's internal name (e.g. squid3 internal name is squid)
156
 * INPUTS
157
 *   $package - array of package data from config
158
 * RESULT
159
 *   string - internal name (if defined) or default to package name
160
 ******/
161
function get_pkg_internal_name($package) {
162
	if (isset($package['internal_name']) && ($package['internal_name'] != "")) {
163
		/* e.g. name is Ipguard-dev, internal name is ipguard */
164
		$pkg_internal_name = $package['internal_name'];
165
	} else {
166
		$pkg_internal_name = $package['name'];
167
	}
168
	return $pkg_internal_name;
169
}
170
171 33b7cc0d Colin Smith
/****f* pkg-utils/get_pkg_info
172
 * NAME
173 5775f324 Chris Buechler
 *   get_pkg_info - Retrieve package information from package server.
174 33b7cc0d Colin Smith
 * INPUTS
175 5b542ae5 Bill Marquette
 *   $pkgs - 'all' to retrieve all packages, an array containing package names otherwise
176
 *   $info - 'all' to retrieve all information, an array containing keys otherwise
177 33b7cc0d Colin Smith
 * RESULT
178
 *   $raw_versions - Array containing retrieved information, indexed by package name.
179
 ******/
180
function get_pkg_info($pkgs = 'all', $info = 'all') {
181 7597c8e8 Colin Smith
	global $g;
182 b2a66231 Ermal
183 2addd5b2 Ermal
	$freebsd_machine = php_uname("m");
184 340c0677 Scott Ullrich
	$params = array(
185
		"pkg" => $pkgs, 
186
		"info" => $info, 
187 770a7759 Renato Botelho
		"freebsd_version" => get_freebsd_version(),
188 e4c3d767 sullrich
		"freebsd_machine" => $freebsd_machine
189
	);
190 e65a287f Scott Ullrich
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
191
	return $resp ? $resp : array();
192
}
193
194
function get_pkg_sizes($pkgs = 'all') {
195 2addd5b2 Ermal
	global $config, $g;
196 b2a66231 Ermal
197 2addd5b2 Ermal
	$freebsd_machine = php_uname("m");
198
	$params = array(
199
		"pkg" => $pkgs, 
200 770a7759 Renato Botelho
		"freebsd_version" => get_freebsd_version(),
201 2addd5b2 Ermal
		"freebsd_machine" => $freebsd_machine
202
	);
203 e65a287f Scott Ullrich
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
204 7c8f3711 jim-p
	$xmlrpc_base_url = get_active_xml_rpc_base_url();
205 ffba4976 jim-p
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
206 43db85f8 Scott Ullrich
	$resp = $cli->send($msg, 10);
207 2addd5b2 Ermal
	if(!is_object($resp))
208
		log_error("Could not get response from XMLRPC server!");
209
 	else if (!$resp->faultCode()) {
210 e65a287f Scott Ullrich
		$raw_versions = $resp->value();
211 34da63c3 Colin Smith
		return xmlrpc_value_to_php($raw_versions);
212
	}
213 b2a66231 Ermal
214
	return array();
215 8c6516d1 Colin Smith
}
216
217 cac80f49 Phil Davis
/****f* pkg-utils/compare_pkg_versions
218
 * NAME
219
 *   compare_pkg_versions - Decide if the installed package is newer, the same or older than the available package.
220
 * INPUTS
221
 *   $installed_pkg_ver - the package version installed on the system.
222
 *   $available_pkg_ver - the package version available from the package server.
223
 * RESULT
224
 *   -1 - the installed package is older (an upgrade is available)
225
 *   0 - the package versions are the same
226
 *   1 - the installed package is newer (somebody has installed a newer version than is officially available)
227
 ******/
228
function compare_pkg_versions($installed_pkg_ver, $available_pkg_ver) {
229
	// If the strings are the same then short-cut all the processing.
230
	if (strcmp($installed_pkg_ver, $available_pkg_ver) == 0) {
231
		return 0;
232
	}
233
234
	// Split into pieces that are groups of digits and groups of non-digits.
235
	$installed_arr = preg_split( '/([0-9]+)/', $installed_pkg_ver, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
236
	$available_arr = preg_split( '/([0-9]+)/', $available_pkg_ver, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
237
	foreach ($installed_arr as $n => $val) {
238
		if (array_key_exists($n, $available_arr)) {
239
			// Check if this piece looks like a genuine integer like "123", "0" rather than "05", "005", "1a", "abc".
240
			// Note: At this point the pieces cannot be like "-1", "+1" so we do not need to worry about those possibilities that filter_var() will see as "genuine integers".
241
			$val1_as_int = filter_var($val, FILTER_VALIDATE_INT);
242
			$val2_as_int = filter_var($available_arr[$n], FILTER_VALIDATE_INT);
243
			if (($val1_as_int === false) || ($val2_as_int === false)) {
244
				// One of them does not look like a genuine integer so use string comparison.
245 4fdcdbf3 Phil Davis
				if (strcasecmp($val, $available_arr[$n]) > 0) {
246 cac80f49 Phil Davis
					return 1;
247 4fdcdbf3 Phil Davis
				} elseif (strcasecmp($val, $available_arr[$n]) < 0) {
248 cac80f49 Phil Davis
					return -1;
249
				}
250
			} else {
251
				// Both look like genuine integers so compare as numbers.
252
				if ($val1_as_int > $val2_as_int) {
253
					return 1;
254
				} elseif ($val1_as_int < $val2_as_int) {
255
					return -1;
256
				}
257
			}
258
		} else {
259
			// The installed package version is greater, since all components have matched up to this point
260
			// and available_arr doesn't have any more data.
261
			return 1;
262
		}
263
	}
264
265
	if (count($available_arr) > count($installed_arr)) {
266
		// All the installed package components matched the corresponding available package components.
267
		// The available package is longer than the installed package, so the installed package is old.
268
		return -1;
269
	} else {
270
		// Both versions are of equal length and value.
271
		return 0;
272
	}
273
274
	return $resp ? $resp : array();
275
}
276
277 8c6516d1 Colin Smith
/*
278
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
279
 * This function may also print output to the terminal indicating progress.
280
 */
281
function resync_all_package_configs($show_message = false) {
282 b1224cdc jim-p
	global $config, $pkg_interface, $g;
283 b2a66231 Ermal
284 6acdf659 Carlos Eduardo Ramos
	log_error(gettext("Resyncing configuration for all packages."));
285 06e57df8 Scott Ullrich
286 2addd5b2 Ermal
	if (!is_array($config['installedpackages']['package']))
287 3a9eb3c9 Ermal
		return;
288 06e57df8 Scott Ullrich
289 3a9eb3c9 Ermal
	if($show_message == true)
290
		echo "Syncing packages:";
291 b2a66231 Ermal
292 78b94214 Ermal
	conf_mount_rw();
293 06e57df8 Scott Ullrich
294 2addd5b2 Ermal
	foreach($config['installedpackages']['package'] as $idx => $package) {
295
		if (empty($package['name']))
296
			continue;
297
		if($show_message == true)
298
			echo " " . $package['name'];
299
		get_pkg_depends($package['name'], "all");
300 285ef132 Ermal LUÇI
		if(platform_booting() != true)
301 75a01a7c Phil Davis
			stop_service(get_pkg_internal_name($package));
302 2addd5b2 Ermal
		sync_package($idx, true, true);
303
		if($pkg_interface == "console") 
304 c92ccac7 Vinicius Coque
			echo "\n" . gettext("Syncing packages:");
305 e65a287f Scott Ullrich
	}
306 06e57df8 Scott Ullrich
307 b2a66231 Ermal
	if($show_message == true)
308 08452bff Warren Baker
		echo " done.\n";
309 06e57df8 Scott Ullrich
310 3a9eb3c9 Ermal
	@unlink("/conf/needs_package_sync");
311 78b94214 Ermal
	conf_mount_ro();
312 8c6516d1 Colin Smith
}
313
314 7597c8e8 Colin Smith
/*
315
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
316
 *				package is installed.
317
 */
318
function is_freebsd_pkg_installed($pkg) {
319 86af45ec Scott Ullrich
	if(!$pkg) 
320
		return;
321 fcf92dae Ermal
	$output = "";
322 e9490019 Renato Botelho
	$_gb = exec("/usr/local/sbin/pbi_info " . escapeshellarg($pkg) . ' 2>/dev/null', $output, $retval);
323 b2a66231 Ermal
324 fcf92dae Ermal
	return (intval($retval) == 0);
325 7597c8e8 Colin Smith
}
326
327 8c6516d1 Colin Smith
/*
328
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
329
 *
330
 * $filetype = "all" || ".xml", ".tgz", etc.
331
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
332
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
333
 *
334
 */
335
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
336 e65a287f Scott Ullrich
	global $config;
337 b2a66231 Ermal
338 e65a287f Scott Ullrich
	$pkg_id = get_pkg_id($pkg_name);
339 b2a66231 Ermal
	if($pkg_id == -1)
340
		return -1; // This package doesn't really exist - exit the function.
341
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
342
		return; // No package belongs to the pkg_id passed to this function.
343
344
	$package =& $config['installedpackages']['package'][$pkg_id];
345 e65a287f Scott Ullrich
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
346 addc0439 Renato Botelho
		log_error(sprintf(gettext('The %1$s package is missing required dependencies and must be reinstalled. %2$s'), $package['name'], $package['configurationfile']));
347 2c794549 Ermal
		uninstall_package($package['name']);
348 2addd5b2 Ermal
		if (install_package($package['name']) < 0) {
349
			log_error("Failed reinstalling package {$package['name']}.");
350 2c794549 Ermal
			return false;
351 2addd5b2 Ermal
		}
352 093441f0 Colin Smith
	}
353 19a11678 Colin Smith
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
354 b2a66231 Ermal
	if (!empty($pkg_xml['additional_files_needed'])) {
355 e65a287f Scott Ullrich
		foreach($pkg_xml['additional_files_needed'] as $item) {
356 b2a66231 Ermal
			if ($return_nosync == 0 && isset($item['nosync']))
357
				continue; // Do not return depends with nosync set if not required.
358 e65a287f Scott Ullrich
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
359
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
360 b2a66231 Ermal
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file)))
361 2b7fb769 Renato Botelho
			if (($filetype != "all") && (strtolower(substr($depend_file, -strlen($filetype))) != strtolower($filetype)))
362 b2a66231 Ermal
					continue;
363 2c794549 Ermal
			if ($item['prefix'] != "")
364 e65a287f Scott Ullrich
				$prefix = $item['prefix'];
365 2c794549 Ermal
			else
366 e65a287f Scott Ullrich
				$prefix = "/usr/local/pkg/";
367 017d381c Scott Ullrich
			// Ensure that the prefix exists to avoid installation errors.
368
			if(!is_dir($prefix)) 
369 b2a66231 Ermal
				exec("/bin/mkdir -p {$prefix}");
370 3e155fab Scott Ullrich
			if(!file_exists($prefix . $depend_file))
371 6acdf659 Carlos Eduardo Ramos
				log_error(sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']));
372 e65a287f Scott Ullrich
			switch ($format) {
373 b2a66231 Ermal
			case "files":
374
				$depends[] = $prefix . $depend_file;
375
				break;
376
			case "names":
377
				switch ($filetype) {
378
				case "all":
379
					if(preg_match("/\.xml/i", $depend_file)) {
380
						$depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui");
381
						if (!empty($depend_xml))
382 017d381c Scott Ullrich
							$depends[] = $depend_xml['name'];
383 b2a66231 Ermal
					} else
384
						$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
385
					break;
386
				case ".xml":
387
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
388
					if (!empty($depend_xml))
389
						$depends[] = $depend_xml['name'];
390
					break;
391
				default:
392
					$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
393
					break;
394
				}
395 e65a287f Scott Ullrich
			}
396 b2a66231 Ermal
		}
397 e65a287f Scott Ullrich
		return $depends;
398
	}
399 8c6516d1 Colin Smith
}
400
401 2c794549 Ermal
function uninstall_package($pkg_name) {
402 fcf92dae Ermal
	global $config, $static_output;
403 f0695975 Scott Ullrich
	global $builder_package_install;
404 b2a66231 Ermal
405 f898cf33 Scott Ullrich
	$id = get_pkg_id($pkg_name);
406 df5da531 Ermal
	if ($id >= 0) {
407 75a01a7c Phil Davis
		stop_service(get_pkg_internal_name($config['installedpackages']['package'][$id]));
408 a5566aa8 Vinicius Coque
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package_pbi'];
409 fcf92dae Ermal
		$static_output .= "Removing package...\n";
410
		update_output_window($static_output);
411 b7729cee Ermal
		if (is_array($pkg_depends)) {
412
			foreach ($pkg_depends as $pkg_depend)
413 fcf92dae Ermal
				delete_package($pkg_depend);
414 569aeae7 Vinicius Coque
		} else {
415 8059acb5 Phil Davis
			// The packages (1 or more) are all in one long string.
416
			// We need to pass them 1 at a time to delete_package.
417
			// Compress any multiple whitespace (sp, tab, cr, lf...) into a single space char.
418
			$pkg_dep_str = preg_replace("'\s+'", ' ', $pkg_depends);
419
			// Get rid of any leading or trailing space.
420
			$pkg_dep_str = trim($pkg_dep_str);
421
			// Now we have a space-separated string. Make it into an array and process it.
422
			$pkg_dep_array = explode(" ", $pkg_dep_str);
423
			foreach ($pkg_dep_array as $pkg_depend) {
424
				delete_package($pkg_depend);
425
			}
426 b7729cee Ermal
		}
427 1570d27a Ermal Lu?i
	}
428 f898cf33 Scott Ullrich
	delete_package_xml($pkg_name);
429 4c6a49d7 Scott Ullrich
430 8c147077 Ermal
	$static_output .= gettext("done.") . "\n";
431
	update_output_window($static_output);
432 f898cf33 Scott Ullrich
}
433
434 7bbfe007 Scott Ullrich
function force_remove_package($pkg_name) {
435
	delete_package_xml($pkg_name);
436
}
437
438 8c6516d1 Colin Smith
/*
439
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
440
 */
441
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
442 c132bdb0 Ermal
	global $config, $config_parsed;
443 f0695975 Scott Ullrich
	global $builder_package_install;
444
	
445 09e11b69 Scott Ullrich
	// If this code is being called by pfspkg_installer 
446
	// which the builder system uses then return (ignore).
447 f0695975 Scott Ullrich
	if($builder_package_install)
448
		return;
449 b2a66231 Ermal
	
450
	if(empty($config['installedpackages']['package']))
451
		return;
452 669e1adb Bill Marquette
	if(!is_numeric($pkg_name)) {
453
		$pkg_id = get_pkg_id($pkg_name);
454 b2a66231 Ermal
		if($pkg_id == -1)
455
			return -1; // This package doesn't really exist - exit the function.
456 3e643dba Ermal LUÇI
	} else
457 669e1adb Bill Marquette
		$pkg_id = $pkg_name;
458 3e643dba Ermal LUÇI
459
	if(!is_array($config['installedpackages']['package'][$pkg_id]))
460
		return;  // No package belongs to the pkg_id passed to this function.
461
462
	$package =& $config['installedpackages']['package'][$pkg_id];
463 669e1adb Bill Marquette
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
464 6acdf659 Carlos Eduardo Ramos
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
465 7bbfe007 Scott Ullrich
		force_remove_package($package['name']);
466 2c794549 Ermal
		return -1;
467
	}
468
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
469 2addd5b2 Ermal
	if(isset($pkg_config['nosync']))
470
		return;
471 2c794549 Ermal
	/* Bring in package include files */
472
	if (!empty($pkg_config['include_file'])) {
473
		$include_file = $pkg_config['include_file'];
474
		if (file_exists($include_file))
475
			require_once($include_file);
476
		else {
477
			/* XXX: What the heck is this?! */
478
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
479
			uninstall_package($package['name']);
480
			if (install_package($package['name']) < 0) {
481
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
482
				return -1;
483 83cfae8d Ermal Lu?i
			}
484 30e4c34a Scott Ullrich
		}
485 2c794549 Ermal
	}
486 30e4c34a Scott Ullrich
487 2c794549 Ermal
	if(!empty($pkg_config['custom_php_global_functions']))
488
		eval($pkg_config['custom_php_global_functions']);
489
	if(!empty($pkg_config['custom_php_resync_config_command']))
490
		eval($pkg_config['custom_php_resync_config_command']);
491
	if($sync_depends == true) {
492
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
493
		if(is_array($depends)) {
494
			foreach($depends as $item) {
495
				if(!file_exists($item)) {
496 2addd5b2 Ermal
					require_once("notices.inc");
497 b96f6496 Renato Botelho
					file_notice($package['name'], sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']), "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
498 2c794549 Ermal
					log_error("Could not find {$item}. Reinstalling package.");
499
					uninstall_package($pkg_name);
500 2addd5b2 Ermal
					if (install_package($pkg_name) < 0) {
501
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
502
						return -1;
503
					}
504 2c794549 Ermal
				} else {
505
					$item_config = parse_xml_config_pkg($item, "packagegui");
506
					if (empty($item_config))
507
						continue;
508
					if(isset($item_config['nosync']))
509
						continue;
510 2addd5b2 Ermal
					if (!empty($item_config['include_file'])) {
511
						if (file_exists($item_config['include_file']))	
512
							require_once($item_config['include_file']);
513
						else {
514
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
515
							continue;
516
						}
517
					}
518
					if($item_config['custom_php_global_functions'] <> "")
519
						eval($item_config['custom_php_global_functions']);
520 2c794549 Ermal
					if($item_config['custom_php_resync_config_command'] <> "")
521
						eval($item_config['custom_php_resync_config_command']);
522
					if($show_message == true)
523
						print " " . $item_config['name'];
524 669e1adb Bill Marquette
				}
525
			}
526
		}
527
	}
528 8c6516d1 Colin Smith
}
529
530 7597c8e8 Colin Smith
/*
531 43dad535 Vinicius Coque
 * pkg_fetch_recursive: Download and install a FreeBSD PBI package. This function provides output to
532 7597c8e8 Colin Smith
 * 			a progress bar and output window.
533
 */
534 0cdf4e87 Ermal
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
535 83491ba5 jim-p
	global $static_output, $g, $config;
536 b2a66231 Ermal
537 19f576fd Scott Ullrich
	// Clean up incoming filenames
538
	$filename = str_replace("  ", " ", $filename);
539
	$filename = str_replace("\n", " ", $filename);
540
	$filename = str_replace("  ", " ", $filename);
541
542 cfbfd941 smos
	$pkgs = explode(" ", $filename);
543 764bd0ac Scott Ullrich
	foreach($pkgs as $filename) {
544 21762198 jim-p
		$filename = trim($filename);
545 e61f548f Ermal
		if ($g['platform'] == "nanobsd") {
546 05ff388a Scott Ullrich
			$pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ ";
547
			$pkgstagingdir = "/root/tmp";
548
			if (!is_dir($pkgstagingdir))
549
				mkdir($pkgstagingdir);
550
			$pkgstaging = "-o {$pkgstagingdir}/instmp.XXXXXX";
551
			$fetchdir = $pkgstagingdir;
552 aeaa7358 Ermal
		} else {
553 05ff388a Scott Ullrich
			$fetchdir = $g['tmp_path'];
554 aeaa7358 Ermal
		}
555 22beab88 jim-p
556 a448b35f jim-p
		/* FreeBSD has no PBI's hosted, so fall back to our own URL for now. (Maybe fail to PC-BSD?) */
557
		$rel = get_freebsd_version();
558 375fce94 Chris Buechler
		$priv_url = "https://files.pfsense.org/packages/{$rel}/All/";
559 05ff388a Scott Ullrich
		if (empty($base_url))
560
			$base_url = $priv_url;
561
		if (substr($base_url, -1) == "/")
562
			$base_url = substr($base_url, 0, -1);
563
		$fetchto = "{$fetchdir}/apkg_{$filename}";
564
		$static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... ";
565 645f2fa8 Phil Davis
		if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto, "read_body", PKG_FILE_DOWNLOAD_CONNECT_TIMEOUT) !== true) {
566
			if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto, "read_body", PKG_FILE_DOWNLOAD_CONNECT_TIMEOUT) !== true) {
567 05ff388a Scott Ullrich
				$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
568
				update_output_window($static_output);
569
				return false;
570
			} else if ($base_url == $priv_url) {
571
				$static_output .= " failed to download.\n";
572
				update_output_window($static_output);
573
				return false;
574
			} else {
575
				$static_output .= " [{$osname} repository]\n";
576
				update_output_window($static_output);
577
			}
578
		}
579
		$static_output .= " (extracting)\n";
580
		update_output_window($static_output);
581 43dad535 Vinicius Coque
582 05ff388a Scott Ullrich
		$pkgaddout = "";
583 b2a66231 Ermal
584 e5b5e29c Renato Botelho
		$no_checksig = "";
585
		if (isset($config['system']['pkg_nochecksig']))
586
			$no_checksig = "--no-checksig";
587
588 e4a4ec89 Renato Botelho
		$result = exec("/usr/local/sbin/pbi_add " . $pkgstaging . " -f -v {$no_checksig} " . escapeshellarg($fetchto) . " 2>&1", $pkgaddout, $rc);
589 6635f5b9 Renato Botelho
		pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\n");
590
		if ($rc == 0) {
591 7860191a Renato Botelho
			$pbi_name = preg_replace('/\.pbi$/','',$filename);
592
593
			$gb = exec("/usr/local/sbin/pbi_info {$pbi_name} | /usr/bin/awk '/Prefix/ {print $2}'", $pbi_prefix);
594
			$pbi_prefix = $pbi_prefix[0];
595
596
			$links = get_pbi_binaries(escapeshellarg($pbi_name));
597 3cc28680 Renato Botelho
			foreach($links as $link) {
598
				@unlink("/usr/local/{$link['link_name']}");
599
				@symlink("{$link['target']}","/usr/local/{$link['link_name']}");
600 43dad535 Vinicius Coque
			}
601 7860191a Renato Botelho
602
			$extra_links = array(
603
				array("target" => "bin", "link_name" => "sbin"),
604
				array("target" => "local/lib", "link_name" => "lib"),
605
				array("target" => "local/libexec", "link_name" => "libexec"),
606
				array("target" => "local/share", "link_name" => "share"),
607 6c87714d Renato Botelho
				array("target" => "local/www", "link_name" => "www"),
608 7860191a Renato Botelho
				array("target" => "local/etc", "link_name" => "etc")
609
			);
610
611
			foreach ($extra_links as $link) {
612
				if (!file_exists($pbi_prefix . "/" . $link['target']))
613
					continue;
614
				@rmdir("{$pbi_prefix}/{$link['link_name']}");
615
				unlink_if_exists("{$pbi_prefix}/{$link['link_name']}");
616
				@symlink("{$pbi_prefix}/{$link['target']}", "{$pbi_prefix}/{$link['link_name']}");
617
			}
618 6635f5b9 Renato Botelho
			pkg_debug("pbi_add successfully completed.\n");
619
		} else {
620
			if (is_array($pkgaddout))
621
				foreach ($pkgaddout as $line)
622
					$static_output .= " " . $line .= "\n";
623
624
			update_output_window($static_output);
625
			pkg_debug("pbi_add failed.\n");
626
			return false;
627 43dad535 Vinicius Coque
		}
628
	}
629 e65a287f Scott Ullrich
	return true;
630 8c6516d1 Colin Smith
}
631
632 384e2647 Renato Botelho
function get_pbi_binaries($pbi) {
633
	$result = array();
634
635
	if (empty($pbi))
636
		return $result;
637
638
	$gb = exec("/usr/local/sbin/pbi_info {$pbi} | /usr/bin/awk '/Prefix/ {print $2}'", $pbi_prefix);
639
	$pbi_prefix = $pbi_prefix[0];
640
641
	if (empty($pbi_prefix))
642
		return $result;
643
644
	foreach(array('bin', 'sbin') as $dir) {
645
		if(!is_dir("{$pbi_prefix}/{$dir}"))
646
			continue;
647
648
		$files = glob("{$pbi_prefix}/{$dir}/*.pbiopt");
649
		foreach($files as $f) {
650
			$pbiopts = file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
651
			foreach($pbiopts as $pbiopt) {
652
				if (!preg_match('/^TARGET:\s+(.*)$/', $pbiopt, $matches))
653
					continue;
654
655 3cc28680 Renato Botelho
				$result[] = array(
656
					'target' => preg_replace('/\.pbiopt$/', '', $f),
657
					'link_name' => $matches[1]);
658 384e2647 Renato Botelho
			}
659
		}
660
	}
661
662
	return $result;
663
}
664
665 bfe9c9e7 jim-p
666 633d51b7 bcyrill
function install_package($package, $pkg_info = "", $force_install = false) {
667 2addd5b2 Ermal
	global $g, $config, $static_output, $pkg_interface;
668 b2a66231 Ermal
669 43ad432c Ermal Lu?i
	/* safe side. Write config below will send to ro again. */
670
	conf_mount_rw();
671
672 dbef849d Scott Ullrich
	if($pkg_interface == "console") 	
673
		echo "\n";
674 7597c8e8 Colin Smith
	/* fetch package information if needed */
675 b2a66231 Ermal
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
676 7597c8e8 Colin Smith
		$pkg_info = get_pkg_info(array($package));
677
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
678 1b28121f Ermal
		if (empty($pkg_info)) {
679
			conf_mount_ro();
680
			return -1;
681
		}
682 7597c8e8 Colin Smith
	}
683 633d51b7 bcyrill
	if (!$force_install) {
684
		$compatible = true;
685
		$version = rtrim(file_get_contents("/etc/version"));
686
		
687
		if (isset($pkg_info['required_version']))
688
			$compatible = (pfs_version_compare("", $version, $pkg_info['required_version']) >= 0);
689
		if (isset($pkg_info['maximum_version']))
690
			$compatible = $compatible && (pfs_version_compare("", $version, $pkg_info['maximum_version']) <= 0);
691
		
692
		if (!$compatible) {
693
			log_error(sprintf(gettext('Package %s is not supported on this version.'), $pkg_info['name']));
694
			$static_output .= sprintf(gettext("Package %s is not supported on this version."), $pkg_info['name']);
695
			update_status($static_output);
696
			
697
			conf_mount_ro();
698
			return -1;
699
		}
700
	}
701 c92ccac7 Vinicius Coque
	pkg_debug(gettext("Beginning package installation.") . "\n");
702
	log_error(sprintf(gettext('Beginning package installation for %s .'), $pkg_info['name']));
703
	$static_output .= sprintf(gettext("Beginning package installation for %s ."), $pkg_info['name']);
704 1b28121f Ermal
	update_status($static_output);
705 bfe9c9e7 jim-p
706 7597c8e8 Colin Smith
	/* fetch the package's configuration file */
707 bfe9c9e7 jim-p
	pkg_fetch_config_file($package, $pkg_info);
708
709 7597c8e8 Colin Smith
	/* add package information to config.xml */
710
	$pkgid = get_pkg_id($pkg_info['name']);
711 6acdf659 Carlos Eduardo Ramos
	$static_output .= gettext("Saving updated package information...") . " ";
712 7597c8e8 Colin Smith
	update_output_window($static_output);
713
	if($pkgid == -1) {
714
		$config['installedpackages']['package'][] = $pkg_info;
715 b1e4005f Vinicius Coque
		$changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']);
716 6acdf659 Carlos Eduardo Ramos
		$to_output = gettext("done.") . "\n";
717 7597c8e8 Colin Smith
	} else {
718
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
719 6acdf659 Carlos Eduardo Ramos
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
720
		$to_output = gettext("overwrite!") . "\n";
721 7597c8e8 Colin Smith
	}
722 6622e126 Scott Ullrich
	if(file_exists('/conf/needs_package_sync'))
723
		@unlink('/conf/needs_package_sync');
724 3339fac0 Ermal Lu?i
	conf_mount_ro();
725 f9c8e64c jim-p
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
726 7597c8e8 Colin Smith
	$static_output .= $to_output;
727
	update_output_window($static_output);
728
	/* install other package components */
729 2c794549 Ermal
	if (!install_package_xml($package)) {
730
		uninstall_package($package);
731
		write_config($changedesc);
732 d274a75b Renato Botelho
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
733 b96f6496 Renato Botelho
		$static_output .= gettext("Failed to install package.") . "\n";
734 2c794549 Ermal
		update_output_window($static_output);
735
		return -1;
736
	} else {
737 b96f6496 Renato Botelho
		$static_output .= gettext("Writing configuration... ");
738 2c794549 Ermal
		update_output_window($static_output);
739
		write_config($changedesc);
740 7525f05d jim-p
		log_error(sprintf(gettext("Successfully installed package: %s."), $pkg_info['name']));
741 b96f6496 Renato Botelho
		$static_output .= gettext("done.") . "\n";
742 2c794549 Ermal
		update_output_window($static_output);
743
		if($pkg_info['after_install_info']) 
744
			update_output_window($pkg_info['after_install_info']);	
745
	}
746 7597c8e8 Colin Smith
}
747
748 cfde64b8 Scott Ullrich
function get_after_install_info($package) {
749
	global $pkg_info;
750
	/* fetch package information if needed */
751
	if(!$pkg_info or !is_array($pkg_info[$package])) {
752
		$pkg_info = get_pkg_info(array($package));
753
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
754
	}
755
	if($pkg_info['after_install_info'])
756
		return $pkg_info['after_install_info'];
757
}
758
759 2a0e6517 Colin Smith
function eval_once($toeval) {
760
	global $evaled;
761 57965588 Colin Smith
	if(!$evaled) $evaled = array();
762 2a0e6517 Colin Smith
	$evalmd5 = md5($toeval);
763
	if(!in_array($evalmd5, $evaled)) {
764 8604523b Ermal Lu?i
		@eval($toeval);
765 2a0e6517 Colin Smith
		$evaled[] = $evalmd5;
766
	}
767
	return;
768
}
769
770 7597c8e8 Colin Smith
function install_package_xml($pkg) {
771 c132bdb0 Ermal
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
772 b2a66231 Ermal
773 7597c8e8 Colin Smith
	if(($pkgid = get_pkg_id($pkg)) == -1) {
774 6acdf659 Carlos Eduardo Ramos
		$static_output .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n");
775 7597c8e8 Colin Smith
		update_output_window($static_output);
776 1a22ffcd Scott Ullrich
		if($pkg_interface <> "console") {
777 91f026b0 ayvis
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
778
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
779 1a22ffcd Scott Ullrich
		}
780 7597c8e8 Colin Smith
		sleep(1);
781 2c794549 Ermal
		return false;
782 b2a66231 Ermal
	} else
783 7597c8e8 Colin Smith
		$pkg_info = $config['installedpackages']['package'][$pkgid];
784 b2a66231 Ermal
785 a6d0d461 Colin Smith
	/* pkg_add the package and its dependencies */
786 e65a287f Scott Ullrich
	if($pkg_info['depends_on_package_base_url'] != "") {
787 dbef849d Scott Ullrich
		if($pkg_interface == "console") 
788
			echo "\n";
789 6acdf659 Carlos Eduardo Ramos
		update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies."));
790
		$static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... ");
791 e65a287f Scott Ullrich
		$static_orig = $static_output;
792
		$static_output .= "\n";
793
		update_output_window($static_output);
794 a5566aa8 Vinicius Coque
		foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) {
795 e65a287f Scott Ullrich
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
796 b3a4ff7c Scott Ullrich
			$static_output = $static_orig . "\nChecking for package installation... ";
797 1b28121f Ermal
			update_output_window($static_output);
798 ad88ff3f Ermal
			if (!is_freebsd_pkg_installed($pkg_name)) {
799 a0b205f0 Ermal
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
800 ad88ff3f Ermal
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
801
					update_output_window($static_output);
802 c92ccac7 Vinicius Coque
					pkg_debug(gettext("Package WAS NOT installed properly.") . "\n");
803 ad88ff3f Ermal
					if($pkg_interface <> "console") {
804 91f026b0 ayvis
						echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
805
						echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
806 ad88ff3f Ermal
					}
807
					sleep(1);
808
					return false;
809 1a22ffcd Scott Ullrich
				}
810 e65a287f Scott Ullrich
			}
811
		}
812
	}
813 bfe9c9e7 jim-p
814 7597c8e8 Colin Smith
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
815
	if(file_exists("/usr/local/pkg/" . $configfile)) {
816 9d3d8d00 Vinicius Coque
		$static_output .= gettext("Loading package configuration... ");
817 7597c8e8 Colin Smith
		update_output_window($static_output);
818 43db85f8 Scott Ullrich
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
819 6acdf659 Carlos Eduardo Ramos
		$static_output .= gettext("done.") . "\n";
820 7597c8e8 Colin Smith
		update_output_window($static_output);
821 9d3d8d00 Vinicius Coque
		$static_output .= gettext("Configuring package components...\n");
822 8dee24a6 Ermal Lu?i
		if (!empty($pkg_config['filter_rules_needed']))
823 bc771948 Ermal Lu?i
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
824 7597c8e8 Colin Smith
		update_output_window($static_output);
825
		/* modify system files */
826 fcf92dae Ermal
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
827 9d3d8d00 Vinicius Coque
			$static_output .= gettext("System files... ");
828 7597c8e8 Colin Smith
			update_output_window($static_output);
829
			foreach($pkg_config['modify_system']['item'] as $ms) {
830
				if($ms['textneeded']) {
831
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
832
				}
833
			}
834 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
835 7597c8e8 Colin Smith
			update_output_window($static_output);
836
		}
837 b2a66231 Ermal
838 645f2fa8 Phil Davis
		if (!pkg_fetch_additional_files($pkg, $pkg_info)) {
839
			return false;
840
		}
841 b2a66231 Ermal
842 2df5cb99 Scott Ullrich
		/*   if a require exists, include it.  this will
843
		 *   show us where an error exists in a package
844
		 *   instead of making us blindly guess
845
		 */
846 fcf92dae Ermal
		$missing_include = false;
847 2df5cb99 Scott Ullrich
		if($pkg_config['include_file'] <> "") {
848 206c15cc PiBa-NL
			$static_output .= gettext("Loading package instructions...") . "\n";
849 2df5cb99 Scott Ullrich
			update_output_window($static_output);
850 eab543ed Ermal
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
851 43ad432c Ermal Lu?i
			if (file_exists($pkg_config['include_file']))
852
				require_once($pkg_config['include_file']);
853 fcf92dae Ermal
			else {
854
				$missing_include = true;
855 7dbbaecd Scott Ullrich
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
856 fcf92dae Ermal
				update_output_window($static_output);
857
				/* XXX: Should undo the steps before this?! */
858
				return false;
859
			}
860 43db85f8 Scott Ullrich
		}
861 57811192 Ermal
862
		/* custom commands */
863
		$static_output .= gettext("Custom commands...") . "\n";
864
		update_output_window($static_output);
865
		if ($missing_include == false) {
866
			if($pkg_config['custom_php_global_functions'] <> "") {
867
				$static_output .= gettext("Executing custom_php_global_functions()...");
868
				update_output_window($static_output);
869
				eval_once($pkg_config['custom_php_global_functions']);
870
				$static_output .= gettext("done.") . "\n";
871
				update_output_window($static_output);
872
			}
873
			if($pkg_config['custom_php_install_command']) {
874
				$static_output .= gettext("Executing custom_php_install_command()...");
875
				update_output_window($static_output);
876 169f1574 Vinicius Coque
				/* XXX: create symlinks for conf files into the PBI directories.
877
				 *	change packages to store configs at /usr/pbi/pkg/etc and remove this
878
				 */
879
				eval_once($pkg_config['custom_php_install_command']);
880 8059acb5 Phil Davis
				// Note: pkg may be mixed-case, e.g. "squidGuard" but the PBI names are lowercase.
881
				// e.g. "squidguard-1.4_4-i386" so feed lowercase to pbi_info below.
882
				// Also add the "-" so that examples like "squid-" do not match "squidguard-".
883
				$pkg_name_for_pbi_match = strtolower($pkg) . "-";
884 a1d4a048 Phil Davis
				exec("/usr/local/sbin/pbi_info | grep '^{$pkg_name_for_pbi_match}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray);
885 84d50fe7 Phil Davis
				$pbidir0 = $pbidirarray[0];
886 7b27b18b Renato Botelho
				exec("find /usr/local/etc/ -name *.conf | grep " . escapeshellarg($pkg),$files);
887 169f1574 Vinicius Coque
				foreach($files as $f) {
888 84d50fe7 Phil Davis
					$pbiconf = str_replace('/usr/local',$pbidir0,$f);
889 a1d4a048 Phil Davis
					if(is_file($pbiconf) || is_link($pbiconf)) {
890 8059acb5 Phil Davis
						unlink($pbiconf);
891
					}
892 a1d4a048 Phil Davis
					if(is_dir(dirname($pbiconf))) {
893
						symlink($f,$pbiconf);
894
					} else {
895
						log_error("The dir for {$pbiconf} does not exist. Cannot add symlink to {$f}.");
896
					}
897 169f1574 Vinicius Coque
				}
898 57811192 Ermal
				eval_once($pkg_config['custom_php_install_command']);
899
				$static_output .= gettext("done.") . "\n";
900
				update_output_window($static_output);
901
			}
902
			if($pkg_config['custom_php_resync_config_command'] <> "") {
903
				$static_output .= gettext("Executing custom_php_resync_config_command()...");
904
				update_output_window($static_output);
905
				eval_once($pkg_config['custom_php_resync_config_command']);
906
				$static_output .= gettext("done.") . "\n";
907
				update_output_window($static_output);
908
			}
909
		}
910 7597c8e8 Colin Smith
		/* sidebar items */
911 1570d27a Ermal Lu?i
		if(is_array($pkg_config['menu'])) {
912 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Menu items... ");
913 7597c8e8 Colin Smith
			update_output_window($static_output);
914 1570d27a Ermal Lu?i
			foreach($pkg_config['menu'] as $menu) {
915 f3a274b7 Ermal
				if(is_array($config['installedpackages']['menu'])) {
916 1570d27a Ermal Lu?i
					foreach($config['installedpackages']['menu'] as $amenu)
917
						if($amenu['name'] == $menu['name'])
918
							continue 2;
919 f3a274b7 Ermal
				} else
920 27018d3c Ermal
					$config['installedpackages']['menu'] = array();
921 1570d27a Ermal Lu?i
				$config['installedpackages']['menu'][] = $menu;
922 7597c8e8 Colin Smith
			}
923 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
924 7597c8e8 Colin Smith
			update_output_window($static_output);
925
		}
926 b63f2e8b Matthew Grooms
		/* integrated tab items */
927 1570d27a Ermal Lu?i
		if(is_array($pkg_config['tabs']['tab'])) {
928 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Integrated Tab items... ");
929 b63f2e8b Matthew Grooms
			update_output_window($static_output);
930 1570d27a Ermal Lu?i
			foreach($pkg_config['tabs']['tab'] as $tab) {
931 f3a274b7 Ermal
				if(is_array($config['installedpackages']['tab'])) {
932 1570d27a Ermal Lu?i
					foreach($config['installedpackages']['tab'] as $atab)
933
						if($atab['name'] == $tab['name'])
934
							continue 2;
935 f3a274b7 Ermal
				} else
936 27018d3c Ermal
					$config['installedpackages']['tab'] = array();
937 1570d27a Ermal Lu?i
				$config['installedpackages']['tab'][] = $tab;
938 b63f2e8b Matthew Grooms
			}
939 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
940 b63f2e8b Matthew Grooms
			update_output_window($static_output);
941
		}
942 2dc264a4 Colin Smith
		/* services */
943 1570d27a Ermal Lu?i
		if(is_array($pkg_config['service'])) {
944 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Services... ");
945 2dc264a4 Colin Smith
			update_output_window($static_output);
946
			foreach($pkg_config['service'] as $service) {
947 f3a274b7 Ermal
				if(is_array($config['installedpackages']['service'])) {
948 d282095a Renato Botelho
					foreach($config['installedpackages']['service'] as $aservice)
949
						if($aservice['name'] == $service['name'])
950
							continue 2;
951 f3a274b7 Ermal
				} else
952 27018d3c Ermal
					$config['installedpackages']['service'] = array();
953 2dc264a4 Colin Smith
				$config['installedpackages']['service'][] = $service;
954
			}
955 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
956 2dc264a4 Colin Smith
			update_output_window($static_output);
957
		}
958 7597c8e8 Colin Smith
	} else {
959 6acdf659 Carlos Eduardo Ramos
		$static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted.");
960 7597c8e8 Colin Smith
		update_output_window($static_output);
961 c92ccac7 Vinicius Coque
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
962 1a22ffcd Scott Ullrich
		if($pkg_interface <> "console") {
963 91f026b0 ayvis
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
964
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
965 1a22ffcd Scott Ullrich
		}
966 e65a287f Scott Ullrich
		sleep(1);
967 2c794549 Ermal
		return false;
968 7597c8e8 Colin Smith
	}
969 2c794549 Ermal
970
	/* set up package logging streams */
971
	if($pkg_info['logging']) {
972
		system_syslogd_start();
973
	}
974
975
	return true;
976 7597c8e8 Colin Smith
}
977 407bf67a Colin Smith
978 64974db7 Scott Ullrich
function does_package_depend($pkg) {
979
	// Should not happen, but just in case.
980
	if(!$pkg)
981
		return;
982
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
983
	// If this package has dependency then return true
984
	foreach($pkg_var_db_dir as $pvdd) {
985
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
986
			return true;
987
	}	
988
	// Did not find a record of dependencies, so return false.
989
	return false;
990
}
991
992 fcf92dae Ermal
function delete_package($pkg) {
993 1b28121f Ermal
	global $config, $g, $static_output, $vardb;
994 b2a66231 Ermal
995 86af45ec Scott Ullrich
	if(!$pkg) 
996
		return;
997 62c55268 Colin Smith
998 8059acb5 Phil Davis
	// Note: $pkg has the full PBI package name followed by ".pbi". Strip off ".pbi".
999 fcf92dae Ermal
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
1000 b2a66231 Ermal
1001 a5566aa8 Vinicius Coque
	if($pkg)
1002
		$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
1003
	update_output_window($static_output);
1004 64974db7 Scott Ullrich
1005 9eeef922 Scott Ullrich
	remove_freebsd_package($pkg);
1006 d9426abc Ermal
	$static_output .= "done.\n";
1007
	update_output_window($static_output);
1008 fcf92dae Ermal
1009 b7ff3186 Ermal
	/* Rescan directories for what has been left and avoid fooling other programs. */
1010
	mwexec("/sbin/ldconfig");
1011
1012 407bf67a Colin Smith
	return;
1013
}
1014
1015
function delete_package_xml($pkg) {
1016 c5966711 phildd
	global $g, $config, $static_output, $pkg_interface;
1017 b2a66231 Ermal
1018 232b01db jim-p
	conf_mount_rw();
1019 6955830f Ermal Lu?i
1020 b2a66231 Ermal
	$pkgid = get_pkg_id($pkg);
1021
	if ($pkgid == -1) {
1022 6acdf659 Carlos Eduardo Ramos
		$static_output .= sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $pkg, "\n\n");
1023 e65a287f Scott Ullrich
		update_output_window($static_output);
1024 1a22ffcd Scott Ullrich
		if($pkg_interface <> "console") {
1025 91f026b0 ayvis
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
1026
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
1027 1a22ffcd Scott Ullrich
		}
1028 e65a287f Scott Ullrich
		ob_flush();
1029
		sleep(1);
1030 3339fac0 Ermal Lu?i
		conf_mount_ro();
1031 e65a287f Scott Ullrich
		return;
1032
	}
1033 c92ccac7 Vinicius Coque
	pkg_debug(sprintf(gettext("Removing %s package... "),$pkg));
1034
	$static_output .= sprintf(gettext("Removing %s components..."),$pkg) . "\n";
1035 407bf67a Colin Smith
	update_output_window($static_output);
1036
	/* parse package configuration */
1037
	$packages = &$config['installedpackages']['package'];
1038 b63f2e8b Matthew Grooms
	$tabs =& $config['installedpackages']['tab'];
1039
	$menus =& $config['installedpackages']['menu'];
1040 3c41c4ab Colin Smith
	$services = &$config['installedpackages']['service'];
1041 2addd5b2 Ermal
	$pkg_info =& $packages[$pkgid];
1042
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
1043 19a11678 Colin Smith
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
1044 b63f2e8b Matthew Grooms
		/* remove tab items */
1045
		if(is_array($pkg_config['tabs'])) {
1046 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Tabs items... ");
1047 b63f2e8b Matthew Grooms
			update_output_window($static_output);
1048 8604523b Ermal Lu?i
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
1049
				foreach($pkg_config['tabs']['tab'] as $tab) {
1050 b2a66231 Ermal
					foreach($tabs as $key => $insttab) {
1051
						if($insttab['name'] == $tab['name']) {
1052 5274feb0 Scott Ullrich
							unset($tabs[$key]);
1053 b2a66231 Ermal
							break;
1054
						}
1055
					}
1056 8604523b Ermal Lu?i
				}
1057
			}
1058 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
1059 b63f2e8b Matthew Grooms
			update_output_window($static_output);
1060
		}
1061 3f01fe47 Colin Smith
		/* remove menu items */
1062
		if(is_array($pkg_config['menu'])) {
1063 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Menu items... ");
1064 3f01fe47 Colin Smith
			update_output_window($static_output);
1065 8604523b Ermal Lu?i
			if (is_array($pkg_config['menu']) && is_array($menus)) {
1066
				foreach($pkg_config['menu'] as $menu) {
1067 b2a66231 Ermal
					foreach($menus as $key => $instmenu) {
1068
						if($instmenu['name'] == $menu['name']) {
1069 8604523b Ermal Lu?i
							unset($menus[$key]);
1070 b2a66231 Ermal
							break;
1071
						}
1072
					}
1073 8604523b Ermal Lu?i
				}
1074
			}
1075 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
1076 3f01fe47 Colin Smith
			update_output_window($static_output);
1077 407bf67a Colin Smith
		}
1078 3c41c4ab Colin Smith
		/* remove services */
1079
		if(is_array($pkg_config['service'])) {
1080 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Services... ");
1081 3c41c4ab Colin Smith
			update_output_window($static_output);
1082 8604523b Ermal Lu?i
			if (is_array($pkg_config['service']) && is_array($services)) {
1083
				foreach($pkg_config['service'] as $service) {
1084
					foreach($services as $key => $instservice) {
1085
						if($instservice['name'] == $service['name']) {
1086 285ef132 Ermal LUÇI
							if(platform_booting() != true)
1087 06e57df8 Scott Ullrich
								stop_service($service['name']);
1088 941baf1e Ermal
							if($service['rcfile']) {
1089 c5966711 phildd
								$prefix = RCFILEPREFIX;
1090 941baf1e Ermal
								if (!empty($service['prefix']))
1091
									$prefix = $service['prefix'];
1092
								if (file_exists("{$prefix}{$service['rcfile']}"))
1093
									@unlink("{$prefix}{$service['rcfile']}");
1094
							}
1095 8604523b Ermal Lu?i
							unset($services[$key]);
1096
						}
1097 0cab7cad Colin Smith
					}
1098 3c41c4ab Colin Smith
				}
1099
			}
1100 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
1101 3c41c4ab Colin Smith
			update_output_window($static_output);
1102
		}
1103 b2a66231 Ermal
		/*
1104
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
1105
		 * 	Same is done during installation.
1106
		 */
1107 f9c8e64c jim-p
		write_config("Intermediate config write during package removal for {$pkg}.");
1108 b2a66231 Ermal
1109
		/*
1110
		 * If a require exists, include it.  this will
1111
		 * show us where an error exists in a package
1112
		 * instead of making us blindly guess
1113 892aef15 Scott Ullrich
		 */
1114 fcf92dae Ermal
		$missing_include = false;
1115 892aef15 Scott Ullrich
		if($pkg_config['include_file'] <> "") {
1116 3ec86ca8 Renato Botelho
			$static_output .= gettext("Loading package instructions...") . "\n";
1117 892aef15 Scott Ullrich
			update_output_window($static_output);
1118 eab543ed Ermal
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
1119 fcf92dae Ermal
			if (file_exists($pkg_config['include_file']))
1120 1570d27a Ermal Lu?i
				require_once($pkg_config['include_file']);
1121 fcf92dae Ermal
			else {
1122
				$missing_include = true;
1123
				update_output_window($static_output);
1124 7dbbaecd Scott Ullrich
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
1125 fcf92dae Ermal
			}
1126
		}
1127
		/* ermal
1128
		 * NOTE: It is not possible to handle parse errors on eval.
1129
		 * So we prevent it from being run at all to not interrupt all the other code.
1130
		 */
1131
		if ($missing_include == false) {
1132
			/* evalate this package's global functions and pre deinstall commands */
1133
			if($pkg_config['custom_php_global_functions'] <> "")
1134
				eval_once($pkg_config['custom_php_global_functions']);
1135
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
1136
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
1137 43db85f8 Scott Ullrich
		}
1138 3f01fe47 Colin Smith
		/* system files */
1139 fcf92dae Ermal
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
1140 9d3d8d00 Vinicius Coque
			$static_output .= gettext("System files... ");
1141 3f01fe47 Colin Smith
			update_output_window($static_output);
1142 b2a66231 Ermal
			foreach($pkg_config['modify_system']['item'] as $ms)
1143 3f01fe47 Colin Smith
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
1144 b2a66231 Ermal
1145 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
1146 3f01fe47 Colin Smith
			update_output_window($static_output);
1147 407bf67a Colin Smith
		}
1148 644d2d59 Colin Smith
		/* deinstall commands */
1149
		if($pkg_config['custom_php_deinstall_command'] <> "") {
1150 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Deinstall commands... ");
1151 644d2d59 Colin Smith
			update_output_window($static_output);
1152 fcf92dae Ermal
			if ($missing_include == false) {
1153
				eval_once($pkg_config['custom_php_deinstall_command']);
1154 3ec86ca8 Renato Botelho
				$static_output .= gettext("done.") . "\n";
1155 fcf92dae Ermal
			} else
1156 7dbbaecd Scott Ullrich
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
1157 644d2d59 Colin Smith
			update_output_window($static_output);
1158
		}
1159 1570d27a Ermal Lu?i
		if($pkg_config['include_file'] <> "") {
1160 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Removing package instructions...");
1161 b2b15543 Scott Ullrich
			update_output_window($static_output);
1162 633d51b7 bcyrill
			pkg_debug(sprintf(gettext("Remove '%s'"), $pkg_config['include_file']) . "\n");
1163 b2b15543 Scott Ullrich
			unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1164 9d3d8d00 Vinicius Coque
			$static_output .= gettext("done.") . "\n";
1165 b2b15543 Scott Ullrich
			update_output_window($static_output);
1166
		}
1167 af8fca8f jim-p
		/* remove all additional files */
1168
		if(is_array($pkg_config['additional_files_needed'])) {
1169 9d3d8d00 Vinicius Coque
			$static_output .= gettext("Auxiliary files... ");
1170 af8fca8f jim-p
			update_output_window($static_output);
1171
			foreach($pkg_config['additional_files_needed'] as $afn) {
1172
				$filename = get_filename_from_url($afn['item'][0]);
1173 b2a66231 Ermal
				if($afn['prefix'] <> "")
1174 af8fca8f jim-p
					$prefix = $afn['prefix'];
1175 b2a66231 Ermal
				else
1176 af8fca8f jim-p
					$prefix = "/usr/local/pkg/";
1177
				unlink_if_exists($prefix . $filename);
1178
			}
1179 6acdf659 Carlos Eduardo Ramos
			$static_output .= gettext("done.") . "\n";
1180 af8fca8f jim-p
			update_output_window($static_output);
1181
		}
1182 047c40c4 Colin Smith
		/* package XML file */
1183 9d3d8d00 Vinicius Coque
		$static_output .= gettext("Package XML... ");
1184 047c40c4 Colin Smith
		update_output_window($static_output);
1185
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1186 6acdf659 Carlos Eduardo Ramos
		$static_output .= gettext("done.") . "\n";
1187 047c40c4 Colin Smith
		update_output_window($static_output);
1188 407bf67a Colin Smith
	}
1189 2addd5b2 Ermal
	/* syslog */
1190 0c2f769c doktornotor
	$need_syslog_restart = false;
1191 ec0ef1cf doktornotor
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfilename'] <> "") {
1192 7dbbaecd Scott Ullrich
		$static_output .= "Syslog entries... ";
1193 2addd5b2 Ermal
		update_output_window($static_output);
1194
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1195
		$static_output .= "done.\n";
1196
		update_output_window($static_output);
1197 0c2f769c doktornotor
		$need_syslog_restart = true;
1198 2addd5b2 Ermal
	}
1199 e9c7a334 Scott Ullrich
	
1200 2addd5b2 Ermal
	/* remove config.xml entries */
1201 9d3d8d00 Vinicius Coque
	$static_output .= gettext("Configuration... ");
1202 407bf67a Colin Smith
	update_output_window($static_output);
1203
	unset($config['installedpackages']['package'][$pkgid]);
1204 6acdf659 Carlos Eduardo Ramos
	$static_output .= gettext("done.") . "\n";
1205 407bf67a Colin Smith
	update_output_window($static_output);
1206 fcf92dae Ermal
	write_config("Removed {$pkg} package.\n");
1207 0c2f769c doktornotor
	
1208
	/* remove package entry from /etc/syslog.conf if needed */
1209 aac2557e doktornotor
	/* this must be done after removing the entries from config.xml */
1210 0c2f769c doktornotor
	if ($need_syslog_restart) {
1211
		system_syslogd_start();
1212
	}
1213
1214
	conf_mount_ro();
1215 407bf67a Colin Smith
}
1216 566181ea Colin Smith
1217
function expand_to_bytes($size) {
1218
	$conv = array(
1219
			"G" =>	"3",
1220
			"M" =>  "2",
1221
			"K" =>  "1",
1222
			"B" =>  "0"
1223
		);
1224
	$suffix = substr($size, -1);
1225
	if(!in_array($suffix, array_keys($conv))) return $size;
1226
	$size = substr($size, 0, -1);
1227
	for($i = 0; $i < $conv[$suffix]; $i++) {
1228
		$size *= 1024;
1229
	}
1230
	return $size;
1231
}
1232
1233
function get_pkg_db() {
1234
	global $g;
1235
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1236
}
1237
1238 b8a1c2a3 Colin Smith
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1239 1570d27a Ermal Lu?i
	if(!$pkgdb)
1240
		$pkgdb = get_pkg_db();
1241
	if(!is_array($alreadyseen))
1242
		$alreadyseen = array();
1243
	if (!is_array($depend))
1244
		$depend = array();
1245 566181ea Colin Smith
	foreach($depend as $adepend) {
1246
		$pkgname = reverse_strrchr($adepend['name'], '.');
1247 b8a1c2a3 Colin Smith
		if(in_array($pkgname, $alreadyseen)) {
1248
			continue;
1249
		} elseif(!in_array($pkgname, $pkgdb)) {
1250
			$size += expand_to_bytes($adepend['size']);
1251
			$alreadyseen[] = $pkgname;
1252
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1253
		}
1254 566181ea Colin Smith
	}
1255
	return $size;
1256
}
1257
1258
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1259
	global $config, $g;
1260 1570d27a Ermal Lu?i
	if((!is_array($pkg)) and ($pkg != 'all'))
1261
		$pkg = array($pkg);
1262 566181ea Colin Smith
	$pkgdb = get_pkg_db();
1263 1570d27a Ermal Lu?i
	if(!$pkg_info)
1264
		$pkg_info = get_pkg_sizes($pkg);
1265 566181ea Colin Smith
	foreach($pkg as $apkg) {
1266 2addd5b2 Ermal
		if(!$pkg_info[$apkg])
1267
			continue;
1268 b8a1c2a3 Colin Smith
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1269 566181ea Colin Smith
	}
1270 b8a1c2a3 Colin Smith
	return $toreturn;
1271 566181ea Colin Smith
}
1272 f0a550fd Colin Smith
1273 e43ba9ad Colin Smith
function squash_from_bytes($size, $round = "") {
1274 f0a550fd Colin Smith
	$conv = array(1 => "B", "K", "M", "G");
1275
	foreach($conv as $div => $suffix) {
1276
		$sizeorig = $size;
1277
		if(($size /= 1024) < 1) {
1278 e43ba9ad Colin Smith
			if($round) {
1279
				$sizeorig = round($sizeorig, $round);
1280
			}
1281 f0a550fd Colin Smith
			return $sizeorig . $suffix;
1282
		}
1283
	}
1284
	return;
1285
}
1286 5025a56c Scott Ullrich
1287 9b193619 Scott Ullrich
function pkg_reinstall_all() {
1288
	global $g, $config;
1289 c53eb903 Ermal
1290
	@unlink('/conf/needs_package_sync');
1291 633d51b7 bcyrill
	if (is_array($config['installedpackages']['package'])) {
1292 2b125a17 jim-p
		echo gettext("One moment please, reinstalling packages...\n");
1293
		echo gettext(" >>> Trying to fetch package info...");
1294
		log_error(gettext("Attempting to reinstall all packages"));
1295 633d51b7 bcyrill
		$pkg_info = get_pkg_info();
1296
		if ($pkg_info) {
1297
			echo " Done.\n";
1298
		} else {
1299 7c8f3711 jim-p
			$xmlrpc_base_url = get_active_xml_rpc_base_url();
1300 2b125a17 jim-p
			$error = sprintf(gettext(' >>> Unable to communicate with %1$s. Please verify DNS and interface configuration, and that %2$s has functional Internet connectivity.'), $xmlrpc_base_url, $g['product_name']);
1301
			echo "\n{$error}\n";
1302
			log_error(gettext("Cannot reinstall packages: ") . $error);
1303 633d51b7 bcyrill
			return;
1304
		}
1305
		$todo = array();
1306 2b125a17 jim-p
		$all_names = array();
1307
		foreach($config['installedpackages']['package'] as $package) {
1308 9b193619 Scott Ullrich
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1309 2b125a17 jim-p
			$all_names[] = $package['name'];
1310
		}
1311
		$package_name_list = gettext("List of packages to reinstall: ") . implode(", ", $all_names);
1312
		echo " >>> {$package_name_list}\n";
1313
		log_error($package_name_list);
1314
1315 9b193619 Scott Ullrich
		foreach($todo as $pkgtodo) {
1316
			$static_output = "";
1317
			if($pkgtodo['name']) {
1318 2b125a17 jim-p
				log_error(gettext("Uninstalling package") . " {$pkgtodo['name']}");
1319 9b193619 Scott Ullrich
				uninstall_package($pkgtodo['name']);
1320 2b125a17 jim-p
				log_error(gettext("Finished uninstalling package") . " {$pkgtodo['name']}");
1321
				log_error(gettext("Reinstalling package") . " {$pkgtodo['name']}");
1322 dd34d7d2 Ermal LUÇI
				install_package($pkgtodo['name'], '', true);
1323 2b125a17 jim-p
				log_error(gettext("Finished installing package") . " {$pkgtodo['name']}");
1324 9b193619 Scott Ullrich
			}
1325
		}
1326 2b125a17 jim-p
		log_error(gettext("Finished reinstalling all packages."));
1327 633d51b7 bcyrill
	} else
1328
		echo "No packages are installed.";
1329 9b193619 Scott Ullrich
}
1330
1331 60dd7649 jim-p
function stop_packages() {
1332
	require_once("config.inc");
1333
	require_once("functions.inc");
1334
	require_once("filter.inc");
1335
	require_once("shaper.inc");
1336
	require_once("captiveportal.inc");
1337
	require_once("pkg-utils.inc");
1338
	require_once("pfsense-utils.inc");
1339
	require_once("service-utils.inc");
1340
1341 c5966711 phildd
	global $config, $g;
1342 60dd7649 jim-p
1343
	log_error("Stopping all packages.");
1344
1345 c5966711 phildd
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1346 60dd7649 jim-p
	if (!$rcfiles)
1347
		$rcfiles = array();
1348
	else {
1349
		$rcfiles = array_flip($rcfiles);
1350
		if (!$rcfiles)
1351
			$rcfiles = array();
1352
	}
1353
1354
	if (is_array($config['installedpackages']['package'])) {
1355
		foreach($config['installedpackages']['package'] as $package) {
1356
			echo " Stopping package {$package['name']}...";
1357 75a01a7c Phil Davis
			$internal_name = get_pkg_internal_name($package);
1358
			stop_service($internal_name);
1359
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1360 60dd7649 jim-p
			echo "done.\n";
1361
		}
1362
	}
1363
1364 6186cdc4 jim-p
	foreach ($rcfiles as $rcfile => $number) {
1365
		$shell = @popen("/bin/sh", "w");
1366
		if ($shell) {
1367 60dd7649 jim-p
			echo " Stopping {$rcfile}...";
1368 61ef1385 Ermal
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1369
				if ($shell)
1370
					pclose($shell);
1371
				$shell = @popen("/bin/sh", "w");
1372
			}
1373 60dd7649 jim-p
			echo "done.\n";
1374 6186cdc4 jim-p
			pclose($shell);
1375 60dd7649 jim-p
		}
1376
	}
1377
}
1378
1379 9b4df982 marcelloc
function package_skip_tests($index,$requested_version){
1380
	global $config, $g;
1381
1382
	/* Get pfsense version*/
1383
	$version = rtrim(file_get_contents("/etc/version"));
1384
	
1385
	if($g['platform'] == "nanobsd")
1386
		if($index['noembedded']) 
1387
			return true;
1388
						
1389
	/* If we are on not on HEAD, and the package wants it, skip */
1390
	if ($version <> "HEAD" && $index['required_version'] == "HEAD" && $requested_version <> "other")
1391
		return true;
1392
							
1393
	/* If there is no required version, and the requested package version is not 'none', then skip */
1394
	if (empty($index['required_version']) && $requested_version <> "none")
1395
		return true;
1396
							
1397
	/* If the requested version is not 'other', and the required version is newer than what we have, skip. */
1398
	if($requested_version <> "other" && (pfs_version_compare("", $version, $index['required_version']) < 0))
1399
		return true;
1400
							
1401
	/* If the requestion version is 'other' and we are on the version requested, skip. */
1402
	if($requested_version == "other" && (pfs_version_compare("", $version, $index['required_version']) == 0))
1403
		return true;
1404
							
1405
	/* Package is only for an older version, lets skip */
1406
	if($index['maximum_version'] && (pfs_version_compare("", $version, $index['maximum_version']) > 0))
1407
		return true;
1408
		
1409
	/* Do not skip package list */	
1410
	return false;
1411
}
1412 f8466c36 jim-p
1413
function get_pkg_interfaces_select_source($include_localhost=false) {
1414
	$interfaces = get_configured_interface_with_descr();
1415
	$ssifs = array();
1416
	foreach ($interfaces as $iface => $ifacename) {
1417
		$tmp["name"]  = $ifacename;
1418
		$tmp["value"] = $iface;
1419
		$ssifs[] = $tmp;
1420
	}
1421
	if ($include_localhost) {
1422
		$tmp["name"]  = "Localhost";
1423
		$tmp["value"] = "lo0";
1424
		$ssifs[] = $tmp;
1425
	}
1426
	return $ssifs;
1427
}
1428 c55dfc4a jim-p
1429
function verify_all_package_servers() {
1430 7c8f3711 jim-p
	return verify_package_server(get_active_xml_rpc_base_url());
1431 c55dfc4a jim-p
}
1432
1433
/* Check if the active package server is a valid default or if it has been
1434
	altered. */
1435
function verify_package_server($server) {
1436
	/* Define the expected default package server domains. Include
1437
		preceding "." to prevent matching from being too liberal. */
1438
	$default_package_domains = array('.pfsense.org', '.pfsense.com', '.netgate.com');
1439
1440
	/* For this test we only need to check the hostname. */
1441
	$xmlrpcbase = parse_url($server, PHP_URL_HOST);
1442
1443
	foreach ($default_package_domains as $dom) {
1444
		if (substr($xmlrpcbase, -(strlen($dom))) == $dom) {
1445
			return true;
1446
		}
1447
	}
1448
	return false;
1449
}
1450
1451 6916360e jim-p
/* Test the package server certificate to ensure that it validates properly */
1452
function check_package_server_ssl() {
1453
	global $g;
1454
	$xmlrpcurl = get_active_xml_rpc_base_url() . $g['xmlrpcpath'];
1455
1456
	/* If the package server is using HTTP, we can't verify SSL */
1457
	if (substr($xmlrpcurl, 0, 5) == "http:") {
1458
		return "http";
1459
	}
1460
1461
	/* Setup a basic cURL connection. We do not care about the content of
1462
		the result, only the SSL verification. */
1463
	$ch = curl_init($xmlrpcurl);
1464
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1465
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
1466
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '30');
1467
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
1468
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1469
	$result_page = curl_exec($ch);
1470
	$verifyfail = curl_getinfo($ch, CURLINFO_SSL_VERIFYRESULT);
1471
	curl_close($ch);
1472
1473
	/* The result from curl is 1 on failure, 0 on success. */
1474
	if ($verifyfail == 0)
1475
		return true;
1476
	else
1477
		return false;
1478
}
1479
1480
/* Keep this message centrally since it will be used several times on pages
1481
	in the GUI. */
1482
function package_server_ssl_failure_message() {
1483
	$msg = "The package server's SSL certificate could not be verified. "
1484
	. "The SSL certificate itself may be invalid, its chain of trust may "
1485
	. "have failed validation, or the server may have been impersonated. "
1486
	. "Downloaded packages may come from an untrusted source. "
1487
	. "Proceed with caution.";
1488
1489
	return sprintf(gettext($msg), htmlspecialchars(get_active_xml_rpc_base_url()));
1490
}
1491
1492 7c8f3711 jim-p
/* Keep this message centrally since it will be used several times on pages
1493
	in the GUI. */
1494
function package_server_mismatch_message() {
1495 6916360e jim-p
	$msg = "The package server currently configured on "
1496 7c8f3711 jim-p
	. "this firewall (%s) is NOT an official package server. The contents "
1497
	. "of such servers cannot be verified and may contain malicious files. "
1498
	. "Return the package server settings to their default values to "
1499 6916360e jim-p
	. "ensure that verifiable and trusted packages are received.";
1500
1501
	return sprintf(gettext($msg), htmlspecialchars(get_active_xml_rpc_base_url())) . '<br/><br/>'
1502 7c8f3711 jim-p
	. '<a href="/pkg_mgr_settings.php">' . gettext("Package Manager Settings") . '</a>';
1503
}
1504
1505 bfe9c9e7 jim-p
1506
function pkg_fetch_config_file($package, $pkg_info = "") {
1507
	global $g, $config, $static_output, $pkg_interface;
1508
	conf_mount_rw();
1509
1510
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
1511
		$pkg_info = get_pkg_info(array($package));
1512
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
1513
		if (empty($pkg_info)) {
1514
			conf_mount_ro();
1515
			return -1;
1516
		}
1517
	}
1518
1519
	/* fetch the package's configuration file */
1520
	if($pkg_info['config_file'] != "") {
1521
		$static_output .= "\n" . gettext("Downloading package configuration file... ");
1522
		update_output_window($static_output);
1523
		pkg_debug(gettext("Downloading package configuration file...") . "\n");
1524
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
1525 645f2fa8 Phil Davis
		if (download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto, "read_body", PKG_FILE_DOWNLOAD_CONNECT_TIMEOUT) !== true) {
1526 bfe9c9e7 jim-p
			pkg_debug(gettext("ERROR! Unable to fetch package configuration file. Aborting installation.") . "\n");
1527
			if($pkg_interface == "console")
1528
				print "\n" . gettext("ERROR! Unable to fetch package configuration file. Aborting package installation.") . "\n";
1529
			else {
1530
				$static_output .= gettext("failed!\n\nInstallation aborted.\n");
1531
				update_output_window($static_output);
1532
				echo "<br />Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
1533
			}
1534
			conf_mount_ro();
1535
			return -1;
1536
		}
1537
		$static_output .= gettext("done.") . "\n";
1538
		update_output_window($static_output);
1539
	}
1540
	conf_mount_ro();
1541
	return true;
1542
}
1543
1544
1545
function pkg_fetch_additional_files($package, $pkg_info = "") {
1546
	global $g, $config, $static_output, $pkg_interface;
1547
	conf_mount_rw();
1548
1549
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
1550
		$pkg_info = get_pkg_info(array($package));
1551
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
1552
		if (empty($pkg_info)) {
1553
			conf_mount_ro();
1554
			return -1;
1555
		}
1556
	}
1557
1558
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
1559
	if(file_exists("/usr/local/pkg/" . $configfile)) {
1560
		$static_output .= gettext("Loading package configuration... ");
1561
		update_output_window($static_output);
1562
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
1563
		$static_output .= gettext("done.") . "\n";
1564
		update_output_window($static_output);
1565
		/* download additional files */
1566
		if(is_array($pkg_config['additional_files_needed'])) {
1567
			$static_output .= gettext("Additional files... ");
1568
			$static_orig = $static_output;
1569
			update_output_window($static_output);
1570
			foreach($pkg_config['additional_files_needed'] as $afn) {
1571
				$filename = get_filename_from_url($afn['item'][0]);
1572
				if($afn['chmod'] <> "")
1573
					$pkg_chmod = $afn['chmod'];
1574
				else
1575
					$pkg_chmod = "";
1576
1577
				if($afn['prefix'] <> "")
1578
					$prefix = $afn['prefix'];
1579
				else
1580
					$prefix = "/usr/local/pkg/";
1581
1582
				if(!is_dir($prefix))
1583
					safe_mkdir($prefix);
1584
				$static_output .= $filename . " ";
1585
				update_output_window($static_output);
1586 645f2fa8 Phil Davis
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename, "read_body", PKG_FILE_DOWNLOAD_CONNECT_TIMEOUT) !== true) {
1587 bfe9c9e7 jim-p
					$static_output .= "failed.\n";
1588
					@unlink($prefix . $filename);
1589
					update_output_window($static_output);
1590
					return false;
1591
				}
1592
				if(stristr($filename, ".tgz") <> "") {
1593
					pkg_debug(gettext("Extracting tarball to -C for ") . $filename . "...\n");
1594
					$tarout = "";
1595
					exec("/usr/bin/tar xvzf " . escapeshellarg($prefix . $filename) . " -C / 2>&1", $tarout);
1596
					pkg_debug(print_r($tarout, true) . "\n");
1597
				}
1598
				if($pkg_chmod <> "") {
1599
					pkg_debug(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $prefix, $filename, "\n"));
1600
					@chmod($prefix . $filename, $pkg_chmod);
1601
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
1602
				}
1603
				$static_output = $static_orig;
1604
				update_output_window($static_output);
1605
			}
1606
			$static_output .= gettext("done.") . "\n";
1607
			update_output_window($static_output);
1608
		}
1609
		conf_mount_ro();
1610
		return true;
1611
	}
1612
}
1613
1614 61ef1385 Ermal
?>