Project

General

Profile

Download (31.7 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * pkg-utils.inc
4
 */
5
/* ====================================================================
6
 *	Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
7
 *	Copyright (c)  2005-2006 Colin Smith (ethethlay@gmail.com)
8
 *
9
 *	Redistribution and use in source and binary forms, with or without modification,
10
 *	are permitted provided that the following conditions are met:
11
 *
12
 *	1. Redistributions of source code must retain the above copyright notice,
13
 *		this list of conditions and the following disclaimer.
14
 *
15
 *	2. Redistributions in binary form must reproduce the above copyright
16
 *		notice, this list of conditions and the following disclaimer in
17
 *		the documentation and/or other materials provided with the
18
 *		distribution.
19
 *
20
 *	3. All advertising materials mentioning features or use of this software
21
 *		must display the following acknowledgment:
22
 *		"This product includes software developed by the pfSense Project
23
 *		 for use in the pfSense software distribution. (http://www.pfsense.org/).
24
 *
25
 *	4. The names "pfSense" and "pfSense Project" must not be used to
26
 *		 endorse or promote products derived from this software without
27
 *		 prior written permission. For written permission, please contact
28
 *		 coreteam@pfsense.org.
29
 *
30
 *	5. Products derived from this software may not be called "pfSense"
31
 *		nor may "pfSense" appear in their names without prior written
32
 *		permission of the Electric Sheep Fencing, LLC.
33
 *
34
 *	6. Redistributions of any form whatsoever must retain the following
35
 *		acknowledgment:
36
 *
37
 *	"This product includes software developed by the pfSense Project
38
 *	for use in the pfSense software distribution (http://www.pfsense.org/).
39
 *
40
 *	THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
41
 *	EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
 *	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43
 *	PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
44
 *	ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45
 *	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46
 *	NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47
 *	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48
 *	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49
 *	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50
 *	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51
 *	OF THE POSSIBILITY OF SUCH DAMAGE.
52
 *
53
 *	====================================================================
54
 *
55
 */
56
/*
57
	pfSense_MODULE: pkg
58
*/
59

    
60
require_once("globals.inc");
61
require_once("service-utils.inc");
62

    
63
if (file_exists("/cf/conf/use_xmlreader")) {
64
	require_once("xmlreader.inc");
65
} else {
66
	require_once("xmlparse.inc");
67
}
68

    
69
require_once("pfsense-utils.inc");
70

    
71
if (!function_exists("pkg_debug")) {
72
	/* set up logging if needed */
73
	function pkg_debug($msg) {
74
		global $g, $debug, $fd_log;
75

    
76
		if (!$debug) {
77
			return;
78
		}
79

    
80
		if (!$fd_log) {
81
			if (!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_debug.log", "w")) {
82
				update_status(gettext("Warning, could not open log for writing.") . "\n");
83
			}
84
		}
85
		@fwrite($fd_log, $msg);
86
	}
87
}
88

    
89
/* Remove pkg_prefix from package name if it's present */
90
function pkg_remove_prefix(&$pkg_name) {
91
	global $g;
92

    
93
	if (substr($pkg_name, 0, strlen($g['pkg_prefix'])) == $g['pkg_prefix']) {
94
		$pkg_name = substr($pkg_name, strlen($g['pkg_prefix']));
95
	}
96
}
97

    
98
/* Execute pkg update when it's necessary */
99
function pkg_update($force = false) {
100
	global $g;
101

    
102
	$now = strftime('%s');
103
	if (!$force) {
104
		$last_update_file="{$g['varrun_path']}/{$g['product_name']}-upgrade-last-update";
105

    
106
		if (file_exists($last_update_file)) {
107
			$last_update = rtrim(file_get_contents($last_update_file), "\n");
108
			if (!is_numericint($last_update)) {
109
				$last_update = 0;
110
			}
111
		}
112

    
113
		if ($last_update > 0) {
114
			if ($now > $last_update && ($now - $last_update) <= (60 * 60)) {
115
				return true;
116
			}
117
		}
118
	}
119

    
120
	$rc = pkg_call("update");
121

    
122
	if ($rc) {
123
		file_put_contents($last_update_file, $now . "\n");
124
	}
125

    
126
	return $rc;
127
}
128

    
129
/* Execute a pkg call */
130
function pkg_call($params, $mute = false) {
131
	global $g, $config;
132

    
133
	if (empty($params)) {
134
		return false;
135
	}
136

    
137
	$user_agent = $g['product_name'] . '/' . $g['product_version'];
138
	if (!isset($config['system']['host_uuid'])) {
139
		$user_agent .= ' : ' . get_single_sysctl('kern.hostuuid');
140
	}
141

    
142
	$env = array(
143
		"HTTP_USER_AGENT" => $user_agent,
144
		"ASSUME_ALWAYS_YES" => "true",
145
		"REPO_AUTOUPDATE" => "false"
146
	);
147

    
148
	$descriptorspec = array(
149
		1 => array("pipe", "w"), /* stdout */
150
		2 => array("pipe", "w")	 /* stderr */
151
	);
152

    
153
	pkg_debug("pkg_call(): {$params}\n");
154
	$process = proc_open("/usr/sbin/pkg {$params}", $descriptorspec, $pipes, '/', $env);
155

    
156
	if (!is_resource($process)) {
157
		return false;
158
	}
159

    
160
	stream_set_blocking($pipes[1], 0);
161
	stream_set_blocking($pipes[2], 0);
162

    
163
	/* XXX: should be a tunnable? */
164
	$timeout = 300; // seconds
165
	$error_log = '';
166
	$started = time();
167
	$maxwaittime = 10; // Number of seconds to wait for a response fromteh pacakge we are calling
168

    
169
	do {
170
		$write = array();
171
		$read = array($pipes[1], $pipes[2]);
172
		$except = array();
173

    
174
		$stream = stream_select($read, $write, $except, null, $timeout);
175
		if ($stream !== FALSE && $stream > 0) {
176
			foreach ($read as $pipe) {
177
				$content = stream_get_contents($pipe);
178
				if ($content == '') {
179
					continue;
180
				}
181
				if ($pipe === $pipes[1]) {
182
					if (!$mute) {
183
						update_status($content);
184
					}
185
					flush();
186
				} else if ($pipe === $pipes[2]) {
187
					$error_log .= $content;
188
				}
189
			}
190
		}
191

    
192
		$status = proc_get_status($process);
193

    
194
		$now = time();
195

    
196
		if(($now - $started) >= $maxwaittime) {
197
			$rc = -1;
198
			proc_terminate($process);
199
			break;
200
		}
201

    
202
	} while ($status['running']);
203

    
204
	fclose($pipes[1]);
205
	fclose($pipes[2]);
206
	proc_close($process);
207

    
208
	if(!isset($rc)) {
209
		$rc = $status['exitcode'];
210
	}
211

    
212
	pkg_debug("pkg_call(): rc = {$rc}\n");
213
	if ($rc == 0) {
214
		return true;
215
	}
216

    
217
	pkg_debug("pkg_call(): error_log\n{$error_log}\n");
218
	if (!$mute) {
219
		update_status("\n\n" .  sprintf(gettext(
220
		    "ERROR!!! An error occurred on pkg execution (rc = %d) with parameters '%s':"),
221
		    $rc, $params) . "\n" . $error_log . "\n");
222
	}
223

    
224
	return false;
225
}
226

    
227
/* Execute pkg with $params, fill stdout and stderr and return pkg rc */
228
function pkg_exec($params, &$stdout, &$stderr) {
229
	global $g, $config;
230

    
231
	if (empty($params)) {
232
		return -1;
233
	}
234

    
235
	$user_agent = $g['product_name'] . '/' . $g['product_version'];
236
	if (!isset($config['system']['host_uuid'])) {
237
		$user_agent .= ' : ' . get_single_sysctl('kern.hostuuid');
238
	}
239

    
240
	$env = array(
241
		"HTTP_USER_AGENT" => $user_agent,
242
		"ASSUME_ALWAYS_YES" => "true",
243
		"REPO_AUTOUPDATE" => "false"
244
	);
245

    
246
	$descriptorspec = array(
247
		1 => array("pipe", "w"), /* stdout */
248
		2 => array("pipe", "w")	 /* stderr */
249
	);
250

    
251
	pkg_debug("pkg_exec(): {$params}\n");
252
	$process = proc_open("/usr/sbin/pkg {$params}", $descriptorspec, $pipes, '/', $env);
253

    
254
	if (!is_resource($process)) {
255
		return -1;
256
	}
257

    
258
	$stdout = '';
259
	while (($l = fgets($pipes[1])) !== FALSE) {
260
		$stdout .= $l;
261
	}
262
	fclose($pipes[1]);
263

    
264
	$stderr = '';
265
	while (($l = fgets($pipes[2])) !== FALSE) {
266
		$stderr .= $l;
267
	}
268
	fclose($pipes[2]);
269

    
270
	return proc_close($process);
271
}
272

    
273
/* Compare 2 pkg versions and return:
274
 * '=' - versions are the same
275
 * '>' - $v1 > $v2
276
 * '<' - $v1 < $v2
277
 * '?' - Error
278
 */
279
function pkg_version_compare($v1, $v2) {
280
	if (empty($v1) || empty($v2)) {
281
		return '?';
282
	}
283

    
284
	$rc = pkg_exec("version -t '{$v1}' '{$v2}'", $stdout, $stderr);
285

    
286
	if ($rc != 0) {
287
		return '?';
288
	}
289

    
290
	return str_replace("\n", "", $stdout);
291
}
292

    
293
/* Check if package is installed */
294
function is_pkg_installed($pkg_name) {
295
	global $g;
296

    
297
	if (empty($pkg_name)) {
298
		return false;
299
	}
300

    
301
	return pkg_call("info -e " . $pkg_name, true);
302
}
303

    
304
/* Install package, $pkg_name should not contain prefix */
305
function pkg_install($pkg_name, $force = false) {
306
	global $g;
307
	$result = false;
308

    
309
	$shortname = $pkg_name;
310
	pkg_remove_prefix($shortname);
311

    
312
	$pkg_force = "";
313
	if ($force) {
314
		$pkg_force = "-f ";
315
	}
316

    
317
	pkg_debug("Installing package {$shortname}\n");
318
	if ($force || !is_pkg_installed($pkg_name)) {
319
		$result = pkg_call("install -y " . $pkg_force . $pkg_name);
320
		/* Cleanup cacke to free disk space */
321
		pkg_call("clean -y");
322
	}
323

    
324
	return $result;
325
}
326

    
327
/* Delete package from FreeBSD, $pkg_name should not contain prefix */
328
function pkg_delete($pkg_name) {
329
	global $g;
330

    
331
	$shortname = $pkg_name;
332
	pkg_remove_prefix($shortname);
333

    
334
	pkg_debug("Removing package {$shortname}\n");
335
	if (is_pkg_installed($pkg_name)) {
336
		pkg_call("delete -y " . $pkg_name);
337
		/* Cleanup unecessary dependencies */
338
		pkg_call("autoremove -y");
339
	}
340
}
341

    
342
/* Check if package is present in config.xml */
343
function is_package_installed($package_name) {
344
	return (get_package_id($package_name) != -1);
345
}
346

    
347
/* Find package array index */
348
function get_package_id($package_name) {
349
	global $config;
350

    
351
	if (!is_array($config['installedpackages']['package'])) {
352
		return -1;
353
	}
354

    
355
	foreach ($config['installedpackages']['package'] as $idx => $pkg) {
356
		if ($pkg['name'] == $package_name ||
357
			get_package_internal_name($pkg) == $package_name) {
358
			return $idx;
359
		}
360
	}
361

    
362
	return -1;
363
}
364

    
365
/* Keep backward compatibility since snort/suricata use this function */
366
function get_pkg_id($package_name) {
367
	return get_package_id($package_name);
368
}
369

    
370
/* Return internal_name when it's defined, otherwise, returns name */
371
function get_package_internal_name($package_data) {
372
	if (isset($package_data['internal_name']) && ($package_data['internal_name'] != "")) {
373
		/* e.g. name is Ipguard-dev, internal name is ipguard */
374
		return $package_data['internal_name'];
375
	} else {
376
		return $package_data['name'];
377
	}
378
}
379

    
380
// Get information about packages.
381
function get_pkg_info($pkgs = 'all', $info = 'all') {
382
	global $g, $input_errors;
383

    
384
	$out = '';
385
	$err = '';
386

    
387
	unset($pkg_filter);
388
	if (is_array($pkgs)) {
389
		$pkg_filter = $pkgs;
390
		$pkgs = 'all';
391
	}
392

    
393
	if ($pkgs == 'all') {
394
		$pkgs = $g['pkg_prefix'];
395
	}
396

    
397
	/* Make sure repo metadata is up2date */
398
	update_status("\n" .
399
	    gettext("Updating package repository metadada...") . "\n");
400

    
401
	if (!pkg_update()) {
402
		$input_errors[] = gettext(
403
		    "ERROR: An error occurred when updating packages repository. Aborting...")
404
		    . "\n";
405
		update_status("\n" . gettext(
406
		    "ERROR: An error occurred when updating packages repository. Aborting...")
407
		    . "\n");
408
		return array();
409
	}
410

    
411
	$rc = pkg_exec("search -U --raw-format json-compact " . $pkgs, $out, $err);
412

    
413
	if ($rc != 0) {
414
		update_status("\n" . gettext(
415
		    "ERROR: Error trying to get packages list. Aborting...")
416
		    . "\n");
417
		update_status($err);
418
		$input_errors[] =  gettext("ERROR: Error trying to get packages list. Aborting...") . "\n";
419
		$input_errors[] =  $err;
420
		return array();
421
	}
422

    
423
	$result = array();
424
	$pkgs_info = explode("\n", $out);
425
	foreach ($pkgs_info as $pkg_info_json) {
426
		$pkg_info = json_decode($pkg_info_json, true);
427
		if (!isset($pkg_info['name'])) {
428
			continue;
429
		}
430

    
431
		if (isset($pkg_filter) && !in_array($pkg_info['name'], $pkg_filter)) {
432
			continue;
433
		}
434

    
435
		$pkg_info['shortname'] = $pkg_info['name'];
436
		pkg_remove_prefix($pkg_info['shortname']);
437

    
438
		/* XXX: Add it to globals.inc? */
439
		$pkg_info['changeloglink'] =
440
		    "https://github.com/pfsense/FreeBSD-ports/commits/devel/" .
441
		    $pkg_info['categories'][0] . '/' . $pkg_info['name'];
442

    
443
		if (is_pkg_installed($pkg_info['name'])) {
444
			$pkg_info['installed'] = true;
445

    
446
			$rc = pkg_exec("query %v {$pkg_info['name']}", $out, $err);
447

    
448
			if ($rc != 0) {
449
				update_status("\n" . gettext(
450
				    "ERROR: Error trying to get package version. Aborting...")
451
				    . "\n");
452
				update_status($err);
453
				$input_errors[] =  gettext("ERROR: Error trying to get package version. Aborting...") . "\n";
454
				$input_errors[] =  $err;
455
				return array();
456
			}
457

    
458
			$pkg_info['installed_version'] = str_replace("\n", "", $out);
459
		} else if (is_package_installed($pkg_info['shortname'])) {
460
			$pkg_info['broken'] = true;
461
		}
462

    
463
		$pkg_info['desc'] = preg_replace('/\n+WWW:.*$/', '', $pkg_info['desc']);
464

    
465
		$result[] = $pkg_info;
466
		unset($pkg_info);
467
	}
468

    
469
	/* Sort result alphabetically */
470
	usort($result, function($a, $b) {
471
		return(strcasecmp ($a['name'], $b['name']));
472
	});
473

    
474
	return $result;
475
}
476

    
477
/*
478
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
479
 * This function may also print output to the terminal indicating progress.
480
 */
481
function resync_all_package_configs($show_message = false) {
482
	global $config, $pkg_interface, $g;
483

    
484
	log_error(gettext("Resyncing configuration for all packages."));
485

    
486
	if (!is_array($config['installedpackages']['package'])) {
487
		return;
488
	}
489

    
490
	if ($show_message == true) {
491
		echo "Syncing packages:";
492
	}
493

    
494
	conf_mount_rw();
495

    
496
	foreach ($config['installedpackages']['package'] as $idx => $package) {
497
		if (empty($package['name'])) {
498
			continue;
499
		}
500
		if ($show_message == true) {
501
			echo " " . $package['name'];
502
		}
503
		if (platform_booting() != true) {
504
			stop_service(get_package_internal_name($package));
505
		}
506
		sync_package($package['name']);
507
		update_status(gettext("Syncing packages...") . "\n");
508
	}
509

    
510
	if ($show_message == true) {
511
		echo " done.\n";
512
	}
513

    
514
	@unlink("/conf/needs_package_sync");
515
	conf_mount_ro();
516
}
517

    
518
function uninstall_package($package_name) {
519
	global $config;
520

    
521
	$internal_name = $package_name;
522
	$id = get_package_id($package_name);
523
	if ($id >= 0) {
524
		$internal_name = get_package_internal_name($config['installedpackages']['package'][$id]);
525
		stop_service($internal_name);
526
	}
527
	$pkg_name = $g['pkg_prefix'] . $internal_name;
528

    
529
	if (is_pkg_installed($pkg_name)) {
530
		update_status(gettext("Removing package...") . "\n");
531
		pkg_delete($pkg_name);
532
	} else {
533
		delete_package_xml($package_name);
534
	}
535

    
536
	update_status(gettext("done.") . "\n");
537
}
538

    
539
/* Run <custom_php_resync_config_command> */
540
function sync_package($package_name) {
541
	global $config, $builder_package_install;
542

    
543
	// If this code is being called by pfspkg_installer
544
	// which the builder system uses then return (ignore).
545
	if ($builder_package_install) {
546
		return;
547
	}
548

    
549
	if (empty($config['installedpackages']['package'])) {
550
		return;
551
	}
552

    
553
	if (($pkg_id = get_package_id($package_name)) == -1) {
554
		return; // This package doesn't really exist - exit the function.
555
	}
556

    
557
	if (!is_array($config['installedpackages']['package'][$pkg_id])) {
558
		return;	 // No package belongs to the pkg_id passed to this function.
559
	}
560

    
561
	$package =& $config['installedpackages']['package'][$pkg_id];
562
	if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
563
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
564
		delete_package_xml($package['name']);
565
		return;
566
	}
567

    
568
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
569
	if (isset($pkg_config['nosync'])) {
570
		return;
571
	}
572

    
573
	/* Bring in package include files */
574
	if (!empty($pkg_config['include_file'])) {
575
		$include_file = $pkg_config['include_file'];
576
		if (file_exists($include_file)) {
577
			require_once($include_file);
578
		} else {
579
			log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!");
580
			uninstall_package($package['name']);
581
			if (install_package($package['name']) != 0) {
582
				log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!");
583
				return;
584
			}
585
			if (file_exists($include_file)) {
586
				require_once($include_file);
587
			} else {
588
				return;
589
			}
590
		}
591
	}
592

    
593
	if (!empty($pkg_config['custom_php_global_functions'])) {
594
		eval($pkg_config['custom_php_global_functions']);
595
	}
596
	if (!empty($pkg_config['custom_php_resync_config_command'])) {
597
		eval($pkg_config['custom_php_resync_config_command']);
598
	}
599
}
600

    
601
/* Read info.xml installed by package and return an array */
602
function read_package_config($package_name) {
603
	global $g;
604

    
605
	$pkg_info_xml = '/usr/local/share/' . $g['pkg_prefix'] . $package_name . '/info.xml';
606

    
607
	if (!file_exists($pkg_info_xml)) {
608
		return false;
609
	}
610

    
611
	$pkg_info = parse_xml_config_pkg($pkg_info_xml, 'pfsensepkgs');
612

    
613
	if (empty($pkg_info)) {
614
		return false;
615
	}
616

    
617
	/* it always returns an array with 1 item */
618
	return $pkg_info['package'][0];
619
}
620

    
621
/* Read package configurationfile and return an array */
622
function read_package_configurationfile($package_name) {
623
	global $config, $g;
624

    
625
	$pkg_config = array();
626
	$id = get_package_id($package_name);
627

    
628
	if ($id < 0 || !isset($config['installedpackages']['package'][$id]['configurationfile'])) {
629
		return $pkg_config;
630
	}
631

    
632
	$pkg_configurationfile = $config['installedpackages']['package'][$id]['configurationfile'];
633

    
634
	if (empty($pkg_configurationfile) || !file_exists('/usr/local/pkg/' . $pkg_configurationfile)) {
635
		return $pkg_config;
636
	}
637

    
638
	$pkg_config = parse_xml_config_pkg('/usr/local/pkg/' . $pkg_configurationfile, "packagegui");
639

    
640
	return $pkg_config;
641
}
642

    
643
function get_after_install_info($package_name) {
644
	$pkg_config = read_package_config($package_name);
645

    
646
	if (isset($pkg_config['after_install_info'])) {
647
		return $pkg_config['after_install_info'];
648
	}
649

    
650
	return '';
651
}
652

    
653
function eval_once($toeval) {
654
	global $evaled;
655
	if (!$evaled) {
656
		$evaled = array();
657
	}
658
	$evalmd5 = md5($toeval);
659
	if (!in_array($evalmd5, $evaled)) {
660
		@eval($toeval);
661
		$evaled[] = $evalmd5;
662
	}
663
	return;
664
}
665

    
666
function install_package_xml($package_name) {
667
	global $g, $config, $pkg_interface;
668

    
669
	if (($pkg_info = read_package_config($package_name)) == false) {
670
		return false;
671
	}
672

    
673
	/* safe side. Write config below will send to ro again. */
674
	conf_mount_rw();
675

    
676
	pkg_debug(gettext("Beginning package installation.") . "\n");
677
	log_error(sprintf(gettext('Beginning package installation for %s .'), $pkg_info['name']));
678

    
679
	/* add package information to config.xml */
680
	$pkgid = get_package_id($pkg_info['name']);
681
	update_status(gettext("Saving updated package information...") . "\n");
682
	if ($pkgid == -1) {
683
		$config['installedpackages']['package'][] = $pkg_info;
684
		$changedesc = sprintf(gettext("Installed %s package."), $pkg_info['name']);
685
		$to_output = gettext("done.") . "\n";
686
	} else {
687
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
688
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
689
		$to_output = gettext("overwrite!") . "\n";
690
	}
691
	unlink_if_exists('/conf/needs_package_sync');
692
	write_config("Intermediate config write during package install for {$pkg_info['name']}.");
693
	conf_mount_ro();
694
	update_status($to_output);
695

    
696
	if (($pkgid = get_package_id($package_name)) == -1) {
697
		update_status(sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $package_name, "\n\n"));
698

    
699
		uninstall_package($package_name);
700
		write_config($changedesc);
701
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
702
		update_status(gettext("Failed to install package.") . "\n");
703
		return false;
704
	}
