]> git.sur5r.net Git - i3/i3/blob - src/config_parser.c
config parser: recover after invalid input
[i3/i3] / src / config_parser.c
1 #undef I3__FILE__
2 #define I3__FILE__ "config_parser.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * config_parser.c: hand-written parser to parse configuration directives.
10  *
11  * See also src/commands_parser.c for rationale on why we use a custom parser.
12  *
13  * This parser works VERY MUCH like src/commands_parser.c, so read that first.
14  * The differences are:
15  *
16  * 1. config_parser supports the 'number' token type (in addition to 'word' and
17  *    'string'). Numbers are referred to using &num (like $str).
18  *
19  * 2. Criteria are not executed immediately, they are just stored.
20  *
21  * 3. config_parser recognizes \n and \r as 'end' token, while commands_parser
22  *    ignores them.
23  *
24  * 4. config_parser skips the current line on invalid inputs and follows the
25  *    nearest <error> token.
26  *
27  */
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <stdbool.h>
33 #include <stdint.h>
34
35 #include "all.h"
36
37 // Macros to make the YAJL API a bit easier to use.
38 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
39 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
40
41 /*******************************************************************************
42  * The data structures used for parsing. Essentially the current state and a
43  * list of tokens for that state.
44  *
45  * The GENERATED_* files are generated by generate-commands-parser.pl with the
46  * input parser-specs/configs.spec.
47  ******************************************************************************/
48
49 #include "GENERATED_config_enums.h"
50
51 typedef struct token {
52     char *name;
53     char *identifier;
54     /* This might be __CALL */
55     cmdp_state next_state;
56     union {
57         uint16_t call_identifier;
58     } extra;
59 } cmdp_token;
60
61 typedef struct tokenptr {
62     cmdp_token *array;
63     int n;
64 } cmdp_token_ptr;
65
66 #include "GENERATED_config_tokens.h"
67
68 /*******************************************************************************
69  * The (small) stack where identified literals are stored during the parsing
70  * of a single command (like $workspace).
71  ******************************************************************************/
72
73 struct stack_entry {
74     /* Just a pointer, not dynamically allocated. */
75     const char *identifier;
76     enum {
77         STACK_STR = 0,
78         STACK_LONG = 1,
79     } type;
80     union {
81         char *str;
82         long num;
83     } val;
84 };
85
86 /* 10 entries should be enough for everybody. */
87 static struct stack_entry stack[10];
88
89 /*
90  * Pushes a string (identified by 'identifier') on the stack. We simply use a
91  * single array, since the number of entries we have to store is very small.
92  *
93  */
94 static void push_string(const char *identifier, char *str) {
95     for (int c = 0; c < 10; c++) {
96         if (stack[c].identifier != NULL &&
97             strcmp(stack[c].identifier, identifier) != 0)
98             continue;
99         if (stack[c].identifier == NULL) {
100             /* Found a free slot, let’s store it here. */
101             stack[c].identifier = identifier;
102             stack[c].val.str = str;
103             stack[c].type = STACK_STR;
104         } else {
105             /* Append the value. */
106             sasprintf(&(stack[c].val.str), "%s,%s", stack[c].val.str, str);
107         }
108         return;
109     }
110
111     /* When we arrive here, the stack is full. This should not happen and
112      * means there’s either a bug in this parser or the specification
113      * contains a command with more than 10 identified tokens. */
114     fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
115                     "in the code, or a new command which contains more than "
116                     "10 identified tokens.\n");
117     exit(1);
118 }
119
120 static void push_long(const char *identifier, long num) {
121     for (int c = 0; c < 10; c++) {
122         if (stack[c].identifier != NULL)
123             continue;
124         /* Found a free slot, let’s store it here. */
125         stack[c].identifier = identifier;
126         stack[c].val.num = num;
127         stack[c].type = STACK_LONG;
128         return;
129     }
130
131     /* When we arrive here, the stack is full. This should not happen and
132      * means there’s either a bug in this parser or the specification
133      * contains a command with more than 10 identified tokens. */
134     fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
135                     "in the code, or a new command which contains more than "
136                     "10 identified tokens.\n");
137     exit(1);
138
139 }
140
141 static const char *get_string(const char *identifier) {
142     for (int c = 0; c < 10; c++) {
143         if (stack[c].identifier == NULL)
144             break;
145         if (strcmp(identifier, stack[c].identifier) == 0)
146             return stack[c].val.str;
147     }
148     return NULL;
149 }
150
151 static const long get_long(const char *identifier) {
152     for (int c = 0; c < 10; c++) {
153         if (stack[c].identifier == NULL)
154             break;
155         if (strcmp(identifier, stack[c].identifier) == 0)
156             return stack[c].val.num;
157     }
158     return 0;
159 }
160
161 static void clear_stack(void) {
162     for (int c = 0; c < 10; c++) {
163         if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
164             free(stack[c].val.str);
165         stack[c].identifier = NULL;
166         stack[c].val.str = NULL;
167         stack[c].val.num = 0;
168     }
169 }
170
171 // TODO: remove this if it turns out we don’t need it for testing.
172 #if 0
173 /*******************************************************************************
174  * A dynamically growing linked list which holds the criteria for the current
175  * command.
176  ******************************************************************************/
177
178 typedef struct criterion {
179     char *type;
180     char *value;
181
182     TAILQ_ENTRY(criterion) criteria;
183 } criterion;
184
185 static TAILQ_HEAD(criteria_head, criterion) criteria =
186   TAILQ_HEAD_INITIALIZER(criteria);
187
188 /*
189  * Stores the given type/value in the list of criteria.
190  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
191  *
192  */
193 static void push_criterion(void *unused_criteria, const char *type,
194                            const char *value) {
195     struct criterion *criterion = malloc(sizeof(struct criterion));
196     criterion->type = strdup(type);
197     criterion->value = strdup(value);
198     TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
199 }
200
201 /*
202  * Clears the criteria linked list.
203  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
204  *
205  */
206 static void clear_criteria(void *unused_criteria) {
207     struct criterion *criterion;
208     while (!TAILQ_EMPTY(&criteria)) {
209         criterion = TAILQ_FIRST(&criteria);
210         free(criterion->type);
211         free(criterion->value);
212         TAILQ_REMOVE(&criteria, criterion, criteria);
213         free(criterion);
214     }
215 }
216 #endif
217
218 /*******************************************************************************
219  * The parser itself.
220  ******************************************************************************/
221
222 static cmdp_state state;
223 static Match current_match;
224 static struct ConfigResult subcommand_output;
225 static struct ConfigResult command_output;
226
227 /* A list which contains the states that lead to the current state, e.g.
228  * INITIAL, WORKSPACE_LAYOUT.
229  * When jumping back to INITIAL, statelist_idx will simply be set to 1
230  * (likewise for other states, e.g. MODE or BAR).
231  * This list is used to process the nearest error token. */
232 static cmdp_state statelist[10] = { INITIAL };
233 /* NB: statelist_idx points to where the next entry will be inserted */
234 static int statelist_idx = 1;
235
236 #include "GENERATED_config_call.h"
237
238
239 static void next_state(const cmdp_token *token) {
240     cmdp_state _next_state = token->next_state;
241
242         //printf("token = name %s identifier %s\n", token->name, token->identifier);
243         //printf("next_state = %d\n", token->next_state);
244     if (token->next_state == __CALL) {
245         subcommand_output.json_gen = command_output.json_gen;
246         GENERATED_call(token->extra.call_identifier, &subcommand_output);
247         _next_state = subcommand_output.next_state;
248         clear_stack();
249     }
250
251     state = _next_state;
252     if (state == INITIAL) {
253         clear_stack();
254     }
255
256     /* See if we are jumping back to a state in which we were in previously
257      * (statelist contains INITIAL) and just move statelist_idx accordingly. */
258     for (int i = 0; i < statelist_idx; i++) {
259         if (statelist[i] != _next_state)
260             continue;
261         statelist_idx = i+1;
262         return;
263     }
264
265     /* Otherwise, the state is new and we add it to the list */
266     statelist[statelist_idx++] = _next_state;
267 }
268
269 /*
270  * Returns a pointer to the start of the line (one byte after the previous \r,
271  * \n) or the start of the input, if this is the first line.
272  *
273  */
274 static const char *start_of_line(const char *walk, const char *beginning) {
275     while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
276         walk--;
277     }
278
279     return walk + 1;
280 }
281
282 /*
283  * Copies the line and terminates it at the next \n, if any.
284  *
285  * The caller has to free() the result.
286  *
287  */
288 static char *single_line(const char *start) {
289     char *result = sstrdup(start);
290     char *end = strchr(result, '\n');
291     if (end != NULL)
292         *end = '\0';
293     return result;
294 }
295
296 struct ConfigResult *parse_config(const char *input, struct context *context) {
297     /* Dump the entire config file into the debug log. We cannot just use
298      * DLOG("%s", input); because one log message must not exceed 4 KiB. */
299     const char *dumpwalk = input;
300     int linecnt = 1;
301     while (*dumpwalk != '\0') {
302         char *next_nl = strchr(dumpwalk, '\n');
303         if (next_nl != NULL) {
304             DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
305             dumpwalk = next_nl + 1;
306         } else {
307             DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
308             break;
309         }
310         linecnt++;
311     }
312     state = INITIAL;
313     statelist_idx = 1;
314
315 /* A YAJL JSON generator used for formatting replies. */
316 #if YAJL_MAJOR >= 2
317     command_output.json_gen = yajl_gen_alloc(NULL);
318 #else
319     command_output.json_gen = yajl_gen_alloc(NULL, NULL);
320 #endif
321
322     y(array_open);
323
324     const char *walk = input;
325     const size_t len = strlen(input);
326     int c;
327     const cmdp_token *token;
328     bool token_handled;
329     linecnt = 1;
330
331     // TODO: make this testable
332 #ifndef TEST_PARSER
333     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
334 #endif
335
336     /* The "<=" operator is intentional: We also handle the terminating 0-byte
337      * explicitly by looking for an 'end' token. */
338     while ((walk - input) <= len) {
339         /* Skip whitespace before every token, newlines are relevant since they
340          * separate configuration directives. */
341         while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
342             walk++;
343
344                 //printf("remaining input: %s\n", walk);
345
346         cmdp_token_ptr *ptr = &(tokens[state]);
347         token_handled = false;
348         for (c = 0; c < ptr->n; c++) {
349             token = &(ptr->array[c]);
350
351             /* A literal. */
352             if (token->name[0] == '\'') {
353                 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
354                     if (token->identifier != NULL)
355                         push_string(token->identifier, sstrdup(token->name + 1));
356                     walk += strlen(token->name) - 1;
357                     next_state(token);
358                     token_handled = true;
359                     break;
360                 }
361                 continue;
362             }
363
364             if (strcmp(token->name, "number") == 0) {
365                 /* Handle numbers. We only accept decimal numbers for now. */
366                 char *end = NULL;
367                 errno = 0;
368                 long int num = strtol(walk, &end, 10);
369                 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
370                     (errno != 0 && num == 0))
371                     continue;
372
373                 /* No valid numbers found */
374                 if (end == walk)
375                     continue;
376
377                 if (token->identifier != NULL)
378                     push_long(token->identifier, num);
379
380                 /* Set walk to the first non-number character */
381                 walk = end;
382                 next_state(token);
383                 token_handled = true;
384                 break;
385             }
386
387             if (strcmp(token->name, "string") == 0 ||
388                 strcmp(token->name, "word") == 0) {
389                 const char *beginning = walk;
390                 /* Handle quoted strings (or words). */
391                 if (*walk == '"') {
392                     beginning++;
393                     walk++;
394                     while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
395                         walk++;
396                 } else {
397                     if (token->name[0] == 's') {
398                         while (*walk != '\0' && *walk != '\r' && *walk != '\n')
399                             walk++;
400                     } else {
401                         /* For a word, the delimiters are white space (' ' or
402                          * '\t'), closing square bracket (]), comma (,) and
403                          * semicolon (;). */
404                         while (*walk != ' ' && *walk != '\t' &&
405                                *walk != ']' && *walk != ',' &&
406                                *walk !=  ';' && *walk != '\r' &&
407                                *walk != '\n' && *walk != '\0')
408                             walk++;
409                     }
410                 }
411                 if (walk != beginning) {
412                     char *str = scalloc(walk-beginning + 1);
413                     /* We copy manually to handle escaping of characters. */
414                     int inpos, outpos;
415                     for (inpos = 0, outpos = 0;
416                          inpos < (walk-beginning);
417                          inpos++, outpos++) {
418                         /* We only handle escaped double quotes to not break
419                          * backwards compatibility with people using \w in
420                          * regular expressions etc. */
421                         if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
422                             inpos++;
423                         str[outpos] = beginning[inpos];
424                     }
425                     if (token->identifier)
426                         push_string(token->identifier, str);
427                     /* If we are at the end of a quoted string, skip the ending
428                      * double quote. */
429                     if (*walk == '"')
430                         walk++;
431                     next_state(token);
432                     token_handled = true;
433                     break;
434                 }
435             }
436
437             if (strcmp(token->name, "end") == 0) {
438                 //printf("checking for end: *%s*\n", walk);
439                 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
440                     next_state(token);
441                     token_handled = true;
442                     /* To make sure we start with an appropriate matching
443                      * datastructure for commands which do *not* specify any
444                      * criteria, we re-initialize the criteria system after
445                      * every command. */
446                     // TODO: make this testable
447 #ifndef TEST_PARSER
448                     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
449 #endif
450                     linecnt++;
451                     walk++;
452                     break;
453                }
454            }
455         }
456
457         if (!token_handled) {
458             /* Figure out how much memory we will need to fill in the names of
459              * all tokens afterwards. */
460             int tokenlen = 0;
461             for (c = 0; c < ptr->n; c++)
462                 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
463
464             /* Build up a decent error message. We include the problem, the
465              * full input, and underline the position where the parser
466              * currently is. */
467             char *errormessage;
468             char *possible_tokens = smalloc(tokenlen + 1);
469             char *tokenwalk = possible_tokens;
470             for (c = 0; c < ptr->n; c++) {
471                 token = &(ptr->array[c]);
472                 if (token->name[0] == '\'') {
473                     /* A literal is copied to the error message enclosed with
474                      * single quotes. */
475                     *tokenwalk++ = '\'';
476                     strcpy(tokenwalk, token->name + 1);
477                     tokenwalk += strlen(token->name + 1);
478                     *tokenwalk++ = '\'';
479                 } else {
480                     /* Skip error tokens in error messages, they are used
481                      * internally only and might confuse users. */
482                     if (strcmp(token->name, "error") == 0)
483                         continue;
484                     /* Any other token is copied to the error message enclosed
485                      * with angle brackets. */
486                     *tokenwalk++ = '<';
487                     strcpy(tokenwalk, token->name);
488                     tokenwalk += strlen(token->name);
489                     *tokenwalk++ = '>';
490                 }
491                 if (c < (ptr->n - 1)) {
492                     *tokenwalk++ = ',';
493                     *tokenwalk++ = ' ';
494                 }
495             }
496             *tokenwalk = '\0';
497             sasprintf(&errormessage, "Expected one of these tokens: %s",
498                       possible_tokens);
499             free(possible_tokens);
500
501
502             /* Go back to the beginning of the line */
503             const char *error_line = start_of_line(walk, input);
504
505             /* Contains the same amount of characters as 'input' has, but with
506              * the unparseable part highlighted using ^ characters. */
507             char *position = scalloc(strlen(error_line) + 1);
508             const char *copywalk;
509             for (copywalk = error_line;
510                  *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
511                  copywalk++)
512                 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
513             position[(copywalk - error_line)] = '\0';
514
515             ELOG("CONFIG: %s\n", errormessage);
516             ELOG("CONFIG: (in file %s)\n", context->filename);
517             char *error_copy = single_line(error_line);
518
519             /* Print context lines *before* the error, if any. */
520             if (linecnt > 1) {
521                 const char *context_p1_start = start_of_line(error_line-2, input);
522                 char *context_p1_line = single_line(context_p1_start);
523                 if (linecnt > 2) {
524                     const char *context_p2_start = start_of_line(context_p1_start-2, input);
525                     char *context_p2_line = single_line(context_p2_start);
526                     ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
527                     free(context_p2_line);
528                 }
529                 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
530                 free(context_p1_line);
531             }
532             ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
533             ELOG("CONFIG:           %s\n", position);
534             free(error_copy);
535             /* Print context lines *after* the error, if any. */
536             for (int i = 0; i < 2; i++) {
537                 char *error_line_end = strchr(error_line, '\n');
538                 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
539                     error_line = error_line_end + 1;
540                     error_copy = single_line(error_line);
541                     ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
542                     free(error_copy);
543                 }
544             }
545
546             context->has_errors = true;
547
548             /* Format this error message as a JSON reply. */
549             y(map_open);
550             ystr("success");
551             y(bool, false);
552             /* We set parse_error to true to distinguish this from other
553              * errors. i3-nagbar is spawned upon keypresses only for parser
554              * errors. */
555             ystr("parse_error");
556             y(bool, true);
557             ystr("error");
558             ystr(errormessage);
559             ystr("input");
560             ystr(input);
561             ystr("errorposition");
562             ystr(position);
563             y(map_close);
564
565             /* Skip the rest of this line, but continue parsing. */
566             while ((walk - input) <= len && *walk != '\n')
567                 walk++;
568
569             free(position);
570             free(errormessage);
571             clear_stack();
572
573             /* To figure out in which state to go (e.g. MODE or INITIAL),
574              * we find the nearest state which contains an <error> token
575              * and follow that one. */
576             bool error_token_found = false;
577             for (int i = statelist_idx-1; (i >= 0) && !error_token_found; i--) {
578                 cmdp_token_ptr *errptr = &(tokens[statelist[i]]);
579                 for (int j = 0; j < errptr->n; j++) {
580                     if (strcmp(errptr->array[j].name, "error") != 0)
581                         continue;
582                     next_state(&(errptr->array[j]));
583                     error_token_found = true;
584                     break;
585                 }
586             }
587
588             assert(error_token_found);
589         }
590     }
591
592     y(array_close);
593
594     return &command_output;
595 }
596
597 /*******************************************************************************
598  * Code for building the stand-alone binary test.commands_parser which is used
599  * by t/187-commands-parser.t.
600  ******************************************************************************/
601
602 #ifdef TEST_PARSER
603
604 /*
605  * Logs the given message to stdout while prefixing the current time to it,
606  * but only if debug logging was activated.
607  * This is to be called by DLOG() which includes filename/linenumber
608  *
609  */
610 void debuglog(char *fmt, ...) {
611     va_list args;
612
613     va_start(args, fmt);
614     fprintf(stdout, "# ");
615     vfprintf(stdout, fmt, args);
616     va_end(args);
617 }
618
619 void errorlog(char *fmt, ...) {
620     va_list args;
621
622     va_start(args, fmt);
623     vfprintf(stderr, fmt, args);
624     va_end(args);
625 }
626
627 static int criteria_next_state;
628
629 void cfg_criteria_init(I3_CFG, int _state) {
630     criteria_next_state = _state;
631 }
632
633 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
634 }
635
636 void cfg_criteria_pop_state(I3_CFG) {
637     result->next_state = criteria_next_state;
638 }
639
640 int main(int argc, char *argv[]) {
641     if (argc < 2) {
642         fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
643         return 1;
644     }
645     struct context context;
646     context.filename = "<stdin>";
647     parse_config(argv[1], &context);
648 }
649 #endif