Project

General

Profile

Download (38.5 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 Lu?i
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
if(file_exists("/cf/conf/use_xmlreader"))
46
	require_once("xmlreader.inc");
47
else
48
	require_once("xmlparse.inc");
49
require_once("service-utils.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
conf_mount_rw();
84
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
85
	safe_mkdir("/usr/local/pkg");
86
	safe_mkdir("/usr/local/pkg/pf");	
87
}
88
conf_mount_ro();
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
	exec("/usr/sbin/pkg_delete -x {$packagestring}");
102
}
103

    
104
/****f* pkg-utils/is_package_installed
105
 * NAME
106
 *   is_package_installed - Check whether a package is installed.
107
 * INPUTS
108
 *   $packagename	- name of the package to check
109
 * RESULT
110
 *   boolean	- true if the package is installed, false otherwise
111
 * NOTES
112
 *   This function is deprecated - get_pkg_id() can already check for installation.
113
 ******/
114
function is_package_installed($packagename) {
115
	$pkg = get_pkg_id($packagename);
116
	if($pkg == -1)
117
		return false;
118
	return true;
119
}
120

    
121
/****f* pkg-utils/get_pkg_id
122
 * NAME
123
 *   get_pkg_id - Find a package's numeric ID.
124
 * INPUTS
125
 *   $pkg_name	- name of the package to check
126
 * RESULT
127
 *   integer    - -1 if package is not found, >-1 otherwise
128
 ******/
129
function get_pkg_id($pkg_name) {
130
	global $config;
131

    
132
	if (is_array($config['installedpackages']['package'])) {
133
		foreach($config['installedpackages']['package'] as $idx => $pkg) {
134
			if($pkg['name'] == $pkg_name)
135
				return $idx;
136
		}
137
	}
138
	return -1;
139
}
140

    
141
/****f* pkg-utils/get_pkg_info
142
 * NAME
143
 *   get_pkg_info - Retrive package information from pfsense.com.
144
 * INPUTS
145
 *   $pkgs - 'all' to retrive all packages, an array containing package names otherwise
146
 *   $info - 'all' to retrive all information, an array containing keys otherwise
147
 * RESULT
148
 *   $raw_versions - Array containing retrieved information, indexed by package name.
149
 ******/
150
function get_pkg_info($pkgs = 'all', $info = 'all') {
151
	global $g;
152

    
153
	$freebsd_version = php_uname("r");
154
	$freebsd_machine = php_uname("m");
155
	$params = array(
156
		"pkg" => $pkgs, 
157
		"info" => $info, 
158
		"freebsd_version" => $freebsd_version[0],
159
		"freebsd_machine" => $freebsd_machine
160
	);
161
	$resp = call_pfsense_method('pfsense.get_pkgs', $params, 10);
162
	return $resp ? $resp : array();
163
}
164

    
165
function get_pkg_sizes($pkgs = 'all') {
166
	global $config, $g;
167

    
168
	$freebsd_version = php_uname("r");
169
	$freebsd_machine = php_uname("m");
170
	$params = array(
171
		"pkg" => $pkgs, 
172
		"freebsd_version" => $freebsd_version,
173
		"freebsd_machine" => $freebsd_machine
174
	);
175
	$msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params)));
176
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
177
	$cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url);
178
	$resp = $cli->send($msg, 10);
179
	if(!is_object($resp))
180
		log_error("Could not get response from XMLRPC server!");
181
 	else if (!$resp->faultCode()) {
182
		$raw_versions = $resp->value();
183
		return xmlrpc_value_to_php($raw_versions);
184
	}
185

    
186
	return array();
187
}
188

    
189
/*
190
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
191
 * This function may also print output to the terminal indicating progress.
192
 */
193
function resync_all_package_configs($show_message = false) {
194
	global $config, $pkg_interface;
195

    
196
	log_error("Resyncing configuration for all packages.");
197
	if (!is_array($config['installedpackages']['package']))
198
		return;
199
	if($show_message == true)
200
		echo "Syncing packages:";
201

    
202
	conf_mount_rw();
203
	foreach($config['installedpackages']['package'] as $idx => $package) {
204
		if (empty($package['name']))
205
			continue;
206
		if($show_message == true)
207
			echo " " . $package['name'];
208
		get_pkg_depends($package['name'], "all");
209
		stop_service($package['name']);
210
		sync_package($idx, true, true);
211
		if($pkg_interface == "console") 
212
			echo "\nSyncing packages:";
213
	}
214
	if($show_message == true)
215
		echo " done.\n";
216
	@unlink("/conf/needs_package_sync");
217
	conf_mount_ro();
218
}
219

    
220
/*
221
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
222
 *				package is installed.
223
 */
