]> git.sur5r.net Git - i3/i3/blob - src/config_parser.c
b81aa3c3752078b21a2001add1b76cd5ce6d597f
[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 #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 static pid_t configerror_pid = -1;
47 /* The path to the temporary script files used by i3-nagbar. We need to keep
48  * them around to delete the files in the i3-nagbar SIGCHLD handler. */
49 static char *edit_script_path, *pager_script_path;
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: commands_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: commands_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
155 static const char *get_string(const char *identifier) {
156     for (int c = 0; c < 10; c++) {
157         if (stack[c].identifier == NULL)
158             break;
159         if (strcmp(identifier, stack[c].identifier) == 0)
160             return stack[c].val.str;
161     }
162     return NULL;
163 }
164
165 static const long get_long(const char *identifier) {
166     for (int c = 0; c < 10; c++) {
167         if (stack[c].identifier == NULL)
168             break;
169         if (strcmp(identifier, stack[c].identifier) == 0)
170             return stack[c].val.num;
171     }
172     return 0;
173 }
174
175 static void clear_stack(void) {
176     for (int c = 0; c < 10; c++) {
177         if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
178             free(stack[c].val.str);
179         stack[c].identifier = NULL;
180         stack[c].val.str = NULL;
181         stack[c].val.num = 0;
182     }
183 }
184
185 // TODO: remove this if it turns out we don’t need it for testing.
186 #if 0
187 /*******************************************************************************
188  * A dynamically growing linked list which holds the criteria for the current
189  * command.
190  ******************************************************************************/
191
192 typedef struct criterion {
193     char *type;
194     char *value;
195
196     TAILQ_ENTRY(criterion) criteria;
197 } criterion;
198
199 static TAILQ_HEAD(criteria_head, criterion) criteria =
200   TAILQ_HEAD_INITIALIZER(criteria);
201
202 /*
203  * Stores the given type/value in the list of criteria.
204  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
205  *
206  */
207 static void push_criterion(void *unused_criteria, const char *type,
208                            const char *value) {
209     struct criterion *criterion = malloc(sizeof(struct criterion));
210     criterion->type = strdup(type);
211     criterion->value = strdup(value);
212     TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
213 }
214
215 /*
216  * Clears the criteria linked list.
217  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
218  *
219  */
220 static void clear_criteria(void *unused_criteria) {
221     struct criterion *criterion;
222     while (!TAILQ_EMPTY(&criteria)) {
223         criterion = TAILQ_FIRST(&criteria);
224         free(criterion->type);
225         free(criterion->value);
226         TAILQ_REMOVE(&criteria, criterion, criteria);
227         free(criterion);
228     }
229 }
230 #endif
231
232 /*******************************************************************************
233  * The parser itself.
234  ******************************************************************************/
235
236 static cmdp_state state;
237 static Match current_match;
238 static struct ConfigResult subcommand_output;
239 static struct ConfigResult command_output;
240
241 /* A list which contains the states that lead to the current state, e.g.
242  * INITIAL, WORKSPACE_LAYOUT.
243  * When jumping back to INITIAL, statelist_idx will simply be set to 1
244  * (likewise for other states, e.g. MODE or BAR).
245  * This list is used to process the nearest error token. */
246 static cmdp_state statelist[10] = { INITIAL };
247 /* NB: statelist_idx points to where the next entry will be inserted */
248 static int statelist_idx = 1;
249
250 #include "GENERATED_config_call.h"
251
252
253 static void next_state(const cmdp_token *token) {
254     cmdp_state _next_state = token->next_state;
255
256         //printf("token = name %s identifier %s\n", token->name, token->identifier);
257         //printf("next_state = %d\n", token->next_state);
258     if (token->next_state == __CALL) {
259         subcommand_output.json_gen = command_output.json_gen;
260         GENERATED_call(token->extra.call_identifier, &subcommand_output);
261         _next_state = subcommand_output.next_state;
262         clear_stack();
263     }
264
265     state = _next_state;
266     if (state == INITIAL) {
267         clear_stack();
268     }
269
270     /* See if we are jumping back to a state in which we were in previously
271      * (statelist contains INITIAL) and just move statelist_idx accordingly. */
272     for (int i = 0; i < statelist_idx; i++) {
273         if (statelist[i] != _next_state)
274             continue;
275         statelist_idx = i+1;
276         return;
277     }
278
279     /* Otherwise, the state is new and we add it to the list */
280     statelist[statelist_idx++] = _next_state;
281 }
282
283 /*
284  * Returns a pointer to the start of the line (one byte after the previous \r,
285  * \n) or the start of the input, if this is the first line.
286  *
287  */
288 static const char *start_of_line(const char *walk, const char *beginning) {
289     while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
290         walk--;
291     }
292
293     return walk + 1;
294 }
295
296 /*
297  * Copies the line and terminates it at the next \n, if any.
298  *
299  * The caller has to free() the result.
300  *
301  */
302 static char *single_line(const char *start) {
303     char *result = sstrdup(start);
304     char *end = strchr(result, '\n');
305     if (end != NULL)
306         *end = '\0';
307     return result;
308 }
309
310 struct ConfigResult *parse_config(const char *input, struct context *context) {
311     /* Dump the entire config file into the debug log. We cannot just use
312      * DLOG("%s", input); because one log message must not exceed 4 KiB. */
313     const char *dumpwalk = input;
314     int linecnt = 1;
315     while (*dumpwalk != '\0') {
316         char *next_nl = strchr(dumpwalk, '\n');
317         if (next_nl != NULL) {
318             DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
319             dumpwalk = next_nl + 1;
320         } else {
321             DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
322             break;
323         }
324         linecnt++;
325     }
326     state = INITIAL;
327     statelist_idx = 1;
328
329 /* A YAJL JSON generator used for formatting replies. */
330 #if YAJL_MAJOR >= 2
331     command_output.json_gen = yajl_gen_alloc(NULL);
332 #else
333     command_output.json_gen = yajl_gen_alloc(NULL, NULL);
334 #endif
335
336     y(array_open);
337
338     const char *walk = input;
339     const size_t len = strlen(input);
340     int c;
341     const cmdp_token *token;
342     bool token_handled;
343     linecnt = 1;
344
345     // TODO: make this testable
346 #ifndef TEST_PARSER
347     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
348 #endif
349
350     /* The "<=" operator is intentional: We also handle the terminating 0-byte
351      * explicitly by looking for an 'end' token. */
352     while ((walk - input) <= len) {
353         /* Skip whitespace before every token, newlines are relevant since they
354          * separate configuration directives. */
355         while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
356             walk++;
357
358                 //printf("remaining input: %s\n", walk);
359
360         cmdp_token_ptr *ptr = &(tokens[state]);
361         token_handled = false;
362         for (c = 0; c < ptr->n; c++) {
363             token = &(ptr->array[c]);
364
365             /* A literal. */
366             if (token->name[0] == '\'') {
367                 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
368                     if (token->identifier != NULL)
369                         push_string(token->identifier, token->name + 1);
370                     walk += strlen(token->name) - 1;
371                     next_state(token);
372                     token_handled = true;
373                     break;
374                 }
375                 continue;
376             }
377
378             if (strcmp(token->name, "number") == 0) {
379                 /* Handle numbers. We only accept decimal numbers for now. */
380                 char *end = NULL;
381                 errno = 0;
382                 long int num = strtol(walk, &end, 10);
383                 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
384                     (errno != 0 && num == 0))
385                     continue;
386
387                 /* No valid numbers found */
388                 if (end == walk)
389                     continue;
390
391                 if (token->identifier != NULL)
392                     push_long(token->identifier, num);
393
394                 /* Set walk to the first non-number character */
395                 walk = end;
396                 next_state(token);
397                 token_handled = true;
398                 break;
399             }
400
401             if (strcmp(token->name, "string") == 0 ||
402                 strcmp(token->name, "word") == 0) {
403                 const char *beginning = walk;
404                 /* Handle quoted strings (or words). */
405                 if (*walk == '"') {
406                     beginning++;
407                     walk++;
408                     while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
409                         walk++;
410                 } else {
411                     if (token->name[0] == 's') {
412                         while (*walk != '\0' && *walk != '\r' && *walk != '\n')
413                             walk++;
414                     } else {
415                         /* For a word, the delimiters are white space (' ' or
416                          * '\t'), closing square bracket (]), comma (,) and
417                          * semicolon (;). */
418                         while (*walk != ' ' && *walk != '\t' &&
419                                *walk != ']' && *walk != ',' &&
420                                *walk !=  ';' && *walk != '\r' &&
421                                *walk != '\n' && *walk != '\0')
422                             walk++;
423                     }
424                 }
425                 if (walk != beginning) {
426                     char *str = scalloc(walk-beginning + 1);
427                     /* We copy manually to handle escaping of characters. */
428                     int inpos, outpos;
429                     for (inpos = 0, outpos = 0;
430                          inpos < (walk-beginning);
431                          inpos++, outpos++) {
432                         /* We only handle escaped double quotes to not break
433                          * backwards compatibility with people using \w in
434                          * regular expressions etc. */
435                         if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
436                             inpos++;
437                         str[outpos] = beginning[inpos];
438                     }
439                     if (token->identifier)
440                         push_string(token->identifier, str);
441                     free(str);
442                     /* If we are at the end of a quoted string, skip the ending
443                      * double quote. */
444                     if (*walk == '"')
445                         walk++;
446                     next_state(token);
447                     token_handled = true;
448                     break;
449                 }
450             }
451
452             if (strcmp(token->name, "end") == 0) {
453                 //printf("checking for end: *%s*\n", walk);
454                 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
455                     next_state(token);
456                     token_handled = true;
457                     /* To make sure we start with an appropriate matching
458                      * datastructure for commands which do *not* specify any
459                      * criteria, we re-initialize the criteria system after
460                      * every command. */
461                     // TODO: make this testable
462 #ifndef TEST_PARSER
463                     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
464 #endif
465                     linecnt++;
466                     walk++;
467                     break;
468                }
469            }
470         }
471
472         if (!token_handled) {
473             /* Figure out how much memory we will need to fill in the names of
474              * all tokens afterwards. */
475             int tokenlen = 0;
476             for (c = 0; c < ptr->n; c++)
477                 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
478
479             /* Build up a decent error message. We include the problem, the
480              * full input, and underline the position where the parser
481              * currently is. */
482             char *errormessage;
483             char *possible_tokens = smalloc(tokenlen + 1);
484             char *tokenwalk = possible_tokens;
485             for (c = 0; c < ptr->n; c++) {
486                 token = &(ptr->array[c]);
487                 if (token->name[0] == '\'') {
488                     /* A literal is copied to the error message enclosed with
489                      * single quotes. */
490                     *tokenwalk++ = '\'';
491                     strcpy(tokenwalk, token->name + 1);
492                     tokenwalk += strlen(token->name + 1);
493                     *tokenwalk++ = '\'';
494                 } else {
495                     /* Skip error tokens in error messages, they are used
496                      * internally only and might confuse users. */
497                     if (strcmp(token->name, "error") == 0)
498                         continue;
499                     /* Any other token is copied to the error message enclosed
500                      * with angle brackets. */
501                     *tokenwalk++ = '<';
502                     strcpy(tokenwalk, token->name);
503                     tokenwalk += strlen(token->name);
504                     *tokenwalk++ = '>';
505                 }
506                 if (c < (ptr->n - 1)) {
507                     *tokenwalk++ = ',';
508                     *tokenwalk++ = ' ';
509                 }
510             }
511             *tokenwalk = '\0';
512             sasprintf(&errormessage, "Expected one of these tokens: %s",
513                       possible_tokens);
514             free(possible_tokens);
515
516
517             /* Go back to the beginning of the line */
518             const char *error_line = start_of_line(walk, input);
519
520             /* Contains the same amount of characters as 'input' has, but with
521              * the unparseable part highlighted using ^ characters. */
522             char *position = scalloc(strlen(error_line) + 1);
523             const char *copywalk;
524             for (copywalk = error_line;
525                  *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
526                  copywalk++)
527                 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
528             position[(copywalk - error_line)] = '\0';
529
530             ELOG("CONFIG: %s\n", errormessage);
531             ELOG("CONFIG: (in file %s)\n", context->filename);
532             char *error_copy = single_line(error_line);
533
534             /* Print context lines *before* the error, if any. */
535             if (linecnt > 1) {
536                 const char *context_p1_start = start_of_line(error_line-2, input);
537                 char *context_p1_line = single_line(context_p1_start);
538                 if (linecnt > 2) {
539                     const char *context_p2_start = start_of_line(context_p1_start-2, input);
540                     char *context_p2_line = single_line(context_p2_start);
541                     ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
542                     free(context_p2_line);
543                 }
544                 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
545                 free(context_p1_line);
546             }
547             ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
548             ELOG("CONFIG:           %s\n", position);
549             free(error_copy);
550             /* Print context lines *after* the error, if any. */
551             for (int i = 0; i < 2; i++) {
552                 char *error_line_end = strchr(error_line, '\n');
553                 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
554                     error_line = error_line_end + 1;
555                     error_copy = single_line(error_line);
556                     ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
557                     free(error_copy);
558                 }
559             }
560
561             context->has_errors = true;
562
563             /* Format this error message as a JSON reply. */
564             y(map_open);
565             ystr("success");
566             y(bool, false);
567             /* We set parse_error to true to distinguish this from other
568              * errors. i3-nagbar is spawned upon keypresses only for parser
569              * errors. */
570             ystr("parse_error");
571             y(bool, true);
572             ystr("error");
573             ystr(errormessage);
574             ystr("input");
575             ystr(input);
576             ystr("errorposition");
577             ystr(position);
578             y(map_close);
579
580             /* Skip the rest of this line, but continue parsing. */
581             while ((walk - input) <= len && *walk != '\n')
582                 walk++;
583
584             free(position);
585             free(errormessage);
586             clear_stack();
587
588             /* To figure out in which state to go (e.g. MODE or INITIAL),
589              * we find the nearest state which contains an <error> token
590              * and follow that one. */
591             bool error_token_found = false;
592             for (int i = statelist_idx-1; (i >= 0) && !error_token_found; i--) {
593                 cmdp_token_ptr *errptr = &(tokens[statelist[i]]);
594                 for (int j = 0; j < errptr->n; j++) {
595                     if (strcmp(errptr->array[j].name, "error") != 0)
596                         continue;
597                     next_state(&(errptr->array[j]));
598                     error_token_found = true;
599                     break;
600                 }
601             }
602
603             assert(error_token_found);
604         }
605     }
606
607     y(array_close);
608
609     return &command_output;
610 }
611
612 /*******************************************************************************
613  * Code for building the stand-alone binary test.commands_parser which is used
614  * by t/187-commands-parser.t.
615  ******************************************************************************/
616
617 #ifdef TEST_PARSER
618
619 /*
620  * Logs the given message to stdout while prefixing the current time to it,
621  * but only if debug logging was activated.
622  * This is to be called by DLOG() which includes filename/linenumber
623  *
624  */
625 void debuglog(char *fmt, ...) {
626     va_list args;
627
628     va_start(args, fmt);
629     fprintf(stdout, "# ");
630     vfprintf(stdout, fmt, args);
631     va_end(args);
632 }
633
634 void errorlog(char *fmt, ...) {
635     va_list args;
636
637     va_start(args, fmt);
638     vfprintf(stderr, fmt, args);
639     va_end(args);
640 }
641
642 static int criteria_next_state;
643
644 void cfg_criteria_init(I3_CFG, int _state) {
645     criteria_next_state = _state;
646 }
647
648 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
649 }
650
651 void cfg_criteria_pop_state(I3_CFG) {
652     result->next_state = criteria_next_state;
653 }
654
655 int main(int argc, char *argv[]) {
656     if (argc < 2) {
657         fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
658         return 1;
659     }
660     struct context context;
661     context.filename = "<stdin>";
662     parse_config(argv[1], &context);
663 }
664
665 #else
666
667 /*
668  * Writes the given command as a shell script to path.
669  * Returns true unless something went wrong.
670  *
671  */
672 static bool write_nagbar_script(const char *path, const char *command) {
673     int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
674     if (fd == -1) {
675         warn("Could not create temporary script to store the nagbar command");
676         return false;
677     }
678     write(fd, "#!/bin/sh\n", strlen("#!/bin/sh\n"));
679     write(fd, command, strlen(command));
680     close(fd);
681     return true;
682 }
683
684 /*
685  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
686  * it exited (or could not be started, depending on the exit code).
687  *
688  */
689 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
690     ev_child_stop(EV_A_ watcher);
691
692     if (unlink(edit_script_path) != 0)
693         warn("Could not delete temporary i3-nagbar script %s", edit_script_path);
694     if (unlink(pager_script_path) != 0)
695         warn("Could not delete temporary i3-nagbar script %s", pager_script_path);
696
697     if (!WIFEXITED(watcher->rstatus)) {
698         fprintf(stderr, "ERROR: i3-nagbar did not exit normally.\n");
699         return;
700     }
701
702     int exitcode = WEXITSTATUS(watcher->rstatus);
703     printf("i3-nagbar process exited with status %d\n", exitcode);
704     if (exitcode == 2) {
705         fprintf(stderr, "ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
706     }
707
708     configerror_pid = -1;
709 }
710
711 /* We need ev >= 4 for the following code. Since it is not *that* important (it
712  * only makes sure that there are no i3-nagbar instances left behind) we still
713  * support old systems with libev 3. */
714 #if EV_VERSION_MAJOR >= 4
715 /*
716  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
717  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
718  *
719  */
720 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
721     if (configerror_pid != -1) {
722         LOG("Sending SIGKILL (9) to i3-nagbar with PID %d\n", configerror_pid);
723         kill(configerror_pid, SIGKILL);
724     }
725 }
726 #endif
727
728 /*
729  * Kills the configerror i3-nagbar process, if any.
730  *
731  * Called when reloading/restarting.
732  *
733  * If wait_for_it is set (restarting), this function will waitpid(), otherwise,
734  * ev is assumed to handle it (reloading).
735  *
736  */
737 void kill_configerror_nagbar(bool wait_for_it) {
738     if (configerror_pid == -1)
739         return;
740
741     if (kill(configerror_pid, SIGTERM) == -1)
742         warn("kill(configerror_nagbar) failed");
743
744     if (!wait_for_it)
745         return;
746
747     /* When restarting, we don’t enter the ev main loop anymore and after the
748      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
749      * for us and we would end up with a <defunct> process. Therefore we
750      * waitpid() here. */
751     waitpid(configerror_pid, NULL, 0);
752 }
753
754 /*
755  * Goes through each line of buf (separated by \n) and checks for statements /
756  * commands which only occur in i3 v4 configuration files. If it finds any, it
757  * returns version 4, otherwise it returns version 3.
758  *
759  */
760 static int detect_version(char *buf) {
761     char *walk = buf;
762     char *line = buf;
763     while (*walk != '\0') {
764         if (*walk != '\n') {
765             walk++;
766             continue;
767         }
768
769         /* check for some v4-only statements */
770         if (strncasecmp(line, "bindcode", strlen("bindcode")) == 0 ||
771             strncasecmp(line, "force_focus_wrapping", strlen("force_focus_wrapping")) == 0 ||
772             strncasecmp(line, "# i3 config file (v4)", strlen("# i3 config file (v4)")) == 0 ||
773             strncasecmp(line, "workspace_layout", strlen("workspace_layout")) == 0) {
774             printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
775             return 4;
776         }
777
778         /* if this is a bind statement, we can check the command */
779         if (strncasecmp(line, "bind", strlen("bind")) == 0) {
780             char *bind = strchr(line, ' ');
781             if (bind == NULL)
782                 goto next;
783             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
784                 bind++;
785             if (*bind == '\0')
786                 goto next;
787             if ((bind = strchr(bind, ' ')) == NULL)
788                 goto next;
789             while ((*bind == ' ' || *bind == '\t') && *bind != '\0')
790                 bind++;
791             if (*bind == '\0')
792                 goto next;
793             if (strncasecmp(bind, "layout", strlen("layout")) == 0 ||
794                 strncasecmp(bind, "floating", strlen("floating")) == 0 ||
795                 strncasecmp(bind, "workspace", strlen("workspace")) == 0 ||
796                 strncasecmp(bind, "focus left", strlen("focus left")) == 0 ||
797                 strncasecmp(bind, "focus right", strlen("focus right")) == 0 ||
798                 strncasecmp(bind, "focus up", strlen("focus up")) == 0 ||
799                 strncasecmp(bind, "focus down", strlen("focus down")) == 0 ||
800                 strncasecmp(bind, "border normal", strlen("border normal")) == 0 ||
801                 strncasecmp(bind, "border 1pixel", strlen("border 1pixel")) == 0 ||
802                 strncasecmp(bind, "border pixel", strlen("border pixel")) == 0 ||
803                 strncasecmp(bind, "border borderless", strlen("border borderless")) == 0 ||
804                 strncasecmp(bind, "--no-startup-id", strlen("--no-startup-id")) == 0 ||
805                 strncasecmp(bind, "bar", strlen("bar")) == 0) {
806                 printf("deciding for version 4 due to this line: %.*s\n", (int)(walk-line), line);
807                 return 4;
808             }
809         }
810
811 next:
812         /* advance to the next line */
813         walk++;
814         line = walk;
815     }
816
817     return 3;
818 }
819
820 /*
821  * Calls i3-migrate-config-to-v4 to migrate a configuration file (input
822  * buffer).
823  *
824  * Returns the converted config file or NULL if there was an error (for
825  * example the script could not be found in $PATH or the i3 executable’s
826  * directory).
827  *
828  */
829 static char *migrate_config(char *input, off_t size) {
830     int writepipe[2];
831     int readpipe[2];
832
833     if (pipe(writepipe) != 0 ||
834         pipe(readpipe) != 0) {
835         warn("migrate_config: Could not create pipes");
836         return NULL;
837     }
838
839     pid_t pid = fork();
840     if (pid == -1) {
841         warn("Could not fork()");
842         return NULL;
843     }
844
845     /* child */
846     if (pid == 0) {
847         /* close writing end of writepipe, connect reading side to stdin */
848         close(writepipe[1]);
849         dup2(writepipe[0], 0);
850
851         /* close reading end of readpipe, connect writing side to stdout */
852         close(readpipe[0]);
853         dup2(readpipe[1], 1);
854
855         static char *argv[] = {
856             NULL, /* will be replaced by the executable path */
857             NULL
858         };
859         exec_i3_utility("i3-migrate-config-to-v4", argv);
860     }
861
862     /* parent */
863
864     /* close reading end of the writepipe (connected to the script’s stdin) */
865     close(writepipe[0]);
866
867     /* write the whole config file to the pipe, the script will read everything
868      * immediately */
869     int written = 0;
870     int ret;
871     while (written < size) {
872         if ((ret = write(writepipe[1], input + written, size - written)) < 0) {
873             warn("Could not write to pipe");
874             return NULL;
875         }
876         written += ret;
877     }
878     close(writepipe[1]);
879
880     /* close writing end of the readpipe (connected to the script’s stdout) */
881     close(readpipe[1]);
882
883     /* read the script’s output */
884     int conv_size = 65535;
885     char *converted = malloc(conv_size);
886     int read_bytes = 0;
887     do {
888         if (read_bytes == conv_size) {
889             conv_size += 65535;
890             converted = realloc(converted, conv_size);
891         }
892         ret = read(readpipe[0], converted + read_bytes, conv_size - read_bytes);
893         if (ret == -1) {
894             warn("Cannot read from pipe");
895             FREE(converted);
896             return NULL;
897         }
898         read_bytes += ret;
899     } while (ret > 0);
900
901     /* get the returncode */
902     int status;
903     wait(&status);
904     if (!WIFEXITED(status)) {
905         fprintf(stderr, "Child did not terminate normally, using old config file (will lead to broken behaviour)\n");
906         return NULL;
907     }
908
909     int returncode = WEXITSTATUS(status);
910     if (returncode != 0) {
911         fprintf(stderr, "Migration process exit code was != 0\n");
912         if (returncode == 2) {
913             fprintf(stderr, "could not start the migration script\n");
914             /* TODO: script was not found. tell the user to fix his system or create a v4 config */
915         } else if (returncode == 1) {
916             fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
917             fprintf(stderr, "# i3 config file (v4)\n");
918             /* TODO: nag the user with a message to include a hint for i3 in his config file */
919         }
920         return NULL;
921     }
922
923     return converted;
924 }
925
926 /*
927  * Checks for duplicate key bindings (the same keycode or keysym is configured
928  * more than once). If a duplicate binding is found, a message is printed to
929  * stderr and the has_errors variable is set to true, which will start
930  * i3-nagbar.
931  *
932  */
933 static void check_for_duplicate_bindings(struct context *context) {
934     Binding *bind, *current;
935     TAILQ_FOREACH(current, bindings, bindings) {
936         TAILQ_FOREACH(bind, bindings, bindings) {
937             /* Abort when we reach the current keybinding, only check the
938              * bindings before */
939             if (bind == current)
940                 break;
941
942             /* Check if one is using keysym while the other is using bindsym.
943              * If so, skip. */
944             /* XXX: It should be checked at a later place (when translating the
945              * keysym to keycodes) if there are any duplicates */
946             if ((bind->symbol == NULL && current->symbol != NULL) ||
947                 (bind->symbol != NULL && current->symbol == NULL))
948                 continue;
949
950             /* If bind is NULL, current has to be NULL, too (see above).
951              * If the keycodes differ, it can't be a duplicate. */
952             if (bind->symbol != NULL &&
953                 strcasecmp(bind->symbol, current->symbol) != 0)
954                 continue;
955
956             /* Check if the keycodes or modifiers are different. If so, they
957              * can't be duplicate */
958             if (bind->keycode != current->keycode ||
959                 bind->mods != current->mods ||
960                 bind->release != current->release)
961                 continue;
962
963             context->has_errors = true;
964             if (current->keycode != 0) {
965                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keycode %d, command \"%s\"\n",
966                      current->mods, current->keycode, current->command);
967             } else {
968                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keysym %s, command \"%s\"\n",
969                      current->mods, current->symbol, current->command);
970             }
971         }
972     }
973 }
974
975 /*
976  * Starts an i3-nagbar process which alerts the user that his configuration
977  * file contains one or more errors. Also offers two buttons: One to launch an
978  * $EDITOR on the config file and another one to launch a $PAGER on the error
979  * logfile.
980  *
981  */
982 static void start_configerror_nagbar(const char *config_path) {
983     if (only_check_config)
984         return;
985
986     fprintf(stderr, "Starting i3-nagbar due to configuration errors\n");
987
988     /* We need to create a custom script containing our actual command
989      * since not every terminal emulator which is contained in
990      * i3-sensible-terminal supports -e with multiple arguments (and not
991      * all of them support -e with one quoted argument either).
992      *
993      * NB: The paths need to be unique, that is, don’t assume users close
994      * their nagbars at any point in time (and they still need to work).
995      * */
996     edit_script_path = get_process_filename("nagbar-cfgerror-edit");
997     pager_script_path = get_process_filename("nagbar-cfgerror-pager");
998
999     configerror_pid = fork();
1000     if (configerror_pid == -1) {
1001         warn("Could not fork()");
1002         return;
1003     }
1004
1005     /* child */
1006     if (configerror_pid == 0) {
1007         char *edit_command, *pager_command;
1008         sasprintf(&edit_command, "i3-sensible-editor \"%s\" && i3-msg reload\n", config_path);
1009         sasprintf(&pager_command, "i3-sensible-pager \"%s\"\n", errorfilename);
1010         if (!write_nagbar_script(edit_script_path, edit_command) ||
1011             !write_nagbar_script(pager_script_path, pager_command))
1012             return;
1013
1014         char *editaction,
1015              *pageraction;
1016         sasprintf(&editaction, "i3-sensible-terminal -e \"%s\"", edit_script_path);
1017         sasprintf(&pageraction, "i3-sensible-terminal -e \"%s\"", pager_script_path);
1018         char *argv[] = {
1019             NULL, /* will be replaced by the executable path */
1020             "-t",
1021             (context->has_errors ? "error" : "warning"),
1022             "-m",
1023             (context->has_errors ?
1024              "You have an error in your i3 config file!" :
1025              "Your config is outdated. Please fix the warnings to make sure everything works."),
1026             "-b",
1027             "edit config",
1028             editaction,
1029             (errorfilename ? "-b" : NULL),
1030             (context->has_errors ? "show errors" : "show warnings"),
1031             pageraction,
1032             NULL
1033         };
1034         exec_i3_utility("i3-nagbar", argv);
1035     }
1036
1037     /* parent */
1038     /* install a child watcher */
1039     ev_child *child = smalloc(sizeof(ev_child));
1040     ev_child_init(child, &nagbar_exited, configerror_pid, 0);
1041     ev_child_start(main_loop, child);
1042
1043 /* We need ev >= 4 for the following code. Since it is not *that* important (it
1044  * only makes sure that there are no i3-nagbar instances left behind) we still
1045  * support old systems with libev 3. */
1046 #if EV_VERSION_MAJOR >= 4
1047     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
1048      * still running) */
1049     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
1050     ev_cleanup_init(cleanup, nagbar_cleanup);
1051     ev_cleanup_start(main_loop, cleanup);
1052 #endif
1053 }
1054
1055 /*
1056  * Parses the given file by first replacing the variables, then calling
1057  * parse_config and possibly launching i3-nagbar.
1058  *
1059  */
1060 void parse_file(const char *f) {
1061     SLIST_HEAD(variables_head, Variable) variables = SLIST_HEAD_INITIALIZER(&variables);
1062     int fd, ret, read_bytes = 0;
1063     struct stat stbuf;
1064     char *buf;
1065     FILE *fstr;
1066     char buffer[1026], key[512], value[512];
1067
1068     if ((fd = open(f, O_RDONLY)) == -1)
1069         die("Could not open configuration file: %s\n", strerror(errno));
1070
1071     if (fstat(fd, &stbuf) == -1)
1072         die("Could not fstat file: %s\n", strerror(errno));
1073
1074     buf = scalloc((stbuf.st_size + 1) * sizeof(char));
1075     while (read_bytes < stbuf.st_size) {
1076         if ((ret = read(fd, buf + read_bytes, (stbuf.st_size - read_bytes))) < 0)
1077             die("Could not read(): %s\n", strerror(errno));
1078         read_bytes += ret;
1079     }
1080
1081     if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
1082         die("Could not lseek: %s\n", strerror(errno));
1083
1084     if ((fstr = fdopen(fd, "r")) == NULL)
1085         die("Could not fdopen: %s\n", strerror(errno));
1086
1087     while (!feof(fstr)) {
1088         if (fgets(buffer, 1024, fstr) == NULL) {
1089             if (feof(fstr))
1090                 break;
1091             die("Could not read configuration file\n");
1092         }
1093
1094         /* sscanf implicitly strips whitespace. Also, we skip comments and empty lines. */
1095         if (sscanf(buffer, "%s %[^\n]", key, value) < 1 ||
1096             key[0] == '#' || strlen(key) < 3)
1097             continue;
1098
1099         if (strcasecmp(key, "set") == 0) {
1100             if (value[0] != '$') {
1101                 ELOG("Malformed variable assignment, name has to start with $\n");
1102                 continue;
1103             }
1104
1105             /* get key/value for this variable */
1106             char *v_key = value, *v_value;
1107             if (strstr(value, " ") == NULL && strstr(value, "\t") == NULL) {
1108                 ELOG("Malformed variable assignment, need a value\n");
1109                 continue;
1110             }
1111
1112             if (!(v_value = strstr(value, " ")))
1113                 v_value = strstr(value, "\t");
1114
1115             *(v_value++) = '\0';
1116             while (*v_value == '\t' || *v_value == ' ')
1117                 v_value++;
1118
1119             struct Variable *new = scalloc(sizeof(struct Variable));
1120             new->key = sstrdup(v_key);
1121             new->value = sstrdup(v_value);
1122             SLIST_INSERT_HEAD(&variables, new, variables);
1123             DLOG("Got new variable %s = %s\n", v_key, v_value);
1124             continue;
1125         }
1126     }
1127     fclose(fstr);
1128
1129     /* For every custom variable, see how often it occurs in the file and
1130      * how much extra bytes it requires when replaced. */
1131     struct Variable *current, *nearest;
1132     int extra_bytes = 0;
1133     /* We need to copy the buffer because we need to invalidate the
1134      * variables (otherwise we will count them twice, which is bad when
1135      * 'extra' is negative) */
1136     char *bufcopy = sstrdup(buf);
1137     SLIST_FOREACH(current, &variables, variables) {
1138         int extra = (strlen(current->value) - strlen(current->key));
1139         char *next;
1140         for (next = bufcopy;
1141              next < (bufcopy + stbuf.st_size) &&
1142              (next = strcasestr(next, current->key)) != NULL;
1143              next += strlen(current->key)) {
1144             *next = '_';
1145             extra_bytes += extra;
1146         }
1147     }
1148     FREE(bufcopy);
1149
1150     /* Then, allocate a new buffer and copy the file over to the new one,
1151      * but replace occurences of our variables */
1152     char *walk = buf, *destwalk;
1153     char *new = smalloc((stbuf.st_size + extra_bytes + 1) * sizeof(char));
1154     destwalk = new;
1155     while (walk < (buf + stbuf.st_size)) {
1156         /* Find the next variable */
1157         SLIST_FOREACH(current, &variables, variables)
1158             current->next_match = strcasestr(walk, current->key);
1159         nearest = NULL;
1160         int distance = stbuf.st_size;
1161         SLIST_FOREACH(current, &variables, variables) {
1162             if (current->next_match == NULL)
1163                 continue;
1164             if ((current->next_match - walk) < distance) {
1165                 distance = (current->next_match - walk);
1166                 nearest = current;
1167             }
1168         }
1169         if (nearest == NULL) {
1170             /* If there are no more variables, we just copy the rest */
1171             strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
1172             destwalk += (buf + stbuf.st_size) - walk;
1173             *destwalk = '\0';
1174             break;
1175         } else {
1176             /* Copy until the next variable, then copy its value */
1177             strncpy(destwalk, walk, distance);
1178             strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
1179             walk += distance + strlen(nearest->key);
1180             destwalk += distance + strlen(nearest->value);
1181         }
1182     }
1183
1184     /* analyze the string to find out whether this is an old config file (3.x)
1185      * or a new config file (4.x). If it’s old, we run the converter script. */
1186     int version = detect_version(buf);
1187     if (version == 3) {
1188         /* We need to convert this v3 configuration */
1189         char *converted = migrate_config(new, stbuf.st_size);
1190         if (converted != NULL) {
1191             ELOG("\n");
1192             ELOG("****************************************************************\n");
1193             ELOG("NOTE: Automatically converted configuration file from v3 to v4.\n");
1194             ELOG("\n");
1195             ELOG("Please convert your config file to v4. You can use this command:\n");
1196             ELOG("    mv %s %s.O\n", f, f);
1197             ELOG("    i3-migrate-config-to-v4 %s.O > %s\n", f, f);
1198             ELOG("****************************************************************\n");
1199             ELOG("\n");
1200             free(new);
1201             new = converted;
1202         } else {
1203             printf("\n");
1204             printf("**********************************************************************\n");
1205             printf("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
1206             printf("was not correctly installed on your system?\n");
1207             printf("**********************************************************************\n");
1208             printf("\n");
1209         }
1210     }
1211
1212
1213     context = scalloc(sizeof(struct context));
1214     context->filename = f;
1215
1216     struct ConfigResult *config_output = parse_config(new, context);
1217     yajl_gen_free(config_output->json_gen);
1218
1219     check_for_duplicate_bindings(context);
1220
1221     if (context->has_errors || context->has_warnings) {
1222         ELOG("FYI: You are using i3 version " I3_VERSION "\n");
1223         if (version == 3)
1224             ELOG("Please convert your configfile first, then fix any remaining errors (see above).\n");
1225         start_configerror_nagbar(f);
1226     }
1227
1228     FREE(context->line_copy);
1229     free(context);
1230     free(new);
1231     free(buf);
1232
1233     while (!SLIST_EMPTY(&variables)) {
1234         current = SLIST_FIRST(&variables);
1235         FREE(current->key);
1236         FREE(current->value);
1237         SLIST_REMOVE_HEAD(&variables, variables);
1238         FREE(current);
1239     }
1240 }
1241
1242 #endif