Projet

Général

Profil

Télécharger (54 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / pkg-utils.inc @ 2b7fb769

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

    
111
/****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
function is_package_installed($packagename) {
122
	$pkg = get_pkg_id($packagename);
123
	if($pkg == -1)
124
		return false;
125
	return true;
126
}
127

    
128
/****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
function get_pkg_id($pkg_name) {
137
	global $config;
138

    
139
	if (is_array($config['installedpackages']['package'])) {
140
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
141
			if($pkg['name'] == $pkg_name)
142
				return $idx;
143
		}
144
	}
145
	return -1;
146
}
147

    
148
/****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
/****f* pkg-utils/get_pkg_info
167
 * NAME
168
 *   get_pkg_info - Retrieve package information from package server.
169
 * INPUTS
170
 *   $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
 * RESULT
173
 *   $raw_versions - Array containing retrieved information, indexed by package name.
174
 ******/
175
function get_pkg_info($pkgs = 'all', $info = 'all') {
176
	global $g;
177

    
178
	$freebsd_machine = php_uname("m");
179
	$params = array(
180
		"pkg" => $pkgs, 
181
		"info" => $info, 
182
		"freebsd_version" => get_freebsd_version(),
183
		"freebsd_machine" => $freebsd_machine
184
	);
185
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
186
	return $resp ? $resp : array();
187
}
188

    
189
function get_pkg_sizes($pkgs = 'all') {
190
	global $config, $g;
191

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

    
209
	return array();
210
}
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
	global $config, $pkg_interface, $g;
218

    
219
	log_error(gettext("Resyncing configuration for all packages."));
220

    
221
	if (!is_array($config['installedpackages']['package']))
222
		return;
223

    
224
	if($show_message == true)
225
		echo "Syncing packages:";
226

    
227
	conf_mount_rw();
228

    
229
	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
		if($g['booting'] != true)
236
			stop_service(get_pkg_internal_name($package));
237
		sync_package($idx, true, true);
238
		if($pkg_interface == "console") 
239
			echo "\n" . gettext("Syncing packages:");
240
	}
241

    
242
	if($show_message == true)
243
		echo " done.\n";
244

    
245
	@unlink("/conf/needs_package_sync");
246
	conf_mount_ro();
247
}
248

    
249
/*
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
	if(!$pkg) 
255
		return;
256
	$output = "";
257
	$_gb = exec("/usr/local/sbin/pbi_info " . escapeshellarg($pkg) . ' 2>/dev/null', $output, $retval);
258

    
259
	return (intval($retval) == 0);
260
}
261

    
262
/*
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
	global $config;
272

    
273
	$pkg_id = get_pkg_id($pkg_name);
274
	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
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
281
		log_error(sprintf(gettext('The %1$s package is missing required dependencies and must be reinstalled. %2$s'), $package['name'], $package['configurationfile']));
282
		uninstall_package($package['name']);
283
		if (install_package($package['name']) < 0) {
284
			log_error("Failed reinstalling package {$package['name']}.");
285
			return false;
286
		}
287
	}
288
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
289
	if (!empty($pkg_xml['additional_files_needed'])) {
290
		foreach($pkg_xml['additional_files_needed'] as $item) {
291
			if ($return_nosync == 0 && isset($item['nosync']))
292
				continue; // Do not return depends with nosync set if not required.
293
			$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
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file)))
296
			if (($filetype != "all") && (strtolower(substr($depend_file, -strlen($filetype))) != strtolower($filetype)))
297
					continue;
298
			if ($item['prefix'] != "")
299
				$prefix = $item['prefix'];
300
			else
301
				$prefix = "/usr/local/pkg/";
302
			// Ensure that the prefix exists to avoid installation errors.
303
			if(!is_dir($prefix)) 
304
				exec("/bin/mkdir -p {$prefix}");
305
			if(!file_exists($prefix . $depend_file))
306
				log_error(sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']));
307
			switch ($format) {
308
			case "files":
309
				$depends[] = $prefix . $depend_file;
310
				break;
311
			case "names":
312
				switch ($filetype) {
313
				case "all":
314
					if(preg_match("/\.xml/i", $depend_file)) {
315
						$depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui");
316
						if (!empty($depend_xml))
317
							$depends[] = $depend_xml['name'];
318
					} else
319
						$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
320
					break;
321
				case ".xml":
322
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
323
					if (!empty($depend_xml))
324
						$depends[] = $depend_xml['name'];
325
					break;
326
				default:
327
					$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
328
					break;
329
				}
330
			}
331
		}
332
		return $depends;
333
	}
334
}
335

    
336
function uninstall_package($pkg_name) {
337
	global $config, $static_output;
338
	global $builder_package_install;
339

    
340
	$id = get_pkg_id($pkg_name);
341
	if ($id >= 0) {
342
		stop_service(get_pkg_internal_name($config['installedpackages']['package'][$id]));
343
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package_pbi'];
344
		$static_output .= "Removing package...\n";
345
		update_output_window($static_output);
346
		if (is_array($pkg_depends)) {
347
			foreach ($pkg_depends as $pkg_depend)
348
				delete_package($pkg_depend);
349
		} else {
350
			// The packages (1 or more) are all in one long string.
351
			// We need to pass them 1 at a time to delete_package.
352
			// Compress any multiple whitespace (sp, tab, cr, lf...) into a single space char.
353
			$pkg_dep_str = preg_replace("'\s+'", ' ', $pkg_depends);
354
			// Get rid of any leading or trailing space.
355
			$pkg_dep_str = trim($pkg_dep_str);
356
			// Now we have a space-separated string. Make it into an array and process it.
357
			$pkg_dep_array = explode(" ", $pkg_dep_str);
358
			foreach ($pkg_dep_array as $pkg_depend) {
359
				delete_package($pkg_depend);
360
			}
361
		}
362
	}
363
	delete_package_xml($pkg_name);
364

    
365
	$static_output .= gettext("done.") . "\n";
366
	update_output_window($static_output);
367
}
368

    
369
function force_remove_package($pkg_name) {
370
	delete_package_xml($pkg_name);
371
}
372

    
373
/*
374
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
375
 */
376
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
377
	global $config, $config_parsed;
378
	global $builder_package_install;
379
	
380
	// If this code is being called by pfspkg_installer 
