Project

General

Profile

Download (41.6 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-2018 Rubicon Communications, LLC (Netgate)
8
 * All rights reserved.
9
 *
10
 * Licensed under the Apache License, Version 2.0 (the "License");
11
 * you may not use this file except in compliance with the License.
12
 * You may obtain a copy of the License at
13
 *
14
 * http://www.apache.org/licenses/LICENSE-2.0
15
 *
16
 * Unless required by applicable law or agreed to in writing, software
17
 * distributed under the License is distributed on an "AS IS" BASIS,
18
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
 * See the License for the specific language governing permissions and
20
 * limitations under the License.
21
 */
22

    
23
require_once("globals.inc");
24
require_once("service-utils.inc");
25

    
26
if (file_exists("/cf/conf/use_xmlreader")) {
27
	require_once("xmlreader.inc");
28
} else {
29
	require_once("xmlparse.inc");
30
}
31

    
32
require_once("pfsense-utils.inc");
33

    
34
if (!function_exists("pkg_debug")) {
35
	/* set up logging if needed */
36
	function pkg_debug($msg) {
37
		global $g, $debug, $fd_log;
38

    
39
		if (!$debug) {
40
			return;
41
		}
42

    
43
		if (!$fd_log) {
44
			if (!$fd_log = fopen("{$g['tmp_path']}/pkg_mgr_debug.log", "w")) {
45
				update_status(gettext("Warning, could not open log for writing.") . "\n");
46
			}
47
		}
48
		@fwrite($fd_log, $msg);
49
	}
50
}
51

    
52
/* Validate if pkg name is valid */
53
function pkg_valid_name($pkgname) {
54
	global $g;
55

    
56
	$pattern = "/^{$g['pkg_prefix']}[a-zA-Z0-9\.\-_]+$/";
57
	return preg_match($pattern, $pkgname);
58
}
59

    
60
/* Remove pkg_prefix from package name if it's present */
61
function pkg_remove_prefix(&$pkg_name) {
62
	global $g;
63

    
64
	if (substr($pkg_name, 0, strlen($g['pkg_prefix'])) == $g['pkg_prefix']) {
65
		$pkg_name = substr($pkg_name, strlen($g['pkg_prefix']));
66
	}
67
}
68

    
69
/* Execute pkg update when it's necessary */
70
function pkg_update($force = false) {
71
	global $g;
72

    
73
	return pkg_call("update" . ($force ? " -f" : ""));
74
}
75

    
76
/* return an array with necessary environment vars for pkg */
77
function pkg_env($extra_env = array()) {
78
	global $config, $g;
79

    
80
	$user_agent = $g['product_name'] . '/' . $g['product_version'];
81
	if (!isset($config['system']['do_not_send_uniqueid'])) {
82
		$user_agent .= ':' . system_get_uniqueid();
83
	}
84

    
85
	$pkg_env_vars = array(
86
		"LANG" => "C",
87
		"HTTP_USER_AGENT" => $user_agent,
88
		"ASSUME_ALWAYS_YES" => "true",
89
		"FETCH_TIMEOUT" => 5,
90
		"FETCH_RETRY" => 2
91
	);
92

    
93
	if (!empty($config['system']['proxyurl'])) {
94
		$http_proxy = $config['system']['proxyurl'];
95
		if (!empty($config['system']['proxyport'])) {
96
			$http_proxy .= ':' . $config['system']['proxyport'];
97
		}
98
		$pkg_env_vars['HTTP_PROXY'] = $http_proxy;
99

    
100
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
101
			$pkg_env_vars['HTTP_PROXY_AUTH'] = "basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
102
		}
103
	}
104

    
105
	if (isset($config['system']['use_mfs_tmpvar'])) {
106
		$pkg_env_vars['PKG_DBDIR'] = '/root/var/db/pkg';
107
		$pkg_env_vars['PKG_CACHEDIR'] = '/root/var/cache/pkg';
108
	}
109

    
110
	foreach ($extra_env as $key => $value) {
111
		$pkg_env_vars[$key] = $value;
112
	}
113

    
114
	return $pkg_env_vars;
115
}
116

    
117
/* Execute a pkg call */
118
function pkg_call($params, $mute = false, $extra_env = array()) {
119
	global $g, $config;
120

    
121
	if (empty($params)) {
122
		return false;
123
	}
124

    
125
	$descriptorspec = array(
126
		1 => array("pipe", "w"), /* stdout */
127
		2 => array("pipe", "w")	 /* stderr */
128
	);
129

    
130
	pkg_debug("pkg_call(): {$params}\n");
131
	$process = proc_open("/usr/local/sbin/pkg-static {$params}",
132
	    $descriptorspec, $pipes, '/', pkg_env($extra_env));
133

    
134
	if (!is_resource($process)) {
135
		return false;
136
	}
137

    
138
	stream_set_blocking($pipes[1], 0);
139
	stream_set_blocking($pipes[2], 0);
140

    
141
	/* XXX: should be a tunnable? */
142
	$timeout = 60; // seconds
143
	$error_log = '';
144

    
145
	do {
146
		$write = array();
147
		$read = array($pipes[1], $pipes[2]);
148
		$except = array();
149

    
150
		$stream = stream_select($read, $write, $except, $timeout);
151
		if ($stream !== FALSE && $stream > 0) {
152
			foreach ($read as $pipe) {
153
				$content = stream_get_contents($pipe);
154
				if ($content == '') {
155
					continue;
156
				}
157
				if ($pipe === $pipes[1]) {
158
					if (!$mute) {
159
						update_status($content);
160
					}
161
					flush();
162
				} else if ($pipe === $pipes[2]) {
163
					$error_log .= $content;
164
				}
165
			}
166
		}
167

    
168
		$status = proc_get_status($process);
169
	} while ($status['running']);
170

    
171
	fclose($pipes[1]);
172
	fclose($pipes[2]);
173
	proc_close($process);
174

    
175

    
176
	$rc = $status['exitcode'];
177

    
178
	pkg_debug("pkg_call(): rc = {$rc}\n");
179
	if ($rc == 0) {
180
		return true;
181
	}
182

    
183
	pkg_debug("pkg_call(): error_log\n{$error_log}\n");
184
	if (!$mute) {
185
		update_status("\n\n" .  sprintf(gettext(
186
		    "ERROR!!! An error occurred on pkg execution (rc = %d) with parameters '%s':"),
187
		    $rc, $params) . "\n" . $error_log . "\n");
188
	}
189

    
190
	return false;
191
}
192

    
193
/* Execute pkg with $params, fill stdout and stderr and return pkg rc */
194
function pkg_exec($params, &$stdout, &$stderr, $extra_env = array()) {
195
	global $g, $config;
196

    
197
	if (empty($params)) {
198
		return -1;
199
	}
200

    
201
	$descriptorspec = array(
202
		1 => array("pipe", "w"), /* stdout */
203
		2 => array("pipe", "w")	 /* stderr */
204
	);
205

    
206

    
207
	pkg_debug("pkg_exec(): {$params}\n");
208
	$process = proc_open("/usr/local/sbin/pkg-static {$params}",
209
	    $descriptorspec, $pipes, '/', pkg_env($extra_env));
210

    
211
	if (!is_resource($process)) {
212
		return -1;
213
	}
214

    
215
	$stdout = '';
216
	while (($l = fgets($pipes[1])) !== FALSE) {
217
		$stdout .= $l;
218
	}
219
	fclose($pipes[1]);
220

    
221
	$stderr = '';
222
	while (($l = fgets($pipes[2])) !== FALSE) {
223
		$stderr .= $l;
224
	}
225
	fclose($pipes[2]);
226

    
227

    
228
	return proc_close($process);
229
}
230

    
231
/* Compare 2 pkg versions and return:
232
 * '=' - versions are the same
233
 * '>' - $v1 > $v2
234
 * '<' - $v1 < $v2
235
 * '?' - Error
236
 */
