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