Project

General

Profile

Download (31.9 KB) Statistics
| Branch: | Tag: | Revision:
1 12df7edc Erik
<?php
2 09221bc3 Renato Botelho
/*
3 8acd654a Renato Botelho
 * config.lib.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6 2a2396a6 Renato Botelho
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
7 8acd654a Renato Botelho
 * Copyright (c) 2009 Erik Kristensen
8
 * All rights reserved.
9
 *
10
 * originally part of m0n0wall (http://m0n0.ch/wall)
11 aaec5634 Renato Botelho
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
12 8acd654a Renato Botelho
 * All rights reserved.
13
 *
14
 * Redistribution and use in source and binary forms, with or without
15
 * modification, are permitted provided that the following conditions are met:
16
 *
17
 * 1. Redistributions of source code must retain the above copyright notice,
18
 *    this list of conditions and the following disclaimer.
19
 *
20
 * 2. Redistributions in binary form must reproduce the above copyright
21
 *    notice, this list of conditions and the following disclaimer in
22
 *    the documentation and/or other materials provided with the
23
 *    distribution.
24
 *
25
 * 3. All advertising materials mentioning features or use of this software
26
 *    must display the following acknowledgment:
27
 *    "This product includes software developed by the pfSense Project
28
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
29
 *
30
 * 4. The names "pfSense" and "pfSense Project" must not be used to
31
 *    endorse or promote products derived from this software without
32
 *    prior written permission. For written permission, please contact
33
 *    coreteam@pfsense.org.
34
 *
35
 * 5. Products derived from this software may not be called "pfSense"
36
 *    nor may "pfSense" appear in their names without prior written
37
 *    permission of the Electric Sheep Fencing, LLC.
38
 *
39
 * 6. Redistributions of any form whatsoever must retain the following
40
 *    acknowledgment:
41
 *
42
 * "This product includes software developed by the pfSense Project
43
 * for use in the pfSense software distribution (http://www.pfsense.org/).
44
 *
45
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
46
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
48
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
49
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
50
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
51
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
52
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
54
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
56
 * OF THE POSSIBILITY OF SUCH DAMAGE.
57
 */
58 12df7edc Erik
59
/****f* config/encrypted_configxml
60
 * NAME
61
 *   encrypted_configxml - Checks to see if config.xml is encrypted and if so, prompts to unlock.
62
 * INPUTS
63
 *   None
64
 * RESULT
65
 *   $config 	- rewrites config.xml without encryption
66
 ******/
67
function encrypted_configxml() {
68
	global $g, $config;
69 02e9880e Ermal
70 1e0b1727 Phil Davis
	if (!file_exists($g['conf_path'] . "/config.xml")) {
71 02e9880e Ermal
		return;
72 1e0b1727 Phil Davis
	}
73 02e9880e Ermal
74 1e0b1727 Phil Davis
	if (!platform_booting()) {
75 02e9880e Ermal
		return;
76 1e0b1727 Phil Davis
	}
77 02e9880e Ermal
78 1e0b1727 Phil Davis
	$configtxt = file_get_contents($g['conf_path'] . "/config.xml");
79
	if (tagfile_deformat($configtxt, $configtxt, "config.xml")) {
80 02e9880e Ermal
		$fp = fopen('php://stdin', 'r');
81
		$data = "";
82
		echo "\n\n*** Encrypted config.xml detected ***\n";
83 1e0b1727 Phil Davis
		while ($data == "") {
84 02e9880e Ermal
			echo "\nEnter the password to decrypt config.xml: ";
85
			$decrypt_password = chop(fgets($fp));
86
			$data = decrypt_data($configtxt, $decrypt_password);
87 1e0b1727 Phil Davis
			if (!strstr($data, "<pfsense>")) {
88 12df7edc Erik
				$data = "";
89 1e0b1727 Phil Davis
			}
90
			if ($data) {
91 02e9880e Ermal
				$fd = fopen($g['conf_path'] . "/config.xml.tmp", "w");
92
				fwrite($fd, $data);
93
				fclose($fd);
94
				exec("/bin/mv {$g['conf_path']}/config.xml.tmp {$g['conf_path']}/config.xml");
95 9d3d8d00 Vinicius Coque
				echo "\n" . gettext("Config.xml unlocked.") . "\n";
96 02e9880e Ermal
				fclose($fp);
97 8a811010 Chris Buechler
				pfSense_fsync("{$g['conf_path']}/config.xml");
98 02e9880e Ermal
			} else {
99 9d3d8d00 Vinicius Coque
				echo "\n" . gettext("Invalid password entered.  Please try again.") . "\n";
100 12df7edc Erik
			}
101
		}
102
	}
103
}
104
105
/****f* config/parse_config
106
 * NAME
107
 *   parse_config - Read in config.cache or config.xml if needed and return $config array
108
 * INPUTS
109
 *   $parse       - boolean to force parse_config() to read config.xml and generate config.cache
110
 * RESULT
111
 *   $config      - array containing all configuration variables
112
 ******/
