Projet

Général

Profil

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

univnautes / etc / inc / pkg-utils.inc @ 26d060bc

1
<?php
2
/****h* pfSense/pkg-utils
3
 * NAME
4
 *   pkg-utils.inc - Package subsystem
5
 * DESCRIPTION
6
 *   This file contains various functions used by the pfSense package system.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2010 Ermal Luci
12
 * Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
13
 * All rights reserved.
14
 * Redistribution and use in source and binary forms, with or without
15
 * modification, are permitted provided that the following conditions are met:
16
 *
17
 * 1. Redistributions of source code must retain the above copyright notice,
18
 * this list of conditions and the following disclaimer.
19
 *
20
 * 2. Redistributions in binary form must reproduce the above copyright
21
 * notice, this list of conditions and the following disclaimer in the
22
 * documentation and/or other materials provided with the distribution.
23
 *
24
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
26
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
28
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
 * POSSIBILITY OF SUCH DAMAGE.
34
 *
35
 */
36

    
37
/*
38
	pfSense_BUILDER_BINARIES:	/usr/bin/cd	/usr/bin/tar	/usr/sbin/fifolog_create	/bin/chmod
39
	pfSense_BUILDER_BINARIES:	/usr/sbin/pkg_add	/usr/sbin/pkg_info	/usr/sbin/pkg_delete	/bin/rm
40
	pfSense_MODULE:	pkg
41
*/
42

    
43
require_once("globals.inc");
44
require_once("xmlrpc.inc");
45
require_once("service-utils.inc");
46
if(file_exists("/cf/conf/use_xmlreader"))
47
	require_once("xmlreader.inc");
48
else
49
	require_once("xmlparse.inc");
50
require_once("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
if(!is_dir("/usr/local/pkg") or !is_dir("/usr/local/pkg/pf")) {
85
	conf_mount_rw();
86
	safe_mkdir("/usr/local/pkg");
87
	safe_mkdir("/usr/local/pkg/pf");	
88
	conf_mount_ro();
89
}
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
	// The packagestring passed in must be the full PBI package name, 
103
	// as displayed by the pbi_info utility. e.g. "package-1.2.3_4-i386" 
104
	// It must NOT have ".pbi" on the end.
105
	$links = get_pbi_binaries(escapeshellarg($packagestring));
106
	foreach($links as $link)
107
		if (is_link("/usr/local/{$link['link_name']}"))
108
			@unlink("/usr/local/{$link['link_name']}");
109
	exec("/usr/local/sbin/pbi_delete " . escapeshellarg($packagestring) . " 2>>/tmp/pbi_delete_errors.txt");
110
}
111

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

    
129
/****f* pkg-utils/get_pkg_id
130
 * NAME
131
 *   get_pkg_id - Find a package's numeric ID.
132
 * INPUTS
133
 *   $pkg_name	- name of the package to check
134
 * RESULT
135
 *   integer    - -1 if package is not found, >-1 otherwise
136
 ******/