237
function pkg_version_compare($v1, $v2) {
238
	if (empty($v1) || empty($v2)) {
239
		return '?';
240
	}
241

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

    
244
	if ($rc != 0) {
245
		return '?';
246
	}
247

    
248
	return str_replace("\n", "", $stdout);
249
}
250

    
251
/* Check if package is installed */
252
function is_pkg_installed($pkg_name) {
253
	global $g;
254

    
255
	if (empty($pkg_name)) {
256
		return false;
257
	}
258

    
259
	return pkg_call("info -e " . $pkg_name, true);
260
}
261

    
262
/* Install package, $pkg_name should not contain prefix */
263
function pkg_install($pkg_name, $force = false) {
264
	global $g;
265
	$result = false;
266

    
267
	$shortname = $pkg_name;
268
	pkg_remove_prefix($shortname);
269

    
270
	$pkg_force = "";
271
	if ($force) {
272
		$pkg_force = "-f ";
273
	}
274

    
275
	pkg_debug("Installing package {$shortname}\n");
276
	if ($force || !is_pkg_installed($pkg_name)) {
277
		$result = pkg_call("install -y " . $pkg_force . $pkg_name);
278
		/* Cleanup cacke to free disk space */
279
		pkg_call("clean -y");
280
	}
281

    
282
	return $result;
283
}
284

    
285
/* Delete package from FreeBSD, $pkg_name should not contain prefix */
286
function pkg_delete($pkg_name) {
287
	global $g;
288

    
289
	$shortname = $pkg_name;
290
	pkg_remove_prefix($shortname);
291

    
292
	pkg_debug("Removing package {$shortname}\n");
293
	if (is_pkg_installed($pkg_name)) {
294
		pkg_call("delete -y " . $pkg_name);
295
		/* Cleanup unecessary dependencies */
296
		pkg_call("autoremove -y");
297
	}
298
}
299

    
300
/* Check if package is present in config.xml */
301
function is_package_installed($package_name) {
302
	return (get_package_id($package_name) != -1);
303
}
304

    
305
/* Find package array index */
306
function get_package_id($package_name) {
307
	global $config;
308

    
309
	if (!is_array($config['installedpackages']['package'])) {
310
		return -1;
311
	}
312

    
313
	foreach ($config['installedpackages']['package'] as $idx => $pkg) {
314
		if ($pkg['name'] == $package_name ||
315
		    get_package_internal_name($pkg) == $package_name) {
316
			return $idx;
317
		}
318
	}
319

    
320
	return -1;
321
}
322

    
323
/* Return internal_name when it's defined, otherwise, returns name */
324
function get_package_internal_name($package_data) {
325
	if (isset($package_data['internal_name']) && ($package_data['internal_name'] != "")) {
326
		/* e.g. name is Ipguard-dev, internal name is ipguard */
327
		return $package_data['internal_name'];
328
	} else {
329
		return $package_data['name'];
330
	}
331
}
332

    
333
// Get information about packages.
334
function get_pkg_info($pkgs = 'all', $remote_repo_usage_disabled = false,
335
    $installed_pkgs_only = false) {
336
	global $g, $input_errors;
337

    
338
	$out = $err = $extra_param = '';
339
	$rc = 0;
340

    
341
	unset($pkg_filter);
342

    
343
	if (is_array($pkgs)) {
344
		$pkg_filter = $pkgs;
345
		$pkgs = $g['pkg_prefix'] . '*';
346
	} elseif ($pkgs == 'all') {
347
		$pkgs = $g['pkg_prefix'] . '*';
348
	}
349

    
350
	$base_packages = (substr($pkgs, 0, strlen($g['pkg_prefix'])) !=
351
	    $g['pkg_prefix']);
352

    
353
	if ($installed_pkgs_only && !is_pkg_installed($pkgs)) {
354
		/*
355
		 * Return early if the caller wants just installed packages
356
		 * and there are none.  Saves doing any calls that might
357
		 * access a remote package repo.
358
		 */
359
		return array();
360
	}
361

    
362
	if (!function_exists('is_subsystem_dirty')) {
363
		require_once("util.inc");
364
	}
365

    
366
	/* Do not run remote operations if pkg has a lock */
367
	if (is_subsystem_dirty('pkg')) {
368
		$remote_repo_usage_disabled = true;
369
		$lock = false;
370
	} else {
371
		$lock = true;
372
	}
373

    
374
	if ($lock) {
375
		mark_subsystem_dirty('pkg');
376
	}
377

    
378
	if ($remote_repo_usage_disabled) {
379
		$extra_param = "-U ";
380
	}
381

    
382
	$did_search = false;
383
	$search_rc = 0;
384
	$info_rc = 0;
385
	$search_items = array();
386
	$info_items = array();
387

    
388
	if ($base_packages) {
389
		$repo_param = "";
390
	} else {
391
		$repo_param = "-r {$g['product_name']}";
392
	}
393

    
394
	/*
395
	 * If we want more than just the currently installed packages or
396
	 * we want up-to-date remote repo info then do a full pkg search
397
	 */
398
	if (!$installed_pkgs_only || !$remote_repo_usage_disabled) {
399
		$did_search = true;
400
		$search_rc = pkg_exec("search {$repo_param} " .
401
		    "{$extra_param}-R --raw-format json-compact " .
402
		    $pkgs, $search_out, $search_err);
403
		if ($search_rc == 0) {
404
			$search_items = explode("\n", chop($search_out));
405
			array_walk($search_items, function(&$v, &$k) {
406
				$v = json_decode($v, true);
407
			});
408
		}
409
	}
410

    
411
	/*
412
	 * We always should look for local items to detect packages that
413
	 * were removed from remote repo but are already installed locally
414
	 *
415
	 * Take pkg search return code into consideration to fallback to local
416
	 * information when remote repo is not accessible
417
	 */
418
	if (is_pkg_installed($pkgs) || $search_rc != 0) {
419
		$info_rc = pkg_exec("info -R --raw-format json-compact " .
420
		    $pkgs, $info_out, $info_err);
421
		if ($info_rc == 0) {
422
			$info_items = explode("\n", chop($info_out));
423
			array_walk($info_items, function(&$v, &$k) {
424
				$v = json_decode($v, true);
425
			});
426
		}
427
	}
428

    
429
	if ($lock) {
430
		clear_subsystem_dirty('pkg');
431
	}
432

    
433
	if ($search_rc != 0 && $info_rc != 0) {
434
		update_status("\n" . gettext(
435
		    "ERROR: Error trying to get packages list. Aborting...")
436
		    . "\n");
437
		update_status($search_err . "\n" . $info_err);
438
		$input_errors[] = gettext(
439
		    "ERROR: Error trying to get packages list. Aborting...") .
440
		    "\n";
441
		$input_errors[] = $search_err . "\n" . $info_err;
442
		return array();
443
	}
444

    
445
	/* It was not possible to search, use local information only */
446
	if ($search_rc != 0 || !$did_search) {
447
		$search_items = $info_items;
448
	} else {
449
		foreach ($info_items as $pkg_info) {
450
			if (empty($pkg_info['name'])) {
451
				continue;
452
			}
453

    
454
			if (array_search($pkg_info['name'], array_column(
455
			    $search_items, 'name')) === FALSE) {
456
				$pkg_info['obsolete'] = true;
457
				$search_items[] = $pkg_info;
458
			}
459
		}
460
	}
461

    
462
	$result = array();
463
	foreach ($search_items as $pkg_info) {
464
		if (empty($pkg_info['name'])) {
465
			continue;
466
		}
467

    
468
		if (isset($pkg_filter) && !in_array($pkg_info['name'],
469
		    $pkg_filter)) {
470
			continue;
471
		}
472

    
473
		$pkg_info['shortname'] = $pkg_info['name'];
474
		pkg_remove_prefix($pkg_info['shortname']);
475

    
476
		/* XXX: Add it to globals.inc? */
477
		$pkg_info['changeloglink'] =
478
		    "https://github.com/pfsense/FreeBSD-ports/commits/devel/" .
479
		    $pkg_info['categories'][0] . '/' . $pkg_info['name'];
480

    
481
		$pkg_is_installed = false;
482

    
483
		if (is_pkg_installed($pkg_info['name'])) {
484
			$rc = pkg_exec("query %R {$pkg_info['name']}", $out,
485
			    $err);
486
			if (!$base_packages &&
487
			    rtrim($out) != $g['product_name']) {
488
				continue;
489
			}
490

    
491
			$pkg_info['installed'] = true;
492
			$pkg_is_installed = true;
493

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

    
497
			if ($rc != 0) {
498
				update_status("\n" . gettext("ERROR: Error " .
499
				    "trying to get package version. " .
500
				    "Aborting...") . "\n");
501
				update_status($err);
502
				$input_errors[] = gettext("ERROR: Error " .
503
				    "trying to get package version. " .
504
				    "Aborting...") . "\n";
505
				$input_errors[] = $err;
506
				return array();
507
			}
508

    
509
			$pkg_info['installed_version'] = str_replace("\n", "",
510
			    $out);
511

    
512
			/*
513
			 * We used pkg info to collect pkg data so remote
514
			 * version is not available. Lets try to collect it
515
			 * using rquery if possible
516
			 */
517
			if ($search_rc != 0 || !$did_search) {
518
				$rc = pkg_exec(
519
				    "rquery -U %v {$pkg_info['name']}", $out,
520
				    $err);
521

    
522
				if ($rc == 0) {
523
					$pkg_info['version'] =
524
					    str_replace("\n", "", $out);
525
				}
526
			}
527

    
528
		} else if (is_package_installed($pkg_info['shortname'])) {
529
			$pkg_info['broken'] = true;
530
			$pkg_is_installed = true;
531
		}
532

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

    
536
		if (!$installed_pkgs_only || $pkg_is_installed) {
537
			$result[] = $pkg_info;
538
		}
539
		unset($pkg_info);
540
	}
541

    
542
	/* Sort result alphabetically */
543
	usort($result, function($a, $b) {
544
		return(strcasecmp ($a['name'], $b['name']));
545
	});
546

    
547
	return $result;
548
}
549

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

    
561
	$pkg_info = get_pkg_info('all', true, true);
