]> git.sur5r.net Git - i3/i3/blob - i3bar/src/child.c
Merge branch 'fix-unmap'
[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 <fcntl.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <err.h>
20 #include <ev.h>
21 #include <yajl/yajl_common.h>
22 #include <yajl/yajl_parse.h>
23 #include <yajl/yajl_version.h>
24
25 #include "common.h"
26
27 /* Global variables for child_*() */
28 i3bar_child child = { 0 };
29
30 /* stdin- and sigchild-watchers */
31 ev_io    *stdin_io;
32 ev_child *child_sig;
33
34 /* JSON parser for stdin */
35 yajl_callbacks callbacks;
36 yajl_handle parser;
37
38 typedef struct parser_ctx {
39     /* True if one of the parsed blocks was urgent */
40     bool has_urgent;
41
42     /* A copy of the last JSON map key. */
43     char *last_map_key;
44
45     /* The current block. Will be filled, then copied and put into the list of
46      * blocks. */
47     struct status_block block;
48 } parser_ctx;
49
50 parser_ctx parser_context;
51
52 /* The buffer statusline points to */
53 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
54 char *statusline_buffer = NULL;
55
56 /*
57  * Stop and free() the stdin- and sigchild-watchers
58  *
59  */
60 void cleanup(void) {
61     if (stdin_io != NULL) {
62         ev_io_stop(main_loop, stdin_io);
63         FREE(stdin_io);
64         FREE(statusline_buffer);
65         /* statusline pointed to memory within statusline_buffer */
66         statusline = NULL;
67     }
68
69     if (child_sig != NULL) {
70         ev_child_stop(main_loop, child_sig);
71         FREE(child_sig);
72     }
73
74     memset(&child, 0, sizeof(i3bar_child));
75 }
76
77 /*
78  * The start of a new array is the start of a new status line, so we clear all
79  * previous entries.
80  *
81  */
82 static int stdin_start_array(void *context) {
83     struct status_block *first;
84     while (!TAILQ_EMPTY(&statusline_head)) {
85         first = TAILQ_FIRST(&statusline_head);
86         I3STRING_FREE(first->full_text);
87         FREE(first->color);
88         TAILQ_REMOVE(&statusline_head, first, blocks);
89         free(first);
90     }
91     return 1;
92 }
93
94 /*
95  * The start of a map is the start of a single block of the status line.
96  *
97  */
98 static int stdin_start_map(void *context) {
99     parser_ctx *ctx = context;
100     memset(&(ctx->block), '\0', sizeof(struct status_block));
101
102     /* Default width of the separator block. */
103     ctx->block.sep_block_width = 9;
104
105     return 1;
106 }
107
108 #if YAJL_MAJOR >= 2
109 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
110 #else
111 static int stdin_map_key(void *context, const unsigned char *key, unsigned int len) {
112 #endif
113     parser_ctx *ctx = context;
114     FREE(ctx->last_map_key);
115     sasprintf(&(ctx->last_map_key), "%.*s", len, key);
116     return 1;
117 }
118
119 static int stdin_boolean(void *context, int val) {
120     parser_ctx *ctx = context;
121     if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
122         ctx->block.urgent = val;
123     }
124     if (strcasecmp(ctx->last_map_key, "separator") == 0) {
125         ctx->block.no_separator = !val;
126     }
127     return 1;
128 }
129
130 #if YAJL_MAJOR >= 2
131 static int stdin_string(void *context, const unsigned char *val, size_t len) {
132 #else
133 static int stdin_string(void *context, const unsigned char *val, unsigned int len) {
134 #endif
135     parser_ctx *ctx = context;
136     if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
137         ctx->block.full_text = i3string_from_utf8_with_length((const char *)val, len);
138     }
139     if (strcasecmp(ctx->last_map_key, "color") == 0) {
140         sasprintf(&(ctx->block.color), "%.*s", len, val);
141     }
142     if (strcasecmp(ctx->last_map_key, "align") == 0) {
143         if (len == strlen("left") && !strncmp((const char*)val, "left", strlen("left"))) {
144             ctx->block.align = ALIGN_LEFT;
145         } else if (len == strlen("right") && !strncmp((const char*)val, "right", strlen("right"))) {
146             ctx->block.align = ALIGN_RIGHT;
147         } else {
148             ctx->block.align = ALIGN_CENTER;
149         }
150     } else if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
151         i3String *text = i3string_from_utf8_with_length((const char *)val, len);
152         ctx->block.min_width = (uint32_t)predict_text_width(text);
153         i3string_free(text);
154     }
155     return 1;
156 }
157
158 #if YAJL_MAJOR >= 2
159 static int stdin_integer(void *context, long long val) {
160 #else
161 static int stdin_integer(void *context, long val) {
162 #endif
163     parser_ctx *ctx = context;
164     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
165         ctx->block.min_width = (uint32_t)val;
166     }
167     if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
168         ctx->block.sep_block_width = (uint32_t)val;
169     }
170     return 1;
171 }
172
173 static int stdin_end_map(void *context) {
174     parser_ctx *ctx = context;
175     struct status_block *new_block = smalloc(sizeof(struct status_block));
176     memcpy(new_block, &(ctx->block), sizeof(struct status_block));
177     /* Ensure we have a full_text set, so that when it is missing (or null),
178      * i3bar doesn’t crash and the user gets an annoying message. */
179     if (!new_block->full_text)
180         new_block->full_text = i3string_from_utf8("SPEC VIOLATION (null)");
181     if (new_block->urgent)
182         ctx->has_urgent = true;
183     TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
184     return 1;
185 }
186
187 static int stdin_end_array(void *context) {
188     DLOG("dumping statusline:\n");
189     struct status_block *current;
190     TAILQ_FOREACH(current, &statusline_head, blocks) {
191         DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
192         DLOG("color = %s\n", current->color);
193     }
194     DLOG("end of dump\n");
195     return 1;
196 }
197
198 /*
199  * Helper function to read stdin
200  *
201  */
202 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
203     int fd = watcher->fd;
204     int n = 0;
205     int rec = 0;
206     int buffer_len = STDIN_CHUNK_SIZE;
207     unsigned char *buffer = smalloc(buffer_len+1);
208     buffer[0] = '\0';
209     while(1) {
210         n = read(fd, buffer + rec, buffer_len - rec);
211         if (n == -1) {
212             if (errno == EAGAIN) {
213                 /* finish up */
214                 break;
215             }
216             ELOG("read() failed!: %s\n", strerror(errno));
217             exit(EXIT_FAILURE);
218         }
219         if (n == 0) {
220             /* end of file, kill the watcher */
221             ELOG("stdin: received EOF\n");
222             cleanup();
223             draw_bars(false);
224             *ret_buffer_len = -1;
225             return NULL;
226         }
227         rec += n;
228
229         if (rec == buffer_len) {
230             buffer_len += STDIN_CHUNK_SIZE;
231             buffer = srealloc(buffer, buffer_len);
232         }
233     }
234     if (*buffer == '\0') {
235         FREE(buffer);
236         rec = -1;
237     }
238     *ret_buffer_len = rec;
239     return buffer;
240 }
241
242 static void read_flat_input(char *buffer, int length) {
243     struct status_block *first = TAILQ_FIRST(&statusline_head);
244     /* Clear the old buffer if any. */
245     I3STRING_FREE(first->full_text);
246     /* Remove the trailing newline and terminate the string at the same
247      * time. */
248     if (buffer[length-1] == '\n' || buffer[length-1] == '\r')
249         buffer[length-1] = '\0';
250     else buffer[length] = '\0';
251     first->full_text = i3string_from_utf8(buffer);
252 }
253
254 static bool read_json_input(unsigned char *input, int length) {
255     yajl_status status = yajl_parse(parser, input, length);
256     bool has_urgent = false;
257 #if YAJL_MAJOR >= 2
258     if (status != yajl_status_ok) {
259 #else
260     if (status != yajl_status_ok && status != yajl_status_insufficient_data) {
261 #endif
262         fprintf(stderr, "[i3bar] Could not parse JSON input (code %d): %.*s\n",
263                 status, length, input);
264     } else if (parser_context.has_urgent) {
265         has_urgent = true;
266     }
267     return has_urgent;
268 }
269
270 /*
271  * Callbalk for stdin. We read a line from stdin and store the result
272  * in statusline
273  *
274  */
275 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
276     int rec;
277     unsigned char *buffer = get_buffer(watcher, &rec);
278     if (buffer == NULL)
279         return;
280     bool has_urgent = false;
281     if (child.version > 0) {
282         has_urgent = read_json_input(buffer, rec);
283     } else {
284         read_flat_input((char*)buffer, rec);
285     }
286     free(buffer);
287     draw_bars(has_urgent);
288 }
289
290 /*
291  * Callbalk for stdin first line. We read the first line to detect
292  * whether this is JSON or plain text
293  *
294  */
295 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
296     int rec;
297     unsigned char *buffer = get_buffer(watcher, &rec);
298     if (buffer == NULL)
299         return;
300     DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
301     /* Detect whether this is JSON or plain text. */
302     unsigned int consumed = 0;
303     /* At the moment, we don’t care for the version. This might change
304      * in the future, but for now, we just discard it. */
305     parse_json_header(&child, buffer, rec, &consumed);
306     if (child.version > 0) {
307         /* If hide-on-modifier is set, we start of by sending the
308          * child a SIGSTOP, because the bars aren't mapped at start */
309         if (config.hide_on_modifier) {
310             stop_child();
311         }
312         read_json_input(buffer + consumed, rec - consumed);
313     } else {
314         /* In case of plaintext, we just add a single block and change its
315          * full_text pointer later. */
316         struct status_block *new_block = scalloc(sizeof(struct status_block));
317         TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
318         read_flat_input((char*)buffer, rec);
319     }
320     free(buffer);
321     ev_io_stop(main_loop, stdin_io);
322     ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
323     ev_io_start(main_loop, stdin_io);
324 }
325
326 /*
327  * We received a sigchild, meaning, that the child-process terminated.
328  * We simply free the respective data-structures and don't care for input
329  * anymore
330  *
331  */
332 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
333     ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
334            child.pid,
335            watcher->rstatus);
336     cleanup();
337 }
338
339 /*
340  * Start a child-process with the specified command and reroute stdin.
341  * We actually start a $SHELL to execute the command so we don't have to care
342  * about arguments and such
343  *
344  */
345 void start_child(char *command) {
346     /* Allocate a yajl parser which will be used to parse stdin. */
347     memset(&callbacks, '\0', sizeof(yajl_callbacks));
348     callbacks.yajl_map_key = stdin_map_key;
349     callbacks.yajl_boolean = stdin_boolean;
350     callbacks.yajl_string = stdin_string;
351     callbacks.yajl_integer = stdin_integer;
352     callbacks.yajl_start_array = stdin_start_array;
353     callbacks.yajl_end_array = stdin_end_array;
354     callbacks.yajl_start_map = stdin_start_map;
355     callbacks.yajl_end_map = stdin_end_map;
356 #if YAJL_MAJOR < 2
357     yajl_parser_config parse_conf = { 0, 0 };
358
359     parser = yajl_alloc(&callbacks, &parse_conf, NULL, (void*)&parser_context);
360 #else
361     parser = yajl_alloc(&callbacks, NULL, &parser_context);
362 #endif
363
364     if (command != NULL) {
365         int fd[2];
366         if (pipe(fd) == -1)
367             err(EXIT_FAILURE, "pipe(fd)");
368
369         child.pid = fork();
370         switch (child.pid) {
371             case -1:
372                 ELOG("Couldn't fork(): %s\n", strerror(errno));
373                 exit(EXIT_FAILURE);
374             case 0:
375                 /* Child-process. Reroute stdout and start shell */
376                 close(fd[0]);
377
378                 dup2(fd[1], STDOUT_FILENO);
379
380                 static const char *shell = NULL;
381
382                 if ((shell = getenv("SHELL")) == NULL)
383                     shell = "/bin/sh";
384
385                 execl(shell, shell, "-c", command, (char*) NULL);
386                 return;
387             default:
388                 /* Parent-process. Rerout stdin */
389                 close(fd[1]);
390
391                 dup2(fd[0], STDIN_FILENO);
392
393                 break;
394         }
395     }
396
397     /* We set O_NONBLOCK because blocking is evil in event-driven software */
398     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
399
400     stdin_io = smalloc(sizeof(ev_io));
401     ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
402     ev_io_start(main_loop, stdin_io);
403
404     /* We must cleanup, if the child unexpectedly terminates */
405     child_sig = smalloc(sizeof(ev_child));
406     ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
407     ev_child_start(main_loop, child_sig);
408
409     atexit(kill_child_at_exit);
410 }
411
412 /*
413  * kill()s the child-process (if any). Called when exit()ing.
414  *
415  */
416 void kill_child_at_exit(void) {
417     if (child.pid > 0) {
418         if (child.cont_signal > 0 && child.stopped)
419             kill(child.pid, child.cont_signal);
420         kill(child.pid, SIGTERM);
421     }
422 }
423
424 /*
425  * kill()s the child-process (if existent) and closes and
426  * free()s the stdin- and sigchild-watchers
427  *
428  */
429 void kill_child(void) {
430     if (child.pid > 0) {
431         if (child.cont_signal > 0 && child.stopped)
432             kill(child.pid, child.cont_signal);
433         kill(child.pid, SIGTERM);
434         int status;
435         waitpid(child.pid, &status, 0);
436         cleanup();
437     }
438 }
439
440 /*
441  * Sends a SIGSTOP to the child-process (if existent)
442  *
443  */
444 void stop_child(void) {
445     if (child.stop_signal > 0 && !child.stopped) {
446         child.stopped = true;
447         kill(child.pid, child.stop_signal);
448     }
449 }
450
451 /*
452  * Sends a SIGCONT to the child-process (if existent)
453  *
454  */
455 void cont_child(void) {
456     if (child.cont_signal > 0 && child.stopped) {
457         child.stopped = false;
458         kill(child.pid, child.cont_signal);
459     }
460 }