]> git.sur5r.net Git - i3/i3/blob - i3bar/src/child.c
Merge pull request #1575 from hwangcc23/next
[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-2012 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(sizeof(struct status_block));
109     err_block->full_text = i3string_from_utf8("Error: ");
110     err_block->name = "error";
111     err_block->color = "red";
112     err_block->no_separator = true;
113
114     struct status_block *message_block = scalloc(sizeof(struct status_block));
115     message_block->full_text = i3string_from_utf8(message);
116     message_block->name = "error_message";
117     message_block->color = "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     ctx->block.sep_block_width = logical_px(9);
166
167     return 1;
168 }
169
170 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
171     parser_ctx *ctx = context;
172     FREE(ctx->last_map_key);
173     sasprintf(&(ctx->last_map_key), "%.*s", len, key);
174     return 1;
175 }
176
177 static int stdin_boolean(void *context, int val) {
178     parser_ctx *ctx = context;
179     if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
180         ctx->block.urgent = val;
181         return 1;
182     }
183     if (strcasecmp(ctx->last_map_key, "separator") == 0) {
184         ctx->block.no_separator = !val;
185         return 1;
186     }
187
188     return 1;
189 }
190
191 static int stdin_string(void *context, const unsigned char *val, size_t len) {
192     parser_ctx *ctx = context;
193     if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
194         ctx->block.full_text = i3string_from_markup_with_length((const char *)val, len);
195         return 1;
196     }
197     if (strcasecmp(ctx->last_map_key, "short_text") == 0) {
198         ctx->block.short_text = i3string_from_markup_with_length((const char *)val, len);
199         return 1;
200     }
201     if (strcasecmp(ctx->last_map_key, "color") == 0) {
202         sasprintf(&(ctx->block.color), "%.*s", len, val);
203         return 1;
204     }
205     if (strcasecmp(ctx->last_map_key, "markup") == 0) {
206         ctx->block.is_markup = (len == strlen("pango") && !strncasecmp((const char *)val, "pango", strlen("pango")));
207         return 1;
208     }
209     if (strcasecmp(ctx->last_map_key, "align") == 0) {
210         if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
211             ctx->block.align = ALIGN_CENTER;
212         } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
213             ctx->block.align = ALIGN_RIGHT;
214         } else {
215             ctx->block.align = ALIGN_LEFT;
216         }
217         return 1;
218     }
219     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
220         char *copy = (char *)malloc(len + 1);
221         strncpy(copy, (const char *)val, len);
222         copy[len] = 0;
223         ctx->block.min_width_str = copy;
224         return 1;
225     }
226     if (strcasecmp(ctx->last_map_key, "name") == 0) {
227         char *copy = (char *)malloc(len + 1);
228         strncpy(copy, (const char *)val, len);
229         copy[len] = 0;
230         ctx->block.name = copy;
231         return 1;
232     }
233     if (strcasecmp(ctx->last_map_key, "instance") == 0) {
234         char *copy = (char *)malloc(len + 1);
235         strncpy(copy, (const char *)val, len);
236         copy[len] = 0;
237         ctx->block.instance = copy;
238         return 1;
239     }
240
241     return 1;
242 }
243
244 static int stdin_integer(void *context, long long val) {
245     parser_ctx *ctx = context;
246     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
247         ctx->block.min_width = (uint32_t)val;
248         return 1;
249     }
250     if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
251         ctx->block.sep_block_width = (uint32_t)val;
252         return 1;
253     }
254
255     return 1;
256 }
257
258 /*
259  * When a map is finished, we have an entire status block.
260  * Move it from the parser's context to the statusline buffer.
261  */
262 static int stdin_end_map(void *context) {
263     parser_ctx *ctx = context;
264     struct status_block *new_block = smalloc(sizeof(struct status_block));
265     memcpy(new_block, &(ctx->block), sizeof(struct status_block));
266     /* Ensure we have a full_text set, so that when it is missing (or null),
267      * i3bar doesn’t crash and the user gets an annoying message. */
268     if (!new_block->full_text)
269         new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
270     if (new_block->urgent)
271         ctx->has_urgent = true;
272
273     if (new_block->min_width_str) {
274         i3String *text = i3string_from_utf8(new_block->min_width_str);
275         i3string_set_markup(text, new_block->is_markup);
276         new_block->min_width = (uint32_t)predict_text_width(text);
277         i3string_free(text);
278     }
279
280     i3string_set_markup(new_block->full_text, new_block->is_markup);
281
282     if (new_block->short_text != NULL)
283         i3string_set_markup(new_block->short_text, new_block->is_markup);
284
285     TAILQ_INSERT_TAIL(&statusline_buffer, new_block, blocks);
286     return 1;
287 }
288
289 /*
290  * When an array is finished, we have an entire statusline.
291  * Copy it from the buffer to the actual statusline.
292  */
293 static int stdin_end_array(void *context) {
294     DLOG("copying statusline_buffer to statusline_head\n");
295     clear_statusline(&statusline_head, true);
296     copy_statusline(&statusline_buffer, &statusline_head);
297
298     DLOG("dumping statusline:\n");
299     struct status_block *current;
300     TAILQ_FOREACH(current, &statusline_head, blocks) {
301         DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
302         DLOG("short_text = %s\n", (current->short_text == NULL ? NULL : i3string_as_utf8(current->short_text)));
303         DLOG("color = %s\n", current->color);
304     }
305     DLOG("end of dump\n");
306     return 1;
307 }
308
309 /*
310  * Helper function to read stdin
311  *
312  * Returns NULL on EOF.
313  *
314  */
315 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
316     int fd = watcher->fd;
317     int n = 0;
318     int rec = 0;
319     int buffer_len = STDIN_CHUNK_SIZE;
320     unsigned char *buffer = smalloc(buffer_len + 1);
321     buffer[0] = '\0';
322     while (1) {
323         n = read(fd, buffer + rec, buffer_len - rec);
324         if (n == -1) {
325             if (errno == EAGAIN) {
326                 /* finish up */
327                 break;
328             }
329             ELOG("read() failed!: %s\n", strerror(errno));
330             exit(EXIT_FAILURE);
331         }
332         if (n == 0) {
333             ELOG("stdin: received EOF\n");
334             *ret_buffer_len = -1;
335             return NULL;
336         }
337         rec += n;
338
339         if (rec == buffer_len) {
340             buffer_len += STDIN_CHUNK_SIZE;
341             buffer = srealloc(buffer, buffer_len);
342         }
343     }
344     if (*buffer == '\0') {
345         FREE(buffer);
346         rec = -1;
347     }
348     *ret_buffer_len = rec;
349     return buffer;
350 }
351
352 static void read_flat_input(char *buffer, int length) {
353     struct status_block *first = TAILQ_FIRST(&statusline_head);
354     /* Clear the old buffer if any. */
355     I3STRING_FREE(first->full_text);
356     /* Remove the trailing newline and terminate the string at the same
357      * time. */
358     if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r')
359         buffer[length - 1] = '\0';
360     else
361         buffer[length] = '\0';
362     first->full_text = i3string_from_markup(buffer);
363 }
364
365 static bool read_json_input(unsigned char *input, int length) {
366     yajl_status status = yajl_parse(parser, input, length);
367     bool has_urgent = false;
368     if (status != yajl_status_ok) {
369         char *message = (char *)yajl_get_error(parser, 0, input, length);
370
371         /* strip the newline yajl adds to the error message */
372         if (message[strlen(message) - 1] == '\n')
373             message[strlen(message) - 1] = '\0';
374
375         fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
376                 status, message, length, input);
377
378         set_statusline_error("Could not parse JSON (%s)", message);
379         yajl_free_error(parser, (unsigned char *)message);
380         draw_bars(false);
381     } else if (parser_context.has_urgent) {
382         has_urgent = true;
383     }
384     return has_urgent;
385 }
386
387 /*
388  * Callbalk for stdin. We read a line from stdin and store the result
389  * in statusline
390  *
391  */
392 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
393     int rec;
394     unsigned char *buffer = get_buffer(watcher, &rec);
395     if (buffer == NULL)
396         return;
397     bool has_urgent = false;
398     if (child.version > 0) {
399         has_urgent = read_json_input(buffer, rec);
400     } else {
401         read_flat_input((char *)buffer, rec);
402     }
403     free(buffer);
404     draw_bars(has_urgent);
405 }
406
407 /*
408  * Callbalk for stdin first line. We read the first line to detect
409  * whether this is JSON or plain text
410  *
411  */
412 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
413     int rec;
414     unsigned char *buffer = get_buffer(watcher, &rec);
415     if (buffer == NULL)
416         return;
417     DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
418     /* Detect whether this is JSON or plain text. */
419     unsigned int consumed = 0;
420     /* At the moment, we don’t care for the version. This might change
421      * in the future, but for now, we just discard it. */
422     parse_json_header(&child, buffer, rec, &consumed);
423     if (child.version > 0) {
424         /* If hide-on-modifier is set, we start of by sending the
425          * child a SIGSTOP, because the bars aren't mapped at start */
426         if (config.hide_on_modifier) {
427             stop_child();
428         }
429         draw_bars(read_json_input(buffer + consumed, rec - consumed));
430     } else {
431         /* In case of plaintext, we just add a single block and change its
432          * full_text pointer later. */
433         struct status_block *new_block = scalloc(sizeof(struct status_block));
434         TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
435         read_flat_input((char *)buffer, rec);
436     }
437     free(buffer);
438     ev_io_stop(main_loop, stdin_io);
439     ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
440     ev_io_start(main_loop, stdin_io);
441 }
442
443 /*
444  * We received a SIGCHLD, meaning, that the child process terminated.
445  * We simply free the respective data structures and don't care for input
446  * anymore
447  *
448  */
449 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
450     int exit_status = WEXITSTATUS(watcher->rstatus);
451
452     ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
453          child.pid,
454          exit_status);
455
456     /* this error is most likely caused by a user giving a nonexecutable or
457      * nonexistent file, so we will handle those cases separately. */
458     if (exit_status == 126)
459         set_statusline_error("status_command is not executable (exit %d)", exit_status);
460     else if (exit_status == 127)
461         set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
462     else
463         set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
464
465     cleanup();
466     draw_bars(false);
467 }
468
469 void child_write_output(void) {
470     if (child.click_events) {
471         const unsigned char *output;
472         size_t size;
473         ssize_t n;
474
475         yajl_gen_get_buf(gen, &output, &size);
476
477         n = writeall(child_stdin, output, size);
478         if (n != -1)
479             n = writeall(child_stdin, "\n", 1);
480
481         yajl_gen_clear(gen);
482
483         if (n == -1) {
484             child.click_events = false;
485             kill_child();
486             set_statusline_error("child_write_output failed");
487             draw_bars(false);
488         }
489     }
490 }
491
492 /*
493  * Start a child process with the specified command and reroute stdin.
494  * We actually start a $SHELL to execute the command so we don't have to care
495  * about arguments and such.
496  *
497  * If `command' is NULL, such as in the case when no `status_command' is given
498  * in the bar config, no child will be started.
499  *
500  */
501 void start_child(char *command) {
502     if (command == NULL)
503         return;
504
505     /* Allocate a yajl parser which will be used to parse stdin. */
506     static yajl_callbacks callbacks = {
507         .yajl_boolean = stdin_boolean,
508         .yajl_integer = stdin_integer,
509         .yajl_string = stdin_string,
510         .yajl_start_map = stdin_start_map,
511         .yajl_map_key = stdin_map_key,
512         .yajl_end_map = stdin_end_map,
513         .yajl_start_array = stdin_start_array,
514         .yajl_end_array = stdin_end_array,
515     };
516     parser = yajl_alloc(&callbacks, NULL, &parser_context);
517
518     gen = yajl_gen_alloc(NULL);
519
520     int pipe_in[2];  /* pipe we read from */
521     int pipe_out[2]; /* pipe we write to */
522
523     if (pipe(pipe_in) == -1)
524         err(EXIT_FAILURE, "pipe(pipe_in)");
525     if (pipe(pipe_out) == -1)
526         err(EXIT_FAILURE, "pipe(pipe_out)");
527
528     child.pid = fork();
529     switch (child.pid) {
530         case -1:
531             ELOG("Couldn't fork(): %s\n", strerror(errno));
532             exit(EXIT_FAILURE);
533         case 0:
534             /* Child-process. Reroute streams and start shell */
535
536             close(pipe_in[0]);
537             close(pipe_out[1]);
538
539             dup2(pipe_in[1], STDOUT_FILENO);
540             dup2(pipe_out[0], STDIN_FILENO);
541
542             setpgid(child.pid, 0);
543             execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
544             return;
545         default:
546             /* Parent-process. Reroute streams */
547
548             close(pipe_in[1]);
549             close(pipe_out[0]);
550
551             dup2(pipe_in[0], STDIN_FILENO);
552             child_stdin = pipe_out[1];
553
554             break;
555     }
556
557     /* We set O_NONBLOCK because blocking is evil in event-driven software */
558     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
559
560     stdin_io = smalloc(sizeof(ev_io));
561     ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
562     ev_io_start(main_loop, stdin_io);
563
564     /* We must cleanup, if the child unexpectedly terminates */
565     child_sig = smalloc(sizeof(ev_child));
566     ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
567     ev_child_start(main_loop, child_sig);
568
569     atexit(kill_child_at_exit);
570 }
571
572 void child_click_events_initialize(void) {
573     if (!child.click_events_init) {
574         yajl_gen_array_open(gen);
575         child_write_output();
576         child.click_events_init = true;
577     }
578 }
579
580 void child_click_events_key(const char *key) {
581     yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
582 }
583
584 /*
585  * Generates a click event, if enabled.
586  *
587  */
588 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
589     if (!child.click_events) {
590         return;
591     }
592
593     child_click_events_initialize();
594
595     yajl_gen_map_open(gen);
596
597     if (name) {
598         child_click_events_key("name");
599         yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
600     }
601
602     if (instance) {
603         child_click_events_key("instance");
604         yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
605     }
606
607     child_click_events_key("button");
608     yajl_gen_integer(gen, button);
609
610     child_click_events_key("x");
611     yajl_gen_integer(gen, x);
612
613     child_click_events_key("y");
614     yajl_gen_integer(gen, y);
615
616     yajl_gen_map_close(gen);
617     child_write_output();
618 }
619
620 /*
621  * kill()s the child process (if any). Called when exit()ing.
622  *
623  */
624 void kill_child_at_exit(void) {
625     if (child.pid > 0) {
626         if (child.cont_signal > 0 && child.stopped)
627             killpg(child.pid, child.cont_signal);
628         killpg(child.pid, SIGTERM);
629     }
630 }
631
632 /*
633  * kill()s the child process (if existent) and closes and
634  * free()s the stdin- and SIGCHLD-watchers
635  *
636  */
637 void kill_child(void) {
638     if (child.pid > 0) {
639         if (child.cont_signal > 0 && child.stopped)
640             killpg(child.pid, child.cont_signal);
641         killpg(child.pid, SIGTERM);
642         int status;
643         waitpid(child.pid, &status, 0);
644         cleanup();
645     }
646 }
647
648 /*
649  * Sends a SIGSTOP to the child process (if existent)
650  *
651  */
652 void stop_child(void) {
653     if (child.stop_signal > 0 && !child.stopped) {
654         child.stopped = true;
655         killpg(child.pid, child.stop_signal);
656     }
657 }
658
659 /*
660  * Sends a SIGCONT to the child process (if existent)
661  *
662  */
663 void cont_child(void) {
664     if (child.cont_signal > 0 && child.stopped) {
665         child.stopped = false;
666         killpg(child.pid, child.cont_signal);
667     }
668 }
669
670 /*
671  * Whether or not the child want click events
672  *
673  */
674 bool child_want_click_events(void) {
675     return child.click_events;
676 }