Project

General

Profile

Download (37.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6
 *   This file contains various functions used by the pfSense package system.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2010 Ermal 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	/bin/cat	/usr/sbin/fifolog_create	/bin/chmod
39
	pfSense_BUILDER_BINARIES:	/usr/bin/killall	/usr/sbin/pkg_info	/usr/sbin/pkg_delete	/bin/rm	/bin/ls
40
	pfSense_BUILDER_BINARIES:	/sbin/pfctl
41
	pfSense_MODULE:	pkg
42
*/
43

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

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

    
64
if (!function_exists("pkg_debug")) {
65
	/* set up logging if needed */
66
	function pkg_debug($msg) {
67
		global $g, $debug, $fd_log;
68

    
69
		if (!$debug)
70
			return;
71

    
72
		if (!$fd_log) {
73
			if (!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_{$package}.log", "w"))
74
				update_output_window("Warning, could not open log for writing.");
75
		}
76
		@fwrite($fd_log, $msg);
77
	}
78
}
79

    
80
$vardb = "/var/db/pkg";
81
safe_mkdir($vardb);
82
$g['platform'] = trim(file_get_contents("/etc/platform"));
83

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

    
91
/****f* pkg-utils/remove_package
92
 * NAME
93
 *   remove_package - Removes package from FreeBSD if it exists
94
 * INPUTS
95
 *   $packagestring	- name/string to check for
96
 * RESULT
97
 *   none
98
 * NOTES
99
 *   
100
 ******/
101
function remove_freebsd_package($packagestring) {
102
	exec("/usr/sbin/pkg_delete -x {$packagestring}");
103
}
104

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

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

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

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

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

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

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

    
187
	return array();
188
}
189

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

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

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

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

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

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

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

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

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

    
308
	$id = get_pkg_id($pkg_name);
309
	if ($id >= 0) {
310
		$pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package'];
311
		$static_output .= "Removing package...\n";
312
		update_output_window($static_output);
313
		if (is_array($pkg_depends)) {
314
			foreach ($pkg_depends as $pkg_depend)
315
				delete_package($pkg_depend);
316
		}
317
	}
318
	delete_package_xml($pkg_name);
319
}
320

    
321
function force_remove_package($pkg_name) {
322
	delete_package_xml($pkg_name);
323
}
324

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

    
370
	if(!empty($pkg_config['custom_php_global_functions']))
371
		eval($pkg_config['custom_php_global_functions']);
372
	if(!empty($pkg_config['custom_php_resync_config_command']))
373
		eval($pkg_config['custom_php_resync_config_command']);
374
	if($sync_depends == true) {
375
		$depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking.
376
		if(is_array($depends)) {
377
			foreach($depends as $item) {
378
				if(!file_exists($item)) {
379
					require_once("notices.inc");
380
					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);
381
					log_error("Could not find {$item}. Reinstalling package.");
382
					uninstall_package($pkg_name);
383
					if (install_package($pkg_name) < 0) {
384
						log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
385
						return -1;
386
					}
387
				} else {
388
					$item_config = parse_xml_config_pkg($item, "packagegui");
389
					if (empty($item_config))
390
						continue;
391
					if(isset($item_config['nosync']))
392
						continue;
393
					if (!empty($item_config['include_file'])) {
394
						if (file_exists($item_config['include_file']))	
395
							require_once($item_config['include_file']);
396
						else {
397
							log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing.");
398
							continue;
399
						}
400
					}
401
					if($item_config['custom_php_global_functions'] <> "")
402
						eval($item_config['custom_php_global_functions']);
403
					if($item_config['custom_php_resync_config_command'] <> "")
404
						eval($item_config['custom_php_resync_config_command']);
405
					if($show_message == true)
406
						print " " . $item_config['name'];
407
				}
408
			}
409
		}
410
	}
411
}
412

    
413
/*
414
 * pkg_fetch_recursive: Download and install a FreeBSD package and its dependencies. This function provides output to
415
 * 			a progress bar and output window.
416
 */
