From eb3da9012f462da2451edeb8d67c5b67c833a0b1 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Fri, 13 Nov 2015 00:54:56 +0100 Subject: util-lib: optionally, when writing a string to a file, verify string on failure With this change, the idiom: r = write_string_file(p, buf, 0); if (r < 0) { if (verify_one_line_file(p, buf) > 0) r = 0; } gets reduced to: r = write_string_file(p, buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE); i.e. when writing the string fails and the new flag WRITE_STRING_FILE_VERIFY_ON_FAILURE is specified we'll not return a failure immediately, but check the contents of the file. If it matches what we wanted to write we suppress the error and exit cleanly. --- src/test/test-fileio.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src/test/test-fileio.c') diff --git a/src/test/test-fileio.c b/src/test/test-fileio.c index e588681b86..bde3c7c3cf 100644 --- a/src/test/test-fileio.c +++ b/src/test/test-fileio.c @@ -363,6 +363,26 @@ static void test_write_string_file_no_create(void) { unlink(fn); } +static void test_write_string_file_verify(void) { + _cleanup_free_ char *buf = NULL, *buf2 = NULL; + int r; + + assert_se(read_one_line_file("/proc/cmdline", &buf) >= 0); + assert_se((buf2 = strjoin(buf, "\n", NULL))); + + r = write_string_file("/proc/cmdline", buf, 0); + assert_se(r == -EACCES || r == -EIO); + r = write_string_file("/proc/cmdline", buf2, 0); + assert_se(r == -EACCES || r == -EIO); + + assert_se(write_string_file("/proc/cmdline", buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE) == 0); + assert_se(write_string_file("/proc/cmdline", buf2, WRITE_STRING_FILE_VERIFY_ON_FAILURE) == 0); + + r = write_string_file("/proc/cmdline", buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_AVOID_NEWLINE); + assert_se(r == -EACCES || r == -EIO); + assert_se(write_string_file("/proc/cmdline", buf2, WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_AVOID_NEWLINE) == 0); +} + static void test_load_env_file_pairs(void) { char fn[] = "/tmp/test-load_env_file_pairs-XXXXXX"; int fd; @@ -419,6 +439,7 @@ int main(int argc, char *argv[]) { test_write_string_stream(); test_write_string_file(); test_write_string_file_no_create(); + test_write_string_file_verify(); test_load_env_file_pairs(); return 0; -- cgit v1.2.3-54-g00ecf