Project

General

Profile

Download (37.2 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 Rubicon Communications, LLC (Netgate)
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
	$user_agent = $g['product_name'] . '/' . $g['product_version'];
113
	if (!isset($config['system']['do_not_send_uniqueid'])) {
114
		$user_agent .= ':' . system_get_uniqueid();
115
	}
116

    
117
	$pkg_env_vars = array(
118
		"LANG" => "C",
119
		"HTTP_USER_AGENT" => $user_agent,
120
		"ASSUME_ALWAYS_YES" => "true",
121
		"FETCH_TIMEOUT" => 5,
122
		"FETCH_RETRY" => 2
123
	);
124

    
125
	if (!empty($config['system']['proxyurl'])) {
126
		$http_proxy = $config['system']['proxyurl'];
127
		if (!empty($config['system']['proxyport'])) {
128
			$http_proxy .= ':' . $config['system']['proxyport'];
129
		}
130
		$pkg_env_vars['HTTP_PROXY'] = $http_proxy;
131
	}
132

    
133
	if ($g['platform'] == "nanobsd" ||
134
	    isset($config['system']['use_mfs_tmpvar'])) {
135
		$pkg_env_vars['PKG_DBDIR'] = '/root/var/db/pkg';
136
		$pkg_env_vars['PKG_CACHEDIR'] = '/root/var/cache/pkg';
137
	}
138

    
139
	foreach ($extra_env as $key => $value) {
140
		$pkg_env_vars[$key] = $value;
141
	}
142

    
143
	return $pkg_env_vars;
144
}
145

    
146
/* Execute a pkg call */
147
function pkg_call($params, $mute = false, $extra_env = array()) {
148
	global $g, $config;
149

    
150
	if (empty($params)) {
151
		return false;
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 = 60; // 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, $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
	$descriptorspec = array(
235
		1 => array("pipe", "w"), /* stdout */
236
		2 => array("pipe", "w")	 /* stderr */
237
	);
238

    
239
	conf_mount_rw();
240

    
241
	pkg_debug("pkg_exec(): {$params}\n");
242
	$process = proc_open("/usr/sbin/pkg {$params}", $descriptorspec, $pipes,
243
	    '/', pkg_env($extra_env));
244

    
245
	if (!is_resource($process)) {
246
		conf_mount_ro();
247
		return -1;
248
	}
249

    
250
	$stdout = '';
251
	while (($l = fgets($pipes[1])) !== FALSE) {
252
		$stdout .= $l;
253
	}
254
	fclose($pipes[1]);
255

    
256
	$stderr = '';
257
	while (($l = fgets($pipes[2])) !== FALSE) {
258
		$stderr .= $l;
259
	}
260
	fclose($pipes[2]);
261

    
262
	conf_mount_ro();
263

    
264
	return proc_close($process);
265
}
266

    
267
/* Compare 2 pkg versions and return:
268
 * '=' - versions are the same
269
 * '>' - $v1 > $v2
270
 * '<' - $v1 < $v2
271
 * '?' - Error
272
 */
273
function pkg_version_compare($v1, $v2) {
274
	if (empty($v1) || empty($v2)) {
275
		return '?';
276
	}
277

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

    
280
	if ($rc != 0) {
281
		return '?';
282
	}
283

    
284
	return str_replace("\n", "", $stdout);
285
}
286

    
287
/* Check if package is installed */
288
function is_pkg_installed($pkg_name) {
289
	global $g;
290

    
291
	if (empty($pkg_name)) {
292
		return false;
293
	}
294

    
295
	return pkg_call("info -e " . $pkg_name, true);
296
}
297

    
298
/* Install package, $pkg_name should not contain prefix */
299
function pkg_install($pkg_name, $force = false) {
300
	global $g;
301
	$result = false;
302

    
303
	$shortname = $pkg_name;
304
	pkg_remove_prefix($shortname);
305

    
306
	$pkg_force = "";
307
	if ($force) {
308
		$pkg_force = "-f ";
309
	}
310

    
311
	pkg_debug("Installing package {$shortname}\n");
312
	if ($force || !is_pkg_installed($pkg_name)) {
313
		$result = pkg_call("install -y " . $pkg_force . $pkg_name);
314
		/* Cleanup cacke to free disk space */
315
		pkg_call("clean -y");
316
	}
317

    
318
	return $result;
319
}
320

    
321
/* Delete package from FreeBSD, $pkg_name should not contain prefix */
322
function pkg_delete($pkg_name) {
323
	global $g;
324

    
325
	$shortname = $pkg_name;
326
	pkg_remove_prefix($shortname);
327

    
328
	pkg_debug("Removing package {$shortname}\n");
329
	if (is_pkg_installed($pkg_name)) {
330
		pkg_call("delete -y " . $pkg_name);
331
		/* Cleanup unecessary dependencies */
332
		pkg_call("autoremove -y");
333
	}
334
}
335

    
336
/* Check if package is present in config.xml */
337
function is_package_installed($package_name) {
338
	return (get_package_id($package_name) != -1);
339
}
340

    
341
/* Find package array index */
342
function get_package_id($package_name) {
343
	global $config;
344

    
345
	if (!is_array($config['installedpackages']['package'])) {
346
		return -1;
347
	}
348

    
349
	foreach ($config['installedpackages']['package'] as $idx => $pkg) {
350
		if ($pkg['name'] == $package_name ||
351
		    get_package_internal_name($pkg) == $package_name) {
352
			return $idx;
353
		}
354
	}
355

    
356
	return -1;
357
}
358

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

    
369
// Get information about packages.
370
function get_pkg_info($pkgs = 'all', $remote_repo_usage_disabled = false,
371
    $installed_pkgs_only = false) {
372
	global $g, $input_errors;
373

    
374
	$out = $err = $extra_param = '';
375
	$rc = 0;
376

    
377
	unset($pkg_filter);
378

    
379
	if (is_array($pkgs)) {
380
		$pkg_filter = $pkgs;
381
		$pkgs = $g['pkg_prefix'] . '*';
382
	} elseif ($pkgs == 'all') {
383
		$pkgs = $g['pkg_prefix'] . '*';
384
	}
385

    
386
	
387
	if ($installed_pkgs_only && !is_pkg_installed($pkgs)) {
388
		// Return early if the caller wants just installed packages and there are none.
389
		// Saves doing any calls that might access a remote package repo.
390
		return array();
391
	}
392

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

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

    
405
	if ($lock) {
406
		mark_subsystem_dirty('pkg');
407
	}
408

    
409
	if ($remote_repo_usage_disabled) {
410
		$extra_param = "-U ";
411
	}
412

    
413
	// If we want more than just the currently installed packages or
414
	//    we want up-to-date remote repo info
415
	// then do a full pkg search
416
	if (!$installed_pkgs_only || !$remote_repo_usage_disabled) {
417
		$rc = pkg_exec(
418
		    "search {$extra_param}-R --raw-format json-compact " .
419
		    $pkgs, $out, $err);
420
	}
421

    
422
	if (($installed_pkgs_only || $rc != 0) &&
423
	    $remote_repo_usage_disabled &&
424
	    is_pkg_installed($pkgs)) {
425
		/*
426
		 * Fall back on pkg info to return locally installed matching
427
		 * pkgs instead, if:
428
		 *
429
		 *   (1) only installed pkgs needed, or
430
		 *       we tried to check the local catalog copy (implying that
431
		 *       we would have accepted incomplete/outdated pkg info)
432
		 *       but it didn't have any contents, or for other reasons
433
		 *       returned an error.
434
		 *   AND
435
		 *   (2) remote repo data is not required
436
		 *   AND
437
		 *   (3) at least some pkgs matching <pattern> are installed
438
		 *
439
		 * Following an unsuccessful attempt to access a remote repo
440
		 * catalog, the local copy is wiped clear. Thereafter any
441
		 * "pkg search" will return an error until online+updated again.
442
		 * If the calling code would have accepted local copy info
443
		 * (which could be incomplete/out of date), then it makes sense
444
		 * to fall back on pkg info to at least return the known
445
		 * info about installed pkgs (pkg info should still work),
446
		 * instead of failing and returning no info at all. 
447
		 * For example, this at least enables offline view + management
448
		 * of installed pkgs in GUI/console.
449
		 *
450
		 * We skip this step if no matching pkgs are installed, because
451
		 * then pkg info would return a "no matching pkgs" RC code,
452
		 * even though this wouldn't be considered an "error" (and
453
		 * $out+$err would be correct empty strings if none match).
454
		 *
455
		 * Note that is_pkg_installed() is a wrapper for pkg info -e
456
		 * <pattern> which is what we need here.
457
		*/
458
		
459
		// ok, 1 or more packages match, so pkg info can be safely called to get the pkg list  
460
		$rc = pkg_exec("info -R --raw-format json-compact " . $pkgs,
461
		    $out, $err);
462
	}
463

    
464
	if ($lock) {
465
		clear_subsystem_dirty('pkg');
466
	}
467

    
468
	if ($rc != 0) {
469
		update_status("\n" . gettext(
470
		    "ERROR: Error trying to get packages list. Aborting...")
471
		    . "\n");
472
		update_status($err);
473
		$input_errors[] = gettext(
474
		    "ERROR: Error trying to get packages list. Aborting...") .
475
		    "\n";
476
		$input_errors[] = $err;
477
		return array();
478
	}
479

    
480
	$result = array();
481
	$pkgs_info = explode("\n", $out);
482
	foreach ($pkgs_info as $pkg_info_json) {
483
		$pkg_info = json_decode($pkg_info_json, true);
484
		if (!isset($pkg_info['name'])) {
485
			continue;
486
		}
487

    
488
		if (isset($pkg_filter) && !in_array($pkg_info['name'],
489
		    $pkg_filter)) {
490
			continue;
491
		}
492

    
493
		$pkg_info['shortname'] = $pkg_info['name'];
494
		pkg_remove_prefix($pkg_info['shortname']);
495

    
496
		/* XXX: Add it to globals.inc? */
497
		$pkg_info['changeloglink'] =
498
		    "https://github.com/pfsense/FreeBSD-ports/commits/devel/" .
499
		    $pkg_info['categories'][0] . '/' . $pkg_info['name'];
500

    
501
		$pkg_is_installed = false;
502

    
503
		if (is_pkg_installed($pkg_info['name'])) {
504
			$pkg_info['installed'] = true;
505
			$pkg_is_installed = true;
506

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

    
510
			if ($rc != 0) {
511
				update_status("\n" . gettext(
512
				    "ERROR: Error trying to get package version. Aborting...")
513
				    . "\n");
514
				update_status($err);
515
				$input_errors[] = gettext(
516
				    "ERROR: Error trying to get package version. Aborting...") .
517
				    "\n";
518
				$input_errors[] = $err;
519
				return array();
520
			}
521

    
522
			$pkg_info['installed_version'] = str_replace("\n", "",
523
			    $out);
524
		} else if (is_package_installed($pkg_info['shortname'])) {
525
			$pkg_info['broken'] = true;
526
			$pkg_is_installed = true;
527
		}
528

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

    
532
		if (!$installed_pkgs_only || $pkg_is_installed) {
533
			$result[] = $pkg_info;
534
		}
535
		unset($pkg_info);
536
	}
537

    
538
	/* Sort result alphabetically */
539
	usort($result, function($a, $b) {
540
		return(strcasecmp ($a['name'], $b['name']));
541
	});
542

    
543
	return $result;
544
}
545

    
546
/*
547
 * If binary pkg is installed but post-install tasks were not
548
 * executed yet, do it now.
549
 * This scenario can happen when a pkg is pre-installed during
550
 * build phase, and at this point, cannot find a running system
551
 * to register itself in config.xml and also execute custom
552
 * install functions
553
 */
554
function register_all_installed_packages() {
555
	global $g, $config, $pkg_interface;
556

    
557
	$pkg_info = get_pkg_info('all', true, true);
558

    
559
	foreach ($pkg_info as $pkg) {
560
		pkg_remove_prefix($pkg['name']);
561

    
562
		if (is_package_installed($pkg['name'])) {
563
			continue;
564
		}
565

    
566
		update_status(sprintf(gettext(
567
		    "Running last steps of %s installation.") . "\n",
568
		    $pkg['name']));
569
		install_package_xml($pkg['name']);
570
	}
571
}
572

    
573
/*
574
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
575
 * This function may also print output to the terminal indicating progress.
576
 */
577
function resync_all_package_configs($show_message = false) {
578
	global $config, $pkg_interface, $g;
579

    
580
	log_error(gettext("Resyncing configuration for all packages."));
581

    
582
	if (!is_array($config['installedpackages']['package'])) {
583
		return;
584
	}
585

    
586
	if ($show_message == true) {
587
		echo "Syncing packages:";
588
	}
589

    
590
	conf_mount_rw();
591

    
592
	foreach ($config['installedpackages']['package'] as $idx => $package) {
593
		if (empty($package['name'])) {
594
			continue;
595
		}
596
		if ($show_message == true) {
597
			echo " " . $package['name'];
598
		}
599
		if (platform_booting() != true) {
600
			stop_service(get_package_internal_name($package));
601
		}
602
		sync_package($package['name']);
603
		update_status(gettext("Syncing packages...") . "\n");
604
	}
605

    
606
	if ($show_message == true) {
607
		echo " done.\n";
608
	}
609

    
610
	@unlink("/conf/needs_package_sync");
611
	conf_mount_ro();
612
}
613

    
614
function uninstall_package($package_name) {
615
	global $config;
616

    
617
	$internal_name = $package_name;
618
	$id = get_package_id($package_name);
619
	if ($id >= 0) {
620
		$internal_name = get_package_internal_name($config['installedpackages']['package'][$id]);
621
		stop_service($internal_name);
622
	}
623
	$pkg_name = $g['pkg_prefix'] . $internal_name;
624

    
625
	if (is_pkg_installed($pkg_name)) {
626
		update_status(gettext("Removing package...") . "\n");
627
		pkg_delete($pkg_name);
628
	} else {
629
		delete_package_xml($package_name);
630
	}
631

    
632
	update_status(gettext("done.") . "\n");
633
}
634

    
635
/* Run <custom_php_resync_config_command> */
636
function sync_package($package_name) {
637
	global $config, $builder_package_install;
638

    
639
	// If this code is being called by pfspkg_installer
640
	// which the builder system uses then return (ignore).
641
	if ($builder_package_install) {
642
		return;
643
	}
644

    
645
	if (empty($config['installedpackages']['package'])) {
646
		return;
647
	}
648

    
649
	if (($pkg_id = get_package_id($package_name)) == -1) {
650
		return; // This package doesn't really exist - exit the function.
651
	}
652

    
653
	if (!is_array($config['installedpackages']['package'][$pkg_id])) {
654
		return;	 // No package belongs to the pkg_id passed to this function.
655
	}
656

    
657
	$package =& $config['installedpackages']['package'][$pkg_id];
658
	if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
659
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
660
		delete_package_xml($package['name']);
661
		return;
662
	}
663

    
664
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
665
	if (isset($pkg_config['nosync'])) {
666
		return;
667
	}
668

    
669
	/* Bring in package include files */
670
	if (!empty($pkg_config['include_file'])) {
671
		$include_file = $pkg_config['include_file'];
672
		if (file_exists($include_file)) {
673
			require_once($include_file);
674
		} else {
675
			log_error(sprintf(gettext('Reinstalling package %1$s because its include file(%2$s) is missing!'), $package['name'], $include_file));
676
			uninstall_package($package['name']);
677
			if (install_package($package['name']) != 0) {
678
				log_error(sprintf(gettext("Reinstalling package %s failed. Take appropriate measures!!!"), $package['name']));
679
				return;
680
			}
681
			if (file_exists($include_file)) {
682
				require_once($include_file);
683
			} else {
684
				return;
685
			}
686
		}
687
	}
688

    
689
	if (!empty($pkg_config['custom_php_global_functions'])) {
690
		eval($pkg_config['custom_php_global_functions']);
691
	}
692
	if (!empty($pkg_config['custom_php_resync_config_command'])) {
693
		eval($pkg_config['custom_php_resync_config_command']);
694
	}
695
}
696

    
697
/* Read info.xml installed by package and return an array */
698
function read_package_config($package_name) {
699
	global $g;
700

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

    
703
	if (!file_exists($pkg_info_xml)) {
704
		return false;
705
	}
706

    
707
	$pkg_info = parse_xml_config_pkg($pkg_info_xml, 'pfsensepkgs');
708

    
709
	if (empty($pkg_info)) {
710
		return false;
711
	}
712

    
713
	/* it always returns an array with 1 item */
714
	return $pkg_info['package'][0];
715
}
716

    
717
/* Read package configurationfile and return an array */
718
function read_package_configurationfile($package_name) {
719
	global $config, $g;
720

    
721
	$pkg_config = array();
722
	$id = get_package_id($package_name);
723

    
724
	if ($id < 0 || !isset($config['installedpackages']['package'][$id]['configurationfile'])) {
725
		return $pkg_config;
726
	}
727

    
728
	$pkg_configurationfile = $config['installedpackages']['package'][$id]['configurationfile'];
729

    
730
	if (empty($pkg_configurationfile) || !file_exists('/usr/local/pkg/' . $pkg_configurationfile)) {
731
		return $pkg_config;
732
	}
733

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

    
736
	return $pkg_config;
737
}
738

    
739
function get_after_install_info($package_name) {
740
	$pkg_config = read_package_config($package_name);
741

    
742
	if (isset($pkg_config['after_install_info'])) {
743
		return $pkg_config['after_install_info'];
744
	}
745

    
746
	return '';
747
}
748

    
749
function eval_once($toeval) {
750
	global $evaled;
751
	if (!$evaled) {
752
		$evaled = array();
753
	}
754
	$evalmd5 = md5($toeval);
755
	if (!in_array($evalmd5, $evaled)) {
756
		@eval($toeval);
757
		$evaled[] = $evalmd5;
758
	}
759
	return;
760
}
761

    
762
function install_package_xml($package_name) {
763
	global $g, $config, $pkg_interface;
764

    
765
	if (($pkg_info = read_package_config($package_name)) == false) {
766
		return false;
767
	}
768

    
769
	/* safe side. Write config below will send to ro again. */
770
	conf_mount_rw();
771

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

    
775
	/* add package information to config.xml */
776
	$pkgid = get_package_id($pkg_info['name']);
777
	update_status(gettext("Saving updated package information...") . "\n");
778
	if ($pkgid == -1) {
779
		$config['installedpackages']['package'][] = $pkg_info;
780
		$changedesc = sprintf(gettext("Installed %s package."), $pkg_info['name']);
781
		$to_output = gettext("done.") . "\n";
782
	} else {
783
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
784
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
785
		$to_output = gettext("overwrite!") . "\n";
786
	}
787
	unlink_if_exists('/conf/needs_package_sync');
788
	write_config(sprintf(gettext("Intermediate config write during package install for %s."), $pkg_info['name']));
789
	conf_mount_ro();
790
	update_status($to_output);
791

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

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

    
802
	if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
803
		update_status(gettext("Loading package configuration... "));
804
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $pkg_info['configurationfile'], "packagegui");
805
		update_status(gettext("done.") . "\n");
