]> git.sur5r.net Git - i3/i3/blob - i3bar/src/child.c
0b6f07df34ff06ecf61f40de367587b230588831
[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-2011 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 pid_t child_pid;
29
30 /* stdin- and sigchild-watchers */
31 ev_io    *stdin_io;
32 ev_child *child_sig;
33
34 /* JSON parser for stdin */
35 bool first_line = true;
36 bool plaintext = false;
37 yajl_callbacks callbacks;
38 yajl_handle parser;
39
40 typedef struct parser_ctx {
41     /* A copy of the last JSON map key. */
42     char *last_map_key;
43
44     /* The current block. Will be filled, then copied and put into the list of
45      * blocks. */
46     struct status_block block;
47 } parser_ctx;
48
49 parser_ctx parser_context;
50
51 /* The buffer statusline points to */
52 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
53 char *statusline_buffer = NULL;
54
55 /*
56  * Stop and free() the stdin- and sigchild-watchers
57  *
58  */
59 void cleanup() {
60     if (stdin_io != NULL) {
61         ev_io_stop(main_loop, stdin_io);
62         FREE(stdin_io);
63         FREE(statusline_buffer);
64         /* statusline pointed to memory within statusline_buffer */
65         statusline = NULL;
66     }
67
68     if (child_sig != NULL) {
69         ev_child_stop(main_loop, child_sig);
70         FREE(child_sig);
71     }
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         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         sasprintf(&(ctx->block.full_text), "%.*s", len, val);
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     TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
132     return 1;
133 }
134
135 static int stdin_end_array(void *context) {
136     DLOG("dumping statusline:\n");
137     struct status_block *current;
138     TAILQ_FOREACH(current, &statusline_head, blocks) {
139         DLOG("full_text = %s\n", current->full_text);
140         DLOG("color = %s\n", current->color);
141     }
142     DLOG("end of dump\n");
143     return 1;
144 }
145
146 /*
147  * Callbalk for stdin. We read a line from stdin and store the result
148  * in statusline
149  *
150  */
151 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
152     int fd = watcher->fd;
153     int n = 0;
154     int rec = 0;
155     int buffer_len = STDIN_CHUNK_SIZE;
156     unsigned char *buffer = smalloc(buffer_len+1);
157     buffer[0] = '\0';
158     while(1) {
159         n = read(fd, buffer + rec, buffer_len - rec);
160         if (n == -1) {
161             if (errno == EAGAIN) {
162                 /* finish up */
163                 break;
164             }
165             ELOG("read() failed!: %s\n", strerror(errno));
166             exit(EXIT_FAILURE);
167         }
168         if (n == 0) {
169             /* end of file, kill the watcher */
170             ELOG("stdin: received EOF\n");
171             cleanup();
172             draw_bars();
173             return;
174         }
175         rec += n;
176
177         if (rec == buffer_len) {
178             buffer_len += STDIN_CHUNK_SIZE;
179             buffer = srealloc(buffer, buffer_len);
180         }
181     }
182     if (*buffer == '\0') {
183         FREE(buffer);
184         return;
185     }
186
187     unsigned char *json_input = buffer;
188     if (first_line) {
189         DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
190         /* Detect whether this is JSON or plain text. */
191         plaintext = (strncasecmp((char*)buffer, "{\"version\":", strlen("{\"version\":")) != 0);
192         if (plaintext) {
193             /* In case of plaintext, we just add a single block and change its
194              * full_text pointer later. */
195             struct status_block *new_block = scalloc(sizeof(struct status_block));
196             TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
197         } else {
198             /* At the moment, we don’t care for the version. This might change
199              * in the future, but for now, we just discard it. */
200             while (*json_input != '\n' && *json_input != '\0') {
201                 json_input++;
202                 rec--;
203             }
204         }
205         first_line = false;
206     }
207     if (!plaintext) {
208         yajl_status status = yajl_parse(parser, json_input, rec);
209         if (status != yajl_status_ok) {
210             fprintf(stderr, "[i3bar] Could not parse JSON input: %.*s\n",
211                     rec, json_input);
212         }
213         free(buffer);
214     } else {
215         struct status_block *first = TAILQ_FIRST(&statusline_head);
216         /* Clear the old buffer if any. */
217         FREE(first->full_text);
218         /* Remove the trailing newline and terminate the string at the same
219          * time. */
220         if (buffer[rec-1] == '\n' || buffer[rec-1] == '\r')
221             buffer[rec-1] = '\0';
222         else buffer[rec] = '\0';
223         first->full_text = (char*)buffer;
224     }
225     draw_bars();
226 }
227
228 /*
229  * We received a sigchild, meaning, that the child-process terminated.
230  * We simply free the respective data-structures and don't care for input
231  * anymore
232  *
233  */
234 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
235     ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
236            child_pid,
237            watcher->rstatus);
238     cleanup();
239 }
240
241 /*
242  * Start a child-process with the specified command and reroute stdin.
243  * We actually start a $SHELL to execute the command so we don't have to care
244  * about arguments and such
245  *
246  */
247 void start_child(char *command) {
248     /* Allocate a yajl parser which will be used to parse stdin. */
249     memset(&callbacks, '\0', sizeof(yajl_callbacks));
250     callbacks.yajl_map_key = stdin_map_key;
251     callbacks.yajl_string = stdin_string;
252     callbacks.yajl_start_array = stdin_start_array;
253     callbacks.yajl_end_array = stdin_end_array;
254     callbacks.yajl_start_map = stdin_start_map;
255     callbacks.yajl_end_map = stdin_end_map;
256 #if YAJL_MAJOR < 2
257     yajl_parser_config parse_conf = { 0, 0 };
258
259     parser = yajl_alloc(&callbacks, &parse_conf, NULL, (void*)&parser_context);
260 #else
261     parser = yajl_alloc(&callbacks, NULL, &parser_context);
262 #endif
263
264     child_pid = 0;
265     if (command != NULL) {
266         int fd[2];
267         if (pipe(fd) == -1)
268             err(EXIT_FAILURE, "pipe(fd)");
269
270         child_pid = fork();
271         switch (child_pid) {
272             case -1:
273                 ELOG("Couldn't fork(): %s\n", strerror(errno));
274                 exit(EXIT_FAILURE);
275             case 0:
276                 /* Child-process. Reroute stdout and start shell */
277                 close(fd[0]);
278
279                 dup2(fd[1], STDOUT_FILENO);
280
281                 static const char *shell = NULL;
282
283                 if ((shell = getenv("SHELL")) == NULL)
284                     shell = "/bin/sh";
285
286                 execl(shell, shell, "-c", command, (char*) NULL);
287                 return;
288             default:
289                 /* Parent-process. Rerout stdin */
290                 close(fd[1]);
291
292                 dup2(fd[0], STDIN_FILENO);
293
294                 /* If hide-on-modifier is set, we start of by sending the
295                  * child a SIGSTOP, because the bars aren't mapped at start */
296                 if (config.hide_on_modifier) {
297                     stop_child();
298                 }
299
300                 break;
301         }
302     }
303
304     /* We set O_NONBLOCK because blocking is evil in event-driven software */
305     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
306
307     stdin_io = smalloc(sizeof(ev_io));
308     ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
309     ev_io_start(main_loop, stdin_io);
310
311     /* We must cleanup, if the child unexpectedly terminates */
312     child_sig = smalloc(sizeof(ev_child));
313     ev_child_init(child_sig, &child_sig_cb, child_pid, 0);
314     ev_child_start(main_loop, child_sig);
315
316     atexit(kill_child_at_exit);
317 }
318
319 /*
320  * kill()s the child-process (if any). Called when exit()ing.
321  *
322  */
323 void kill_child_at_exit() {
324     if (child_pid != 0) {
325         kill(child_pid, SIGCONT);
326         kill(child_pid, SIGTERM);
327     }
328 }
329
330 /*
331  * kill()s the child-process (if existent) and closes and
332  * free()s the stdin- and sigchild-watchers
333  *
334  */
335 void kill_child() {
336     if (child_pid != 0) {
337         kill(child_pid, SIGCONT);
338         kill(child_pid, SIGTERM);
339         int status;
340         waitpid(child_pid, &status, 0);
341         child_pid = 0;
342         cleanup();
343     }
344 }
345
346 /*
347  * Sends a SIGSTOP to the child-process (if existent)
348  *
349  */
350 void stop_child() {
351     if (child_pid != 0) {
352         kill(child_pid, SIGSTOP);
353     }
354 }
355
356 /*
357  * Sends a SIGCONT to the child-process (if existent)
358  *
359  */
360 void cont_child() {
361     if (child_pid != 0) {
362         kill(child_pid, SIGCONT);
363     }
364 }