Project

General

Profile

Download (39.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

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

    
357
	if (!function_exists('is_subsystem_dirty')) {
358
		require_once("util.inc");
359
	}
360

    
361
	/* Do not run remote operations if pkg has a lock */
362
	if (is_subsystem_dirty('pkg')) {
363
		$remote_repo_usage_disabled = true;
364
		$lock = false;
365
	} else {
366
		$lock = true;
367
	}
368

    
369
	if ($lock) {
370
		mark_subsystem_dirty('pkg');
371
	}
372

    
373
	if ($remote_repo_usage_disabled) {
374
		$extra_param = "-U ";
375
	}
376

    
377
	$did_search = false;
378
	$search_rc = 0;
379
	$info_rc = 0;
380
	$search_items = array();
381
	$info_items = array();
382

    
383
	/*
384
	 * If we want more than just the currently installed packages or
385
	 * we want up-to-date remote repo info then do a full pkg search
386
	 */
387
	if (!$installed_pkgs_only || !$remote_repo_usage_disabled) {
388
		$did_search = true;
389
		$search_rc = pkg_exec(
390
		    "search {$extra_param}-R --raw-format json-compact " .
391
		    $pkgs, $search_out, $search_err);
392
		if ($search_rc == 0) {
393
			$search_items = explode("\n", chop($search_out));
394
			array_walk($search_items, function(&$v, &$k) {
395
				$v = json_decode($v, true);
396
			});
397
		}
398
	}
399

    
400
	/*
401
	 * We always should look for local items to detect packages that
402
	 * were removed from remote repo but are already installed locally
403
	 *
404
	 * Take pkg search return code into consideration to fallback to local
405
	 * information when remote repo is not accessible
406
	 */
407
	if (is_pkg_installed($pkgs) || $search_rc != 0) {
408
		$info_rc = pkg_exec("info -R --raw-format json-compact " .
409
		    $pkgs, $info_out, $info_err);
410
		if ($info_rc == 0) {
411
			$info_items = explode("\n", chop($info_out));
412
			array_walk($info_items, function(&$v, &$k) {
413
				$v = json_decode($v, true);
414
			});
415
		}
416
	}
417

    
418
	if ($lock) {
419
		clear_subsystem_dirty('pkg');
420
	}
421

    
422
	if ($search_rc != 0 && $info_rc != 0) {
423
		update_status("\n" . gettext(
424
		    "ERROR: Error trying to get packages list. Aborting...")
425
		    . "\n");
426
		update_status($search_err . "\n" . $info_err);
427
		$input_errors[] = gettext(
428
		    "ERROR: Error trying to get packages list. Aborting...") .
429
		    "\n";
430
		$input_errors[] = $search_err . "\n" . $info_err;
431
		return array();
432
	}
433

    
434
	/* It was not possible to search, use local information only */
435
	if ($search_rc != 0 || !$did_search) {
436
		$search_items = $info_items;
437
	} else {
438
		foreach ($info_items as $pkg_info) {
439
			if (empty($pkg_info['name'])) {
440
				continue;
441
			}
442

    
443
			if (array_search($pkg_info['name'], array_column(
444
			    $search_items, 'name')) === FALSE) {
445
				$pkg_info['obsolete'] = true;
446
				$search_items[] = $pkg_info;
447
			}
448
		}
449
	}
450

    
451
	$result = array();
452
	foreach ($search_items as $pkg_info) {
453
		if (empty($pkg_info['name'])) {
454
			continue;
455
		}
456

    
457
		if (isset($pkg_filter) && !in_array($pkg_info['name'],
458
		    $pkg_filter)) {
459
			continue;
460
		}
461

    
462
		$pkg_info['shortname'] = $pkg_info['name'];
463
		pkg_remove_prefix($pkg_info['shortname']);
464

    
465
		/* XXX: Add it to globals.inc? */
466
		$pkg_info['changeloglink'] =
467
		    "https://github.com/pfsense/FreeBSD-ports/commits/devel/" .
468
		    $pkg_info['categories'][0] . '/' . $pkg_info['name'];
469

    
470
		$pkg_is_installed = false;
471

    
472
		if (is_pkg_installed($pkg_info['name'])) {
473
			$pkg_info['installed'] = true;
474
			$pkg_is_installed = true;
475

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

    
479
			if ($rc != 0) {
480
				update_status("\n" . gettext(
481
				    "ERROR: Error trying to get package version. Aborting...")
482
				    . "\n");
483
				update_status($err);
484
				$input_errors[] = gettext(
485
				    "ERROR: Error trying to get package version. Aborting...") .
486
				    "\n";
487
				$input_errors[] = $err;
488
				return array();
489
			}
490

    
491
			$pkg_info['installed_version'] = str_replace("\n", "", $out);
492

    
493
			/*
494
			* We used pkg info to collect pkg data so remote
495
			* version is not available. Lets try to collect it
496
			* using rquery if possible
497
			*/
498
			if ($search_rc != 0 || !$did_search) {
499
				$rc = pkg_exec("rquery -U %v {$pkg_info['name']}", $out, $err);
500

    
501
				if ($rc == 0) {
502
					$pkg_info['version'] = str_replace("\n", "", $out);
503
				}
504
			}
505

    
506
		} else if (is_package_installed($pkg_info['shortname'])) {
507
			$pkg_info['broken'] = true;
508
			$pkg_is_installed = true;
509
		}
510

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

    
514
		if (!$installed_pkgs_only || $pkg_is_installed) {
515
			$result[] = $pkg_info;
516
		}
517
		unset($pkg_info);
518
	}
519

    
520
	/* Sort result alphabetically */
521
	usort($result, function($a, $b) {
522
		return(strcasecmp ($a['name'], $b['name']));
523
	});
524

    
525
	return $result;
526
}
527

    
528
/*
529
 * If binary pkg is installed but post-install tasks were not
530
 * executed yet, do it now.
531
 * This scenario can happen when a pkg is pre-installed during
532
 * build phase, and at this point, cannot find a running system
533
 * to register itself in config.xml and also execute custom
534
 * install functions
535
 */