113 1295e769 Scott Ullrich
function parse_config($parse = false) {
114 4e9a3392 Scott Ullrich
	global $g, $config_parsed, $config_extra;
115 02e9880e Ermal
116 12df7edc Erik
	$lockkey = lock('config');
117 0af381c2 Scott Ullrich
	$config_parsed = false;
118 02e9880e Ermal
119 12df7edc Erik
	if (!file_exists("{$g['conf_path']}/config.xml") || filesize("{$g['conf_path']}/config.xml") == 0) {
120
		$last_backup = discover_last_backup();
121 1e0b1727 Phil Davis
		if ($last_backup) {
122 4e038d31 Carlos Eduardo Ramos
			log_error(gettext("No config.xml found, attempting last known config restore."));
123
			file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", "");
124 12df7edc Erik
			restore_backup("{$g['conf_path']}/backup/{$last_backup}");
125
		} else {
126
			unlock($lockkey);
127 4e038d31 Carlos Eduardo Ramos
			die(gettext("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup."));
128 12df7edc Erik
		}
129
	}
130 02e9880e Ermal
131 086cf944 Phil Davis
	if (platform_booting(true)) {
132 02e9880e Ermal
		echo ".";
133 086cf944 Phil Davis
	}
134 02e9880e Ermal
135 12df7edc Erik
	// Check for encrypted config.xml
136
	encrypted_configxml();
137 02e9880e Ermal
138 1e0b1727 Phil Davis
	if (!$parse) {
139 02e9880e Ermal
		if (file_exists($g['tmp_path'] . '/config.cache')) {
140 12df7edc Erik
			$config = unserialize(file_get_contents($g['tmp_path'] . '/config.cache'));
141 381b8f1c Chris Buechler
			if (!is_array($config)) {
142 02e9880e Ermal
				$parse = true;
143 1e0b1727 Phil Davis
			}
144
		} else {
145 02e9880e Ermal
			$parse = true;
146 1e0b1727 Phil Davis
		}
147 02e9880e Ermal
	}
148
	if ($parse == true) {
149 1e0b1727 Phil Davis
		if (!file_exists($g['conf_path'] . "/config.xml")) {
150
			if (platform_booting(true)) {
151 02e9880e Ermal
				echo ".";
152 1e0b1727 Phil Davis
			}
153 12df7edc Erik
			log_error("No config.xml found, attempting last known config restore.");
154
			file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
155
			$last_backup = discover_last_backup();
156 1e0b1727 Phil Davis
			if ($last_backup) {
157 12df7edc Erik
				restore_backup("/cf/conf/backup/{$last_backup}");
158 1e0b1727 Phil Davis
			} else {
159 4e038d31 Carlos Eduardo Ramos
				log_error(gettext("Could not restore config.xml."));
160 50cafcf3 Ermal
				unlock($lockkey);
161 4816e5ca Renato Botelho
				die(gettext("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup."));
162 50cafcf3 Ermal
			}
163 12df7edc Erik
		}
164 990d7c03 Erik Fonnesbeck
		$config = parse_xml_config($g['conf_path'] . '/config.xml', array($g['xml_rootobj'], 'pfsense'));
165 1e0b1727 Phil Davis
		if ($config == -1) {
166 12df7edc Erik
			$last_backup = discover_last_backup();
167 1e0b1727 Phil Davis
			if ($last_backup) {
168 12df7edc Erik
				restore_backup("/cf/conf/backup/{$last_backup}");
169 1e0b1727 Phil Davis
			} else {
170 12df7edc Erik
				log_error(gettext("Could not restore config.xml."));
171 50cafcf3 Ermal
				unlock($lockkey);
172
				die("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup.");
173
			}
174 12df7edc Erik
		}
175
		generate_config_cache($config);
176
	}
177 02e9880e Ermal
178 1e0b1727 Phil Davis
	if (platform_booting(true)) {
179 02e9880e Ermal
		echo ".";
180 1e0b1727 Phil Davis
	}
181 02e9880e Ermal
182 12df7edc Erik
	$config_parsed = true;
183
	unlock($lockkey);
184
185 02e9880e Ermal
	alias_make_table($config);
186
187 12df7edc Erik
	return $config;
188
}
189
190
/****f* config/generate_config_cache
191
 * NAME
192
 *   generate_config_cache - Write serialized configuration to cache.
193
 * INPUTS
194
 *   $config	- array containing current firewall configuration
195
 * RESULT
196
 *   boolean	- true on completion
197
 ******/
198
function generate_config_cache($config) {
199 4e9a3392 Scott Ullrich
	global $g, $config_extra;
200 12df7edc Erik
201
	$configcache = fopen($g['tmp_path'] . '/config.cache', "w");
202
	fwrite($configcache, serialize($config));
203
	fclose($configcache);
204 88f2c335 Chris Buechler
	pfSense_fsync("{$g['tmp_path']}/config.cache");
205 6990ad35 Phil Davis
206 4e9a3392 Scott Ullrich
	unset($configcache);
207
	/* Used for config.extra.xml */
208 1e0b1727 Phil Davis
	if (file_exists($g['tmp_path'] . '/config.extra.cache') && $config_extra) {
209 4e9a3392 Scott Ullrich
		$configcacheextra = fopen($g['tmp_path'] . '/config.extra.cache', "w");
210
		fwrite($configcacheextra, serialize($config_extra));
211 1e0b1727 Phil Davis
		fclose($configcacheextra);
212 fd29caa1 Chris Buechler
		pfSense_fsync("{$g['tmp_path']}/config.extra.cache");
213 4e9a3392 Scott Ullrich
		unset($configcacheextra);
214
	}
215 12df7edc Erik
}
216
217
function discover_last_backup() {
218 692c21fd Renato Botelho
	$backups = glob('/cf/conf/backup/*.xml');
219 12df7edc Erik
	$last_backup = "";
220 692c21fd Renato Botelho
	$last_mtime = 0;
221 1e0b1727 Phil Davis
	foreach ($backups as $backup) {
222
		if (filemtime($backup) > $last_mtime) {
223 692c21fd Renato Botelho
			$last_mtime = filemtime($backup);
224
			$last_backup = $backup;
225
		}
226
	}
227 12df7edc Erik
228 692c21fd Renato Botelho
	return basename($last_backup);
229 12df7edc Erik
}
230
231
function restore_backup($file) {
232
	global $g;
233
234
	if (file_exists($file)) {
235
		conf_mount_rw();
236
		unlink_if_exists("{$g['tmp_path']}/config.cache");
237 086cf944 Phil Davis
		copy("$file", "/cf/conf/config.xml");
238 38b35612 Renato Botelho
		pfSense_fsync("/cf/conf/config.xml");
239 d7b97ca3 Chris Buechler
		pfSense_fsync($g['conf_path']);
240 0f806eca Erik Fonnesbeck
		disable_security_checks();
241 addc0439 Renato Botelho
		log_error(sprintf(gettext('%1$s is restoring the configuration %2$s'), $g['product_name'], $file));
242
		file_notice("config.xml", sprintf(gettext('%1$s is restoring the configuration %2$s'), $g['product_name'], $file), "pfSenseConfigurator", "");
243 12df7edc Erik
		conf_mount_ro();
244
	}
245
}
246
247
/****f* config/parse_config_bootup
248
 * NAME
249
 *   parse_config_bootup - Bootup-specific configuration checks.
250
 * RESULT
251
 *   null
252
 ******/