562

    
563
	foreach ($pkg_info as $pkg) {
564
		pkg_remove_prefix($pkg['name']);
565

    
566
		if (is_package_installed($pkg['name'])) {
567
			continue;
568
		}
569

    
570
		update_status(sprintf(gettext(
571
		    "Running last steps of %s installation.") . "\n",
572
		    $pkg['name']));
573
		install_package_xml($pkg['name']);
574
	}
575
}
576

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

    
584
	log_error(gettext("Resyncing configuration for all packages."));
585

    
586
	if (!is_array($config['installedpackages']['package'])) {
587
		return;
588
	}
589

    
590
	if ($show_message == true) {
591
		echo "Syncing packages:";
592
	}
593

    
594

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

    
609
	if ($show_message == true) {
610
		echo " done.\n";
611
	}
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
function reinstall_package($package_name) {
636
	global $config, $g;
637

    
638
	$internal_name = $package_name;
639
	$id = get_package_id($package_name);
640
	if ($id >= 0) {
641
		$internal_name = get_package_internal_name($config['installedpackages']['package'][$id]);
642
	}
643
	$pkg_name = $g['pkg_prefix'] . $internal_name;
644
	pkg_install($pkg_name);
645
}
646

    
647
/* Run <custom_php_resync_config_command> */
648
function sync_package($package_name) {
649
	global $config, $builder_package_install;
650

    
651
	// If this code is being called by pfspkg_installer
652
	// which the builder system uses then return (ignore).
653
	if ($builder_package_install) {
654
		return;
655
	}
656

    
657
	if (empty($config['installedpackages']['package'])) {
658
		return;
659
	}
660

    
661
	if (($pkg_id = get_package_id($package_name)) == -1) {
662
		return; // This package doesn't really exist - exit the function.
663
	}
664

    
665
	if (!is_array($config['installedpackages']['package'][$pkg_id])) {
666
		return;	 // No package belongs to the pkg_id passed to this function.
667
	}
668

    
669
	$package =& $config['installedpackages']['package'][$pkg_id];
670
	if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
671
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
672
		delete_package_xml($package['name']);
673
		return;
674
	}
