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