705

    
706
	$configfile = substr(strrchr($pkg_info['config_file'], '/'), 1);
707
	if (file_exists("/usr/local/pkg/" . $configfile)) {
708
		update_status(gettext("Loading package configuration... "));
709
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui");
710
		update_status(gettext("done.") . "\n");
711
		update_status(gettext("Configuring package components...") . "\n");
712
		if (!empty($pkg_config['filter_rules_needed'])) {
713
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
714
		}
715
		/* modify system files */
716

    
717
		/* if a require exists, include it.  this will
718
		 * show us where an error exists in a package
719
		 * instead of making us blindly guess
720
		 */
721
		$missing_include = false;
722
		if ($pkg_config['include_file'] <> "") {
723
			update_status(gettext("Loading package instructions...") . "\n");
724
			if (file_exists($pkg_config['include_file'])) {
725
				pkg_debug("require_once('{$pkg_config['include_file']}')\n");
726
				require_once($pkg_config['include_file']);
727
			} else {
728
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
729
				$missing_include = true;
730
				update_status("Include " . basename($pkg_config['include_file']) . " is missing!\n");
731

    
732
				uninstall_package($package_name);
733
				write_config($changedesc);
734
				log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
735
				update_status(gettext("Failed to install package.") . "\n");
736
				return false;
737
			}
738
		}
739

    
740
		/* custom commands */
741
		update_status(gettext("Custom commands...") . "\n");
742
		if ($missing_include == false) {
743
			if ($pkg_config['custom_php_global_functions'] <> "") {
744
				update_status(gettext("Executing custom_php_global_functions()..."));
745
				eval_once($pkg_config['custom_php_global_functions']);
746
				update_status(gettext("done.") . "\n");
747
			}
748
			if ($pkg_config['custom_php_install_command']) {
749
				update_status(gettext("Executing custom_php_install_command()..."));
750
				eval_once($pkg_config['custom_php_install_command']);
751
				update_status(gettext("done.") . "\n");
752
			}
753
			if ($pkg_config['custom_php_resync_config_command'] <> "") {
754
				update_status(gettext("Executing custom_php_resync_config_command()..."));
755
				eval_once($pkg_config['custom_php_resync_config_command']);
756
				update_status(gettext("done.") . "\n");
757
			}
758
		}
759
		/* sidebar items */
760
		if (is_array($pkg_config['menu'])) {
761
			update_status(gettext("Menu items... "));
762
			foreach ($pkg_config['menu'] as $menu) {
763
				if (is_array($config['installedpackages']['menu'])) {
764
					foreach ($config['installedpackages']['menu'] as $amenu) {
765
						if ($amenu['name'] == $menu['name']) {
766
							continue 2;
767
						}
768
					}
769
				} else {
770
					$config['installedpackages']['menu'] = array();
771
				}
772
				$config['installedpackages']['menu'][] = $menu;
773
			}
774
			update_status(gettext("done.") . "\n");
775
		}
776
		/* services */
777
		if (is_array($pkg_config['service'])) {
778
			update_status(gettext("Services... "));
779
			foreach ($pkg_config['service'] as $service) {
780
				if (is_array($config['installedpackages']['service'])) {
781
					foreach ($config['installedpackages']['service'] as $aservice) {
782
						if ($aservice['name'] == $service['name']) {
783
							continue 2;
784
						}
785
					}
786
				} else {
787
					$config['installedpackages']['service'] = array();
788
				}
789
				$config['installedpackages']['service'][] = $service;
790
			}
791
			update_status(gettext("done.") . "\n");
792
		}
793
	} else {
794
		pkg_debug("Unable to find config file\n");
795
		update_status(gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted."));
796
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
797

    
798
		uninstall_package($package_name);
799
		write_config($changedesc);
800
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
801
		update_status(gettext("Failed to install package.") . "\n");
802
		return false;
803
	}
804

    
805
	/* set up package logging streams */
806
	if ($pkg_info['logging']) {
807
		system_syslogd_start();
808
	}
809

    
810
	update_status(gettext("Writing configuration... "));
811
	write_config($changedesc);
812
	log_error(sprintf(gettext("Successfully installed package: %s."), $pkg_info['name']));
813
	update_status(gettext("done.") . "\n");
814
	if ($pkg_info['after_install_info']) {
815
		update_status($pkg_info['after_install_info']);
816
	}
817

    
818
	return true;
819
}
820

    
821
function delete_package_xml($package_name, $when = "post-deinstall") {
822
	global $g, $config, $pkg_interface;
823

    
824
	conf_mount_rw();
825

    
826
	$pkgid = get_package_id($package_name);
827
	if ($pkgid == -1) {
828
		update_status(sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $package_name, "\n\n"));
829
		ob_flush();
830
		sleep(1);
831
		conf_mount_ro();
832
		return;
833
	}