381
	// which the builder system uses then return (ignore).
382
	if($builder_package_install)
383
		return;
384
	
385
	if(empty($config['installedpackages']['package']))
386
		return;
387
	if(!is_numeric($pkg_name)) {
388
		$pkg_id = get_pkg_id($pkg_name);
389
		if($pkg_id == -1)
390
			return -1; // This package doesn't really exist - exit the function.
391
	} else {
392
		$pkg_id = $pkg_name;
393
		if(empty($config['installedpackages']['package'][$pkg_id]))
394
			return;  // No package belongs to the pkg_id passed to this function.
395
	}
396
	if (is_array($config['installedpackages']['package'][$pkg_id]))
397
		$package =& $config['installedpackages']['package'][$pkg_id];
398
	else
399
		return; /* empty package tag */
400
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
401
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
402
		force_remove_package($package['name']);
403
		return -1;
404
	}
405
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
406
	if(isset($pkg_config['nosync']))
407
		return;
408
	/* Bring in package include files */
409
	if (!empty($pkg_config['include_file'])) {
410
		$include_file = $pkg_config['include_file'];
411
		if (file_exists($include_file))
412
			require_once($include_file);
413
		else {
414
			/* XXX: What the heck is this?! */
415
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
416
			uninstall_package($package['name']);
417
			if (install_package($package['name']) < 0) {
418
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
419
				return -1;
420
			}
421
		}
422
	}
423

    
424
	if(!empty($pkg_config['custom_php_global_functions']))
425
		eval($pkg_config['custom_php_global_functions']);
426
	if(!empty($pkg_config['custom_php_resync_config_command']))
427
		eval($pkg_config['custom_php_resync_config_command']);
428
	if($sync_depends == true) {
429
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
430
		if(is_array($depends)) {
431
			foreach($depends as $item) {
432
				if(!file_exists($item)) {
433
					require_once("notices.inc");
434
					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);
435
					log_error("Could not find {$item}. Reinstalling package.");
436
					uninstall_package($pkg_name);
437
					if (install_package($pkg_name) < 0) {
438
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
439
						return -1;
440
					}
441
				} else {
442
					$item_config = parse_xml_config_pkg($item, "packagegui");
443
					if (empty($item_config))
444
						continue;
445
					if(isset($item_config['nosync']))
446
						continue;
447
					if (!empty($item_config['include_file'])) {
448
						if (file_exists($item_config['include_file']))	
449
							require_once($item_config['include_file']);
450
						else {
451
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
452
							continue;
453
						}
454
					}
455
					if($item_config['custom_php_global_functions'] <> "")
456
						eval($item_config['custom_php_global_functions']);
457
					if($item_config['custom_php_resync_config_command'] <> "")
458
						eval($item_config['custom_php_resync_config_command']);
459
					if($show_message == true)
460
						print " " . $item_config['name'];
461
				}
462
			}
463
		}
464
	}
465
}
466

    
467
/*
468
 * pkg_fetch_recursive: Download and install a FreeBSD PBI package. This function provides output to
469
 * 			a progress bar and output window.
470
 */
471
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
472
	global $static_output, $g, $config;
473

    
474
	// Clean up incoming filenames
475
	$filename = str_replace("  ", " ", $filename);
476
	$filename = str_replace("\n", " ", $filename);
477
	$filename = str_replace("  ", " ", $filename);
478

    
479
	$pkgs = explode(" ", $filename);
480
	foreach($pkgs as $filename) {
481
		$filename = trim($filename);
482
		if ($g['platform'] == "nanobsd") {
483
			$pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ ";
484
			$pkgstagingdir = "/root/tmp";
485
			if (!is_dir($pkgstagingdir))
486
				mkdir($pkgstagingdir);
487
			$pkgstaging = "-o {$pkgstagingdir}/instmp.XXXXXX";
488
			$fetchdir = $pkgstagingdir;
489
		} else {
490
			$fetchdir = $g['tmp_path'];
491
		}
492

    
493
		/* FreeBSD has no PBI's hosted, so fall back to our own URL for now. (Maybe fail to PC-BSD?) */
494
		$rel = get_freebsd_version();
495
		$priv_url = "https://files.pfsense.org/packages/{$rel}/All/";
496
		if (empty($base_url))
497
			$base_url = $priv_url;
498
		if (substr($base_url, -1) == "/")
499
			$base_url = substr($base_url, 0, -1);
500
		$fetchto = "{$fetchdir}/apkg_{$filename}";
501
		$static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... ";
502
		if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
503
			if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
504
				$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
505
				update_output_window($static_output);
506
				return false;
507
			} else if ($base_url == $priv_url) {
508
				$static_output .= " failed to download.\n";
509
				update_output_window($static_output);
510
				return false;
511
			} else {
512
				$static_output .= " [{$osname} repository]\n";
513
				update_output_window($static_output);
514
			}
515
		}
516
		$static_output .= " (extracting)\n";
517
		update_output_window($static_output);
518

    
519
		$pkgaddout = "";
520

    
521
		$no_checksig = "";
522
		if (isset($config['system']['pkg_nochecksig']))
523
			$no_checksig = "--no-checksig";
524

    
525
		$result = exec("/usr/local/sbin/pbi_add " . $pkgstaging . " -f -v {$no_checksig} " . escapeshellarg($fetchto) . " 2>&1", $pkgaddout, $rc);
526
		pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\n");