224
function is_freebsd_pkg_installed($pkg) {
225
	$output = "";
226
	exec("/usr/sbin/pkg_info -E \"{$pkg}*\"", $output, $retval);
227

    
228
	return (intval($retval) == 0);
229
}
230

    
231
/*
232
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
233
 *
234
 * $filetype = "all" || ".xml", ".tgz", etc.
235
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
236
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
237
 *
238
 */
239
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
240
	global $config;
241

    
242
	$pkg_id = get_pkg_id($pkg_name);
243
	if($pkg_id == -1)
244
		return -1; // This package doesn't really exist - exit the function.
245
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
246
		return; // No package belongs to the pkg_id passed to this function.
247

    
248
	$package =& $config['installedpackages']['package'][$pkg_id];
249
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
250
		log_error("The {$package['name']} package is missing required dependencies and is being reinstalled." . $package['configurationfile']);
251
		uninstall_package($package['name']);
252
		if (install_package($package['name']) < 0) {
253
			log_error("Failed reinstalling package {$package['name']}.");
254
			return false;
255
		}
256
	}
257
	$pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
258
	if (!empty($pkg_xml['additional_files_needed'])) {
259
		foreach($pkg_xml['additional_files_needed'] as $item) {
260
			if ($return_nosync == 0 && isset($item['nosync']))
261
				continue; // Do not return depends with nosync set if not required.
262
			$depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames.
263
			$depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name.
264
			if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file)))
265
					continue;
266
			if ($item['prefix'] != "")
267
				$prefix = $item['prefix'];
268
			else
269
				$prefix = "/usr/local/pkg/";
270
			// Ensure that the prefix exists to avoid installation errors.
271
			if(!is_dir($prefix)) 
272
				exec("/bin/mkdir -p {$prefix}");
273
			if(!file_exists($prefix . $depend_file))
274
				log_error("The {$package['name']} package is missing required dependencies and must be reinstalled.");
275
			switch ($format) {
276
			case "files":
277
				$depends[] = $prefix . $depend_file;
278
				break;
279
			case "names":
280
				switch ($filetype) {
281
				case "all":
282
					if(preg_match("/\.xml/i", $depend_file)) {
283
						$depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui");
284
						if (!empty($depend_xml))
285
							$depends[] = $depend_xml['name'];
286
					} else
287
						$depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename.
288
					break;
289
				case ".xml":
290
					$depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui");
291
					if (!empty($depend_xml))
292
						$depends[] = $depend_xml['name'];
293
					break;
294
				default:
295
					$depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have).
296
					break;
297
				}
298
			}
299
		}
300
		return $depends;
301
	}
302
}
303

    
304
function uninstall_package($pkg_name) {
305
	global $config, $static_output;
306

    
307
	// Back up /usr/local/lib libraries first
308
	if(!file_exists("/tmp/pkg_libs.tgz")) {
309
		$static_output .= "\tBacking up libraries... ";
310
		update_output_window($static_output);
311
		exec("/usr/bin/tar czPf /tmp/pkg_libs.tgz `/bin/cat /etc/pfSense_md5.txt | /usr/bin/grep 'local/lib' | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`");
312
		$static_output .= "\n";
313
	}
314

    
315
	$id = get_pkg_id($pkg_name);
316
	if ($id >= 0) {
317
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
318
		$static_output .= "Removing package...\n";
319
		update_output_window($static_output);
320
		if (is_array($pkg_depends)) {
321
			foreach ($pkg_depends as $pkg_depend)
322
				delete_package($pkg_depend);
323
		}
324
	}
325
	delete_package_xml($pkg_name);
326

    
327
	// Restore libraries that we backed up
328
	$static_output .= "\tCleaning up... ";
329
	update_output_window($static_output);
330
	exec("/usr/bin/tar xzPf /tmp/pkg_libs.tgz -C /");
331
	@unlink("/tmp/pkg_libs.tgz");	
332
}
333

    
334
function force_remove_package($pkg_name) {
335
	delete_package_xml($pkg_name);
336
}
337

    
338
/*
339
 * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files.
340
 */
