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