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);
209 y(bool, (con == focused));
212 switch (con->layout) {
231 switch (con->border_style) {
243 dump_rect(gen, "rect", con->rect);
244 dump_rect(gen, "window_rect", con->window_rect);
245 dump_rect(gen, "geometry", con->geometry);
248 if (con->window && con->window->name_json)
249 ystr(con->window->name_json);
253 if (con->type == CT_WORKSPACE) {
255 y(integer, con->num);
260 y(integer, con->window->id);
266 if (con->type != CT_DOCKAREA || !inplace_restart) {
267 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
268 dump_node(gen, node, inplace_restart);
273 ystr("floating_nodes");
275 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
276 dump_node(gen, node, inplace_restart);
282 TAILQ_FOREACH(node, &(con->focus_head), nodes) {
283 y(integer, (long int)node);
287 ystr("fullscreen_mode");
288 y(integer, con->fullscreen_mode);
293 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
294 if (match->dock != -1) {
297 y(integer, match->dock);
298 ystr("insert_where");
299 y(integer, match->insert_where);
303 /* TODO: the other swallow keys */
306 if (inplace_restart) {
307 if (con->window != NULL) {
310 y(integer, con->window->id);
320 setlocale(LC_NUMERIC, "C");
322 yajl_gen gen = yajl_gen_alloc(NULL);
324 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
326 dump_node(gen, croot, false);
327 setlocale(LC_NUMERIC, "");
329 const unsigned char *payload;
335 y(get_buf, &payload, &length);
337 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
342 * Formats the reply message for a GET_WORKSPACES request and sends it to the
346 IPC_HANDLER(get_workspaces) {
348 yajl_gen gen = yajl_gen_alloc(NULL);
350 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
354 Con *focused_ws = con_get_workspace(focused);
357 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
359 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
360 assert(ws->type == CT_WORKSPACE);
366 else y(integer, ws->num);
372 y(bool, workspace_is_visible(ws));
375 y(bool, ws == focused_ws);
380 y(integer, ws->rect.x);
382 y(integer, ws->rect.y);
384 y(integer, ws->rect.width);
386 y(integer, ws->rect.height);
401 const unsigned char *payload;
407 y(get_buf, &payload, &length);
409 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
414 * Formats the reply message for a GET_OUTPUTS request and sends it to the
418 IPC_HANDLER(get_outputs) {
420 yajl_gen gen = yajl_gen_alloc(NULL);
422 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
427 TAILQ_FOREACH(output, &outputs, outputs) {
434 y(bool, output->active);
439 y(integer, output->rect.x);
441 y(integer, output->rect.y);
443 y(integer, output->rect.width);
445 y(integer, output->rect.height);
448 ystr("current_workspace");
450 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
459 const unsigned char *payload;
465 y(get_buf, &payload, &length);
467 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
472 * Callback for the YAJL parser (will be called when a string is parsed).
476 static int add_subscription(void *extra, const unsigned char *s,
479 static int add_subscription(void *extra, const unsigned char *s,
482 ipc_client *client = extra;
484 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
485 int event = client->num_events;
487 client->num_events++;
488 client->events = realloc(client->events, client->num_events * sizeof(char*));
489 /* We copy the string because it is not null-terminated and strndup()
490 * is missing on some BSD systems */
491 client->events[event] = scalloc(len+1);
492 memcpy(client->events[event], s, len);
494 DLOG("client is now subscribed to:\n");
495 for (int i = 0; i < client->num_events; i++)
496 DLOG("event %s\n", client->events[i]);
503 * Subscribes this connection to the event types which were given as a JSON
504 * serialized array in the payload field of the message.
507 IPC_HANDLER(subscribe) {
509 yajl_callbacks callbacks;
511 ipc_client *current, *client = NULL;
513 /* Search the ipc_client structure for this connection */
514 TAILQ_FOREACH(current, &all_clients, clients) {
515 if (current->fd != fd)
522 if (client == NULL) {
523 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
527 /* Setup the JSON parser */
528 memset(&callbacks, 0, sizeof(yajl_callbacks));
529 callbacks.yajl_string = add_subscription;
532 p = yajl_alloc(&callbacks, NULL, (void*)client);
534 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
536 stat = yajl_parse(p, (const unsigned char*)message, message_size);
537 if (stat != yajl_status_ok) {
539 err = yajl_get_error(p, true, (const unsigned char*)message,
541 ELOG("YAJL parse error: %s\n", err);
542 yajl_free_error(p, err);
544 const char *reply = "{\"success\":false}";
545 ipc_send_message(fd, (const unsigned char*)reply,
546 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
551 const char *reply = "{\"success\":true}";
552 ipc_send_message(fd, (const unsigned char*)reply,
553 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
556 /* The index of each callback function corresponds to the numeric
557 * value of the message type (see include/i3/ipc.h) */
558 handler_t handlers[5] = {
560 handle_get_workspaces,
567 * Handler for activity on a client connection, receives a message from a
570 * For now, the maximum message size is 2048. I’m not sure for what the
571 * IPC interface will be used in the future, thus I’m not implementing a
572 * mechanism for arbitrarily long messages, as it seems like overkill
576 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
578 int n = read(w->fd, buf, sizeof(buf));
580 /* On error or an empty message, we close the connection */
583 /* FIXME: I get these when closing a client socket,
584 * therefore we just treat them as an error. Is this
586 if (errno == EAGAIN || errno == EWOULDBLOCK)
590 /* If not, there was some kind of error. We don’t bother
591 * and close the connection */
594 /* Delete the client from the list of clients */
596 TAILQ_FOREACH(current, &all_clients, clients) {
597 if (current->fd != w->fd)
600 for (int i = 0; i < current->num_events; i++)
601 free(current->events[i]);
602 /* We can call TAILQ_REMOVE because we break out of the
603 * TAILQ_FOREACH afterwards */
604 TAILQ_REMOVE(&all_clients, current, clients);
610 DLOG("IPC: client disconnected\n");
614 /* Terminate the message correctly */
617 /* Check if the message starts with the i3 IPC magic code */
618 if (n < strlen(I3_IPC_MAGIC)) {
619 DLOG("IPC: message too short, ignoring\n");
623 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
624 DLOG("IPC: message does not start with the IPC magic\n");
628 uint8_t *message = (uint8_t*)buf;
630 DLOG("IPC: n = %d\n", n);
631 message += strlen(I3_IPC_MAGIC);
632 n -= strlen(I3_IPC_MAGIC);
634 /* The next 32 bit after the magic are the message size */
635 uint32_t message_size;
636 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
637 message += sizeof(uint32_t);
638 n -= sizeof(uint32_t);
640 if (message_size > n) {
641 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
645 /* The last 32 bits of the header are the message type */
646 uint32_t message_type;
647 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
648 message += sizeof(uint32_t);
649 n -= sizeof(uint32_t);
651 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
652 DLOG("Unhandled message type: %d\n", message_type);
654 handler_t h = handlers[message_type];
655 h(w->fd, message, n, message_size, message_type);
658 message += message_size;
663 * Handler for activity on the listening socket, meaning that a new client
664 * has just connected and we should accept() him. Sets up the event handler
665 * for activity on the new connection and inserts the file descriptor into
666 * the list of clients.
669 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
670 struct sockaddr_un peer;
671 socklen_t len = sizeof(struct sockaddr_un);
673 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
676 else perror("accept()");
680 set_nonblock(client);
682 struct ev_io *package = scalloc(sizeof(struct ev_io));
683 ev_io_init(package, ipc_receive_message, client, EV_READ);
684 ev_io_start(EV_A_ package);
686 DLOG("IPC: new client connected\n");
688 ipc_client *new = scalloc(sizeof(ipc_client));
691 TAILQ_INSERT_TAIL(&all_clients, new, clients);
695 * Creates the UNIX domain socket at the given path, sets it to non-blocking
696 * mode, bind()s and listen()s on it.
699 int ipc_create_socket(const char *filename) {
702 FREE(current_socketpath);
704 char *resolved = resolve_tilde(filename);
705 DLOG("Creating IPC-socket at %s\n", resolved);
706 char *copy = sstrdup(resolved);
707 const char *dir = dirname(copy);
708 if (!path_exists(dir))
712 /* Unlink the unix domain socket before */
715 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
721 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
723 struct sockaddr_un addr;
724 memset(&addr, 0, sizeof(struct sockaddr_un));
725 addr.sun_family = AF_LOCAL;
726 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
727 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
733 set_nonblock(sockfd);
735 if (listen(sockfd, 5) < 0) {
741 current_socketpath = resolved;