675

    
676
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
677
	if (isset($pkg_config['nosync'])) {
678
		return;
679
	}
680

    
681
	/* Bring in package include files */
682
	if (!empty($pkg_config['include_file'])) {
683
		$include_file = $pkg_config['include_file'];
684
		if (file_exists($include_file)) {
685
			require_once($include_file);
686
		} else {
687
			log_error(sprintf(gettext('Reinstalling package %1$s because its include file(%2$s) is missing!'), $package['name'], $include_file));
688
			uninstall_package($package['name']);
689
			if (reinstall_package($package['name']) != 0) {
690
				log_error(sprintf(gettext("Reinstalling package %s failed. Take appropriate measures!!!"), $package['name']));
691
				return;
692
			}
693
			if (file_exists($include_file)) {
694
				require_once($include_file);
695
			} else {
696
				return;
697
			}
698
		}
699
	}
700

    
701
	if (!empty($pkg_config['custom_php_global_functions'])) {
702
		eval($pkg_config['custom_php_global_functions']);
703
	}
704
	if (!empty($pkg_config['custom_php_resync_config_command'])) {
705
		eval($pkg_config['custom_php_resync_config_command']);
706
	}
707
}
708

    
709
/* Read info.xml installed by package and return an array */
710
function read_package_config($package_name) {
711
	global $g;
712

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

    
715
	if (!file_exists($pkg_info_xml)) {
716
		return false;
717
	}
718

    
719
	$pkg_info = parse_xml_config_pkg($pkg_info_xml, 'pfsensepkgs');
720

    
721
	if (empty($pkg_info)) {
722
		return false;
723
	}
724

    
725
	/* it always returns an array with 1 item */
726
	return $pkg_info['package'][0];
727
}
728

    
729
/* Read package configurationfile and return an array */
730
function read_package_configurationfile($package_name) {
731
	global $config, $g;
732

    
733
	$pkg_config = array();
734
	$id = get_package_id($package_name);
735

    
736
	if ($id < 0 || !isset($config['installedpackages']['package'][$id]['configurationfile'])) {
737
		return $pkg_config;
738
	}
739

    
740
	$pkg_configurationfile = $config['installedpackages']['package'][$id]['configurationfile'];
741

    
742
	if (empty($pkg_configurationfile) || !file_exists('/usr/local/pkg/' . $pkg_configurationfile)) {
743
		return $pkg_config;
744
	}
745

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

    
748
	return $pkg_config;
749
}
750

    
751
function get_after_install_info($package_name) {
752
	$pkg_config = read_package_config($package_name);
753

    
754
	if (isset($pkg_config['after_install_info'])) {
755
		return $pkg_config['after_install_info'];
756
	}
757

    
758
	return '';
759
}
760

    
761
function eval_once($toeval) {
762
	global $evaled;
763
	if (!$evaled) {
764
		$evaled = array();
765
	}
766
	$evalmd5 = md5($toeval);
767
	if (!in_array($evalmd5, $evaled)) {
768
		@eval($toeval);
769
		$evaled[] = $evalmd5;
770
	}
771
	return;
772
}
773

    
774
function install_package_xml($package_name) {
775
	global $g, $config, $pkg_interface;
776

    
777
	if (($pkg_info = read_package_config($package_name)) == false) {
778
		return false;
779
	}
780

    
781
	/* safe side. Write config below will send to ro again. */
782

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

    
786
	/* add package information to config.xml */
787
	$pkgid = get_package_id($pkg_info['name']);
788
	update_status(gettext("Saving updated package information...") . "\n");
789
	if ($pkgid == -1) {
790
		$config['installedpackages']['package'][] = $pkg_info;
791
		$changedesc = sprintf(gettext("Installed %s package."), $pkg_info['name']);
792
		$to_output = gettext("done.") . "\n";
793
	} else {
794
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
795
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
796
		$to_output = gettext("overwrite!") . "\n";
797
	}
798
	write_config(sprintf(gettext("Intermediate config write during package install for %s."), $pkg_info['name']));
799
	update_status($to_output);
800

    
801
	if (($pkgid = get_package_id($package_name)) == -1) {
802
		update_status(sprintf(gettext('The %1$s package is not installed.%2$sInstallation aborted.'), $package_name, "\n\n"));
803

    
804
		uninstall_package($package_name);
805
		write_config($changedesc);
806
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
807
		update_status(gettext("Failed to install package.") . "\n");
808
		return false;
809
	}
810

    
811
	if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
812
		update_status(gettext("Loading package configuration... "));
813
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $pkg_info['configurationfile'], "packagegui");
814
		update_status(gettext("done.") . "\n");