527
		if ($rc == 0) {
528
			$pbi_name = preg_replace('/\.pbi$/','',$filename);
529

    
530
			$gb = exec("/usr/local/sbin/pbi_info {$pbi_name} | /usr/bin/awk '/Prefix/ {print $2}'", $pbi_prefix);
531
			$pbi_prefix = $pbi_prefix[0];
532

    
533
			$links = get_pbi_binaries(escapeshellarg($pbi_name));
534
			foreach($links as $link) {
535
				@unlink("/usr/local/{$link['link_name']}");
536
				@symlink("{$link['target']}","/usr/local/{$link['link_name']}");
537
			}
538

    
539
			$extra_links = array(
540
				array("target" => "bin", "link_name" => "sbin"),
541
				array("target" => "local/lib", "link_name" => "lib"),
542
				array("target" => "local/libexec", "link_name" => "libexec"),
543
				array("target" => "local/share", "link_name" => "share"),
544
				array("target" => "local/www", "link_name" => "www"),
545
				array("target" => "local/etc", "link_name" => "etc")
546
			);
547

    
548
			foreach ($extra_links as $link) {
549
				if (!file_exists($pbi_prefix . "/" . $link['target']))
550
					continue;
551
				@rmdir("{$pbi_prefix}/{$link['link_name']}");
552
				unlink_if_exists("{$pbi_prefix}/{$link['link_name']}");
553
				@symlink("{$pbi_prefix}/{$link['target']}", "{$pbi_prefix}/{$link['link_name']}");
554
			}
555
			pkg_debug("pbi_add successfully completed.\n");
556
		} else {
557
			if (is_array($pkgaddout))
558
				foreach ($pkgaddout as $line)
559
					$static_output .= " " . $line .= "\n";
560

    
561
			update_output_window($static_output);
562
			pkg_debug("pbi_add failed.\n");
563
			return false;
564
		}
565
	}
566
	return true;
567
}
568

    
569
function get_pbi_binaries($pbi) {
570
	$result = array();
571

    
572
	if (empty($pbi))
573
		return $result;
574

    
575
	$gb = exec("/usr/local/sbin/pbi_info {$pbi} | /usr/bin/awk '/Prefix/ {print $2}'", $pbi_prefix);
576
	$pbi_prefix = $pbi_prefix[0];
577

    
578
	if (empty($pbi_prefix))
579
		return $result;
580

    
581
	foreach(array('bin', 'sbin') as $dir) {
582
		if(!is_dir("{$pbi_prefix}/{$dir}"))
583
			continue;
584

    
585
		$files = glob("{$pbi_prefix}/{$dir}/*.pbiopt");
586
		foreach($files as $f) {
587
			$pbiopts = file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
588
			foreach($pbiopts as $pbiopt) {
589
				if (!preg_match('/^TARGET:\s+(.*)$/', $pbiopt, $matches))
590
					continue;
591

    
592
				$result[] = array(
593
					'target' => preg_replace('/\.pbiopt$/', '', $f),
594
					'link_name' => $matches[1]);
595
			}
596
		}
597
	}
598

    
599
	return $result;
600
}
601

    
602

    
603
function install_package($package, $pkg_info = "", $force_install = false) {
604
	global $g, $config, $static_output, $pkg_interface;
605

    
606
	/* safe side. Write config below will send to ro again. */
607
	conf_mount_rw();
608

    
609
	if($pkg_interface == "console") 	
610
		echo "\n";
611
	/* fetch package information if needed */
612
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
613
		$pkg_info = get_pkg_info(array($package));
614
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
615
		if (empty($pkg_info)) {
616
			conf_mount_ro();
617
			return -1;
618
		}
619
	}
620
	if (!$force_install) {
621
		$compatible = true;
622
		$version = rtrim(file_get_contents("/etc/version"));
623
		
624
		if (isset($pkg_info['required_version']))
625
			$compatible = (pfs_version_compare("", $version, $pkg_info['required_version']) >= 0);
626
		if (isset($pkg_info['maximum_version']))
627
			$compatible = $compatible && (pfs_version_compare("", $version, $pkg_info['maximum_version']) <= 0);
628
		
629
		if (!$compatible) {
630
			log_error(sprintf(gettext('Package %s is not supported on this version.'), $pkg_info['name']));
631
			$static_output .= sprintf(gettext("Package %s is not supported on this version."), $pkg_info['name']);
632
			update_status($static_output);
633
			
634
			conf_mount_ro();
635
			return -1;
636
		}
637
	}
638
	pkg_debug(gettext("Beginning package installation.") . "\n");
639
	log_error(sprintf(gettext('Beginning package installation for %s .'), $pkg_info['name']));
640
	$static_output .= sprintf(gettext("Beginning package installation for %s ."), $pkg_info['name']);
641
	update_status($static_output);
642

    
643
	/* fetch the package's configuration file */
644
	pkg_fetch_config_file($package, $pkg_info);
645

    
646
	/* add package information to config.xml */
647
	$pkgid = get_pkg_id($pkg_info['name']);
648
	$static_output .= gettext("Saving updated package information...") . " ";
649
	update_output_window($static_output);
650
	if($pkgid == -1) {
651
		$config['installedpackages']['package'][] = $pkg_info;
652
		$changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']);
653
		$to_output = gettext("done.") . "\n";
654
	} else {
655
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
656
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
657
		$to_output = gettext("overwrite!") . "\n";
658
	}
659
	if(file_exists('/conf/needs_package_sync'))
660
		@unlink('/conf/needs_package_sync');
661
	conf_mount_ro();
662
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
663
	$static_output .= $to_output;
664
	update_output_window($static_output);
665
	/* install other package components */
666
	if (!install_package_xml($package)) {
667
		uninstall_package($package);
668
		write_config($changedesc);
669
		$static_output .= gettext("Failed to install package.") . "\n";
670
		update_output_window($static_output);
671
		return -1;
672
	} else {
673
		$static_output .= gettext("Writing configuration... ");
674
		update_output_window($static_output);
675
		write_config($changedesc);
676
		$static_output .= gettext("done.") . "\n";
677
		update_output_window($static_output);
678
		if($pkg_info['after_install_info']) 
679
			update_output_window($pkg_info['after_install_info']);	
680
	}
