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