Project

General

Profile

Download (56.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6
 *   This file contains various functions used by the pfSense package system.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2010 Ermal Luci
12
 * Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
13
 * 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

    
37
/*
38
	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
	pfSense_MODULE:	pkg
41
*/
42

    
43
require_once("globals.inc");
44
require_once("xmlrpc.inc");
45
require_once("service-utils.inc");
46
if(file_exists("/cf/conf/use_xmlreader"))
47
	require_once("xmlreader.inc");
48
else
49
	require_once("xmlparse.inc");
50
require_once("pfsense-utils.inc");
51

    
52
if(!function_exists("update_status")) {
53
	function update_status($status) {
54
		echo $status . "\n";
55
	}
56
}
57
if(!function_exists("update_output_window")) {
58
	function update_output_window($status) {
59
		echo $status . "\n";
60
	}
61
}
62

    
63
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
$vardb = "/var/db/pkg";
80
safe_mkdir($vardb);
81
$g['platform'] = trim(file_get_contents("/etc/platform"));
82

    
83
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
84
	conf_mount_rw();
85
	safe_mkdir("/usr/local/pkg");
86
	safe_mkdir("/usr/local/pkg/pf");	
87
	conf_mount_ro();
88
}
89

    
90
// 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
/****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
	// 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
	$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
	exec("/usr/local/sbin/pbi_delete " . escapeshellarg($packagestring) . " 2>>/tmp/pbi_delete_errors.txt");
114
}
115

    
116
/****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
function is_package_installed($packagename) {
127
	$pkg = get_pkg_id($packagename);
128
	if($pkg == -1)
129
		return false;
130
	return true;
131
}
132

    
133
/****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
function get_pkg_id($pkg_name) {
142
	global $config;
143

    
144
	if (is_array($config['installedpackages']['package'])) {
145
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
146
			if($pkg['name'] == $pkg_name)
147
				return $idx;
148
		}
149
	}
150
	return -1;
151
}
152

    
153
/****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
/****f* pkg-utils/get_pkg_info
172
 * NAME
173
 *   get_pkg_info - Retrieve package information from package server.
174
 * INPUTS
175
 *   $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
 * RESULT
178
 *   $raw_versions - Array containing retrieved information, indexed by package name.
179
 ******/