536
function register_all_installed_packages() {
537
	global $g, $config, $pkg_interface;
538

    
539
	$pkg_info = get_pkg_info('all', true, true);
540

    
541
	foreach ($pkg_info as $pkg) {
542
		pkg_remove_prefix($pkg['name']);
543

    
544
		if (is_package_installed($pkg['name'])) {
545
			continue;
546
		}
547

    
548
		update_status(sprintf(gettext(
549
		    "Running last steps of %s installation.") . "\n",
550
		    $pkg['name']));
551
		install_package_xml($pkg['name']);
552
	}
553
}
554

    
555
/*
556
 * resync_all_package_configs() Force packages to setup their configuration and rc.d files.
557
 * This function may also print output to the terminal indicating progress.
558
 */
559
function resync_all_package_configs($show_message = false) {
560
	global $config, $pkg_interface, $g;
561

    
562
	log_error(gettext("Resyncing configuration for all packages."));
563

    
564
	if (!is_array($config['installedpackages']['package'])) {
565
		return;
566
	}
567

    
568
	if ($show_message == true) {
569
		echo "Syncing packages:";
570
	}
571

    
572

    
573
	foreach ($config['installedpackages']['package'] as $idx => $package) {
574
		if (empty($package['name'])) {
575
			continue;
576
		}
577
		if ($show_message == true) {
578
			echo " " . $package['name'];
579
		}
580
		if (platform_booting() != true) {
581
			stop_service(get_package_internal_name($package));
582
		}
583
		sync_package($package['name']);
584
		update_status(gettext("Syncing packages...") . "\n");
585
	}
586

    
587
	if ($show_message == true) {
588
		echo " done.\n";
589
	}
590

    
591
	@unlink("/conf/needs_package_sync");
592
}
593

    
594
function uninstall_package($package_name) {
595
	global $config;
596

    
597
	$internal_name = $package_name;
598
	$id = get_package_id($package_name);
599
	if ($id >= 0) {
600
		$internal_name = get_package_internal_name($config['installedpackages']['package'][$id]);
601
		stop_service($internal_name);
602
	}
603
	$pkg_name = $g['pkg_prefix'] . $internal_name;
604

    
605
	if (is_pkg_installed($pkg_name)) {
606
		update_status(gettext("Removing package...") . "\n");
607
		pkg_delete($pkg_name);
608
	} else {
609
		delete_package_xml($package_name);
610
	}
611

    
612
	update_status(gettext("done.") . "\n");
613
}
614

    
615
function reinstall_package($package_name) {
616
	global $config, $g;
617

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

    
627
/* Run <custom_php_resync_config_command> */
628
function sync_package($package_name) {
629
	global $config, $builder_package_install;
630

    
631
	// If this code is being called by pfspkg_installer
632
	// which the builder system uses then return (ignore).
633
	if ($builder_package_install) {
634
		return;
635
	}
636

    
637
	if (empty($config['installedpackages']['package'])) {
638
		return;
639
	}
640

    
641
	if (($pkg_id = get_package_id($package_name)) == -1) {
642
		return; // This package doesn't really exist - exit the function.
643
	}
644

    
645
	if (!is_array($config['installedpackages']['package'][$pkg_id])) {
646
		return;	 // No package belongs to the pkg_id passed to this function.
647
	}
648

    
649
	$package =& $config['installedpackages']['package'][$pkg_id];
650
	if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
651
		log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name']));
652
		delete_package_xml($package['name']);
653
		return;
654
	}
655

    
656
	$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui");
657
	if (isset($pkg_config['nosync'])) {
658
		return;
659
	}
660

    
661
	/* Bring in package include files */
662
	if (!empty($pkg_config['include_file'])) {
663
		$include_file = $pkg_config['include_file'];
664
		if (file_exists($include_file)) {
665
			require_once($include_file);
666
		} else {
667
			log_error(sprintf(gettext('Reinstalling package %1$s because its include file(%2$s) is missing!'), $package['name'], $include_file));
668
			uninstall_package($package['name']);
669
			if (reinstall_package($package['name']) != 0) {
670
				log_error(sprintf(gettext("Reinstalling package %s failed. Take appropriate measures!!!"), $package['name']));
671
				return;
672
			}
673
			if (file_exists($include_file)) {
674
				require_once($include_file);
675
			} else {
676
				return;
677
			}
678
		}
679
	}
680

    
681
	if (!empty($pkg_config['custom_php_global_functions'])) {
682
		eval($pkg_config['custom_php_global_functions']);
683
	}
684
	if (!empty($pkg_config['custom_php_resync_config_command'])) {
685
		eval($pkg_config['custom_php_resync_config_command']);
686
	}
687
}
688

    
689
/* Read info.xml installed by package and return an array */
690
function read_package_config($package_name) {
691
	global $g;
692

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

    
695
	if (!file_exists($pkg_info_xml)) {
696
		return false;
697
	}
698

    
699
	$pkg_info = parse_xml_config_pkg($pkg_info_xml, 'pfsensepkgs');
700

    
701
	if (empty($pkg_info)) {
702
		return false;
703
	}
704

    
705
	/* it always returns an array with 1 item */
706
	return $pkg_info['package'][0];
707
}
708

    
709
/* Read package configurationfile and return an array */
710
function read_package_configurationfile($package_name) {
711
	global $config, $g;
712

    
713
	$pkg_config = array();
714
	$id = get_package_id($package_name);
715

    
716
	if ($id < 0 || !isset($config['installedpackages']['package'][$id]['configurationfile'])) {
717
		return $pkg_config;
718
	}
719

    
720
	$pkg_configurationfile = $config['installedpackages']['package'][$id]['configurationfile'];
721

    
722
	if (empty($pkg_configurationfile) || !file_exists('/usr/local/pkg/' . $pkg_configurationfile)) {
723
		return $pkg_config;
724
	}
725

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

    
728
	return $pkg_config;
729
}
730

    
731
function get_after_install_info($package_name) {
732
	$pkg_config = read_package_config($package_name);
733

    
734
	if (isset($pkg_config['after_install_info'])) {
735
		return $pkg_config['after_install_info'];
736
	}
737

    
738
	return '';
739
}
740

    
741
function eval_once($toeval) {
742
	global $evaled;
743
	if (!$evaled) {
744
		$evaled = array();
745
	}
746
	$evalmd5 = md5($toeval);
747
	if (!in_array($evalmd5, $evaled)) {
748
		@eval($toeval);
749
		$evaled[] = $evalmd5;
750
	}
751
	return;
752
}
753

    
754
function install_package_xml($package_name) {
755
	global $g, $config, $pkg_interface;
756

    
757
	if (($pkg_info = read_package_config($package_name)) == false) {
758
		return false;
759
	}
760

    
761
	/* safe side. Write config below will send to ro again. */
762

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

    
766
	/* add package information to config.xml */
767
	$pkgid = get_package_id($pkg_info['name']);
768
	update_status(gettext("Saving updated package information...") . "\n");
769
	if ($pkgid == -1) {
770
		$config['installedpackages']['package'][] = $pkg_info;
771
		$changedesc = sprintf(gettext("Installed %s package."), $pkg_info['name']);
772
		$to_output = gettext("done.") . "\n";
773
	} else {
774
		$config['installedpackages']['package'][$pkgid] = $pkg_info;
775
		$changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']);
776
		$to_output = gettext("overwrite!") . "\n";
777
	}
778
	unlink_if_exists('/conf/needs_package_sync');
779
	write_config(sprintf(gettext("Intermediate config write during package install for %s."), $pkg_info['name']));
780
	update_status($to_output);
781

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

    
785
		uninstall_package($package_name);
786
		write_config($changedesc);
787
		log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
788
		update_status(gettext("Failed to install package.") . "\n");
789
		return false;
790
	}
