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