]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Bugfix: store and properly load workspace order when restarting
[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     y(integer, con->orientation);
182
183     ystr("percent");
184     y(double, con->percent);
185
186     ystr("urgent");
187     y(integer, con->urgent);
188
189     ystr("focused");
190     y(integer, (con == focused));
191
192     ystr("layout");
193     y(integer, con->layout);
194
195     ystr("border");
196     y(integer, con->border_style);
197
198     dump_rect(gen, "rect", con->rect);
199     dump_rect(gen, "window_rect", con->window_rect);
200
201     ystr("name");
202     ystr(con->name);
203
204     if (con->type == CT_WORKSPACE) {
205         ystr("num");
206         y(integer, con->num);
207     }
208
209     ystr("window");
210     if (con->window)
211         y(integer, con->window->id);
212     else y(null);
213
214     ystr("nodes");
215     y(array_open);
216     Con *node;
217     TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
218         dump_node(gen, node, inplace_restart);
219     }
220     y(array_close);
221
222     ystr("floating_nodes");
223     y(array_open);
224     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
225         dump_node(gen, node, inplace_restart);
226     }
227     y(array_close);
228
229     ystr("focus");
230     y(array_open);
231     TAILQ_FOREACH(node, &(con->focus_head), nodes) {
232         y(integer, (long int)node);
233     }
234     y(array_close);
235
236     ystr("fullscreen_mode");
237     y(integer, con->fullscreen_mode);
238
239     if (inplace_restart) {
240         if (con->window != NULL) {
241             ystr("swallows");
242             y(array_open);
243             y(map_open);
244             ystr("id");
245             y(integer, con->window->id);
246             y(map_close);
247             y(array_close);
248         }
249     }
250
251     y(map_close);
252 }
253
254 IPC_HANDLER(tree) {
255     setlocale(LC_NUMERIC, "C");
256     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
257     dump_node(gen, croot, false);
258     setlocale(LC_NUMERIC, "");
259
260     const unsigned char *payload;
261     unsigned int length;
262     y(get_buf, &payload, &length);
263
264     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
265     y(free);
266 }
267
268 /*
269  * Formats the reply message for a GET_WORKSPACES request and sends it to the
270  * client
271  *
272  */
273 IPC_HANDLER(get_workspaces) {
274     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
275     y(array_open);
276
277     Con *focused_ws = con_get_workspace(focused);
278
279     Con *output;
280     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
281         Con *ws;
282         TAILQ_FOREACH(ws, &(output->nodes_head), nodes) {
283             assert(ws->type == CT_WORKSPACE);
284             y(map_open);
285
286             ystr("num");
287             if (ws->num == -1)
288                 y(null);
289             else y(integer, ws->num);
290
291             ystr("name");
292             ystr(ws->name);
293
294             ystr("visible");
295             y(bool, workspace_is_visible(ws));
296
297             ystr("focused");
298             y(bool, ws == focused_ws);
299
300             ystr("rect");
301             y(map_open);
302             ystr("x");
303             y(integer, ws->rect.x);
304             ystr("y");
305             y(integer, ws->rect.y);
306             ystr("width");
307             y(integer, ws->rect.width);
308             ystr("height");
309             y(integer, ws->rect.height);
310             y(map_close);
311
312             ystr("output");
313             ystr(output->name);
314
315             ystr("urgent");
316             y(bool, ws->urgent);
317
318             y(map_close);
319         }
320     }
321
322     y(array_close);
323
324     const unsigned char *payload;
325     unsigned int length;
326     y(get_buf, &payload, &length);
327
328     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
329     y(free);
330 }
331
332 /*
333  * Formats the reply message for a GET_OUTPUTS request and sends it to the
334  * client
335  *
336  */
337 IPC_HANDLER(get_outputs) {
338     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
339     y(array_open);
340
341     Output *output;
342     TAILQ_FOREACH(output, &outputs, outputs) {
343         y(map_open);
344
345         ystr("name");
346         ystr(output->name);
347
348         ystr("active");
349         y(bool, output->active);
350
351         ystr("rect");
352         y(map_open);
353         ystr("x");
354         y(integer, output->rect.x);
355         ystr("y");
356         y(integer, output->rect.y);
357         ystr("width");
358         y(integer, output->rect.width);
359         ystr("height");
360         y(integer, output->rect.height);
361         y(map_close);
362
363         ystr("current_workspace");
364         Con *ws = NULL;
365         if (output->con && (ws = con_get_fullscreen_con(output->con)))
366             ystr(ws->name);
367         else y(null);
368
369         y(map_close);
370     }
371
372     y(array_close);
373
374     const unsigned char *payload;
375     unsigned int length;
376     y(get_buf, &payload, &length);
377
378     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
379     y(free);
380 }
381
382 /*
383  * Callback for the YAJL parser (will be called when a string is parsed).
384  *
385  */
386 static int add_subscription(void *extra, const unsigned char *s,
387                             unsigned int len) {
388     ipc_client *client = extra;
389
390     DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
391     int event = client->num_events;
392
393     client->num_events++;
394     client->events = realloc(client->events, client->num_events * sizeof(char*));
395     /* We copy the string because it is not null-terminated and strndup()
396      * is missing on some BSD systems */
397     client->events[event] = scalloc(len+1);
398     memcpy(client->events[event], s, len);
399
400     DLOG("client is now subscribed to:\n");
401     for (int i = 0; i < client->num_events; i++)
402         DLOG("event %s\n", client->events[i]);
403     DLOG("(done)\n");
404
405     return 1;
406 }
407
408 /*
409  * Subscribes this connection to the event types which were given as a JSON
410  * serialized array in the payload field of the message.
411  *
412  */
413 IPC_HANDLER(subscribe) {
414     yajl_handle p;
415     yajl_callbacks callbacks;
416     yajl_status stat;
417     ipc_client *current, *client = NULL;
418
419     /* Search the ipc_client structure for this connection */
420     TAILQ_FOREACH(current, &all_clients, clients) {
421         if (current->fd != fd)
422             continue;
423
424         client = current;
425         break;
426     }
427
428     if (client == NULL) {
429         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
430         return;
431     }
432
433     /* Setup the JSON parser */
434     memset(&callbacks, 0, sizeof(yajl_callbacks));
435     callbacks.yajl_string = add_subscription;
436
437     p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
438     stat = yajl_parse(p, (const unsigned char*)message, message_size);
439     if (stat != yajl_status_ok) {
440         unsigned char *err;
441         err = yajl_get_error(p, true, (const unsigned char*)message,
442                              message_size);
443         ELOG("YAJL parse error: %s\n", err);
444         yajl_free_error(p, err);
445
446         const char *reply = "{\"success\":false}";
447         ipc_send_message(fd, (const unsigned char*)reply,
448                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
449         yajl_free(p);
450         return;
451     }
452     yajl_free(p);
453     const char *reply = "{\"success\":true}";
454     ipc_send_message(fd, (const unsigned char*)reply,
455                      I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
456 }
457
458 /* The index of each callback function corresponds to the numeric
459  * value of the message type (see include/i3/ipc.h) */
460 handler_t handlers[5] = {
461     handle_command,
462     handle_get_workspaces,
463     handle_subscribe,
464     handle_get_outputs,
465     handle_tree
466 };
467
468 /*
469  * Handler for activity on a client connection, receives a message from a
470  * client.
471  *
472  * For now, the maximum message size is 2048. I’m not sure for what the
473  * IPC interface will be used in the future, thus I’m not implementing a
474  * mechanism for arbitrarily long messages, as it seems like overkill
475  * at the moment.
476  *
477  */
478 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
479     char buf[2048];
480     int n = read(w->fd, buf, sizeof(buf));
481
482     /* On error or an empty message, we close the connection */
483     if (n <= 0) {
484 #if 0
485         /* FIXME: I get these when closing a client socket,
486          * therefore we just treat them as an error. Is this
487          * correct? */
488         if (errno == EAGAIN || errno == EWOULDBLOCK)
489                 return;
490 #endif
491
492         /* If not, there was some kind of error. We don’t bother
493          * and close the connection */
494         close(w->fd);
495
496         /* Delete the client from the list of clients */
497         ipc_client *current;
498         TAILQ_FOREACH(current, &all_clients, clients) {
499             if (current->fd != w->fd)
500                 continue;
501
502             for (int i = 0; i < current->num_events; i++)
503                 free(current->events[i]);
504             /* We can call TAILQ_REMOVE because we break out of the
505              * TAILQ_FOREACH afterwards */
506             TAILQ_REMOVE(&all_clients, current, clients);
507             break;
508         }
509
510         ev_io_stop(EV_A_ w);
511
512         DLOG("IPC: client disconnected\n");
513         return;
514     }
515
516     /* Terminate the message correctly */
517     buf[n] = '\0';
518
519     /* Check if the message starts with the i3 IPC magic code */
520     if (n < strlen(I3_IPC_MAGIC)) {
521         DLOG("IPC: message too short, ignoring\n");
522         return;
523     }
524
525     if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
526         DLOG("IPC: message does not start with the IPC magic\n");
527         return;
528     }
529
530     uint8_t *message = (uint8_t*)buf;
531     while (n > 0) {
532         DLOG("IPC: n = %d\n", n);
533         message += strlen(I3_IPC_MAGIC);
534         n -= strlen(I3_IPC_MAGIC);
535
536         /* The next 32 bit after the magic are the message size */
537         uint32_t message_size = *((uint32_t*)message);
538         message += sizeof(uint32_t);
539         n -= sizeof(uint32_t);
540
541         if (message_size > n) {
542             DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
543             return;
544         }
545
546         /* The last 32 bits of the header are the message type */
547         uint32_t message_type = *((uint32_t*)message);
548         message += sizeof(uint32_t);
549         n -= sizeof(uint32_t);
550
551         if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
552             DLOG("Unhandled message type: %d\n", message_type);
553         else {
554             handler_t h = handlers[message_type];
555             h(w->fd, message, n, message_size, message_type);
556         }
557         n -= message_size;
558         message += message_size;
559     }
560 }
561
562 /*
563  * Handler for activity on the listening socket, meaning that a new client
564  * has just connected and we should accept() him. Sets up the event handler
565  * for activity on the new connection and inserts the file descriptor into
566  * the list of clients.
567  *
568  */
569 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
570     struct sockaddr_un peer;
571     socklen_t len = sizeof(struct sockaddr_un);
572     int client;
573     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
574         if (errno == EINTR)
575             return;
576         else perror("accept()");
577         return;
578     }
579
580     set_nonblock(client);
581
582     struct ev_io *package = scalloc(sizeof(struct ev_io));
583     ev_io_init(package, ipc_receive_message, client, EV_READ);
584     ev_io_start(EV_A_ package);
585
586     DLOG("IPC: new client connected\n");
587
588     ipc_client *new = scalloc(sizeof(ipc_client));
589     new->fd = client;
590
591     TAILQ_INSERT_TAIL(&all_clients, new, clients);
592 }
593
594 /*
595  * Creates the UNIX domain socket at the given path, sets it to non-blocking
596  * mode, bind()s and listen()s on it.
597  *
598  */
599 int ipc_create_socket(const char *filename) {
600     int sockfd;
601
602     char *resolved = resolve_tilde(filename);
603     DLOG("Creating IPC-socket at %s\n", resolved);
604     char *copy = sstrdup(resolved);
605     const char *dir = dirname(copy);
606     if (!path_exists(dir))
607         mkdirp(dir);
608     free(copy);
609
610     /* Unlink the unix domain socket before */
611     unlink(resolved);
612
613     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
614         perror("socket()");
615         free(resolved);
616         return -1;
617     }
618
619     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
620
621     struct sockaddr_un addr;
622     memset(&addr, 0, sizeof(struct sockaddr_un));
623     addr.sun_family = AF_LOCAL;
624     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
625     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
626         perror("bind()");
627         free(resolved);
628         return -1;
629     }
630
631     free(resolved);
632     set_nonblock(sockfd);
633
634     if (listen(sockfd, 5) < 0) {
635         perror("listen()");
636         return -1;
637     }
638
639     return sockfd;
640 }