180
function get_pkg_info($pkgs = 'all', $info = 'all') {
181
	global $g;
182

    
183
	$freebsd_machine = php_uname("m");
184
	$params = array(
185
		"pkg" => $pkgs, 
186
		"info" => $info, 
187
		"freebsd_version" => get_freebsd_version(),
188
		"freebsd_machine" => $freebsd_machine
189
	);
190
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
191
	return $resp ? $resp : array();
192
}
193

    
194
function get_pkg_sizes($pkgs = 'all') {
195
	global $config, $g;
196

    
197
	$freebsd_machine = php_uname("m");
198
	$params = array(
199
		"pkg" => $pkgs, 
200
		"freebsd_version" => get_freebsd_version(),
201
		"freebsd_machine" => $freebsd_machine
202
	);
203
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
204
	$xmlrpc_base_url = get_active_xml_rpc_base_url();
205
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
206
	$resp = $cli->send($msg, 10);
207
	if(!is_object($resp))
208
		log_error("Could not get response from XMLRPC server!");
209
 	else if (!$resp->faultCode()) {
210
		$raw_versions = $resp->value();
211
		return xmlrpc_value_to_php($raw_versions);
212
	}
213

    
214
	return array();
215
}
216

    
217
/****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
				if (strcasecmp($val, $available_arr[$n]) > 0) {
246
					return 1;
247
				} elseif (strcasecmp($val, $available_arr[$n]) < 0) {
248
					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
/*
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
	global $config, $pkg_interface, $g;
283

    
284
	log_error(gettext("Resyncing configuration for all packages."));
285

    
286
	if (!is_array($config['installedpackages']['package']))
287
		return;
288

    
289
	if($show_message == true)
290
		echo "Syncing packages:";
291

    
292
	conf_mount_rw();
293

    
294
	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
		if(platform_booting() != true)
301
			stop_service(get_pkg_internal_name($package));
302
		sync_package($idx, true, true);
303
		if($pkg_interface == "console") 
304
			echo "\n" . gettext("Syncing packages:");
305
	}
306

    
307
	if($show_message == true)
308
		echo " done.\n";
309

    
310
	@unlink("/conf/needs_package_sync");
311
	conf_mount_ro();
312
}
313

    
314
/*
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
	if(!$pkg) 
320
		return;
321
	$output = "";
322
	$_gb = exec("/usr/local/sbin/pbi_info " . escapeshellarg($pkg) . ' 2>/dev/null', $output, $retval);
323

    
324
	return (intval($retval) == 0);
325
}
326

    
327
/*
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
	global $config;
337

    
338
	$pkg_id = get_pkg_id($pkg_name);
339
	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
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
346
		log_error(sprintf(gettext('The %1$s package is missing required dependencies and must be reinstalled. %2$s'), $package['name'], $package['configurationfile']));
347
		uninstall_package($package['name']);
348
		if (install_package($package['name']) < 0) {
349
			log_error("Failed reinstalling package {$package['name']}.");
350
			return false;
351
		}
352
	}
353
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
354
	if (!empty($pkg_xml['additional_files_needed'])) {
355
		foreach($pkg_xml['additional_files_needed'] as $item) {
356
			if ($return_nosync == 0 && isset($item['nosync']))
357
				continue; // Do not return depends with nosync set if not required.
358
			$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
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file)))
361
			if (($filetype != "all") && (strtolower(substr($depend_file, -strlen($filetype))) != strtolower($filetype)))
362
					continue;
363
			if ($item['prefix'] != "")
364
				$prefix = $item['prefix'];
365
			else
366
				$prefix = "/usr/local/pkg/";
367
			// Ensure that the prefix exists to avoid installation errors.
368
			if(!is_dir($prefix)) 
369
				exec("/bin/mkdir -p {$prefix}");
370
			if(!file_exists($prefix . $depend_file))
371
				log_error(sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']));
372
			switch ($format) {
373
			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
							$depends[] = $depend_xml['name'];
383
					} 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
			}
396
		}
397
		return $depends;
398
	}
399
}
400

    
401
function uninstall_package($pkg_name) {
402
	global $config, $static_output;
403
	global $builder_package_install;
404

    
405
	$id = get_pkg_id($pkg_name);
406
	if ($id >= 0) {
407
		stop_service(get_pkg_internal_name($config['installedpackages']['package'][$id]));
408
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package_pbi'];
409
		$static_output .= "Removing package...\n";
410
		update_output_window($static_output);
411
		if (is_array($pkg_depends)) {
412
			foreach ($pkg_depends as $pkg_depend)
413
				delete_package($pkg_depend);
414
		} else {
415
			// 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
		}
427
	}
428
	delete_package_xml($pkg_name);
429

    
430
	$static_output .= gettext("done.") . "\n";
431
	update_output_window($static_output);
432
}
433

    
434
function force_remove_package($pkg_name) {
435
	delete_package_xml($pkg_name);
436
}
437

    
438
/*
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
	global $config, $config_parsed;
443
	global $builder_package_install;
444
	
445
	// If this code is being called by pfspkg_installer 
446
	// which the builder system uses then return (ignore).
447
	if($builder_package_install)
448
		return;
449
	
450
	if(empty($config['installedpackages']['package']))
451
		return;
452
	if(!is_numeric($pkg_name)) {
453
		$pkg_id = get_pkg_id($pkg_name);
454
		if($pkg_id == -1)
455
			return -1; // This package doesn't really exist - exit the function.
456
	} else
457
		$pkg_id = $pkg_name;
458

    
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
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
464
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
465
		force_remove_package($package['name']);
466
		return -1;
467
	}
468
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
469
	if(isset($pkg_config['nosync']))
470
		return;
471
	/* 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
			}
484
		}
485
	}
486

    
487
	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
					require_once("notices.inc");
497
					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
					log_error("Could not find {$item}. Reinstalling package.");
499
					uninstall_package($pkg_name);
500
					if (install_package($pkg_name) < 0) {
501
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
502
						return -1;
503
					}
504
				} 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
					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
					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
				}
525
			}
526
		}
527
	}
528
}
529

    
530
/*
531
 * pkg_fetch_recursive: Download and install a FreeBSD PBI package. This function provides output to
532
 * 			a progress bar and output window.
533
 */
534
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
535
	global $static_output, $g, $config;
536

    
537
	// Clean up incoming filenames
538
	$filename = str_replace("  ", " ", $filename);
539
	$filename = str_replace("\n", " ", $filename);
