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