806
		update_status(gettext("Configuring package components...") . "\n");
807
		if (!empty($pkg_config['filter_rules_needed'])) {
808
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
809
		}
810
		/* modify system files */
811

    
812
		/* if a require exists, include it.  this will
813
		 * show us where an error exists in a package
814
		 * instead of making us blindly guess
815
		 */
816
		$missing_include = false;
817
		if ($pkg_config['include_file'] <> "") {
818
			update_status(gettext("Loading package instructions...") . "\n");
819
			if (file_exists($pkg_config['include_file'])) {
820
				pkg_debug("require_once('{$pkg_config['include_file']}')\n");
821
				require_once($pkg_config['include_file']);
822
			} else {
823
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
824
				$missing_include = true;
825
				update_status(sprintf(gettext("Include %s is missing!"), basename($pkg_config['include_file'])) . "\n");
826

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

    
835
		/* custom commands */
836
		update_status(gettext("Custom commands...") . "\n");
837
		if ($missing_include == false) {
838
			if ($pkg_config['custom_php_global_functions'] <> "") {
839
				update_status(gettext("Executing custom_php_global_functions()..."));
840
				eval_once($pkg_config['custom_php_global_functions']);
841
				update_status(gettext("done.") . "\n");
842
			}
843
			if ($pkg_config['custom_php_install_command']) {
844
				update_status(gettext("Executing custom_php_install_command()..."));
845
				eval_once($pkg_config['custom_php_install_command']);
846
				update_status(gettext("done.") . "\n");
847
			}
848
			if ($pkg_config['custom_php_resync_config_command'] <> "") {
849
				update_status(gettext("Executing custom_php_resync_config_command()..."));
850
				eval_once($pkg_config['custom_php_resync_config_command']);
851
				update_status(gettext("done.") . "\n");
852
			}
853
		}
854
		/* sidebar items */
855
		if (is_array($pkg_config['menu'])) {
856
			update_status(gettext("Menu items... "));
857
			foreach ($pkg_config['menu'] as $menu) {
858
				if (is_array($config['installedpackages']['menu'])) {
859
					foreach ($config['installedpackages']['menu'] as $amenu) {
860
						if ($amenu['name'] == $menu['name']) {
861
							continue 2;
862
						}
863
					}
864
				} else {
865
					$config['installedpackages']['menu'] = array();
866
				}
867
				$config['installedpackages']['menu'][] = $menu;
868
			}
869
			update_status(gettext("done.") . "\n");
870
		}
871
		/* services */
872
		if (is_array($pkg_config['service'])) {
873
			update_status(gettext("Services... "));
874
			foreach ($pkg_config['service'] as $service) {
875
				if (is_array($config['installedpackages']['service'])) {
876
					foreach ($config['installedpackages']['service'] as $aservice) {
877
						if ($aservice['name'] == $service['name']) {
878
							continue 2;
879
						}
880
					}
881
				} else {
882
					$config['installedpackages']['service'] = array();
883
				}
884
				$config['installedpackages']['service'][] = $service;
885
			}
886
			update_status(gettext("done.") . "\n");
887
		}
888
 		if (is_array($pkg_config['tabs'])) {
889
 			$config['installedpackages']['package'][$pkgid]['tabs'] = $pkg_config['tabs'];			
890
 		}
891
	} else {
892
		pkg_debug("Unable to find config file\n");
893
		update_status(gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted."));
894
		pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n");
895

    
896
		uninstall_package($package_name);
897
		write_config($changedesc);
898
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
899
		update_status(gettext("Failed to install package.") . "\n");
900
		return false;
901
	}
902

    
903
	update_status(gettext("Writing configuration... "));
904
	write_config($changedesc);
905
	log_error(sprintf(gettext("Successfully installed package: %s."), $pkg_info['name']));
906
	update_status(gettext("done.") . "\n");
907
	if ($pkg_info['after_install_info']) {
908
		update_status($pkg_info['after_install_info']);
909
	}
910

    
911
	/* set up package logging streams */
912
	if ($pkg_info['logging']) {
913
		system_syslogd_start(true);
914
	}
915

    
916
	return true;
917
}
918

    
919
function delete_package_xml($package_name, $when = "post-deinstall") {
920
	global $g, $config, $pkg_interface;
921

    
922
	conf_mount_rw();
923

    
924
	$pkgid = get_package_id($package_name);
925
	if ($pkgid == -1) {
926
		update_status(sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $package_name, "\n\n"));
927
		ob_flush();
928
		sleep(1);
929
		conf_mount_ro();
930
		return;
931
	}
932
	pkg_debug(sprintf(gettext("Removing %s package... "), $package_name));
933
	update_status(sprintf(gettext("Removing %s components..."), $package_name) . "\n");
934
	/* parse package configuration */
935
	$packages = &$config['installedpackages']['package'];
936
	$menus =& $config['installedpackages']['menu'];
937
	$services = &$config['installedpackages']['service'];
938
	$pkg_info =& $packages[$pkgid];
939
	if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
940
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui");
941
		/* remove menu items */
942
		if (is_array($pkg_config['menu'])) {
943
			update_status(gettext("Menu items... "));
944
			if (is_array($pkg_config['menu']) && is_array($menus)) {
945
				foreach ($pkg_config['menu'] as $menu) {
946
					foreach ($menus as $key => $instmenu) {
947
						if ($instmenu['name'] == $menu['name']) {
948
							unset($menus[$key]);
949
							break;
950
						}
951
					}
952
				}
953
			}
954
			update_status(gettext("done.") . "\n");
955
		}
956
		/* remove services */
957
		if (is_array($pkg_config['service'])) {
958
			update_status(gettext("Services... "));
959
			if (is_array($pkg_config['service']) && is_array($services)) {
960
				foreach ($pkg_config['service'] as $service) {
961
					foreach ($services as $key => $instservice) {
962
						if ($instservice['name'] == $service['name']) {
963
							if (platform_booting() != true) {
964
								stop_service($service['name']);
965
							}
966
							if ($service['rcfile']) {
967
								$prefix = RCFILEPREFIX;
968
								if (!empty($service['prefix'])) {
969
									$prefix = $service['prefix'];
970
								}
971
								if (file_exists("{$prefix}{$service['rcfile']}")) {
972
									@unlink("{$prefix}{$service['rcfile']}");
973
								}
974
							}
975
							unset($services[$key]);
976
						}
977
					}
978
				}
979
			}
980
			update_status(gettext("done.") . "\n");
981
		}
982
		/*
983
		 * XXX: Otherwise inclusion of config.inc again invalidates actions taken.
984
		 *	Same is done during installation.
985
		 */
986
		write_config(sprintf(gettext("Intermediate config write during package removal for %s."), $package_name));
987

    
988
		/*
989
		 * If a require exists, include it.	 this will
990
		 * show us where an error exists in a package
991
		 * instead of making us blindly guess
992
		 */
993
		$missing_include = false;
994
		if ($pkg_config['include_file'] <> "") {
995
			update_status(gettext("Loading package instructions...") . "\n");
996
			if (file_exists($pkg_config['include_file'])) {
997
				pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n");
998
				require_once($pkg_config['include_file']);
999
			} else {
1000
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
1001
				$missing_include = true;
1002
				update_status(sprintf(gettext("Include file %s could not be found for inclusion."), basename($pkg_config['include_file'])) . "\n");
1003
			}
1004
		}
1005
		/* ermal
1006
		 * NOTE: It is not possible to handle parse errors on eval.
1007
		 * So we prevent it from being run at all to not interrupt all the other code.
1008
		 */
1009
		if ($when == "deinstall" && $missing_include == false) {
1010
			/* evaluate this package's global functions and pre deinstall commands */
1011
			if ($pkg_config['custom_php_global_functions'] <> "") {
1012
				eval_once($pkg_config['custom_php_global_functions']);
1013
			}
1014
			if ($pkg_config['custom_php_pre_deinstall_command'] <> "") {
1015
				eval_once($pkg_config['custom_php_pre_deinstall_command']);
1016
			}
1017
		}
1018
		/* deinstall commands */
1019
		if ($when == "deinstall" && $pkg_config['custom_php_deinstall_command'] <> "") {
1020
			update_status(gettext("Deinstall commands... "));
1021
			if ($missing_include == false) {
1022
				eval_once($pkg_config['custom_php_deinstall_command']);
1023
				update_status(gettext("done.") . "\n");
1024
			} else {
1025
				update_status("\n". gettext("Not executing custom deinstall hook because an include is missing.") . "\n");
1026
			}
1027
		}
1028
	}
