]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Merge branch 'master' into next
[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     if (con->mark != NULL) {
207         ystr("mark");
208         ystr(con->mark);
209     }
210
211     ystr("focused");
212     y(bool, (con == focused));
213
214     ystr("layout");
215     switch (con->layout) {
216         case L_DEFAULT:
217             ystr("default");
218             break;
219         case L_STACKED:
220             ystr("stacked");
221             break;
222         case L_TABBED:
223             ystr("tabbed");
224             break;
225         case L_DOCKAREA:
226             ystr("dockarea");
227             break;
228         case L_OUTPUT:
229             ystr("output");
230             break;
231     }
232
233     ystr("border");
234     switch (con->border_style) {
235         case BS_NORMAL:
236             ystr("normal");
237             break;
238         case BS_NONE:
239             ystr("none");
240             break;
241         case BS_1PIXEL:
242             ystr("1pixel");
243             break;
244     }
245
246     dump_rect(gen, "rect", con->rect);
247     dump_rect(gen, "window_rect", con->window_rect);
248     dump_rect(gen, "geometry", con->geometry);
249
250     ystr("name");
251     ystr(con->name);
252
253     if (con->type == CT_WORKSPACE) {
254         ystr("num");
255         y(integer, con->num);
256     }
257
258     ystr("window");
259     if (con->window)
260         y(integer, con->window->id);
261     else y(null);
262
263     ystr("nodes");
264     y(array_open);
265     Con *node;
266     if (con->type != CT_DOCKAREA || !inplace_restart) {
267         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
268             dump_node(gen, node, inplace_restart);
269         }
270     }
271     y(array_close);
272
273     ystr("floating_nodes");
274     y(array_open);
275     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
276         dump_node(gen, node, inplace_restart);
277     }
278     y(array_close);
279
280     ystr("focus");
281     y(array_open);
282     TAILQ_FOREACH(node, &(con->focus_head), nodes) {
283         y(integer, (long int)node);
284     }
285     y(array_close);
286
287     ystr("fullscreen_mode");
288     y(integer, con->fullscreen_mode);
289
290     ystr("swallows");
291     y(array_open);
292     Match *match;
293     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
294         if (match->dock != -1) {
295             y(map_open);
296             ystr("dock");
297             y(integer, match->dock);
298             ystr("insert_where");
299             y(integer, match->insert_where);
300             y(map_close);
301         }
302
303         /* TODO: the other swallow keys */
304     }
305
306     if (inplace_restart) {
307         if (con->window != NULL) {
308             y(map_open);
309             ystr("id");
310             y(integer, con->window->id);
311             y(map_close);
312         }
313     }
314     y(array_close);
315
316     y(map_close);
317 }
318
319 IPC_HANDLER(tree) {
320     setlocale(LC_NUMERIC, "C");
321 #if YAJL_MAJOR >= 2
322     yajl_gen gen = yajl_gen_alloc(NULL);
323 #else
324     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
325 #endif
326     dump_node(gen, croot, false);
327     setlocale(LC_NUMERIC, "");
328
329     const unsigned char *payload;
330 #if YAJL_MAJOR >= 2
331     size_t length;
332 #else
333     unsigned int length;
334 #endif
335     y(get_buf, &payload, &length);
336
337     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
338     y(free);
339 }
340
341
342 /*
343  * Formats the reply message for a GET_WORKSPACES request and sends it to the
344  * client
345  *
346  */
347 IPC_HANDLER(get_workspaces) {
348 #if YAJL_MAJOR >= 2
349     yajl_gen gen = yajl_gen_alloc(NULL);
350 #else
351     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
352 #endif
353     y(array_open);
354
355     Con *focused_ws = con_get_workspace(focused);
356
357     Con *output;
358     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
359         Con *ws;
360         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
361             assert(ws->type == CT_WORKSPACE);
362             y(map_open);
363
364             ystr("num");
365             if (ws->num == -1)
366                 y(null);
367             else y(integer, ws->num);
368
369             ystr("name");
370             ystr(ws->name);
371
372             ystr("visible");
373             y(bool, workspace_is_visible(ws));
374
375             ystr("focused");
376             y(bool, ws == focused_ws);
377
378             ystr("rect");
379             y(map_open);
380             ystr("x");
381             y(integer, ws->rect.x);
382             ystr("y");
383             y(integer, ws->rect.y);
384             ystr("width");
385             y(integer, ws->rect.width);
386             ystr("height");
387             y(integer, ws->rect.height);
388             y(map_close);
389
390             ystr("output");
391             ystr(output->name);
392
393             ystr("urgent");
394             y(bool, ws->urgent);
395
396             y(map_close);
397         }
398     }
399
400     y(array_close);
401
402     const unsigned char *payload;
403 #if YAJL_MAJOR >= 2
404     size_t length;
405 #else
406     unsigned int length;
407 #endif
408     y(get_buf, &payload, &length);
409
410     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
411     y(free);
412 }
413
414 /*
415  * Formats the reply message for a GET_OUTPUTS request and sends it to the
416  * client
417  *
418  */
419 IPC_HANDLER(get_outputs) {
420 #if YAJL_MAJOR >= 2
421     yajl_gen gen = yajl_gen_alloc(NULL);
422 #else
423     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
424 #endif
425     y(array_open);
426
427     Output *output;
428     TAILQ_FOREACH(output, &outputs, outputs) {
429         y(map_open);
430
431         ystr("name");
432         ystr(output->name);
433
434         ystr("active");
435         y(bool, output->active);
436
437         ystr("rect");
438         y(map_open);
439         ystr("x");
440         y(integer, output->rect.x);
441         ystr("y");
442         y(integer, output->rect.y);
443         ystr("width");
444         y(integer, output->rect.width);
445         ystr("height");
446         y(integer, output->rect.height);
447         y(map_close);
448
449         ystr("current_workspace");
450         Con *ws = NULL;
451         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
452             ystr(ws->name);
453         else y(null);
454
455         y(map_close);
456     }
457
458     y(array_close);
459
460     const unsigned char *payload;
461 #if YAJL_MAJOR >= 2
462     size_t length;
463 #else
464     unsigned int length;
465 #endif
466     y(get_buf, &payload, &length);
467
468     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
469     y(free);
470 }
471
472 /*
473  * Formats the reply message for a GET_MARKS request and sends it to the
474  * client
475  *
476  */
477 IPC_HANDLER(get_marks) {
478 #if YAJL_MAJOR >= 2
479     yajl_gen gen = yajl_gen_alloc(NULL);
480 #else
481     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
482 #endif
483     y(array_open);
484
485     Con *con;
486     TAILQ_FOREACH(con, &all_cons, all_cons)
487         if (con->mark != NULL)
488             ystr(con->mark);
489
490     y(array_close);
491
492     const unsigned char *payload;
493     unsigned int length;
494     y(get_buf, &payload, &length);
495
496     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_MARKS, length);
497     y(free);
498 }
499
500 /*
501  * Callback for the YAJL parser (will be called when a string is parsed).
502  *
503  */
504 #if YAJL_MAJOR < 2
505 static int add_subscription(void *extra, const unsigned char *s,
506                             unsigned int len) {
507 #else
508 static int add_subscription(void *extra, const unsigned char *s,
509                             size_t len) {
510 #endif
511     ipc_client *client = extra;
512
513     DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
514     int event = client->num_events;
515
516     client->num_events++;
517     client->events = realloc(client->events, client->num_events * sizeof(char*));
518     /* We copy the string because it is not null-terminated and strndup()
519      * is missing on some BSD systems */
520     client->events[event] = scalloc(len+1);
521     memcpy(client->events[event], s, len);
522
523     DLOG("client is now subscribed to:\n");
524     for (int i = 0; i < client->num_events; i++)
525         DLOG("event %s\n", client->events[i]);
526     DLOG("(done)\n");
527
528     return 1;
529 }
530
531 /*
532  * Subscribes this connection to the event types which were given as a JSON
533  * serialized array in the payload field of the message.
534  *
535  */
536 IPC_HANDLER(subscribe) {
537     yajl_handle p;
538     yajl_callbacks callbacks;
539     yajl_status stat;
540     ipc_client *current, *client = NULL;
541
542     /* Search the ipc_client structure for this connection */
543     TAILQ_FOREACH(current, &all_clients, clients) {
544         if (current->fd != fd)
545             continue;
546
547         client = current;
548         break;
549     }
550
551     if (client == NULL) {
552         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
553         return;
554     }
555
556     /* Setup the JSON parser */
557     memset(&callbacks, 0, sizeof(yajl_callbacks));
558     callbacks.yajl_string = add_subscription;
559
560 #if YAJL_MAJOR >= 2
561     p = yajl_alloc(&callbacks, NULL, (void*)client);
562 #else
563     p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
564 #endif
565     stat = yajl_parse(p, (const unsigned char*)message, message_size);
566     if (stat != yajl_status_ok) {
567         unsigned char *err;
568         err = yajl_get_error(p, true, (const unsigned char*)message,
569                              message_size);
570         ELOG("YAJL parse error: %s\n", err);
571         yajl_free_error(p, err);
572
573         const char *reply = "{\"success\":false}";
574         ipc_send_message(fd, (const unsigned char*)reply,
575                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
576         yajl_free(p);
577         return;
578     }
579     yajl_free(p);
580     const char *reply = "{\"success\":true}";
581     ipc_send_message(fd, (const unsigned char*)reply,
582                      I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
583 }
584
585 /* The index of each callback function corresponds to the numeric
586  * value of the message type (see include/i3/ipc.h) */
587 handler_t handlers[6] = {
588     handle_command,
589     handle_get_workspaces,
590     handle_subscribe,
591     handle_get_outputs,
592     handle_tree,
593     handle_get_marks
594 };
595
596 /*
597  * Handler for activity on a client connection, receives a message from a
598  * client.
599  *
600  * For now, the maximum message size is 2048. I’m not sure for what the
601  * IPC interface will be used in the future, thus I’m not implementing a
602  * mechanism for arbitrarily long messages, as it seems like overkill
603  * at the moment.
604  *
605  */
606 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
607     char buf[2048];
608     int n = read(w->fd, buf, sizeof(buf));
609
610     /* On error or an empty message, we close the connection */
611     if (n <= 0) {
612 #if 0
613         /* FIXME: I get these when closing a client socket,
614          * therefore we just treat them as an error. Is this
615          * correct? */
616         if (errno == EAGAIN || errno == EWOULDBLOCK)
617                 return;
618 #endif
619
620         /* If not, there was some kind of error. We don’t bother
621          * and close the connection */
622         close(w->fd);
623
624         /* Delete the client from the list of clients */
625         ipc_client *current;
626         TAILQ_FOREACH(current, &all_clients, clients) {
627             if (current->fd != w->fd)
628                 continue;
629
630             for (int i = 0; i < current->num_events; i++)
631                 free(current->events[i]);
632             /* We can call TAILQ_REMOVE because we break out of the
633              * TAILQ_FOREACH afterwards */
634             TAILQ_REMOVE(&all_clients, current, clients);
635             break;
636         }
637
638         ev_io_stop(EV_A_ w);
639
640         DLOG("IPC: client disconnected\n");
641         return;
642     }
643
644     /* Terminate the message correctly */
645     buf[n] = '\0';
646
647     /* Check if the message starts with the i3 IPC magic code */
648     if (n < strlen(I3_IPC_MAGIC)) {
649         DLOG("IPC: message too short, ignoring\n");
650         return;
651     }
652
653     if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
654         DLOG("IPC: message does not start with the IPC magic\n");
655         return;
656     }
657
658     uint8_t *message = (uint8_t*)buf;
659     while (n > 0) {
660         DLOG("IPC: n = %d\n", n);
661         message += strlen(I3_IPC_MAGIC);
662         n -= strlen(I3_IPC_MAGIC);
663
664         /* The next 32 bit after the magic are the message size */
665         uint32_t message_size;
666         memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
667         message += sizeof(uint32_t);
668         n -= sizeof(uint32_t);
669
670         if (message_size > n) {
671             DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
672             return;
673         }
674
675         /* The last 32 bits of the header are the message type */
676         uint32_t message_type;
677         memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
678         message += sizeof(uint32_t);
679         n -= sizeof(uint32_t);
680
681         if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
682             DLOG("Unhandled message type: %d\n", message_type);
683         else {
684             handler_t h = handlers[message_type];
685             h(w->fd, message, n, message_size, message_type);
686         }
687         n -= message_size;
688         message += message_size;
689     }
690 }
691
692 /*
693  * Handler for activity on the listening socket, meaning that a new client
694  * has just connected and we should accept() him. Sets up the event handler
695  * for activity on the new connection and inserts the file descriptor into
696  * the list of clients.
697  *
698  */
699 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
700     struct sockaddr_un peer;
701     socklen_t len = sizeof(struct sockaddr_un);
702     int client;
703     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
704         if (errno == EINTR)
705             return;
706         else perror("accept()");
707         return;
708     }
709
710     set_nonblock(client);
711
712     struct ev_io *package = scalloc(sizeof(struct ev_io));
713     ev_io_init(package, ipc_receive_message, client, EV_READ);
714     ev_io_start(EV_A_ package);
715
716     DLOG("IPC: new client connected on fd %d\n", w->fd);
717
718     ipc_client *new = scalloc(sizeof(ipc_client));
719     new->fd = client;
720
721     TAILQ_INSERT_TAIL(&all_clients, new, clients);
722 }
723
724 /*
725  * Creates the UNIX domain socket at the given path, sets it to non-blocking
726  * mode, bind()s and listen()s on it.
727  *
728  */
729 int ipc_create_socket(const char *filename) {
730     int sockfd;
731
732     FREE(current_socketpath);
733
734     char *resolved = resolve_tilde(filename);
735     DLOG("Creating IPC-socket at %s\n", resolved);
736     char *copy = sstrdup(resolved);
737     const char *dir = dirname(copy);
738     if (!path_exists(dir))
739         mkdirp(dir);
740     free(copy);
741
742     /* Unlink the unix domain socket before */
743     unlink(resolved);
744
745     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
746         perror("socket()");
747         free(resolved);
748         return -1;
749     }
750
751     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
752
753     struct sockaddr_un addr;
754     memset(&addr, 0, sizeof(struct sockaddr_un));
755     addr.sun_family = AF_LOCAL;
756     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
757     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
758         perror("bind()");
759         free(resolved);
760         return -1;
761     }
762
763     set_nonblock(sockfd);
764
765     if (listen(sockfd, 5) < 0) {
766         perror("listen()");
767         free(resolved);
768         return -1;
769     }
770
771     current_socketpath = resolved;
772     return sockfd;
773 }