815
		update_status(gettext("Configuring package components...") . "\n");
816
		if (!empty($pkg_config['filter_rules_needed'])) {
817
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
818
		}
819
		/* modify system files */
820

    
821
		/* if a require exists, include it.  this will
822
		 * show us where an error exists in a package
823
		 * instead of making us blindly guess
824
		 */
825
		$missing_include = false;
826
		if ($pkg_config['include_file'] <> "") {
827
			update_status(gettext("Loading package instructions...") . "\n");
828
			if (file_exists($pkg_config['include_file'])) {
829
				pkg_debug("require_once('{$pkg_config['include_file']}')\n");
830
				require_once($pkg_config['include_file']);
831
			} else {
832
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
833
				$missing_include = true;
834
				update_status(sprintf(gettext("Include %s is missing!"), basename($pkg_config['include_file'])) . "\n");
835

    
836
				uninstall_package($package_name);
837
				write_config($changedesc);
838
				log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
839
				update_status(gettext("Failed to install package.") . "\n");
840
				return false;
841
			}
842
		}
843

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

    
912
		uninstall_package($package_name);
913
		write_config($changedesc);
914
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
915
		update_status(gettext("Failed to install package.") . "\n");
916
		return false;
917
	}
918

    
919
	update_status(gettext("Writing configuration... "));
920
	write_config($changedesc);
921
	log_error(sprintf(gettext("Successfully installed package: %s."), $pkg_info['name']));
922
	update_status(gettext("done.") . "\n");
923
	if ($pkg_info['after_install_info']) {
924
		update_status($pkg_info['after_install_info']);
925
	}
926

    
927
	/* set up package logging streams */
928
	if ($pkg_info['logging']) {
929
		system_syslogd_start(true);
930
	}
931

    
932
	return true;
933
}
934

    
935
function delete_package_xml($package_name, $when = "post-deinstall") {
936
	global $g, $config, $pkg_interface;
937

    
938

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

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

    
1052
	if ($when == "post-deinstall") {
1053
		/* remove config.xml entries */
1054
		update_status(gettext("Configuration... "));
1055
		unset($config['installedpackages']['package'][$pkgid]);
1056
		update_status(gettext("done.") . "\n");
1057
		write_config(sprintf(gettext("Removed %s package."), $package_name));
1058
		/* remove package entry from /etc/syslog.conf if needed */
1059
		/* this must be done after removing the entries from config.xml */
1060
		if ($need_syslog_restart) {
1061
			system_syslogd_start(true);
1062
		}
1063
	}
1064
}
1065

    
1066
/*
1067
 * Used during upgrade process or retore backup process, verify all
1068
 * packages installed in config.xml and install pkg accordingly
1069
 */