137
function get_pkg_id($pkg_name) {
138
	global $config;
139

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

    
149
/****f* pkg-utils/get_pkg_internal_name
150
 * NAME
151
 *   get_pkg_internal_name - Find a package's internal name (e.g. squid3 internal name is squid)
152
 * INPUTS
153
 *   $package - array of package data from config
154
 * RESULT
155
 *   string - internal name (if defined) or default to package name
156
 ******/
157
function get_pkg_internal_name($package) {
158
	if (isset($package['internal_name']) && ($package['internal_name'] != "")) {
159
		/* e.g. name is Ipguard-dev, internal name is ipguard */
160
		$pkg_internal_name = $package['internal_name'];
161
	} else {
162
		$pkg_internal_name = $package['name'];
163
	}
164
	return $pkg_internal_name;
165
}
166

    
167
/****f* pkg-utils/get_pkg_info
168
 * NAME
169
 *   get_pkg_info - Retrieve package information from package server.
170
 * INPUTS
171
 *   $pkgs - 'all' to retrieve all packages, an array containing package names otherwise
172
 *   $info - 'all' to retrieve all information, an array containing keys otherwise
173
 * RESULT
174
 *   $raw_versions - Array containing retrieved information, indexed by package name.
175
 ******/
176
function get_pkg_info($pkgs = 'all', $info = 'all') {
177
	global $g;
178

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

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

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

    
210
	return array();
211
}
212

    
213
/*
214
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
215
 * This function may also print output to the terminal indicating progress.
216
 */
217
function resync_all_package_configs($show_message = false) {
218
	global $config, $pkg_interface, $g;
219

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

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

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

    
228
	conf_mount_rw();
229

    
230
	foreach($config['installedpackages']['package'] as $idx => $package) {
231
		if (empty($package['name']))
232
			continue;
233
		if($show_message == true)
234
			echo " " . $package['name'];
235
		get_pkg_depends($package['name'], "all");
236
		if($g['booting'] != true)
237
			stop_service(get_pkg_internal_name($package));
238
		sync_package($idx, true, true);
239
		if($pkg_interface == "console") 
240
			echo "\n" . gettext("Syncing packages:");
241
	}
242

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

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

    
250
/*
251
 * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD
252
 *				package is installed.
253
 */
254
function is_freebsd_pkg_installed($pkg) {
255
	if(!$pkg) 
256
		return;
257
	$output = "";
258
	exec("/usr/local/sbin/pbi_info " . escapeshellarg($pkg), $output, $retval);
259

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

    
263
/*
264
 * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1):  Return a package's dependencies.
265
 *
266
 * $filetype = "all" || ".xml", ".tgz", etc.
267
 * $format = "files" (full filenames) || "names" (stripped / parsed depend names)
268
 * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync)
269
 *
270
 */
271
function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) {
272
	global $config;
273

    
274
	$pkg_id = get_pkg_id($pkg_name);
275
	if($pkg_id == -1)
276
		return -1; // This package doesn't really exist - exit the function.
277
	else if (!isset($config['installedpackages']['package'][$pkg_id]))
278
		return; // No package belongs to the pkg_id passed to this function.
279

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

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

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

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

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

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

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

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

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

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

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

    
519
		$pkgaddout = "";
520

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

    
525
		$result = exec("/usr/local/sbin/pbi_add " . $pkgstaging . " -f -v {$no_checksig} " . escapeshellarg($fetchto) . " 2>&1", $pkgaddout, $rc);
526
		pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\n");
527
		if ($rc == 0) {
528
			$links = get_pbi_binaries(escapeshellarg(preg_replace('/\.pbi$/','',$filename)));
529
			foreach($links as $link) {
530
				@unlink("/usr/local/{$link['link_name']}");
531
				@symlink("{$link['target']}","/usr/local/{$link['link_name']}");
532
			}
533
			pkg_debug("pbi_add successfully completed.\n");
534
		} else {
535
			if (is_array($pkgaddout))
536
				foreach ($pkgaddout as $line)
537
					$static_output .= " " . $line .= "\n";
538

    
539
			update_output_window($static_output);
540
			pkg_debug("pbi_add failed.\n");
541
			return false;
542
		}
543
	}
544
	return true;
545
}
546

    
547
function get_pbi_binaries($pbi) {
548
	$result = array();
549

    
550
	if (empty($pbi))
551
		return $result;
552

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

    
556
	if (empty($pbi_prefix))
557
		return $result;
558

    
559
	foreach(array('bin', 'sbin') as $dir) {
560
		if(!is_dir("{$pbi_prefix}/{$dir}"))
561
			continue;
562

    
563
		$files = glob("{$pbi_prefix}/{$dir}/*.pbiopt");
564
		foreach($files as $f) {
565
			$pbiopts = file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
566
			foreach($pbiopts as $pbiopt) {
567
				if (!preg_match('/^TARGET:\s+(.*)$/', $pbiopt, $matches))
568
					continue;
569

    
570
				$result[] = array(
571
					'target' => preg_replace('/\.pbiopt$/', '', $f),
572
					'link_name' => $matches[1]);
573
			}
574
		}
575
	}
576

    
577
	return $result;
578
}
579

    
580
function install_package($package, $pkg_info = "", $force_install = false) {
581
	global $g, $config, $static_output, $pkg_interface;
582

    
583
	/* safe side. Write config below will send to ro again. */
584
	conf_mount_rw();
585

    
586
	if($pkg_interface == "console") 	
587
		echo "\n";
588
	/* fetch package information if needed */
589
	if(empty($pkg_info) or !is_array($pkg_info[$package])) {
590
		$pkg_info = get_pkg_info(array($package));
591
		$pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array.
592
		if (empty($pkg_info)) {
593
			conf_mount_ro();
594
			return -1;
595
		}
596
	}
597
	if (!$force_install) {
598
		$compatible = true;
599
		$version = rtrim(file_get_contents("/etc/version"));
600
		
601
		if (isset($pkg_info['required_version']))
602
			$compatible = (pfs_version_compare("", $version, $pkg_info['required_version']) >= 0);
603
		if (isset($pkg_info['maximum_version']))
604
			$compatible = $compatible && (pfs_version_compare("", $version, $pkg_info['maximum_version']) <= 0);
605
		
606
		if (!$compatible) {
607
			log_error(sprintf(gettext('Package %s is not supported on this version.'), $pkg_info['name']));
608
			$static_output .= sprintf(gettext("Package %s is not supported on this version."), $pkg_info['name']);
609
			update_status($static_output);
610
			
611
			conf_mount_ro();
612
			return -1;
613
		}
614
	}
615
	pkg_debug(gettext("Beginning package installation.") . "\n");
616
	log_error(sprintf(gettext('Beginning package installation for %s .'), $pkg_info['name']));
617
	$static_output .= sprintf(gettext("Beginning package installation for %s ."), $pkg_info['name']);
618
	update_status($static_output);
619
	/* fetch the package's configuration file */
620
	if($pkg_info['config_file'] != "") {
621
		$static_output .= "\n" . gettext("Downloading package configuration file... ");
622
		update_output_window($static_output);
623
		pkg_debug(gettext("Downloading package configuration file...") . "\n");
624
		$fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1);
625
		download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto);
626
		if(!file_exists('/usr/local/pkg/' . $fetchto)) {
627
			pkg_debug(gettext("ERROR! Unable to fetch package configuration file. Aborting installation.") . "\n");
628
			if($pkg_interface == "console")
629
				print "\n" . gettext("ERROR! Unable to fetch package configuration file. Aborting package installation.") . "\n";
630
			else {
631
				$static_output .= gettext("failed!\n\nInstallation aborted.\n");
632
				update_output_window($static_output);
633
				echo "<br />Show <a href=\"pkg_mgr_install.php?showlog=true\">install log</a></center>";
634
			}
635
			conf_mount_ro();
636
			return -1;
637
		}
638
		$static_output .= gettext("done.") . "\n";
639
		update_output_window($static_output);
640
	}
