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