1070
function package_reinstall_all() {
1071
	global $g, $config, $pkg_interface;
1072

    
1073
	if (!isset($config['installedpackages']['package']) ||
1074
	    !is_array($config['installedpackages']['package'])) {
1075
		return true;
1076
	}
1077

    
1078
	/*
1079
	 * Configure default pkg repo for current version instead of
1080
	 * using it from backup, that could be older
1081
	 */
1082
	$default_repo = pkg_get_default_repo();
1083
	$current_repo_path = "";
1084
	if (!empty($config['system']['pkg_repo_conf_path'])) {
1085
		$current_repo_path = $config['system']['pkg_repo_conf_path'];
1086
	}
1087

    
1088
	if ($current_repo_path != $default_repo['path']) {
1089
		$config['system']['pkg_repo_conf_path'] = $default_repo['path'];
1090
		write_config( "Configured default pkg repo after restore");
1091
		pkg_switch_repo($default_repo['path']);
1092
	}
1093

    
1094
	/* wait for internet connection */
1095
	log_error(gettext("Waiting for Internet connection to update pkg " .
1096
	    "metadata and finish package reinstallation"));
1097
	$ntries = 3;
1098
	while ($ntries > 0) {
1099
		if (pkg_update(true)) {
1100
			break;
1101
		}
1102
		sleep(1);
1103
		$ntries--;
1104
	}
1105

    
1106
	if ($ntries == 0) {
1107
		return false;
1108
	}
1109

    
1110
	$package_list = array();
1111
	foreach ($config['installedpackages']['package'] as $package) {
1112
		$package_list[] = get_package_internal_name($package);
1113
	}
1114

    
1115
	if (!empty($package_list)) {
1116
		$pkg_info = get_pkg_info();
1117
	}
1118

    
1119
	foreach ($package_list as $package) {
1120
		$found = false;
1121
		foreach ($pkg_info as $pkg) {
1122
			pkg_remove_prefix($pkg['name']);
1123
			if ($pkg['name'] == $package) {
1124
				pkg_install($g['pkg_prefix'] . $package, true);
1125
				$found = true;
1126
				break;
1127
			}
1128
		}
1129

    
1130
		if (!$found) {
1131
			if (!function_exists("file_notice")) {
1132
				require_once("notices.inc");
1133
			}
1134

    
1135
			file_notice(gettext("Package reinstall"),
1136
			    sprintf(gettext("Package %s does not exist in " .
1137
			    "current %s version and it has been removed."),
1138
			    $package, $g['product_name']));
1139
			uninstall_package($package);
1140
		}
1141
	}
1142

    
1143
	/*
1144
	 * Verify remaining binary packages not present in current config
1145
	 * during backup restore and remove them
1146
	 */
1147
	$installed_packages = get_pkg_info('all', true, true);
1148
	foreach ($installed_packages as $package) {
1149
		$shortname = $package['name'];
1150
		pkg_remove_prefix($shortname);
1151
		if (get_package_id($shortname) != -1) {
1152
			continue;
1153
		}
1154
		pkg_delete($package['name']);
1155
	}
1156

    
1157
	return true;
1158
}
1159

    
1160
function stop_packages() {
1161
	require_once("config.inc");
1162
	require_once("functions.inc");
1163
	require_once("filter.inc");
1164
	require_once("shaper.inc");
1165
	require_once("captiveportal.inc");
1166
	require_once("pkg-utils.inc");
1167
	require_once("pfsense-utils.inc");
1168
	require_once("service-utils.inc");
1169

    
1170
	global $config, $g;
1171

    
1172
	log_error(gettext("Stopping all packages."));
1173

    
1174
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1175
	if (!$rcfiles) {
1176
		$rcfiles = array();
1177
	} else {
1178
		$rcfiles = array_flip($rcfiles);
1179
		if (!$rcfiles) {
1180
			$rcfiles = array();
1181
		}
1182
	}
1183

    
1184
	if (is_array($config['installedpackages']['package'])) {
1185
		foreach ($config['installedpackages']['package'] as $package) {
1186
			echo " Stopping package {$package['name']}...";
1187
			$internal_name = get_package_internal_name($package);
1188
			stop_service($internal_name);
1189
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1190
			echo "done.\n";
1191
		}
1192
	}
1193

    
1194
	foreach ($rcfiles as $rcfile => $number) {
1195
		$shell = @popen("/bin/sh", "w");
1196
		if ($shell) {
1197
			echo " Stopping {$rcfile}...";
1198
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1199
				if ($shell) {
1200
					pclose($shell);
1201
				}
1202
				$shell = @popen("/bin/sh", "w");
1203
			}
1204
			echo "done.\n";
1205
			pclose($shell);
1206
		}
1207
	}