341
function sync_package($pkg_name, $sync_depends = true, $show_message = false) {
342
	global $config, $config_parsed;
343
	
344
	if(empty($config['installedpackages']['package']))
345
		return;
346
	if(!is_numeric($pkg_name)) {
347
		$pkg_id = get_pkg_id($pkg_name);
348
		if($pkg_id == -1)
349
			return -1; // This package doesn't really exist - exit the function.
350
	} else {
351
		$pkg_id = $pkg_name;
352
		if(empty($config['installedpackages']['package'][$pkg_id]))
353
			return;  // No package belongs to the pkg_id passed to this function.
354
	}
355
        if (is_array($config['installedpackages']['package'][$pkg_id]))
356
		$package =& $config['installedpackages']['package'][$pkg_id];
357
        else
358
		return; /* empty package tag */
359
	if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
360
		log_error("The {$package['name']} package is missing its configuration file and must be reinstalled.");
361
		force_remove_package($package['name']);
362
		return -1;
363
	}
364
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
365
	if(isset($pkg_config['nosync']))
366
		return;
367
	/* Bring in package include files */
368
	if (!empty($pkg_config['include_file'])) {
369
		$include_file = $pkg_config['include_file'];
370
		if (file_exists($include_file))
371
			require_once($include_file);
372
		else {
373
			/* XXX: What the heck is this?! */
374
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
375
			uninstall_package($package['name']);
376
			if (install_package($package['name']) < 0) {
377
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
378
				return -1;
379
			}
380
		}
381
	}
382

    
383
	if(!empty($pkg_config['custom_php_global_functions']))
384
		eval($pkg_config['custom_php_global_functions']);
385
	if(!empty($pkg_config['custom_php_resync_config_command']))
386
		eval($pkg_config['custom_php_resync_config_command']);
387
	if($sync_depends == true) {
388
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
389
		if(is_array($depends)) {
390
			foreach($depends as $item) {
391
				if(!file_exists($item)) {
392
					require_once("notices.inc");
393
					file_notice($package['name'], "The {$package['name']} package is missing required dependencies and must be reinstalled.", "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1);
394
					log_error("Could not find {$item}. Reinstalling package.");
395
					uninstall_package($pkg_name);
396
					if (install_package($pkg_name) < 0) {
397
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
398
						return -1;
399
					}
400
				} else {
401
					$item_config = parse_xml_config_pkg($item, "packagegui");
402
					if (empty($item_config))
403
						continue;
404
					if(isset($item_config['nosync']))
405
						continue;
406
					if (!empty($item_config['include_file'])) {
407
						if (file_exists($item_config['include_file']))	
408
							require_once($item_config['include_file']);
409
						else {
410
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
411
							continue;
412
						}
413
					}
414
					if($item_config['custom_php_global_functions'] <> "")
415
						eval($item_config['custom_php_global_functions']);
416
					if($item_config['custom_php_resync_config_command'] <> "")
417
						eval($item_config['custom_php_resync_config_command']);
418
					if($show_message == true)
419
						print " " . $item_config['name'];
420
				}
421
			}
422
		}
423
	}
424
}
425

    
426
/*
427
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
428
 * 			a progress bar and output window.
429
 */
430
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
431
	global $static_output, $g;
432

    
433
	$osname = php_uname("s");
434
	$arch =  php_uname("m");
435
	$rel = php_uname("r");
436
	$rel = strtolower(substr($rel, 0, strrpos($rel, "-")));
437
	$priv_url = "http://ftp2.{$osname}.org/pub/{$osname}/ports/{$arch}/packages-{$rel}/All";
438
	if (empty($base_url))
439
		$base_url = $priv_url;
440
	if (substr($base_url, -1) == "/")
441
		$base_url = substr($base_url, 0, -1);
442
	$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $pkgname . " ";
443
	$fetchto = "{$g['tmp_path']}/apkg_{$filename}";
444
	$static_output .= "\n\t" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... ";
445
	if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) {
446
		if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) {
447
			$static_output .= " could not download from there or {$priv_url}/{$filename}.\n";
448
			update_output_window($static_output);
449
			return false;
450
		} else if ($base_url == $priv_url) {
451
			$static_output .= " failed to download.\n";
452
			update_output_window($static_output);
453
			return false;
454
		} else {
455
			$static_output .= " downloaded from {$osname} repository instead of provided one.\n";
456
			update_output_window($static_output);
457
		}
458
	}
459
	$static_output .= " (extracting)";
460
	update_output_window($static_output);
461
	$slaveout = "";
462
	exec("/usr/bin/tar --fast-read -O -f {$fetchto} -x +CONTENTS 2>&1", $slaveout);
463
	$raw_depends_list = array_values(preg_grep("/\@pkgdep/", $slaveout));