417
function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") {
418
	global $static_output, $g;
419

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

    
472
	return true;
473
}
474

    
475
function install_package($package, $pkg_info = "") {
476
	global $g, $config, $static_output, $pkg_interface;
477

    
478
	/* safe side. Write config below will send to ro again. */
479
	conf_mount_rw();
480

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

    
557
function get_after_install_info($package) {
558
	global $pkg_info;
559
	/* fetch package information if needed */
560
	if(!$pkg_info or !is_array($pkg_info[$package])) {
561
		$pkg_info = get_pkg_info(array($package));
562
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
563
	}
564
	if($pkg_info['after_install_info'])
565
		return $pkg_info['after_install_info'];
566
}
567

    
568
function eval_once($toeval) {
569
	global $evaled;
570
	if(!$evaled) $evaled = array();
571
	$evalmd5 = md5($toeval);
572
	if(!in_array($evalmd5, $evaled)) {
573
		@eval($toeval);
574
		$evaled[] = $evalmd5;
575
	}
576
	return;
577
}
578

    
579
function install_package_xml($pkg) {
580
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
581

    
582
	if(($pkgid = get_pkg_id($pkg)) == -1) {
583
		$static_output .= "The {$pkg} package is not installed.\n\nInstallation aborted.";
584
		update_output_window($static_output);
585
		if($pkg_interface <> "console") {
586
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
587
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
588
		}
589
		sleep(1);
590
		return false;
591
	} else
592
		$pkg_info = $config['installedpackages']['package'][$pkgid];
593

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

    
657
				if($afn['prefix'] <> "")
658
					$prefix = $afn['prefix'];
659
				else
660
					$prefix = "/usr/local/pkg/";
661

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

    
787
	/* set up package logging streams */
788
	if($pkg_info['logging']) {
789
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
790
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
791
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
792
		pkg_debug("Adding text to file /etc/syslog.conf\n");
793
		system_syslogd_start();
794
	}
795

    
796
	return true;
797
}
798

    
799
function delete_package($pkg) {
800
	global $config, $g, $static_output, $vardb;
801

    
802
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
803

    
804

    
805
	if (file_exists("{$vardb}/{$pkg}/+REQUIRED_BY") && count(file("{$vardb}/{$pkg}/+REQUIRED_BY")) > 0) {
806
		$static_output .= "\tSkipping package deletion for {$pkg} because it is required by other packages.\n";
807
		update_output_window($static_output);
808
		return;
809
	} else {
810
		if($pkg)
811
			$static_output .= "\tStarting package deletion for {$pkg}...";
812
		update_output_window($static_output);
813
	}
814
	$info = "";
815
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
816
	remove_freebsd_package($pkg);
817
	$static_output .= "done.\n";
818
	update_output_window($static_output);
819
	foreach($info as $line) {
820
		$depend = trim(str_replace("@pkgdep", "", $line), " \n");
821
		delete_package($depend);
822
	}
823

    
824
	return;
825
}
826

    
827
function delete_package_xml($pkg) {
828
	global $g, $config, $static_output, $pkg_interface;
829

    
830
	conf_mount_rw();
831

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

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

    
949
			$static_output .= "done.\n";
950
			update_output_window($static_output);
951
		}
952
		/* deinstall commands */
953
		if($pkg_config['custom_php_deinstall_command'] <> "") {
954
			$static_output .= "\tDeinstall commands... ";
955
			update_output_window($static_output);
956
			if ($missing_include == false) {
957
				eval_once($pkg_config['custom_php_deinstall_command']);
958
				$static_output .= "done.\n";
959
			} else
960
				$static_output .= "\n\tNot executing custom deinstall hook because an include is missing.\n";
961
			update_output_window($static_output);
962
		}
963
		if($pkg_config['include_file'] <> "") {
964
                        $static_output .= "\tRemoving package instructions...";
965
                        update_output_window($static_output);
966
                        pkg_debug("Remove '{$pkg_config['include_file']}'\n");
967
                        unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
968
			$static_output .= "done.\n";
969
                        update_output_window($static_output);
970
			
971
                }
972
		/* remove all additional files */
973
		if(is_array($pkg_config['additional_files_needed'])) {
974
			$static_output .= "\tAuxiliary files... ";
975
			update_output_window($static_output);
976
			foreach($pkg_config['additional_files_needed'] as $afn) {
977
				$filename = get_filename_from_url($afn['item'][0]);
978
				if($afn['prefix'] <> "")
979
					$prefix = $afn['prefix'];
980
				else
981
					$prefix = "/usr/local/pkg/";
982

    
983
				unlink_if_exists($prefix . $filename);
984
			}
985
			$static_output .= "done.\n";
986
			update_output_window($static_output);
987
		}
988
		/* package XML file */
989
		$static_output .= "\tPackage XML... ";
990
		update_output_window($static_output);
991
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
992
		$static_output .= "done.\n";
993
		update_output_window($static_output);
994
	}