641
	/* add package information to config.xml */
642
	$pkgid = get_pkg_id($pkg_info['name']);
643
	$static_output .= gettext("Saving updated package information...") . " ";
644
	update_output_window($static_output);
645
	if($pkgid == -1) {
646
		$config['installedpackages']['package'][] = $pkg_info;
647
		$changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']);
648
		$to_output = gettext("done.") . "\n";
649
	} else {
650
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
651
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
652
		$to_output = gettext("overwrite!") . "\n";
653
	}
654
	if(file_exists('/conf/needs_package_sync'))
655
		@unlink('/conf/needs_package_sync');
656
	conf_mount_ro();
657
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
658
	$static_output .= $to_output;
659
	update_output_window($static_output);
660
	/* install other package components */
661
	if (!install_package_xml($package)) {
662
		uninstall_package($package);
663
		write_config($changedesc);
664
		$static_output .= gettext("Failed to install package.") . "\n";
665
		update_output_window($static_output);
666
		return -1;
667
	} else {
668
		$static_output .= gettext("Writing configuration... ");
669
		update_output_window($static_output);
670
		write_config($changedesc);
671
		$static_output .= gettext("done.") . "\n";
672
		update_output_window($static_output);
673
		if($pkg_info['after_install_info']) 
674
			update_output_window($pkg_info['after_install_info']);	
675
	}
676
}
677

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

    
689
function eval_once($toeval) {
690
	global $evaled;
691
	if(!$evaled) $evaled = array();
692
	$evalmd5 = md5($toeval);
693
	if(!in_array($evalmd5, $evaled)) {
694
		@eval($toeval);
695
		$evaled[] = $evalmd5;
696
	}
697
	return;
698
}
699

    
700
function install_package_xml($pkg) {
701
	global $g, $config, $static_output, $pkg_interface, $config_parsed;
702

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

    
715
	/* pkg_add the package and its dependencies */
716
	if($pkg_info['depends_on_package_base_url'] != "") {
717
		if($pkg_interface == "console") 
718
			echo "\n";
719
		update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies."));
720
		$static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... ");
721
		$static_orig = $static_output;
722
		$static_output .= "\n";
723
		update_output_window($static_output);
724
		foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) {
725
			$pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1);
726
			$static_output = $static_orig . "\nChecking for package installation... ";
727
			update_output_window($static_output);
728
			if (!is_freebsd_pkg_installed($pkg_name)) {
729
				if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) {
730
					$static_output .= "of {$pkg_name} failed!\n\nInstallation aborted.";
731
					update_output_window($static_output);
732
					pkg_debug(gettext("Package WAS NOT installed properly.") . "\n");
733
					if($pkg_interface <> "console") {
734
						echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
735
						echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
736
					}
737
					sleep(1);
738
					return false;
739
				}
740
			}
741
		}
742
	}
743
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
744
	if(file_exists("/usr/local/pkg/" . $configfile)) {
745
		$static_output .= gettext("Loading package configuration... ");
746
		update_output_window($static_output);
747
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
748
		$static_output .= gettext("done.") . "\n";
749
		update_output_window($static_output);
750
		$static_output .= gettext("Configuring package components...\n");
751
		if (!empty($pkg_config['filter_rules_needed']))
752
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
753
		update_output_window($static_output);
754
		/* modify system files */
755
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
756
			$static_output .= gettext("System files... ");
757
			update_output_window($static_output);
758
			foreach($pkg_config['modify_system']['item'] as $ms) {
759
				if($ms['textneeded']) {
760
					add_text_to_file($ms['modifyfilename'], $ms['textneeded']);
761
				}
762
			}
763
			$static_output .= gettext("done.") . "\n";
764
			update_output_window($static_output);
765
		}
766
		/* download additional files */