464
	if ($raw_depends_list != "") {
465
		$pkg_extension = ".tbz";
466
		foreach($raw_depends_list as $adepend) {
467
			$working_depend = explode(" ", trim($adepend, "\n"));
468
			if (substr($working_depend[1], -4) != ".tbz")
469
				$depend_filename = $working_depend[1] . $pkg_extension;
470
			else
471
				$depend_filename = $working_depend[1];
472
			if (!is_freebsd_pkg_installed($working_depend[1])) {
473
				if (pkg_fetch_recursive($working_depend[1], $depend_filename, $dependlevel + 1, $base_url) == false)
474
					return false;
475
			} else {
476
				//$dependlevel++;
477
				$static_output .= "\n" . str_repeat(" ", $dependlevel * 2) . $working_depend[1] . " already installed.";
478
				pkg_debug($working_depend[1] . "\n");
479
			}
480
		}
481
	}
482
	$pkgaddout = "";
483
	exec("/usr/sbin/pkg_add -fv {$fetchto} 2>&1", $pkgaddout);
484
	pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\npkg_add successfully completed.\n");
485

    
486
	return true;
487
}
488

    
489
function install_package($package, $pkg_info = "") {
490
	global $g, $config, $static_output, $pkg_interface;
491

    
492
	/* safe side. Write config below will send to ro again. */
493
	conf_mount_rw();
494

    
495
	if($pkg_interface == "console") 	
496
		echo "\n";
497
	/* fetch package information if needed */
498
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
499
		$pkg_info = get_pkg_info(array($package));
500
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
501
		if (empty($pkg_info)) {
502
			conf_mount_ro();
503
			return -1;
504
		}
505
	}
506
	pkg_debug("Beginning package installation.\n");
507
	log_error('Beginning package installation for ' . $pkg_info['name'] . '.');
508
	$static_output .= "Beginning package installation for " . $pkg_info['name'] . "...";
509
	update_status($static_output);
510
	/* fetch the package's configuration file */
511
	if($pkg_info['config_file'] != "") {
512
		$static_output .= "\nDownloading package configuration file... ";
513
		update_output_window($static_output);
514
		pkg_debug("Downloading package configuration file...\n");
515
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
516
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
517
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
518
			pkg_debug("ERROR! Unable to fetch package configuration file. Aborting installation.\n");
519
			if($pkg_interface == "console")
520
				print "\nERROR! Unable to fetch package configuration file. Aborting package installation.\n";
521
			else {
522
				$static_output .= "failed!\n\nInstallation aborted.\n";
523
				update_output_window($static_output);
524
				echo "<br>Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
525
			}
526
			conf_mount_ro();
527
			return -1;
528
		}
529
		$static_output .= "done.\n";
530
		update_output_window($static_output);
531
	}
532
	/* add package information to config.xml */
533
	$pkgid = get_pkg_id($pkg_info['name']);
534
	$static_output .= "Saving updated package information... ";
535
	update_output_window($static_output);
536
	if($pkgid == -1) {
537
		$config['installedpackages']['package'][] = $pkg_info;
538
		$changedesc = "Installed {$pkg_info['name']} package.";
539
		$to_output = "done.\n";
540
	} else {
541
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
542
		$changedesc = "Overwrote previous installation of {$pkg_info['name']}.";
543
		$to_output = "overwrite!\n";
544
	}
545
	/* XXX: Fix inclusion of config.inc that causes data loss! */
546
	conf_mount_ro();
547
	write_config();
548
	$static_output .= $to_output;
549
	update_output_window($static_output);
550
	/* install other package components */
551
	if (!install_package_xml($package)) {
552
		uninstall_package($package);
553
		write_config($changedesc);
554
		$static_output .= "Failed to install package.\n";
555
		update_output_window($static_output);
556
		return -1;
557
	} else {
558
		$static_output .= "Writing configuration... ";
559
		update_output_window($static_output);
560
		write_config($changedesc);
561
		$static_output .= "done.\n";
562
		update_output_window($static_output);
563
		$static_output .= "Starting service.\n";
564
		update_output_window($static_output);
565
		if($pkg_info['after_install_info']) 
566
			update_output_window($pkg_info['after_install_info']);	
567
	}