253
function parse_config_bootup() {
254 50cafcf3 Ermal
	global $config, $g;
255 12df7edc Erik
256 1e0b1727 Phil Davis
	if (platform_booting()) {
257 02e9880e Ermal
		echo ".";
258 1e0b1727 Phil Davis
	}
259 12df7edc Erik
260
	$lockkey = lock('config');
261 50cafcf3 Ermal
	if (!file_exists("{$g['conf_path']}/config.xml")) {
262 285ef132 Ermal LUÇI
		if (platform_booting()) {
263 50cafcf3 Ermal
			if (strstr($g['platform'], "cdrom")) {
264
				/* try copying the default config. to the floppy */
265 4816e5ca Renato Botelho
				echo gettext("Resetting factory defaults...") . "\n";
266 7d7da5e5 Phil Davis
				reset_factory_defaults(true, false);
267 50cafcf3 Ermal
				if (!file_exists("{$g['conf_path']}/config.xml")) {
268 4816e5ca Renato Botelho
					echo gettext("No XML configuration file found - using factory defaults.\n" .
269
								 "Make sure that the configuration floppy disk with the conf/config.xml\n" .
270 1c92c5b1 Stephen Beaver
								 "file is inserted. If it isn't, the configuration changes will be lost\n" .
271 4816e5ca Renato Botelho
								 "on reboot.\n");
272 12df7edc Erik
				}
273
			} else {
274 50cafcf3 Ermal
				$last_backup = discover_last_backup();
275 1e0b1727 Phil Davis
				if ($last_backup) {
276 50cafcf3 Ermal
					log_error("No config.xml found, attempting last known config restore.");
277 4816e5ca Renato Botelho
					file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", "");
278 50cafcf3 Ermal
					restore_backup("/cf/conf/backup/{$last_backup}");
279
				}
280 1e0b1727 Phil Davis
				if (!file_exists("{$g['conf_path']}/config.xml")) {
281 4816e5ca Renato Botelho
					echo sprintf(gettext("XML configuration file not found.  %s cannot continue booting."), $g['product_name']) . "\n";
282 02e9880e Ermal
					unlock($lockkey);
283 50cafcf3 Ermal
					mwexec("/sbin/halt");
284
					exit;
285
				}
286 1c92c5b1 Stephen Beaver
				log_error("Last known config found and restored.  Please double check the configuration file for accuracy.");
287
				file_notice("config.xml", gettext("Last known config found and restored.  Please double check the configuration file for accuracy."), "pfSenseConfigurator", "");
288 12df7edc Erik
			}
289 50cafcf3 Ermal
		} else {
290
			unlock($lockkey);
291 b5e8282d Ermal
			log_error(gettext("Could not find a usable configuration file! Exiting...."));
292 50cafcf3 Ermal
			exit(0);
293 12df7edc Erik
		}
294
	}
295 50cafcf3 Ermal
296 12df7edc Erik
	if (filesize("{$g['conf_path']}/config.xml") == 0) {
297
		$last_backup = discover_last_backup();
298 1e0b1727 Phil Davis
		if ($last_backup) {
299 4e038d31 Carlos Eduardo Ramos
			log_error(gettext("No config.xml found, attempting last known config restore."));
300
			file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", "");
301 12df7edc Erik
			restore_backup("{$g['conf_path']}/backup/{$last_backup}");
302
		} else {
303
			unlock($lockkey);
304 4e038d31 Carlos Eduardo Ramos
			die(gettext("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup."));
305 12df7edc Erik
		}
306
	}
307
	unlock($lockkey);
308
309 89adb2f3 Ermal
	$config = parse_config(true);
310
311 12df7edc Erik
	if ((float)$config['version'] > (float)$g['latest_config']) {
312
		echo <<<EOD
313
314
315
*******************************************************************************
316
* WARNING!                                                                    *
317
* The current configuration has been created with a newer version of {$g['product_name']}  *
318
* than this one! This can lead to serious misbehavior and even security       *
319
* holes! You are urged to either upgrade to a newer version of {$g['product_name']} or     *
320
* revert to the default configuration immediately!                            *
321
*******************************************************************************
322
323
324
EOD;
325
		}
326
327
	/* make alias table (for faster lookups) */
328
	alias_make_table($config);
329
}
330
331
/****f* config/conf_mount_rw
332
 * NAME
333
 *   conf_mount_rw - Mount filesystems read/write.
334
 * RESULT
335
 *   null
336
 ******/
337
/* mount flash card read/write */
338 63e18082 jim-p
function conf_mount_rw() {
339 7b229013 jim-p
	global $g, $config;
340 12df7edc Erik
341
	/* do not mount on cdrom platform */
342 2344bed4 Renato Botelho
	if ($g['platform'] == "cdrom" or $g['platform'] == $g['product_name']) {
343 12df7edc Erik
		return;
344 1e0b1727 Phil Davis
	}
345 a45e27ba Ermal
346 1e0b1727 Phil Davis
	if ((refcount_reference(1000) > 1) && is_writable("/")) {
347 12df7edc Erik
		return;
348 1e0b1727 Phil Davis
	}
349 12df7edc Erik
350 e8567e89 jim-p
	$status = mwexec("/sbin/mount -u -w -o sync,noatime {$g['cf_path']}");
351 1e0b1727 Phil Davis
	if ($status <> 0) {
352
		if (platform_booting()) {
353 d32c16bc Ermal LUÇI
			echo gettext("/cf Filesystem is dirty.") . "\n";
354 1e0b1727 Phil Davis
		}
355 e8567e89 jim-p
		$status = mwexec("/sbin/mount -u -w -o sync,noatime {$g['cf_path']}");
356 12df7edc Erik
	}
357
358 2344bed4 Renato Botelho
	/*    if the platform is soekris or wrap or $product, lets mount the
359 12df7edc Erik
	 *    compact flash cards root.
360 1e0b1727 Phil Davis
	*/
361 e8567e89 jim-p
	$status = mwexec("/sbin/mount -u -w -o sync,noatime /");
362 d32c16bc Ermal LUÇI
	/* we could not mount this correctly. */
363 1e0b1727 Phil Davis
	if ($status <> 0) {
364 d32c16bc Ermal LUÇI
		log_error(gettext("/ File system is dirty."));
365 e8567e89 jim-p
		$status = mwexec("/sbin/mount -u -w -o sync,noatime /");
366 12df7edc Erik
	}
367 1e0b1727 Phil Davis
368 12df7edc Erik
	mark_subsystem_dirty('mount');
369
}
370
371
/****f* config/conf_mount_ro
372
 * NAME
373
 *   conf_mount_ro - Mount filesystems readonly.
374
 * RESULT
375
 *   null
376
 ******/
377 63e18082 jim-p
function conf_mount_ro() {
378 7b229013 jim-p
	global $g, $config;
379 12df7edc Erik
380 7a5ab9e2 Chris Buechler
	// do nothing here. redmine #6184
381
	return;
382
383 2de8d745 jim-p
	/* Do not trust $g['platform'] since this can be clobbered during factory reset. */
384
	$platform = trim(file_get_contents("/etc/platform"));
385 23f0ca50 Ermal Lu?i
	/* do not umount on cdrom or pfSense platforms */
386 2344bed4 Renato Botelho
	if ($platform == "cdrom" or $platform == $g['product_name']) {
387 23f0ca50 Ermal Lu?i
		return;
388 1e0b1727 Phil Davis
	}
389 23f0ca50 Ermal Lu?i
390 1e0b1727 Phil Davis
	if (refcount_unreference(1000) > 0) {
391 52f4c092 Scott Ullrich
		return;
392 1e0b1727 Phil Davis
	}
393 52f4c092 Scott Ullrich
394 1e0b1727 Phil Davis
	if (isset($config['system']['nanobsd_force_rw'])) {
395 b8250344 Renato Botelho
		return;
396 1e0b1727 Phil Davis
	}
397 b8250344 Renato Botelho
398 1e0b1727 Phil Davis
	if (platform_booting()) {
399 12df7edc Erik
		return;
400 1e0b1727 Phil Davis
	}
401 12df7edc Erik
402
	clear_subsystem_dirty('mount');
403
	/* sync data, then force a remount of /cf */
404 d0577bd2 Renato Botelho
	pfSense_fsync($g['cf_path']);
405 e8567e89 jim-p
	mwexec("/sbin/mount -u -r -f -o sync,noatime {$g['cf_path']}");
406
	mwexec("/sbin/mount -u -r -f -o sync,noatime /");
407 12df7edc Erik
}
408
409
/****f* config/convert_config
410
 * NAME
411
 *   convert_config - Attempt to update config.xml.
412
 * DESCRIPTION
413
 *   convert_config() reads the current global configuration
414
 *   and attempts to convert it to conform to the latest
415
 *   config.xml version. This allows major formatting changes
416
 *   to be made with a minimum of breakage.
417
 * RESULT
418
 *   null
419
 ******/
