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