Project

General

Profile

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

    
55
require_once("globals.inc");
56
require_once("service-utils.inc");
57

    
58
if (file_exists("/cf/conf/use_xmlreader")) {
59
	require_once("xmlreader.inc");
60
} else {
61
	require_once("xmlparse.inc");
62
}
63

    
64
require_once("pfsense-utils.inc");
65

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

    
71
		if (!$debug) {
72
			return;
73
		}
74

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

    
84
/* Validate if pkg name is valid */
85
function pkg_valid_name($pkgname) {
86
	global $g;
87

    
88
	$pattern = "/^{$g['pkg_prefix']}[a-zA-Z0-9\.\-_]+$/";
89
	return preg_match($pattern, $pkgname);
90
}
91

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

    
96
	if (substr($pkg_name, 0, strlen($g['pkg_prefix'])) == $g['pkg_prefix']) {
97
		$pkg_name = substr($pkg_name, strlen($g['pkg_prefix']));
98
	}
99
}
100

    
101
/* Execute pkg update when it's necessary */
102
function pkg_update($force = false) {
103
	global $g;
104

    
105
	return pkg_call("update" . ($force ? " -f" : ""));
106
}
107

    
108
/* return an array with necessary environment vars for pkg */
109
function pkg_env($extra_env = array()) {
110
	global $config, $g;
111

    
112
	$pkg_env_vars = array(
113
		"LANG" => "C",
114
		"HTTP_USER_AGENT" => $user_agent,
115
		"ASSUME_ALWAYS_YES" => "true",
116
		"FETCH_TIMEOUT" => 5,
117
		"FETCH_RETRY" => 2
118
	);
119

    
120
	if (!empty($config['system']['proxyurl'])) {
121
		$http_proxy = $config['system']['proxyurl'];
122
		if (!empty($config['system']['proxyport'])) {
123
			$http_proxy .= ':' . $config['system']['proxyport'];
124
		}
125
		$pkg_env_vars['HTTP_PROXY'] = $http_proxy;
126
	}
127

    
128
	if ($g['platform'] == "nanobsd" ||
129
	    isset($config['system']['use_mfs_tmpvar'])) {
130
		$pkg_env_vars['PKG_DBDIR'] = '/root/var/db/pkg';
131
		$pkg_env_vars['PKG_CACHEDIR'] = '/root/var/cache/pkg';
132
	}
133

    
134
	foreach ($extra_env as $key => $value) {
135
		$pkg_env_vars[$key] = $value;
136
	}
137

    
138
	return $pkg_env_vars;
139
}
140

    
141
/* Execute a pkg call */
142
function pkg_call($params, $mute = false, $extra_env = array()) {
143
	global $g, $config;
144

    
145
	if (empty($params)) {
146
		return false;
147
	}
148

    
149
	$user_agent = $g['product_name'] . '/' . $g['product_version'];
150
	if (!isset($config['system']['do_not_send_host_uuid'])) {
151
		$user_agent .= ' : ' . get_single_sysctl('kern.hostuuid');
152
	}
153

    
154
	$descriptorspec = array(
155
		1 => array("pipe", "w"), /* stdout */
156
		2 => array("pipe", "w")	 /* stderr */
157
	);
158

    
159
	conf_mount_rw();
160

    
161
	pkg_debug("pkg_call(): {$params}\n");
162
	$process = proc_open("/usr/sbin/pkg {$params}", $descriptorspec, $pipes,
163
	    '/', pkg_env($extra_env));
164

    
165
	if (!is_resource($process)) {
166
		conf_mount_ro();
167
		return false;
168
	}
169

    
170
	stream_set_blocking($pipes[1], 0);
171
	stream_set_blocking($pipes[2], 0);
172

    
173
	/* XXX: should be a tunnable? */
174
	$timeout = 300; // seconds
175
	$error_log = '';
176

    
177
	do {
178
		$write = array();
179
		$read = array($pipes[1], $pipes[2]);
180
		$except = array();
181

    
182
		$stream = stream_select($read, $write, $except, null, $timeout);
183
		if ($stream !== FALSE && $stream > 0) {
184
			foreach ($read as $pipe) {
185
				$content = stream_get_contents($pipe);
186
				if ($content == '') {
187
					continue;
188
				}
189
				if ($pipe === $pipes[1]) {
190
					if (!$mute) {
191
						update_status($content);
192
					}
193
					flush();
194
				} else if ($pipe === $pipes[2]) {
195
					$error_log .= $content;
196
				}
197
			}
198
		}
199

    
200
		$status = proc_get_status($process);
201
	} while ($status['running']);
202

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

    
207
	conf_mount_ro();
208

    
209
	$rc = $status['exitcode'];
210

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

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

    
223
	return false;
224
}
225

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

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

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

    
239
	$descriptorspec = array(
240
		1 => array("pipe", "w"), /* stdout */
241
		2 => array("pipe", "w")	 /* stderr */
242
	);