420
/* convert configuration, if necessary */
421
function convert_config() {
422
	global $config, $g;
423
	$now = date("H:i:s");
424 4e038d31 Carlos Eduardo Ramos
	log_error(sprintf(gettext("Start Configuration upgrade at %s, set execution timeout to 15 minutes"), $now));
425 59cfe65d Ermal
	//ini_set("max_execution_time", "900");
426 12df7edc Erik
427
	/* special case upgrades */
428
	/* fix every minute crontab bogons entry */
429 32a9eb18 Ermal
	if (is_array($config['cron'])) {
430
		$cron_item_count = count($config['cron']['item']);
431 086cf944 Phil Davis
		for ($x = 0; $x < $cron_item_count; $x++) {
432 1e0b1727 Phil Davis
			if (stristr($config['cron']['item'][$x]['command'], "rc.update_bogons.sh")) {
433 086cf944 Phil Davis
				if ($config['cron']['item'][$x]['hour'] == "*") {
434 1e0b1727 Phil Davis
					$config['cron']['item'][$x]['hour'] = "3";
435 32a9eb18 Ermal
					write_config(gettext("Updated bogon update frequency to 3am"));
436
					log_error(gettext("Updated bogon update frequency to 3am"));
437 1e0b1727 Phil Davis
				}
438 32a9eb18 Ermal
			}
439 12df7edc Erik
		}
440
	}
441
442
	// Save off config version
443
	$prev_version = $config['version'];
444 1e0b1727 Phil Davis
445 b96cad97 Seth Mos
	include_once('auth.inc');
446 12df7edc Erik
	include_once('upgrade_config.inc');
447 1e0b1727 Phil Davis
	if (file_exists("/etc/inc/upgrade_config_custom.inc")) {
448 e58da189 Ermal
		include_once("upgrade_config_custom.inc");
449 1e0b1727 Phil Davis
	}
450 3aef796c Renato Botelho
451 54e11642 Renato Botelho
	if ($config['version'] == $g['latest_config']) {
452
		additional_config_upgrade();
453
		return;		/* already at latest version */
454
	}
455
456 3aef796c Renato Botelho
	if (!is_array($config['system']['already_run_config_upgrade'])) {
457
		$config['system']['already_run_config_upgrade'] = array();
458
	}
459 d3d9b707 Renato Botelho
	$already_run = $config['system']['already_run_config_upgrade'];
460 3aef796c Renato Botelho
461 12df7edc Erik
	/* Loop and run upgrade_VER_to_VER() until we're at current version */
462
	while ($config['version'] < $g['latest_config']) {
463
		$cur = $config['version'] * 10;
464
		$next = $cur + 1;
465 3aef796c Renato Botelho
		$migration_function = sprintf('upgrade_%03d_to_%03d', $cur,
466
		    $next);
467
468
		foreach (array("", "_custom") as $suffix) {
469
			$migration_function .= $suffix;
470
			if (!function_exists($migration_function)) {
471
				continue;
472
			}
473
			if (isset($already_run[$migration_function])) {
474
				/* Already executed, skip now */
475 d3d9b707 Renato Botelho
				unset($config['system']
476
				    ['already_run_config_upgrade']
477
				    [$migration_function]);
478 3aef796c Renato Botelho
			} else {
479
				$migration_function();
480
			}
481 1e0b1727 Phil Davis
		}
482 12df7edc Erik
		$config['version'] = sprintf('%.1f', $next / 10);
483 1e0b1727 Phil Davis
		if (platform_booting()) {
484 92cf9fcd sullrich
			echo ".";
485 1e0b1727 Phil Davis
		}
486 12df7edc Erik
	}
487
488 1e0b1727 Phil Davis
	if ($prev_version != $config['version']) {
489 54e11642 Renato Botelho
		$now = date("H:i:s");
490
		log_error(sprintf(gettext("Ended Configuration upgrade at %s"), $now));
491
492 addc0439 Renato Botelho
		write_config(sprintf(gettext('Upgraded config version level from %1$s to %2$s'), $prev_version, $config['version']));
493 1e0b1727 Phil Davis
	}
494 54e11642 Renato Botelho
495
	additional_config_upgrade();
496 12df7edc Erik
}
497
498 ddd42db3 Ermal Lu?i
/****f* config/safe_write_file
499
 * NAME
500
 *   safe_write_file - Write a file out atomically
501
 * DESCRIPTION
502
 *   safe_write_file() Writes a file out atomically by first writing to a
503
 *   temporary file of the same name but ending with the pid of the current
504
 *   process, them renaming the temporary file over the original.
505
 * INPUTS
506
 *   $filename  - string containing the filename of the file to write
507 952ff2cb Renato Botelho
 *   $content   - string or array containing the file content to write to file
508 ddd42db3 Ermal Lu?i
 *   $force_binary      - boolean denoting whether we should force binary
509
 *   mode writing.
510
 * RESULT
511
 *   boolean - true if successful, false if not
512
 ******/
513 e9c60f20 Renato Botelho
function safe_write_file($file, $content, $force_binary = false) {
514 628d1548 Ermal
	$tmp_file = $file . "." . getmypid();
515
	$write_mode = $force_binary ? "wb" : "w";
516 ddd42db3 Ermal Lu?i
517 628d1548 Ermal
	$fd = fopen($tmp_file, $write_mode);
518
	if (!$fd) {
519
		// Unable to open temporary file for writing
520
		return false;
521 1e0b1727 Phil Davis
	}
522 952ff2cb Renato Botelho
	if (is_array($content)) {
523
		foreach ($content as $line) {
524
			if (!fwrite($fd, $line . "\n")) {
525
				// Unable to write to temporary file
526
				fclose($fd);
527
				return false;
528
			}
529
		}
530
	} elseif (!fwrite($fd, $content)) {
531 628d1548 Ermal
		// Unable to write to temporary file
532 00bc5bcc Scott Ullrich
		fclose($fd);
533 628d1548 Ermal
		return false;
534
	}
535
	fflush($fd);
536
	fclose($fd);
537 ddd42db3 Ermal Lu?i
538 a83602e8 Renato Botelho
	if (!pfSense_fsync($tmp_file) || !rename($tmp_file, $file)) {
539 628d1548 Ermal
		// Unable to move temporary file to original
540
		@unlink($tmp_file);
541
		return false;
542
	}
543 00bc5bcc Scott Ullrich
544 628d1548 Ermal
	// Sync file before returning
545 8a811010 Chris Buechler
	return pfSense_fsync($file);
546 ddd42db3 Ermal Lu?i
}
547
548 12df7edc Erik
/****f* config/write_config
549
 * NAME
550
 *   write_config - Backup and write the firewall configuration.
551
 * DESCRIPTION
552
 *   write_config() handles backing up the current configuration,
553
 *   applying changes, and regenerating the configuration cache.
554
 * INPUTS
555
 *   $desc	- string containing the a description of configuration changes
556
 *   $backup	- boolean: do not back up current configuration if false.
557 f5315ac1 NOYB
 *   $write_config_only	- boolean: do not sync or reload anything; just save the configuration if true.
558 12df7edc Erik
 * RESULT
559
 *   null
560
 ******/
