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