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