834
	pkg_debug(sprintf(gettext("Removing %s package... "), $package_name));
835
	update_status(sprintf(gettext("Removing %s components..."), $package_name) . "\n");
836
	/* parse package configuration */
837
	$packages = &$config['installedpackages']['package'];
838
	$menus =& $config['installedpackages']['menu'];
839
	$services = &$config['installedpackages']['service'];
840
	$pkg_info =& $packages[$pkgid];
841
	if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
842
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
843
		/* remove menu items */
844
		if (is_array($pkg_config['menu'])) {
845
			update_status(gettext("Menu items... "));
846
			if (is_array($pkg_config['menu']) && is_array($menus)) {
847
				foreach ($pkg_config['menu'] as $menu) {
848
					foreach ($menus as $key => $instmenu) {
849
						if ($instmenu['name'] == $menu['name']) {
850
							unset($menus[$key]);
851
							break;
852
						}
853
					}
854
				}
855
			}
856
			update_status(gettext("done.") . "\n");
857
		}
858
		/* remove services */
859
		if (is_array($pkg_config['service'])) {
860
			update_status(gettext("Services... "));
861
			if (is_array($pkg_config['service']) && is_array($services)) {
862
				foreach ($pkg_config['service'] as $service) {
863
					foreach ($services as $key => $instservice) {
864
						if ($instservice['name'] == $service['name']) {
865
							if (platform_booting() != true) {
866
								stop_service($service['name']);
867
							}
868
							if ($service['rcfile']) {
869
								$prefix = RCFILEPREFIX;
870
								if (!empty($service['prefix'])) {
871
									$prefix = $service['prefix'];
872
								}
873
								if (file_exists("{$prefix}{$service['rcfile']}")) {
874
									@unlink("{$prefix}{$service['rcfile']}");
875
								}
876
							}
877
							unset($services[$key]);
878
						}
879
					}
880
				}
881
			}
882
			update_status(gettext("done.") . "\n");
883
		}