540
	$filename = str_replace("  ", " ", $filename);
541

    
542
	$pkgs = explode(" ", $filename);
543
	foreach($pkgs as $filename) {
544
		$filename = trim($filename);
545
		if ($g['platform'] == "nanobsd") {
546
			$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
		} else {
553
			$fetchdir = $g['tmp_path'];
554
		}
555

    
556
		/* 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
		$priv_url = "https://files.pfsense.org/packages/{$rel}/All/";
559
		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
		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
				$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

    
582
		$pkgaddout = "";
583

    
584
		$no_checksig = "";
585
		if (isset($config['system']['pkg_nochecksig']))
586
			$no_checksig = "--no-checksig";
587

    
588
		$result = exec("/usr/local/sbin/pbi_add " . $pkgstaging . " -f -v {$no_checksig} " . escapeshellarg($fetchto) . " 2>&1", $pkgaddout, $rc);
589
		pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\n");
590
		if ($rc == 0) {
591
			$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
			foreach($links as $link) {
598
				@unlink("/usr/local/{$link['link_name']}");
599
				@symlink("{$link['target']}","/usr/local/{$link['link_name']}");
600
			}
601

    
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
				array("target" => "local/www", "link_name" => "www"),
608
				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
			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
		}
628
	}
629
	return true;
630
}
631

    
632
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
				$result[] = array(
656
					'target' => preg_replace('/\.pbiopt$/', '', $f),
657
					'link_name' => $matches[1]);
658
			}
659
		}
660
	}
661

    
662
	return $result;
663
}
664

    
665

    
666
function install_package($package, $pkg_info = "", $force_install = false) {
667
	global $g, $config, $static_output, $pkg_interface;
668

    
669
	/* safe side. Write config below will send to ro again. */
670
	conf_mount_rw();
671

    
672
	if($pkg_interface == "console") 	
673
		echo "\n";
674
	/* fetch package information if needed */
675
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
676
		$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
		if (empty($pkg_info)) {
679
			conf_mount_ro();
680
			return -1;
681
		}
682
	}
683
	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
	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
	update_status($static_output);
705

    
706
	/* fetch the package's configuration file */
707
	pkg_fetch_config_file($package, $pkg_info);
708

    
709
	/* add package information to config.xml */
710
	$pkgid = get_pkg_id($pkg_info['name']);
711
	$static_output .= gettext("Saving updated package information...") . " ";
712
	update_output_window($static_output);
713
	if($pkgid == -1) {
714
		$config['installedpackages']['package'][] = $pkg_info;
715
		$changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']);
716
		$to_output = gettext("done.") . "\n";
717
	} else {
718
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
719
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
720
		$to_output = gettext("overwrite!") . "\n";
721
	}
722
	if(file_exists('/conf/needs_package_sync'))
723
		@unlink('/conf/needs_package_sync');
724
	conf_mount_ro();
725
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
726
	$static_output .= $to_output;
727
	update_output_window($static_output);
728
	/* install other package components */
729
	if (!install_package_xml($package)) {
730
		uninstall_package($package);
731
		write_config($changedesc);
732
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
733
		$static_output .= gettext("Failed to install package.") . "\n";
734
		update_output_window($static_output);
735
		return -1;
736
	} else {
737
		$static_output .= gettext("Writing configuration... ");
738
		update_output_window($static_output);
739
		write_config($changedesc);
740
		log_error(sprintf(gettext("Successfully installed package: %s."), $pkg_info['name']));
741
		$static_output .= gettext("done.") . "\n";
742
		update_output_window($static_output);
743
		if($pkg_info['after_install_info']) 
744
			update_output_window($pkg_info['after_install_info']);	
745
	}
