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