568
}
569

    
570
function get_after_install_info($package) {
571
	global $pkg_info;
572
	/* fetch package information if needed */
573
	if(!$pkg_info or !is_array($pkg_info[$package])) {
574
		$pkg_info = get_pkg_info(array($package));
575
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
576
	}
577
	if($pkg_info['after_install_info'])
578
		return $pkg_info['after_install_info'];
579
}
580

    
581
function eval_once($toeval) {
582
	global $evaled;
583
	if(!$evaled) $evaled = array();
584
	$evalmd5 = md5($toeval);
585
	if(!in_array($evalmd5, $evaled)) {
586
		@eval($toeval);
587
		$evaled[] = $evalmd5;
588
	}
589
	return;
590
}
591

    
592
function install_package_xml($pkg) {
593
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
594

    
595
	if(($pkgid = get_pkg_id($pkg)) == -1) {
596
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
597
		update_output_window($static_output);
598
		if($pkg_interface <> "console") {
599
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
600
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
601
		}
602
		sleep(1);
603
		return false;
604
	} else
605
		$pkg_info = $config['installedpackages']['package'][$pkgid];
606

    
607
	/* pkg_add the package and its dependencies */
608
	if($pkg_info['depends_on_package_base_url'] != "") {
609
		if($pkg_interface == "console") 
610
			echo "\n";
611
		update_status("Installing " . $pkg_info['name'] . " and its dependencies.");
612
		$static_output .= "Downloading " . $pkg_info['name'] . " and its dependencies... ";
613
		$static_orig = $static_output;
614
		$static_output .= "\n";
615
		update_output_window($static_output);
616
		foreach((array) $pkg_info['depends_on_package'] as $pkgdep) {
617
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
618
			$static_output = $static_orig . "\nChecking for package installation... ";
619
			update_output_window($static_output);
620
			if (!is_freebsd_pkg_installed($pkg_name)) {
621
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
622
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
623
					update_output_window($static_output);
624
					pkg_debug("Package WAS NOT installed properly.\n");
625
					if($pkg_interface <> "console") {
626
						echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
627
						echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
628
					}
629
					sleep(1);
630
					return false;
631
				}
632
			}
633
		}
634
	}
635
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
636
	if(file_exists("/usr/local/pkg/" . $configfile)) {
637
		$static_output .= "\n\tLoading package configuration... ";
638
		update_output_window($static_output);
639
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
640
		$static_output .= "done.\n";
641
		update_output_window($static_output);
642
		$static_output .= "\tConfiguring package components...\n";
643
		if (!empty($pkg_config['filter_rules_needed']))
644
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
645
		update_output_window($static_output);
646
		/* modify system files */
647
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
648
			$static_output .= "\tSystem files... ";
649
			update_output_window($static_output);
650
			foreach($pkg_config['modify_system']['item'] as $ms) {
651
				if($ms['textneeded']) {
652
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
653
				}
654
			}
655
			$static_output .= "done.\n";
656
			update_output_window($static_output);
657
		}
658
		/* download additional files */
659
		if(is_array($pkg_config['additional_files_needed'])) {
660
			$static_output .= "\tAdditional files... ";
661
			$static_orig = $static_output;
662
			update_output_window($static_output);
663
			foreach($pkg_config['additional_files_needed'] as $afn) {
664
				$filename = get_filename_from_url($afn['item'][0]);
665
				if($afn['chmod'] <> "")
666
					$pkg_chmod = $afn['chmod'];
667
				else
668
					$pkg_chmod = "";
669

    
670
				if($afn['prefix'] <> "")
671
					$prefix = $afn['prefix'];
672
				else
673
					$prefix = "/usr/local/pkg/";
674

    
675
				if(!is_dir($prefix)) 
676
					safe_mkdir($prefix);
677
 				$static_output .= $filename . " ";
678
                                update_output_window($static_output);
679
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
680
					$static_output .= "failed.\n";
681
					update_output_window($static_output);
682
					return false;
683
				}
684
				if(stristr($filename, ".tgz") <> "") {
685
					pkg_debug("Extracting tarball to -C for " . $filename . "...\n");
686
					$tarout = "";
687
					exec("/usr/bin/tar xvzf " . $prefix . $filename . " -C / 2>&1", $tarout);
688
					pkg_debug(print_r($tarout, true) . "\n");
689
				}
690
				if($pkg_chmod <> "") {
691
					pkg_debug("Changing file mode to {$pkg_chmod} for {$prefix}{$filename}\n");
692
					@chmod($prefix . $filename, $pkg_chmod);
693
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
694
				}
695
				$static_output = $static_orig;
696
                                update_output_window($static_output);
697
			}
698
			$static_output .= "done.\n";
699
			update_output_window($static_output);
700
		}
701
		/*   if a require exists, include it.  this will
702
		 *   show us where an error exists in a package
703
		 *   instead of making us blindly guess
704
		 */
705
		$missing_include = false;
706
		if($pkg_config['include_file'] <> "") {
707
			$static_output .= "\tLoading package instructions...\n";
708
			update_output_window($static_output);
709
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
710
			if (file_exists($pkg_config['include_file']))
711
				require_once($pkg_config['include_file']);
712
			else {
713
				$missing_include = true;
714
				$static_output .= "\tInclude " . basename($pkg_config['include_file']) . " is missing!\n";
715
				update_output_window($static_output);
716
				/* XXX: Should undo the steps before this?! */
717
				return false;
718
			}
719
		}