767
		if(is_array($pkg_config['additional_files_needed'])) {
768
			$static_output .= gettext("Additional files... ");
769
			$static_orig = $static_output;
770
			update_output_window($static_output);
771
			foreach($pkg_config['additional_files_needed'] as $afn) {
772
				$filename = get_filename_from_url($afn['item'][0]);
773
				if($afn['chmod'] <> "")
774
					$pkg_chmod = $afn['chmod'];
775
				else
776
					$pkg_chmod = "";
777

    
778
				if($afn['prefix'] <> "")
779
					$prefix = $afn['prefix'];
780
				else
781
					$prefix = "/usr/local/pkg/";
782

    
783
				if(!is_dir($prefix)) 
784
					safe_mkdir($prefix);
785
 				$static_output .= $filename . " ";
786
				update_output_window($static_output);
787
				if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) {
788
					$static_output .= "failed.\n";
789
					@unlink($prefix . $filename);
790
					update_output_window($static_output);
791
					return false;
792
				}
793
				if(stristr($filename, ".tgz") <> "") {
794
					pkg_debug(gettext("Extracting tarball to -C for ") . $filename . "...\n");
795
					$tarout = "";
796
					exec("/usr/bin/tar xvzf " . escapeshellarg($prefix . $filename) . " -C / 2>&1", $tarout);
797
					pkg_debug(print_r($tarout, true) . "\n");
798
				}
799
				if($pkg_chmod <> "") {
800
					pkg_debug(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $prefix, $filename, "\n"));
801
					@chmod($prefix . $filename, $pkg_chmod);
802
					system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}");
803
				}
804
				$static_output = $static_orig;
805
				update_output_window($static_output);
806
			}
807
			$static_output .= gettext("done.") . "\n";
808
			update_output_window($static_output);
809
		}
810
		/*   if a require exists, include it.  this will
811
		 *   show us where an error exists in a package
812
		 *   instead of making us blindly guess
813
		 */
814
		$missing_include = false;
815
		if($pkg_config['include_file'] <> "") {
816
			$static_output .= gettext("Loading package instructions...") . "\n";
817
			update_output_window($static_output);
818
			pkg_debug("require_once('{$pkg_config['include_file']}')\n");
819
			if (file_exists($pkg_config['include_file']))
820
				require_once($pkg_config['include_file']);
821
			else {
822
				$missing_include = true;
823
				$static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n";
824
				update_output_window($static_output);
825
				/* XXX: Should undo the steps before this?! */
826
				return false;
827
			}
828
		}
829

    
830
		/* custom commands */
831
		$static_output .= gettext("Custom commands...") . "\n";
832
		update_output_window($static_output);
833
		if ($missing_include == false) {
834
			if($pkg_config['custom_php_global_functions'] <> "") {
835
				$static_output .= gettext("Executing custom_php_global_functions()...");
836
				update_output_window($static_output);
837
				eval_once($pkg_config['custom_php_global_functions']);
838
				$static_output .= gettext("done.") . "\n";
839
				update_output_window($static_output);
840
			}
841
			if($pkg_config['custom_php_install_command']) {
842
				$static_output .= gettext("Executing custom_php_install_command()...");
843
				update_output_window($static_output);
844
				/* XXX: create symlinks for conf files into the PBI directories.
845
				 *	change packages to store configs at /usr/pbi/pkg/etc and remove this
846
				 */
847
				eval_once($pkg_config['custom_php_install_command']);
848
				// Note: pkg may be mixed-case, e.g. "squidGuard" but the PBI names are lowercase.
849
				// e.g. "squidguard-1.4_4-i386" so feed lowercase to pbi_info below.
850
				// Also add the "-" so that examples like "squid-" do not match "squidguard-".
851
				$pkg_name_for_pbi_match = strtolower($pkg) . "-";
852
				exec("/usr/local/sbin/pbi_info | grep '^{$pkg_name_for_pbi_match}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray);
853
				$pbidir0 = $pbidirarray[0];
854
				exec("find /usr/local/etc/ -name *.conf | grep " . escapeshellarg($pkg),$files);
855
				foreach($files as $f) {
856
					$pbiconf = str_replace('/usr/local',$pbidir0,$f);
857
					if(is_file($pbiconf) || is_link($pbiconf)) {
858
						unlink($pbiconf);
859
					}
860
					if(is_dir(dirname($pbiconf))) {
861
						symlink($f,$pbiconf);
862
					} else {
863
						log_error("The dir for {$pbiconf} does not exist. Cannot add symlink to {$f}.");
864
					}
865
				}
866
				eval_once($pkg_config['custom_php_install_command']);
867
				$static_output .= gettext("done.") . "\n";
868
				update_output_window($static_output);
869
			}
870
			if($pkg_config['custom_php_resync_config_command'] <> "") {
871
				$static_output .= gettext("Executing custom_php_resync_config_command()...");
872
				update_output_window($static_output);
873
				eval_once($pkg_config['custom_php_resync_config_command']);
874
				$static_output .= gettext("done.") . "\n";
875
				update_output_window($static_output);
876
			}
877
		}
878
		/* sidebar items */
879
		if(is_array($pkg_config['menu'])) {
880
			$static_output .= gettext("Menu items... ");
881
			update_output_window($static_output);
882
			foreach($pkg_config['menu'] as $menu) {
883
				if(is_array($config['installedpackages']['menu'])) {
884
					foreach($config['installedpackages']['menu'] as $amenu)
885
						if($amenu['name'] == $menu['name'])
886
							continue 2;
887
				} else
888
					$config['installedpackages']['menu'] = array();
889
				$config['installedpackages']['menu'][] = $menu;
890
			}
891
			$static_output .= gettext("done.") . "\n";
892
			update_output_window($static_output);
893
		}
894
		/* integrated tab items */
895
		if(is_array($pkg_config['tabs']['tab'])) {
896
			$static_output .= gettext("Integrated Tab items... ");
897
			update_output_window($static_output);
898
			foreach($pkg_config['tabs']['tab'] as $tab) {
899
				if(is_array($config['installedpackages']['tab'])) {
900
					foreach($config['installedpackages']['tab'] as $atab)
901
						if($atab['name'] == $tab['name'])
902
							continue 2;
903
				} else
904
					$config['installedpackages']['tab'] = array();
905
				$config['installedpackages']['tab'][] = $tab;
906
			}
907
			$static_output .= gettext("done.") . "\n";
908
			update_output_window($static_output);
909
		}
910
		/* services */
911
		if(is_array($pkg_config['service'])) {
912
			$static_output .= gettext("Services... ");
913
			update_output_window($static_output);
914
			foreach($pkg_config['service'] as $service) {
915
				if(is_array($config['installedpackages']['service'])) {
916
					foreach($config['installedpackages']['service'] as $aservice)
917
						if($aservice['name'] == $service['name'])
918
							continue 2;
919
				} else
920
					$config['installedpackages']['service'] = array();
921
				$config['installedpackages']['service'][] = $service;
922
			}
923
			$static_output .= gettext("done.") . "\n";
924
			update_output_window($static_output);
925
		}
926
	} else {
927
		$static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted.");
928
		update_output_window($static_output);
929
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
930
		if($pkg_interface <> "console") {
931
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
932
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
933
		}
934
		sleep(1);
935
		return false;
936
	}
