]> git.sur5r.net Git - i3/i3/blob - i3bar/src/child.c
fix travis build by switching away from deprecated-2017Q3 (#3650)
[i3/i3] / i3bar / src / child.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3bar - an xcb-based status- and ws-bar for i3
5  * © 2010 Axel Wagner and contributors (see also: LICENSE)
6  *
7  * child.c: Getting input for the statusline
8  *
9  */
10 #include "common.h"
11 #include "yajl_utils.h"
12
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <sys/types.h>
16 #include <sys/wait.h>
17 #include <signal.h>
18 #include <stdio.h>
19 #include <stdarg.h>
20 #include <fcntl.h>
21 #include <string.h>
22 #include <errno.h>
23 #include <err.h>
24 #include <ev.h>
25 #include <yajl/yajl_common.h>
26 #include <yajl/yajl_parse.h>
27 #include <yajl/yajl_version.h>
28 #include <yajl/yajl_gen.h>
29 #include <paths.h>
30
31 #include <xcb/xcb_keysyms.h>
32
33 /* Global variables for child_*() */
34 i3bar_child child;
35
36 /* stdin- and SIGCHLD-watchers */
37 ev_io *stdin_io;
38 int stdin_fd;
39 ev_child *child_sig;
40
41 /* JSON parser for stdin */
42 yajl_handle parser;
43
44 /* JSON generator for stdout */
45 yajl_gen gen;
46
47 typedef struct parser_ctx {
48     /* True if one of the parsed blocks was urgent */
49     bool has_urgent;
50
51     /* A copy of the last JSON map key. */
52     char *last_map_key;
53
54     /* The current block. Will be filled, then copied and put into the list of
55      * blocks. */
56     struct status_block block;
57 } parser_ctx;
58
59 parser_ctx parser_context;
60
61 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
62 /* Used temporarily while reading a statusline */
63 struct statusline_head statusline_buffer = TAILQ_HEAD_INITIALIZER(statusline_buffer);
64
65 int child_stdin;
66
67 /*
68  * Remove all blocks from the given statusline.
69  * If free_resources is set, the fields of each status block will be free'd.
70  */
71 static void clear_statusline(struct statusline_head *head, bool free_resources) {
72     struct status_block *first;
73     while (!TAILQ_EMPTY(head)) {
74         first = TAILQ_FIRST(head);
75         if (free_resources) {
76             I3STRING_FREE(first->full_text);
77             I3STRING_FREE(first->short_text);
78             FREE(first->color);
79             FREE(first->name);
80             FREE(first->instance);
81             FREE(first->min_width_str);
82             FREE(first->background);
83             FREE(first->border);
84         }
85
86         TAILQ_REMOVE(head, first, blocks);
87         free(first);
88     }
89 }
90
91 static void copy_statusline(struct statusline_head *from, struct statusline_head *to) {
92     struct status_block *current;
93     TAILQ_FOREACH(current, from, blocks) {
94         struct status_block *new_block = smalloc(sizeof(struct status_block));
95         memcpy(new_block, current, sizeof(struct status_block));
96         TAILQ_INSERT_TAIL(to, new_block, blocks);
97     }
98 }
99
100 /*
101  * Replaces the statusline in memory with an error message. Pass a format
102  * string and format parameters as you would in `printf'. The next time
103  * `draw_bars' is called, the error message text will be drawn on the bar in
104  * the space allocated for the statusline.
105  */
106 __attribute__((format(printf, 1, 2))) static void set_statusline_error(const char *format, ...) {
107     clear_statusline(&statusline_head, true);
108
109     char *message;
110     va_list args;
111     va_start(args, format);
112     if (vasprintf(&message, format, args) == -1) {
113         goto finish;
114     }
115
116     struct status_block *err_block = scalloc(1, sizeof(struct status_block));
117     err_block->full_text = i3string_from_utf8("Error: ");
118     err_block->name = sstrdup("error");
119     err_block->color = sstrdup("#ff0000");
120     err_block->no_separator = true;
121
122     struct status_block *message_block = scalloc(1, sizeof(struct status_block));
123     message_block->full_text = i3string_from_utf8(message);
124     message_block->name = sstrdup("error_message");
125     message_block->color = sstrdup("#ff0000");
126     message_block->no_separator = true;
127
128     TAILQ_INSERT_HEAD(&statusline_head, err_block, blocks);
129     TAILQ_INSERT_TAIL(&statusline_head, message_block, blocks);
130
131 finish:
132     FREE(message);
133     va_end(args);
134 }
135
136 /*
137  * Stop and free() the stdin- and SIGCHLD-watchers
138  *
139  */
140 static void cleanup(void) {
141     if (stdin_io != NULL) {
142         ev_io_stop(main_loop, stdin_io);
143         FREE(stdin_io);
144     }
145
146     if (child_sig != NULL) {
147         ev_child_stop(main_loop, child_sig);
148         FREE(child_sig);
149     }
150
151     memset(&child, 0, sizeof(i3bar_child));
152 }
153
154 /*
155  * The start of a new array is the start of a new status line, so we clear all
156  * previous entries from the buffer.
157  */
158 static int stdin_start_array(void *context) {
159     // the blocks are still used by statusline_head, so we won't free the
160     // resources here.
161     clear_statusline(&statusline_buffer, false);
162     return 1;
163 }
164
165 /*
166  * The start of a map is the start of a single block of the status line.
167  *
168  */
169 static int stdin_start_map(void *context) {
170     parser_ctx *ctx = context;
171     memset(&(ctx->block), '\0', sizeof(struct status_block));
172
173     /* Default width of the separator block. */
174     if (config.separator_symbol == NULL)
175         ctx->block.sep_block_width = logical_px(9);
176     else
177         ctx->block.sep_block_width = logical_px(8) + separator_symbol_width;
178
179     return 1;
180 }
181
182 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
183     parser_ctx *ctx = context;
184     FREE(ctx->last_map_key);
185     sasprintf(&(ctx->last_map_key), "%.*s", len, key);
186     return 1;
187 }
188
189 static int stdin_boolean(void *context, int val) {
190     parser_ctx *ctx = context;
191     if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
192         ctx->block.urgent = val;
193         return 1;
194     }
195     if (strcasecmp(ctx->last_map_key, "separator") == 0) {
196         ctx->block.no_separator = !val;
197         return 1;
198     }
199
200     return 1;
201 }
202
203 static int stdin_string(void *context, const unsigned char *val, size_t len) {
204     parser_ctx *ctx = context;
205     if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
206         ctx->block.full_text = i3string_from_markup_with_length((const char *)val, len);
207         return 1;
208     }
209     if (strcasecmp(ctx->last_map_key, "short_text") == 0) {
210         ctx->block.short_text = i3string_from_markup_with_length((const char *)val, len);
211         return 1;
212     }
213     if (strcasecmp(ctx->last_map_key, "color") == 0) {
214         sasprintf(&(ctx->block.color), "%.*s", len, val);
215         return 1;
216     }
217     if (strcasecmp(ctx->last_map_key, "background") == 0) {
218         sasprintf(&(ctx->block.background), "%.*s", len, val);
219         return 1;
220     }
221     if (strcasecmp(ctx->last_map_key, "border") == 0) {
222         sasprintf(&(ctx->block.border), "%.*s", len, val);
223         return 1;
224     }
225     if (strcasecmp(ctx->last_map_key, "markup") == 0) {
226         ctx->block.pango_markup = (len == strlen("pango") && !strncasecmp((const char *)val, "pango", strlen("pango")));
227         return 1;
228     }
229     if (strcasecmp(ctx->last_map_key, "align") == 0) {
230         if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
231             ctx->block.align = ALIGN_CENTER;
232         } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
233             ctx->block.align = ALIGN_RIGHT;
234         } else {
235             ctx->block.align = ALIGN_LEFT;
236         }
237         return 1;
238     }
239     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
240         sasprintf(&(ctx->block.min_width_str), "%.*s", len, val);
241         return 1;
242     }
243     if (strcasecmp(ctx->last_map_key, "name") == 0) {
244         sasprintf(&(ctx->block.name), "%.*s", len, val);
245         return 1;
246     }
247     if (strcasecmp(ctx->last_map_key, "instance") == 0) {
248         sasprintf(&(ctx->block.instance), "%.*s", len, val);
249         return 1;
250     }
251
252     return 1;
253 }
254
255 static int stdin_integer(void *context, long long val) {
256     parser_ctx *ctx = context;
257     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
258         ctx->block.min_width = (uint32_t)val;
259         return 1;
260     }
261     if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
262         ctx->block.sep_block_width = (uint32_t)val;
263         return 1;
264     }
265
266     return 1;
267 }
268
269 /*
270  * When a map is finished, we have an entire status block.
271  * Move it from the parser's context to the statusline buffer.
272  */
273 static int stdin_end_map(void *context) {
274     parser_ctx *ctx = context;
275     struct status_block *new_block = smalloc(sizeof(struct status_block));
276     memcpy(new_block, &(ctx->block), sizeof(struct status_block));
277     /* Ensure we have a full_text set, so that when it is missing (or null),
278      * i3bar doesn’t crash and the user gets an annoying message. */
279     if (!new_block->full_text)
280         new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
281     if (new_block->urgent)
282         ctx->has_urgent = true;
283
284     if (new_block->min_width_str) {
285         i3String *text = i3string_from_utf8(new_block->min_width_str);
286         i3string_set_markup(text, new_block->pango_markup);
287         new_block->min_width = (uint32_t)predict_text_width(text);
288         i3string_free(text);
289     }
290
291     i3string_set_markup(new_block->full_text, new_block->pango_markup);
292
293     if (new_block->short_text != NULL)
294         i3string_set_markup(new_block->short_text, new_block->pango_markup);
295
296     TAILQ_INSERT_TAIL(&statusline_buffer, new_block, blocks);
297     return 1;
298 }
299
300 /*
301  * When an array is finished, we have an entire statusline.
302  * Copy it from the buffer to the actual statusline.
303  */
304 static int stdin_end_array(void *context) {
305     DLOG("copying statusline_buffer to statusline_head\n");
306     clear_statusline(&statusline_head, true);
307     copy_statusline(&statusline_buffer, &statusline_head);
308
309     DLOG("dumping statusline:\n");
310     struct status_block *current;
311     TAILQ_FOREACH(current, &statusline_head, blocks) {
312         DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
313         DLOG("short_text = %s\n", (current->short_text == NULL ? NULL : i3string_as_utf8(current->short_text)));
314         DLOG("color = %s\n", current->color);
315     }
316     DLOG("end of dump\n");
317     return 1;
318 }
319
320 /*
321  * Helper function to read stdin
322  *
323  * Returns NULL on EOF.
324  *
325  */
326 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
327     int fd = watcher->fd;
328     int n = 0;
329     int rec = 0;
330     int buffer_len = STDIN_CHUNK_SIZE;
331     unsigned char *buffer = smalloc(buffer_len + 1);
332     buffer[0] = '\0';
333     while (1) {
334         n = read(fd, buffer + rec, buffer_len - rec);
335         if (n == -1) {
336             if (errno == EAGAIN) {
337                 /* finish up */
338                 break;
339             }
340             ELOG("read() failed!: %s\n", strerror(errno));
341             FREE(buffer);
342             exit(EXIT_FAILURE);
343         }
344         if (n == 0) {
345             ELOG("stdin: received EOF\n");
346             FREE(buffer);
347             *ret_buffer_len = -1;
348             return NULL;
349         }
350         rec += n;
351
352         if (rec == buffer_len) {
353             buffer_len += STDIN_CHUNK_SIZE;
354             buffer = srealloc(buffer, buffer_len);
355         }
356     }
357     if (*buffer == '\0') {
358         FREE(buffer);
359         rec = -1;
360     }
361     *ret_buffer_len = rec;
362     return buffer;
363 }
364
365 static void read_flat_input(char *buffer, int length) {
366     struct status_block *first = TAILQ_FIRST(&statusline_head);
367     /* Clear the old buffer if any. */
368     I3STRING_FREE(first->full_text);
369     /* Remove the trailing newline and terminate the string at the same
370      * time. */
371     if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r') {
372         buffer[length - 1] = '\0';
373     } else {
374         buffer[length] = '\0';
375     }
376
377     first->full_text = i3string_from_utf8(buffer);
378 }
379
380 static bool read_json_input(unsigned char *input, int length) {
381     yajl_status status = yajl_parse(parser, input, length);
382     bool has_urgent = false;
383     if (status != yajl_status_ok) {
384         char *message = (char *)yajl_get_error(parser, 0, input, length);
385
386         /* strip the newline yajl adds to the error message */
387         if (message[strlen(message) - 1] == '\n')
388             message[strlen(message) - 1] = '\0';
389
390         fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
391                 status, message, length, input);
392
393         set_statusline_error("Could not parse JSON (%s)", message);
394         yajl_free_error(parser, (unsigned char *)message);
395         draw_bars(false);
396     } else if (parser_context.has_urgent) {
397         has_urgent = true;
398     }
399     return has_urgent;
400 }
401
402 /*
403  * Callbalk for stdin. We read a line from stdin and store the result
404  * in statusline
405  *
406  */
407 static void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
408     int rec;
409     unsigned char *buffer = get_buffer(watcher, &rec);
410     if (buffer == NULL)
411         return;
412     bool has_urgent = false;
413     if (child.version > 0) {
414         has_urgent = read_json_input(buffer, rec);
415     } else {
416         read_flat_input((char *)buffer, rec);
417     }
418     free(buffer);
419     draw_bars(has_urgent);
420 }
421
422 /*
423  * Callbalk for stdin first line. We read the first line to detect
424  * whether this is JSON or plain text
425  *
426  */
427 static void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
428     int rec;
429     unsigned char *buffer = get_buffer(watcher, &rec);
430     if (buffer == NULL)
431         return;
432     DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
433     /* Detect whether this is JSON or plain text. */
434     unsigned int consumed = 0;
435     /* At the moment, we don’t care for the version. This might change
436      * in the future, but for now, we just discard it. */
437     parse_json_header(&child, buffer, rec, &consumed);
438     if (child.version > 0) {
439         /* If hide-on-modifier is set, we start of by sending the
440          * child a SIGSTOP, because the bars aren't mapped at start */
441         if (config.hide_on_modifier) {
442             stop_child();
443         }
444         draw_bars(read_json_input(buffer + consumed, rec - consumed));
445     } else {
446         /* In case of plaintext, we just add a single block and change its
447          * full_text pointer later. */
448         struct status_block *new_block = scalloc(1, sizeof(struct status_block));
449         TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
450         read_flat_input((char *)buffer, rec);
451     }
452     free(buffer);
453     ev_io_stop(main_loop, stdin_io);
454     ev_io_init(stdin_io, &stdin_io_cb, stdin_fd, EV_READ);
455     ev_io_start(main_loop, stdin_io);
456 }
457
458 /*
459  * We received a SIGCHLD, meaning, that the child process terminated.
460  * We simply free the respective data structures and don't care for input
461  * anymore
462  *
463  */
464 static void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
465     int exit_status = WEXITSTATUS(watcher->rstatus);
466
467     ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
468          child.pid,
469          exit_status);
470
471     /* this error is most likely caused by a user giving a nonexecutable or
472      * nonexistent file, so we will handle those cases separately. */
473     if (exit_status == 126)
474         set_statusline_error("status_command is not executable (exit %d)", exit_status);
475     else if (exit_status == 127)
476         set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
477     else
478         set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
479
480     cleanup();
481     draw_bars(false);
482 }
483
484 static void child_write_output(void) {
485     if (child.click_events) {
486         const unsigned char *output;
487         size_t size;
488         ssize_t n;
489
490         yajl_gen_get_buf(gen, &output, &size);
491
492         n = writeall(child_stdin, output, size);
493         if (n != -1)
494             n = writeall(child_stdin, "\n", 1);
495
496         yajl_gen_clear(gen);
497
498         if (n == -1) {
499             child.click_events = false;
500             kill_child();
501             set_statusline_error("child_write_output failed");
502             draw_bars(false);
503         }
504     }
505 }
506
507 /*
508  * Start a child process with the specified command and reroute stdin.
509  * We actually start a $SHELL to execute the command so we don't have to care
510  * about arguments and such.
511  *
512  * If `command' is NULL, such as in the case when no `status_command' is given
513  * in the bar config, no child will be started.
514  *
515  */
516 void start_child(char *command) {
517     if (command == NULL)
518         return;
519
520     /* Allocate a yajl parser which will be used to parse stdin. */
521     static yajl_callbacks callbacks = {
522         .yajl_boolean = stdin_boolean,
523         .yajl_integer = stdin_integer,
524         .yajl_string = stdin_string,
525         .yajl_start_map = stdin_start_map,
526         .yajl_map_key = stdin_map_key,
527         .yajl_end_map = stdin_end_map,
528         .yajl_start_array = stdin_start_array,
529         .yajl_end_array = stdin_end_array,
530     };
531     parser = yajl_alloc(&callbacks, NULL, &parser_context);
532
533     gen = yajl_gen_alloc(NULL);
534
535     int pipe_in[2];  /* pipe we read from */
536     int pipe_out[2]; /* pipe we write to */
537
538     if (pipe(pipe_in) == -1)
539         err(EXIT_FAILURE, "pipe(pipe_in)");
540     if (pipe(pipe_out) == -1)
541         err(EXIT_FAILURE, "pipe(pipe_out)");
542
543     child.pid = fork();
544     switch (child.pid) {
545         case -1:
546             ELOG("Couldn't fork(): %s\n", strerror(errno));
547             exit(EXIT_FAILURE);
548         case 0:
549             /* Child-process. Reroute streams and start shell */
550
551             close(pipe_in[0]);
552             close(pipe_out[1]);
553
554             dup2(pipe_in[1], STDOUT_FILENO);
555             dup2(pipe_out[0], STDIN_FILENO);
556
557             setpgid(child.pid, 0);
558             execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
559             return;
560         default:
561             /* Parent-process. Reroute streams */
562
563             close(pipe_in[1]);
564             close(pipe_out[0]);
565
566             stdin_fd = pipe_in[0];
567             child_stdin = pipe_out[1];
568
569             break;
570     }
571
572     /* We set O_NONBLOCK because blocking is evil in event-driven software */
573     fcntl(stdin_fd, F_SETFL, O_NONBLOCK);
574
575     stdin_io = smalloc(sizeof(ev_io));
576     ev_io_init(stdin_io, &stdin_io_first_line_cb, stdin_fd, EV_READ);
577     ev_io_start(main_loop, stdin_io);
578
579     /* We must cleanup, if the child unexpectedly terminates */
580     child_sig = smalloc(sizeof(ev_child));
581     ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
582     ev_child_start(main_loop, child_sig);
583
584     atexit(kill_child_at_exit);
585 }
586
587 static void child_click_events_initialize(void) {
588     if (!child.click_events_init) {
589         yajl_gen_array_open(gen);
590         child_write_output();
591         child.click_events_init = true;
592     }
593 }
594
595 /*
596  * Generates a click event, if enabled.
597  *
598  */
599 void send_block_clicked(int button, const char *name, const char *instance, int x, int y, int x_rel, int y_rel, int width, int height, int mods) {
600     if (!child.click_events) {
601         return;
602     }
603
604     child_click_events_initialize();
605
606     yajl_gen_map_open(gen);
607
608     if (name) {
609         ystr("name");
610         ystr(name);
611     }
612
613     if (instance) {
614         ystr("instance");
615         ystr(instance);
616     }
617
618     ystr("button");
619     yajl_gen_integer(gen, button);
620
621     ystr("modifiers");
622     yajl_gen_array_open(gen);
623     if (mods & XCB_MOD_MASK_SHIFT)
624         ystr("Shift");
625     if (mods & XCB_MOD_MASK_CONTROL)
626         ystr("Control");
627     if (mods & XCB_MOD_MASK_1)
628         ystr("Mod1");
629     if (mods & XCB_MOD_MASK_2)
630         ystr("Mod2");
631     if (mods & XCB_MOD_MASK_3)
632         ystr("Mod3");
633     if (mods & XCB_MOD_MASK_4)
634         ystr("Mod4");
635     if (mods & XCB_MOD_MASK_5)
636         ystr("Mod5");
637     yajl_gen_array_close(gen);
638
639     ystr("x");
640     yajl_gen_integer(gen, x);
641
642     ystr("y");
643     yajl_gen_integer(gen, y);
644
645     ystr("relative_x");
646     yajl_gen_integer(gen, x_rel);
647
648     ystr("relative_y");
649     yajl_gen_integer(gen, y_rel);
650
651     ystr("width");
652     yajl_gen_integer(gen, width);
653
654     ystr("height");
655     yajl_gen_integer(gen, height);
656
657     yajl_gen_map_close(gen);
658     child_write_output();
659 }
660
661 /*
662  * kill()s the child process (if any). Called when exit()ing.
663  *
664  */
665 void kill_child_at_exit(void) {
666     if (child.pid > 0) {
667         if (child.cont_signal > 0 && child.stopped)
668             killpg(child.pid, child.cont_signal);
669         killpg(child.pid, SIGTERM);
670     }
671 }
672
673 /*
674  * kill()s the child process (if existent) and closes and
675  * free()s the stdin- and SIGCHLD-watchers
676  *
677  */
678 void kill_child(void) {
679     if (child.pid > 0) {
680         if (child.cont_signal > 0 && child.stopped)
681             killpg(child.pid, child.cont_signal);
682         killpg(child.pid, SIGTERM);
683         int status;
684         waitpid(child.pid, &status, 0);
685         cleanup();
686     }
687 }
688
689 /*
690  * Sends a SIGSTOP to the child process (if existent)
691  *
692  */
693 void stop_child(void) {
694     if (child.stop_signal > 0 && !child.stopped) {
695         child.stopped = true;
696         killpg(child.pid, child.stop_signal);
697     }
698 }
699
700 /*
701  * Sends a SIGCONT to the child process (if existent)
702  *
703  */
704 void cont_child(void) {
705     if (child.cont_signal > 0 && child.stopped) {
706         child.stopped = false;
707         killpg(child.pid, child.cont_signal);
708     }
709 }
710
711 /*
712  * Whether or not the child want click events
713  *
714  */
715 bool child_want_click_events(void) {
716     return child.click_events;
717 }