]> git.sur5r.net Git - i3/i3/blob - i3bar/src/child.c
bugfix: don't use con_is_internal
[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 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(void) {
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         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  * Callbalk for stdin. We read a line from stdin and store the result
152  * in statusline
153  *
154  */
155 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
156     int fd = watcher->fd;
157     int n = 0;
158     int rec = 0;
159     int buffer_len = STDIN_CHUNK_SIZE;
160     unsigned char *buffer = smalloc(buffer_len+1);
161     buffer[0] = '\0';
162     while(1) {
163         n = read(fd, buffer + rec, buffer_len - rec);
164         if (n == -1) {
165             if (errno == EAGAIN) {
166                 /* finish up */
167                 break;
168             }
169             ELOG("read() failed!: %s\n", strerror(errno));
170             exit(EXIT_FAILURE);
171         }
172         if (n == 0) {
173             /* end of file, kill the watcher */
174             ELOG("stdin: received EOF\n");
175             cleanup();
176             draw_bars();
177             return;
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         return;
189     }
190
191     unsigned char *json_input = buffer;
192     if (first_line) {
193         DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
194         /* Detect whether this is JSON or plain text. */
195         unsigned int consumed = 0;
196         /* At the moment, we don’t care for the version. This might change
197          * in the future, but for now, we just discard it. */
198         plaintext = (determine_json_version(buffer, buffer_len, &consumed) == -1);
199         if (plaintext) {
200             /* In case of plaintext, we just add a single block and change its
201              * full_text pointer later. */
202             struct status_block *new_block = scalloc(sizeof(struct status_block));
203             TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
204         } else {
205             json_input += consumed;
206             rec -= consumed;
207         }
208         first_line = false;
209     }
210     if (!plaintext) {
211         yajl_status status = yajl_parse(parser, json_input, rec);
212 #if YAJL_MAJOR >= 2
213         if (status != yajl_status_ok) {
214 #else
215         if (status != yajl_status_ok && status != yajl_status_insufficient_data) {
216 #endif
217             fprintf(stderr, "[i3bar] Could not parse JSON input (code %d): %.*s\n",
218                     status, rec, json_input);
219         }
220     } else {
221         struct status_block *first = TAILQ_FIRST(&statusline_head);
222         /* Clear the old buffer if any. */
223         I3STRING_FREE(first->full_text);
224         /* Remove the trailing newline and terminate the string at the same
225          * time. */
226         if (buffer[rec-1] == '\n' || buffer[rec-1] == '\r')
227             buffer[rec-1] = '\0';
228         else buffer[rec] = '\0';
229         first->full_text = i3string_from_utf8((const char *)buffer);
230     }
231     free(buffer);
232     draw_bars();
233 }
234
235 /*
236  * We received a sigchild, meaning, that the child-process terminated.
237  * We simply free the respective data-structures and don't care for input
238  * anymore
239  *
240  */
241 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
242     ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
243            child_pid,
244            watcher->rstatus);
245     cleanup();
246 }
247
248 /*
249  * Start a child-process with the specified command and reroute stdin.
250  * We actually start a $SHELL to execute the command so we don't have to care
251  * about arguments and such
252  *
253  */
254 void start_child(char *command) {
255     /* Allocate a yajl parser which will be used to parse stdin. */
256     memset(&callbacks, '\0', sizeof(yajl_callbacks));
257     callbacks.yajl_map_key = stdin_map_key;
258     callbacks.yajl_string = stdin_string;
259     callbacks.yajl_start_array = stdin_start_array;
260     callbacks.yajl_end_array = stdin_end_array;
261     callbacks.yajl_start_map = stdin_start_map;
262     callbacks.yajl_end_map = stdin_end_map;
263 #if YAJL_MAJOR < 2
264     yajl_parser_config parse_conf = { 0, 0 };
265
266     parser = yajl_alloc(&callbacks, &parse_conf, NULL, (void*)&parser_context);
267 #else
268     parser = yajl_alloc(&callbacks, NULL, &parser_context);
269 #endif
270
271     child_pid = 0;
272     if (command != NULL) {
273         int fd[2];
274         if (pipe(fd) == -1)
275             err(EXIT_FAILURE, "pipe(fd)");
276
277         child_pid = fork();
278         switch (child_pid) {
279             case -1:
280                 ELOG("Couldn't fork(): %s\n", strerror(errno));
281                 exit(EXIT_FAILURE);
282             case 0:
283                 /* Child-process. Reroute stdout and start shell */
284                 close(fd[0]);
285
286                 dup2(fd[1], STDOUT_FILENO);
287
288                 static const char *shell = NULL;
289
290                 if ((shell = getenv("SHELL")) == NULL)
291                     shell = "/bin/sh";
292
293                 execl(shell, shell, "-c", command, (char*) NULL);
294                 return;
295             default:
296                 /* Parent-process. Rerout stdin */
297                 close(fd[1]);
298
299                 dup2(fd[0], STDIN_FILENO);
300
301                 /* If hide-on-modifier is set, we start of by sending the
302                  * child a SIGSTOP, because the bars aren't mapped at start */
303                 if (config.hide_on_modifier) {
304                     stop_child();
305                 }
306
307                 break;
308         }
309     }
310
311     /* We set O_NONBLOCK because blocking is evil in event-driven software */
312     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
313
314     stdin_io = smalloc(sizeof(ev_io));
315     ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
316     ev_io_start(main_loop, stdin_io);
317
318     /* We must cleanup, if the child unexpectedly terminates */
319     child_sig = smalloc(sizeof(ev_child));
320     ev_child_init(child_sig, &child_sig_cb, child_pid, 0);
321     ev_child_start(main_loop, child_sig);
322
323     atexit(kill_child_at_exit);
324 }
325
326 /*
327  * kill()s the child-process (if any). Called when exit()ing.
328  *
329  */
330 void kill_child_at_exit(void) {
331     if (child_pid != 0) {
332         kill(child_pid, SIGCONT);
333         kill(child_pid, SIGTERM);
334     }
335 }
336
337 /*
338  * kill()s the child-process (if existent) and closes and
339  * free()s the stdin- and sigchild-watchers
340  *
341  */
342 void kill_child(void) {
343     if (child_pid != 0) {
344         kill(child_pid, SIGCONT);
345         kill(child_pid, SIGTERM);
346         int status;
347         waitpid(child_pid, &status, 0);
348         child_pid = 0;
349         cleanup();
350     }
351 }
352
353 /*
354  * Sends a SIGSTOP to the child-process (if existent)
355  *
356  */
357 void stop_child(void) {
358     if (child_pid != 0) {
359         kill(child_pid, SIGSTOP);
360     }
361 }
362
363 /*
364  * Sends a SIGCONT to the child-process (if existent)
365  *
366  */
367 void cont_child(void) {
368     if (child_pid != 0) {
369         kill(child_pid, SIGCONT);
370     }
371 }