720
		/* sidebar items */
721
		if(is_array($pkg_config['menu'])) {
722
			$static_output .= "\tMenu items... ";
723
			update_output_window($static_output);
724
			foreach($pkg_config['menu'] as $menu) {
725
				if(is_array($config['installedpackages']['menu']))
726
					foreach($config['installedpackages']['menu'] as $amenu)
727
						if($amenu['name'] == $menu['name'])
728
							continue 2;
729
				$config['installedpackages']['menu'][] = $menu;
730
			}
731
			$static_output .= "done.\n";
732
			update_output_window($static_output);
733
		}
734
		/* integrated tab items */
735
		if(is_array($pkg_config['tabs']['tab'])) {
736
			$static_output .= "\tIntegrated Tab items... ";
737
			update_output_window($static_output);
738
			foreach($pkg_config['tabs']['tab'] as $tab) {
739
				if(is_array($config['installedpackages']['tab']))
740
					foreach($config['installedpackages']['tab'] as $atab)
741
						if($atab['name'] == $tab['name'])
742
							continue 2;
743
				$config['installedpackages']['tab'][] = $tab;
744
			}
745
			$static_output .= "done.\n";
746
			update_output_window($static_output);
747
		}
748
		/* services */
749
		if(is_array($pkg_config['service'])) {
750
			$static_output .= "\tServices... ";
751
			update_output_window($static_output);
752
			foreach($pkg_config['service'] as $service) {
753
				if(is_array($config['installedpackages']['service']))
754
					foreach($config['installedpackages']['service'] as $aservice)
755
						if($aservice['name'] == $service['name'])
756
							continue 2;
757
				$config['installedpackages']['service'][] = $service;
758
			}
759
			$static_output .= "done.\n";
760
			update_output_window($static_output);
761
		}
762
		/* custom commands */
763
		$static_output .= "Custom commands...\n";
764
		update_output_window($static_output);
765
		if ($missing_include == false) {
766
			if($pkg_config['custom_php_global_functions'] <> "") {
767
				$static_output .= "\tExecuting custom_php_global_functions()...";
768
				update_output_window($static_output);
769
				eval_once($pkg_config['custom_php_global_functions']);
770
				$static_output .= "done.\n";
771
				update_output_window($static_output);
772
			}
773
			if($pkg_config['custom_php_install_command']) {
774
				$static_output .= "\tExecuting custom_php_install_command()...";
775
				update_output_window($static_output);
776
				eval_once($pkg_config['custom_php_install_command']);
777
				$static_output .= "done.\n";
778
				update_output_window($static_output);
779
			}
780
			if($pkg_config['custom_php_resync_config_command'] <> "") {
781
				$static_output .= "\tExecuting custom_php_resync_config_command()...";
782
				update_output_window($static_output);
783
				eval_once($pkg_config['custom_php_resync_config_command']);
784
				$static_output .= "done.\n";
785
				update_output_window($static_output);
786
			}
787
		}
788
	} else {
789
		$static_output .= "\tLoading package configuration... failed!\n\nInstallation aborted.";
790
		update_output_window($static_output);
791
		pkg_debug("Unable to load package configuration. Installation aborted.\n");
792
		if($pkg_interface <> "console") {
793
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
794
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
795
		}
796
		sleep(1);
797
		return false;
798
	}
799

    
800
	/* set up package logging streams */
801
	if($pkg_info['logging']) {
802
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
803
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
804
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
805
		pkg_debug("Adding text to file /etc/syslog.conf\n");
806
		system_syslogd_start();
807
	}
808

    
809
	return true;
