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