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 
44 xcb_xrm_database_t *database = NULL;
45 
46 #ifndef TEST_PARSER
48 static 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 
61 typedef 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;
68  } extra;
69 } cmdp_token;
70 
71 typedef struct tokenptr {
72  cmdp_token *array;
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 
83 struct stack_entry {
84  /* Just a pointer, not dynamically allocated. */
85  const char *identifier;
86  enum {
87  STACK_STR = 0,
88  STACK_LONG = 1,
89  } type;
90  union {
91  char *str;
92  long num;
93  } val;
94 };
95 
96 /* 10 entries should be enough for everybody. */
97 static 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  */
104 static 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(1);
130 }
131 
132 static 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(1);
150 }
151 
152 static 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 
162 static 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 
172 static void clear_stack(void) {
173  for (int c = 0; c < 10; c++) {
174  if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
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 
186 static 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. */
196 static cmdp_state statelist[10] = {INITIAL};
197 /* NB: statelist_idx points to where the next entry will be inserted */
198 static int statelist_idx = 1;
199 
200 #include "GENERATED_config_call.h"
201 
202 static 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  */
237 static 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  */
251 static 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 
259 struct 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)
314  push_string(token->identifier, token->name + 1);
315  walk += strlen(token->name) - 1;
316  next_state(token);
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)
337  push_long(token->identifier, num);
338 
339  /* Set walk to the first non-number character */
340  walk = end;
341  next_state(token);
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)
385  push_string(token->identifier, str);
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++;
391  next_state(token);
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++;
400  next_state(token);
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') {
410  next_state(token);
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  */
579 void 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 
588 void errorlog(char *fmt, ...) {
589  va_list args;
590 
591  va_start(args, fmt);
592  vfprintf(stderr, fmt, args);
593  va_end(args);
594 }
595 
596 static int criteria_next_state;
597 
598 void cfg_criteria_init(I3_CFG, int _state) {
599  criteria_next_state = _state;
600 }
601 
602 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
603 }
604 
605 void cfg_criteria_pop_state(I3_CFG) {
606  result->next_state = criteria_next_state;
607 }
608 
609 int 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  */
627 static 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  */
696 static 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 = smalloc(conv_size);
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  return NULL;
768  }
769 
770  int returncode = WEXITSTATUS(status);
771  if (returncode != 0) {
772  fprintf(stderr, "Migration process exit code was != 0\n");
773  if (returncode == 2) {
774  fprintf(stderr, "could not start the migration script\n");
775  /* TODO: script was not found. tell the user to fix their system or create a v4 config */
776  } else if (returncode == 1) {
777  fprintf(stderr, "This already was a v4 config. Please add the following line to your config file:\n");
778  fprintf(stderr, "# i3 config file (v4)\n");
779  /* TODO: nag the user with a message to include a hint for i3 in their config file */
780  }
781  return NULL;
782  }
783 
784  return converted;
785 }
786 
790 void start_config_error_nagbar(const char *configpath, bool has_errors) {
791  char *editaction, *pageraction;
792  sasprintf(&editaction, "i3-sensible-editor \"%s\" && i3-msg reload\n", configpath);
793  sasprintf(&pageraction, "i3-sensible-pager \"%s\"\n", errorfilename);
794  char *argv[] = {
795  NULL, /* will be replaced by the executable path */
796  "-f",
797  (config.font.pattern ? config.font.pattern : "fixed"),
798  "-t",
799  (has_errors ? "error" : "warning"),
800  "-m",
801  (has_errors ? "You have an error in your i3 config file!" : "Your config is outdated. Please fix the warnings to make sure everything works."),
802  "-b",
803  "edit config",
804  editaction,
805  (errorfilename ? "-b" : NULL),
806  (has_errors ? "show errors" : "show warnings"),
807  pageraction,
808  NULL};
809 
811  free(editaction);
812  free(pageraction);
813 }
814 
815 /*
816  * Inserts or updates a variable assignment depending on whether it already exists.
817  *
818  */
819 static void upsert_variable(struct variables_head *variables, char *key, char *value) {
820  struct Variable *current;
821  SLIST_FOREACH(current, variables, variables) {
822  if (strcmp(current->key, key) != 0) {
823  continue;
824  }
825 
826  DLOG("Updated variable: %s = %s -> %s\n", key, current->value, value);
827  FREE(current->value);
828  current->value = sstrdup(value);
829  return;
830  }
831 
832  DLOG("Defined new variable: %s = %s\n", key, value);
833  struct Variable *new = scalloc(1, sizeof(struct Variable));
834  struct Variable *test = NULL, *loc = NULL;
835  new->key = sstrdup(key);
836  new->value = sstrdup(value);
837  /* ensure that the correct variable is matched in case of one being
838  * the prefix of another */
839  SLIST_FOREACH(test, variables, variables) {
840  if (strlen(new->key) >= strlen(test->key))
841  break;
842  loc = test;
843  }
844 
845  if (loc == NULL) {
846  SLIST_INSERT_HEAD(variables, new, variables);
847  } else {
848  SLIST_INSERT_AFTER(loc, new, variables);
849  }
850 }
851 
852 static char *get_resource(char *name) {
853  if (conn == NULL) {
854  return NULL;
855  }
856 
857  /* Load the resource database lazily. */
858  if (database == NULL) {
859  database = xcb_xrm_database_from_default(conn);
860 
861  if (database == NULL) {
862  ELOG("Failed to open the resource database.\n");
863 
864  /* Load an empty database so we don't keep trying to load the
865  * default database over and over again. */
866  database = xcb_xrm_database_from_string("");
867 
868  return NULL;
869  }
870  }
871 
872  char *resource;
873  xcb_xrm_resource_get_string(database, name, NULL, &resource);
874  return resource;
875 }
876 
877 /*
878  * Parses the given file by first replacing the variables, then calling
879  * parse_config and possibly launching i3-nagbar.
880  *
881  */
882 bool parse_file(const char *f, bool use_nagbar) {
883  struct variables_head variables = SLIST_HEAD_INITIALIZER(&variables);
884  int fd;
885  struct stat stbuf;
886  char *buf;
887  FILE *fstr;
888  char buffer[4096], key[512], value[4096], *continuation = NULL;
889 
890  if ((fd = open(f, O_RDONLY)) == -1)
891  die("Could not open configuration file: %s\n", strerror(errno));
892 
893  if (fstat(fd, &stbuf) == -1)
894  die("Could not fstat file: %s\n", strerror(errno));
895 
896  buf = scalloc(stbuf.st_size + 1, 1);
897 
898  if ((fstr = fdopen(fd, "r")) == NULL)
899  die("Could not fdopen: %s\n", strerror(errno));
900 
902  current_config = scalloc(stbuf.st_size + 1, 1);
903  fread(current_config, 1, stbuf.st_size, fstr);
904  rewind(fstr);
905 
906  bool invalid_sets = false;
907 
908  while (!feof(fstr)) {
909  if (!continuation)
910  continuation = buffer;
911  if (fgets(continuation, sizeof(buffer) - (continuation - buffer), fstr) == NULL) {
912  if (feof(fstr))
913  break;
914  die("Could not read configuration file\n");
915  }
916  if (buffer[strlen(buffer) - 1] != '\n' && !feof(fstr)) {
917  ELOG("Your line continuation is too long, it exceeds %zd bytes\n", sizeof(buffer));
918  }
919 
920  /* sscanf implicitly strips whitespace. */
921  value[0] = '\0';
922  const bool skip_line = (sscanf(buffer, "%511s %4095[^\n]", key, value) < 1 || strlen(key) < 3);
923  const bool comment = (key[0] == '#');
924  value[4095] = '\n';
925 
926  continuation = strstr(buffer, "\\\n");
927  if (continuation) {
928  if (!comment) {
929  continue;
930  }
931  DLOG("line continuation in comment is ignored: \"%.*s\"\n", (int)strlen(buffer) - 1, buffer);
932  continuation = NULL;
933  }
934 
935  strncpy(buf + strlen(buf), buffer, strlen(buffer) + 1);
936 
937  /* Skip comments and empty lines. */
938  if (skip_line || comment) {
939  continue;
940  }
941 
942  if (strcasecmp(key, "set") == 0 && *value != '\0') {
943  char v_key[512];
944  char v_value[4096] = {'\0'};
945 
946  if (sscanf(value, "%511s %4095[^\n]", v_key, v_value) < 1) {
947  ELOG("Failed to parse variable specification '%s', skipping it.\n", value);
948  invalid_sets = true;
949  continue;
950  }
951 
952  if (v_key[0] != '$') {
953  ELOG("Malformed variable assignment, name has to start with $\n");
954  invalid_sets = true;
955  continue;
956  }
957 
958  upsert_variable(&variables, v_key, v_value);
959  continue;
960  } else if (strcasecmp(key, "set_from_resource") == 0) {
961  char res_name[512] = {'\0'};
962  char v_key[512];
963  char fallback[4096] = {'\0'};
964 
965  /* Ensure that this string is terminated. For example, a user might
966  * want a variable to be empty if the resource can't be found and
967  * uses
968  * set_from_resource $foo i3wm.foo
969  * Without explicitly terminating the string first, sscanf() will
970  * leave it uninitialized, causing garbage in the config.*/
971  fallback[0] = '\0';
972 
973  if (sscanf(value, "%511s %511s %4095[^\n]", v_key, res_name, fallback) < 1) {
974  ELOG("Failed to parse resource specification '%s', skipping it.\n", value);
975  invalid_sets = true;
976  continue;
977  }
978 
979  if (v_key[0] != '$') {
980  ELOG("Malformed variable assignment, name has to start with $\n");
981  invalid_sets = true;
982  continue;
983  }
984 
985  char *res_value = get_resource(res_name);
986  if (res_value == NULL) {
987  DLOG("Could not get resource '%s', using fallback '%s'.\n", res_name, fallback);
988  res_value = sstrdup(fallback);
989  }
990 
991  upsert_variable(&variables, v_key, res_value);
992  FREE(res_value);
993  continue;
994  }
995  }
996  fclose(fstr);
997 
998  if (database != NULL) {
999  xcb_xrm_database_free(database);
1000  /* Explicitly set the database to NULL again in case the config gets reloaded. */
1001  database = NULL;
1002  }
1003 
1004  /* For every custom variable, see how often it occurs in the file and
1005  * how much extra bytes it requires when replaced. */
1006  struct Variable *current, *nearest;
1007  int extra_bytes = 0;
1008  /* We need to copy the buffer because we need to invalidate the
1009  * variables (otherwise we will count them twice, which is bad when
1010  * 'extra' is negative) */
1011  char *bufcopy = sstrdup(buf);
1012  SLIST_FOREACH(current, &variables, variables) {
1013  int extra = (strlen(current->value) - strlen(current->key));
1014  char *next;
1015  for (next = bufcopy;
1016  next < (bufcopy + stbuf.st_size) &&
1017  (next = strcasestr(next, current->key)) != NULL;
1018  next += strlen(current->key)) {
1019  *next = '_';
1020  extra_bytes += extra;
1021  }
1022  }
1023  FREE(bufcopy);
1024 
1025  /* Then, allocate a new buffer and copy the file over to the new one,
1026  * but replace occurrences of our variables */
1027  char *walk = buf, *destwalk;
1028  char *new = scalloc(stbuf.st_size + extra_bytes + 1, 1);
1029  destwalk = new;
1030  while (walk < (buf + stbuf.st_size)) {
1031  /* Find the next variable */
1032  SLIST_FOREACH(current, &variables, variables)
1033  current->next_match = strcasestr(walk, current->key);
1034  nearest = NULL;
1035  int distance = stbuf.st_size;
1036  SLIST_FOREACH(current, &variables, variables) {
1037  if (current->next_match == NULL)
1038  continue;
1039  if ((current->next_match - walk) < distance) {
1040  distance = (current->next_match - walk);
1041  nearest = current;
1042  }
1043  }
1044  if (nearest == NULL) {
1045  /* If there are no more variables, we just copy the rest */
1046  strncpy(destwalk, walk, (buf + stbuf.st_size) - walk);
1047  destwalk += (buf + stbuf.st_size) - walk;
1048  *destwalk = '\0';
1049  break;
1050  } else {
1051  /* Copy until the next variable, then copy its value */
1052  strncpy(destwalk, walk, distance);
1053  strncpy(destwalk + distance, nearest->value, strlen(nearest->value));
1054  walk += distance + strlen(nearest->key);
1055  destwalk += distance + strlen(nearest->value);
1056  }
1057  }
1058 
1059  /* analyze the string to find out whether this is an old config file (3.x)
1060  * or a new config file (4.x). If it’s old, we run the converter script. */
1061  int version = detect_version(buf);
1062  if (version == 3) {
1063  /* We need to convert this v3 configuration */
1064  char *converted = migrate_config(new, stbuf.st_size);
1065  if (converted != NULL) {
1066  ELOG("\n");
1067  ELOG("****************************************************************\n");
1068  ELOG("NOTE: Automatically converted configuration file from v3 to v4.\n");
1069  ELOG("\n");
1070  ELOG("Please convert your config file to v4. You can use this command:\n");
1071  ELOG(" mv %s %s.O\n", f, f);
1072  ELOG(" i3-migrate-config-to-v4 %s.O > %s\n", f, f);
1073  ELOG("****************************************************************\n");
1074  ELOG("\n");
1075  free(new);
1076  new = converted;
1077  } else {
1078  LOG("\n");
1079  LOG("**********************************************************************\n");
1080  LOG("ERROR: Could not convert config file. Maybe i3-migrate-config-to-v4\n");
1081  LOG("was not correctly installed on your system?\n");
1082  LOG("**********************************************************************\n");
1083  LOG("\n");
1084  }
1085  }
1086 
1087  context = scalloc(1, sizeof(struct context));
1088  context->filename = f;
1089 
1090  struct ConfigResultIR *config_output = parse_config(new, context);
1091  yajl_gen_free(config_output->json_gen);
1092 
1095  reorder_bindings();
1096 
1097  if (use_nagbar && (context->has_errors || context->has_warnings || invalid_sets)) {
1098  ELOG("FYI: You are using i3 version %s\n", i3_version);
1099  if (version == 3)
1100  ELOG("Please convert your configfile first, then fix any remaining errors (see above).\n");
1101 
1102  start_config_error_nagbar(f, context->has_errors || invalid_sets);
1103  }
1104 
1105  bool has_errors = context->has_errors;
1106 
1107  FREE(context->line_copy);
1108  free(context);
1109  free(new);
1110  free(buf);
1111 
1112  while (!SLIST_EMPTY(&variables)) {
1113  current = SLIST_FIRST(&variables);
1114  FREE(current->key);
1115  FREE(current->value);
1116  SLIST_REMOVE_HEAD(&variables, variables);
1117  FREE(current);
1118  }
1119 
1120  return !has_errors;
1121 }
1122 
1123 #endif
union stack_entry::@2 val
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...
static char * migrate_config(char *input, off_t size)
Holds a user-assigned variable for parsing the configuration file.
Definition: configuration.h:67
char * line_copy
Definition: configuration.h:39
static char * single_line(const char *start)
bool has_errors
Definition: configuration.h:35
static char * get_resource(char *name)
char * sstrdup(const char *str)
Safe-wrapper around strdup which exits if malloc returns NULL (meaning that there is no more memory a...
static int statelist_idx
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 ...
#define SLIST_INSERT_AFTER(slistelm, elm, field)
Definition: queue.h:132
#define ELOG(fmt,...)
Definition: libi3.h:99
static struct ConfigResultIR command_output
struct tokenptr cmdp_token_ptr
#define LOG(fmt,...)
Definition: libi3.h:94
static void upsert_variable(struct variables_head *variables, char *key, char *value)
#define SLIST_EMPTY(head)
Definition: queue.h:111
char * errorfilename
Definition: log.c:40
xcb_connection_t * conn
XCB connection and root screen.
Definition: main.c:46
static struct stack_entry stack[10]
Definition: config_parser.c:97
char * next_match
Definition: configuration.h:70
char * current_config
Definition: config.c:16
char * value
Definition: configuration.h:69
static int detect_version(char *buf)
const char * i3_version
Git commit identifier, from version.c.
Definition: version.c:13
const char * identifier
static long get_long(const char *identifier)
static Match current_match
void debuglog(char *fmt,...)
Definition: log.c:339
#define FREE(pointer)
Definition: util.h:50
static int criteria_next_state
enum stack_entry::@1 type
char * name
static cmdp_state statelist[10]
void reorder_bindings(void)
Reorders bindings by event_state_mask descendingly so that get_binding() correctly matches more speci...
Definition: bindings.c:718
static const char * get_string(const char *identifier)
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:735
char * identifier
void errorlog(char *fmt,...)
Definition: log.c:319
void start_config_error_nagbar(const char *configpath, bool has_errors)
Launch nagbar to indicate errors in the configuration file.
char * pattern
The pattern/name used to load the font.
Definition: libi3.h:70
static struct ConfigResultIR subcommand_output
const char * filename
Definition: configuration.h:40
void * smalloc(size_t size)
Safe-wrapper around malloc which exits if malloc returns NULL (meaning that there is no more memory a...
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...
struct ConfigResultIR * parse_config(const char *input, struct context *context)
static cmdp_state state
#define I3_CFG
The beginning of the prototype for every cfg_ function.
#define SLIST_INSERT_HEAD(head, elm, field)
Definition: queue.h:138
void * srealloc(void *ptr, size_t size)
Safe-wrapper around realloc which exits if realloc returns NULL (meaning that there is no more memory...
char * key
Definition: configuration.h:68
int main(int argc, char *argv[])
Definition: main.c:192
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:142
static const char * start_of_line(const char *walk, const char *beginning)
cmdp_token * array
static void push_string(const char *identifier, const char *str)
struct token cmdp_token
#define die(...)
Definition: util.h:19
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 void clear_stack(void)
#define DLOG(fmt,...)
Definition: libi3.h:104
#define SLIST_FOREACH(var, head, field)
Definition: queue.h:114
void extract_workspace_names_from_bindings(void)
Extracts workspace names from keybindings (e.g.
Definition: workspace.c:119
#define y(x,...)
Definition: config_parser.c:41
static void push_long(const char *identifier, long num)
A "match" is a data structure which acts like a mask or expression to match certain windows or not...
Definition: data.h:483
Used during the config file lexing/parsing to keep the state of the lexer in order to provide useful ...
Definition: configuration.h:34
yajl_gen json_gen
Definition: config_parser.h:27
#define SLIST_FIRST(head)
Definition: queue.h:109
#define SLIST_HEAD_INITIALIZER(head)
Definition: queue.h:98
#define ystr(str)
Definition: config_parser.c:42
Config config
Definition: config.c:17
bool has_warnings
Definition: configuration.h:36
xcb_xrm_database_t * database
Definition: config_parser.c:44
#define SLIST_REMOVE_HEAD(head, field)
Definition: queue.h:149
i3Font font
Definition: configuration.h:98
uint16_t call_identifier
static struct context * context
Definition: config_parser.c:48
void start_nagbar(pid_t *nagbar_pid, char *argv[])
Starts an i3-nagbar instance with the given parameters.
Definition: util.c:405
pid_t config_error_nagbar_pid
Definition: config_parser.c:47
union token::@0 extra
cmdp_state next_state