Projet

Général

Profil

Télécharger (53,8 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / pkg-utils.inc @ bfe9c9e7

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

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

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

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

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

    
68
		if (!$debug)
69
			return;
70

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

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

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

    
90
/****f* pkg-utils/remove_package
91
 * NAME
92
 *   remove_package - Removes package from FreeBSD if it exists
93
 * INPUTS
94
 *   $packagestring	- name/string to check for
95
 * RESULT
96
 *   none
97
 * NOTES
98
 *   
99
 ******/
100
function remove_freebsd_package($packagestring) {
101
	// The packagestring passed in must be the full PBI package name, 
102
	// as displayed by the pbi_info utility. e.g. "package-1.2.3_4-i386" 
103
	// It must NOT have ".pbi" on the end.
104
	$links = get_pbi_binaries(escapeshellarg($packagestring));
105
	foreach($links as $link)
106
		if (is_link("/usr/local/{$link['link_name']}"))
107
			@unlink("/usr/local/{$link['link_name']}");
108
	exec("/usr/local/sbin/pbi_delete " . escapeshellarg($packagestring) . " 2>>/tmp/pbi_delete_errors.txt");
109
}
110

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

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

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

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

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

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

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

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

    
209
	return array();
210
}
211

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

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

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

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

    
227
	conf_mount_rw();
228

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
518
		$pkgaddout = "";
519

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
598
	return $result;
599
}
600

    
601

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

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

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

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

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

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

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

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

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

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

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

    
772
		pkg_fetch_additional_files($pkg, $pkg_info);
773

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

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

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

    
911
	return true;
912
}
913

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

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

    
931
	if(!$pkg) 
932
		return;
933

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

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

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

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

    
948
	return;
949
}
950

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

    
954
	conf_mount_rw();
955

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

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

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

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

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

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

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

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

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

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

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

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

    
1270
	global $config, $g;
1271

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1434

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

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

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

    
1474

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

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

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

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

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

    
1544
?>
(41-41/68)