Project

General

Profile

Download (24.4 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/config
3
 * NAME
4
 *   config.lib.inc - Functions to manipulate config.xml
5
 * DESCRIPTION
6
 *   This include contains various config.xml specific functions.
7
 * HISTORY
8
 * $Id$
9
 ******
10

    
11
	config.lib.inc
12
	Ported from config.inc by Erik Kristensen
13
	Copyright (C) 2004-2010 Scott Ullrich
14
	All rights reserved.
15

    
16
	originally part of m0n0wall (http://m0n0.ch/wall)
17
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
18
	All rights reserved.
19

    
20
	Redistribution and use in source and binary forms, with or without
21
	modification, are permitted provided that the following conditions are met:
22

    
23
	1. Redistributions of source code must retain the above copyright notice,
24
	   this list of conditions and the following disclaimer.
25

    
26
	2. Redistributions in binary form must reproduce the above copyright
27
	   notice, this list of conditions and the following disclaimer in the
28
	   documentation and/or other materials provided with the distribution.
29

    
30
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
31
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
32
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
33
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
34
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39
	POSSIBILITY OF SUCH DAMAGE.
40

    
41

    
42
	pfSense_BUILDER_BINARIES:	/sbin/mount	/sbin/sysctl	/sbin/umount	/sbin/halt	/sbin/fsck
43
	pfSense_MODULE:	config
44
*/
45

    
46
/****f* config/encrypted_configxml
47
 * NAME
48
 *   encrypted_configxml - Checks to see if config.xml is encrypted and if so, prompts to unlock.
49
 * INPUTS
50
 *   None
51
 * RESULT
52
 *   $config 	- rewrites config.xml without encryption
53
 ******/
54
function encrypted_configxml() {
55
	global $g, $config;
56

    
57
	if (!file_exists($g['conf_path'] . "/config.xml"))
58
		return;
59

    
60
	if (!$g['booting'])
61
		return;
62

    
63
	$configtxt = file_get_contents($g['conf_path'] . "/config.xml");			
64
	if(tagfile_deformat($configtxt, $configtxt, "config.xml")) {
65
		$fp = fopen('php://stdin', 'r');
66
		$data = "";
67
		echo "\n\n*** Encrypted config.xml detected ***\n";
68
		while($data == "") {
69
			echo "\nEnter the password to decrypt config.xml: ";
70
			$decrypt_password = chop(fgets($fp));
71
			$data = decrypt_data($configtxt, $decrypt_password);
72
			if(!strstr($data, "<pfsense>"))
73
				$data = "";
74
			if($data) {
75
				$fd = fopen($g['conf_path'] . "/config.xml.tmp", "w");
76
				fwrite($fd, $data);
77
				fclose($fd);
78
				exec("/bin/mv {$g['conf_path']}/config.xml.tmp {$g['conf_path']}/config.xml");
79
				echo "\nConfig.xml unlocked.\n";
80
				fclose($fp);
81
			} else {
82
				echo "\nInvalid password entered.  Please try again.\n";
83
			}
84
		}
85
	}
86
}
87

    
88
/****f* config/parse_config
89
 * NAME
90
 *   parse_config - Read in config.cache or config.xml if needed and return $config array
91
 * INPUTS
92
 *   $parse       - boolean to force parse_config() to read config.xml and generate config.cache
93
 * RESULT
94
 *   $config      - array containing all configuration variables
95
 ******/
96
function parse_config($parse = false) {
97
	global $g, $config_parsed, $config_extra;
98

    
99
	$lockkey = lock('config');
100
	$config_parsed = false;
101

    
102
	if (!file_exists("{$g['conf_path']}/config.xml") || filesize("{$g['conf_path']}/config.xml") == 0) {
103
		$last_backup = discover_last_backup();
104
		if($last_backup) {
105
			log_error("No config.xml found, attempting last known config restore.");
106
			file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
107
			restore_backup("{$g['conf_path']}/backup/{$last_backup}");
108
		} else {
109
			unlock($lockkey);
110
			die("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup.");
111
		}
112
	}
113

    
114
	if($g['booting'])
115
		echo ".";
116

    
117
	// Check for encrypted config.xml
118
	encrypted_configxml();
119

    
120
	if(!$parse) {
121
		if (file_exists($g['tmp_path'] . '/config.cache')) {
122
			$config = unserialize(file_get_contents($g['tmp_path'] . '/config.cache'));
123
			if (is_null($config))
124
				$parse = true;
125
		} else
126
			$parse = true;
127
	}
128
	if ($parse == true) {
129
		if(!file_exists($g['conf_path'] . "/config.xml")) {
130
			if($g['booting'])
131
				echo ".";
132
			log_error("No config.xml found, attempting last known config restore.");
133
			file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
134
			$last_backup = discover_last_backup();
135
			if ($last_backup)
136
				restore_backup("/cf/conf/backup/{$last_backup}");
137
			else {
138
				log_error("Could not restore config.xml.");
139
				unlock($lockkey);
140
				die("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup.");
141
			}
142
		}
143
		$config = parse_xml_config($g['conf_path'] . '/config.xml', array($g['xml_rootobj'], 'pfsense'));
144
		if($config == -1) {
145
			$last_backup = discover_last_backup();
146
			if ($last_backup)
147
				restore_backup("/cf/conf/backup/{$last_backup}");
148
			else {
149
				log_error(gettext("Could not restore config.xml."));
150
				unlock($lockkey);
151
				die("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup.");
152
			}
153
		}
154
		generate_config_cache($config);
155
	}
156

    
157
	if($g['booting'])
158
		echo ".";
159

    
160
	$config_parsed = true;
161
	unlock($lockkey);
162

    
163
	alias_make_table($config);
164

    
165
	return $config;
166
}
167

    
168
/****f* config/generate_config_cache
169
 * NAME
170
 *   generate_config_cache - Write serialized configuration to cache.
171
 * INPUTS
172
 *   $config	- array containing current firewall configuration
173
 * RESULT
174
 *   boolean	- true on completion
175
 ******/
176
function generate_config_cache($config) {
177
	global $g, $config_extra;
178

    
179
	$configcache = fopen($g['tmp_path'] . '/config.cache', "w");
180
	fwrite($configcache, serialize($config));
181
	fclose($configcache);
182
	unset($configcache);
183
	/* Used for config.extra.xml */
184
	if(file_exists($g['tmp_path'] . '/config.extra.cache') && $config_extra) {
185
		$configcacheextra = fopen($g['tmp_path'] . '/config.extra.cache', "w");
186
		fwrite($configcacheextra, serialize($config_extra));
187
		fclose($configcacheextra);		
188
		unset($configcacheextra);
189
	}
190
}
191

    
192
function discover_last_backup() {
193
        $backups = split("\n", `cd /cf/conf/backup && ls -ltr *.xml | awk '{print \$9}'`);
194
	$last_backup = "";
195
        foreach($backups as $backup)
196
        	if($backup)
197
	        	$last_backup = $backup;
198

    
199
        return $last_backup;
200
}
201

    
202
function restore_backup($file) {
203
	global $g;
204

    
205
	if (file_exists($file)) {
206
		conf_mount_rw();
207
		unlink_if_exists("{$g['tmp_path']}/config.cache");
208
		copy("$file","/cf/conf/config.xml");
209
		disable_security_checks();
210
		log_error("{$g['product_name']} is restoring the configuration $file");
211
		file_notice("config.xml", "{$g['product_name']} is restoring the configuration $file", "{$g['product_name']}Configurator", "");
212
		conf_mount_ro();
213
	}
214
}
215

    
216
/****f* config/parse_config_bootup
217
 * NAME
218
 *   parse_config_bootup - Bootup-specific configuration checks.
219
 * RESULT
220
 *   null
221
 ******/
222
function parse_config_bootup() {
223
	global $config, $g;
224

    
225
	if($g['booting'])
226
		echo ".";
227

    
228
	$lockkey = lock('config');
229
	if (!file_exists("{$g['conf_path']}/config.xml")) {
230
		if ($g['booting']) {
231
			if (strstr($g['platform'], "cdrom")) {
232
				/* try copying the default config. to the floppy */
233
				echo "Resetting factory defaults...\n";
234
				reset_factory_defaults(true);
235
				if (!file_exists("{$g['conf_path']}/config.xml")) {
236
					echo "No XML configuration file found - using factory defaults.\n";
237
					echo "Make sure that the configuration floppy disk with the conf/config.xml\n";
238
					echo "file is inserted. If it isn't, your configuration changes will be lost\n";
239
					echo "on reboot.\n";
240
				}
241
			} else {
242
				$last_backup = discover_last_backup();
243
				if($last_backup) {
244
					log_error("No config.xml found, attempting last known config restore.");
245
					file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
246
					restore_backup("/cf/conf/backup/{$last_backup}");
247
				}
248
				if(!file_exists("{$g['conf_path']}/config.xml")) {
249
					echo "XML configuration file not found.  {$g['product_name']} cannot continue booting.\n";
250
					unlock($lockkey);
251
					mwexec("/sbin/halt");
252
					exit;
253
				}
254
				log_error("Last known config found and restored.  Please double check your configuration file for accuracy.");
255
				file_notice("config.xml", "Last known config found and restored.  Please double check your configuration file for accuracy.", "pfSenseConfigurator", "");
256
			}
257
		} else {
258
			unlock($lockkey);
259
			exit(0);
260
		}
261
	}
262

    
263
	if (filesize("{$g['conf_path']}/config.xml") == 0) {
264
		$last_backup = discover_last_backup();
265
		if($last_backup) {
266
			log_error("No config.xml found, attempting last known config restore.");
267
			file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
268
			restore_backup("{$g['conf_path']}/backup/{$last_backup}");
269
		} else {
270
			unlock($lockkey);
271
			die("Config.xml is corrupted and is 0 bytes.  Could not restore a previous backup.");
272
		}
273
	}
274
	unlock($lockkey);
275
	parse_config(true);
276

    
277
	if ((float)$config['version'] > (float)$g['latest_config']) {
278
		echo <<<EOD
279

    
280

    
281
*******************************************************************************
282
* WARNING!                                                                    *
283
* The current configuration has been created with a newer version of {$g['product_name']}  *
284
* than this one! This can lead to serious misbehavior and even security       *
285
* holes! You are urged to either upgrade to a newer version of {$g['product_name']} or     *
286
* revert to the default configuration immediately!                            *
287
*******************************************************************************
288

    
289

    
290
EOD;
291
		}
292

    
293
	/* make alias table (for faster lookups) */
294
	alias_make_table($config);
295
}
296

    
297
/****f* config/conf_mount_rw
298
 * NAME
299
 *   conf_mount_rw - Mount filesystems read/write.
300
 * RESULT
301
 *   null
302
 ******/
303
/* mount flash card read/write */
304
function conf_mount_rw() {
305
	global $g;
306

    
307
	/* do not mount on cdrom platform */
308
	if($g['platform'] == "cdrom" or $g['platform'] == "pfSense")
309
		return;
310

    
311
	if (refcount_reference(1000) > 1)
312
		return;
313

    
314
	$status = mwexec("/sbin/mount -u -w {$g['cf_path']}");
315
	if($status <> 0) {
316
		if($g['booting'])
317
			echo "Disk is dirty.  Running fsck -y\n";
318
		mwexec("/sbin/fsck -y {$g['cf_path']}");
319
		$status = mwexec("/sbin/mount -u -w {$g['cf_path']}");
320
	}
321

    
322
	/*    if the platform is soekris or wrap or pfSense, lets mount the
323
	 *    compact flash cards root.
324
         */
325
	$status = mwexec("/sbin/mount -u -w /");
326
	/* we could not mount this correctly.  kick off fsck */
327
	if($status <> 0) {
328
		log_error("File system is dirty.  Launching FSCK for /");
329
		mwexec("/sbin/fsck -y /");
330
		$status = mwexec("/sbin/mount -u -w /");
331
	}
332
	
333
	mark_subsystem_dirty('mount');
334
}
335

    
336
/****f* config/conf_mount_ro
337
 * NAME
338
 *   conf_mount_ro - Mount filesystems readonly.
339
 * RESULT
340
 *   null
341
 ******/
342
function conf_mount_ro() {
343
	global $g;
344

    
345
	/* do not umount on cdrom or pfSense platforms */
346
	if($g['platform'] == "cdrom" or $g['platform'] == "pfSense")
347
		return;
348

    
349
	if($g['booting'])
350
		return;
351

    
352
	if (refcount_unreference(1000) > 0)
353
		return;
354

    
355
	clear_subsystem_dirty('mount');
356
	/* sync data, then force a remount of /cf */
357
	pfSense_sync();
358
	mwexec("/sbin/mount -u -r -f {$g['cf_path']}");
359
	mwexec("/sbin/mount -u -r -f /");
360
}
361

    
362
/****f* config/convert_config
363
 * NAME
364
 *   convert_config - Attempt to update config.xml.
365
 * DESCRIPTION
366
 *   convert_config() reads the current global configuration
367
 *   and attempts to convert it to conform to the latest
368
 *   config.xml version. This allows major formatting changes
369
 *   to be made with a minimum of breakage.
370
 * RESULT
371
 *   null
372
 ******/
373
/* convert configuration, if necessary */
374
function convert_config() {
375
	global $config, $g;
376
	$now = date("H:i:s");
377
	log_error("Start Configuration upgrade at $now, set execution timeout to 15 minutes");
378
	//ini_set("max_execution_time", "900");
379

    
380
	/* special case upgrades */
381
	/* fix every minute crontab bogons entry */
382
	$cron_item_count = count($config['cron']['item']);
383
	for($x=0; $x<$cron_item_count; $x++) {
384
		if(stristr($config['cron']['item'][$x]['command'], "rc.update_bogons.sh")) {
385
			if($config['cron']['item'][$x]['hour'] == "*" ) {
386
		        $config['cron']['item'][$x]['hour'] = "3";
387
		 		write_config("Updated bogon update frequency to 3am");
388
		 		log_error("Updated bogon update frequency to 3am");
389
		 	}       
390
		}
391
	}
392
	if ($config['version'] == $g['latest_config'])
393
		return;		/* already at latest version */
394

    
395
	// Save off config version
396
	$prev_version = $config['version'];
397
	
398
	include_once('auth.inc');
399
	include_once('upgrade_config.inc');
400
	/* Loop and run upgrade_VER_to_VER() until we're at current version */
401
	while ($config['version'] < $g['latest_config']) {
402
		$cur = $config['version'] * 10;
403
		$next = $cur + 1;
404
		$migration_function = sprintf('upgrade_%03d_to_%03d', $cur, $next);
405
		$migration_function();
406
		$config['version'] = sprintf('%.1f', $next / 10);
407
		if($g['booting'])
408
			echo ".";
409
	}
410

    
411
	$now = date("H:i:s");
412
	log_error("Ended Configuration upgrade at $now");
413

    
414
	if ($prev_version != $config['version'])
415
		write_config("Upgraded config version level from {$prev_version} to {$config['version']}");
416
}
417

    
418
/****f* config/safe_write_file
419
 * NAME
420
 *   safe_write_file - Write a file out atomically
421
 * DESCRIPTION
422
 *   safe_write_file() Writes a file out atomically by first writing to a
423
 *   temporary file of the same name but ending with the pid of the current
424
 *   process, them renaming the temporary file over the original.
425
 * INPUTS
426
 *   $filename  - string containing the filename of the file to write
427
 *   $content   - string containing the file content to write to file
428
 *   $force_binary      - boolean denoting whether we should force binary
429
 *   mode writing.
430
 * RESULT
431
 *   boolean - true if successful, false if not
432
 ******/
433
function safe_write_file($file, $content, $force_binary) {
434
	$tmp_file = $file . "." . getmypid();
435
	$write_mode = $force_binary ? "wb" : "w";
436

    
437
	$fd = fopen($tmp_file, $write_mode);
438
	if (!$fd) {
439
		// Unable to open temporary file for writing
440
		return false;
441
        }
442
	if (!fwrite($fd, $content)) {
443
		// Unable to write to temporary file
444
		fclose($fd);
445
		return false;
446
	}
447
	fflush($fd);
448
	fclose($fd);
449

    
450
	if (!rename($tmp_file, $file)) {
451
		// Unable to move temporary file to original
452
		@unlink($tmp_file);
453
		return false;
454
	}
455

    
456
	// Sync file before returning
457
	pfSense_sync();
458

    
459
	return true;
460
}
461

    
462
/****f* config/write_config
463
 * NAME
464
 *   write_config - Backup and write the firewall configuration.
465
 * DESCRIPTION
466
 *   write_config() handles backing up the current configuration,
467
 *   applying changes, and regenerating the configuration cache.
468
 * INPUTS
469
 *   $desc	- string containing the a description of configuration changes
470
 *   $backup	- boolean: do not back up current configuration if false.
471
 * RESULT
472
 *   null
473
 ******/
474
/* save the system configuration */
475
function write_config($desc="Unknown", $backup = true) {
476
	global $config, $g;
477

    
478
	/* TODO: Not sure what this was added for; commenting out
479
	 *       for now, since it was preventing config saving. */
480
	// $config = parse_config(true, false, false);
481
	
482
	if($g['booting'])
483
		log_error("WARNING! Configuration written on bootup.  This can cause stray openvpn and load balancing items in config.xml");
484

    
485
	$username = empty($_SESSION["Username"]) ? "(system)" : $_SESSION['Username'];
486

    
487
	if($backup)
488
		backup_config();
489

    
490
	if (!is_array($config['revision']))
491
		$config['revision'] = array();
492

    
493
	if (time() > mktime(0, 0, 0, 9, 1, 2004))       /* make sure the clock settings are plausible */
494
		$config['revision']['time'] = time();
495

    
496
	/* Log the running script so it's not entirely unlogged what changed */
497
	if ($desc == "Unknown")
498
		$desc = "{$_SERVER['SCRIPT_NAME']} made unknown change";
499

    
500
	$config['revision']['description'] = "{$username}: " . $desc;
501
	$config['revision']['username'] = $username;
502

    
503
	conf_mount_rw();
504
	$lockkey = lock('config', LOCK_EX);
505

    
506
	/* generate configuration XML */
507
	$xmlconfig = dump_xml_config($config, $g['xml_rootobj']);
508

    
509
	/* write new configuration */
510
	if (!safe_write_file("{$g['cf_conf_path']}/config.xml", $xmlconfig, false)) {
511
		log_error("WARNING: Config contents could not be save. Could not open file!");
512
		unlock($lockkey);
513
		file_notice("config.xml", "Unable to open {$g['cf_conf_path']}/config.xml for writing in write_config()\n");
514
		return -1;
515
	}
516
	
517
	if($g['platform'] == "embedded" or $g['platform'] == "nanobsd") {
518
		cleanup_backupcache(5, true);
519
	} else {
520
		cleanup_backupcache(30, true);
521
	}
522

    
523
	/* re-read configuration */
524
	/* NOTE: We assume that the file can be parsed since we wrote it. */
525
	$config = parse_xml_config("{$g['conf_path']}/config.xml", $g['xml_rootobj']);
526
	if ($config == -1) {
527
		$last_backup = discover_last_backup();
528
		if ($last_backup)
529
			restore_backup("/cf/conf/backup/{$last_backup}");
530
		else
531
			log_error(gettext("Could not restore config.xml."));
532
	} else
533
		generate_config_cache($config);
534

    
535
	unlock($lockkey);
536

    
537
	unlink_if_exists("/usr/local/pkg/pf/carp_sync_client.php");
538

    
539
	/* tell kernel to sync fs data */
540
	conf_mount_ro();
541

    
542
	/* sync carp entries to other firewalls */
543
	carp_sync_client();
544

    
545
	if(is_dir("/usr/local/pkg/write_config")) {
546
		/* process packager manager custom rules */
547
		run_plugins("/usr/local/pkg/write_config/");
548
	}
549

    
550
	return $config;
551
}
552

    
553
/****f* config/reset_factory_defaults
554
 * NAME
555
 *   reset_factory_defaults - Reset the system to its default configuration.
556
 * RESULT
557
 *   integer	- indicates completion
558
 ******/
559
function reset_factory_defaults($lock = false) {
560
	global $g;
561

    
562
	conf_mount_rw();
563
	if (!$lock)
564
		$lockkey = lock('config', LOCK_EX);
565

    
566
	/* create conf directory, if necessary */
567
	safe_mkdir("{$g['cf_conf_path']}");
568

    
569
	/* clear out /conf */
570
	$dh = opendir($g['conf_path']);
571
	while ($filename = readdir($dh)) {
572
		if (($filename != ".") && ($filename != "..")) {
573
			unlink_if_exists($g['conf_path'] . "/" . $filename);
574
		}
575
	}
576
	closedir($dh);
577

    
578
	/* copy default configuration */
579
	copy("{$g['conf_default_path']}/config.xml", "{$g['conf_path']}/config.xml");
580

    
581
	disable_security_checks();
582

    
583
	/* call the wizard */
584
	touch("/conf/trigger_initial_wizard");
585
	if (!$lock)
586
		unlock($lockkey);
587
	conf_mount_ro();
588

    
589
	return 0;
590
}
591

    
592
function config_restore($conffile) {
593
	global $config, $g;
594

    
595
	if (!file_exists($conffile))
596
		return 1;
597

    
598
	backup_config();
599

    
600
	conf_mount_rw();
601
	
602
	$lockkey = lock('config', LOCK_EX);
603

    
604
	unlink_if_exists("{$g['tmp_path']}/config.cache");
605
	copy($conffile, "{$g['cf_conf_path']}/config.xml");
606

    
607
	disable_security_checks();
608

    
609
	unlock($lockkey);
610

    
611
	$config = parse_config(true);
612

    
613
	conf_mount_ro();
614

    
615
	write_config("Reverted to " . array_pop(explode("/", $conffile)) . ".", false);
616

    
617
	return 0;
618
}
619

    
620
function config_install($conffile) {
621
	global $config, $g;
622

    
623
	if (!file_exists($conffile))
624
		return 1;
625

    
626
	if (!config_validate("{$conffile}"))
627
		return 1;
628

    
629
	if($g['booting'] == true)
630
		echo "Installing configuration...\n";
631
	else
632
		log_error("Installing configuration ....");
633

    
634
	conf_mount_rw();
635
	$lockkey = lock('config', LOCK_EX);
636

    
637
	copy($conffile, "{$g['conf_path']}/config.xml");
638

    
639
	disable_security_checks();
640

    
641
	/* unlink cache file if it exists */
642
	if(file_exists("{$g['tmp_path']}/config.cache"))
643
		unlink("{$g['tmp_path']}/config.cache");
644

    
645
	unlock($lockkey);
646
	conf_mount_ro();
647

    
648
    return 0;
649
}
650

    
651
/*
652
 * Disable security checks for DNS rebind and HTTP referrer until next time
653
 * they pass (or reboot), to aid in preventing accidental lockout when
654
 * restoring settings like hostname, domain, IP addresses, and settings
655
 * related to the DNS rebind and HTTP referrer checks.
656
 * Intended for use when restoring a configuration or directly
657
 * modifying config.xml without an unconditional reboot.
658
 */
659
function disable_security_checks() {
660
	global $g;
661
	touch("{$g['tmp_path']}/disable_security_checks");
662
}
663

    
664
/* Restores security checks.  Should be called after all succeed. */
665
function restore_security_checks() {
666
	global $g;
667
	unlink_if_exists("{$g['tmp_path']}/disable_security_checks");
668
}
669

    
670
/* Returns status of security check temporary disable. */
671
function security_checks_disabled() {
672
	global $g;
673
	return file_exists("{$g['tmp_path']}/disable_security_checks");
674
}
675

    
676
function config_validate($conffile) {
677

    
678
	global $g, $xmlerr;
679

    
680
	$xml_parser = xml_parser_create();
681

    
682
	if (!($fp = fopen($conffile, "r"))) {
683
		$xmlerr = "XML error: unable to open file";
684
		return false;
685
	}
686

    
687
	while ($data = fread($fp, 4096)) {
688
		if (!xml_parse($xml_parser, $data, feof($fp))) {
689
			$xmlerr = sprintf("%s at line %d",
690
						xml_error_string(xml_get_error_code($xml_parser)),
691
						xml_get_current_line_number($xml_parser));
692
			return false;
693
		}
694
	}
695
	xml_parser_free($xml_parser);
696

    
697
	fclose($fp);
698

    
699
	return true;
700
}
701

    
702
function cleanup_backupcache($revisions = 30, $lock = false) {
703
	global $g;
704
	$i = false;
705
	
706
	if (!$lock)
707
		$lockkey = lock('config');
708

    
709
	conf_mount_rw();
710

    
711
	$backups = get_backups();
712
	if ($backups) {
713
		$baktimes = $backups['versions'];
714
		unset($backups['versions']);
715
	} else {
716
		$backups = array();
717
		$baktimes = array();
718
	}
719
	$newbaks = array();
720
	$bakfiles = glob($g['cf_conf_path'] . "/backup/config-*");
721
	$tocache = array();
722

    
723
	foreach($bakfiles as $backup) { // Check for backups in the directory not represented in the cache.
724
		if(filesize($backup) == 0) {
725
			unlink($backup);
726
			continue;
727
		}
728
		$tocheck = array_shift(explode('.', array_pop(explode('-', $backup))));
729
		if(!in_array($tocheck, $baktimes)) {
730
			$i = true;
731
			if($g['booting'])
732
				echo ".";
733
			$newxml = parse_xml_config($backup, array($g['xml_rootobj'], 'pfsense'));
734
			if($newxml == "-1") {
735
				log_error("The backup cache file $backup is corrupted.  Unlinking.");
736
				unlink($backup);
737
				log_error("The backup cache file $backup is corrupted.  Unlinking.");
738
				continue;
739
			}
740
			if($newxml['revision']['description'] == "")
741
				$newxml['revision']['description'] = "Unknown";
742
			$tocache[$tocheck] = array('description' => $newxml['revision']['description']);
743
		}
744
	}
745
	foreach($backups as $checkbak) {
746
		if(count(preg_grep('/' . $checkbak['time'] . '/i', $bakfiles)) != 0) {
747
			$newbaks[] = $checkbak;
748
		} else {
749
			$i = true;
750
			if($g['booting']) print " " . $tocheck . "r";
751
		}
752
	}
753
	foreach($newbaks as $todo) $tocache[$todo['time']] = array('description' => $todo['description']);
754
	if(is_int($revisions) and (count($tocache) > $revisions)) {
755
		$toslice = array_slice(array_keys($tocache), 0, $revisions);
756
		foreach($toslice as $sliced)
757
			$newcache[$sliced] = $tocache[$sliced];
758
		foreach($tocache as $version => $versioninfo) {
759
			if(!in_array($version, array_keys($newcache))) {
760
				unlink_if_exists($g['conf_path'] . '/backup/config-' . $version . '.xml');
761
				//if($g['booting']) print " " . $tocheck . "d";
762
			}
763
		}
764
		$tocache = $newcache;
765
	}
766
	$bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
767
	fwrite($bakout, serialize($tocache));
768
	fclose($bakout);
769
	conf_mount_ro();
770

    
771
	if (!$lock)
772
		unlock($lockkey);
773
}
774

    
775
function get_backups() {
776
	global $g;
777
	if(file_exists("{$g['cf_conf_path']}/backup/backup.cache")) {
778
		$confvers = unserialize(file_get_contents("{$g['cf_conf_path']}/backup/backup.cache"));
779
		$bakvers = array_keys($confvers);
780
		$toreturn = array();
781
		sort($bakvers);
782
		// 	$bakvers = array_reverse($bakvers);
783
		foreach(array_reverse($bakvers) as $bakver)
784
			$toreturn[] = array('time' => $bakver, 'description' => $confvers[$bakver]['description']);
785
	} else {
786
		return false;
787
	}
788
	$toreturn['versions'] = $bakvers;
789
	return $toreturn;
790
}
791

    
792
function backup_config() {
793
	global $config, $g;
794

    
795
	if($g['platform'] == "cdrom")
796
		return;
797

    
798
	conf_mount_rw();
799

    
800
	/* Create backup directory if needed */
801
	safe_mkdir("{$g['cf_conf_path']}/backup");
802

    
803
    if($config['revision']['time'] == "") {
804
            $baktime = 0;
805
    } else {
806
            $baktime = $config['revision']['time'];
807
    }
808
    if($config['revision']['description'] == "") {
809
            $bakdesc = "Unknown";
810
    } else {
811
            $bakdesc = $config['revision']['description'];
812
    }
813
    copy($g['cf_conf_path'] . '/config.xml', $g['cf_conf_path'] . '/backup/config-' . $baktime . '.xml');
814
    if(file_exists($g['cf_conf_path'] . '/backup/backup.cache')) {
815
            $backupcache = unserialize(file_get_contents($g['cf_conf_path'] . '/backup/backup.cache'));
816
    } else {
817
            $backupcache = array();
818
    }
819
    $backupcache[$baktime] = array('description' => $bakdesc);
820
    $bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
821
    fwrite($bakout, serialize($backupcache));
822
    fclose($bakout);
823

    
824
	conf_mount_ro();
825

    
826
	return true;
827
}
828

    
829
function set_device_perms() {
830
	$devices = array(
831
		'pf'	=> array(	'user'	=> 'root',
832
					'group'	=> 'proxy',
833
					'mode'	=> 0660),
834
		);
835

    
836
	foreach ($devices as $name => $attr) {
837
		$path = "/dev/$name";
838
		if (file_exists($path)) {
839
			chown($path, $attr['user']);
840
			chgrp($path, $attr['group']);
841
			chmod($path, $attr['mode']);
842
		}
843
	}
844
}
845

    
846
?>
(13-13/61)