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