243

    
244
	conf_mount_rw();
245

    
246
	pkg_debug("pkg_exec(): {$params}\n");
247
	$process = proc_open("/usr/sbin/pkg {$params}", $descriptorspec, $pipes,
248
	    '/', pkg_env($extra_env));
249

    
250
	if (!is_resource($process)) {
251
		conf_mount_ro();
252
		return -1;
253
	}
254

    
255
	$stdout = '';
256
	while (($l = fgets($pipes[1])) !== FALSE) {
257
		$stdout .= $l;
258
	}
259
	fclose($pipes[1]);
260

    
261
	$stderr = '';
262
	while (($l = fgets($pipes[2])) !== FALSE) {
263
		$stderr .= $l;
264
	}
265
	fclose($pipes[2]);
266

    
267
	conf_mount_ro();
268

    
269
	return proc_close($process);
270
}
271

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

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

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

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

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

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

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

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

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

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

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

    
323
	return $result;
324
}
325

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

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

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

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

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

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

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

    
361
	return -1;
362
}
363

    
364
/* Return internal_name when it's defined, otherwise, returns name */
365
function get_package_internal_name($package_data) {
366
	if (isset($package_data['internal_name']) && ($package_data['internal_name'] != "")) {
367
		/* e.g. name is Ipguard-dev, internal name is ipguard */
368
		return $package_data['internal_name'];
369
	} else {
370
		return $package_data['name'];
371
	}
372
}
373

    
374
// Get information about packages.
375
function get_pkg_info($pkgs = 'all', $info = 'all', $only_local = false) {
376
	global $g, $input_errors;
377

    
378
	$out = '';
379
	$err = '';
380

    
381
	unset($pkg_filter);
382
	if (is_array($pkgs)) {
383
		$pkg_filter = $pkgs;
384
		$pkgs = 'all';
385
	}
386

    
387
	if ($pkgs == 'all') {
388
		$pkgs = $g['pkg_prefix'];
389
	}
390

    
391
	if (!function_exists('is_subsystem_dirty')) {
392
		require_once("util.inc");
393
	}
394

    
395
	/* Do not run remote operations if pkg has a lock */
396
	if (is_subsystem_dirty('pkg')) {
397
		$only_local = true;
398
		$lock = false;
399
	} else {
400
		$lock = true;
401
	}
402

    
403
	$extra_param = "";
404
	if ($only_local) {
405
		$extra_param = "-U ";
406
	}
407

    
408
	if ($lock) {
409
		mark_subsystem_dirty('pkg');
410
	}
411
	$rc = pkg_exec("search {$extra_param}-R --raw-format json-compact " . $pkgs, $out, $err);
412
	if ($lock) {
413
		clear_subsystem_dirty('pkg');
414
	}
415

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

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

    
434
		if (isset($pkg_filter) && !in_array($pkg_info['name'], $pkg_filter)) {
435
			continue;
436
		}
437

    
438
		$pkg_info['shortname'] = $pkg_info['name'];
439
		pkg_remove_prefix($pkg_info['shortname']);
440

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

    
446
		if (is_pkg_installed($pkg_info['name'])) {
447
			$pkg_info['installed'] = true;
448

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

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

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

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

    
468
		$result[] = $pkg_info;
469
		unset($pkg_info);
470
	}
471

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

    
477
	return $result;
478
}
479

    
480
/*
481
 * If binary pkg is installed but post-install tasks were not
482
 * executed yet, do it now.
483
 * This scenario can happen when a pkg is pre-installed during
484
 * build phase, and at this point, cannot find a running system
485
 * to register itself in config.xml and also execute custom
486
 * install functions
487
 */
