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