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