1 /*
2 * SPDX-License-Identifier: GPL-2.0-or-later
3 *
4 * Copyright (c) 2018 Jan Stancek <jstancek@redhat.com>
5 */
6
7 #include <limits.h>
8 #include <stdio.h>
9 #include <unistd.h>
10 #include <string.h>
11
12 #define TST_NO_DEFAULT_MAIN
13 #include "tst_test.h"
14 #include "tst_sys_conf.h"
15
16 static struct tst_sys_conf *save_restore_data;
17
tst_sys_conf_dump(void)18 void tst_sys_conf_dump(void)
19 {
20 struct tst_sys_conf *i;
21
22 for (i = save_restore_data; i; i = i->next)
23 tst_res(TINFO, "%s = %s", i->path, i->value);
24 }
25
tst_sys_conf_save_str(const char * path,const char * value)26 int tst_sys_conf_save_str(const char *path, const char *value)
27 {
28 struct tst_sys_conf *n = SAFE_MALLOC(sizeof(*n));
29
30 strncpy(n->path, path, sizeof(n->path));
31 strncpy(n->value, value, sizeof(n->value));
32
33 n->next = save_restore_data;
34 save_restore_data = n;
35
36 return 0;
37 }
38
tst_sys_conf_save(const char * path)39 int tst_sys_conf_save(const char *path)
40 {
41 char line[PATH_MAX];
42 FILE *fp;
43 void *ret;
44 char flag;
45
46 if (!path)
47 tst_brk(TBROK, "path is empty");
48
49 flag = path[0];
50 if (flag == '?' || flag == '!')
51 path++;
52
53 if (access(path, F_OK) != 0) {
54 switch (flag) {
55 case '?':
56 tst_res(TINFO, "Path not found: '%s'", path);
57 break;
58 case '!':
59 tst_brk(TBROK|TERRNO, "Path not found: '%s'", path);
60 break;
61 default:
62 tst_brk(TCONF|TERRNO, "Path not found: '%s'", path);
63 }
64 return 1;
65 }
66
67 fp = fopen(path, "r");
68 if (fp == NULL) {
69 if (flag == '?')
70 return 1;
71
72 tst_brk(TBROK | TERRNO, "Failed to open FILE '%s' for reading",
73 path);
74 return 1;
75 }
76
77 ret = fgets(line, sizeof(line), fp);
78 fclose(fp);
79
80 if (ret == NULL) {
81 if (flag == '?')
82 return 1;
83
84 tst_brk(TBROK | TERRNO, "Failed to read anything from '%s'",
85 path);
86 }
87
88 return tst_sys_conf_save_str(path, line);
89 }
90
tst_sys_conf_restore(int verbose)91 void tst_sys_conf_restore(int verbose)
92 {
93 struct tst_sys_conf *i;
94
95 for (i = save_restore_data; i; i = i->next) {
96 if (verbose) {
97 tst_res(TINFO, "Restoring conf.: %s -> %s\n",
98 i->path, i->value);
99 }
100 FILE_PRINTF(i->path, "%s", i->value);
101 }
102 }
103
104