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