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