995
	/* syslog */
996
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
997
		$static_output .= "\tSyslog entries... ";
998
		update_output_window($static_output);
999
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1000
		system_syslogd_start();
1001
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1002
		$static_output .= "done.\n";
1003
		update_output_window($static_output);
1004
	}
1005
	conf_mount_ro();
1006
	/* remove config.xml entries */
1007
	$static_output .= "\tConfiguration... ";
1008
	update_output_window($static_output);
1009
	unset($config['installedpackages']['package'][$pkgid]);
1010
	$static_output .= "done.\n";
1011
	update_output_window($static_output);
1012
	write_config("Removed {$pkg} package.\n");
1013
}
1014

    
1015
function expand_to_bytes($size) {
1016
	$conv = array(
1017
			"G" =>	"3",
1018
			"M" =>  "2",
1019
			"K" =>  "1",
1020
			"B" =>  "0"
1021
		);
1022
	$suffix = substr($size, -1);
1023
	if(!in_array($suffix, array_keys($conv))) return $size;
1024
	$size = substr($size, 0, -1);
1025
	for($i = 0; $i < $conv[$suffix]; $i++) {
1026
		$size *= 1024;
1027
	}
1028
	return $size;
1029
}
1030

    
1031
function get_pkg_db() {
1032
	global $g;
1033
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1034
}
1035

    
1036
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1037
	if(!$pkgdb)
1038
		$pkgdb = get_pkg_db();
1039
	if(!is_array($alreadyseen))
1040
		$alreadyseen = array();
1041
	if (!is_array($depend))
1042
		$depend = array();
1043
	foreach($depend as $adepend) {
1044
		$pkgname = reverse_strrchr($adepend['name'], '.');
1045
		if(in_array($pkgname, $alreadyseen)) {
1046
			continue;
1047
		} elseif(!in_array($pkgname, $pkgdb)) {
1048
			$size += expand_to_bytes($adepend['size']);
1049
			$alreadyseen[] = $pkgname;
1050
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1051
		}
1052
	}
1053
	return $size;
1054
}
1055

    
1056
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1057
	global $config, $g;
1058
	if((!is_array($pkg)) and ($pkg != 'all'))
1059
		$pkg = array($pkg);
1060
	$pkgdb = get_pkg_db();
1061
	if(!$pkg_info)
1062
		$pkg_info = get_pkg_sizes($pkg);
1063
	foreach($pkg as $apkg) {
1064
		if(!$pkg_info[$apkg])
1065
			continue;
1066
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1067
	}
1068
	return $toreturn;
1069
}
1070

    
1071
function squash_from_bytes($size, $round = "") {
1072
	$conv = array(1 => "B", "K", "M", "G");
1073
	foreach($conv as $div => $suffix) {
1074
		$sizeorig = $size;
1075
		if(($size /= 1024) < 1) {
1076
			if($round) {
1077
				$sizeorig = round($sizeorig, $round);
1078
			}
1079
			return $sizeorig . $suffix;
1080
		}
1081
	}
1082
	return;
1083
}
1084

    
1085
?>
(31-31/54)