884
		/*
885
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
886
		 *	Same is done during installation.
887
		 */
888
		write_config("Intermediate config write during package removal for {$package_name}.");
889

    
890
		/*
891
		 * If a require exists, include it.	 this will
892
		 * show us where an error exists in a package
893
		 * instead of making us blindly guess
894
		 */
895
		$missing_include = false;
896
		if ($pkg_config['include_file'] <> "") {
897
			update_status(gettext("Loading package instructions...") . "\n");
898
			if (file_exists($pkg_config['include_file'])) {
899
				pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
900
				require_once($pkg_config['include_file']);
901
			} else {
902
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
903
				$missing_include = true;
904
				update_status("Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n");
905
			}
906
		}
907
		/* ermal
908
		 * NOTE: It is not possible to handle parse errors on eval.
909
		 * So we prevent it from being run at all to not interrupt all the other code.
910
		 */
911
		if ($when == "deinstall" && $missing_include == false) {
912
			/* evaluate this package's global functions and pre deinstall commands */
913
			if ($pkg_config['custom_php_global_functions'] <> "") {
914
				eval_once($pkg_config['custom_php_global_functions']);
915
			}
916
			if ($pkg_config['custom_php_pre_deinstall_command'] <> "") {
917
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
918
			}
919
		}
920
		/* deinstall commands */