561
/* save the system configuration */
562 429e0911 NOYB
function write_config($desc="Unknown", $backup = true, $write_config_only = false) {
563 12df7edc Erik
	global $config, $g;
564
565 a74260cb jim-p
	if (!empty($_SERVER['REMOTE_ADDR'])) {
566 1e0b1727 Phil Davis
		if (!session_id()) {
567 a74260cb jim-p
			@session_start();
568 1e0b1727 Phil Davis
		}
569 cf0dae69 Ermal
		if (!empty($_SESSION['Username']) && ($_SESSION['Username'] != "admin")) {
570
			$user = getUserEntry($_SESSION['Username']);
571
			if (is_array($user) && userHasPrivilege($user, "user-config-readonly")) {
572
				session_commit();
573
				return false;
574
			}
575 4111fcf5 Ermal
		}
576 170cb2bc jim-p
	}
577 4111fcf5 Ermal
578 1e0b1727 Phil Davis
	if (!isset($argc)) {
579 9d584d5d Ermal
		session_commit();
580 1e0b1727 Phil Davis
	}
581 4111fcf5 Ermal
582 af0f961b Phil Davis
	if (isset($config['reset_factory_defaults'])) {
583
		/*
584
		   We have put a default config.xml on disk and are about to reboot
585
		   or reload it. Do not let any system or package code try to save
586
		   state to config because that would overwrite the default config
587
		   with the running config.
588
		*/
589
		return false;
590
	}
591
592 1e0b1727 Phil Davis
	if ($backup) {
593 12df7edc Erik
		backup_config();
594 1e0b1727 Phil Davis
	}
595 12df7edc Erik
596 ba1d9714 jim-p
	$config['revision'] = make_config_revision_entry($desc);
597 12df7edc Erik
598 b6c34bfc Ermal
	conf_mount_rw();
599
	$lockkey = lock('config', LOCK_EX);
600 12df7edc Erik
601
	/* generate configuration XML */
602
	$xmlconfig = dump_xml_config($config, $g['xml_rootobj']);
603
604 41bf8e8e Scott Ullrich
	/* write new configuration */
605 e9c60f20 Renato Botelho
	if (!safe_write_file("{$g['cf_conf_path']}/config.xml", $xmlconfig)) {
606 89a8d28e Chris Buechler
		log_error(gettext("WARNING: Config contents could not be saved. Could not open file!"));
607 12df7edc Erik
		unlock($lockkey);
608 4e038d31 Carlos Eduardo Ramos
		file_notice("config.xml", sprintf(gettext("Unable to open %s/config.xml for writing in write_config()%s"), $g['cf_conf_path'], "\n"));
609 541989d5 Ermal
		return -1;
610 e5977136 Scott Ullrich
	}
611 1e0b1727 Phil Davis
612 e1ebe9e2 jim-p
	cleanup_backupcache(true);
613 12df7edc Erik
614
	/* re-read configuration */
615 541989d5 Ermal
	/* NOTE: We assume that the file can be parsed since we wrote it. */
616 12df7edc Erik
	$config = parse_xml_config("{$g['conf_path']}/config.xml", $g['xml_rootobj']);
617 e490f995 Ermal
	if ($config == -1) {
618 557300a7 jim-p
		copy("{$g['conf_path']}/config.xml", "{$g['conf_path']}/config.xml.bad");
619 e490f995 Ermal
		$last_backup = discover_last_backup();
620 557300a7 jim-p
		if ($last_backup) {
621 e490f995 Ermal
			restore_backup("/cf/conf/backup/{$last_backup}");
622 557300a7 jim-p
			$config = parse_xml_config("{$g['conf_path']}/config.xml", $g['xml_rootobj']);
623 285ef132 Ermal LUÇI
			if (platform_booting()) {
624 557300a7 jim-p
				echo "\n\n ************** WARNING **************";
625 6177fd92 jim-p
				echo "\n\n Configuration could not be validated. A previous configuration was restored. \n";
626 05d5503b Ermal
				echo "\n The failed configuration file has been saved as {$g['conf_path']}/config.xml.bad \n\n";
627 557300a7 jim-p
			}
628 1e0b1727 Phil Davis
		} else {
629 e490f995 Ermal
			log_error(gettext("Could not restore config.xml."));
630 1e0b1727 Phil Davis
		}
631
	} else {
632 e490f995 Ermal
		generate_config_cache($config);
633 1e0b1727 Phil Davis
	}
634 12df7edc Erik
635
	unlock($lockkey);
636
637 429e0911 NOYB
	if ($write_config_only) {
638
		/* tell kernel to sync fs data */
639
		conf_mount_ro();
640
		return $config;
641
	}
642
643 12df7edc Erik
	unlink_if_exists("/usr/local/pkg/pf/carp_sync_client.php");
644 16b96ea6 Scott Ullrich
645 b6c34bfc Ermal
	/* tell kernel to sync fs data */
646
	conf_mount_ro();
647
648 12df7edc Erik
	/* sync carp entries to other firewalls */
649 16b96ea6 Scott Ullrich
	carp_sync_client();
650 12df7edc Erik
651 1e0b1727 Phil Davis
	if (is_dir("/usr/local/pkg/write_config")) {
652 12df7edc Erik
		/* process packager manager custom rules */
653
		run_plugins("/usr/local/pkg/write_config/");
654
	}
655
656
	return $config;
657
}
658
659
/****f* config/reset_factory_defaults
660
 * NAME
661
 *   reset_factory_defaults - Reset the system to its default configuration.
662
 * RESULT
663
 *   integer	- indicates completion
664
 ******/