681
}
682

    
683
function get_after_install_info($package) {
684
	global $pkg_info;
685
	/* fetch package information if needed */
686
	if(!$pkg_info or !is_array($pkg_info[$package])) {
687
		$pkg_info = get_pkg_info(array($package));
688
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
689
	}
690
	if($pkg_info['after_install_info'])
691
		return $pkg_info['after_install_info'];
692
}
693

    
694
function eval_once($toeval) {
695
	global $evaled;
696
	if(!$evaled) $evaled = array();
697
	$evalmd5 = md5($toeval);
698
	if(!in_array($evalmd5, $evaled)) {
699
		@eval($toeval);
700
		$evaled[] = $evalmd5;
701
	}
702
	return;
703
}
704

    
705
function install_package_xml($pkg) {
706
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
707

    
708
	if(($pkgid = get_pkg_id($pkg)) == -1) {
709
		$static_output .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n");
710
		update_output_window($static_output);
711
		if($pkg_interface <> "console") {
712
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
713
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
714
		}
715
		sleep(1);
716
		return false;
717
	} else
718
		$pkg_info = $config['installedpackages']['package'][$pkgid];
719

    
720
	/* pkg_add the package and its dependencies */
721
	if($pkg_info['depends_on_package_base_url'] != "") {
722
		if($pkg_interface == "console") 
723
			echo "\n";
724
		update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies."));
725
		$static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... ");
726
		$static_orig = $static_output;
727
		$static_output .= "\n";
728
		update_output_window($static_output);
729
		foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) {
730
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
731
			$static_output = $static_orig . "\nChecking for package installation... ";
732
			update_output_window($static_output);
733
			if (!is_freebsd_pkg_installed($pkg_name)) {
734
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
735
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
736
					update_output_window($static_output);
737
					pkg_debug(gettext("Package WAS NOT installed properly.") . "\n");
738
					if($pkg_interface <> "console") {
739
						echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
740
						echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
741
					}
742
					sleep(1);
743
					return false;
744
				}
745
			}
746
		}
747
	}
748

    
749
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
750
	if(file_exists("/usr/local/pkg/" . $configfile)) {
751
		$static_output .= gettext("Loading package configuration... ");
752
		update_output_window($static_output);
753
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
754
		$static_output .= gettext("done.") . "\n";
755
		update_output_window($static_output);
756
		$static_output .= gettext("Configuring package components...\n");
757
		if (!empty($pkg_config['filter_rules_needed']))
758
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
759
		update_output_window($static_output);
760
		/* modify system files */
761
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
762
			$static_output .= gettext("System files... ");
763
			update_output_window($static_output);
764
			foreach($pkg_config['modify_system']['item'] as $ms) {
765
				if($ms['textneeded']) {
766
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
767
				}
768
			}
769
			$static_output .= gettext("done.") . "\n";
770
			update_output_window($static_output);
771
		}
772

    
773
		pkg_fetch_additional_files($pkg, $pkg_info);
774

    
775
		/*   if a require exists, include it.  this will
776
		 *   show us where an error exists in a package
777
		 *   instead of making us blindly guess
778
		 */
779
		$missing_include = false;
780
		if($pkg_config['include_file'] <> "") {
781
			$static_output .= gettext("Loading package instructions...") . "\n";
782
			update_output_window($static_output);
783
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
784
			if (file_exists($pkg_config['include_file']))
785
				require_once($pkg_config['include_file']);
786
			else {
787
				$missing_include = true;
788
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
789
				update_output_window($static_output);
790
				/* XXX: Should undo the steps before this?! */
791
				return false;
792
			}
793
		}
794

    
795
		/* custom commands */
796
		$static_output .= gettext("Custom commands...") . "\n";
797
		update_output_window($static_output);
798
		if ($missing_include == false) {
799
			if($pkg_config['custom_php_global_functions'] <> "") {
800
				$static_output .= gettext("Executing custom_php_global_functions()...");
801
				update_output_window($static_output);
802
				eval_once($pkg_config['custom_php_global_functions']);
803
				$static_output .= gettext("done.") . "\n";
804
				update_output_window($static_output);
805
			}
806
			if($pkg_config['custom_php_install_command']) {
807
				$static_output .= gettext("Executing custom_php_install_command()...");
808
				update_output_window($static_output);
809
				/* XXX: create symlinks for conf files into the PBI directories.
810
				 *	change packages to store configs at /usr/pbi/pkg/etc and remove this
811
				 */
812
				eval_once($pkg_config['custom_php_install_command']);
813
				// Note: pkg may be mixed-case, e.g. "squidGuard" but the PBI names are lowercase.
814
				// e.g. "squidguard-1.4_4-i386" so feed lowercase to pbi_info below.
815
				// Also add the "-" so that examples like "squid-" do not match "squidguard-".
816
				$pkg_name_for_pbi_match = strtolower($pkg) . "-";
817
				exec("/usr/local/sbin/pbi_info | grep '^{$pkg_name_for_pbi_match}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray);
818
				$pbidir0 = $pbidirarray[0];
819
				exec("find /usr/local/etc/ -name *.conf | grep " . escapeshellarg($pkg),$files);
820
				foreach($files as $f) {
821
					$pbiconf = str_replace('/usr/local',$pbidir0,$f);
822
					if(is_file($pbiconf) || is_link($pbiconf)) {
823
						unlink($pbiconf);
824
					}
825
					if(is_dir(dirname($pbiconf))) {
826
						symlink($f,$pbiconf);
827
					} else {
828
						log_error("The dir for {$pbiconf} does not exist. Cannot add symlink to {$f}.");
829
					}
830
				}
831
				eval_once($pkg_config['custom_php_install_command']);
832
				$static_output .= gettext("done.") . "\n";
833
				update_output_window($static_output);
834
			}
835
			if($pkg_config['custom_php_resync_config_command'] <> "") {
836
				$static_output .= gettext("Executing custom_php_resync_config_command()...");
837
				update_output_window($static_output);
838
				eval_once($pkg_config['custom_php_resync_config_command']);
839
				$static_output .= gettext("done.") . "\n";
840
				update_output_window($static_output);
841
			}
842
		}
843
		/* sidebar items */
844
		if(is_array($pkg_config['menu'])) {
845
			$static_output .= gettext("Menu items... ");
846
			update_output_window($static_output);
847
			foreach($pkg_config['menu'] as $menu) {
848
				if(is_array($config['installedpackages']['menu'])) {
849
					foreach($config['installedpackages']['menu'] as $amenu)
850
						if($amenu['name'] == $menu['name'])
851
							continue 2;
852
				} else
853
					$config['installedpackages']['menu'] = array();
854
				$config['installedpackages']['menu'][] = $menu;
855
			}
856
			$static_output .= gettext("done.") . "\n";
857
			update_output_window($static_output);
858
		}
859
		/* integrated tab items */
860
		if(is_array($pkg_config['tabs']['tab'])) {
861
			$static_output .= gettext("Integrated Tab items... ");
862
			update_output_window($static_output);
863
			foreach($pkg_config['tabs']['tab'] as $tab) {
864
				if(is_array($config['installedpackages']['tab'])) {
865
					foreach($config['installedpackages']['tab'] as $atab)
866
						if($atab['name'] == $tab['name'])
867
							continue 2;
868
				} else
869
					$config['installedpackages']['tab'] = array();
870
				$config['installedpackages']['tab'][] = $tab;
871
			}
872
			$static_output .= gettext("done.") . "\n";
873
			update_output_window($static_output);
874
		}
875
		/* services */
876
		if(is_array($pkg_config['service'])) {
877
			$static_output .= gettext("Services... ");
878
			update_output_window($static_output);
879
			foreach($pkg_config['service'] as $service) {
880
				if(is_array($config['installedpackages']['service'])) {
881
					foreach($config['installedpackages']['service'] as $aservice)
882
						if($aservice['name'] == $service['name'])
883
							continue 2;
884
				} else
885
					$config['installedpackages']['service'] = array();
886
				$config['installedpackages']['service'][] = $service;
887
			}
888
			$static_output .= gettext("done.") . "\n";
889
			update_output_window($static_output);
890
		}
891
	} else {
892
		$static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted.");
893
		update_output_window($static_output);
894
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
895
		if($pkg_interface <> "console") {
896
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
897
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
898
		}
899
		sleep(1);
900
		return false;
901
	}
