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