]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Fix some potential memory leaks
[i3/i3] / src / ipc.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009-2011 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  * ipc.c: Everything about the UNIX domain sockets for IPC
11  *
12  */
13 #include <sys/socket.h>
14 #include <sys/un.h>
15 #include <fcntl.h>
16 #include <libgen.h>
17 #include <ev.h>
18 #include <yajl/yajl_gen.h>
19 #include <yajl/yajl_parse.h>
20 #include <yajl/yajl_version.h>
21
22 #include "all.h"
23
24 char *current_socketpath = NULL;
25
26 /* Shorter names for all those yajl_gen_* functions */
27 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
28 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
29
30 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
31
32 /*
33  * Puts the given socket file descriptor into non-blocking mode or dies if
34  * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
35  * IPC model because we should by no means block the window manager.
36  *
37  */
38 static void set_nonblock(int sockfd) {
39     int flags = fcntl(sockfd, F_GETFL, 0);
40     flags |= O_NONBLOCK;
41     if (fcntl(sockfd, F_SETFL, flags) < 0)
42         err(-1, "Could not set O_NONBLOCK");
43 }
44
45 /*
46  * Emulates mkdir -p (creates any missing folders)
47  *
48  */
49 static bool mkdirp(const char *path) {
50     if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
51         return true;
52     if (errno != ENOENT) {
53         ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
54         return false;
55     }
56     char *copy = strdup(path);
57     /* strip trailing slashes, if any */
58     while (copy[strlen(copy)-1] == '/')
59         copy[strlen(copy)-1] = '\0';
60
61     char *sep = strrchr(copy, '/');
62     if (sep == NULL)
63         return false;
64     *sep = '\0';
65     bool result = false;
66     if (mkdirp(copy))
67         result = mkdirp(path);
68     free(copy);
69
70     return result;
71 }
72
73 static void ipc_send_message(int fd, const unsigned char *payload,
74                              int message_type, int message_size) {
75     int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
76                       sizeof(uint32_t) + message_size;
77     char msg[buffer_size];
78     char *walk = msg;
79
80     strncpy(walk, "i3-ipc", buffer_size - 1);
81     walk += strlen("i3-ipc");
82     memcpy(walk, &message_size, sizeof(uint32_t));
83     walk += sizeof(uint32_t);
84     memcpy(walk, &message_type, sizeof(uint32_t));
85     walk += sizeof(uint32_t);
86     memcpy(walk, payload, message_size);
87
88     int sent_bytes = 0;
89     int bytes_to_go = buffer_size;
90     while (sent_bytes < bytes_to_go) {
91         int n = write(fd, msg + sent_bytes, bytes_to_go);
92         if (n == -1) {
93             DLOG("write() failed: %s\n", strerror(errno));
94             return;
95         }
96
97         sent_bytes += n;
98         bytes_to_go -= n;
99     }
100 }
101
102 /*
103  * Sends the specified event to all IPC clients which are currently connected
104  * and subscribed to this kind of event.
105  *
106  */
107 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
108     ipc_client *current;
109     TAILQ_FOREACH(current, &all_clients, clients) {
110         /* see if this client is interested in this event */
111         bool interested = false;
112         for (int i = 0; i < current->num_events; i++) {
113             if (strcasecmp(current->events[i], event) != 0)
114                 continue;
115             interested = true;
116             break;
117         }
118         if (!interested)
119             continue;
120
121         ipc_send_message(current->fd, (const unsigned char*)payload,
122                          message_type, strlen(payload));
123     }
124 }
125
126 /*
127  * Calls shutdown() on each socket and closes it. This function to be called
128  * when exiting or restarting only!
129  *
130  */
131 void ipc_shutdown() {
132     ipc_client *current;
133     TAILQ_FOREACH(current, &all_clients, clients) {
134         shutdown(current->fd, SHUT_RDWR);
135         close(current->fd);
136     }
137 }
138
139 /*
140  * Executes the command and returns whether it could be successfully parsed
141  * or not (at the moment, always returns true).
142  *
143  */
144 IPC_HANDLER(command) {
145     /* To get a properly terminated buffer, we copy
146      * message_size bytes out of the buffer */
147     char *command = scalloc(message_size + 1);
148     strncpy(command, (const char*)message, message_size);
149     LOG("IPC: received: *%s*\n", command);
150     char *reply = parse_cmd((const char*)command);
151     char *save_reply = reply;
152     free(command);
153
154     /* If no reply was provided, we just use the default success message */
155     if (reply == NULL)
156         reply = "{\"success\":true}";
157     ipc_send_message(fd, (const unsigned char*)reply,
158                      I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
159
160     FREE(save_reply);
161 }
162
163 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
164     ystr(name);
165     y(map_open);
166     ystr("x");
167     y(integer, r.x);
168     ystr("y");
169     y(integer, r.y);
170     ystr("width");
171     y(integer, r.width);
172     ystr("height");
173     y(integer, r.height);
174     y(map_close);
175 }
176
177 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
178     y(map_open);
179     ystr("id");
180     y(integer, (long int)con);
181
182     ystr("type");
183     y(integer, con->type);
184
185     ystr("orientation");
186     switch (con->orientation) {
187         case NO_ORIENTATION:
188             ystr("none");
189             break;
190         case HORIZ:
191             ystr("horizontal");
192             break;
193         case VERT:
194             ystr("vertical");
195             break;
196     }
197
198     ystr("percent");
199     if (con->percent == 0.0)
200         y(null);
201     else y(double, con->percent);
202
203     ystr("urgent");
204     y(bool, con->urgent);
205
206     ystr("focused");
207     y(bool, (con == focused));
208
209     ystr("layout");
210     switch (con->layout) {
211         case L_DEFAULT:
212             ystr("default");
213             break;
214         case L_STACKED:
215             ystr("stacked");
216             break;
217         case L_TABBED:
218             ystr("tabbed");
219             break;
220         case L_DOCKAREA:
221             ystr("dockarea");
222             break;
223         case L_OUTPUT:
224             ystr("output");
225             break;
226     }
227
228     ystr("border");
229     switch (con->border_style) {
230         case BS_NORMAL:
231             ystr("normal");
232             break;
233         case BS_NONE:
234             ystr("none");
235             break;
236         case BS_1PIXEL:
237             ystr("1pixel");
238             break;
239     }
240
241     dump_rect(gen, "rect", con->rect);
242     dump_rect(gen, "window_rect", con->window_rect);
243     dump_rect(gen, "geometry", con->geometry);
244
245     ystr("name");
246     ystr(con->name);
247
248     if (con->type == CT_WORKSPACE) {
249         ystr("num");
250         y(integer, con->num);
251     }
252
253     ystr("window");
254     if (con->window)
255         y(integer, con->window->id);
256     else y(null);
257
258     ystr("nodes");
259     y(array_open);
260     Con *node;
261     if (con->type != CT_DOCKAREA || !inplace_restart) {
262         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
263             dump_node(gen, node, inplace_restart);
264         }
265     }
266     y(array_close);
267
268     ystr("floating_nodes");
269     y(array_open);
270     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
271         dump_node(gen, node, inplace_restart);
272     }
273     y(array_close);
274
275     ystr("focus");
276     y(array_open);
277     TAILQ_FOREACH(node, &(con->focus_head), nodes) {
278         y(integer, (long int)node);
279     }
280     y(array_close);
281
282     ystr("fullscreen_mode");
283     y(integer, con->fullscreen_mode);
284
285     ystr("swallows");
286     y(array_open);
287     Match *match;
288     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
289         if (match->dock != -1) {
290             y(map_open);
291             ystr("dock");
292             y(integer, match->dock);
293             ystr("insert_where");
294             y(integer, match->insert_where);
295             y(map_close);
296         }
297
298         /* TODO: the other swallow keys */
299     }
300
301     if (inplace_restart) {
302         if (con->window != NULL) {
303             y(map_open);
304             ystr("id");
305             y(integer, con->window->id);
306             y(map_close);
307         }
308     }
309     y(array_close);
310
311     y(map_close);
312 }
313
314 IPC_HANDLER(tree) {
315     setlocale(LC_NUMERIC, "C");
316 #if YAJL_MAJOR >= 2
317     yajl_gen gen = yajl_gen_alloc(NULL);
318 #else
319     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
320 #endif
321     dump_node(gen, croot, false);
322     setlocale(LC_NUMERIC, "");
323
324     const unsigned char *payload;
325 #if YAJL_MAJOR >= 2
326     size_t length;
327 #else
328     unsigned int length;
329 #endif
330     y(get_buf, &payload, &length);
331
332     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
333     y(free);
334 }
335
336 /*
337  * Formats the reply message for a GET_WORKSPACES request and sends it to the
338  * client
339  *
340  */
341 IPC_HANDLER(get_workspaces) {
342 #if YAJL_MAJOR >= 2
343     yajl_gen gen = yajl_gen_alloc(NULL);
344 #else
345     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
346 #endif
347     y(array_open);
348
349     Con *focused_ws = con_get_workspace(focused);
350
351     Con *output;
352     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
353         Con *ws;
354         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
355             assert(ws->type == CT_WORKSPACE);
356             y(map_open);
357
358             ystr("num");
359             if (ws->num == -1)
360                 y(null);
361             else y(integer, ws->num);
362
363             ystr("name");
364             ystr(ws->name);
365
366             ystr("visible");
367             y(bool, workspace_is_visible(ws));
368
369             ystr("focused");
370             y(bool, ws == focused_ws);
371
372             ystr("rect");
373             y(map_open);
374             ystr("x");
375             y(integer, ws->rect.x);
376             ystr("y");
377             y(integer, ws->rect.y);
378             ystr("width");
379             y(integer, ws->rect.width);
380             ystr("height");
381             y(integer, ws->rect.height);
382             y(map_close);
383
384             ystr("output");
385             ystr(output->name);
386
387             ystr("urgent");
388             y(bool, ws->urgent);
389
390             y(map_close);
391         }
392     }
393
394     y(array_close);
395
396     const unsigned char *payload;
397 #if YAJL_MAJOR >= 2
398     size_t length;
399 #else
400     unsigned int length;
401 #endif
402     y(get_buf, &payload, &length);
403
404     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
405     y(free);
406 }
407
408 /*
409  * Formats the reply message for a GET_OUTPUTS request and sends it to the
410  * client
411  *
412  */
413 IPC_HANDLER(get_outputs) {
414 #if YAJL_MAJOR >= 2
415     yajl_gen gen = yajl_gen_alloc(NULL);
416 #else
417     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
418 #endif
419     y(array_open);
420
421     Output *output;
422     TAILQ_FOREACH(output, &outputs, outputs) {
423         y(map_open);
424
425         ystr("name");
426         ystr(output->name);
427
428         ystr("active");
429         y(bool, output->active);
430
431         ystr("rect");
432         y(map_open);
433         ystr("x");
434         y(integer, output->rect.x);
435         ystr("y");
436         y(integer, output->rect.y);
437         ystr("width");
438         y(integer, output->rect.width);
439         ystr("height");
440         y(integer, output->rect.height);
441         y(map_close);
442
443         ystr("current_workspace");
444         Con *ws = NULL;
445         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
446             ystr(ws->name);
447         else y(null);
448
449         y(map_close);
450     }
451
452     y(array_close);
453
454     const unsigned char *payload;
455 #if YAJL_MAJOR >= 2
456     size_t length;
457 #else
458     unsigned int length;
459 #endif
460     y(get_buf, &payload, &length);
461
462     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
463     y(free);
464 }
465
466 /*
467  * Callback for the YAJL parser (will be called when a string is parsed).
468  *
469  */
470 #if YAJL_MAJOR < 2
471 static int add_subscription(void *extra, const unsigned char *s,
472                             unsigned int len) {
473 #else
474 static int add_subscription(void *extra, const unsigned char *s,
475                             size_t len) {
476 #endif
477     ipc_client *client = extra;
478
479     DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
480     int event = client->num_events;
481
482     client->num_events++;
483     client->events = realloc(client->events, client->num_events * sizeof(char*));
484     /* We copy the string because it is not null-terminated and strndup()
485      * is missing on some BSD systems */
486     client->events[event] = scalloc(len+1);
487     memcpy(client->events[event], s, len);
488
489     DLOG("client is now subscribed to:\n");
490     for (int i = 0; i < client->num_events; i++)
491         DLOG("event %s\n", client->events[i]);
492     DLOG("(done)\n");
493
494     return 1;
495 }
496
497 /*
498  * Subscribes this connection to the event types which were given as a JSON
499  * serialized array in the payload field of the message.
500  *
501  */
502 IPC_HANDLER(subscribe) {
503     yajl_handle p;
504     yajl_callbacks callbacks;
505     yajl_status stat;
506     ipc_client *current, *client = NULL;
507
508     /* Search the ipc_client structure for this connection */
509     TAILQ_FOREACH(current, &all_clients, clients) {
510         if (current->fd != fd)
511             continue;
512
513         client = current;
514         break;
515     }
516
517     if (client == NULL) {
518         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
519         return;
520     }
521
522     /* Setup the JSON parser */
523     memset(&callbacks, 0, sizeof(yajl_callbacks));
524     callbacks.yajl_string = add_subscription;
525
526 #if YAJL_MAJOR >= 2
527     p = yajl_alloc(&callbacks, NULL, (void*)client);
528 #else
529     p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
530 #endif
531     stat = yajl_parse(p, (const unsigned char*)message, message_size);
532     if (stat != yajl_status_ok) {
533         unsigned char *err;
534         err = yajl_get_error(p, true, (const unsigned char*)message,
535                              message_size);
536         ELOG("YAJL parse error: %s\n", err);
537         yajl_free_error(p, err);
538
539         const char *reply = "{\"success\":false}";
540         ipc_send_message(fd, (const unsigned char*)reply,
541                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
542         yajl_free(p);
543         return;
544     }
545     yajl_free(p);
546     const char *reply = "{\"success\":true}";
547     ipc_send_message(fd, (const unsigned char*)reply,
548                      I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
549 }
550
551 /* The index of each callback function corresponds to the numeric
552  * value of the message type (see include/i3/ipc.h) */
553 handler_t handlers[5] = {
554     handle_command,
555     handle_get_workspaces,
556     handle_subscribe,
557     handle_get_outputs,
558     handle_tree
559 };
560
561 /*
562  * Handler for activity on a client connection, receives a message from a
563  * client.
564  *
565  * For now, the maximum message size is 2048. I’m not sure for what the
566  * IPC interface will be used in the future, thus I’m not implementing a
567  * mechanism for arbitrarily long messages, as it seems like overkill
568  * at the moment.
569  *
570  */
571 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
572     char buf[2048];
573     int n = read(w->fd, buf, sizeof(buf));
574
575     /* On error or an empty message, we close the connection */
576     if (n <= 0) {
577 #if 0
578         /* FIXME: I get these when closing a client socket,
579          * therefore we just treat them as an error. Is this
580          * correct? */
581         if (errno == EAGAIN || errno == EWOULDBLOCK)
582                 return;
583 #endif
584
585         /* If not, there was some kind of error. We don’t bother
586          * and close the connection */
587         close(w->fd);
588
589         /* Delete the client from the list of clients */
590         ipc_client *current;
591         TAILQ_FOREACH(current, &all_clients, clients) {
592             if (current->fd != w->fd)
593                 continue;
594
595             for (int i = 0; i < current->num_events; i++)
596                 free(current->events[i]);
597             /* We can call TAILQ_REMOVE because we break out of the
598              * TAILQ_FOREACH afterwards */
599             TAILQ_REMOVE(&all_clients, current, clients);
600             break;
601         }
602
603         ev_io_stop(EV_A_ w);
604
605         DLOG("IPC: client disconnected\n");
606         return;
607     }
608
609     /* Terminate the message correctly */
610     buf[n] = '\0';
611
612     /* Check if the message starts with the i3 IPC magic code */
613     if (n < strlen(I3_IPC_MAGIC)) {
614         DLOG("IPC: message too short, ignoring\n");
615         return;
616     }
617
618     if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
619         DLOG("IPC: message does not start with the IPC magic\n");
620         return;
621     }
622
623     uint8_t *message = (uint8_t*)buf;
624     while (n > 0) {
625         DLOG("IPC: n = %d\n", n);
626         message += strlen(I3_IPC_MAGIC);
627         n -= strlen(I3_IPC_MAGIC);
628
629         /* The next 32 bit after the magic are the message size */
630         uint32_t message_size;
631         memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
632         message += sizeof(uint32_t);
633         n -= sizeof(uint32_t);
634
635         if (message_size > n) {
636             DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
637             return;
638         }
639
640         /* The last 32 bits of the header are the message type */
641         uint32_t message_type;
642         memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
643         message += sizeof(uint32_t);
644         n -= sizeof(uint32_t);
645
646         if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
647             DLOG("Unhandled message type: %d\n", message_type);
648         else {
649             handler_t h = handlers[message_type];
650             h(w->fd, message, n, message_size, message_type);
651         }
652         n -= message_size;
653         message += message_size;
654     }
655 }
656
657 /*
658  * Handler for activity on the listening socket, meaning that a new client
659  * has just connected and we should accept() him. Sets up the event handler
660  * for activity on the new connection and inserts the file descriptor into
661  * the list of clients.
662  *
663  */
664 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
665     struct sockaddr_un peer;
666     socklen_t len = sizeof(struct sockaddr_un);
667     int client;
668     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
669         if (errno == EINTR)
670             return;
671         else perror("accept()");
672         return;
673     }
674
675     set_nonblock(client);
676
677     struct ev_io *package = scalloc(sizeof(struct ev_io));
678     ev_io_init(package, ipc_receive_message, client, EV_READ);
679     ev_io_start(EV_A_ package);
680
681     DLOG("IPC: new client connected\n");
682
683     ipc_client *new = scalloc(sizeof(ipc_client));
684     new->fd = client;
685
686     TAILQ_INSERT_TAIL(&all_clients, new, clients);
687 }
688
689 /*
690  * Creates the UNIX domain socket at the given path, sets it to non-blocking
691  * mode, bind()s and listen()s on it.
692  *
693  */
694 int ipc_create_socket(const char *filename) {
695     int sockfd;
696
697     FREE(current_socketpath);
698
699     char *resolved = resolve_tilde(filename);
700     DLOG("Creating IPC-socket at %s\n", resolved);
701     char *copy = sstrdup(resolved);
702     const char *dir = dirname(copy);
703     if (!path_exists(dir))
704         mkdirp(dir);
705     free(copy);
706
707     /* Unlink the unix domain socket before */
708     unlink(resolved);
709
710     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
711         perror("socket()");
712         free(resolved);
713         return -1;
714     }
715
716     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
717
718     struct sockaddr_un addr;
719     memset(&addr, 0, sizeof(struct sockaddr_un));
720     addr.sun_family = AF_LOCAL;
721     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
722     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
723         perror("bind()");
724         free(resolved);
725         return -1;
726     }
727
728     set_nonblock(sockfd);
729
730     if (listen(sockfd, 5) < 0) {
731         perror("listen()");
732         free(resolved);
733         return -1;
734     }
735
736     current_socketpath = resolved;
737     return sockfd;
738 }