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