921
		if ($when == "post-deinstall" && $pkg_config['custom_php_deinstall_command'] <> "") {
922
			update_status(gettext("Deinstall commands... "));
923
			if ($missing_include == false) {
924
				eval_once($pkg_config['custom_php_deinstall_command']);
925
				update_status(gettext("done.") . "\n");
926
			} else {
927
				update_status("\nNot executing custom deinstall hook because an include is missing.\n");
928
			}
929
		}
930
	}
931
	/* syslog */
932
	$need_syslog_restart = false;
933
	if (is_array($pkg_info['logging']) && $pkg_info['logging']['logfilename'] <> "") {
934
		update_status("Syslog entries... ");
935
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
936
		update_status("done.\n");
937
		$need_syslog_restart = true;
938
	}
939

    
940
	/* remove config.xml entries */
941
	update_status(gettext("Configuration... "));
942
	unset($config['installedpackages']['package'][$pkgid]);
943
	update_status(gettext("done.") . "\n");
944
	write_config("Removed {$package_name} package.\n");
945

    
946
	/* remove package entry from /etc/syslog.conf if needed */
947
	/* this must be done after removing the entries from config.xml */
948
	if ($need_syslog_restart) {
949
		system_syslogd_start();
950
	}
951

    
952
	conf_mount_ro();