937

    
938
	/* set up package logging streams */
939
	if($pkg_info['logging']) {
940
		mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
941
		@chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600);
942
		add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
943
		pkg_debug("Adding text to file /etc/syslog.conf\n");
944
		system_syslogd_start();
945
	}
946

    
947
	return true;
948
}
949

    
950
function does_package_depend($pkg) {
951
	// Should not happen, but just in case.
952
	if(!$pkg)
953
		return;
954
	$pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*");
955
	// If this package has dependency then return true
956
	foreach($pkg_var_db_dir as $pvdd) {
957
		if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) 
958
			return true;
959
	}	
960
	// Did not find a record of dependencies, so return false.
961
	return false;
962
}
963

    
964
function delete_package($pkg) {
965
	global $config, $g, $static_output, $vardb;
966

    
967
	if(!$pkg) 
968
		return;
969

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

    
973
	if($pkg)
974
		$static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg);
975
	update_output_window($static_output);
976

    
977
	remove_freebsd_package($pkg);
978
	$static_output .= "done.\n";
979
	update_output_window($static_output);
980

    
981
	/* Rescan directories for what has been left and avoid fooling other programs. */
982
	mwexec("/sbin/ldconfig");
983

    
984
	return;
985
}
986

    
987
function delete_package_xml($pkg) {
988
	global $g, $config, $static_output, $pkg_interface;
989

    
990
	conf_mount_rw();
991

    
992
	$pkgid = get_pkg_id($pkg);
993
	if ($pkgid == -1) {
994
		$static_output .= sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $pkg, "\n\n");
995
		update_output_window($static_output);
996
		if($pkg_interface <> "console") {
997
			echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';</script>";
998
			echo "\n<script type=\"text/javascript\">document.progholder.style.visibility='hidden';</script>";
999
		}
1000
		ob_flush();
1001
		sleep(1);
1002
		conf_mount_ro();
1003
		return;
1004
	}
1005
	pkg_debug(sprintf(gettext("Removing %s package... "),$pkg));
1006
	$static_output .= sprintf(gettext("Removing %s components..."),$pkg) . "\n";
1007
	update_output_window($static_output);
1008
	/* parse package configuration */
1009
	$packages = &$config['installedpackages']['package'];
1010
	$tabs =& $config['installedpackages']['tab'];
1011
	$menus =& $config['installedpackages']['menu'];
1012
	$services = &$config['installedpackages']['service'];
1013
	$pkg_info =& $packages[$pkgid];
1014
	if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
1015
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
1016
		/* remove tab items */
