]> git.sur5r.net Git - i3/i3/blob - src/config_parser.c
Introduce support for specifying variables from X resources. (#2286)
[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 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 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <xcb/xcb_xrm.h>
39
40 #include "all.h"
41
42 // Macros to make the YAJL API a bit easier to use.
43 #define y(x, ...) yajl_gen_##x(command_output.json_gen, ##__VA_ARGS__)
44 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char *)str, strlen(str))
45
46 xcb_xrm_database_t *database = NULL;
47
48 #ifndef TEST_PARSER
49 pid_t config_error_nagbar_pid = -1;
50 static struct context *context;
51 #endif
52
53 /*******************************************************************************
54  * The data structures used for parsing. Essentially the current state and a
55  * list of tokens for that state.
56  *
57  * The GENERATED_* files are generated by generate-commands-parser.pl with the
58  * input parser-specs/configs.spec.
59  ******************************************************************************/
60
61 #include "GENERATED_config_enums.h"
62
63 typedef struct token {
64     char *name;
65     char *identifier;
66     /* This might be __CALL */
67     cmdp_state next_state;
68     union {
69         uint16_t call_identifier;
70     } extra;
71 } cmdp_token;
72
73 typedef struct tokenptr {
74     cmdp_token *array;
75     int n;
76 } cmdp_token_ptr;
77
78 #include "GENERATED_config_tokens.h"
79
80 /*******************************************************************************
81  * The (small) stack where identified literals are stored during the parsing
82  * of a single command (like $workspace).
83  ******************************************************************************/
84
85 struct stack_entry {
86     /* Just a pointer, not dynamically allocated. */
87     const char *identifier;
88     enum {
89         STACK_STR = 0,
90         STACK_LONG = 1,
91     } type;
92     union {
93         char *str;
94         long num;
95     } val;
96 };
97
98 /* 10 entries should be enough for everybody. */
99 static struct stack_entry stack[10];
100
101 /*
102  * Pushes a string (identified by 'identifier') on the stack. We simply use a
103  * single array, since the number of entries we have to store is very small.
104  *
105  */
106 static void push_string(const char *identifier, const char *str) {
107     for (int c = 0; c < 10; c++) {
108         if (stack[c].identifier != NULL &&
109             strcmp(stack[c].identifier, identifier) != 0)
110             continue;
111         if (stack[c].identifier == NULL) {
112             /* Found a free slot, let’s store it here. */
113             stack[c].identifier = identifier;
114             stack[c].val.str = sstrdup(str);
115             stack[c].type = STACK_STR;
116         } else {
117             /* Append the value. */
118             char *prev = stack[c].val.str;
119             sasprintf(&(stack[c].val.str), "%s,%s", prev, str);
120             free(prev);
121         }
122         return;
123     }
124
125     /* When we arrive here, the stack is full. This should not happen and
126      * means there’s either a bug in this parser or the specification
127      * contains a command with more than 10 identified tokens. */
128     fprintf(stderr, "BUG: config_parser stack full. This means either a bug "
129                     "in the code, or a new command which contains more than "
130                     "10 identified tokens.\n");
131     exit(1);
132 }
133
134 static void push_long(const char *identifier, long num) {
135     for (int c = 0; c < 10; c++) {
136         if (stack[c].identifier != NULL)
137             continue;
138         /* Found a free slot, let’s store it here. */
139         stack[c].identifier = identifier;
140         stack[c].val.num = num;
141         stack[c].type = STACK_LONG;
142         return;
143     }
144
145     /* When we arrive here, the stack is full. This should not happen and
146      * means there’s either a bug in this parser or the specification
147      * contains a command with more than 10 identified tokens. */
148     fprintf(stderr, "BUG: config_parser stack full. This means either a bug "
149                     "in the code, or a new command which contains more than "
150                     "10 identified tokens.\n");
151     exit(1);
152 }
153
154 static const char *get_string(const char *identifier) {
155     for (int c = 0; c < 10; c++) {
156         if (stack[c].identifier == NULL)
157             break;
158         if (strcmp(identifier, stack[c].identifier) == 0)
159             return stack[c].val.str;
160     }
161     return NULL;
162 }
163
164 static long get_long(const char *identifier) {
165     for (int c = 0; c < 10; c++) {
166         if (stack[c].identifier == NULL)
167             break;
168         if (strcmp(identifier, stack[c].identifier) == 0)
169             return stack[c].val.num;
170     }
171     return 0;
172 }
173
174 static void clear_stack(void) {
175     for (int c = 0; c < 10; c++) {
176         if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
177             free(stack[c].val.str);
178         stack[c].identifier = NULL;
179         stack[c].val.str = NULL;
180         stack[c].val.num = 0;
181     }
182 }
183
184 /*******************************************************************************
185  * The parser itself.
186  ******************************************************************************/
187
188 static cmdp_state state;
189 static Match current_match;
190 static struct ConfigResultIR subcommand_output;
191 static struct ConfigResultIR command_output;
192
193 /* A list which contains the states that lead to the current state, e.g.
194  * INITIAL, WORKSPACE_LAYOUT.
195  * When jumping back to INITIAL, statelist_idx will simply be set to 1
196  * (likewise for other states, e.g. MODE or BAR).
197  * This list is used to process the nearest error token. */
198 static cmdp_state statelist[10] = {INITIAL};
199 /* NB: statelist_idx points to where the next entry will be inserted */
200 static int statelist_idx = 1;
201
202 #include "GENERATED_config_call.h"
203
204 static void next_state(const cmdp_token *token) {
205     cmdp_state _next_state = token->next_state;
206
207     //printf("token = name %s identifier %s\n", token->name, token->identifier);
208     //printf("next_state = %d\n", token->next_state);
209     if (token->next_state == __CALL) {
210         subcommand_output.json_gen = command_output.json_gen;
211         GENERATED_call(token->extra.call_identifier, &subcommand_output);
212         _next_state = subcommand_output.next_state;
213         clear_stack();
214     }
215
216     state = _next_state;
217     if (state == INITIAL) {
218         clear_stack();
219     }
220
221     /* See if we are jumping back to a state in which we were in previously
222      * (statelist contains INITIAL) and just move statelist_idx accordingly. */
223     for (int i = 0; i < statelist_idx; i++) {
224         if (statelist[i] != _next_state)
225             continue;
226         statelist_idx = i + 1;
227         return;
228     }
229
230     /* Otherwise, the state is new and we add it to the list */
231     statelist[statelist_idx++] = _next_state;
232 }
233
234 /*
235  * Returns a pointer to the start of the line (one byte after the previous \r,
236  * \n) or the start of the input, if this is the first line.
237  *
238  */
239 static const char *start_of_line(const char *walk, const char *beginning) {
240     while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
241         walk--;
242     }
243
244     return walk + 1;
245 }
246
247 /*
248  * Copies the line and terminates it at the next \n, if any.
249  *
250  * The caller has to free() the result.
251  *
252  */
253 static char *single_line(const char *start) {
254     char *result = sstrdup(start);
255     char *end = strchr(result, '\n');
256     if (end != NULL)
257         *end = '\0';
258     return result;
259 }
260
261 struct ConfigResultIR *parse_config(const char *input, struct context *context) {
262     /* Dump the entire config file into the debug log. We cannot just use
263      * DLOG("%s", input); because one log message must not exceed 4 KiB. */
264     const char *dumpwalk = input;
265     int linecnt = 1;
266     while (*dumpwalk != '\0') {
267         char *next_nl = strchr(dumpwalk, '\n');
268         if (next_nl != NULL) {
269             DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
270             dumpwalk = next_nl + 1;
271         } else {
272             DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
273             break;
274         }
275         linecnt++;
276     }
277     state = INITIAL;
278     statelist_idx = 1;
279
280     /* A YAJL JSON generator used for formatting replies. */
281     command_output.json_gen = yajl_gen_alloc(NULL);
282
283     y(array_open);
284
285     const char *walk = input;
286     const size_t len = strlen(input);
287     int c;
288     const cmdp_token *token;
289     bool token_handled;
290     linecnt = 1;
291
292 // TODO: make this testable
293 #ifndef TEST_PARSER
294     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
295 #endif
296
297     /* The "<=" operator is intentional: We also handle the terminating 0-byte
298      * explicitly by looking for an 'end' token. */
299     while ((size_t)(walk - input) <= len) {
300         /* Skip whitespace before every token, newlines are relevant since they
301          * separate configuration directives. */
302         while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
303             walk++;
304
305         //printf("remaining input: %s\n", walk);
306
307         cmdp_token_ptr *ptr = &(tokens[state]);
308         token_handled = false;
309         for (c = 0; c < ptr->n; c++) {
310             token = &(ptr->array[c]);
311
312             /* A literal. */
313             if (token->name[0] == '\'') {
314                 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
315                     if (token->identifier != NULL)
316                         push_string(token->identifier, token->name + 1);
317                     walk += strlen(token->name) - 1;
318                     next_state(token);
319                     token_handled = true;
320                     break;
321                 }
322                 continue;
323             }
324
325             if (strcmp(token->name, "number") == 0) {
326                 /* Handle numbers. We only accept decimal numbers for now. */
327                 char *end = NULL;
328                 errno = 0;
329                 long int num = strtol(walk, &end, 10);
330                 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
331                     (errno != 0 && num == 0))
332                     continue;
333
334                 /* No valid numbers found */
335                 if (end == walk)
336                     continue;
337
338                 if (token->identifier != NULL)
339                     push_long(token->identifier, num);
340
341                 /* Set walk to the first non-number character */
342                 walk = end;
343                 next_state(token);
344                 token_handled = true;
345                 break;
346             }
347
348             if (strcmp(token->name, "string") == 0 ||
349                 strcmp(token->name, "word") == 0) {
350                 const char *beginning = walk;
351                 /* Handle quoted strings (or words). */
352                 if (*walk == '"') {
353                     beginning++;
354                     walk++;
355                     while (*walk != '\0' && (*walk != '"' || *(walk - 1) == '\\'))
356                         walk++;
357                 } else {
358                     if (token->name[0] == 's') {
359                         while (*walk != '\0' && *walk != '\r' && *walk != '\n')
360                             walk++;
361                     } else {
362                         /* For a word, the delimiters are white space (' ' or
363                          * '\t'), closing square bracket (]), comma (,) and
364                          * semicolon (;). */
365                         while (*walk != ' ' && *walk != '\t' &&
366                                *walk != ']' && *walk != ',' &&
367                                *walk != ';' && *walk != '\r' &&
368                                *walk != '\n' && *walk != '\0')
369                             walk++;
370                     }
371                 }
372                 if (walk != beginning) {
373                     char *str = scalloc(walk - beginning + 1, 1);
374                     /* We copy manually to handle escaping of characters. */
375                     int inpos, outpos;
376                     for (inpos = 0, outpos = 0;
377                          inpos < (walk - beginning);
378                          inpos++, outpos++) {
379                         /* We only handle escaped double quotes to not break
380                          * backwards compatibility with people using \w in
381                          * regular expressions etc. */
382                         if (beginning[inpos] == '\\' && beginning[inpos + 1] == '"')
383                             inpos++;
384                         str[outpos] = beginning[inpos];
385                     }
386                     if (token->identifier)
387                         push_string(token->identifier, str);
388                     free(str);
389                     /* If we are at the end of a quoted string, skip the ending
390                      * double quote. */
391                     if (*walk == '"')
392                         walk++;
393                     next_state(token);
394                     token_handled = true;
395                     break;
396                 }
397             }
398
399             if (strcmp(token->name, "line") == 0) {
400                 while (*walk != '\0' && *walk != '\n' && *walk != '\r')
401                     walk++;
402                 next_state(token);
403                 token_handled = true;
404                 linecnt++;
405                 walk++;
406                 break;
407             }
408
409             if (strcmp(token->name, "end") == 0) {
410                 //printf("checking for end: *%s*\n", walk);
411                 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
412                     next_state(token);
413                     token_handled = true;
414 /* To make sure we start with an appropriate matching
415                      * datastructure for commands which do *not* specify any
416                      * criteria, we re-initialize the criteria system after
417                      * every command. */
418 // TODO: make this testable
419 #ifndef TEST_PARSER
420                     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
421 #endif
422                     linecnt++;
423                     walk++;
424                     break;
425                 }
426             }
427         }
428
429         if (!token_handled) {
430             /* Figure out how much memory we will need to fill in the names of
431              * all tokens afterwards. */
432             int tokenlen = 0;
433             for (c = 0; c < ptr->n; c++)
434                 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
435
436             /* Build up a decent error message. We include the problem, the
437              * full input, and underline the position where the parser
438              * currently is. */
439             char *errormessage;
440             char *possible_tokens = smalloc(tokenlen + 1);
441             char *tokenwalk = possible_tokens;
442             for (c = 0; c < ptr->n; c++) {
443                 token = &(ptr->array[c]);
444                 if (token->name[0] == '\'') {
445                     /* A literal is copied to the error message enclosed with
446                      * single quotes. */
447                     *tokenwalk++ = '\'';
448                     strcpy(tokenwalk, token->name + 1);
449                     tokenwalk += strlen(token->name + 1);
450                     *tokenwalk++ = '\'';
451                 } else {
452                     /* Skip error tokens in error messages, they are used
453                      * internally only and might confuse users. */
454                     if (strcmp(token->name, "error") == 0)
455                         continue;
456                     /* Any other token is copied to the error message enclosed
457                      * with angle brackets. */
458                     *tokenwalk++ = '<';
459                     strcpy(tokenwalk, token->name);
460                     tokenwalk += strlen(token->name);
461                     *tokenwalk++ = '>';
462                 }
463                 if (c < (ptr->n - 1)) {
464                     *tokenwalk++ = ',';
465                     *tokenwalk++ = ' ';
466                 }
467             }
468             *tokenwalk = '\0';
469             sasprintf(&errormessage, "Expected one of these tokens: %s",
470                       possible_tokens);
471             free(possible_tokens);
472
473             /* Go back to the beginning of the line */
474             const char *error_line = start_of_line(walk, input);
475
476             /* Contains the same amount of characters as 'input' has, but with
477              * the unparseable part highlighted using ^ characters. */
478             char *position = scalloc(strlen(error_line) + 1, 1);
479             const char *copywalk;
480             for (copywalk = error_line;
481                  *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
482                  copywalk++)
483                 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
484             position[(copywalk - error_line)] = '\0';
485
486             ELOG("CONFIG: %s\n", errormessage);
487             ELOG("CONFIG: (in file %s)\n", context->filename);
488             char *error_copy = single_line(error_line);
489
490             /* Print context lines *before* the error, if any. */
491             if (linecnt > 1) {
492                 const char *context_p1_start = start_of_line(error_line - 2, input);
493                 char *context_p1_line = single_line(context_p1_start);
494                 if (linecnt > 2) {
495                     const char *context_p2_start = start_of_line(context_p1_start - 2, input);
496                     char *context_p2_line = single_line(context_p2_start);
497                     ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
498                     free(context_p2_line);
499                 }
500                 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
501                 free(context_p1_line);
502             }
503             ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
504             ELOG("CONFIG:           %s\n", position);
505             free(error_copy);
506             /* Print context lines *after* the error, if any. */
507             for (int i = 0; i < 2; i++) {
508                 char *error_line_end = strchr(error_line, '\n');
509                 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
510                     error_line = error_line_end + 1;
511                     error_copy = single_line(error_line);
512                     ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
513                     free(error_copy);
514                 }
515             }
516
517             context->has_errors = true;
518
519             /* Format this error message as a JSON reply. */
520             y(map_open);
521             ystr("success");
522             y(bool, false);
523             /* We set parse_error to true to distinguish this from other
524              * errors. i3-nagbar is spawned upon keypresses only for parser
525              * errors. */
526             ystr("parse_error");
527             y(bool, true);
528             ystr("error");
529             ystr(errormessage);
530             ystr("input");
531             ystr(input);
532             ystr("errorposition");
533             ystr(position);
534             y(map_close);
535
536             /* Skip the rest of this line, but continue parsing. */
537             while ((size_t)(walk - input) <= len && *walk != '\n')
538                 walk++;
539
540             free(position);
541             free(errormessage);
542             clear_stack();
543
544             /* To figure out in which state to go (e.g. MODE or INITIAL),
545              * we find the nearest state which contains an <error> token
546              * and follow that one. */
547             bool error_token_found = false;
548             for (int i = statelist_idx - 1; (i >= 0) && !error_token_found; i--) {
549                 cmdp_token_ptr *errptr = &(tokens[statelist[i]]);
550                 for (int j = 0; j < errptr->n; j++) {
551                     if (strcmp(errptr->array[j].name, "error") != 0)
552                         continue;
553                     next_state(&(errptr->array[j]));
554                     error_token_found = true;
555                     break;
556                 }
557             }
558
559             assert(error_token_found);
560         }
561     }
562
563     y(array_close);
564
565     return &command_output;
566 }
567
568 /*******************************************************************************
569  * Code for building the stand-alone binary test.commands_parser which is used
570  * by t/187-commands-parser.t.
571  ******************************************************************************/
572
573 #ifdef TEST_PARSER
574
575 /*
576  * Logs the given message to stdout while prefixing the current time to it,
577  * but only if debug logging was activated.
578  * This is to be called by DLOG() which includes filename/linenumber
579  *
580  */
581 void debuglog(char *fmt, ...) {
582     va_list args;
583
584     va_start(args, fmt);
585     fprintf(stdout, "# ");
586     vfprintf(stdout, fmt, args);
587     va_end(args);
588 }
589
590 void errorlog(char *fmt, ...) {
591     va_list args;
592
593     va_start(args, fmt);
594     vfprintf(stderr, fmt, args);
595     va_end(args);
596 }
597
598 static int criteria_next_state;
599
600 void cfg_criteria_init(I3_CFG, int _state) {
601     criteria_next_state = _state;
602 }
603
604 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
605 }
606
607 void cfg_criteria_pop_state(I3_CFG) {
608     result->next_state = criteria_next_state;
609 }
610
611 int main(int argc, char *argv[]) {
612     if (argc < 2) {
613         fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
614         return 1;
615     }
616     struct context context;
617     context.filename = "<stdin>";
618     parse_config(argv[1], &context);
619 }
620
621 #else
622
623 /*
624  * Goes through each line of buf (separated by \n) and checks for statements /
625  * commands which only occur in i3 v4 configuration files. If it finds any, it
626  * returns version 4, otherwise it returns version 3.
627  *
628  */
629 static int detect_version(char *buf) {
630     char *walk = buf;
631     char *line = buf;
632     while (*walk != '\0') {
633         if (*walk != '\n') {
634             walk++;
635             continue;
636         }
637
638         /* check for some v4-only statements */
639         if (strncasecmp(line, "bindcode", strlen("bindcode")) == 0 ||
640             strncasecmp(line, "force_focus_wrapping", strlen("force_focus_wrapping")) == 0 ||
641             strncasecmp(line, "# i3 config file (v4)", strlen("# i3 config file (v4)")) == 0 ||
642             strncasecmp(line, "workspace_layout", strlen("workspace_layout")) == 0) {
643             LOG("deciding for version 4 due to this line: %.*s\n", (int)(walk - line), line);
644             return 4;
645         }
646
647         /* if this is a bind statement, we can check the command */
648         if (strncasecmp(line, "bind", strlen("bind")) == 0) {
649             char *bind = strchr(line, ' ');
650             if (bind == NULL)
651                 goto next;
652             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
653                 bind++;
654             if (*bind == '\0')
655                 goto next;
656             if ((bind = strchr(bind, ' ')) == NULL)
657                 goto next;
658             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
659                 bind++;
660             if (*bind == '\0')
661                 goto next;
662             if (strncasecmp(bind, "layout", strlen("layout")) == 0 ||
663                 strncasecmp(bind, "floating", strlen("floating")) == 0 ||
664                 strncasecmp(bind, "workspace", strlen("workspace")) == 0 ||
665                 strncasecmp(bind, "focus left", strlen("focus left")) == 0 ||
666                 strncasecmp(bind, "focus right", strlen("focus right")) == 0 ||
667                 strncasecmp(bind, "focus up", strlen("focus up")) == 0 ||
668                 strncasecmp(bind, "focus down", strlen("focus down")) == 0 ||
669                 strncasecmp(bind, "border normal", strlen("border normal")) == 0 ||
670                 strncasecmp(bind, "border 1pixel", strlen("border 1pixel")) == 0 ||
671                 strncasecmp(bind, "border pixel", strlen("border pixel")) == 0 ||
672                 strncasecmp(bind, "border borderless", strlen("border borderless")) == 0 ||
673                 strncasecmp(bind, "--no-startup-id", strlen("--no-startup-id")) == 0 ||
674                 strncasecmp(bind, "bar", strlen("bar")) == 0) {
675                 LOG("deciding for version 4 due to this line: %.*s\n", (int)(walk - line), line);
676                 return 4;
677             }
678         }
679
680     next:
681         /* advance to the next line */
682         walk++;
683         line = walk;
684     }
685
686     return 3;
687 }
688
689 /*
690  * Calls i3-migrate-config-to-v4 to migrate a configuration file (input
691  * buffer).
692  *
693  * Returns the converted config file or NULL if there was an error (for
694  * example the script could not be found in $PATH or the i3 executable’s
695  * directory).
696  *
697  */
698 static char *migrate_config(char *input, off_t size) {
699     int writepipe[2];
700     int readpipe[2];
701
702     if (pipe(writepipe) != 0 ||
703         pipe(readpipe) != 0) {
704         warn("migrate_config: Could not create pipes");
705         return NULL;
706     }
707
708     pid_t pid = fork();
709     if (pid == -1) {
710         warn("Could not fork()");
711         return NULL;
712     }
713
714     /* child */
715     if (pid == 0) {
716         /* close writing end of writepipe, connect reading side to stdin */
717         close(writepipe[1]);
718         dup2(writepipe[0], 0);
719
720         /* close reading end of readpipe, connect writing side to stdout */
721         close(readpipe[0]);
722         dup2(readpipe[1], 1);
723
724         static char *argv[] = {
725             NULL, /* will be replaced by the executable path */
726             NULL};
727         exec_i3_utility("i3-migrate-config-to-v4", argv);
728     }
729
730     /* parent */
731
732     /* close reading end of the writepipe (connected to the script’s stdin) */
733     close(writepipe[0]);
734
735     /* write the whole config file to the pipe, the script will read everything
736      * immediately */
737     if (writeall(writepipe[1], input, size) == -1) {
738         warn("Could not write to pipe");
739         return NULL;
740     }
741     close(writepipe[1]);
742
743     /* close writing end of the readpipe (connected to the script’s stdout) */
744     close(readpipe[1]);
745
746     /* read the script’s output */
747     int conv_size = 65535;
748     char *converted = smalloc(conv_size);
749     int read_bytes = 0, ret;
750     do {
751         if (read_bytes == conv_size) {
752             conv_size += 65535;
753             converted = srealloc(converted, conv_size);
754         }
755         ret = read(readpipe[0], converted + read_bytes, conv_size - read_bytes);
756         if (ret == -1) {
757             warn("Cannot read from pipe");
758             FREE(converted);
759             return NULL;
760         }
761         read_bytes += ret;
762     } while (ret > 0);
763
764     /* get the returncode */
765     int status;
766     wait(&status);
767     if (!WIFEXITED(status)) {
768         fprintf(stderr, "Child did not terminate normally, using old config file (will lead to broken behaviour)\n");
769         return NULL;
770     }
771
772     int returncode = WEXITSTATUS(status);
773     if (returncode != 0) {
774         fprintf(stderr, "Migration process exit code was != 0\n");
775         if (returncode == 2) {
776             fprintf(stderr, "could not start the migration script\n");
777             /* TODO: script was not found. tell the user to fix their system or create a v4 config */
778         } else if (returncode == 1) {
779             fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
780             fprintf(stderr, "# i3 config file (v4)\n");
781             /* TODO: nag the user with a message to include a hint for i3 in their config file */
782         }
783         return NULL;
784     }
785
786     return converted;
787 }
788
789 /**
790  * Launch nagbar to indicate errors in the configuration file.
791  */
792 void start_config_error_nagbar(const char *configpath, bool has_errors) {
793     char *editaction, *pageraction;
794     sasprintf(&editaction, "i3-sensible-editor \"%s\" && i3-msg reload\n", configpath);
795     sasprintf(&pageraction, "i3-sensible-pager \"%s\"\n", errorfilename);
796     char *argv[] = {
797         NULL, /* will be replaced by the executable path */
798         "-f",
799         (config.font.pattern ? config.font.pattern : "fixed"),
800         "-t",
801         (has_errors ? "error" : "warning"),
802         "-m",
803         (has_errors ? "You have an error in your i3 config file!" : "Your config is outdated. Please fix the warnings to make sure everything works."),
804         "-b",
805         "edit config",
806         editaction,
807         (errorfilename ? "-b" : NULL),
808         (has_errors ? "show errors" : "show warnings"),
809         pageraction,
810         NULL};
811
812     start_nagbar(&config_error_nagbar_pid, argv);
813     free(editaction);
814     free(pageraction);
815 }
816
817 /*
818  * Inserts or updates a variable assignment depending on whether it already exists.
819  *
820  */
821 static void upsert_variable(struct variables_head *variables, char *key, char *value) {
822     struct Variable *current;
823     SLIST_FOREACH(current, variables, variables) {
824         if (strcmp(current->key, key) != 0) {
825             continue;
826         }
827
828         DLOG("Updated variable: %s = %s -> %s\n", key, current->value, value);
829         FREE(current->value);
830         current->value = sstrdup(value);
831         return;
832     }
833
834     DLOG("Defined new variable: %s = %s\n", key, value);
835     struct Variable *new = scalloc(1, sizeof(struct Variable));
836     struct Variable *test = NULL, *loc = NULL;
837     new->key = sstrdup(key);
838     new->value = sstrdup(value);
839     /* ensure that the correct variable is matched in case of one being
840      * the prefix of another */
841     SLIST_FOREACH(test, variables, variables) {
842         if (strlen(new->key) >= strlen(test->key))
843             break;
844         loc = test;
845     }
846
847     if (loc == NULL) {
848         SLIST_INSERT_HEAD(variables, new, variables);
849     } else {
850         SLIST_INSERT_AFTER(loc, new, variables);
851     }
852 }
853
854 static char *get_resource(char *name) {
855     if (conn == NULL) {
856         return NULL;
857     }
858
859     /* Load the resource database lazily. */
860     if (database == NULL) {
861         database = xcb_xrm_database_from_default(conn);
862
863         if (database == NULL) {
864             ELOG("Failed to open the resource database.\n");
865
866             /* Load an empty database so we don't keep trying to load the
867              * default database over and over again. */
868             database = xcb_xrm_database_from_string("");
869
870             return NULL;
871         }
872     }
873
874     char *resource;
875     xcb_xrm_resource_get_string(database, name, NULL, &resource);
876     return resource;
877 }
878
879 /*
880  * Parses the given file by first replacing the variables, then calling
881  * parse_config and possibly launching i3-nagbar.
882  *
883  */
884 bool parse_file(const char *f, bool use_nagbar) {
885     struct variables_head variables = SLIST_HEAD_INITIALIZER(&variables);
886     int fd;
887     struct stat stbuf;
888     char *buf;
889     FILE *fstr;
890     char buffer[4096], key[512], value[4096], *continuation = NULL;
891
892     if ((fd = open(f, O_RDONLY)) == -1)
893         die("Could not open configuration file: %s\n", strerror(errno));
894
895     if (fstat(fd, &stbuf) == -1)
896         die("Could not fstat file: %s\n", strerror(errno));
897
898     buf = scalloc(stbuf.st_size + 1, 1);
899
900     if ((fstr = fdopen(fd, "r")) == NULL)
901         die("Could not fdopen: %s\n", strerror(errno));
902
903     while (!feof(fstr)) {
904         if (!continuation)
905             continuation = buffer;
906         if (fgets(continuation, sizeof(buffer) - (continuation - buffer), fstr) == NULL) {
907             if (feof(fstr))
908                 break;
909             die("Could not read configuration file\n");
910         }
911         if (buffer[strlen(buffer) - 1] != '\n' && !feof(fstr)) {
912             ELOG("Your line continuation is too long, it exceeds %zd bytes\n", sizeof(buffer));
913         }
914
915         /* sscanf implicitly strips whitespace. */
916         const bool skip_line = (sscanf(buffer, "%511s %4095[^\n]", key, value) < 1 || strlen(key) < 3);
917         const bool comment = (key[0] == '#');
918         value[4095] = '\n';
919
920         continuation = strstr(buffer, "\\\n");
921         if (continuation) {
922             if (!comment) {
923                 continue;
924             }
925             DLOG("line continuation in comment is ignored: \"%.*s\"\n", (int)strlen(buffer) - 1, buffer);
926             continuation = NULL;
927         }
928
929         strncpy(buf + strlen(buf), buffer, strlen(buffer) + 1);
930
931         /* Skip comments and empty lines. */
932         if (skip_line || comment) {
933             continue;
934         }
935
936         if (strcasecmp(key, "set") == 0) {
937             char v_key[512];
938             char v_value[4096];
939
940             if (sscanf(value, "%511s %4095[^\n]", v_key, v_value) < 1) {
941                 ELOG("Failed to parse variable specification '%s', skipping it.\n", value);
942                 continue;
943             }
944
945             if (v_key[0] != '$') {
946                 ELOG("Malformed variable assignment, name has to start with $\n");
947                 continue;
948             }
949
950             upsert_variable(&variables, v_key, v_value);
951             continue;
952         } else if (strcasecmp(key, "set_from_resource") == 0) {
953             char res_name[512];
954             char v_key[512];
955             char fallback[4096];
956
957             if (sscanf(value, "%511s %511s %4095[^\n]", v_key, res_name, fallback) < 1) {
958                 ELOG("Failed to parse resource specification '%s', skipping it.\n", value);
959                 continue;
960             }
961
962             if (v_key[0] != '$') {
963                 ELOG("Malformed variable assignment, name has to start with $\n");
964                 continue;
965             }
966
967             char *res_value = get_resource(res_name);
968             if (res_value == NULL) {
969                 DLOG("Could not get resource '%s', using fallback '%s'.\n", res_name, fallback);
970                 res_value = sstrdup(fallback);
971             }
972
973             upsert_variable(&variables, v_key, res_value);
974             FREE(res_value);
975             continue;
976         }
977     }
978     fclose(fstr);
979
980     if (database != NULL) {
981         xcb_xrm_database_free(database);
982         /* Explicitly set the database to NULL again in case the config gets reloaded. */
983         database = NULL;
984     }
985
986     /* For every custom variable, see how often it occurs in the file and
987      * how much extra bytes it requires when replaced. */
988     struct Variable *current, *nearest;
989     int extra_bytes = 0;
990     /* We need to copy the buffer because we need to invalidate the
991      * variables (otherwise we will count them twice, which is bad when
992      * 'extra' is negative) */
993     char *bufcopy = sstrdup(buf);
994     SLIST_FOREACH(current, &variables, variables) {
995         int extra = (strlen(current->value) - strlen(current->key));
996         char *next;
997         for (next = bufcopy;
998              next < (bufcopy + stbuf.st_size) &&
999                  (next = strcasestr(next, current->key)) != NULL;
1000              next += strlen(current->key)) {
1001             *next = '_';
1002             extra_bytes += extra;
1003         }
1004     }
1005     FREE(bufcopy);
1006
1007     /* Then, allocate a new buffer and copy the file over to the new one,
1008      * but replace occurrences of our variables */
1009     char *walk = buf, *destwalk;
1010     char *new = smalloc(stbuf.st_size + extra_bytes + 1);
1011     destwalk = new;
1012     while (walk < (buf + stbuf.st_size)) {
1013         /* Find the next variable */
1014         SLIST_FOREACH(current, &variables, variables)
1015         current->next_match = strcasestr(walk, current->key);
1016         nearest = NULL;
1017         int distance = stbuf.st_size;
1018         SLIST_FOREACH(current, &variables, variables) {
1019             if (current->next_match == NULL)
1020                 continue;
1021             if ((current->next_match - walk) < distance) {
1022                 distance = (current->next_match - walk);
1023                 nearest = current;
1024             }
1025         }
1026         if (nearest == NULL) {
1027             /* If there are no more variables, we just copy the rest */
1028             strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
1029             destwalk += (buf + stbuf.st_size) - walk;
1030             *destwalk = '\0';
1031             break;
1032         } else {
1033             /* Copy until the next variable, then copy its value */
1034             strncpy(destwalk, walk, distance);
1035             strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
1036             walk += distance + strlen(nearest->key);
1037             destwalk += distance + strlen(nearest->value);
1038         }
1039     }
1040
1041     /* analyze the string to find out whether this is an old config file (3.x)
1042      * or a new config file (4.x). If it’s old, we run the converter script. */
1043     int version = detect_version(buf);
1044     if (version == 3) {
1045         /* We need to convert this v3 configuration */
1046         char *converted = migrate_config(new, stbuf.st_size);
1047         if (converted != NULL) {
1048             ELOG("\n");
1049             ELOG("****************************************************************\n");
1050             ELOG("NOTE: Automatically converted configuration file from v3 to v4.\n");
1051             ELOG("\n");
1052             ELOG("Please convert your config file to v4. You can use this command:\n");
1053             ELOG("    mv %s %s.O\n", f, f);
1054             ELOG("    i3-migrate-config-to-v4 %s.O > %s\n", f, f);
1055             ELOG("****************************************************************\n");
1056             ELOG("\n");
1057             free(new);
1058             new = converted;
1059         } else {
1060             LOG("\n");
1061             LOG("**********************************************************************\n");
1062             LOG("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
1063             LOG("was not correctly installed on your system?\n");
1064             LOG("**********************************************************************\n");
1065             LOG("\n");
1066         }
1067     }
1068
1069     context = scalloc(1, sizeof(struct context));
1070     context->filename = f;
1071
1072     struct ConfigResultIR *config_output = parse_config(new, context);
1073     yajl_gen_free(config_output->json_gen);
1074
1075     extract_workspace_names_from_bindings();
1076     check_for_duplicate_bindings(context);
1077     reorder_bindings();
1078
1079     if (use_nagbar && (context->has_errors || context->has_warnings)) {
1080         ELOG("FYI: You are using i3 version %s\n", i3_version);
1081         if (version == 3)
1082             ELOG("Please convert your configfile first, then fix any remaining errors (see above).\n");
1083
1084         start_config_error_nagbar(f, context->has_errors);
1085     }
1086
1087     bool has_errors = context->has_errors;
1088
1089     FREE(context->line_copy);
1090     free(context);
1091     free(new);
1092     free(buf);
1093
1094     while (!SLIST_EMPTY(&variables)) {
1095         current = SLIST_FIRST(&variables);
1096         FREE(current->key);
1097         FREE(current->value);
1098         SLIST_REMOVE_HEAD(&variables, variables);
1099         FREE(current);
1100     }
1101
1102     return !has_errors;
1103 }
1104
1105 #endif