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