791

    
792
	if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) {
793
		update_status(gettext("Loading package configuration... "));
794
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $pkg_info['configurationfile'], "packagegui");
795
		update_status(gettext("done.") . "\n");
796
		update_status(gettext("Configuring package components...") . "\n");
797
		if (!empty($pkg_config['filter_rules_needed'])) {
798
			$config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed'];
799
		}
800
		/* modify system files */
801

    
802
		/* if a require exists, include it.  this will
803
		 * show us where an error exists in a package
804
		 * instead of making us blindly guess
805
		 */
806
		$missing_include = false;
807
		if ($pkg_config['include_file'] <> "") {
808
			update_status(gettext("Loading package instructions...") . "\n");
809
			if (file_exists($pkg_config['include_file'])) {
810
				pkg_debug("require_once('{$pkg_config['include_file']}')\n");
811
				require_once($pkg_config['include_file']);
812
			} else {
813
				pkg_debug("Missing include {$pkg_config['include_file']}\n");
814
				$missing_include = true;
815
				update_status(sprintf(gettext("Include %s is missing!"), basename($pkg_config['include_file'])) . "\n");
816

    
817
				uninstall_package($package_name);
818
				write_config($changedesc);
819
				log_error(sprintf(gettext("Failed to install package: %s."), $pkg_info['name']));
820
				update_status(gettext("Failed to install package.") . "\n");
821
				return false;
822
			}
823
		}
