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