665 7d7da5e5 Phil Davis
function reset_factory_defaults($lock = false, $reboot_required = true) {
666 af0f961b Phil Davis
	global $config, $g;
667 12df7edc Erik
668 961884ae Renato Botelho
	conf_mount_rw();
669 7222324e Renato Botelho
670 961884ae Renato Botelho
	/* Remove all additional packages */
671 5e8c3fa0 Renato Botelho
	mwexec("/bin/sh /usr/local/sbin/{$g['product_name']}-upgrade " .
672
	    "-r ALL_PACKAGES");
673 7222324e Renato Botelho
674 1e0b1727 Phil Davis
	if (!$lock) {
675 b6c34bfc Ermal
		$lockkey = lock('config', LOCK_EX);
676 1e0b1727 Phil Davis
	}
677 12df7edc Erik
678
	/* create conf directory, if necessary */
679 5e8c3fa0 Renato Botelho
	safe_mkdir($g['cf_conf_path']);
680 12df7edc Erik
681
	/* clear out /conf */
682
	$dh = opendir($g['conf_path']);
683
	while ($filename = readdir($dh)) {
684 5e8c3fa0 Renato Botelho
		if (($filename != ".") && ($filename != "..") &&
685
		    (!is_dir($g['conf_path'] . "/" . $filename))) {
686 12df7edc Erik
			unlink_if_exists($g['conf_path'] . "/" . $filename);
687
		}
688
	}
689
	closedir($dh);
690 63dd9f08 Ermal
	unlink_if_exists($g['tmp_path'] . "/config.cache");
691 12df7edc Erik
692
	/* copy default configuration */
693 5e8c3fa0 Renato Botelho
	copy("{$g['conf_default_path']}/config.xml",
694
	    "{$g['cf_conf_path']}/config.xml");
695 12df7edc Erik
696 0f806eca Erik Fonnesbeck
	disable_security_checks();
697
698 af0f961b Phil Davis
	/*
699
	   Let write_config know that we are awaiting reload of the current config
700
	   to factory defaults. Either the system is about to reboot, throwing away
701
	   the current in-memory config as it shuts down, or the in-memory config
702
	   is about to be reloaded on-the-fly by parse_config.
703
704
	   In both cases, we want to ensure that write_config does not flush the
705
	   in-memory config back to disk.
706
	*/
707
	$config['reset_factory_defaults'] = true;
708
709 12df7edc Erik
	/* call the wizard */
710 7d7da5e5 Phil Davis
	if ($reboot_required) {
711
		// If we need a reboot first then touch a different trigger file.
712
		touch("/conf/trigger_initial_wizard_after_reboot");
713
	} else {
714
		touch("/conf/trigger_initial_wizard");
715
	}
716 1e0b1727 Phil Davis
	if (!$lock) {
717 12df7edc Erik
		unlock($lockkey);
718 1e0b1727 Phil Davis
	}
719 b6c34bfc Ermal
	conf_mount_ro();
720 673966e4 jim-p
	setup_serial_port();
721 12df7edc Erik
	return 0;
722
}
723
724
function config_restore($conffile) {
725
	global $config, $g;
726
727 1e0b1727 Phil Davis
	if (!file_exists($conffile)) {
728 12df7edc Erik
		return 1;
729 1e0b1727 Phil Davis
	}
730 12df7edc Erik
731
	backup_config();
732
733 f2087c85 Scott Ullrich
	conf_mount_rw();
734 1e0b1727 Phil Davis
735 b6c34bfc Ermal
	$lockkey = lock('config', LOCK_EX);
736 12df7edc Erik
737
	unlink_if_exists("{$g['tmp_path']}/config.cache");
738 e490f995 Ermal
	copy($conffile, "{$g['cf_conf_path']}/config.xml");
739 12df7edc Erik
740 0f806eca Erik Fonnesbeck
	disable_security_checks();
741
742 12df7edc Erik
	unlock($lockkey);
743
744
	$config = parse_config(true);
745
746
	conf_mount_ro();
747
748 d18f3f6e Phil Davis
	write_config(sprintf(gettext("Reverted to %s."), array_pop(explode("/", $conffile))), false);
749 e296b183 Ermal Lu?i
750 12df7edc Erik
	return 0;
751
}
752
753
function config_install($conffile) {
754
	global $config, $g;
755
756 1e0b1727 Phil Davis
	if (!file_exists($conffile)) {
757 12df7edc Erik
		return 1;
758 1e0b1727 Phil Davis
	}
759 12df7edc Erik
760 1e0b1727 Phil Davis
	if (!config_validate("{$conffile}")) {
761 12df7edc Erik
		return 1;
762 1e0b1727 Phil Davis
	}
763 12df7edc Erik
764 1e0b1727 Phil Davis
	if (platform_booting()) {
765 4e038d31 Carlos Eduardo Ramos
		echo gettext("Installing configuration...") . "\n";
766 1e0b1727 Phil Davis
	} else {
767 4e038d31 Carlos Eduardo Ramos
		log_error(gettext("Installing configuration ...."));
768 1e0b1727 Phil Davis
	}
769 12df7edc Erik
770
	conf_mount_rw();
771 b6c34bfc Ermal
	$lockkey = lock('config', LOCK_EX);
772 12df7edc Erik
773
	copy($conffile, "{$g['conf_path']}/config.xml");
774
775 0f806eca Erik Fonnesbeck
	disable_security_checks();
776
777 12df7edc Erik
	/* unlink cache file if it exists */
778 1e0b1727 Phil Davis
	if (file_exists("{$g['tmp_path']}/config.cache")) {
779 12df7edc Erik
		unlink("{$g['tmp_path']}/config.cache");
780 1e0b1727 Phil Davis
	}
781 12df7edc Erik
782
	unlock($lockkey);
783
	conf_mount_ro();
784
785 1e0b1727 Phil Davis
	return 0;
786 12df7edc Erik
}
787
788 0f806eca Erik Fonnesbeck
/*
789
 * Disable security checks for DNS rebind and HTTP referrer until next time
790
 * they pass (or reboot), to aid in preventing accidental lockout when
791
 * restoring settings like hostname, domain, IP addresses, and settings
792
 * related to the DNS rebind and HTTP referrer checks.
793
 * Intended for use when restoring a configuration or directly
794
 * modifying config.xml without an unconditional reboot.
795
 */
