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