746
}
747

    
748
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
function eval_once($toeval) {
760
	global $evaled;
761
	if(!$evaled) $evaled = array();
762
	$evalmd5 = md5($toeval);
763
	if(!in_array($evalmd5, $evaled)) {
764
		@eval($toeval);
765
		$evaled[] = $evalmd5;
766
	}
767
	return;
768
}
769

    
770
function install_package_xml($pkg) {
771
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
772

    
773
	if(($pkgid = get_pkg_id($pkg)) == -1) {
774
		$static_output .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n");
775
		update_output_window($static_output);
776
		if($pkg_interface <> "console") {
777
			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
		}
780
		sleep(1);
781
		return false;
782
	} else
783
		$pkg_info = $config['installedpackages']['package'][$pkgid];
784

    
785
	/* pkg_add the package and its dependencies */
786
	if($pkg_info['depends_on_package_base_url'] != "") {
787
		if($pkg_interface == "console") 
788
			echo "\n";
789
		update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies."));
790
		$static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... ");
791
		$static_orig = $static_output;
792
		$static_output .= "\n";
793
		update_output_window($static_output);
794
		foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) {
795
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
796
			$static_output = $static_orig . "\nChecking for package installation... ";
797
			update_output_window($static_output);
798
			if (!is_freebsd_pkg_installed($pkg_name)) {
799
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
800
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
801
					update_output_window($static_output);
802
					pkg_debug(gettext("Package WAS NOT installed properly.") . "\n");
803
					if($pkg_interface <> "console") {
804
						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
					}
807
					sleep(1);
808
					return false;
809
				}
810
			}
811
		}
812
	}
813

    
814
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
815
	if(file_exists("/usr/local/pkg/" . $configfile)) {
816
		$static_output .= gettext("Loading package configuration... ");
817
		update_output_window($static_output);
818
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
819
		$static_output .= gettext("done.") . "\n";
820
		update_output_window($static_output);
821
		$static_output .= gettext("Configuring package components...\n");
822
		if (!empty($pkg_config['filter_rules_needed']))
823
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
824
		update_output_window($static_output);
825
		/* modify system files */
826
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
827
			$static_output .= gettext("System files... ");
828
			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
			$static_output .= gettext("done.") . "\n";
835
			update_output_window($static_output);
836
		}
837

    
838
		if (!pkg_fetch_additional_files($pkg, $pkg_info)) {
839
			return false;
840
		}
841

    
842
		/*   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
		$missing_include = false;
847
		if($pkg_config['include_file'] <> "") {
848
			$static_output .= gettext("Loading package instructions...") . "\n";
849
			update_output_window($static_output);
850
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
851
			if (file_exists($pkg_config['include_file']))
852
				require_once($pkg_config['include_file']);
853
			else {
854
				$missing_include = true;
855
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
856
				update_output_window($static_output);
857
				/* XXX: Should undo the steps before this?! */
858
				return false;
859
			}
860
		}
861

    
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
				/* 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
				// 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
				exec("/usr/local/sbin/pbi_info | grep '^{$pkg_name_for_pbi_match}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray);
885
				$pbidir0 = $pbidirarray[0];
886
				exec("find /usr/local/etc/ -name *.conf | grep " . escapeshellarg($pkg),$files);
887
				foreach($files as $f) {
888
					$pbiconf = str_replace('/usr/local',$pbidir0,$f);
889
					if(is_file($pbiconf) || is_link($pbiconf)) {
890
						unlink($pbiconf);
891
					}
892
					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
				}
898
				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
		/* sidebar items */
911
		if(is_array($pkg_config['menu'])) {
912
			$static_output .= gettext("Menu items... ");
913
			update_output_window($static_output);
914
			foreach($pkg_config['menu'] as $menu) {
915
				if(is_array($config['installedpackages']['menu'])) {
916
					foreach($config['installedpackages']['menu'] as $amenu)
917
						if($amenu['name'] == $menu['name'])
918
							continue 2;
919
				} else
920
					$config['installedpackages']['menu'] = array();
921
				$config['installedpackages']['menu'][] = $menu;
922
			}
923
			$static_output .= gettext("done.") . "\n";
924
			update_output_window($static_output);
925
		}
926
		/* integrated tab items */
927
		if(is_array($pkg_config['tabs']['tab'])) {
928
			$static_output .= gettext("Integrated Tab items... ");
929
			update_output_window($static_output);
930
			foreach($pkg_config['tabs']['tab'] as $tab) {
931
				if(is_array($config['installedpackages']['tab'])) {
932
					foreach($config['installedpackages']['tab'] as $atab)
933
						if($atab['name'] == $tab['name'])
934
							continue 2;
935
				} else
936
					$config['installedpackages']['tab'] = array();
937
				$config['installedpackages']['tab'][] = $tab;
938
			}
939
			$static_output .= gettext("done.") . "\n";
940
			update_output_window($static_output);
941
		}
942
		/* services */
