2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
6 * © 2009-2011 Michael Stapelberg and contributors
8 * See file LICENSE for license information.
10 * ipc.c: Everything about the UNIX domain sockets for IPC
13 #include <sys/socket.h>
18 #include <yajl/yajl_gen.h>
19 #include <yajl/yajl_parse.h>
20 #include <yajl/yajl_version.h>
24 char *current_socketpath = NULL;
26 /* Shorter names for all those yajl_gen_* functions */
27 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
28 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
30 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
33 * Puts the given socket file descriptor into non-blocking mode or dies if
34 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
35 * IPC model because we should by no means block the window manager.
38 static void set_nonblock(int sockfd) {
39 int flags = fcntl(sockfd, F_GETFL, 0);
41 if (fcntl(sockfd, F_SETFL, flags) < 0)
42 err(-1, "Could not set O_NONBLOCK");
46 * Emulates mkdir -p (creates any missing folders)
49 static bool mkdirp(const char *path) {
50 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
52 if (errno != ENOENT) {
53 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
56 char *copy = strdup(path);
57 /* strip trailing slashes, if any */
58 while (copy[strlen(copy)-1] == '/')
59 copy[strlen(copy)-1] = '\0';
61 char *sep = strrchr(copy, '/');
69 result = mkdirp(path);
75 static void ipc_send_message(int fd, const unsigned char *payload,
76 int message_type, int message_size) {
77 int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
78 sizeof(uint32_t) + message_size;
79 char msg[buffer_size];
82 strncpy(walk, "i3-ipc", buffer_size - 1);
83 walk += strlen("i3-ipc");
84 memcpy(walk, &message_size, sizeof(uint32_t));
85 walk += sizeof(uint32_t);
86 memcpy(walk, &message_type, sizeof(uint32_t));
87 walk += sizeof(uint32_t);
88 memcpy(walk, payload, message_size);
91 int bytes_to_go = buffer_size;
92 while (sent_bytes < bytes_to_go) {
93 int n = write(fd, msg + sent_bytes, bytes_to_go);
95 DLOG("write() failed: %s\n", strerror(errno));
105 * Sends the specified event to all IPC clients which are currently connected
106 * and subscribed to this kind of event.
109 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
111 TAILQ_FOREACH(current, &all_clients, clients) {
112 /* see if this client is interested in this event */
113 bool interested = false;
114 for (int i = 0; i < current->num_events; i++) {
115 if (strcasecmp(current->events[i], event) != 0)
123 ipc_send_message(current->fd, (const unsigned char*)payload,
124 message_type, strlen(payload));
129 * Calls shutdown() on each socket and closes it. This function to be called
130 * when exiting or restarting only!
133 void ipc_shutdown() {
135 TAILQ_FOREACH(current, &all_clients, clients) {
136 shutdown(current->fd, SHUT_RDWR);
142 * Executes the command and returns whether it could be successfully parsed
143 * or not (at the moment, always returns true).
146 IPC_HANDLER(command) {
147 /* To get a properly terminated buffer, we copy
148 * message_size bytes out of the buffer */
149 char *command = scalloc(message_size + 1);
150 strncpy(command, (const char*)message, message_size);
151 LOG("IPC: received: *%s*\n", command);
152 char *reply = parse_cmd((const char*)command);
153 char *save_reply = reply;
156 /* If no reply was provided, we just use the default success message */
158 reply = "{\"success\":true}";
159 ipc_send_message(fd, (const unsigned char*)reply,
160 I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
165 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
175 y(integer, r.height);
179 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
182 y(integer, (long int)con);
185 y(integer, con->type);
188 switch (con->orientation) {
201 if (con->percent == 0.0)
203 else y(double, con->percent);
206 y(bool, con->urgent);
208 if (con->mark != NULL) {
214 y(bool, (con == focused));
217 switch (con->layout) {
236 switch (con->border_style) {
248 dump_rect(gen, "rect", con->rect);
249 dump_rect(gen, "window_rect", con->window_rect);
250 dump_rect(gen, "geometry", con->geometry);
253 if (con->window && con->window->name_json)
254 ystr(con->window->name_json);
258 if (con->type == CT_WORKSPACE) {
260 y(integer, con->num);
265 y(integer, con->window->id);
271 if (con->type != CT_DOCKAREA || !inplace_restart) {
272 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
273 dump_node(gen, node, inplace_restart);
278 ystr("floating_nodes");
280 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
281 dump_node(gen, node, inplace_restart);
287 TAILQ_FOREACH(node, &(con->focus_head), nodes) {
288 y(integer, (long int)node);
292 ystr("fullscreen_mode");
293 y(integer, con->fullscreen_mode);
298 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
299 if (match->dock != -1) {
302 y(integer, match->dock);
303 ystr("insert_where");
304 y(integer, match->insert_where);
308 /* TODO: the other swallow keys */
311 if (inplace_restart) {
312 if (con->window != NULL) {
315 y(integer, con->window->id);
325 setlocale(LC_NUMERIC, "C");
327 yajl_gen gen = yajl_gen_alloc(NULL);
329 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
331 dump_node(gen, croot, false);
332 setlocale(LC_NUMERIC, "");
334 const unsigned char *payload;
340 y(get_buf, &payload, &length);
342 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
348 * Formats the reply message for a GET_WORKSPACES request and sends it to the
352 IPC_HANDLER(get_workspaces) {
354 yajl_gen gen = yajl_gen_alloc(NULL);
356 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
360 Con *focused_ws = con_get_workspace(focused);
363 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
365 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
366 assert(ws->type == CT_WORKSPACE);
372 else y(integer, ws->num);
378 y(bool, workspace_is_visible(ws));
381 y(bool, ws == focused_ws);
386 y(integer, ws->rect.x);
388 y(integer, ws->rect.y);
390 y(integer, ws->rect.width);
392 y(integer, ws->rect.height);
407 const unsigned char *payload;
413 y(get_buf, &payload, &length);
415 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
420 * Formats the reply message for a GET_OUTPUTS request and sends it to the
424 IPC_HANDLER(get_outputs) {
426 yajl_gen gen = yajl_gen_alloc(NULL);
428 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
433 TAILQ_FOREACH(output, &outputs, outputs) {
440 y(bool, output->active);
445 y(integer, output->rect.x);
447 y(integer, output->rect.y);
449 y(integer, output->rect.width);
451 y(integer, output->rect.height);
454 ystr("current_workspace");
456 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
465 const unsigned char *payload;
471 y(get_buf, &payload, &length);
473 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
478 * Formats the reply message for a GET_MARKS request and sends it to the
482 IPC_HANDLER(get_marks) {
484 yajl_gen gen = yajl_gen_alloc(NULL);
486 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
491 TAILQ_FOREACH(con, &all_cons, all_cons)
492 if (con->mark != NULL)
497 const unsigned char *payload;
503 y(get_buf, &payload, &length);
505 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_MARKS, length);
510 * Callback for the YAJL parser (will be called when a string is parsed).
514 static int add_subscription(void *extra, const unsigned char *s,
517 static int add_subscription(void *extra, const unsigned char *s,
520 ipc_client *client = extra;
522 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
523 int event = client->num_events;
525 client->num_events++;
526 client->events = realloc(client->events, client->num_events * sizeof(char*));
527 /* We copy the string because it is not null-terminated and strndup()
528 * is missing on some BSD systems */
529 client->events[event] = scalloc(len+1);
530 memcpy(client->events[event], s, len);
532 DLOG("client is now subscribed to:\n");
533 for (int i = 0; i < client->num_events; i++)
534 DLOG("event %s\n", client->events[i]);
541 * Subscribes this connection to the event types which were given as a JSON
542 * serialized array in the payload field of the message.
545 IPC_HANDLER(subscribe) {
547 yajl_callbacks callbacks;
549 ipc_client *current, *client = NULL;
551 /* Search the ipc_client structure for this connection */
552 TAILQ_FOREACH(current, &all_clients, clients) {
553 if (current->fd != fd)
560 if (client == NULL) {
561 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
565 /* Setup the JSON parser */
566 memset(&callbacks, 0, sizeof(yajl_callbacks));
567 callbacks.yajl_string = add_subscription;
570 p = yajl_alloc(&callbacks, NULL, (void*)client);
572 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
574 stat = yajl_parse(p, (const unsigned char*)message, message_size);
575 if (stat != yajl_status_ok) {
577 err = yajl_get_error(p, true, (const unsigned char*)message,
579 ELOG("YAJL parse error: %s\n", err);
580 yajl_free_error(p, err);
582 const char *reply = "{\"success\":false}";
583 ipc_send_message(fd, (const unsigned char*)reply,
584 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
589 const char *reply = "{\"success\":true}";
590 ipc_send_message(fd, (const unsigned char*)reply,
591 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
594 /* The index of each callback function corresponds to the numeric
595 * value of the message type (see include/i3/ipc.h) */
596 handler_t handlers[6] = {
598 handle_get_workspaces,
606 * Handler for activity on a client connection, receives a message from a
609 * For now, the maximum message size is 2048. I’m not sure for what the
610 * IPC interface will be used in the future, thus I’m not implementing a
611 * mechanism for arbitrarily long messages, as it seems like overkill
615 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
617 int n = read(w->fd, buf, sizeof(buf));
619 /* On error or an empty message, we close the connection */
622 /* FIXME: I get these when closing a client socket,
623 * therefore we just treat them as an error. Is this
625 if (errno == EAGAIN || errno == EWOULDBLOCK)
629 /* If not, there was some kind of error. We don’t bother
630 * and close the connection */
633 /* Delete the client from the list of clients */
635 TAILQ_FOREACH(current, &all_clients, clients) {
636 if (current->fd != w->fd)
639 for (int i = 0; i < current->num_events; i++)
640 free(current->events[i]);
641 /* We can call TAILQ_REMOVE because we break out of the
642 * TAILQ_FOREACH afterwards */
643 TAILQ_REMOVE(&all_clients, current, clients);
649 DLOG("IPC: client disconnected\n");
653 /* Terminate the message correctly */
656 /* Check if the message starts with the i3 IPC magic code */
657 if (n < strlen(I3_IPC_MAGIC)) {
658 DLOG("IPC: message too short, ignoring\n");
662 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
663 DLOG("IPC: message does not start with the IPC magic\n");
667 uint8_t *message = (uint8_t*)buf;
669 DLOG("IPC: n = %d\n", n);
670 message += strlen(I3_IPC_MAGIC);
671 n -= strlen(I3_IPC_MAGIC);
673 /* The next 32 bit after the magic are the message size */
674 uint32_t message_size;
675 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
676 message += sizeof(uint32_t);
677 n -= sizeof(uint32_t);
679 if (message_size > n) {
680 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
684 /* The last 32 bits of the header are the message type */
685 uint32_t message_type;
686 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
687 message += sizeof(uint32_t);
688 n -= sizeof(uint32_t);
690 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
691 DLOG("Unhandled message type: %d\n", message_type);
693 handler_t h = handlers[message_type];
694 h(w->fd, message, n, message_size, message_type);
697 message += message_size;
702 * Handler for activity on the listening socket, meaning that a new client
703 * has just connected and we should accept() him. Sets up the event handler
704 * for activity on the new connection and inserts the file descriptor into
705 * the list of clients.
708 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
709 struct sockaddr_un peer;
710 socklen_t len = sizeof(struct sockaddr_un);
712 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
715 else perror("accept()");
719 set_nonblock(client);
721 struct ev_io *package = scalloc(sizeof(struct ev_io));
722 ev_io_init(package, ipc_receive_message, client, EV_READ);
723 ev_io_start(EV_A_ package);
725 DLOG("IPC: new client connected on fd %d\n", w->fd);
727 ipc_client *new = scalloc(sizeof(ipc_client));
730 TAILQ_INSERT_TAIL(&all_clients, new, clients);
734 * Creates the UNIX domain socket at the given path, sets it to non-blocking
735 * mode, bind()s and listen()s on it.
738 int ipc_create_socket(const char *filename) {
741 FREE(current_socketpath);
743 char *resolved = resolve_tilde(filename);
744 DLOG("Creating IPC-socket at %s\n", resolved);
745 char *copy = sstrdup(resolved);
746 const char *dir = dirname(copy);
747 if (!path_exists(dir))
751 /* Unlink the unix domain socket before */
754 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
760 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
762 struct sockaddr_un addr;
763 memset(&addr, 0, sizeof(struct sockaddr_un));
764 addr.sun_family = AF_LOCAL;
765 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
766 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
772 set_nonblock(sockfd);
774 if (listen(sockfd, 5) < 0) {
780 current_socketpath = resolved;