953
}
954

    
955
/*
956
 * Used during upgrade process or retore backup process, verify all
957
 * packages installed in config.xml and install pkg accordingly
958
 */
959
function package_reinstall_all() {
960
	global $g, $config, $pkg_interface;
961

    
962
	if (!isset($config['installedpackages']['package']) ||
963
	    !is_array($config['installedpackages']['package'])) {
964
		return true;
965
	}
966

    
967
	$upgrade = (file_exists('/conf/needs_package_sync') && platform_booting());
968

    
969
	/* During boot after upgrade, wait for internet connection */
970
	if ($upgrade) {
971
		update_status(gettext("Waiting for internet connection to update pkg metadata and fini package reinstallation"));
972
		while (true) {
973
			if (pkg_update(true)) {
974
				break;
975
			}
976
			update_status('.');
977
			sleep(1);
978
		}
979
		update_status("\n");
980
	} else {
981
		if (!pkg_update()) {
982
			return false;
983
		}
984
	}
985

    
986
	$pkg_info = get_pkg_info();
987

    
988
	foreach ($config['installedpackages']['package'] as $package) {
989
		$found = false;
990
		$internal_name = get_package_internal_name($package);
991
		foreach ($pkg_info as $pkg) {
992
			pkg_remove_prefix($pkg['name']);
993
			if ($pkg['name'] == $internal_name) {
994
				$found = true;
995
				break;
996
			}
997
		}
998

    
999
		if (!$found) {
1000
			if (!function_exists("file_notice")) {
1001
				require_once("notices.inc");
1002
			}
1003

    
1004
			file_notice(gettext("Package reinstall"),
1005
			    sprintf(gettext("Package %s does not exist in current %s version and it has been removed."), $package['name'], $g['product_name']));
1006
			uninstall_package($package['name']);
1007
		}
1008
	}
1009

    
1010
	/* Obsoleted packages were removed, lets reinstall all remaining */
1011
	foreach ($config['installedpackages']['package'] as $package) {
1012
		$internal_name = get_package_internal_name($package);
1013
		pkg_install($g['pkg_prefix'] . $internal_name, true);
1014
	}
1015

    
1016
	return true;
1017
}
1018

    
1019
function stop_packages() {
1020
	require_once("config.inc");
1021
	require_once("functions.inc");
1022
	require_once("filter.inc");
1023
	require_once("shaper.inc");
1024
	require_once("captiveportal.inc");
1025
	require_once("pkg-utils.inc");
1026
	require_once("pfsense-utils.inc");
1027
	require_once("service-utils.inc");
1028

    
1029
	global $config, $g;
1030

    
1031
	log_error("Stopping all packages.");
1032

    
1033
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1034
	if (!$rcfiles) {
1035
		$rcfiles = array();
1036
	} else {
1037
		$rcfiles = array_flip($rcfiles);
1038
		if (!$rcfiles) {
1039
			$rcfiles = array();
1040
		}
1041
	}
1042

    
1043
	if (is_array($config['installedpackages']['package'])) {
1044
		foreach ($config['installedpackages']['package'] as $package) {
1045
			echo " Stopping package {$package['name']}...";
1046
			$internal_name = get_package_internal_name($package);
1047
			stop_service($internal_name);
1048
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1049
			echo "done.\n";
1050
		}
1051
	}
1052

    
1053
	foreach ($rcfiles as $rcfile => $number) {
1054
		$shell = @popen("/bin/sh", "w");
1055
		if ($shell) {
1056
			echo " Stopping {$rcfile}...";
1057
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1058
				if ($shell) {
1059
					pclose($shell);
1060
				}
1061
				$shell = @popen("/bin/sh", "w");
1062
			}
1063
			echo "done.\n";
1064
			pclose($shell);
1065
		}
1066
	}