488
function register_all_installed_packages() {
489
	global $g, $config, $pkg_interface;
490

    
491
	$pkg_info = get_pkg_info('all', 'all', true);
492

    
493
	foreach ($pkg_info as $pkg) {
494
		if (!isset($pkg['installed'])) {
495
			continue;
496
		}
497

    
498
		pkg_remove_prefix($pkg['name']);
499

    
500
		if (is_package_installed($pkg['name'])) {
501
			continue;
502
		}
503

    
504
		update_status(sprintf(gettext(
505
		    "Running last steps of %s installation.") . "\n",
506
		    $pkg['name']));
507
		install_package_xml($pkg['name']);
508
	}
509
}
510

    
511
/*
512
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
513
 * This function may also print output to the terminal indicating progress.
514
 */
515
function resync_all_package_configs($show_message = false) {
516
	global $config, $pkg_interface, $g;
517

    
518
	log_error(gettext("Resyncing configuration for all packages."));
519

    
520
	if (!is_array($config['installedpackages']['package'])) {
521
		return;
522
	}
523

    
524
	if ($show_message == true) {
525
		echo "Syncing packages:";
526
	}
527

    
528
	conf_mount_rw();
529

    
530
	foreach ($config['installedpackages']['package'] as $idx => $package) {
531
		if (empty($package['name'])) {
532
			continue;
533
		}
534
		if ($show_message == true) {
535
			echo " " . $package['name'];
536
		}
537
		if (platform_booting() != true) {
538
			stop_service(get_package_internal_name($package));
539
		}
540
		sync_package($package['name']);
541
		update_status(gettext("Syncing packages...") . "\n");
542
	}
543

    
544
	if ($show_message == true) {
545
		echo " done.\n";
546
	}
547

    
548
	@unlink("/conf/needs_package_sync");
549
	conf_mount_ro();
550
}
551

    
552
function uninstall_package($package_name) {
553
	global $config;
554

    
555
	$internal_name = $package_name;
556
	$id = get_package_id($package_name);
557
	if ($id >= 0) {
558
		$internal_name = get_package_internal_name($config['installedpackages']['package'][$id]);
559
		stop_service($internal_name);
560
	}
561
	$pkg_name = $g['pkg_prefix'] . $internal_name;
562

    
563
	if (is_pkg_installed($pkg_name)) {
564
		update_status(gettext("Removing package...") . "\n");
565
		pkg_delete($pkg_name);
566
	} else {
567
		delete_package_xml($package_name);
568
	}
569

    
570
	update_status(gettext("done.") . "\n");
571
}
572

    
573
/* Run <custom_php_resync_config_command> */
574
function sync_package($package_name) {
575
	global $config, $builder_package_install;
576

    
577
	// If this code is being called by pfspkg_installer
578
	// which the builder system uses then return (ignore).
579
	if ($builder_package_install) {
580
		return;
581
	}
582

    
583
	if (empty($config['installedpackages']['package'])) {
584
		return;
585
	}
586

    
587
	if (($pkg_id = get_package_id($package_name)) == -1) {
588
		return; // This package doesn't really exist - exit the function.
589
	}
590

    
591
	if (!is_array($config['installedpackages']['package'][$pkg_id])) {
592
		return;	 // No package belongs to the pkg_id passed to this function.
593
	}
594

    
595
	$package =& $config['installedpackages']['package'][$pkg_id];
596
	if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
597
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
598
		delete_package_xml($package['name']);
599
		return;
600
	}
601

    
602
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
603
	if (isset($pkg_config['nosync'])) {
604
		return;
605
	}
606

    
607
	/* Bring in package include files */
608
	if (!empty($pkg_config['include_file'])) {
609
		$include_file = $pkg_config['include_file'];
610
		if (file_exists($include_file)) {
611
			require_once($include_file);
612
		} else {
613
			log_error(sprintf(gettext('Reinstalling package %1$s because its include file(%2$s) is missing!'), $package['name'], $include_file));
614
			uninstall_package($package['name']);
615
			if (install_package($package['name']) != 0) {
616
				log_error(sprintf(gettext("Reinstalling package %s failed. Take appropriate measures!!!"), $package['name']));
617
				return;
618
			}
619
			if (file_exists($include_file)) {
620
				require_once($include_file);
621
			} else {
622
				return;
623
			}
624
		}
625
	}