810
}
811

    
812
function delete_package($pkg) {
813
	global $config, $g, $static_output, $vardb;
814

    
815
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
816

    
817

    
818
	if (file_exists("{$vardb}/{$pkg}/+REQUIRED_BY") && count(file("{$vardb}/{$pkg}/+REQUIRED_BY")) > 0) {
819
		$static_output .= "\tSkipping package deletion for {$pkg} because it is required by other packages.\n";
820
		update_output_window($static_output);
821
		return;
822
	} else {
823
		if($pkg)
824
			$static_output .= "\tStarting package deletion for {$pkg}...";
825
		update_output_window($static_output);
826
	}
827
	$info = "";
828
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
829
	remove_freebsd_package($pkg);
830
	$static_output .= "done.\n";
831
	update_output_window($static_output);
832
	foreach($info as $line) {
833
		$depend = trim(str_replace("@pkgdep", "", $line), " \n");
834
		delete_package($depend);
835
	}
836

    
837
	return;
838
}
839

    
840
function delete_package_xml($pkg) {
841
	global $g, $config, $static_output, $pkg_interface;
842

    
843
	conf_mount_rw();
844

    
845
	$pkgid = get_pkg_id($pkg);
846
	if ($pkgid == -1) {
847
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
848
		update_output_window($static_output);
849
		if($pkg_interface <> "console") {
850
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
851
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
852
		}
853
		ob_flush();
854
		sleep(1);
855
		conf_mount_ro();
856
		return;
857
	}
858
	pkg_debug("Removing {$pkg} package... ");
859
	$static_output .= "Removing {$pkg} components...\n";
860
	update_output_window($static_output);
861
	/* parse package configuration */
862
	$packages = &$config['installedpackages']['package'];
863
	$tabs =& $config['installedpackages']['tab'];
864
	$menus =& $config['installedpackages']['menu'];
865
	$services = &$config['installedpackages']['service'];
866
	$pkg_info =& $packages[$pkgid];
867
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
868
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
869
		/* remove tab items */
870
		if(is_array($pkg_config['tabs'])) {
871
			$static_output .= "\tTabs items... ";
872
			update_output_window($static_output);
873
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
874
				foreach($pkg_config['tabs']['tab'] as $tab) {
875
					foreach($tabs as $key => $insttab) {
876
						if($insttab['name'] == $tab['name']) {
877
							unset($tabs[$key]);
878
							break;
879
						}
880
					}
881
				}
882
			}
883
			$static_output .= "done.\n";
884
			update_output_window($static_output);
885
		}
886
		/* remove menu items */
887
		if(is_array($pkg_config['menu'])) {
888
			$static_output .= "\tMenu items... ";
889
			update_output_window($static_output);
890
			if (is_array($pkg_config['menu']) && is_array($menus)) {
891
				foreach($pkg_config['menu'] as $menu) {
892
					foreach($menus as $key => $instmenu) {
893
						if($instmenu['name'] == $menu['name']) {
894
							unset($menus[$key]);
895
							break;
896
						}
897
					}
898
				}
899
			}
900
			$static_output .= "done.\n";
901
			update_output_window($static_output);
902
		}
903
		/* remove services */
904
		if(is_array($pkg_config['service'])) {
905
			$static_output .= "\tServices... ";
906
			update_output_window($static_output);
907
			if (is_array($pkg_config['service']) && is_array($services)) {
908
				foreach($pkg_config['service'] as $service) {
909
					foreach($services as $key => $instservice) {
910
						if($instservice['name'] == $service['name']) {
911
							stop_service($service['name']);
912
							unset($services[$key]);
913
						}
914
					}
915
				}
916
			}
917
			$static_output .= "done.\n";
918
			update_output_window($static_output);
919
		}
920
		/*
921
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
922
		 * 	Same is done during installation.
923
		 */
924
		write_config();
925

    
926
		/*
927
		 * If a require exists, include it.  this will
928
		 * show us where an error exists in a package
929
		 * instead of making us blindly guess
930
		 */
931
		$missing_include = false;
932
		if($pkg_config['include_file'] <> "") {
933
			$static_output .= "\tLoading package instructions...\n";
934
			update_output_window($static_output);
935
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
936
			if (file_exists($pkg_config['include_file']))
937
				require_once($pkg_config['include_file']);
938
			else {
939
				$missing_include = true;
940
				update_output_window($static_output);
941
				$static_output .= "\tInclude file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
942
			}
943
		}
944
		/* ermal
945
		 * NOTE: It is not possible to handle parse errors on eval.
946
		 * So we prevent it from being run at all to not interrupt all the other code.
947
		 */
948
		if ($missing_include == false) {
949
			/* evalate this package's global functions and pre deinstall commands */
950
			if($pkg_config['custom_php_global_functions'] <> "")
951
				eval_once($pkg_config['custom_php_global_functions']);
952
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
953
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
954
		}
955
		/* system files */
956
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
957
			$static_output .= "\tSystem files... ";
958
			update_output_window($static_output);
959
			foreach($pkg_config['modify_system']['item'] as $ms)
960
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
961

    
962
			$static_output .= "done.\n";
963
			update_output_window($static_output);
964
		}
965
		/* deinstall commands */