943
		if(is_array($pkg_config['service'])) {
944
			$static_output .= gettext("Services... ");
945
			update_output_window($static_output);
946
			foreach($pkg_config['service'] as $service) {
947
				if(is_array($config['installedpackages']['service'])) {
948
					foreach($config['installedpackages']['service'] as $aservice)
949
						if($aservice['name'] == $service['name'])
950
							continue 2;
951
				} else
952
					$config['installedpackages']['service'] = array();
953
				$config['installedpackages']['service'][] = $service;
954
			}
955
			$static_output .= gettext("done.") . "\n";
956
			update_output_window($static_output);
957
		}
958
	} else {
959
		$static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted.");
960
		update_output_window($static_output);
961
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
962
		if($pkg_interface <> "console") {
963
			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
		}
966
		sleep(1);
967
		return false;
968
	}
969

    
970
	/* set up package logging streams */
971
	if($pkg_info['logging']) {
972
		system_syslogd_start();
973
	}
974

    
975
	return true;
976
}
977

    
978
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
function delete_package($pkg) {
993
	global $config, $g, $static_output, $vardb;
994

    
995
	if(!$pkg) 
996
		return;
997

    
998
	// Note: $pkg has the full PBI package name followed by ".pbi". Strip off ".pbi".
999
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
1000

    
1001
	if($pkg)
1002
		$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
1003
	update_output_window($static_output);
1004

    
1005
	remove_freebsd_package($pkg);
1006
	$static_output .= "done.\n";
1007
	update_output_window($static_output);
1008

    
1009
	/* Rescan directories for what has been left and avoid fooling other programs. */
1010
	mwexec("/sbin/ldconfig");
1011

    
1012
	return;
1013
}
1014

    
1015
function delete_package_xml($pkg) {
1016
	global $g, $config, $static_output, $pkg_interface;
1017

    
1018
	conf_mount_rw();
1019

    
1020
	$pkgid = get_pkg_id($pkg);
1021
	if ($pkgid == -1) {
1022
		$static_output .= sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $pkg, "\n\n");
1023
		update_output_window($static_output);
1024
		if($pkg_interface <> "console") {
1025
			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
		}
1028
		ob_flush();
1029
		sleep(1);
1030
		conf_mount_ro();
1031
		return;
1032
	}
1033
	pkg_debug(sprintf(gettext("Removing %s package... "),$pkg));
1034
	$static_output .= sprintf(gettext("Removing %s components..."),$pkg) . "\n";
1035
	update_output_window($static_output);
1036
	/* parse package configuration */
1037
	$packages = &$config['installedpackages']['package'];
1038
	$tabs =& $config['installedpackages']['tab'];
1039
	$menus =& $config['installedpackages']['menu'];
1040
	$services = &$config['installedpackages']['service'];
1041
	$pkg_info =& $packages[$pkgid];
1042
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
1043
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
1044
		/* remove tab items */
1045
		if(is_array($pkg_config['tabs'])) {
1046
			$static_output .= gettext("Tabs items... ");
1047
			update_output_window($static_output);
1048
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
1049
				foreach($pkg_config['tabs']['tab'] as $tab) {
1050
					foreach($tabs as $key => $insttab) {
1051
						if($insttab['name'] == $tab['name']) {
1052
							unset($tabs[$key]);
1053
							break;
1054
						}
1055
					}
1056
				}
1057
			}
1058
			$static_output .= gettext("done.") . "\n";
1059
			update_output_window($static_output);
1060
		}
1061
		/* remove menu items */
1062
		if(is_array($pkg_config['menu'])) {
1063
			$static_output .= gettext("Menu items... ");
1064
			update_output_window($static_output);
1065
			if (is_array($pkg_config['menu']) && is_array($menus)) {
1066
				foreach($pkg_config['menu'] as $menu) {
1067
					foreach($menus as $key => $instmenu) {
1068
						if($instmenu['name'] == $menu['name']) {
1069
							unset($menus[$key]);
1070
							break;
1071
						}
1072
					}
1073
				}
1074
			}
1075
			$static_output .= gettext("done.") . "\n";
1076
			update_output_window($static_output);
1077
		}
1078
		/* remove services */
1079
		if(is_array($pkg_config['service'])) {
1080
			$static_output .= gettext("Services... ");
1081
			update_output_window($static_output);
1082
			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
							if(platform_booting() != true)
1087
								stop_service($service['name']);
1088
							if($service['rcfile']) {
1089
								$prefix = RCFILEPREFIX;
1090
								if (!empty($service['prefix']))
1091
									$prefix = $service['prefix'];
1092
								if (file_exists("{$prefix}{$service['rcfile']}"))
1093
									@unlink("{$prefix}{$service['rcfile']}");
1094
							}
1095
							unset($services[$key]);
1096
						}
