]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
x: recurse x_push_node in focus order. reduces flickering when switching workspaces
[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-2010 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
21 #include "all.h"
22
23 char *current_socketpath = NULL;
24
25 /* Shorter names for all those yajl_gen_* functions */
26 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
27 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
28
29 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
30
31 /*
32  * Puts the given socket file descriptor into non-blocking mode or dies if
33  * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
34  * IPC model because we should by no means block the window manager.
35  *
36  */
37 static void set_nonblock(int sockfd) {
38     int flags = fcntl(sockfd, F_GETFL, 0);
39     flags |= O_NONBLOCK;
40     if (fcntl(sockfd, F_SETFL, flags) < 0)
41         err(-1, "Could not set O_NONBLOCK");
42 }
43
44 /*
45  * Emulates mkdir -p (creates any missing folders)
46  *
47  */
48 static bool mkdirp(const char *path) {
49     if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
50         return true;
51     if (errno != ENOENT) {
52         ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
53         return false;
54     }
55     char *copy = strdup(path);
56     /* strip trailing slashes, if any */
57     while (copy[strlen(copy)-1] == '/')
58         copy[strlen(copy)-1] = '\0';
59
60     char *sep = strrchr(copy, '/');
61     if (sep == NULL)
62         return false;
63     *sep = '\0';
64     bool result = false;
65     if (mkdirp(copy))
66         result = mkdirp(path);
67     free(copy);
68
69     return result;
70 }
71
72 static void ipc_send_message(int fd, const unsigned char *payload,
73                              int message_type, int message_size) {
74     int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
75                       sizeof(uint32_t) + message_size;
76     char msg[buffer_size];
77     char *walk = msg;
78
79     strcpy(walk, "i3-ipc");
80     walk += strlen("i3-ipc");
81     memcpy(walk, &message_size, sizeof(uint32_t));
82     walk += sizeof(uint32_t);
83     memcpy(walk, &message_type, sizeof(uint32_t));
84     walk += sizeof(uint32_t);
85     memcpy(walk, payload, message_size);
86
87     int sent_bytes = 0;
88     int bytes_to_go = buffer_size;
89     while (sent_bytes < bytes_to_go) {
90         int n = write(fd, msg + sent_bytes, bytes_to_go);
91         if (n == -1) {
92             DLOG("write() failed: %s\n", strerror(errno));
93             return;
94         }
95
96         sent_bytes += n;
97         bytes_to_go -= n;
98     }
99 }
100
101 /*
102  * Sends the specified event to all IPC clients which are currently connected
103  * and subscribed to this kind of event.
104  *
105  */
106 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
107     ipc_client *current;
108     TAILQ_FOREACH(current, &all_clients, clients) {
109         /* see if this client is interested in this event */
110         bool interested = false;
111         for (int i = 0; i < current->num_events; i++) {
112             if (strcasecmp(current->events[i], event) != 0)
113                 continue;
114             interested = true;
115             break;
116         }
117         if (!interested)
118             continue;
119
120         ipc_send_message(current->fd, (const unsigned char*)payload,
121                          message_type, strlen(payload));
122     }
123 }
124
125 /*
126  * Calls shutdown() on each socket and closes it. This function to be called
127  * when exiting or restarting only!
128  *
129  */
130 void ipc_shutdown() {
131     ipc_client *current;
132     TAILQ_FOREACH(current, &all_clients, clients) {
133         shutdown(current->fd, SHUT_RDWR);
134         close(current->fd);
135     }
136 }
137
138 /*
139  * Executes the command and returns whether it could be successfully parsed
140  * or not (at the moment, always returns true).
141  *
142  */
143 IPC_HANDLER(command) {
144     /* To get a properly terminated buffer, we copy
145      * message_size bytes out of the buffer */
146     char *command = scalloc(message_size + 1);
147     strncpy(command, (const char*)message, message_size);
148     LOG("IPC: received: *%s*\n", command);
149     const char *reply = parse_cmd((const char*)command);
150     tree_render();
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     y(integer, con->layout);
206
207     ystr("border");
208     y(integer, con->border_style);
209
210     dump_rect(gen, "rect", con->rect);
211     dump_rect(gen, "window_rect", con->window_rect);
212     dump_rect(gen, "geometry", con->geometry);
213
214     ystr("name");
215     ystr(con->name);
216
217     if (con->type == CT_WORKSPACE) {
218         ystr("num");
219         y(integer, con->num);
220     }
221
222     ystr("window");
223     if (con->window)
224         y(integer, con->window->id);
225     else y(null);
226
227     ystr("nodes");
228     y(array_open);
229     Con *node;
230     if (con->type != CT_DOCKAREA || !inplace_restart) {
231         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
232             dump_node(gen, node, inplace_restart);
233         }
234     }
235     y(array_close);
236
237     ystr("floating_nodes");
238     y(array_open);
239     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
240         dump_node(gen, node, inplace_restart);
241     }
242     y(array_close);
243
244     ystr("focus");
245     y(array_open);
246     TAILQ_FOREACH(node, &(con->focus_head), nodes) {
247         y(integer, (long int)node);
248     }
249     y(array_close);
250
251     ystr("fullscreen_mode");
252     y(integer, con->fullscreen_mode);
253
254     ystr("swallows");
255     y(array_open);
256     Match *match;
257     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
258         if (match->dock != -1) {
259             y(map_open);
260             ystr("dock");
261             y(integer, match->dock);
262             ystr("insert_where");
263             y(integer, match->insert_where);
264             y(map_close);
265         }
266
267         /* TODO: the other swallow keys */
268     }
269
270     if (inplace_restart) {
271         if (con->window != NULL) {
272             y(map_open);
273             ystr("id");
274             y(integer, con->window->id);
275             y(map_close);
276         }
277     }
278     y(array_close);
279
280     y(map_close);
281 }
282
283 IPC_HANDLER(tree) {
284     setlocale(LC_NUMERIC, "C");
285     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
286     dump_node(gen, croot, false);
287     setlocale(LC_NUMERIC, "");
288
289     const unsigned char *payload;
290     unsigned int length;
291     y(get_buf, &payload, &length);
292
293     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
294     y(free);
295 }
296
297 /*
298  * Formats the reply message for a GET_WORKSPACES request and sends it to the
299  * client
300  *
301  */
302 IPC_HANDLER(get_workspaces) {
303     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
304     y(array_open);
305
306     Con *focused_ws = con_get_workspace(focused);
307
308     Con *output;
309     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
310         Con *ws;
311         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
312             assert(ws->type == CT_WORKSPACE);
313             y(map_open);
314
315             ystr("num");
316             if (ws->num == -1)
317                 y(null);
318             else y(integer, ws->num);
319
320             ystr("name");
321             ystr(ws->name);
322
323             ystr("visible");
324             y(bool, workspace_is_visible(ws));
325
326             ystr("focused");
327             y(bool, ws == focused_ws);
328
329             ystr("rect");
330             y(map_open);
331             ystr("x");
332             y(integer, ws->rect.x);
333             ystr("y");
334             y(integer, ws->rect.y);
335             ystr("width");
336             y(integer, ws->rect.width);
337             ystr("height");
338             y(integer, ws->rect.height);
339             y(map_close);
340
341             ystr("output");
342             ystr(output->name);
343
344             ystr("urgent");
345             y(bool, ws->urgent);
346
347             y(map_close);
348         }
349     }
350
351     y(array_close);
352
353     const unsigned char *payload;
354     unsigned int length;
355     y(get_buf, &payload, &length);
356
357     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
358     y(free);
359 }
360
361 /*
362  * Formats the reply message for a GET_OUTPUTS request and sends it to the
363  * client
364  *
365  */
366 IPC_HANDLER(get_outputs) {
367     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
368     y(array_open);
369
370     Output *output;
371     TAILQ_FOREACH(output, &outputs, outputs) {
372         y(map_open);
373
374         ystr("name");
375         ystr(output->name);
376
377         ystr("active");
378         y(bool, output->active);
379
380         ystr("rect");
381         y(map_open);
382         ystr("x");
383         y(integer, output->rect.x);
384         ystr("y");
385         y(integer, output->rect.y);
386         ystr("width");
387         y(integer, output->rect.width);
388         ystr("height");
389         y(integer, output->rect.height);
390         y(map_close);
391
392         ystr("current_workspace");
393         Con *ws = NULL;
394         if (output->con && (ws = con_get_fullscreen_con(output->con)))
395             ystr(ws->name);
396         else y(null);
397
398         y(map_close);
399     }
400
401     y(array_close);
402
403     const unsigned char *payload;
404     unsigned int length;
405     y(get_buf, &payload, &length);
406
407     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
408     y(free);
409 }
410
411 /*
412  * Callback for the YAJL parser (will be called when a string is parsed).
413  *
414  */
415 static int add_subscription(void *extra, const unsigned char *s,
416                             unsigned int len) {
417     ipc_client *client = extra;
418
419     DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
420     int event = client->num_events;
421
422     client->num_events++;
423     client->events = realloc(client->events, client->num_events * sizeof(char*));
424     /* We copy the string because it is not null-terminated and strndup()
425      * is missing on some BSD systems */
426     client->events[event] = scalloc(len+1);
427     memcpy(client->events[event], s, len);
428
429     DLOG("client is now subscribed to:\n");
430     for (int i = 0; i < client->num_events; i++)
431         DLOG("event %s\n", client->events[i]);
432     DLOG("(done)\n");
433
434     return 1;
435 }
436
437 /*
438  * Subscribes this connection to the event types which were given as a JSON
439  * serialized array in the payload field of the message.
440  *
441  */
442 IPC_HANDLER(subscribe) {
443     yajl_handle p;
444     yajl_callbacks callbacks;
445     yajl_status stat;
446     ipc_client *current, *client = NULL;
447
448     /* Search the ipc_client structure for this connection */
449     TAILQ_FOREACH(current, &all_clients, clients) {
450         if (current->fd != fd)
451             continue;
452
453         client = current;
454         break;
455     }
456
457     if (client == NULL) {
458         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
459         return;
460     }
461
462     /* Setup the JSON parser */
463     memset(&callbacks, 0, sizeof(yajl_callbacks));
464     callbacks.yajl_string = add_subscription;
465
466     p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
467     stat = yajl_parse(p, (const unsigned char*)message, message_size);
468     if (stat != yajl_status_ok) {
469         unsigned char *err;
470         err = yajl_get_error(p, true, (const unsigned char*)message,
471                              message_size);
472         ELOG("YAJL parse error: %s\n", err);
473         yajl_free_error(p, err);
474
475         const char *reply = "{\"success\":false}";
476         ipc_send_message(fd, (const unsigned char*)reply,
477                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
478         yajl_free(p);
479         return;
480     }
481     yajl_free(p);
482     const char *reply = "{\"success\":true}";
483     ipc_send_message(fd, (const unsigned char*)reply,
484                      I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
485 }
486
487 /* The index of each callback function corresponds to the numeric
488  * value of the message type (see include/i3/ipc.h) */
489 handler_t handlers[5] = {
490     handle_command,
491     handle_get_workspaces,
492     handle_subscribe,
493     handle_get_outputs,
494     handle_tree
495 };
496
497 /*
498  * Handler for activity on a client connection, receives a message from a
499  * client.
500  *
501  * For now, the maximum message size is 2048. I’m not sure for what the
502  * IPC interface will be used in the future, thus I’m not implementing a
503  * mechanism for arbitrarily long messages, as it seems like overkill
504  * at the moment.
505  *
506  */
507 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
508     char buf[2048];
509     int n = read(w->fd, buf, sizeof(buf));
510
511     /* On error or an empty message, we close the connection */
512     if (n <= 0) {
513 #if 0
514         /* FIXME: I get these when closing a client socket,
515          * therefore we just treat them as an error. Is this
516          * correct? */
517         if (errno == EAGAIN || errno == EWOULDBLOCK)
518                 return;
519 #endif
520
521         /* If not, there was some kind of error. We don’t bother
522          * and close the connection */
523         close(w->fd);
524
525         /* Delete the client from the list of clients */
526         ipc_client *current;
527         TAILQ_FOREACH(current, &all_clients, clients) {
528             if (current->fd != w->fd)
529                 continue;
530
531             for (int i = 0; i < current->num_events; i++)
532                 free(current->events[i]);
533             /* We can call TAILQ_REMOVE because we break out of the
534              * TAILQ_FOREACH afterwards */
535             TAILQ_REMOVE(&all_clients, current, clients);
536             break;
537         }
538
539         ev_io_stop(EV_A_ w);
540
541         DLOG("IPC: client disconnected\n");
542         return;
543     }
544
545     /* Terminate the message correctly */
546     buf[n] = '\0';
547
548     /* Check if the message starts with the i3 IPC magic code */
549     if (n < strlen(I3_IPC_MAGIC)) {
550         DLOG("IPC: message too short, ignoring\n");
551         return;
552     }
553
554     if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
555         DLOG("IPC: message does not start with the IPC magic\n");
556         return;
557     }
558
559     uint8_t *message = (uint8_t*)buf;
560     while (n > 0) {
561         DLOG("IPC: n = %d\n", n);
562         message += strlen(I3_IPC_MAGIC);
563         n -= strlen(I3_IPC_MAGIC);
564
565         /* The next 32 bit after the magic are the message size */
566         uint32_t message_size = *((uint32_t*)message);
567         message += sizeof(uint32_t);
568         n -= sizeof(uint32_t);
569
570         if (message_size > n) {
571             DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
572             return;
573         }
574
575         /* The last 32 bits of the header are the message type */
576         uint32_t message_type = *((uint32_t*)message);
577         message += sizeof(uint32_t);
578         n -= sizeof(uint32_t);
579
580         if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
581             DLOG("Unhandled message type: %d\n", message_type);
582         else {
583             handler_t h = handlers[message_type];
584             h(w->fd, message, n, message_size, message_type);
585         }
586         n -= message_size;
587         message += message_size;
588     }
589 }
590
591 /*
592  * Handler for activity on the listening socket, meaning that a new client
593  * has just connected and we should accept() him. Sets up the event handler
594  * for activity on the new connection and inserts the file descriptor into
595  * the list of clients.
596  *
597  */
598 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
599     struct sockaddr_un peer;
600     socklen_t len = sizeof(struct sockaddr_un);
601     int client;
602     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
603         if (errno == EINTR)
604             return;
605         else perror("accept()");
606         return;
607     }
608
609     set_nonblock(client);
610
611     struct ev_io *package = scalloc(sizeof(struct ev_io));
612     ev_io_init(package, ipc_receive_message, client, EV_READ);
613     ev_io_start(EV_A_ package);
614
615     DLOG("IPC: new client connected\n");
616
617     ipc_client *new = scalloc(sizeof(ipc_client));
618     new->fd = client;
619
620     TAILQ_INSERT_TAIL(&all_clients, new, clients);
621 }
622
623 /*
624  * Creates the UNIX domain socket at the given path, sets it to non-blocking
625  * mode, bind()s and listen()s on it.
626  *
627  */
628 int ipc_create_socket(const char *filename) {
629     int sockfd;
630
631     FREE(current_socketpath);
632
633     char *resolved = resolve_tilde(filename);
634     DLOG("Creating IPC-socket at %s\n", resolved);
635     char *copy = sstrdup(resolved);
636     const char *dir = dirname(copy);
637     if (!path_exists(dir))
638         mkdirp(dir);
639     free(copy);
640
641     /* Unlink the unix domain socket before */
642     unlink(resolved);
643
644     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
645         perror("socket()");
646         free(resolved);
647         return -1;
648     }
649
650     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
651
652     struct sockaddr_un addr;
653     memset(&addr, 0, sizeof(struct sockaddr_un));
654     addr.sun_family = AF_LOCAL;
655     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
656     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
657         perror("bind()");
658         free(resolved);
659         return -1;
660     }
661
662     set_nonblock(sockfd);
663
664     if (listen(sockfd, 5) < 0) {
665         perror("listen()");
666         free(resolved);
667         return -1;
668     }
669
670     current_socketpath = resolved;
671     return sockfd;
672 }