626

    
627
	if (!empty($pkg_config['custom_php_global_functions'])) {
628
		eval($pkg_config['custom_php_global_functions']);
629
	}
630
	if (!empty($pkg_config['custom_php_resync_config_command'])) {
631
		eval($pkg_config['custom_php_resync_config_command']);
632
	}
633
}
634

    
635
/* Read info.xml installed by package and return an array */
636
function read_package_config($package_name) {
637
	global $g;
638

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

    
641
	if (!file_exists($pkg_info_xml)) {
642
		return false;
643
	}
644

    
645
	$pkg_info = parse_xml_config_pkg($pkg_info_xml, 'pfsensepkgs');
646

    
647
	if (empty($pkg_info)) {
648
		return false;
649
	}
650

    
651
	/* it always returns an array with 1 item */
652
	return $pkg_info['package'][0];
653
}
654

    
655
/* Read package configurationfile and return an array */
656
function read_package_configurationfile($package_name) {
657
	global $config, $g;
658

    
659
	$pkg_config = array();
660
	$id = get_package_id($package_name);
661

    
662
	if ($id < 0 || !isset($config['installedpackages']['package'][$id]['configurationfile'])) {
663
		return $pkg_config;
664
	}
665

    
666
	$pkg_configurationfile = $config['installedpackages']['package'][$id]['configurationfile'];
667

    
668
	if (empty($pkg_configurationfile) || !file_exists('/usr/local/pkg/' . $pkg_configurationfile)) {
669
		return $pkg_config;
670
	}
671

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

    
674
	return $pkg_config;
675
}
676

    
677
function get_after_install_info($package_name) {
678
	$pkg_config = read_package_config($package_name);
679

    
680
	if (isset($pkg_config['after_install_info'])) {
681
		return $pkg_config['after_install_info'];
682
	}
683

    
684
	return '';
685
}
686

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

    
700
function install_package_xml($package_name) {
701
	global $g, $config, $pkg_interface;
702

    
703
	if (($pkg_info = read_package_config($package_name)) == false) {
704
		return false;
705
	}
706

    
707
	/* safe side. Write config below will send to ro again. */
708
	conf_mount_rw();
709

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

    
713
	/* add package information to config.xml */
714
	$pkgid = get_package_id($pkg_info['name']);
715
	update_status(gettext("Saving updated package information...") . "\n");
716
	if ($pkgid == -1) {
717
		$config['installedpackages']['package'][] = $pkg_info;
718
		$changedesc = sprintf(gettext("Installed %s package."), $pkg_info['name']);
719
		$to_output = gettext("done.") . "\n";
720
	} else {
721
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
722
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
723
		$to_output = gettext("overwrite!") . "\n";
724
	}
725
	unlink_if_exists('/conf/needs_package_sync');
726
	write_config(sprintf(gettext("Intermediate config write during package install for %s."), $pkg_info['name']));
727
	conf_mount_ro();
728
	update_status($to_output);
729

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

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

    
740
	if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
741
		update_status(gettext("Loading package configuration... "));
742
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $pkg_info['configurationfile'], "packagegui");
743
		update_status(gettext("done.") . "\n");
744
		update_status(gettext("Configuring package components...") . "\n");
745
		if (!empty($pkg_config['filter_rules_needed'])) {
746
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
747
		}
748
		/* modify system files */
749

    
750
		/* if a require exists, include it.  this will
751
		 * show us where an error exists in a package
752
		 * instead of making us blindly guess
753
		 */
754
		$missing_include = false;
755
		if ($pkg_config['include_file'] <> "") {
756
			update_status(gettext("Loading package instructions...") . "\n");
757
			if (file_exists($pkg_config['include_file'])) {
758
				pkg_debug("require_once('{$pkg_config['include_file']}')\n");
759
				require_once($pkg_config['include_file']);
760
			} else {
761
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
762
				$missing_include = true;
763
				update_status(sprintf(gettext("Include %s is missing!"), basename($pkg_config['include_file'])) . "\n");
764

    
765
				uninstall_package($package_name);
766
				write_config($changedesc);
767
				log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
768
				update_status(gettext("Failed to install package.") . "\n");
769
				return false;
770
			}
771
		}