902

    
903
	/* set up package logging streams */
904
	if($pkg_info['logging']) {
905
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
906
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
907
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
908
		pkg_debug("Adding text to file /etc/syslog.conf\n");
909
		system_syslogd_start();
910
	}
911

    
912
	return true;
913
}
914

    
915
function does_package_depend($pkg) {
916
	// Should not happen, but just in case.
917
	if(!$pkg)
918
		return;
919
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
920
	// If this package has dependency then return true
921
	foreach($pkg_var_db_dir as $pvdd) {
922
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
923
			return true;
924
	}	
925
	// Did not find a record of dependencies, so return false.
926
	return false;
927
}
928

    
929
function delete_package($pkg) {
930
	global $config, $g, $static_output, $vardb;
931

    
932
	if(!$pkg) 
933
		return;
934

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

    
938
	if($pkg)
939
		$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
940
	update_output_window($static_output);
941

    
942
	remove_freebsd_package($pkg);
943
	$static_output .= "done.\n";
944
	update_output_window($static_output);
945

    
946
	/* Rescan directories for what has been left and avoid fooling other programs. */
947
	mwexec("/sbin/ldconfig");
948

    
949
	return;
950
}
951

    
952
function delete_package_xml($pkg) {
953
	global $g, $config, $static_output, $pkg_interface;
954

    
955
	conf_mount_rw();
956

    
957
	$pkgid = get_pkg_id($pkg);
958
	if ($pkgid == -1) {
959
		$static_output .= sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $pkg, "\n\n");
960
		update_output_window($static_output);
961
		if($pkg_interface <> "console") {
962
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
963
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
964
		}
965
		ob_flush();
966
		sleep(1);
967
		conf_mount_ro();
968
		return;
969
	}
970
	pkg_debug(sprintf(gettext("Removing %s package... "),$pkg));
971
	$static_output .= sprintf(gettext("Removing %s components..."),$pkg) . "\n";
972
	update_output_window($static_output);
973
	/* parse package configuration */
974
	$packages = &$config['installedpackages']['package'];
975
	$tabs =& $config['installedpackages']['tab'];
976
	$menus =& $config['installedpackages']['menu'];
977
	$services = &$config['installedpackages']['service'];
978
	$pkg_info =& $packages[$pkgid];
979
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
980
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
981
		/* remove tab items */
982
		if(is_array($pkg_config['tabs'])) {
983
			$static_output .= gettext("Tabs items... ");
984
			update_output_window($static_output);
985
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
986
				foreach($pkg_config['tabs']['tab'] as $tab) {
987
					foreach($tabs as $key => $insttab) {
988
						if($insttab['name'] == $tab['name']) {
989
							unset($tabs[$key]);
990
							break;
991
						}
992
					}
993
				}
994
			}
995
			$static_output .= gettext("done.") . "\n";
996
			update_output_window($static_output);
997
		}
998
		/* remove menu items */
999
		if(is_array($pkg_config['menu'])) {
1000
			$static_output .= gettext("Menu items... ");
1001
			update_output_window($static_output);
1002
			if (is_array($pkg_config['menu']) && is_array($menus)) {
1003
				foreach($pkg_config['menu'] as $menu) {
1004
					foreach($menus as $key => $instmenu) {
1005
						if($instmenu['name'] == $menu['name']) {
1006
							unset($menus[$key]);
1007
							break;
1008
						}
1009
					}
1010
				}
1011
			}
1012
			$static_output .= gettext("done.") . "\n";
1013
			update_output_window($static_output);
1014
		}
1015
		/* remove services */
1016
		if(is_array($pkg_config['service'])) {
1017
			$static_output .= gettext("Services... ");
1018
			update_output_window($static_output);
1019
			if (is_array($pkg_config['service']) && is_array($services)) {
1020
				foreach($pkg_config['service'] as $service) {
1021
					foreach($services as $key => $instservice) {
1022
						if($instservice['name'] == $service['name']) {
1023
							if($g['booting'] != true)
1024
								stop_service($service['name']);
1025
							if($service['rcfile']) {
1026
								$prefix = RCFILEPREFIX;
1027
								if (!empty($service['prefix']))
1028
									$prefix = $service['prefix'];
1029
								if (file_exists("{$prefix}{$service['rcfile']}"))
1030
									@unlink("{$prefix}{$service['rcfile']}");
1031
							}
1032
							unset($services[$key]);
1033
						}
1034
					}
1035
				}
1036
			}
1037
			$static_output .= gettext("done.") . "\n";
1038
			update_output_window($static_output);
1039
		}
1040
		/*
1041
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
1042
		 * 	Same is done during installation.
1043
		 */
1044
		write_config("Intermediate config write during package removal for {$pkg}.");
1045

    
1046
		/*
1047
		 * If a require exists, include it.  this will
1048
		 * show us where an error exists in a package
1049
		 * instead of making us blindly guess
1050
		 */
1051
		$missing_include = false;