824

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

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

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

    
908
	/* set up package logging streams */
909
	if ($pkg_info['logging']) {
910
		system_syslogd_start(true);
911
	}
912

    
913
	return true;
914
}
915

    
916
function delete_package_xml($package_name, $when = "post-deinstall") {
917
	global $g, $config, $pkg_interface;
918

    
919

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

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

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

    
1047
/*
1048
 * Used during upgrade process or retore backup process, verify all
1049
 * packages installed in config.xml and install pkg accordingly
1050
 */
1051
function package_reinstall_all() {
1052
	global $g, $config, $pkg_interface;
1053

    
1054
	$upgrade = (file_exists('/conf/needs_package_sync') && platform_booting());
1055

    
1056
	if ((!isset($config['installedpackages']['package']) ||
1057
	    !is_array($config['installedpackages']['package'])) && !$upgrade) {
1058
		return true;
1059
	}
1060

    
1061
	/* During boot after upgrade, wait for internet connection */
1062
	if ($upgrade) {
1063
		update_status(gettext("Waiting for Internet connection to update pkg metadata and finish package reinstallation"));
1064
		$ntries = 3;
1065
		while ($ntries > 0) {
1066
			if (pkg_update(true)) {
1067
				break;
1068
			}
1069
			update_status('.');
1070
			sleep(1);
1071
			$ntries--;
1072
		}
1073
		update_status("\n");
1074

    
1075
		if ($ntries == 0) {
1076
			file_notice(gettext("Package reinstall"),
1077
			    gettext("Package reinstall process was ABORTED due to lack of internet connectivity"));
1078
			return false;
1079
		}
1080
	}
1081

    
1082
	$pkg_info = get_pkg_info();
1083

    
1084
	if ($upgrade &&
1085
	    file_exists("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt")) {
1086
		$package_list = file("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt",
1087
		    FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1088
		unlink_if_exists("{$g['cf_conf_path']}/packages_to_reinstall_after_upgrade.txt");
1089
	} else {
1090
		if (!isset($config['installedpackages']['package']) || !is_array($config['installedpackages']['package'])) {
1091
			return true;
1092
		}
1093
		$package_list = array();
1094
		foreach ($config['installedpackages']['package'] as $package) {
1095
			$package_list[] = get_package_internal_name($package);
1096
		}
1097
	}
1098

    
1099
	foreach ($package_list as $package) {
1100
		$found = false;
1101
		foreach ($pkg_info as $pkg) {
1102
			pkg_remove_prefix($pkg['name']);
1103
			if ($pkg['name'] == $package) {
1104
				pkg_install($g['pkg_prefix'] . $package, true);
1105
				$found = true;
1106
				break;
1107
			}
1108
		}
1109

    
1110
		if (!$found) {
1111
			if (!function_exists("file_notice")) {
1112
				require_once("notices.inc");
1113
			}
1114

    
1115
			file_notice(gettext("Package reinstall"),
1116
			    sprintf(gettext("Package %s does not exist in current %s version and it has been removed."),
1117
			    $package, $g['product_name']));
1118
			uninstall_package($package);
1119
		}
1120
	}
1121

    
1122
	return true;
1123
}
1124

    
1125
function stop_packages() {
1126
	require_once("config.inc");
1127
	require_once("functions.inc");
1128
	require_once("filter.inc");
1129
	require_once("shaper.inc");
1130
	require_once("captiveportal.inc");
1131
	require_once("pkg-utils.inc");
1132
	require_once("pfsense-utils.inc");
1133
	require_once("service-utils.inc");
1134

    
1135
	global $config, $g;
1136

    
1137
	log_error(gettext("Stopping all packages."));
1138

    
1139
	$rcfiles = glob(RCFILEPREFIX . "*.sh");
1140
	if (!$rcfiles) {
1141
		$rcfiles = array();
1142
	} else {
1143
		$rcfiles = array_flip($rcfiles);
1144
		if (!$rcfiles) {
1145
			$rcfiles = array();
1146
		}
1147
	}
1148

    
1149
	if (is_array($config['installedpackages']['package'])) {
1150
		foreach ($config['installedpackages']['package'] as $package) {
1151
			echo " Stopping package {$package['name']}...";
1152
			$internal_name = get_package_internal_name($package);
1153
			stop_service($internal_name);
1154
			unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]);
1155
			echo "done.\n";
1156
		}
1157
	}
1158

    
1159
	foreach ($rcfiles as $rcfile => $number) {
1160
		$shell = @popen("/bin/sh", "w");
1161
		if ($shell) {
1162
			echo " Stopping {$rcfile}...";
1163
			if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) {
1164
				if ($shell) {
1165
					pclose($shell);
1166
				}
1167
				$shell = @popen("/bin/sh", "w");
1168
			}
1169
			echo "done.\n";
1170
			pclose($shell);
1171
		}
1172
	}