1067
}
1068

    
1069
/* Identify which meta package is installed */
1070
function get_meta_pkg_name() {
1071
	global $g;
1072

    
1073
	/* XXX: Use pkg annotation */
1074
	if (is_pkg_installed($g['product_name'])) {
1075
		return $g['product_name'];
1076
	} else if (is_pkg_installed($g['product_name'] . '-vmware')) {
1077
		return $g['product_name'] . '-vmware';
1078
	}
1079
	return false;
1080
}
1081

    
1082
/* Identify which base package is installed */
1083
function get_base_pkg_name() {
1084
	global $g;
1085

    
1086
	/* XXX: Use pkg annotation */
1087
	if (is_pkg_installed($g['product_name'] . '-base-' . $g['platform'])) {
1088
		return $g['product_name'];
1089
		return $g['product_name'] . '-base-' . $g['platform'];
1090
	} else if (is_pkg_installed($g['product_name'] . '-base')) {
1091
		return $g['product_name'] . '-base';
1092
	}
1093
	return false;
1094
}
1095

    
1096
/* Verify if system needs upgrade (meta package or base) */
1097
function get_system_pkg_version() {
1098
	global $g;
1099

    
1100
	$base_pkg = get_base_pkg_name();
1101
	$meta_pkg = get_meta_pkg_name();
1102

    
1103
	if (!$base_pkg || !$meta_pkg) {
1104
		return false;
1105
	}
1106

    
1107
	$info = get_pkg_info($base_pkg);
1108
	$pkg_name = $base_pkg;
1109

    
1110
	$pkg_info = array();
1111
	foreach ($info as $item) {
1112
		if ($item['name'] == $base_pkg) {
1113
			$pkg_info = $item;
1114
		}
1115
	}
1116

    
1117
	if (empty($pkg_info) ||
1118
	    $pkg_info['version'] == $pkg_info['installed_version']) {
1119
		$info = get_pkg_info($meta_pkg);
1120
		$pkg_name = $meta_pkg;
1121

    
1122
		foreach ($info as $item) {
1123
			if ($item['name'] == $meta_pkg) {
1124
				$pkg_info = $item;
1125
			}
1126
		}
1127
	}
1128

    
1129
	if (empty($pkg_info)) {
1130
		return false;
1131
	}
1132

    
1133
	return array(
1134
	    'pkg_name'          => $pkg_name,
1135
	    'version'           => $pkg_info['version'],
1136
	    'installed_version' => $pkg_info['installed_version']
1137
	);
1138
}
1139

    
1140
?>
(41-41/67)