1052
		if($pkg_config['include_file'] <> "") {
1053
			$static_output .= gettext("Loading package instructions...") . "\n";
1054
			update_output_window($static_output);
1055
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
1056
			if (file_exists($pkg_config['include_file']))
1057
				require_once($pkg_config['include_file']);
1058
			else {
1059
				$missing_include = true;
1060
				update_output_window($static_output);
1061
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
1062
			}
1063
		}
1064
		/* ermal
1065
		 * NOTE: It is not possible to handle parse errors on eval.
1066
		 * So we prevent it from being run at all to not interrupt all the other code.
1067
		 */
1068
		if ($missing_include == false) {
1069
			/* evalate this package's global functions and pre deinstall commands */
1070
			if($pkg_config['custom_php_global_functions'] <> "")
1071
				eval_once($pkg_config['custom_php_global_functions']);
1072
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
1073
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
1074
		}
1075
		/* system files */
1076
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
1077
			$static_output .= gettext("System files... ");
1078
			update_output_window($static_output);
1079
			foreach($pkg_config['modify_system']['item'] as $ms)
1080
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
1081

    
1082
			$static_output .= gettext("done.") . "\n";
1083
			update_output_window($static_output);
1084
		}
1085
		/* deinstall commands */
1086
		if($pkg_config['custom_php_deinstall_command'] <> "") {
1087
			$static_output .= gettext("Deinstall commands... ");
1088
			update_output_window($static_output);
1089
			if ($missing_include == false) {
1090
				eval_once($pkg_config['custom_php_deinstall_command']);
1091
				$static_output .= gettext("done.") . "\n";
1092
			} else
1093
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
1094
			update_output_window($static_output);
1095
		}
1096
		if($pkg_config['include_file'] <> "") {
1097
			$static_output .= gettext("Removing package instructions...");
1098
			update_output_window($static_output);
1099
			pkg_debug(sprintf(gettext("Remove '%s'"), $pkg_config['include_file']) . "\n");
1100
			unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1101
			$static_output .= gettext("done.") . "\n";
1102
			update_output_window($static_output);
1103
		}
1104
		/* remove all additional files */
1105
		if(is_array($pkg_config['additional_files_needed'])) {
1106
			$static_output .= gettext("Auxiliary files... ");
1107
			update_output_window($static_output);
1108
			foreach($pkg_config['additional_files_needed'] as $afn) {
1109
				$filename = get_filename_from_url($afn['item'][0]);
1110
				if($afn['prefix'] <> "")
1111
					$prefix = $afn['prefix'];
1112
				else
1113
					$prefix = "/usr/local/pkg/";
1114
				unlink_if_exists($prefix . $filename);
1115
			}
1116
			$static_output .= gettext("done.") . "\n";
1117
			update_output_window($static_output);
1118
		}
1119
		/* package XML file */
1120
		$static_output .= gettext("Package XML... ");
1121
		update_output_window($static_output);
1122
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1123
		$static_output .= gettext("done.") . "\n";
1124
		update_output_window($static_output);
1125
	}
1126
	/* syslog */
1127
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1128
		$static_output .= "Syslog entries... ";
1129
		update_output_window($static_output);
1130
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1131
		system_syslogd_start();
1132
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1133
		$static_output .= "done.\n";
1134
		update_output_window($static_output);
1135
	}
1136
	
1137
	conf_mount_ro();
1138
	/* remove config.xml entries */
1139
	$static_output .= gettext("Configuration... ");
1140
	update_output_window($static_output);
1141
	unset($config['installedpackages']['package'][$pkgid]);
1142
	$static_output .= gettext("done.") . "\n";
1143
	update_output_window($static_output);
1144
	write_config("Removed {$pkg} package.\n");
1145
}
1146

    
1147
function expand_to_bytes($size) {
1148
	$conv = array(
1149
			"G" =>	"3",
1150
			"M" =>  "2",
1151
			"K" =>  "1",
1152
			"B" =>  "0"
1153
		);
1154
	$suffix = substr($size, -1);
1155
	if(!in_array($suffix, array_keys($conv))) return $size;
1156
	$size = substr($size, 0, -1);
1157
	for($i = 0; $i < $conv[$suffix]; $i++) {
1158
		$size *= 1024;
1159
	}
1160
	return $size;
1161
}
1162

    
1163
function get_pkg_db() {
1164
	global $g;
1165
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1166
}
1167

    
1168
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1169
	if(!$pkgdb)
1170
		$pkgdb = get_pkg_db();
1171
	if(!is_array($alreadyseen))
1172
		$alreadyseen = array();
1173
	if (!is_array($depend))
1174
		$depend = array();
1175
	foreach($depend as $adepend) {
1176
		$pkgname = reverse_strrchr($adepend['name'], '.');
1177
		if(in_array($pkgname, $alreadyseen)) {
1178
			continue;
1179
		} elseif(!in_array($pkgname, $pkgdb)) {
1180
			$size += expand_to_bytes($adepend['size']);
1181
			$alreadyseen[] = $pkgname;
1182
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1183
		}
1184
	}
1185
	return $size;
1186
}
1187

    
1188
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1189
	global $config, $g;
1190
	if((!is_array($pkg)) and ($pkg != 'all'))
1191
		$pkg = array($pkg);
1192
	$pkgdb = get_pkg_db();
1193
	if(!$pkg_info)
1194
		$pkg_info = get_pkg_sizes($pkg);
1195
	foreach($pkg as $apkg) {
1196
		if(!$pkg_info[$apkg])
1197
			continue;
1198
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1199
	}
1200
	return $toreturn;