1208
}
1209

    
1210
/* Identify which meta package is installed */
1211
function get_meta_pkg_name() {
1212
	global $g;
1213

    
1214
	/* XXX: Use pkg annotation */
1215
	if (is_pkg_installed($g['product_name'])) {
1216
		return $g['product_name'];
1217
	}
1218
	foreach ($g['alternativemetaports'] as $suffix) {
1219
		if (is_pkg_installed($g['product_name'] . '-' . $suffix)) {
1220
			return $g['product_name'] . '-' . $suffix;
1221
		}
1222
	}
1223
	return false;
1224
}
1225

    
1226
/* Identify which base package is installed */
1227
function get_base_pkg_name() {
1228
	global $g;
1229

    
1230
	/* XXX: Use pkg annotation */
1231
	if (is_pkg_installed($g['product_name'] . '-base-' . $g['platform'])) {
1232
		return $g['product_name'] . '-base-' . $g['platform'];
1233
	} else if (is_pkg_installed($g['product_name'] . '-base')) {
1234
		return $g['product_name'] . '-base';
1235
	}
1236
	return false;
1237
}
1238

    
1239
/* Verify if system needs upgrade (meta package or base) */
1240
function get_system_pkg_version($baseonly = false, $use_cache = true) {
1241
	global $g;
1242

    
1243
	$cache_file = $g['version_cache_file'];
1244
	$rc_file = $cache_file . '.rc';
1245

    
1246
	$rc = "";
1247
	if ($use_cache && file_exists($rc_file) &&
1248
	    (time()-filemtime($rc_file) < $g['version_cache_refresh'])) {
1249
		$rc = chop(@file_get_contents($rc_file));
1250
	}
1251

    
1252
	if ($rc == "2") {
1253
		$output = @file_get_contents($cache_file);
1254
	} else if ($rc != "0") {
1255
		$output = exec(
1256
		    "/usr/local/sbin/{$g['product_name']}-upgrade -c", $_gc,
1257
		    $rc);
1258

    
1259
		/* Update cache if it succeeded */
1260
		if ($rc == 0 || $rc == 2) {
1261
			@file_put_contents($cache_file, $output);
1262
			@file_put_contents($rc_file, $rc);
1263
		}
1264
	}
1265

    
1266
	/* pfSense-upgrade returns 2 when there is a new version */
1267
	if ($rc == "2") {
1268
		$new_version = explode(' ', $output)[0];
1269
	}
1270

    
1271
	$base_pkg = get_base_pkg_name();
1272
	$meta_pkg = get_meta_pkg_name();
1273

    
1274
	if (!$base_pkg || !$meta_pkg) {
1275
		return false;
1276
	}
1277

    
1278
	$info = get_pkg_info($base_pkg, true, true);
1279

    
1280
	$pkg_info = array();
1281
	foreach ($info as $item) {
1282
		if ($item['name'] == $base_pkg) {
1283
			$pkg_info = $item;
1284
			break;
1285
		}
1286
	}
1287

    
1288
	if (empty($pkg_info) || (!$baseonly && ($pkg_info['version'] ==
1289
	    $pkg_info['installed_version']))) {
1290
		$info = get_pkg_info($meta_pkg, true, true);
1291

    
1292
		foreach ($info as $item) {
1293
			if ($item['name'] == $meta_pkg) {
1294
				$pkg_info = $item;
1295
				break;
1296
			}
1297
		}
1298
	}
1299

    
1300
	if (empty($pkg_info)) {
1301
		return false;
1302
	}
1303

    
1304
	$result = array(
1305
	    'version'           => $new_version ?: $pkg_info['version'],
1306
	    'installed_version' => $pkg_info['installed_version']
1307
	);
1308

    
1309
	$result['pkg_version_compare'] = pkg_version_compare(
1310
	    $result['installed_version'], $result['version']);
1311

    
1312
	return $result;
1313
}
1314

    
1315
/* List available repos */
1316
function pkg_list_repos() {
1317
	global $g;
1318

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

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

    
1323
	$default = array(
1324
	    'name' => 'Default',
1325
	    'path' => $path . "/{$g['product_name']}-repo.conf",
1326
	    'descr' => $default_descr
1327
	);
1328

    
1329
	$result = array($default);
1330

    
1331
	$conf_files = glob("{$path}/{$g['product_name']}-repo-*.conf");
1332
	foreach ($conf_files as $conf_file) {
1333
		$descr_file = preg_replace('/.conf$/', '.descr', $conf_file);
1334
		if (file_exists($descr_file)) {
1335
			$descr_content = file($descr_file);
1336
			$descr = chop($descr_content[0]);
1337
		} else {
1338
			$descr = 'Unknown';
1339
		}
1340
		if (!preg_match('/-repo-(.*).conf/', $conf_file, $matches)) {
1341
			continue;
1342
		}
1343
		$entry = array(
1344
		    'name' => ucfirst(strtolower($matches[1])),
1345
		    'path' => $conf_file,
1346
		    'descr' => $descr
1347
		);
1348
		if (file_exists($conf_file . ".default")) {
1349
			$entry['default'] = true;
1350
		}
1351
		$result[] = $entry;
1352
	}
1353

    
1354
	return $result;
1355
}
1356

    
1357
function pkg_get_default_repo() {
1358
	$repos = pkg_list_repos();
1359

    
1360
	foreach ($repos as $repo) {
1361
		if (isset($repo['default'])) {
1362
			return $repo;
1363
		}
1364
	}
1365

    
1366
	/* No default found, return the first one */
1367
	return ($repos[0]);
1368
}
1369

    
1370
/* List available repos on a format to be used by selectors */
1371
function pkg_build_repo_list() {
1372
	$repos = pkg_list_repos();
1373
	$list = array();
1374

    
1375
	foreach ($repos as $repo) {
1376
		$list[$repo['name']] = $repo['descr'];
1377
	}
1378

    
1379
	return($list);
1380
}
1381

    
1382
/* Find repo by path */
1383
function pkg_get_repo_name($path) {
1384
	$repos = pkg_list_repos();
1385

    
1386
	$default = $repos[0]['name'];
1387
	foreach ($repos as $repo) {
1388
		if ($repo['path'] == $path) {
1389
			return $repo['name'];
1390
		}
1391
		if (isset($repo['default'])) {
1392
			$default = $repo['name'];
1393
		}
1394
	}
1395

    
1396
	/* Default */
1397
	return $default;
1398
}
1399

    
1400
/* Setup pkg.conf according current repo */
1401
function pkg_conf_setup() {
1402
	global $g;
1403

    
1404
	$pkg_conf_path = "/usr/local/etc/pkg.conf";
1405
	$conf = "/usr/local/etc/pkg/repos/{$g['product_name']}.conf";
1406
	if (!file_exists($conf)) {
1407
		return;
1408
	}
1409

    
1410
	$real_conf = readlink($conf);
1411

    
1412
	if (!$real_conf) {
1413
		return;
1414
	}
1415

    
1416
	$abi_file = str_replace('.conf', '.abi', $real_conf);
1417
	$altabi_file = str_replace('.conf', '.altabi', $real_conf);
1418

    
1419
	$pkg_conf = array();
1420
	if (file_exists($abi_file) && file_exists($altabi_file)) {
1421
		$abi = file_get_contents($abi_file);
1422
		$altabi = file_get_contents($altabi_file);
1423

    
1424
		$pkg_conf = array(
1425
			"ABI={$abi}",
1426
			"ALTABI={$altabi}"
1427
		);
1428
	}
1429

    
1430
	file_put_contents($pkg_conf_path, $pkg_conf);
1431
}
1432

    
1433
/* Switch between stable and devel repos */
1434
function pkg_switch_repo($path) {
1435
	global $g;
1436

    
1437
	safe_mkdir("/usr/local/etc/pkg/repos");
1438
	@unlink("/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1439
	@symlink($path, "/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1440

    
1441
	pkg_conf_setup();
1442

    
1443
	/* Update pfSense_version cache */
1444
	mwexec_bg("/etc/rc.update_pkg_metadata now");
1445
	return;
1446
}
1447

    
1448
$FQDN = "https://ews.netgate.com/pfupdate";
1449
$refreshinterval = (24 * 3600);	// 24 hours
1450
$idfile = "/var/db/uniqueid";
1451
$repopath = "/usr/local/share/{$g['product_name']}/pkg/repos";
1452
$configflename = "{$repopath}/{$g['product_name']}-repo-custom.conf";
1453

    
1454
// Update the list of available repositories from the server. This will allow migration to another
1455
// update repository should the existing one becomes unavailable
1456
function update_repos() {
1457
	global $g, $config, $idfile, $FQDN, $repopath;
1458

    
1459
	if (file_exists($idfile)) {
1460
		// If the custom repository definition does not exist, or is more than 24 hours old
1461
		// Fetch a copy from the server
1462
		if ( (! file_exists($configflename)) || ( time()-filemtime($configflename) > $refreshinterval)) {
1463
			if (function_exists('curl_version')) {
1464
				// Gather some information about the system so the proper repo can be returned
1465
				$nid = file_get_contents($idfile);
1466
				$serial = system_get_serial();
1467
				$arch = php_uname('p');
1468

    
1469
				$base_pkg = get_base_pkg_name();
1470

    
1471
				$info = get_pkg_info($base_pkg, true, true);
1472

    
1473
				$pkg_info = array();
1474
					foreach ($info as $item) {
1475
						if ($item['name'] == $base_pkg) {
1476
							$pkg_info = $item;
1477
							break;
1478
						}
1479
					}
1480

    
1481
				$version = $pkg_info['installed_version'];
1482
				$locale = $config['system']['language'];
1483
				// Architecture comes from the last word in the uname output
1484
				$arch = array_pop(explode(' ', php_uname('p')));
1485

    
1486
				$post = ['uid' => $nid,
1487
						 'language' => $locale,
1488
						 'serial' => $serial,
1489
						 'version' => $version,
1490
						 'arch' => $arch
1491
						];
1492

    
1493
				$ch = curl_init();
1494
				curl_setopt($ch, CURLOPT_HEADER, 0);
1495
				curl_setopt($ch, CURLOPT_VERBOSE, 0);
1496
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1497
				curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . $g['product_version']);
1498
				curl_setopt($ch, CURLOPT_URL, $FQDN);
1499
				curl_setopt($ch, CURLOPT_POST, true);
1500
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
1501
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,4);
1502
				$response = curl_exec($ch);
1503
				$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1504
				curl_close($ch);
1505

    
1506
				if ($status == 200) {
1507
					save_repo($response);
1508
				}
1509
			}
1510
		}
1511
	}
1512
}
1513

    
1514
// Parse the received JSON data and save the custom repository information
1515
function save_repo($json) {
1516
	global $repopath, $g;
1517
	$repo = json_decode($json, true);
1518

    
1519
	if (($repo != NULL) && isset($repo['abi']) && isset($repo['altabi']) && isset($repo['conf']) &&
1520
	    isset($repo['descr']) && isset($repo['name']) && (strlen($repo['conf']) > 10)) {
1521
		$basename = "{$repopath}/{$g['product_name']}-repo-custom.";
1522

    
1523
		file_put_contents($basename . "conf", base64_decode($repo['conf']));
1524
		file_put_contents($basename . "descr", $repo['descr']);
1525
		file_put_contents($basename . "abi", $repo['abi']);
1526
		file_put_contents($basename . "altabi", $repo['altabi']);
1527
		file_put_contents($basename . "name", $repo['name']);
1528
		file_put_contents($basename . "help", $repo['help']);
1529
	} else {
1530
		// If there was anything wrong with the custom repository definition, remove the help text
1531
		// to avoid possible confusion
1532
		if (file_exists($basename . "help")) {
1533
			unlink($basename . "help");
1534
		}
1535
	}
1536
}
1537

    
1538
?>
(40-40/60)