• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* conf.c - config file parser */
2 
3 #include "config.h"
4 #include <ctype.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 
9 #include "src/conf.h"
10 
strip_char(char * line,char c)11 void strip_char (char *line, char c)
12 {
13   char *p = strchr (line, c);
14   if (p)
15     *p = '\0';
16 }
17 
strip_newlines(char * line)18 void strip_newlines (char *line)
19 {
20   strip_char (line, '\n');
21   strip_char (line, '\r');
22 }
23 
eat_whitespace(char * line)24 char *eat_whitespace (char *line)
25 {
26   while (isspace ((int)(unsigned char)*line))
27     line++;
28   return line;
29 }
30 
is_ignored_line(char * line)31 int is_ignored_line (char *line)
32 {
33   return !*line || *line == '#';
34 }
35 
conf_parse(FILE * f)36 struct conf_entry *conf_parse (FILE *f)
37 {
38   struct conf_entry *head = NULL;
39   struct conf_entry *tail = NULL;
40   char buf[CONF_MAX_LINE];
41 
42   while (fgets (buf, sizeof (buf), f))
43     {
44       struct conf_entry *e;
45       char *start = buf;
46       char *key;
47       char *val;
48       strip_newlines (start);
49       start = eat_whitespace (start);
50       if (is_ignored_line (start))
51         continue;
52       key = strtok (start, " \t");
53       val = strtok (NULL, "");
54       if (val)
55         val = eat_whitespace (val);
56       e = malloc (sizeof *e);
57       if (!e)
58         goto fail;
59       e->next = NULL;
60       e->key = strdup (key);
61       e->value = val ? strdup (val) : NULL;
62       if (!e->key || (val && !e->value))
63         {
64           free (e->key);
65           free (e->value);
66           goto fail;
67         }
68       if (!head)
69         {
70           head = e;
71           tail = e;
72         }
73       else
74         {
75           tail->next = e;
76           tail = e;
77         }
78     }
79 
80   return head;
81 fail:
82   conf_free (head);
83   return NULL;
84 }
85 
conf_free(struct conf_entry * e)86 void conf_free (struct conf_entry *e)
87 {
88   struct conf_entry *n;
89   while (e)
90     {
91       n = e->next;
92       free (e->key);
93       free (e->value);
94       free (e);
95       e = n;
96     }
97 }
98