1017
		if(is_array($pkg_config['tabs'])) {
1018
			$static_output .= gettext("Tabs items... ");
1019
			update_output_window($static_output);
1020
			if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) {
1021
				foreach($pkg_config['tabs']['tab'] as $tab) {
1022
					foreach($tabs as $key => $insttab) {
1023
						if($insttab['name'] == $tab['name']) {
1024
							unset($tabs[$key]);
1025
							break;
1026
						}
1027
					}
1028
				}
1029
			}
1030
			$static_output .= gettext("done.") . "\n";
1031
			update_output_window($static_output);
1032
		}
1033
		/* remove menu items */
1034
		if(is_array($pkg_config['menu'])) {
1035
			$static_output .= gettext("Menu items... ");
1036
			update_output_window($static_output);
1037
			if (is_array($pkg_config['menu']) && is_array($menus)) {
1038
				foreach($pkg_config['menu'] as $menu) {
1039
					foreach($menus as $key => $instmenu) {
1040
						if($instmenu['name'] == $menu['name']) {
1041
							unset($menus[$key]);
1042
							break;
1043
						}
1044
					}
1045
				}
1046
			}
1047
			$static_output .= gettext("done.") . "\n";
1048
			update_output_window($static_output);
1049
		}
1050
		/* remove services */
1051
		if(is_array($pkg_config['service'])) {
1052
			$static_output .= gettext("Services... ");
1053
			update_output_window($static_output);
1054
			if (is_array($pkg_config['service']) && is_array($services)) {
1055
				foreach($pkg_config['service'] as $service) {
1056
					foreach($services as $key => $instservice) {
1057
						if($instservice['name'] == $service['name']) {
1058
							if($g['booting'] != true)
1059
								stop_service($service['name']);
1060
							if($service['rcfile']) {
1061
								$prefix = RCFILEPREFIX;
1062
								if (!empty($service['prefix']))
1063
									$prefix = $service['prefix'];
1064
								if (file_exists("{$prefix}{$service['rcfile']}"))
1065
									@unlink("{$prefix}{$service['rcfile']}");
1066
							}
1067
							unset($services[$key]);
1068
						}
1069
					}
1070
				}
1071
			}
1072
			$static_output .= gettext("done.") . "\n";
1073
			update_output_window($static_output);
1074
		}
1075
		/*
1076
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
1077
		 * 	Same is done during installation.
1078
		 */
1079
		write_config("Intermediate config write during package removal for {$pkg}.");
1080

    
1081
		/*
1082
		 * If a require exists, include it.  this will
1083
		 * show us where an error exists in a package
1084
		 * instead of making us blindly guess
1085
		 */
1086
		$missing_include = false;
1087
		if($pkg_config['include_file'] <> "") {
1088
			$static_output .= gettext("Loading package instructions...") . "\n";
1089
			update_output_window($static_output);
1090
			pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
1091
			if (file_exists($pkg_config['include_file']))
1092
				require_once($pkg_config['include_file']);
1093
			else {
1094
				$missing_include = true;
1095
				update_output_window($static_output);
1096
				$static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n";
1097
			}
1098
		}
1099
		/* ermal
1100
		 * NOTE: It is not possible to handle parse errors on eval.
1101
		 * So we prevent it from being run at all to not interrupt all the other code.
1102
		 */
1103
		if ($missing_include == false) {
1104
			/* evalate this package's global functions and pre deinstall commands */
1105
			if($pkg_config['custom_php_global_functions'] <> "")
1106
				eval_once($pkg_config['custom_php_global_functions']);
1107
			if($pkg_config['custom_php_pre_deinstall_command'] <> "")
1108
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
1109
		}
1110
		/* system files */
1111
		if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) {
1112
			$static_output .= gettext("System files... ");
1113
			update_output_window($static_output);
1114
			foreach($pkg_config['modify_system']['item'] as $ms)
1115
				if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']);
1116

    
1117
			$static_output .= gettext("done.") . "\n";
1118
			update_output_window($static_output);
1119
		}
1120
		/* deinstall commands */
1121
		if($pkg_config['custom_php_deinstall_command'] <> "") {
1122
			$static_output .= gettext("Deinstall commands... ");
1123
			update_output_window($static_output);
1124
			if ($missing_include == false) {
1125
				eval_once($pkg_config['custom_php_deinstall_command']);
1126
				$static_output .= gettext("done.") . "\n";
1127
			} else
1128
				$static_output .= "\nNot executing custom deinstall hook because an include is missing.\n";
1129
			update_output_window($static_output);
1130
		}
1131
		if($pkg_config['include_file'] <> "") {
1132
			$static_output .= gettext("Removing package instructions...");
1133
			update_output_window($static_output);
1134
			pkg_debug(sprintf(gettext("Remove '%s'"), $pkg_config['include_file']) . "\n");
1135
			unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']);
1136
			$static_output .= gettext("done.") . "\n";
1137
			update_output_window($static_output);
1138
		}
1139
		/* remove all additional files */