1097
					}
1098
				}
1099
			}
1100
			$static_output .= gettext("done.") . "\n";
1101
			update_output_window($static_output);
1102
		}
1103
		/*
1104
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
1105
		 * 	Same is done during installation.
1106
		 */
1107
		write_config("Intermediate config write during package removal for {$pkg}.");
1108

    
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
		 */
1114
		$missing_include = false;
1115
		if($pkg_config['include_file'] <> "") {
1116
			$static_output .= gettext("Loading package instructions...") . "\n";
1117
			update_output_window($static_output);
1118
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
1119
			if (file_exists($pkg_config['include_file']))
1120
				require_once($pkg_config['include_file']);
1121
			else {
1122
				$missing_include = true;
1123
				update_output_window($static_output);
1124
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
1125
			}
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
		}
1138
		/* system files */
1139
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
1140
			$static_output .= gettext("System files... ");
1141
			update_output_window($static_output);
1142
			foreach($pkg_config['modify_system']['item'] as $ms)
1143
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
1144

    
1145
			$static_output .= gettext("done.") . "\n";
1146
			update_output_window($static_output);
1147
		}
1148
		/* deinstall commands */
1149
		if($pkg_config['custom_php_deinstall_command'] <> "") {
1150
			$static_output .= gettext("Deinstall commands... ");
1151
			update_output_window($static_output);
1152
			if ($missing_include == false) {
1153
				eval_once($pkg_config['custom_php_deinstall_command']);
1154
				$static_output .= gettext("done.") . "\n";
1155
			} else
1156
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
1157
			update_output_window($static_output);
1158
		}
1159
		if($pkg_config['include_file'] <> "") {
1160
			$static_output .= gettext("Removing package instructions...");
1161
			update_output_window($static_output);
1162
			pkg_debug(sprintf(gettext("Remove '%s'"), $pkg_config['include_file']) . "\n");
1163
			unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1164
			$static_output .= gettext("done.") . "\n";
1165
			update_output_window($static_output);
1166
		}
1167
		/* remove all additional files */
1168
		if(is_array($pkg_config['additional_files_needed'])) {
1169
			$static_output .= gettext("Auxiliary files... ");
1170
			update_output_window($static_output);
1171
			foreach($pkg_config['additional_files_needed'] as $afn) {
1172
				$filename = get_filename_from_url($afn['item'][0]);
1173
				if($afn['prefix'] <> "")
1174
					$prefix = $afn['prefix'];
1175
				else
1176
					$prefix = "/usr/local/pkg/";
1177
				unlink_if_exists($prefix . $filename);
1178
			}
1179
			$static_output .= gettext("done.") . "\n";
1180
			update_output_window($static_output);
1181
		}
1182
		/* package XML file */
1183
		$static_output .= gettext("Package XML... ");
1184
		update_output_window($static_output);
1185
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1186
		$static_output .= gettext("done.") . "\n";
1187
		update_output_window($static_output);
1188
	}
1189
	/* syslog */
1190
	$need_syslog_restart = false;
1191
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfilename'] <> "") {
1192
		$static_output .= "Syslog entries... ";
1193
		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
		$need_syslog_restart = true;
1198
	}
1199
	
1200
	/* remove config.xml entries */
1201
	$static_output .= gettext("Configuration... ");
1202
	update_output_window($static_output);
1203
	unset($config['installedpackages']['package'][$pkgid]);
1204
	$static_output .= gettext("done.") . "\n";
1205
	update_output_window($static_output);
1206
	write_config("Removed {$pkg} package.\n");
1207
	
1208
	/* remove package entry from /etc/syslog.conf if needed */
1209
	/* this must be done after removing the entries from config.xml */
1210
	if ($need_syslog_restart) {
1211
		system_syslogd_start();
1212
	}
1213

    
1214
	conf_mount_ro();
1215
}
1216

    
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
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1239
	if(!$pkgdb)
1240
		$pkgdb = get_pkg_db();
1241
	if(!is_array($alreadyseen))
1242
		$alreadyseen = array();
1243
	if (!is_array($depend))
1244
		$depend = array();
