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