1201
}
1202

    
1203
function squash_from_bytes($size, $round = "") {
1204
	$conv = array(1 => "B", "K", "M", "G");
1205
	foreach($conv as $div => $suffix) {
1206
		$sizeorig = $size;
1207
		if(($size /= 1024) < 1) {
1208
			if($round) {
1209
				$sizeorig = round($sizeorig, $round);
1210
			}
1211
			return $sizeorig . $suffix;
1212
		}
1213
	}
1214
	return;
1215
}
1216

    
1217
function pkg_reinstall_all() {
1218
	global $g, $config;
1219

    
1220
	@unlink('/conf/needs_package_sync');
1221
	if (is_array($config['installedpackages']['package'])) {
1222
		echo gettext("One moment please, reinstalling packages...\n");
1223
		echo gettext(" >>> Trying to fetch package info...");
1224
		log_error(gettext("Attempting to reinstall all packages"));
1225
		$pkg_info = get_pkg_info();
1226
		if ($pkg_info) {
1227
			echo " Done.\n";
1228
		} else {
1229
			$xmlrpc_base_url = get_active_xml_rpc_base_url();
1230
			$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']);
1231
			echo "\n{$error}\n";
1232
			log_error(gettext("Cannot reinstall packages: ") . $error);
1233
			return;
1234
		}
1235
		$todo = array();
1236
		$all_names = array();
1237
		foreach($config['installedpackages']['package'] as $package) {
1238
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1239
			$all_names[] = $package['name'];
1240
		}
1241
		$package_name_list = gettext("List of packages to reinstall: ") . implode(", ", $all_names);
1242
		echo " >>> {$package_name_list}\n";
1243
		log_error($package_name_list);
1244

    
1245
		foreach($todo as $pkgtodo) {
1246
			$static_output = "";
1247
			if($pkgtodo['name']) {
1248
				log_error(gettext("Uninstalling package") . " {$pkgtodo['name']}");
1249
				uninstall_package($pkgtodo['name']);
1250
				log_error(gettext("Finished uninstalling package") . " {$pkgtodo['name']}");
1251
				log_error(gettext("Reinstalling package") . " {$pkgtodo['name']}");
1252
				install_package($pkgtodo['name']);
1253
				log_error(gettext("Finished installing package") . " {$pkgtodo['name']}");
1254
			}
1255
		}
1256
		log_error(gettext("Finished reinstalling all packages."));
1257
	} else
1258
		echo "No packages are installed.";
1259
}
1260

    
1261
function stop_packages() {
1262
	require_once("config.inc");
1263
	require_once("functions.inc");
1264
	require_once("filter.inc");
1265
	require_once("shaper.inc");
1266
	require_once("captiveportal.inc");
1267
	require_once("pkg-utils.inc");
1268
	require_once("pfsense-utils.inc");
1269
	require_once("service-utils.inc");
1270

    
1271
	global $config, $g;
1272

    
1273
	log_error("Stopping all packages.");
1274

    
1275
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1276
	if (!$rcfiles)
1277
		$rcfiles = array();
1278
	else {
1279
		$rcfiles = array_flip($rcfiles);
1280
		if (!$rcfiles)
1281
			$rcfiles = array();
1282
	}
1283

    
1284
	if (is_array($config['installedpackages']['package'])) {
1285
		foreach($config['installedpackages']['package'] as $package) {
1286
			echo " Stopping package {$package['name']}...";
1287
			$internal_name = get_pkg_internal_name($package);
1288
			stop_service($internal_name);
1289
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1290
			echo "done.\n";
1291
		}
1292
	}
1293

    
1294
	foreach ($rcfiles as $rcfile => $number) {
1295
		$shell = @popen("/bin/sh", "w");
1296
		if ($shell) {
1297
			echo " Stopping {$rcfile}...";
1298
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1299
				if ($shell)
1300
					pclose($shell);
1301
				$shell = @popen("/bin/sh", "w");
1302
			}
1303
			echo "done.\n";
1304
			pclose($shell);
1305
		}
1306
	}
1307
}
1308

    
1309
function package_skip_tests($index,$requested_version){
1310
	global $config, $g;
1311

    
1312
	/* Get pfsense version*/
1313
	$version = rtrim(file_get_contents("/etc/version"));
1314
	
1315
	if($g['platform'] == "nanobsd")
1316
		if($index['noembedded']) 
1317
			return true;
1318
						
1319
	/* If we are on not on HEAD, and the package wants it, skip */
1320
	if ($version <> "HEAD" && $index['required_version'] == "HEAD" && $requested_version <> "other")
1321
		return true;
1322
							
1323
	/* If there is no required version, and the requested package version is not 'none', then skip */
1324
	if (empty($index['required_version']) && $requested_version <> "none")
1325
		return true;
1326
							
1327
	/* If the requested version is not 'other', and the required version is newer than what we have, skip. */
1328
	if($requested_version <> "other" && (pfs_version_compare("", $version, $index['required_version']) < 0))
1329
		return true;
1330
							
1331
	/* If the requestion version is 'other' and we are on the version requested, skip. */
1332
	if($requested_version == "other" && (pfs_version_compare("", $version, $index['required_version']) == 0))
1333
		return true;
1334
							
1335
	/* Package is only for an older version, lets skip */
1336
	if($index['maximum_version'] && (pfs_version_compare("", $version, $index['maximum_version']) > 0))
1337
		return true;
1338
		
1339
	/* Do not skip package list */	
1340
	return false;
1341
}
1342

    
1343
function get_pkg_interfaces_select_source($include_localhost=false) {
1344
	$interfaces = get_configured_interface_with_descr();
1345
	$ssifs = array();
1346
	foreach ($interfaces as $iface => $ifacename) {
1347
		$tmp["name"]  = $ifacename;
1348
		$tmp["value"] = $iface;
1349
		$ssifs[] = $tmp;
1350
	}
1351
	if ($include_localhost) {
1352
		$tmp["name"]  = "Localhost";
1353
		$tmp["value"] = "lo0";
1354
		$ssifs[] = $tmp;
1355
	}
1356
	return $ssifs;
1357
}
1358

    
1359
function verify_all_package_servers() {
1360
	return verify_package_server(get_active_xml_rpc_base_url());
1361
}
1362

    
1363
/* Check if the active package server is a valid default or if it has been
1364
	altered. */
1365
function verify_package_server($server) {
1366
	/* Define the expected default package server domains. Include
1367
		preceding "." to prevent matching from being too liberal. */
1368
	$default_package_domains = array('.pfsense.org', '.pfsense.com', '.netgate.com');
1369

    
1370
	/* For this test we only need to check the hostname. */
1371
	$xmlrpcbase = parse_url($server, PHP_URL_HOST);
1372

    
1373
	foreach ($default_package_domains as $dom) {
1374
		if (substr($xmlrpcbase, -(strlen($dom))) == $dom) {
1375
			return true;
1376
		}
1377
	}
1378
	return false;
1379
}
1380

    
1381
/* Test the package server certificate to ensure that it validates properly */
1382
function check_package_server_ssl() {
1383
	global $g;
1384
	$xmlrpcurl = get_active_xml_rpc_base_url() . $g['xmlrpcpath'];
1385

    
1386
	/* If the package server is using HTTP, we can't verify SSL */
1387
	if (substr($xmlrpcurl, 0, 5) == "http:") {
1388
		return "http";
1389
	}
1390

    
1391
	/* Setup a basic cURL connection. We do not care about the content of
1392
		the result, only the SSL verification. */
1393
	$ch = curl_init($xmlrpcurl);
1394
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1395
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
1396
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '30');
1397
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
1398
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1399
	$result_page = curl_exec($ch);
