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