772

    
773
		/* custom commands */
774
		update_status(gettext("Custom commands...") . "\n");
775
		if ($missing_include == false) {
776
			if ($pkg_config['custom_php_global_functions'] <> "") {
777
				update_status(gettext("Executing custom_php_global_functions()..."));
778
				eval_once($pkg_config['custom_php_global_functions']);
779
				update_status(gettext("done.") . "\n");
780
			}
781
			if ($pkg_config['custom_php_install_command']) {
782
				update_status(gettext("Executing custom_php_install_command()..."));
783
				eval_once($pkg_config['custom_php_install_command']);
784
				update_status(gettext("done.") . "\n");
785
			}
786
			if ($pkg_config['custom_php_resync_config_command'] <> "") {
787
				update_status(gettext("Executing custom_php_resync_config_command()..."));
788
				eval_once($pkg_config['custom_php_resync_config_command']);
789
				update_status(gettext("done.") . "\n");
790
			}
791
		}
792
		/* sidebar items */
793
		if (is_array($pkg_config['menu'])) {
794
			update_status(gettext("Menu items... "));
795
			foreach ($pkg_config['menu'] as $menu) {
796
				if (is_array($config['installedpackages']['menu'])) {
797
					foreach ($config['installedpackages']['menu'] as $amenu) {
798
						if ($amenu['name'] == $menu['name']) {
799
							continue 2;
800
						}
801
					}
802
				} else {
803
					$config['installedpackages']['menu'] = array();
804
				}
805
				$config['installedpackages']['menu'][] = $menu;
806
			}
807
			update_status(gettext("done.") . "\n");
808
		}
809
		/* services */
810
		if (is_array($pkg_config['service'])) {
811
			update_status(gettext("Services... "));
812
			foreach ($pkg_config['service'] as $service) {
813
				if (is_array($config['installedpackages']['service'])) {
814
					foreach ($config['installedpackages']['service'] as $aservice) {
815
						if ($aservice['name'] == $service['name']) {
816
							continue 2;
817
						}
818
					}
819
				} else {
820
					$config['installedpackages']['service'] = array();
821
				}
822
				$config['installedpackages']['service'][] = $service;
823
			}
824
			update_status(gettext("done.") . "\n");
825
		}
826
	} else {
827
		pkg_debug("Unable to find config file\n");
828
		update_status(gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted."));
829
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
830

    
831
		uninstall_package($package_name);
832
		write_config($changedesc);
833
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
834
		update_status(gettext("Failed to install package.") . "\n");
835
		return false;
836
	}
837

    
838
	/* set up package logging streams */
839
	if ($pkg_info['logging']) {
840
		system_syslogd_start();
841
	}
842

    
843
	update_status(gettext("Writing configuration... "));
844
	write_config($changedesc);
845
	log_error(sprintf(gettext("Successfully installed package: %s."), $pkg_info['name']));
846
	update_status(gettext("done.") . "\n");
847
	if ($pkg_info['after_install_info']) {
848
		update_status($pkg_info['after_install_info']);
849
	}
850

    
851
	return true;
852
}
853

    
854
function delete_package_xml($package_name, $when = "post-deinstall") {
855
	global $g, $config, $pkg_interface;
856

    
857
	conf_mount_rw();
858

    
859
	$pkgid = get_package_id($package_name);
860
	if ($pkgid == -1) {
861
		update_status(sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $package_name, "\n\n"));
862
		ob_flush();
863
		sleep(1);
864
		conf_mount_ro();
865
		return;
866
	}
867
	pkg_debug(sprintf(gettext("Removing %s package... "), $package_name));
868
	update_status(sprintf(gettext("Removing %s components..."), $package_name) . "\n");
869
	/* parse package configuration */
870
	$packages = &$config['installedpackages']['package'];
871
	$menus =& $config['installedpackages']['menu'];
872
	$services = &$config['installedpackages']['service'];
873
	$pkg_info =& $packages[$pkgid];
874
	if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
875
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
876
		/* remove menu items */
