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