Project

General

Profile

Download (39.4 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} 2>>/tmp/pkg_delete_errors.txt");
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
	if(!$pkg) 
226
		return;
227
	$output = "";
228
	exec("/usr/sbin/pkg_info -E \"{$pkg}*\"", $output, $retval);
229

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

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

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

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

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

    
309
	// Back up /usr/local/lib libraries first
310
	if(!file_exists("/tmp/pkg_libs.tgz")) {
311
		$static_output .= "Backing up libraries... ";
312
		update_output_window($static_output);
313
		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`");
314
		$static_output .= "\n";
315
	}
316

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

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

    
336
function force_remove_package($pkg_name) {
337
	delete_package_xml($pkg_name);
338
}
339

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

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

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

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

    
487
	return true;
488
}
489

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

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

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

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

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

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

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

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

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

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

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

    
811
	return true;
812
}
813

    
814
function does_package_depend($pkg) {
815
	// Should not happen, but just in case.
816
	if(!$pkg)
817
		return;
818
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
819
	// If this package has dependency then return true
820
	foreach($pkg_var_db_dir as $pvdd) {
821
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
822
			return true;
823
	}	
824
	// Did not find a record of dependencies, so return false.
825
	return false;
826
}
827

    
828
function delete_package($pkg) {
829
	global $config, $g, $static_output, $vardb;
830

    
831
	if(!$pkg) 
832
		return;
833

    
834
	$pkg = substr(reverse_strrchr($pkg, "."), 0, -1);
835

    
836
	// If package has dependencies then skip it
837
	if(does_package_depend($pkg)) {
838
		$static_output .= "Skipping package deletion for {$pkg} because it is required by other packages.\n";
839
		update_output_window($static_output);
840
		return;		
841
	} else {
842
		if($pkg)
843
			$static_output .= "Starting package deletion for {$pkg}...";
844
		update_output_window($static_output);		
845
	}
846

    
847
	$info = "";
848
	exec("/usr/sbin/pkg_info -qrx {$pkg}", $info);
849
	remove_freebsd_package($pkg);
850
	$static_output .= "done.\n";
851
	update_output_window($static_output);
852
	foreach($info as $line) {
853
		$depend = trim(str_replace("@pkgdep ", "", $line), " \n");
854
		// If package has dependencies then skip it
855
		if(!does_package_depend($depend)) 			
856
			delete_package($depend);
857
	}
858

    
859
	return;
860
}
861

    
862
function delete_package_xml($pkg) {
863
	global $g, $config, $static_output, $pkg_interface;
864

    
865
	conf_mount_rw();
866

    
867
	$pkgid = get_pkg_id($pkg);
868
	if ($pkgid == -1) {
869
		$static_output .= "The {$pkg} package is not installed.\n\nDeletion aborted.";
870
		update_output_window($static_output);
871
		if($pkg_interface <> "console") {
872
			echo "\n<script language=\"JavaScript\">document.progressbar.style.visibility='hidden';</script>";
873
			echo "\n<script language=\"JavaScript\">document.progholder.style.visibility='hidden';</script>";
874
		}
875
		ob_flush();
876
		sleep(1);
877
		conf_mount_ro();
878
		return;
879
	}
880
	pkg_debug("Removing {$pkg} package... ");
881
	$static_output .= "Removing {$pkg} components...\n";
882
	update_output_window($static_output);
883
	/* parse package configuration */
884
	$packages = &$config['installedpackages']['package'];
885
	$tabs =& $config['installedpackages']['tab'];
886
	$menus =& $config['installedpackages']['menu'];
887
	$services = &$config['installedpackages']['service'];
888
	$pkg_info =& $packages[$pkgid];
889
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
890
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
891
		/* remove tab items */
892
		if(is_array($pkg_config['tabs'])) {
893
			$static_output .= "Tabs items... ";
894
			update_output_window($static_output);
895
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
896
				foreach($pkg_config['tabs']['tab'] as $tab) {
897
					foreach($tabs as $key => $insttab) {
898
						if($insttab['name'] == $tab['name']) {
899
							unset($tabs[$key]);
900
							break;
901
						}
902
					}
903
				}
904
			}
905
			$static_output .= "done.\n";
906
			update_output_window($static_output);
907
		}
908
		/* remove menu items */
909
		if(is_array($pkg_config['menu'])) {
910
			$static_output .= "Menu items... ";
911
			update_output_window($static_output);
912
			if (is_array($pkg_config['menu']) && is_array($menus)) {
913
				foreach($pkg_config['menu'] as $menu) {
914
					foreach($menus as $key => $instmenu) {
915
						if($instmenu['name'] == $menu['name']) {
916
							unset($menus[$key]);
917
							break;
918
						}
919
					}
920
				}
921
			}
922
			$static_output .= "done.\n";
923
			update_output_window($static_output);
924
		}
925
		/* remove services */
926
		if(is_array($pkg_config['service'])) {
927
			$static_output .= "Services... ";
928
			update_output_window($static_output);
929
			if (is_array($pkg_config['service']) && is_array($services)) {
930
				foreach($pkg_config['service'] as $service) {
931
					foreach($services as $key => $instservice) {
932
						if($instservice['name'] == $service['name']) {
933
							stop_service($service['name']);
934
							unset($services[$key]);
935
						}
936
					}
937
				}
938
			}
939
			$static_output .= "done.\n";
940
			update_output_window($static_output);
941
		}
942
		/*
943
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
944
		 * 	Same is done during installation.
945
		 */
946
		write_config();
947

    
948
		/*
949
		 * If a require exists, include it.  this will
950
		 * show us where an error exists in a package
951
		 * instead of making us blindly guess
952
		 */
953
		$missing_include = false;
954
		if($pkg_config['include_file'] <> "") {
955
			$static_output .= "Loading package instructions...\n";
956
			update_output_window($static_output);
957
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
958
			if (file_exists($pkg_config['include_file']))
959
				require_once($pkg_config['include_file']);
960
			else {
961
				$missing_include = true;
962
				update_output_window($static_output);
963
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
964
			}
965
		}
966
		/* ermal
967
		 * NOTE: It is not possible to handle parse errors on eval.
968
		 * So we prevent it from being run at all to not interrupt all the other code.
969
		 */
970
		if ($missing_include == false) {
971
			/* evalate this package's global functions and pre deinstall commands */
972
			if($pkg_config['custom_php_global_functions'] <> "")
973
				eval_once($pkg_config['custom_php_global_functions']);
974
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
975
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
976
		}
977
		/* system files */
978
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
979
			$static_output .= "System files... ";
980
			update_output_window($static_output);
981
			foreach($pkg_config['modify_system']['item'] as $ms)
982
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
983

    
984
			$static_output .= "done.\n";
985
			update_output_window($static_output);
986
		}
987
		/* deinstall commands */
988
		if($pkg_config['custom_php_deinstall_command'] <> "") {
989
			$static_output .= "Deinstall commands... ";
990
			update_output_window($static_output);
991
			if ($missing_include == false) {
992
				eval_once($pkg_config['custom_php_deinstall_command']);
993
				$static_output .= "done.\n";
994
			} else
995
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
996
			update_output_window($static_output);
997
		}
998
		if($pkg_config['include_file'] <> "") {
999
                        $static_output .= "Removing package instructions...";
1000
                        update_output_window($static_output);
1001
                        pkg_debug("Remove '{$pkg_config['include_file']}'\n");
1002
                        unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1003
			$static_output .= "done.\n";
1004
                        update_output_window($static_output);
1005
			
1006
                }
1007
		/* remove all additional files */
1008
		if(is_array($pkg_config['additional_files_needed'])) {
1009
			$static_output .= "Auxiliary files... ";
1010
			update_output_window($static_output);
1011
			foreach($pkg_config['additional_files_needed'] as $afn) {
1012
				$filename = get_filename_from_url($afn['item'][0]);
1013
				if($afn['prefix'] <> "")
1014
					$prefix = $afn['prefix'];
1015
				else
1016
					$prefix = "/usr/local/pkg/";
1017

    
1018
				unlink_if_exists($prefix . $filename);
1019
			}
1020
			$static_output .= "done.\n";
1021
			update_output_window($static_output);
1022
		}
1023
		/* package XML file */
1024
		$static_output .= "Package XML... ";
1025
		update_output_window($static_output);
1026
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1027
		$static_output .= "done.\n";
1028
		update_output_window($static_output);
1029
	}
1030
	/* syslog */
1031
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1032
		$static_output .= "Syslog entries... ";
1033
		update_output_window($static_output);
1034
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1035
		system_syslogd_start();
1036
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1037
		$static_output .= "done.\n";
1038
		update_output_window($static_output);
1039
	}
1040
	
1041
	conf_mount_ro();
1042
	/* remove config.xml entries */
1043
	$static_output .= "Configuration... ";
1044
	update_output_window($static_output);
1045
	unset($config['installedpackages']['package'][$pkgid]);
1046
	$static_output .= "done.\n";
1047
	update_output_window($static_output);
1048
	write_config("Removed {$pkg} package.\n");
1049
}
1050

    
1051
function expand_to_bytes($size) {
1052
	$conv = array(
1053
			"G" =>	"3",
1054
			"M" =>  "2",
1055
			"K" =>  "1",
1056
			"B" =>  "0"
1057
		);
1058
	$suffix = substr($size, -1);
1059
	if(!in_array($suffix, array_keys($conv))) return $size;
1060
	$size = substr($size, 0, -1);
1061
	for($i = 0; $i < $conv[$suffix]; $i++) {
1062
		$size *= 1024;
1063
	}
1064
	return $size;
1065
}
1066

    
1067
function get_pkg_db() {
1068
	global $g;
1069
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1070
}
1071

    
1072
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1073
	if(!$pkgdb)
1074
		$pkgdb = get_pkg_db();
1075
	if(!is_array($alreadyseen))
1076
		$alreadyseen = array();
1077
	if (!is_array($depend))
1078
		$depend = array();
1079
	foreach($depend as $adepend) {
1080
		$pkgname = reverse_strrchr($adepend['name'], '.');
1081
		if(in_array($pkgname, $alreadyseen)) {
1082
			continue;
1083
		} elseif(!in_array($pkgname, $pkgdb)) {
1084
			$size += expand_to_bytes($adepend['size']);
1085
			$alreadyseen[] = $pkgname;
1086
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1087
		}
1088
	}
1089
	return $size;
1090
}
1091

    
1092
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1093
	global $config, $g;
1094
	if((!is_array($pkg)) and ($pkg != 'all'))
1095
		$pkg = array($pkg);
1096
	$pkgdb = get_pkg_db();
1097
	if(!$pkg_info)
1098
		$pkg_info = get_pkg_sizes($pkg);
1099
	foreach($pkg as $apkg) {
1100
		if(!$pkg_info[$apkg])
1101
			continue;
1102
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1103
	}
1104
	return $toreturn;
1105
}
1106

    
1107
function squash_from_bytes($size, $round = "") {
1108
	$conv = array(1 => "B", "K", "M", "G");
1109
	foreach($conv as $div => $suffix) {
1110
		$sizeorig = $size;
1111
		if(($size /= 1024) < 1) {
1112
			if($round) {
1113
				$sizeorig = round($sizeorig, $round);
1114
			}
1115
			return $sizeorig . $suffix;
1116
		}
1117
	}
1118
	return;
1119
}
1120

    
1121
function pkg_reinstall_all() {
1122
	global $g, $config;
1123
	$pkg_id = 0;
1124
	$todo = array();
1125
	if (is_array($config['installedpackages']['package']))
1126
		foreach($config['installedpackages']['package'] as $package)
1127
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1128
	echo "One moment please, reinstalling packages...\n";
1129
	if(is_array($todo)) {
1130
		foreach($todo as $pkgtodo) {
1131
			$static_output = "";
1132
			if($pkgtodo['name']) {
1133
				uninstall_package($pkgtodo['name']);
1134
				install_package($pkgtodo['name']);
1135
				$pkg_id++;
1136
			}
1137
		}
1138
	}
1139
}
1140

    
1141
?>
(36-36/61)