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