1029
	/* syslog */
1030
	$need_syslog_restart = false;
1031
	if (is_array($pkg_info['logging']) && $pkg_info['logging']['logfilename'] <> "") {
1032
		update_status(gettext("Syslog entries... "));
1033
		@unlink_if_exists("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}");
1034
		update_status("done.\n");
1035
		$need_syslog_restart = true;
1036
	}
1037

    
1038
	if ($when == "post-deinstall") {
1039
		/* remove config.xml entries */
1040
		update_status(gettext("Configuration... "));
1041
		unset($config['installedpackages']['package'][$pkgid]);
1042
		update_status(gettext("done.") . "\n");
1043
		write_config(sprintf(gettext("Removed %s package."), $package_name));
1044
		/* remove package entry from /etc/syslog.conf if needed */
1045
		/* this must be done after removing the entries from config.xml */
1046
		if ($need_syslog_restart) {
1047
			system_syslogd_start(true);
1048
		}
1049
	}
1050

    
1051
	conf_mount_ro();
1052
}
1053

    
1054
/*
1055
 * Used during upgrade process or retore backup process, verify all
1056
 * packages installed in config.xml and install pkg accordingly
1057
 */
1058
function package_reinstall_all() {
1059
	global $g, $config, $pkg_interface;
1060

    
1061
	$upgrade = (file_exists('/conf/needs_package_sync') && platform_booting());
1062

    
1063
	if ((!isset($config['installedpackages']['package']) ||
1064
	    !is_array($config['installedpackages']['package'])) && !$upgrade) {
1065
		return true;
1066
	}
1067

    
1068
	/* During boot after upgrade, wait for internet connection */
1069
	if ($upgrade) {
1070
		update_status(gettext("Waiting for Internet connection to update pkg metadata and finish package reinstallation"));
1071
		$ntries = 3;
1072
		while ($ntries > 0) {
1073
			if (pkg_update(true)) {
1074
				break;
1075
			}
1076
			update_status('.');
1077
			sleep(1);
1078
			$ntries--;
1079
		}
1080
		update_status("\n");
1081

    
1082
		if ($ntries == 0) {
1083
			file_notice(gettext("Package reinstall"),
1084
			    gettext("Package reinstall process was ABORTED due to lack of internet connectivity"));
1085
			return false;
1086
		}
1087
	}
1088

    
1089
	$pkg_info = get_pkg_info();
1090

    
1091
	if ($upgrade &&
1092
	    file_exists("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt")) {
1093
		$package_list = file("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt",
1094
		    FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1095
		unlink_if_exists("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt");
1096
	} else {
1097
		if (!isset($config['installedpackages']['package']) || !is_array($config['installedpackages']['package'])) {
1098
			return true;
1099
		}
1100
		$package_list = array();
1101
		foreach ($config['installedpackages']['package'] as $package) {
1102
			$package_list[] = get_package_internal_name($package);
1103
		}
1104
	}
1105

    
1106
	foreach ($package_list as $package) {
1107
		$found = false;
1108
		foreach ($pkg_info as $pkg) {
1109
			pkg_remove_prefix($pkg['name']);
1110
			if ($pkg['name'] == $package) {
1111
				pkg_install($g['pkg_prefix'] . $package, true);
1112
				$found = true;
1113
				break;
1114
			}
1115
		}
1116

    
1117
		if (!$found) {
1118
			if (!function_exists("file_notice")) {
1119
				require_once("notices.inc");
1120
			}
1121

    
1122
			file_notice(gettext("Package reinstall"),
1123
			    sprintf(gettext("Package %s does not exist in current %s version and it has been removed."),
1124
			    $package, $g['product_name']));
1125
			uninstall_package($package);
1126
		}
1127
	}
1128

    
1129
	return true;
1130
}
1131

    
1132
function stop_packages() {
1133
	require_once("config.inc");
1134
	require_once("functions.inc");
1135
	require_once("filter.inc");
1136
	require_once("shaper.inc");
1137
	require_once("captiveportal.inc");
1138
	require_once("pkg-utils.inc");
1139
	require_once("pfsense-utils.inc");
1140
	require_once("service-utils.inc");
1141

    
1142
	global $config, $g;
1143

    
1144
	log_error(gettext("Stopping all packages."));
1145

    
1146
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1147
	if (!$rcfiles) {
1148
		$rcfiles = array();
1149
	} else {
1150
		$rcfiles = array_flip($rcfiles);
1151
		if (!$rcfiles) {
1152
			$rcfiles = array();
1153
		}
1154
	}
1155

    
1156
	if (is_array($config['installedpackages']['package'])) {
1157
		foreach ($config['installedpackages']['package'] as $package) {
1158
			echo " Stopping package {$package['name']}...";
1159
			$internal_name = get_package_internal_name($package);
1160
			stop_service($internal_name);
1161
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1162
			echo "done.\n";
1163
		}
1164
	}
1165

    
1166
	foreach ($rcfiles as $rcfile => $number) {
1167
		$shell = @popen("/bin/sh", "w");
1168
		if ($shell) {
1169
			echo " Stopping {$rcfile}...";
1170
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1171
				if ($shell) {
1172
					pclose($shell);
1173
				}
1174
				$shell = @popen("/bin/sh", "w");
1175
			}
1176
			echo "done.\n";
1177
			pclose($shell);
1178
		}
1179
	}
1180
}
1181

    
1182
/* Identify which meta package is installed */
1183
function get_meta_pkg_name() {
1184
	global $g;
1185

    
1186
	/* XXX: Use pkg annotation */
1187
	if (is_pkg_installed($g['product_name'])) {
1188
		return $g['product_name'];
1189
	} else if (is_pkg_installed($g['product_name'] . '-vmware')) {
1190
		return $g['product_name'] . '-vmware';
1191
	}
1192
	return false;
1193
}
1194

    
1195
/* Identify which base package is installed */
1196
function get_base_pkg_name() {
1197
	global $g;
1198

    
1199
	/* XXX: Use pkg annotation */
1200
	if (is_pkg_installed($g['product_name'] . '-base-' . $g['platform'])) {
1201
		return $g['product_name'] . '-base-' . $g['platform'];
1202
	} else if (is_pkg_installed($g['product_name'] . '-base')) {
1203
		return $g['product_name'] . '-base';
1204
	}
1205
	return false;
1206
}
1207

    
1208
/* Verify if system needs upgrade (meta package or base) */
1209
function get_system_pkg_version($baseonly = false) {
1210
	global $g;
1211

    
1212
	$output = exec("/usr/local/sbin/{$g['product_name']}-upgrade -c", $_gc,
1213
	    $rc);
1214

    
1215
	/* pfSense-upgrade returns 2 when there is a new version */
1216
	if ($rc == 2) {
1217
		$new_version = explode(' ', $output)[0];
1218
	}
1219

    
1220
	$base_pkg = get_base_pkg_name();
1221
	$meta_pkg = get_meta_pkg_name();
1222

    
1223
	if (!$base_pkg || !$meta_pkg) {
1224
		return false;
1225
	}
1226

    
1227
	$info = get_pkg_info($base_pkg, true);
1228

    
1229
	$pkg_info = array();
1230
	foreach ($info as $item) {
1231
		if ($item['name'] == $base_pkg) {
1232
			$pkg_info = $item;
1233
			break;
1234
		}
1235
	}
1236

    
1237
	if (empty($pkg_info) || (!$baseonly && ($pkg_info['version'] ==
1238
	    $pkg_info['installed_version']))) {
1239
		$info = get_pkg_info($meta_pkg, true);
1240

    
1241
		foreach ($info as $item) {
1242
			if ($item['name'] == $meta_pkg) {
1243
				$pkg_info = $item;
1244
				break;
1245
			}
1246
		}
1247
	}
1248

    
1249
	if (empty($pkg_info)) {
1250
		return false;
1251
	}
1252

    
1253
	return array(
1254
	    'version'           => $new_version ?: $pkg_info['version'],
1255
	    'installed_version' => $pkg_info['installed_version']
1256
	);
1257
}
1258

    
1259
/* List available repos */
1260
function pkg_list_repos() {
1261
	global $g;
1262

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

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

    
1267
	$default = array(
1268
	    'name' => 'Default',
1269
	    'path' => $path . "/{$g['product_name']}-repo.conf",
1270
	    'descr' => $default_descr
1271
	);
1272

    
1273
	$result = array($default);
1274

    
1275
	$conf_files = glob("{$path}/{$g['product_name']}-repo-*.conf");
1276
	foreach ($conf_files as $conf_file) {
1277
		$descr_file = preg_replace('/.conf$/', '.descr', $conf_file);
1278
		if (file_exists($descr_file)) {
1279
			$descr_content = file($descr_file);
1280
			$descr = chop($descr_content[0]);
1281
		} else {
1282
			$descr = 'Unknown';
1283
		}
1284
		if (!preg_match('/-repo-(.*).conf/', $conf_file, $matches)) {
1285
			continue;
1286
		}
1287
		$entry = array(
1288
		    'name' => ucfirst(strtolower($matches[1])),
1289
		    'path' => $conf_file,
1290
		    'descr' => $descr
1291
		);
1292
		$result[] = $entry;
1293
	}
1294

    
1295
	return $result;
1296
}
1297

    
1298
/* Switch between stable and devel repos */
1299
function pkg_switch_repo($path) {
1300
	global $g;
1301

    
1302
	safe_mkdir("/usr/local/etc/pkg/repos");
1303
	@unlink("/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1304
	@symlink($path, "/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1305

    
1306
	$abi_file = str_replace('.conf', '.abi', $path);
1307
	$altabi_file = str_replace('.conf', '.altabi', $path);
1308

    
1309
	if (file_exists($abi_file) && file_exists($altabi_file)) {
1310
		$abi = file_get_contents($abi_file);
1311
		$altabi = file_get_contents($altabi_file);
1312

    
1313
		$pkg_conf = array(
1314
			"ABI={$abi}",
1315
			"ALTABI={$altabi}"
1316
		);
1317

    
1318
		file_put_contents("/usr/local/etc/pkg.conf", $pkg_conf);
1319
	}
1320

    
1321
	return pkg_update(true);
1322
}
1323

    
1324
?>
(42-42/67)