877
		if (is_array($pkg_config['menu'])) {
878
			update_status(gettext("Menu items... "));
879
			if (is_array($pkg_config['menu']) && is_array($menus)) {
880
				foreach ($pkg_config['menu'] as $menu) {
881
					foreach ($menus as $key => $instmenu) {
882
						if ($instmenu['name'] == $menu['name']) {
883
							unset($menus[$key]);
884
							break;
885
						}
886
					}
887
				}
888
			}
889
			update_status(gettext("done.") . "\n");
890
		}
891
		/* remove services */
892
		if (is_array($pkg_config['service'])) {
893
			update_status(gettext("Services... "));
894
			if (is_array($pkg_config['service']) && is_array($services)) {
895
				foreach ($pkg_config['service'] as $service) {
896
					foreach ($services as $key => $instservice) {
897
						if ($instservice['name'] == $service['name']) {
898
							if (platform_booting() != true) {
899
								stop_service($service['name']);
900
							}
901
							if ($service['rcfile']) {
902
								$prefix = RCFILEPREFIX;
903
								if (!empty($service['prefix'])) {
904
									$prefix = $service['prefix'];
905
								}
906
								if (file_exists("{$prefix}{$service['rcfile']}")) {
907
									@unlink("{$prefix}{$service['rcfile']}");
908
								}
909
							}
910
							unset($services[$key]);
911
						}
912
					}
913
				}
914
			}
915
			update_status(gettext("done.") . "\n");
916
		}
917
		/*
918
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
919
		 *	Same is done during installation.
920
		 */
921
		write_config(sprintf(gettext("Intermediate config write during package removal for %s."), $package_name));
922

    
923
		/*
924
		 * If a require exists, include it.	 this will
925
		 * show us where an error exists in a package
926
		 * instead of making us blindly guess
927
		 */
928
		$missing_include = false;
929
		if ($pkg_config['include_file'] <> "") {
930
			update_status(gettext("Loading package instructions...") . "\n");
931
			if (file_exists($pkg_config['include_file'])) {
932
				pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
933
				require_once($pkg_config['include_file']);
934
			} else {
935
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
936
				$missing_include = true;
937
				update_status(sprintf(gettext("Include file %s could not be found for inclusion."), basename($pkg_config['include_file'])) . "\n");
938
			}
939
		}
940
		/* ermal
941
		 * NOTE: It is not possible to handle parse errors on eval.
942
		 * So we prevent it from being run at all to not interrupt all the other code.
943
		 */
944
		if ($when == "deinstall" && $missing_include == false) {
945
			/* evaluate this package's global functions and pre deinstall commands */
946
			if ($pkg_config['custom_php_global_functions'] <> "") {
947
				eval_once($pkg_config['custom_php_global_functions']);
948
			}
949
			if ($pkg_config['custom_php_pre_deinstall_command'] <> "") {
950
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
951
			}
952
		}
953
		/* deinstall commands */
954
		if ($when == "post-deinstall" && $pkg_config['custom_php_deinstall_command'] <> "") {
955
			update_status(gettext("Deinstall commands... "));
956
			if ($missing_include == false) {
957
				eval_once($pkg_config['custom_php_deinstall_command']);
958
				update_status(gettext("done.") . "\n");
959
			} else {
960
				update_status("\n". gettext("Not executing custom deinstall hook because an include is missing.") . "\n");
961
			}
962
		}
963
	}
964
	/* syslog */
965
	$need_syslog_restart = false;
966
	if (is_array($pkg_info['logging']) && $pkg_info['logging']['logfilename'] <> "") {
967
		update_status(gettext("Syslog entries... "));
968
		@unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
969
		update_status("done.\n");
970
		$need_syslog_restart = true;
971
	}
972

    
973
	if ($when == "post-deinstall") {
974
		/* remove config.xml entries */
975
		update_status(gettext("Configuration... "));
976
		unset($config['installedpackages']['package'][$pkgid]);
977
		update_status(gettext("done.") . "\n");
978
		write_config(sprintf(gettext("Removed %s package."), $package_name));
979
	}
980

    
981
	/* remove package entry from /etc/syslog.conf if needed */
982
	/* this must be done after removing the entries from config.xml */
983
	if ($need_syslog_restart) {
984
		system_syslogd_start();
985
	}
986

    
987
	conf_mount_ro();
988
}
989

    
990
/*
991
 * Used during upgrade process or retore backup process, verify all
992
 * packages installed in config.xml and install pkg accordingly
993
 */