796
function disable_security_checks() {
797
	global $g;
798
	touch("{$g['tmp_path']}/disable_security_checks");
799
}
800
801
/* Restores security checks.  Should be called after all succeed. */
802
function restore_security_checks() {
803
	global $g;
804
	unlink_if_exists("{$g['tmp_path']}/disable_security_checks");
805
}
806
807
/* Returns status of security check temporary disable. */
808
function security_checks_disabled() {
809
	global $g;
810
	return file_exists("{$g['tmp_path']}/disable_security_checks");
811
}
812
813 12df7edc Erik
function config_validate($conffile) {
814
815
	global $g, $xmlerr;
816
817
	$xml_parser = xml_parser_create();
818
819
	if (!($fp = fopen($conffile, "r"))) {
820 4e038d31 Carlos Eduardo Ramos
		$xmlerr = gettext("XML error: unable to open file");
821 12df7edc Erik
		return false;
822
	}
823
824
	while ($data = fread($fp, 4096)) {
825
		if (!xml_parse($xml_parser, $data, feof($fp))) {
826 addc0439 Renato Botelho
			$xmlerr = sprintf(gettext('%1$s at line %2$d'),
827 12df7edc Erik
						xml_error_string(xml_get_error_code($xml_parser)),
828
						xml_get_current_line_number($xml_parser));
829
			return false;
830
		}
831
	}
832
	xml_parser_free($xml_parser);
833
834
	fclose($fp);
835
836
	return true;
837
}
838
839 e1ebe9e2 jim-p
function cleanup_backupcache($lock = false) {
840 8c5b9920 jim-p
	global $config, $g;
841 12df7edc Erik
	$i = false;
842 e1ebe9e2 jim-p
843 3d256eb1 stilez
	$revisions = intval(is_numericint($config['system']['backupcount']) ? $config['system']['backupcount'] : $g['default_config_backup_count']);
844 e1ebe9e2 jim-p
845 1e0b1727 Phil Davis
	if (!$lock) {
846 12df7edc Erik
		$lockkey = lock('config');
847 1e0b1727 Phil Davis
	}
848 cd25a2b2 jim-p
849
	conf_mount_rw();
850
851
	$backups = get_backups();
852
	if ($backups) {
853 12df7edc Erik
		$baktimes = $backups['versions'];
854
		unset($backups['versions']);
855 cd25a2b2 jim-p
	} else {
856
		$backups = array();
857
		$baktimes = array();
858
	}
859
	$newbaks = array();
860
	$bakfiles = glob($g['cf_conf_path'] . "/backup/config-*");
861
	$tocache = array();
862 12df7edc Erik
863 1e0b1727 Phil Davis
	foreach ($bakfiles as $backup) { // Check for backups in the directory not represented in the cache.
864 bfe615ee jim-p
		$backupsize = filesize($backup);
865 1e0b1727 Phil Davis
		if ($backupsize == 0) {
866 cd25a2b2 jim-p
			unlink($backup);
867
			continue;
868
		}
869 b3bbed58 Ermal LUÇI
		$backupexp = explode('-', $backup);
870
		$backupexp = explode('.', array_pop($backupexp));
871
		$tocheck = array_shift($backupexp);
872
		unset($backupexp);
873 1e0b1727 Phil Davis
		if (!in_array($tocheck, $baktimes)) {
874 cd25a2b2 jim-p
			$i = true;
875 1e0b1727 Phil Davis
			if (platform_booting()) {
876 cd25a2b2 jim-p
				echo ".";
877 1e0b1727 Phil Davis
			}
878 990d7c03 Erik Fonnesbeck
			$newxml = parse_xml_config($backup, array($g['xml_rootobj'], 'pfsense'));
879 1e0b1727 Phil Davis
			if ($newxml == "-1") {
880 4e038d31 Carlos Eduardo Ramos
				log_error(sprintf(gettext("The backup cache file %s is corrupted.  Unlinking."), $backup));
881 cd25a2b2 jim-p
				unlink($backup);
882 4e038d31 Carlos Eduardo Ramos
				log_error(sprintf(gettext("The backup cache file %s is corrupted.  Unlinking."), $backup));
883 cd25a2b2 jim-p
				continue;
884 12df7edc Erik
			}
885 1e0b1727 Phil Davis
			if ($newxml['revision']['description'] == "") {
886 cd25a2b2 jim-p
				$newxml['revision']['description'] = "Unknown";
887 1e0b1727 Phil Davis
			}
888
			if ($newxml['version'] == "") {
889 92420c0a jim-p
				$newxml['version'] = "?";
890 1e0b1727 Phil Davis
			}
891 bfe615ee jim-p
			$tocache[$tocheck] = array('description' => $newxml['revision']['description'], 'version' => $newxml['version'], 'filesize' => $backupsize);
892 12df7edc Erik
		}
893 cd25a2b2 jim-p
	}
894 1e0b1727 Phil Davis
	foreach ($backups as $checkbak) {
895
		if (count(preg_grep('/' . $checkbak['time'] . '/i', $bakfiles)) != 0) {
896 cd25a2b2 jim-p
			$newbaks[] = $checkbak;
897
		} else {
898
			$i = true;
899 285ef132 Ermal LUÇI
			if (platform_booting()) print " " . $tocheck . "r";
900 cd25a2b2 jim-p
		}
901
	}
902 1e0b1727 Phil Davis
	foreach ($newbaks as $todo) {
903
		$tocache[$todo['time']] = array('description' => $todo['description'], 'version' => $todo['version'], 'filesize' => $todo['filesize']);
904
	}
905
	if (is_int($revisions) and (count($tocache) > $revisions)) {
906 cd25a2b2 jim-p
		$toslice = array_slice(array_keys($tocache), 0, $revisions);
907 1e0b1727 Phil Davis
		foreach ($toslice as $sliced) {
908 cd25a2b2 jim-p
			$newcache[$sliced] = $tocache[$sliced];
909 1e0b1727 Phil Davis
		}
910
		foreach ($tocache as $version => $versioninfo) {
911
			if (!in_array($version, array_keys($newcache))) {
912 cd25a2b2 jim-p
				unlink_if_exists($g['conf_path'] . '/backup/config-' . $version . '.xml');
913 12df7edc Erik
			}
914
		}
915 cd25a2b2 jim-p
		$tocache = $newcache;
916 12df7edc Erik
	}
917 cd25a2b2 jim-p
	$bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
918
	fwrite($bakout, serialize($tocache));
919
	fclose($bakout);
920 8a811010 Chris Buechler
	pfSense_fsync("{$g['cf_conf_path']}/backup/backup.cache");
921 cd25a2b2 jim-p
	conf_mount_ro();
922
923 1e0b1727 Phil Davis
	if (!$lock) {
924 12df7edc Erik
		unlock($lockkey);
925 1e0b1727 Phil Davis
	}
926 12df7edc Erik
}
927
928
function get_backups() {
929
	global $g;
930 1e0b1727 Phil Davis
	if (file_exists("{$g['cf_conf_path']}/backup/backup.cache")) {
931 12df7edc Erik
		$confvers = unserialize(file_get_contents("{$g['cf_conf_path']}/backup/backup.cache"));
932
		$bakvers = array_keys($confvers);
933
		$toreturn = array();
934
		sort($bakvers);
935
		// 	$bakvers = array_reverse($bakvers);
936 1e0b1727 Phil Davis
		foreach (array_reverse($bakvers) as $bakver) {
937 bfe615ee jim-p
			$toreturn[] = array('time' => $bakver, 'description' => $confvers[$bakver]['description'], 'version' => $confvers[$bakver]['version'], 'filesize' => $confvers[$bakver]['filesize']);
938 1e0b1727 Phil Davis
		}
939 12df7edc Erik
	} else {
940
		return false;
941
	}
942
	$toreturn['versions'] = $bakvers;
943
	return $toreturn;
944
}
945
946
function backup_config() {
947
	global $config, $g;
948
949 1e0b1727 Phil Davis
	if ($g['platform'] == "cdrom") {
950 12df7edc Erik
		return;
951 1e0b1727 Phil Davis
	}
952 12df7edc Erik
953
	conf_mount_rw();
954
955
	/* Create backup directory if needed */
956
	safe_mkdir("{$g['cf_conf_path']}/backup");
957 1e0b1727 Phil Davis
	if ($config['revision']['time'] == "") {
958
		$baktime = 0;
959
	} else {
960
		$baktime = $config['revision']['time'];
961
	}
962 8a811010 Chris Buechler
963 1e0b1727 Phil Davis
	if ($config['revision']['description'] == "") {
964
		$bakdesc = "Unknown";
965
	} else {
966
		$bakdesc = $config['revision']['description'];
967
	}
968 8059f9cb jim-p
969
	$bakver = ($config['version'] == "") ? "?" : $config['version'];
970 bfe615ee jim-p
	$bakfilename = $g['cf_conf_path'] . '/backup/config-' . $baktime . '.xml';
971
	copy($g['cf_conf_path'] . '/config.xml', $bakfilename);
972 8a811010 Chris Buechler
973 1e0b1727 Phil Davis
	if (file_exists($g['cf_conf_path'] . '/backup/backup.cache')) {
974
		$backupcache = unserialize(file_get_contents($g['cf_conf_path'] . '/backup/backup.cache'));
975
	} else {
976
		$backupcache = array();
977
	}
978 bfe615ee jim-p
	$backupcache[$baktime] = array('description' => $bakdesc, 'version' => $bakver, 'filesize' => filesize($bakfilename));
979 1e0b1727 Phil Davis
	$bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
980
	fwrite($bakout, serialize($backupcache));
981
	fclose($bakout);
982 8a811010 Chris Buechler
	pfSense_fsync("{$g['cf_conf_path']}/backup/backup.cache");
983 12df7edc Erik
984
	conf_mount_ro();
985
986
	return true;
987
}
988
989
function set_device_perms() {
990
	$devices = array(
991 6c07db48 Phil Davis
		'pf' => array(
992
			'user' => 'root',
993
			'group' => 'proxy',
994
			'mode' => 0660),
995 12df7edc Erik
		);
996
997
	foreach ($devices as $name => $attr) {
998
		$path = "/dev/$name";
999
		if (file_exists($path)) {
1000
			chown($path, $attr['user']);
1001
			chgrp($path, $attr['group']);
1002
			chmod($path, $attr['mode']);
1003
		}
1004
	}
1005
}
1006
1007 ba1d9714 jim-p
function get_config_user() {
1008
	if (empty($_SESSION["Username"])) {
1009 362ec35d Ermal
		$username = getenv("USER");
1010 1e0b1727 Phil Davis
		if (empty($conuser) || $conuser == "root") {
1011 ba1d9714 jim-p
			$username = "(system)";
1012 1e0b1727 Phil Davis
		}
1013
	} else {
1014 ba1d9714 jim-p
		$username = $_SESSION["Username"];
1015 1e0b1727 Phil Davis
	}
1016 ba1d9714 jim-p
1017 1e0b1727 Phil Davis
	if (!empty($_SERVER['REMOTE_ADDR'])) {
1018 ba1d9714 jim-p
		$username .= '@' . $_SERVER['REMOTE_ADDR'];
1019 1e0b1727 Phil Davis
	}
1020 ba1d9714 jim-p
1021
	return $username;
1022
}
1023
1024
function make_config_revision_entry($desc = null, $override_user = null) {
1025 1e0b1727 Phil Davis
	if (empty($override_user)) {
1026 ba1d9714 jim-p
		$username = get_config_user();
1027 1e0b1727 Phil Davis
	} else {
1028 ba1d9714 jim-p
		$username = $override_user;
1029 1e0b1727 Phil Davis
	}
1030 ba1d9714 jim-p
1031
	$revision = array();
1032
1033 1e0b1727 Phil Davis
	if (time() > mktime(0, 0, 0, 9, 1, 2004)) {     /* make sure the clock settings are plausible */
1034 ba1d9714 jim-p
		$revision['time'] = time();
1035 1e0b1727 Phil Davis
	}
1036 ba1d9714 jim-p
1037
	/* Log the running script so it's not entirely unlogged what changed */
1038 1e0b1727 Phil Davis
	if ($desc == "Unknown") {
1039 ba1d9714 jim-p
		$desc = sprintf(gettext("%s made unknown change"), $_SERVER['SCRIPT_NAME']);
1040 1e0b1727 Phil Davis
	}
1041
	if (!empty($desc)) {
1042 ba1d9714 jim-p
		$revision['description'] = "{$username}: " . $desc;
1043 1e0b1727 Phil Davis
	}
1044 ba1d9714 jim-p
	$revision['username'] = $username;
1045
	return $revision;
1046
}
1047
1048 00e55088 Ermal
function pfSense_clear_globals() {
1049
	global $config, $FilterIfList, $GatewaysList, $filterdns, $aliases, $aliastable;
1050
1051 be2d7eb7 Chris Buechler
	$error = error_get_last();
1052 1e0b1727 Phil Davis
1053 ce5e2867 stilez
	// Errors generated by user code (diag_commands.php) are identified by path and not added to notices
1054 3ca59456 Renato Botelho
	if ($error !== NULL && !preg_match('|^' . preg_quote($g['tmp_path_user_code']) . '/[^/]{1,16}$|', $error['file'])) {
1055 e102e1d9 PiBa-NL
		if (in_array($error['type'], array(E_ERROR, E_COMPILE_ERROR, E_CORE_ERROR, E_RECOVERABLE_ERROR))) {
1056 be2d7eb7 Chris Buechler
			$errorstr = "PHP ERROR: Type: {$error['type']}, File: {$error['file']}, Line: {$error['line']}, Message: {$error['message']}";
1057 b3f2f476 PiBa-NL
			print($errorstr);
1058
			log_error($errorstr);
1059 e102e1d9 PiBa-NL
			file_notice("phperror", $errorstr, 'PHP errors');
1060 6c07db48 Phil Davis
		} else if ($error['type'] != E_NOTICE) {
1061 b3f2f476 PiBa-NL
			$errorstr = "PHP WARNING: Type: {$error['type']}, File: {$error['file']}, Line: {$error['line']}, Message: {$error['message']}";
1062 e8e494f3 Chris Buechler
			// XXX: comment out for now, should re-enable post-2.2
1063
			//print($errorstr);
1064
			//log_error($errorstr);
1065 e102e1d9 PiBa-NL
			//file_notice("phpwarning", $errorstr, 'PHP warning');
1066 be2d7eb7 Chris Buechler
		}
1067
	}
1068
1069 1e0b1727 Phil Davis
	if (isset($FilterIfList)) {
1070 00e55088 Ermal
		unset($FilterIfList);
1071 1e0b1727 Phil Davis
	}
1072 00e55088 Ermal
1073 1e0b1727 Phil Davis
	if (isset($GatewaysList)) {
1074 00e55088 Ermal
		unset($GatewaysList);
1075 1e0b1727 Phil Davis
	}
1076 00e55088 Ermal
1077
	/* Used for the hostname dns resolver */
1078 1e0b1727 Phil Davis
	if (isset($filterdns)) {
1079 00e55088 Ermal
		unset($filterdns);
1080 1e0b1727 Phil Davis
	}
1081 00e55088 Ermal
1082
	/* Used for aliases and interface macros */
1083 1e0b1727 Phil Davis
	if (isset($aliases)) {
1084 00e55088 Ermal
		unset($aliases);
1085 1e0b1727 Phil Davis
	}
1086
	if (isset($aliastable)) {
1087 00e55088 Ermal
		unset($aliastable);
1088 1e0b1727 Phil Davis
	}
1089 00e55088 Ermal
1090
	unset($config);
1091
}
1092
1093
register_shutdown_function('pfSense_clear_globals');
1094
1095 09221bc3 Renato Botelho
?>