Project

General

Profile

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