966
		if($pkg_config['custom_php_deinstall_command'] <> "") {
967
			$static_output .= "\tDeinstall commands... ";
968
			update_output_window($static_output);
969
			if ($missing_include == false) {
970
				eval_once($pkg_config['custom_php_deinstall_command']);
971
				$static_output .= "done.\n";
972
			} else
973
				$static_output .= "\n\tNot executing custom deinstall hook because an include is missing.\n";
974
			update_output_window($static_output);
975
		}
976
		if($pkg_config['include_file'] <> "") {
977
                        $static_output .= "\tRemoving package instructions...";
978
                        update_output_window($static_output);
979
                        pkg_debug("Remove '{$pkg_config['include_file']}'\n");
980
                        unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
981
			$static_output .= "done.\n";
982
                        update_output_window($static_output);
983
			
984
                }
985
		/* remove all additional files */
986
		if(is_array($pkg_config['additional_files_needed'])) {
987
			$static_output .= "\tAuxiliary files... ";
988
			update_output_window($static_output);
989
			foreach($pkg_config['additional_files_needed'] as $afn) {
990
				$filename = get_filename_from_url($afn['item'][0]);
991
				if($afn['prefix'] <> "")
992
					$prefix = $afn['prefix'];
993
				else
994
					$prefix = "/usr/local/pkg/";
995

    
996
				unlink_if_exists($prefix . $filename);
997
			}
998
			$static_output .= "done.\n";
999
			update_output_window($static_output);
1000
		}
1001
		/* package XML file */
1002
		$static_output .= "\tPackage XML... ";
1003
		update_output_window($static_output);
1004
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1005
		$static_output .= "done.\n";
1006
		update_output_window($static_output);
1007
	}
1008
	/* syslog */
1009
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1010
		$static_output .= "\tSyslog entries... ";
1011
		update_output_window($static_output);
1012
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1013
		system_syslogd_start();
1014
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1015
		$static_output .= "done.\n";
1016
		update_output_window($static_output);
1017
	}
1018
	
1019
	conf_mount_ro();
1020
	/* remove config.xml entries */
1021
	$static_output .= "\tConfiguration... ";
1022
	update_output_window($static_output);
1023
	unset($config['installedpackages']['package'][$pkgid]);
1024
	$static_output .= "done.\n";
1025
	update_output_window($static_output);
1026
	write_config("Removed {$pkg} package.\n");
1027
}
1028

    
1029
function expand_to_bytes($size) {
1030
	$conv = array(
1031
			"G" =>	"3",
1032
			"M" =>  "2",
1033
			"K" =>  "1",
1034
			"B" =>  "0"
1035
		);
1036
	$suffix = substr($size, -1);
1037
	if(!in_array($suffix, array_keys($conv))) return $size;
1038
	$size = substr($size, 0, -1);
1039
	for($i = 0; $i < $conv[$suffix]; $i++) {
1040
		$size *= 1024;
1041
	}
1042
	return $size;
1043
}
1044

    
1045
function get_pkg_db() {
1046
	global $g;
1047
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1048
}
1049

    
1050
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1051
	if(!$pkgdb)
1052
		$pkgdb = get_pkg_db();
1053
	if(!is_array($alreadyseen))
1054
		$alreadyseen = array();
1055
	if (!is_array($depend))
1056
		$depend = array();
1057
	foreach($depend as $adepend) {
1058
		$pkgname = reverse_strrchr($adepend['name'], '.');
1059
		if(in_array($pkgname, $alreadyseen)) {
1060
			continue;
1061
		} elseif(!in_array($pkgname, $pkgdb)) {
1062
			$size += expand_to_bytes($adepend['size']);
1063
			$alreadyseen[] = $pkgname;
1064
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1065
		}
1066
	}
1067
	return $size;
1068
}
1069

    
1070
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1071
	global $config, $g;
1072
	if((!is_array($pkg)) and ($pkg != 'all'))
1073
		$pkg = array($pkg);
1074
	$pkgdb = get_pkg_db();
1075
	if(!$pkg_info)
1076
		$pkg_info = get_pkg_sizes($pkg);
1077
	foreach($pkg as $apkg) {
1078
		if(!$pkg_info[$apkg])
1079
			continue;
1080
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1081
	}
1082
	return $toreturn;
1083
}
1084

    
1085
function squash_from_bytes($size, $round = "") {
1086
	$conv = array(1 => "B", "K", "M", "G");
1087
	foreach($conv as $div => $suffix) {
1088
		$sizeorig = $size;
1089
		if(($size /= 1024) < 1) {
1090
			if($round) {
1091
				$sizeorig = round($sizeorig, $round);
1092
			}
1093
			return $sizeorig . $suffix;
1094
		}
1095
	}
1096
	return;
1097
}
1098

    
1099
?>
(31-31/54)