]> mj.ucw.cz Git - libucw.git/blob - lib/conf-input.c
036181dc81c7aaf48d098fa2db52dedcd69e9003
[libucw.git] / lib / conf-input.c
1 /*
2  *      UCW Library -- Configuration files: parsing input streams
3  *
4  *      (c) 2001--2006 Robert Spalek <robert@ucw.cz>
5  *      (c) 2003--2006 Martin Mares <mj@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "lib/lib.h"
12 #include "lib/conf.h"
13 #include "lib/getopt.h"
14 #include "lib/conf-internal.h"
15 #include "lib/mempool.h"
16 #include "lib/fastbuf.h"
17 #include "lib/chartype.h"
18 #include "lib/stkstring.h"
19
20 #include <stdlib.h>
21 #include <string.h>
22 #include <fcntl.h>
23
24 /* Text file parser */
25
26 static byte *name_parse_fb;
27 static struct fastbuf *parse_fb;
28 static uns line_num;
29
30 #define MAX_LINE        4096
31 static byte line_buf[MAX_LINE];
32 static byte *line = line_buf;
33
34 #include "lib/bbuf.h"
35 static bb_t copy_buf;
36 static uns copied;
37
38 #define GBUF_TYPE       uns
39 #define GBUF_PREFIX(x)  split_##x
40 #include "lib/gbuf.h"
41 static split_t word_buf;
42 static uns words;
43 static uns ends_by_brace;               // the line is ended by "{"
44
45 static int
46 get_line(byte **msg)
47 {
48   int err = bgets_nodie(parse_fb, line_buf, MAX_LINE);
49   line_num++;
50   if (err <= 0) {
51     *msg = err < 0 ? "Line too long" : NULL;
52     return 0;
53   }
54   line = line_buf;
55   while (Cblank(*line))
56     line++;
57   return 1;
58 }
59
60 static void
61 append(byte *start, byte *end)
62 {
63   uns len = end - start;
64   bb_grow(&copy_buf, copied + len + 1);
65   memcpy(copy_buf.ptr + copied, start, len);
66   copied += len + 1;
67   copy_buf.ptr[copied-1] = 0;
68 }
69
70 static byte *
71 get_word(uns is_command_name)
72 {
73   byte *msg;
74   if (*line == '\'') {
75     line++;
76     while (1) {
77       byte *start = line;
78       while (*line && *line != '\'')
79         line++;
80       append(start, line);
81       if (*line)
82         break;
83       copy_buf.ptr[copied-1] = '\n';
84       if (!get_line(&msg))
85         return msg ? : (byte*) "Unterminated apostrophe word at the end";
86     }
87     line++;
88
89   } else if (*line == '"') {
90     line++;
91     uns start_copy = copied;
92     while (1) {
93       byte *start = line;
94       uns escape = 0;
95       while (*line) {
96         if (*line == '"' && !escape)
97           break;
98         else if (*line == '\\')
99           escape ^= 1;
100         else
101           escape = 0;
102         line++;
103       }
104       append(start, line);
105       if (*line)
106         break;
107       if (!escape)
108         copy_buf.ptr[copied-1] = '\n';
109       else // merge two lines
110         copied -= 2;
111       if (!get_line(&msg))
112         return msg ? : (byte*) "Unterminated quoted word at the end";
113     }
114     line++;
115
116     byte *tmp = stk_str_unesc(copy_buf.ptr + start_copy);
117     uns l = strlen(tmp);
118     bb_grow(&copy_buf, start_copy + l + 1);
119     strcpy(copy_buf.ptr + start_copy, tmp);
120     copied = start_copy + l + 1;
121
122   } else {
123     // promised that *line is non-null and non-blank
124     byte *start = line;
125     while (*line && !Cblank(*line)
126         && *line != '{' && *line != '}' && *line != ';'
127         && (*line != '=' || !is_command_name))
128       line++;
129     if (*line == '=') {                         // nice for setting from a command-line
130       if (line == start)
131         return "Assignment without a variable";
132       *line = ' ';
133     }
134     if (line == start)                          // already the first char is control
135       line++;
136     append(start, line);
137   }
138   while (Cblank(*line))
139     line++;
140   return NULL;
141 }
142
143 static byte *
144 get_token(uns is_command_name, byte **msg)
145 {
146   *msg = NULL;
147   while (1) {
148     if (!*line || *line == '#') {
149       if (!is_command_name || !get_line(msg))
150         return NULL;
151     } else if (*line == ';') {
152       *msg = get_word(0);
153       if (!is_command_name || *msg)
154         return NULL;
155     } else if (*line == '\\' && !line[1]) {
156       if (!get_line(msg)) {
157         if (!*msg)
158           *msg = "Last line ends by a backslash";
159         return NULL;
160       }
161       if (!*line || *line == '#')
162         log(L_WARN, "The line %s:%d following a backslash is empty", name_parse_fb, line_num);
163     } else {
164       split_grow(&word_buf, words+1);
165       uns start = copied;
166       word_buf.ptr[words++] = copied;
167       *msg = get_word(is_command_name);
168       return *msg ? NULL : copy_buf.ptr + start;
169     }
170   }
171 }
172
173 static byte *
174 split_command(void)
175 {
176   words = copied = ends_by_brace = 0;
177   byte *msg, *start_word;
178   if (!(start_word = get_token(1, &msg)))
179     return msg;
180   if (*start_word == '{')                       // only one opening brace
181     return "Unexpected opening brace";
182   while (*line != '}')                          // stays for the next time
183   {
184     if (!(start_word = get_token(0, &msg)))
185       return msg;
186     if (*start_word == '{') {
187       words--;                                  // discard the brace
188       ends_by_brace = 1;
189       break;
190     }
191   }
192   return NULL;
193 }
194
195 /* Parsing multiple files */
196
197 static byte *
198 parse_fastbuf(byte *name_fb, struct fastbuf *fb, uns depth)
199 {
200   byte *msg;
201   name_parse_fb = name_fb;
202   parse_fb = fb;
203   line_num = 0;
204   line = line_buf;
205   *line = 0;
206   while (1)
207   {
208     msg = split_command();
209     if (msg)
210       goto error;
211     if (!words)
212       return NULL;
213     byte *name = copy_buf.ptr + word_buf.ptr[0];
214     byte *pars[words-1];
215     for (uns i=1; i<words; i++)
216       pars[i-1] = copy_buf.ptr + word_buf.ptr[i];
217     if (!strcasecmp(name, "include"))
218     {
219       if (words != 2)
220         msg = "Expecting one filename";
221       else if (depth > 8)
222         msg = "Too many nested files";
223       else if (*line && *line != '#')           // because the contents of line_buf is not re-entrant and will be cleared
224         msg = "The input command must be the last one on a line";
225       if (msg)
226         goto error;
227       struct fastbuf *new_fb = bopen_try(pars[0], O_RDONLY, 1<<14);
228       if (!new_fb) {
229         msg = cf_printf("Cannot open file %s: %m", pars[0]);
230         goto error;
231       }
232       uns ll = line_num;
233       msg = parse_fastbuf(stk_strdup(pars[0]), new_fb, depth+1);
234       line_num = ll;
235       bclose(new_fb);
236       if (msg)
237         goto error;
238       parse_fb = fb;
239       continue;
240     }
241     enum cf_operation op;
242     byte *c = strchr(name, ':');
243     if (!c)
244       op = strcmp(name, "}") ? OP_SET : OP_CLOSE;
245     else {
246       *c++ = 0;
247       switch (Clocase(*c)) {
248         case 's': op = OP_SET; break;
249         case 'u': op = OP_UNSET; break;
250         case 'c': op = Clocase(c[1]) == 'l' ? OP_CLEAR: OP_COPY; break;
251         case 'a': switch (Clocase(c[1])) {
252                     case 'p': op = OP_APPEND; break;
253                     case 'f': op = OP_AFTER; break;
254                     default: op = OP_ALL;
255                   }; break;
256         case 'p': op = OP_PREPEND; break;
257         case 'r': op = OP_REMOVE; break;
258         case 'e': op = OP_EDIT; break;
259         case 'b': op = OP_BEFORE; break;
260         default: op = OP_SET; break;
261       }
262       if (strcasecmp(c, cf_op_names[op])) {
263         msg = cf_printf("Unknown operation %s", c);
264         goto error;
265       }
266     }
267     if (ends_by_brace)
268       op |= OP_OPEN;
269     msg = cf_interpret_line(name, op, words-1, pars);
270     if (msg)
271       goto error;
272   }
273 error:
274   log(L_ERROR, "File %s, line %d: %s", name_fb, line_num, msg);
275   return "included from here";
276 }
277
278 #ifndef DEFAULT_CONFIG
279 #define DEFAULT_CONFIG NULL
280 #endif
281 byte *cf_def_file = DEFAULT_CONFIG;
282
283 static uns postpone_commit;                     // only for cf_getopt()
284 static uns everything_committed;                // after the 1st load, this flag is set on
285
286 static int
287 done_stack(void)
288 {
289   if (cf_check_stack())
290     return 1;
291   if (cf_commit_all(postpone_commit ? CF_NO_COMMIT : everything_committed ? CF_COMMIT : CF_COMMIT_ALL))
292     return 1;
293   if (!postpone_commit)
294     everything_committed = 1;
295   return 0;
296 }
297
298 static int
299 load_file(byte *file)
300 {
301   cf_init_stack();
302   struct fastbuf *fb = bopen_try(file, O_RDONLY, 1<<14);
303   if (!fb) {
304     log(L_ERROR, "Cannot open %s: %m", file);
305     return 1;
306   }
307   byte *msg = parse_fastbuf(file, fb, 0);
308   bclose(fb);
309   int err = !!msg || done_stack();
310   if (!err)
311     cf_def_file = NULL;
312   return err;
313 }
314
315 static int
316 load_string(byte *string)
317 {
318   cf_init_stack();
319   struct fastbuf fb;
320   fbbuf_init_read(&fb, string, strlen(string), 0);
321   byte *msg = parse_fastbuf("memory string", &fb, 0);
322   return !!msg || done_stack();
323 }
324
325 /* Safe loading and reloading */
326
327 int
328 cf_reload(byte *file)
329 {
330   cf_journal_swap();
331   struct cf_journal_item *oldj = cf_journal_new_transaction(1);
332   uns ec = everything_committed;
333   everything_committed = 0;
334   int err = load_file(file);
335   if (!err)
336   {
337     cf_journal_delete();
338     cf_journal_commit_transaction(1, NULL);
339   }
340   else
341   {
342     everything_committed = ec;
343     cf_journal_rollback_transaction(1, oldj);
344     cf_journal_swap();
345   }
346   return err;
347 }
348
349 int
350 cf_load(byte *file)
351 {
352   struct cf_journal_item *oldj = cf_journal_new_transaction(1);
353   int err = load_file(file);
354   if (!err)
355     cf_journal_commit_transaction(1, oldj);
356   else
357     cf_journal_rollback_transaction(1, oldj);
358   return err;
359 }
360
361 int
362 cf_set(byte *string)
363 {
364   struct cf_journal_item *oldj = cf_journal_new_transaction(0);
365   int err = load_string(string);
366   if (!err)
367     cf_journal_commit_transaction(0, oldj);
368   else
369     cf_journal_rollback_transaction(0, oldj);
370   return err;
371 }
372
373 /* Command-line parser */
374
375 static void
376 load_default(void)
377 {
378   if (cf_def_file)
379     if (cf_load(cf_def_file))
380       die("Cannot load default config %s", cf_def_file);
381 }
382
383 static void
384 final_commit(void)
385 {
386   if (postpone_commit) {
387     postpone_commit = 0;
388     if (done_stack())
389       die("Cannot commit after the initialization");
390   }
391 }
392
393 int
394 cf_getopt(int argc, char * const argv[], const char *short_opts, const struct option *long_opts, int *long_index)
395 {
396   static int other_options = 0;
397   while (1) {
398     int res = getopt_long (argc, argv, short_opts, long_opts, long_index);
399     if (res == 'S' || res == 'C' || res == 0x64436667)
400     {
401       if (other_options)
402         die("The -S and -C options must precede all other arguments");
403       if (res == 'S') {
404         postpone_commit = 1;
405         load_default();
406         if (cf_set(optarg))
407           die("Cannot set %s", optarg);
408       } else if (res == 'C') {
409         postpone_commit = 1;
410         if (cf_load(optarg))
411           die("Cannot load config file %s", optarg);
412       }
413 #ifdef CONFIG_DEBUG
414       else {   /* --dumpconfig */
415         load_default();
416         final_commit();
417         struct fastbuf *b = bfdopen(1, 4096);
418         cf_dump_sections(b);
419         bclose(b);
420         exit(0);
421       }
422 #endif
423     } else {
424       /* unhandled option or end of options */
425       if (res != ':' && res != '?')
426         load_default();
427       final_commit();
428       other_options++;
429       return res;
430     }
431   }
432 }
433