From ddd42db3a9e46d19526bd2988b1a1e1faaf0b091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20Lu=E7i?= Date: Wed, 3 Mar 2010 17:20:24 +0000 Subject: Put safe_write_file to the include it belongs to. --- etc/inc/config.lib.inc | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'etc/inc/config.lib.inc') diff --git a/etc/inc/config.lib.inc b/etc/inc/config.lib.inc index 240a3a3..255b45a 100644 --- a/etc/inc/config.lib.inc +++ b/etc/inc/config.lib.inc @@ -418,6 +418,45 @@ function convert_config() { echo "Loading new configuration..."; } +/****f* config/safe_write_file + * NAME + * safe_write_file - Write a file out atomically + * DESCRIPTION + * safe_write_file() Writes a file out atomically by first writing to a + * temporary file of the same name but ending with the pid of the current + * process, them renaming the temporary file over the original. + * INPUTS + * $filename - string containing the filename of the file to write + * $content - string containing the file content to write to file + * $force_binary - boolean denoting whether we should force binary + * mode writing. + * RESULT + * boolean - true if successful, false if not + ******/ +function safe_write_file($file, $content, $force_binary) { + $tmp_file = $file . "." . getmypid(); + $write_mode = $force_binary ? "wb" : "w"; + + $fd = fopen($tmp_file, $write_mode); + if (!$fd) { + // Unable to open temporary file for writing + return false; + } + if (!fwrite($fd, $content)) { + // Unable to write to temporary file + fclose($fd); + return false; + } + fclose($fd); + + if (!rename($tmp_file, $file)) { + // Unable to move temporary file to original + unlink($tmp_file); + return false; + } + return true; +} + /****f* config/write_config * NAME * write_config - Backup and write the firewall configuration. -- cgit v1.1