1140
		if(is_array($pkg_config['additional_files_needed'])) {
1141
			$static_output .= gettext("Auxiliary files... ");
1142
			update_output_window($static_output);
1143
			foreach($pkg_config['additional_files_needed'] as $afn) {
1144
				$filename = get_filename_from_url($afn['item'][0]);
1145
				if($afn['prefix'] <> "")
1146
					$prefix = $afn['prefix'];
1147
				else
1148
					$prefix = "/usr/local/pkg/";
1149
				unlink_if_exists($prefix . $filename);
1150
			}
1151
			$static_output .= gettext("done.") . "\n";
1152
			update_output_window($static_output);
1153
		}
1154
		/* package XML file */
1155
		$static_output .= gettext("Package XML... ");
1156
		update_output_window($static_output);
1157
		unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']);
1158
		$static_output .= gettext("done.") . "\n";
1159
		update_output_window($static_output);
1160
	}
1161
	/* syslog */
1162
	if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") {
1163
		$static_output .= "Syslog entries... ";
1164
		update_output_window($static_output);
1165
		remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']);
1166
		system_syslogd_start();
1167
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1168
		$static_output .= "done.\n";
1169
		update_output_window($static_output);
1170
	}
1171
	
1172
	conf_mount_ro();
1173
	/* remove config.xml entries */
1174
	$static_output .= gettext("Configuration... ");
1175
	update_output_window($static_output);
1176
	unset($config['installedpackages']['package'][$pkgid]);
1177
	$static_output .= gettext("done.") . "\n";
1178
	update_output_window($static_output);
1179
	write_config("Removed {$pkg} package.\n");
1180
}
1181

    
1182
function expand_to_bytes($size) {
1183
	$conv = array(
1184
			"G" =>	"3",
1185
			"M" =>  "2",
1186
			"K" =>  "1",
1187
			"B" =>  "0"
1188
		);
1189
	$suffix = substr($size, -1);
1190
	if(!in_array($suffix, array_keys($conv))) return $size;
1191
	$size = substr($size, 0, -1);
1192
	for($i = 0; $i < $conv[$suffix]; $i++) {
1193
		$size *= 1024;
1194
	}
1195
	return $size;
1196
}
1197

    
1198
function get_pkg_db() {
1199
	global $g;
1200
	return return_dir_as_array($g['vardb_path'] . '/pkg');
1201
}
1202

    
1203
function walk_depend($depend, $pkgdb = "", $alreadyseen = "") {
1204
	if(!$pkgdb)
1205
		$pkgdb = get_pkg_db();
1206
	if(!is_array($alreadyseen))
1207
		$alreadyseen = array();
1208
	if (!is_array($depend))
1209
		$depend = array();
1210
	foreach($depend as $adepend) {
1211
		$pkgname = reverse_strrchr($adepend['name'], '.');
1212
		if(in_array($pkgname, $alreadyseen)) {
1213
			continue;
1214
		} elseif(!in_array($pkgname, $pkgdb)) {
1215
			$size += expand_to_bytes($adepend['size']);
1216
			$alreadyseen[] = $pkgname;
1217
			if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen);
1218
		}
1219
	}
1220
	return $size;
1221
}
1222

    
1223
function get_package_install_size($pkg = 'all', $pkg_info = "") {
1224
	global $config, $g;
1225
	if((!is_array($pkg)) and ($pkg != 'all'))
1226
		$pkg = array($pkg);
1227
	$pkgdb = get_pkg_db();
1228
	if(!$pkg_info)
1229
		$pkg_info = get_pkg_sizes($pkg);
1230
	foreach($pkg as $apkg) {
1231
		if(!$pkg_info[$apkg])
1232
			continue;
1233
		$toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb));
1234
	}
1235
	return $toreturn;