1400
	$verifyfail = curl_getinfo($ch, CURLINFO_SSL_VERIFYRESULT);
1401
	curl_close($ch);
1402

    
1403
	/* The result from curl is 1 on failure, 0 on success. */
1404
	if ($verifyfail == 0)
1405
		return true;
1406
	else
1407
		return false;
1408
}
1409

    
1410
/* Keep this message centrally since it will be used several times on pages
1411
	in the GUI. */
1412
function package_server_ssl_failure_message() {
1413
	$msg = "The package server's SSL certificate could not be verified. "
1414
	. "The SSL certificate itself may be invalid, its chain of trust may "
1415
	. "have failed validation, or the server may have been impersonated. "
1416
	. "Downloaded packages may come from an untrusted source. "
1417
	. "Proceed with caution.";
1418

    
1419
	return sprintf(gettext($msg), htmlspecialchars(get_active_xml_rpc_base_url()));
1420
}
1421

    
1422
/* Keep this message centrally since it will be used several times on pages
1423
	in the GUI. */
1424
function package_server_mismatch_message() {
1425
	$msg = "The package server currently configured on "
1426
	. "this firewall (%s) is NOT an official package server. The contents "
1427
	. "of such servers cannot be verified and may contain malicious files. "
1428
	. "Return the package server settings to their default values to "
1429
	. "ensure that verifiable and trusted packages are received.";
1430

    
1431
	return sprintf(gettext($msg), htmlspecialchars(get_active_xml_rpc_base_url())) . '<br/><br/>'
1432
	. '<a href="/pkg_mgr_settings.php">' . gettext("Package Manager Settings") . '</a>';
1433
}
1434

    
1435

    
1436
function pkg_fetch_config_file($package, $pkg_info = "") {
1437
	global $g, $config, $static_output, $pkg_interface;
1438
	conf_mount_rw();
1439

    
1440
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
1441
		$pkg_info = get_pkg_info(array($package));
1442
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
1443
		if (empty($pkg_info)) {
1444
			conf_mount_ro();
1445
			return -1;
1446
		}
1447
	}
1448

    
1449
	/* fetch the package's configuration file */
1450
	if($pkg_info['config_file'] != "") {
1451
		$static_output .= "\n" . gettext("Downloading package configuration file... ");
1452
		update_output_window($static_output);
1453
		pkg_debug(gettext("Downloading package configuration file...") . "\n");
1454
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
1455
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
1456
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
1457
			pkg_debug(gettext("ERROR! Unable to fetch package configuration file. Aborting installation.") . "\n");
1458
			if($pkg_interface == "console")
1459
				print "\n" . gettext("ERROR! Unable to fetch package configuration file. Aborting package installation.") . "\n";
1460
			else {
1461
				$static_output .= gettext("failed!\n\nInstallation aborted.\n");
1462
				update_output_window($static_output);
1463
				echo "<br />Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
1464
			}
1465
			conf_mount_ro();
1466
			return -1;
1467
		}
1468
		$static_output .= gettext("done.") . "\n";
1469
		update_output_window($static_output);
1470
	}
1471
	conf_mount_ro();
1472
	return true;
1473
}
1474

    
1475

    
1476
function pkg_fetch_additional_files($package, $pkg_info = "") {
1477
	global $g, $config, $static_output, $pkg_interface;
1478
	conf_mount_rw();
1479

    
1480
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
1481
		$pkg_info = get_pkg_info(array($package));
1482
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
1483
		if (empty($pkg_info)) {
1484
			conf_mount_ro();
1485
			return -1;
1486
		}
1487
	}
1488

    
1489
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
1490
	if(file_exists("/usr/local/pkg/" . $configfile)) {
1491
		$static_output .= gettext("Loading package configuration... ");
1492
		update_output_window($static_output);
1493
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
1494
		$static_output .= gettext("done.") . "\n";
1495
		update_output_window($static_output);
1496
		/* download additional files */
1497
		if(is_array($pkg_config['additional_files_needed'])) {
1498
			$static_output .= gettext("Additional files... ");
1499
			$static_orig = $static_output;
1500
			update_output_window($static_output);
1501
			foreach($pkg_config['additional_files_needed'] as $afn) {
1502
				$filename = get_filename_from_url($afn['item'][0]);
1503
				if($afn['chmod'] <> "")
1504
					$pkg_chmod = $afn['chmod'];
1505
				else
1506
					$pkg_chmod = "";
1507

    
1508
				if($afn['prefix'] <> "")
1509
					$prefix = $afn['prefix'];
1510
				else
1511
					$prefix = "/usr/local/pkg/";
1512

    
1513
				if(!is_dir($prefix))
1514
					safe_mkdir($prefix);
1515
				$static_output .= $filename . " ";
1516
				update_output_window($static_output);
1517
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
1518
					$static_output .= "failed.\n";
1519
					@unlink($prefix . $filename);
1520
					update_output_window($static_output);
1521
					return false;
1522
				}
1523
				if(stristr($filename, ".tgz") <> "") {
1524
					pkg_debug(gettext("Extracting tarball to -C for ") . $filename . "...\n");
1525
					$tarout = "";
1526
					exec("/usr/bin/tar xvzf " . escapeshellarg($prefix . $filename) . " -C / 2>&1", $tarout);
1527
					pkg_debug(print_r($tarout, true) . "\n");
1528
				}
1529
				if($pkg_chmod <> "") {
1530
					pkg_debug(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $prefix, $filename, "\n"));
1531
					@chmod($prefix . $filename, $pkg_chmod);
1532
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
1533
				}
1534
				$static_output = $static_orig;
1535
				update_output_window($static_output);
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
?>
(41-41/68)