1173
}
1174

    
1175
/* Identify which meta package is installed */
1176
function get_meta_pkg_name() {
1177
	global $g;
1178

    
1179
	/* XXX: Use pkg annotation */
1180
	if (is_pkg_installed($g['product_name'])) {
1181
		return $g['product_name'];
1182
	} else if (is_pkg_installed($g['product_name'] . '-vmware')) {
1183
		return $g['product_name'] . '-vmware';
1184
	}
1185
	return false;
1186
}
1187

    
1188
/* Identify which base package is installed */
1189
function get_base_pkg_name() {
1190
	global $g;
1191

    
1192
	/* XXX: Use pkg annotation */
1193
	if (is_pkg_installed($g['product_name'] . '-base-' . $g['platform'])) {
1194
		return $g['product_name'] . '-base-' . $g['platform'];
1195
	} else if (is_pkg_installed($g['product_name'] . '-base')) {
1196
		return $g['product_name'] . '-base';
1197
	}
1198
	return false;
1199
}
1200

    
1201
/* Verify if system needs upgrade (meta package or base) */
1202
function get_system_pkg_version($baseonly = false, $use_cache = true) {
1203
	global $g;
1204

    
1205
	$cache_file = $g['version_cache_file'];
1206
	$rc_file = $cache_file . '.rc';
1207

    
1208
	$rc = "";
1209
	if ($use_cache && file_exists($rc_file) &&
1210
	    (time()-filemtime($rc_file) < $g['version_cache_refresh'])) {
1211
		$rc = chop(@file_get_contents($rc_file));
1212
	}
1213

    
1214
	if ($rc == "2") {
1215
		$output = @file_get_contents($cache_file);
1216
	} else if ($rc != "0") {
1217
		$output = exec(
1218
		    "/usr/local/sbin/{$g['product_name']}-upgrade -c", $_gc,
1219
		    $rc);
1220

    
1221
		/* Update cache if it succeeded */
1222
		if ($rc == 0 || $rc == 2) {
1223
			@file_put_contents($cache_file, $output);
1224
			@file_put_contents($rc_file, $rc);
1225
		}
1226
	}
1227

    
1228
	/* pfSense-upgrade returns 2 when there is a new version */
1229
	if ($rc == "2") {
1230
		$new_version = explode(' ', $output)[0];
1231
	}
1232

    
1233
	$base_pkg = get_base_pkg_name();
1234
	$meta_pkg = get_meta_pkg_name();
1235

    
1236
	if (!$base_pkg || !$meta_pkg) {
1237
		return false;
1238
	}
1239

    
1240
	$info = get_pkg_info($base_pkg, true, true);
1241

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

    
1250
	if (empty($pkg_info) || (!$baseonly && ($pkg_info['version'] ==
1251
	    $pkg_info['installed_version']))) {
1252
		$info = get_pkg_info($meta_pkg, true, true);
1253

    
1254
		foreach ($info as $item) {
1255
			if ($item['name'] == $meta_pkg) {
1256
				$pkg_info = $item;
1257
				break;
1258
			}
1259
		}
1260
	}
1261

    
1262
	if (empty($pkg_info)) {
1263
		return false;
1264
	}
1265

    
1266
	$result = array(
1267
	    'version'           => $new_version ?: $pkg_info['version'],
1268
	    'installed_version' => $pkg_info['installed_version']
1269
	);
1270

    
1271
	$result['pkg_version_compare'] = pkg_version_compare(
1272
	    $result['installed_version'], $result['version']);
1273

    
1274
	return $result;
1275
}
1276

    
1277
/* List available repos */
1278
function pkg_list_repos() {
1279
	global $g;
1280

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

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

    
1285
	$default = array(
1286
	    'name' => 'Default',
1287
	    'path' => $path . "/{$g['product_name']}-repo.conf",
1288
	    'descr' => $default_descr
1289
	);
1290

    
1291
	$result = array($default);
1292

    
1293
	$conf_files = glob("{$path}/{$g['product_name']}-repo-*.conf");
1294
	foreach ($conf_files as $conf_file) {
1295
		$descr_file = preg_replace('/.conf$/', '.descr', $conf_file);
1296
		if (file_exists($descr_file)) {
1297
			$descr_content = file($descr_file);
1298
			$descr = chop($descr_content[0]);
1299
		} else {
1300
			$descr = 'Unknown';
1301
		}
1302
		if (!preg_match('/-repo-(.*).conf/', $conf_file, $matches)) {
1303
			continue;
1304
		}
1305
		$entry = array(
1306
		    'name' => ucfirst(strtolower($matches[1])),
1307
		    'path' => $conf_file,
1308
		    'descr' => $descr
1309
		);
1310
		$result[] = $entry;
1311
	}
1312

    
1313
	return $result;
1314
}
1315

    
1316
/* Switch between stable and devel repos */
1317
function pkg_switch_repo($path) {
1318
	global $g;
1319

    
1320
	safe_mkdir("/usr/local/etc/pkg/repos");
1321
	@unlink("/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1322
	@symlink($path, "/usr/local/etc/pkg/repos/{$g['product_name']}.conf");
1323

    
1324
	$abi_file = str_replace('.conf', '.abi', $path);
1325
	$altabi_file = str_replace('.conf', '.altabi', $path);
1326

    
1327
	if (file_exists($abi_file) && file_exists($altabi_file)) {
1328
		$abi = file_get_contents($abi_file);
1329
		$altabi = file_get_contents($altabi_file);
1330

    
1331
		$pkg_conf = array(
1332
			"ABI={$abi}",
1333
			"ALTABI={$altabi}"
1334
		);
1335

    
1336
		file_put_contents("/usr/local/etc/pkg.conf", $pkg_conf);
1337
	}
1338

    
1339
	/* Update pfSense_version cache */
1340
	mwexec_bg("/etc/rc.update_pkg_metadata now");
1341
	return;
1342
}
1343

    
1344
$FQDN = "https://ews.netgate.com/pfupdate";
1345
$refreshinterval = (24 * 3600);	// 24 hours
1346
$idfile = "/var/db/uniqueid";
1347
$repopath = "/usr/local/share/{$g['product_name']}/pkg/repos";
1348
$configflename = "{$repopath}/{$g['product_name']}-repo-custom.conf";
1349

    
1350
// Update the list of available repositories from the server. This will allow migration to another
1351
// update repository should the existing one becomes unavailable
1352
function update_repos() {
1353
	global $g, $config, $idfile, $FQDN, $repopath;
1354

    
1355
	if (file_exists($idfile)) {
1356
		// If the custom repository definition does not exist, or is more than 24 hours old
1357
		// Fetch a copy from the server
1358
		if ( (! file_exists($configflename)) || ( time()-filemtime($configflename) > $refreshinterval)) {
1359
			if (function_exists('curl_version')) {
1360
				// Gather some information about the system so the proper repo can be returned
1361
				$nid = file_get_contents($idfile);
1362
				$serial = system_get_serial();
1363
				$arch = php_uname(p);
1364
				$version = $g['product_version'];
1365
				$locale = $config['system']['language'];
1366
				// Architecture comes from the last word in the uname output
1367
				$arch = array_pop(explode(' ', php_uname(p)));
1368

    
1369
				$post = ['uid' => $nid,
1370
						 'language' => $locale,
1371
						 'serial' => $serial,
1372
						 'version' => $version,
1373
						 'arch' => $arch
1374
						];
1375

    
1376
				$ch = curl_init();
1377
				curl_setopt($ch, CURLOPT_HEADER, 0);
1378
				curl_setopt($ch, CURLOPT_VERBOSE, 0);
1379
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1380
				curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . $g['product_version']);
1381
				curl_setopt($ch, CURLOPT_URL, $FQDN);
1382
				curl_setopt($ch, CURLOPT_POST, true);
1383
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
1384
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,4);
1385
				$response = curl_exec($ch);
1386
				$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1387
				curl_close($ch);
1388

    
1389
				if ($status == 200) {
1390
					save_repo($response);
1391
				}
1392
			}
1393
		}
1394
	}
1395
}
1396

    
1397
// Parse the received JSON data and save the custom repository information
1398
function save_repo($json) {
1399
	global $repopath, $g;
1400
	$repo = json_decode($json, true);
1401

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

    
1406
		file_put_contents($basename . "conf", base64_decode($repo['conf']));
1407
		file_put_contents($basename . "descr", $repo['descr']);
1408
		file_put_contents($basename . "abi", $repo['abi']);
1409
		file_put_contents($basename . "altabi", $repo['altabi']);
1410
		file_put_contents($basename . "name", $repo['name']);
1411
		file_put_contents($basename . "help", $repo['help']);
1412
	} else {
1413
		// If there was anything wrong with the custom repository definition, remove the help text
1414
		// to avoid possible confusion
1415
		if (file_exists($basename . "help")) {
1416
			unlink($basename . "help");
1417
		}
1418
	}
1419
}
1420
?>
(35-35/55)