1236
}
1237

    
1238
function squash_from_bytes($size, $round = "") {
1239
	$conv = array(1 => "B", "K", "M", "G");
1240
	foreach($conv as $div => $suffix) {
1241
		$sizeorig = $size;
1242
		if(($size /= 1024) < 1) {
1243
			if($round) {
1244
				$sizeorig = round($sizeorig, $round);
1245
			}
1246
			return $sizeorig . $suffix;
1247
		}
1248
	}
1249
	return;
1250
}
1251

    
1252
function pkg_reinstall_all() {
1253
	global $g, $config;
1254

    
1255
	@unlink('/conf/needs_package_sync');
1256
	if (is_array($config['installedpackages']['package'])) {
1257
		echo gettext("One moment please, reinstalling packages...\n");
1258
		echo gettext(" >>> Trying to fetch package info...");
1259
		log_error(gettext("Attempting to reinstall all packages"));
1260
		$pkg_info = get_pkg_info();
1261
		if ($pkg_info) {
1262
			echo " Done.\n";
1263
		} else {
1264
			$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
1265
			$error = sprintf(gettext(' >>> Unable to communicate with %1$s. Please verify DNS and interface configuration, and that %2$s has functional Internet connectivity.'), $xmlrpc_base_url, $g['product_name']);
1266
			echo "\n{$error}\n";
1267
			log_error(gettext("Cannot reinstall packages: ") . $error);
1268
			return;
1269
		}
1270
		$todo = array();
1271
		$all_names = array();
1272
		foreach($config['installedpackages']['package'] as $package) {
1273
			$todo[] = array('name' => $package['name'], 'version' => $package['version']);
1274
			$all_names[] = $package['name'];
1275
		}
1276
		$package_name_list = gettext("List of packages to reinstall: ") . implode(", ", $all_names);
1277
		echo " >>> {$package_name_list}\n";
1278
		log_error($package_name_list);
1279

    
1280
		foreach($todo as $pkgtodo) {
1281
			$static_output = "";
1282
			if($pkgtodo['name']) {
1283
				log_error(gettext("Uninstalling package") . " {$pkgtodo['name']}");
1284
				uninstall_package($pkgtodo['name']);
1285
				log_error(gettext("Finished uninstalling package") . " {$pkgtodo['name']}");
1286
				log_error(gettext("Reinstalling package") . " {$pkgtodo['name']}");
1287
				install_package($pkgtodo['name']);
1288
				log_error(gettext("Finished installing package") . " {$pkgtodo['name']}");
1289
			}
1290
		}
1291
		log_error(gettext("Finished reinstalling all packages."));
1292
	} else
1293
		echo "No packages are installed.";
1294
}
1295

    
1296
function stop_packages() {
1297
	require_once("config.inc");
1298
	require_once("functions.inc");
1299
	require_once("filter.inc");
1300
	require_once("shaper.inc");
1301
	require_once("captiveportal.inc");
1302
	require_once("pkg-utils.inc");
1303
	require_once("pfsense-utils.inc");
1304
	require_once("service-utils.inc");
1305

    
1306
	global $config, $g;
1307

    
1308
	log_error("Stopping all packages.");
1309

    
1310
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1311
	if (!$rcfiles)
1312
		$rcfiles = array();
1313
	else {
1314
		$rcfiles = array_flip($rcfiles);
1315
		if (!$rcfiles)
1316
			$rcfiles = array();
1317
	}
1318

    
1319
	if (is_array($config['installedpackages']['package'])) {
1320
		foreach($config['installedpackages']['package'] as $package) {
1321
			echo " Stopping package {$package['name']}...";
1322
			$internal_name = get_pkg_internal_name($package);
1323
			stop_service($internal_name);
1324
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1325
			echo "done.\n";
1326
		}
1327
	}
1328

    
1329
	foreach ($rcfiles as $rcfile => $number) {
1330
		$shell = @popen("/bin/sh", "w");
1331
		if ($shell) {
1332
			echo " Stopping {$rcfile}...";
1333
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1334
				if ($shell)
1335
					pclose($shell);
1336
				$shell = @popen("/bin/sh", "w");
1337
			}
1338
			echo "done.\n";
1339
			pclose($shell);
1340
		}
1341
	}
1342
}
1343

    
1344
function package_skip_tests($index,$requested_version){
1345
	global $config, $g;
1346

    
1347
	/* Get pfsense version*/
1348
	$version = rtrim(file_get_contents("/etc/version"));
1349
	
1350
	if($g['platform'] == "nanobsd")
1351
		if($index['noembedded']) 
1352
			return true;
1353
						
1354
	/* If we are on not on HEAD, and the package wants it, skip */
1355
	if ($version <> "HEAD" && $index['required_version'] == "HEAD" && $requested_version <> "other")
1356
		return true;
1357
							
1358
	/* If there is no required version, and the requested package version is not 'none', then skip */
1359
	if (empty($index['required_version']) && $requested_version <> "none")
1360
		return true;
1361
							
1362
	/* If the requested version is not 'other', and the required version is newer than what we have, skip. */
1363
	if($requested_version <> "other" && (pfs_version_compare("", $version, $index['required_version']) < 0))
1364
		return true;
1365
							
1366
	/* If the requestion version is 'other' and we are on the version requested, skip. */
1367
	if($requested_version == "other" && (pfs_version_compare("", $version, $index['required_version']) == 0))
1368
		return true;
1369
							
1370
	/* Package is only for an older version, lets skip */
1371
	if($index['maximum_version'] && (pfs_version_compare("", $version, $index['maximum_version']) > 0))
1372
		return true;
1373
		
1374
	/* Do not skip package list */	
1375
	return false;
1376
}
1377

    
1378
function get_pkg_interfaces_select_source($include_localhost=false) {
1379
	$interfaces = get_configured_interface_with_descr();
1380
	$ssifs = array();
1381
	foreach ($interfaces as $iface => $ifacename) {
1382
		$tmp["name"]  = $ifacename;
1383
		$tmp["value"] = $iface;
1384
		$ssifs[] = $tmp;
1385
	}
1386
	if ($include_localhost) {
1387
		$tmp["name"]  = "Localhost";
1388
		$tmp["value"] = "lo0";
1389
		$ssifs[] = $tmp;
1390
	}
1391
	return $ssifs;
1392
}
1393
?>
(40-40/67)