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