]> mj.ucw.cz Git - libucw.git/blob - lib/conf-input.c
conf: don't die in bgets() on too long lines
[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 'c': op = Clocase(c[1]) == 'l' ? OP_CLEAR: OP_COPY; break;
250         case 'a': op = Clocase(c[1]) == 'p' ? OP_APPEND : OP_AFTER; break;
251         case 'p': op = OP_PREPEND; break;
252         case 'r': op = OP_REMOVE; break;
253         case 'e': op = OP_EDIT; break;
254         case 'b': op = OP_BEFORE; break;
255         default: op = OP_SET; break;
256       }
257       if (strcasecmp(c, cf_op_names[op])) {
258         msg = cf_printf("Unknown operation %s", c);
259         goto error;
260       }
261     }
262     if (ends_by_brace)
263       op |= OP_OPEN;
264     msg = cf_interpret_line(name, op, words-1, pars);
265     if (msg)
266       goto error;
267   }
268 error:
269   log(L_ERROR, "File %s, line %d: %s", name_fb, line_num, msg);
270   return "included from here";
271 }
272
273 #ifndef DEFAULT_CONFIG
274 #define DEFAULT_CONFIG NULL
275 #endif
276 byte *cf_def_file = DEFAULT_CONFIG;
277
278 static uns postpone_commit;                     // only for cf_getopt()
279 static uns everything_committed;                // after the 1st load, this flag is set on
280
281 static int
282 done_stack(void)
283 {
284   if (cf_check_stack())
285     return 1;
286   if (cf_commit_all(postpone_commit ? CF_NO_COMMIT : everything_committed ? CF_COMMIT : CF_COMMIT_ALL))
287     return 1;
288   if (!postpone_commit)
289     everything_committed = 1;
290   return 0;
291 }
292
293 static int
294 load_file(byte *file)
295 {
296   cf_init_stack();
297   struct fastbuf *fb = bopen_try(file, O_RDONLY, 1<<14);
298   if (!fb) {
299     log(L_ERROR, "Cannot open %s: %m", file);
300     return 1;
301   }
302   byte *msg = parse_fastbuf(file, fb, 0);
303   bclose(fb);
304   int err = !!msg || done_stack();
305   if (!err)
306     cf_def_file = NULL;
307   return err;
308 }
309
310 static int
311 load_string(byte *string)
312 {
313   cf_init_stack();
314   struct fastbuf fb;
315   fbbuf_init_read(&fb, string, strlen(string), 0);
316   byte *msg = parse_fastbuf("memory string", &fb, 0);
317   return !!msg || done_stack();
318 }
319
320 /* Safe loading and reloading */
321
322 int
323 cf_reload(byte *file)
324 {
325   cf_journal_swap();
326   struct cf_journal_item *oldj = cf_journal_new_transaction(1);
327   uns ec = everything_committed;
328   everything_committed = 0;
329   int err = load_file(file);
330   if (!err)
331   {
332     cf_journal_delete();
333     cf_journal_commit_transaction(1, NULL);
334   }
335   else
336   {
337     everything_committed = ec;
338     cf_journal_rollback_transaction(1, oldj);
339     cf_journal_swap();
340   }
341   return err;
342 }
343
344 int
345 cf_load(byte *file)
346 {
347   struct cf_journal_item *oldj = cf_journal_new_transaction(1);
348   int err = load_file(file);
349   if (!err)
350     cf_journal_commit_transaction(1, oldj);
351   else
352     cf_journal_rollback_transaction(1, oldj);
353   return err;
354 }
355
356 int
357 cf_set(byte *string)
358 {
359   struct cf_journal_item *oldj = cf_journal_new_transaction(0);
360   int err = load_string(string);
361   if (!err)
362     cf_journal_commit_transaction(0, oldj);
363   else
364     cf_journal_rollback_transaction(0, oldj);
365   return err;
366 }
367
368 /* Command-line parser */
369
370 static void
371 load_default(void)
372 {
373   if (cf_def_file)
374     if (cf_load(cf_def_file))
375       die("Cannot load default config %s", cf_def_file);
376 }
377
378 static void
379 final_commit(void)
380 {
381   if (postpone_commit) {
382     postpone_commit = 0;
383     if (done_stack())
384       die("Cannot commit after the initialization");
385   }
386 }
387
388 int
389 cf_getopt(int argc, char * const argv[], const char *short_opts, const struct option *long_opts, int *long_index)
390 {
391   static int other_options = 0;
392   while (1) {
393     int res = getopt_long (argc, argv, short_opts, long_opts, long_index);
394     if (res == 'S' || res == 'C' || res == 0x64436667)
395     {
396       if (other_options)
397         die("The -S and -C options must precede all other arguments");
398       if (res == 'S') {
399         postpone_commit = 1;
400         load_default();
401         if (cf_set(optarg))
402           die("Cannot set %s", optarg);
403       } else if (res == 'C') {
404         postpone_commit = 1;
405         if (cf_load(optarg))
406           die("Cannot load config file %s", optarg);
407       }
408 #ifdef CONFIG_DEBUG
409       else {   /* --dumpconfig */
410         load_default();
411         final_commit();
412         struct fastbuf *b = bfdopen(1, 4096);
413         cf_dump_sections(b);
414         bclose(b);
415         exit(0);
416       }
417 #endif
418     } else {
419       /* unhandled option or end of options */
420       if (res != ':' && res != '?')
421         load_default();
422       final_commit();
423       other_options++;
424       return res;
425     }
426   }
427 }
428