1245
	foreach($depend as $adepend) {
1246
		$pkgname = reverse_strrchr($adepend['name'], '.');
1247
		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
	}
1255
	return $size;
1256
}
1257

    
1258
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1259
	global $config, $g;
1260
	if((!is_array($pkg)) and ($pkg != 'all'))
1261
		$pkg = array($pkg);
1262
	$pkgdb = get_pkg_db();
1263
	if(!$pkg_info)
1264
		$pkg_info = get_pkg_sizes($pkg);
1265
	foreach($pkg as $apkg) {
1266
		if(!$pkg_info[$apkg])
1267
			continue;
1268
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1269
	}
1270
	return $toreturn;
1271
}
1272

    
1273
function squash_from_bytes($size, $round = "") {
1274
	$conv = array(1 => "B", "K", "M", "G");
1275
	foreach($conv as $div => $suffix) {
1276
		$sizeorig = $size;
1277
		if(($size /= 1024) < 1) {
1278
			if($round) {
1279
				$sizeorig = round($sizeorig, $round);
1280
			}
1281
			return $sizeorig . $suffix;
1282
		}
1283
	}
1284
	return;
1285
}
1286

    
1287
function pkg_reinstall_all() {
1288
	global $g, $config;
1289

    
1290
	@unlink('/conf/needs_package_sync');
1291
	if (is_array($config['installedpackages']['package'])) {
1292
		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
		$pkg_info = get_pkg_info();
1296
		if ($pkg_info) {
1297
			echo " Done.\n";
1298
		} else {
1299
			$xmlrpc_base_url = get_active_xml_rpc_base_url();
1300
			$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
			return;
1304
		}
1305
		$todo = array();
1306
		$all_names = array();
1307
		foreach($config['installedpackages']['package'] as $package) {
1308
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1309
			$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
		foreach($todo as $pkgtodo) {
1316
			$static_output = "";
1317
			if($pkgtodo['name']) {
1318
				log_error(gettext("Uninstalling package") . " {$pkgtodo['name']}");
1319
				uninstall_package($pkgtodo['name']);
1320
				log_error(gettext("Finished uninstalling package") . " {$pkgtodo['name']}");
1321
				log_error(gettext("Reinstalling package") . " {$pkgtodo['name']}");
1322
				install_package($pkgtodo['name'], '', true);
1323
				log_error(gettext("Finished installing package") . " {$pkgtodo['name']}");
1324
			}
1325
		}
1326
		log_error(gettext("Finished reinstalling all packages."));
1327
	} else
1328
		echo "No packages are installed.";
1329
}
1330

    
1331
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
	global $config, $g;
1342

    
1343
	log_error("Stopping all packages.");
1344

    
1345
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1346
	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
			$internal_name = get_pkg_internal_name($package);
1358
			stop_service($internal_name);
1359
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1360
			echo "done.\n";
1361
		}
1362
	}
1363

    
1364
	foreach ($rcfiles as $rcfile => $number) {
1365
		$shell = @popen("/bin/sh", "w");
1366
		if ($shell) {
1367
			echo " Stopping {$rcfile}...";
1368
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1369
				if ($shell)
1370
					pclose($shell);
1371
				$shell = @popen("/bin/sh", "w");
1372
			}
1373
			echo "done.\n";
1374
			pclose($shell);
1375
		}
1376
	}
1377
}
1378

    
1379
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

    
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

    
1429
function verify_all_package_servers() {
1430
	return verify_package_server(get_active_xml_rpc_base_url());
1431
}
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
/* 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
/* Keep this message centrally since it will be used several times on pages
1493
	in the GUI. */
1494
function package_server_mismatch_message() {
1495
	$msg = "The package server currently configured on "
1496
	. "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
	. "ensure that verifiable and trusted packages are received.";
1500

    
1501
	return sprintf(gettext($msg), htmlspecialchars(get_active_xml_rpc_base_url())) . '<br/><br/>'
1502
	. '<a href="/pkg_mgr_settings.php">' . gettext("Package Manager Settings") . '</a>';
1503
}
1504

    
1505

    
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
		if (download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto, "read_body", PKG_FILE_DOWNLOAD_CONNECT_TIMEOUT) !== true) {
1526
			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
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename, "read_body", PKG_FILE_DOWNLOAD_CONNECT_TIMEOUT) !== true) {
1587
					$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
?>
(41-41/68)