994
function package_reinstall_all() {
995
	global $g, $config, $pkg_interface;
996

    
997
	$upgrade = (file_exists('/conf/needs_package_sync') && platform_booting());
998

    
999
	if ((!isset($config['installedpackages']['package']) ||
1000
	    !is_array($config['installedpackages']['package'])) && !$upgrade) {
1001
		return true;
1002
	}
1003

    
1004
	/* During boot after upgrade, wait for internet connection */
1005
	if ($upgrade) {
1006
		update_status(gettext("Waiting for Internet connection to update pkg metadata and finish package reinstallation"));
1007
		$ntries = 3;
1008
		while ($ntries > 0) {
1009
			if (pkg_update(true)) {
1010
				break;
1011
			}
1012
			update_status('.');
1013
			sleep(1);
1014
			$ntries--;
1015
		}
1016
		update_status("\n");
1017

    
1018
		if ($ntries == 0) {
1019
			file_notice(gettext("Package reinstall"),
1020
			    gettext("Package reinstall process was ABORTED due to lack of internet connectivity"));
1021
			return false;
1022
		}
1023
	}
1024

    
1025
	$pkg_info = get_pkg_info();
1026

    
1027
	if ($upgrade &&
1028
	    file_exists("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt")) {
1029
		$package_list = file("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt",
1030
		    FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1031
		unlink_if_exists("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt");
1032
	} else {
1033
		if (!isset($config['installedpackages']['package']) || !is_array($config['installedpackages']['package'])) {
1034
			return true;
1035
		}
1036
		$package_list = array();
1037
		foreach ($config['installedpackages']['package'] as $package) {
1038
			$package_list[] = get_package_internal_name($package);
1039
		}
1040
	}
1041

    
1042
	foreach ($package_list as $package) {
1043
		$found = false;
1044
		foreach ($pkg_info as $pkg) {
1045
			pkg_remove_prefix($pkg['name']);
1046
			if ($pkg['name'] == $package) {
1047
				pkg_install($g['pkg_prefix'] . $package, true);
1048
				$found = true;
1049
				break;
1050
			}
1051
		}
1052

    
1053
		if (!$found) {
1054
			if (!function_exists("file_notice")) {
1055
				require_once("notices.inc");
1056
			}
1057

    
1058
			file_notice(gettext("Package reinstall"),
1059
			    sprintf(gettext("Package %s does not exist in current %s version and it has been removed."),
1060
			    $package, $g['product_name']));
1061
			uninstall_package($package);
1062
		}
1063
	}
1064

    
1065
	return true;
1066
}
1067

    
1068
function stop_packages() {
1069
	require_once("config.inc");
1070
	require_once("functions.inc");
1071
	require_once("filter.inc");
1072
	require_once("shaper.inc");
1073
	require_once("captiveportal.inc");
1074
	require_once("pkg-utils.inc");
1075
	require_once("pfsense-utils.inc");
1076
	require_once("service-utils.inc");
1077

    
1078
	global $config, $g;
1079

    
1080
	log_error(gettext("Stopping all packages."));
1081

    
1082
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1083
	if (!$rcfiles) {
1084
		$rcfiles = array();
1085
	} else {
1086
		$rcfiles = array_flip($rcfiles);
1087
		if (!$rcfiles) {
1088
			$rcfiles = array();
1089
		}
1090
	}
1091

    
1092
	if (is_array($config['installedpackages']['package'])) {
1093
		foreach ($config['installedpackages']['package'] as $package) {
1094
			echo " Stopping package {$package['name']}...";
1095
			$internal_name = get_package_internal_name($package);
1096
			stop_service($internal_name);
1097
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1098
			echo "done.\n";
1099
		}
1100
	}
1101

    
1102
	foreach ($rcfiles as $rcfile => $number) {
1103
		$shell = @popen("/bin/sh", "w");
1104
		if ($shell) {
1105
			echo " Stopping {$rcfile}...";
1106
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1107
				if ($shell) {
1108
					pclose($shell);
1109
				}
1110
				$shell = @popen("/bin/sh", "w");
1111
			}
1112
			echo "done.\n";
1113
			pclose($shell);
1114
		}
1115
	}
1116
}
1117

    
1118
/* Identify which meta package is installed */
1119
function get_meta_pkg_name() {
1120
	global $g;
1121

    
1122
	/* XXX: Use pkg annotation */
1123
	if (is_pkg_installed($g['product_name'])) {
1124
		return $g['product_name'];
1125
	} else if (is_pkg_installed($g['product_name'] . '-vmware')) {
1126
		return $g['product_name'] . '-vmware';
1127
	}
1128
	return false;
1129
}
1130

    
1131
/* Identify which base package is installed */
1132
function get_base_pkg_name() {
1133
	global $g;
1134

    
1135
	/* XXX: Use pkg annotation */
1136
	if (is_pkg_installed($g['product_name'] . '-base-' . $g['platform'])) {
1137
		return $g['product_name'] . '-base-' . $g['platform'];
1138
	} else if (is_pkg_installed($g['product_name'] . '-base')) {
1139
		return $g['product_name'] . '-base';
1140
	}
1141
	return false;
1142
}
1143

    
1144
/* Verify if system needs upgrade (meta package or base) */
1145
function get_system_pkg_version($baseonly = false) {
1146
	global $g;
1147

    
1148
	$base_pkg = get_base_pkg_name();
1149
	$meta_pkg = get_meta_pkg_name();
1150

    
1151
	if (!$base_pkg || !$meta_pkg) {
1152
		return false;
1153
	}
1154

    
1155
	$info = get_pkg_info($base_pkg);
1156
	$pkg_name = $base_pkg;
1157

    
1158
	$pkg_info = array();
1159
	foreach ($info as $item) {
1160
		if ($item['name'] == $base_pkg) {
1161
			$pkg_info = $item;
1162
		}
1163
	}
1164

    
1165
	if (empty($pkg_info) || (!$baseonly && ($pkg_info['version'] == $pkg_info['installed_version']))) {
1166
		$info = get_pkg_info($meta_pkg);
1167
		$pkg_name = $meta_pkg;
1168

    
1169
		foreach ($info as $item) {
1170
			if ($item['name'] == $meta_pkg) {
1171
				$pkg_info = $item;
1172
			}
1173
		}
1174
	}
1175

    
1176
	if (empty($pkg_info)) {
1177
		return false;
1178
	}
1179

    
1180
	return array(
1181
	    'pkg_name'          => $pkg_name,
1182
	    'version'           => $pkg_info['version'],
1183
	    'installed_version' => $pkg_info['installed_version']
1184
	);
1185
}
1186

    
1187
/* List available repos */
1188
function pkg_list_repos() {
1189
	global $g;
1190

    
1191
	$path = "/usr/local/share/{$g['product_name']}/pkg/repos";
1192

    
1193
	$default_descr = @file_get_contents($path . "/{$g['product_name']}-repo.descr");
1194

    
1195
	$default = array(
1196
	    'name' => 'Default',
1197
	    'path' => $path . "/{$g['product_name']}-repo.conf",
1198
	    'descr' => $default_descr
1199
	);
1200

    
1201
	$result = array($default);
1202

    
1203
	$conf_files = glob("{$path}/{$g['product_name']}-repo-*.conf");
1204
	foreach ($conf_files as $conf_file) {
1205
		$descr_file = preg_replace('/.conf$/', '.descr', $conf_file);
1206
		if (file_exists($descr_file)) {
1207
			$descr_content = file($descr_file);
1208
			$descr = chop($descr_content[0]);
1209
		} else {
1210
			$descr = 'Unknown';
1211
		}
1212
		if (!preg_match('/-repo-(.*).conf/', $conf_file, $matches)) {
1213
			continue;
1214
		}
1215
		$entry = array(
1216
		    'name' => ucfirst(strtolower($matches[1])),
1217
		    'path' => $conf_file,
1218
		    'descr' => $descr
1219
		);
1220
		$result[] = $entry;
1221
	}
1222

    
1223
	return $result;
1224
}
1225

    
1226
/* Switch between stable and devel repos */
1227
function pkg_switch_repo($path) {
1228
	global $g;
1229

    
1230
	safe_mkdir("/usr/local/etc/pkg/repos");
1231
	@unlink("/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1232
	@symlink($path, "/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1233

    
1234
	return pkg_update(true);
1235
}
1236

    
1237
?>
(40-40/65)