2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
7 * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
12 #include <sys/socket.h>
17 #include <yajl/yajl_gen.h>
18 #include <yajl/yajl_parse.h>
19 #include <yajl/yajl_version.h>
21 char *current_socketpath = NULL;
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))
27 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
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.
35 static void set_nonblock(int sockfd) {
36 int flags = fcntl(sockfd, F_GETFL, 0);
38 if (fcntl(sockfd, F_SETFL, flags) < 0)
39 err(-1, "Could not set O_NONBLOCK");
43 * Emulates mkdir -p (creates any missing folders)
46 static bool mkdirp(const char *path) {
47 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
49 if (errno != ENOENT) {
50 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
53 char *copy = strdup(path);
54 /* strip trailing slashes, if any */
55 while (copy[strlen(copy)-1] == '/')
56 copy[strlen(copy)-1] = '\0';
58 char *sep = strrchr(copy, '/');
66 result = mkdirp(path);
73 * Sends the specified event to all IPC clients which are currently connected
74 * and subscribed to this kind of event.
77 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
79 TAILQ_FOREACH(current, &all_clients, clients) {
80 /* see if this client is interested in this event */
81 bool interested = false;
82 for (int i = 0; i < current->num_events; i++) {
83 if (strcasecmp(current->events[i], event) != 0)
91 ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t*)payload);
96 * Calls shutdown() on each socket and closes it. This function to be called
97 * when exiting or restarting only!
100 void ipc_shutdown(void) {
102 while (!TAILQ_EMPTY(&all_clients)) {
103 current = TAILQ_FIRST(&all_clients);
104 shutdown(current->fd, SHUT_RDWR);
106 TAILQ_REMOVE(&all_clients, current, clients);
112 * Executes the command and returns whether it could be successfully parsed
113 * or not (at the moment, always returns true).
116 IPC_HANDLER(command) {
117 /* To get a properly terminated buffer, we copy
118 * message_size bytes out of the buffer */
119 char *command = scalloc(message_size + 1);
120 strncpy(command, (const char*)message, message_size);
121 LOG("IPC: received: *%s*\n", command);
122 struct CommandResult *command_output = parse_command((const char*)command);
125 if (command_output->needs_tree_render)
128 const unsigned char *reply;
134 yajl_gen_get_buf(command_output->json_gen, &reply, &length);
136 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
137 (const uint8_t*)reply);
139 yajl_gen_free(command_output->json_gen);
142 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
152 y(integer, r.height);
156 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
159 y(integer, (long int)con);
162 y(integer, con->type);
164 /* provided for backwards compatibility only. */
169 if (con_orientation(con) == HORIZ)
171 else ystr("vertical");
174 ystr("scratchpad_state");
175 switch (con->scratchpad_state) {
176 case SCRATCHPAD_NONE:
179 case SCRATCHPAD_FRESH:
182 case SCRATCHPAD_CHANGED:
188 if (con->percent == 0.0)
190 else y(double, con->percent);
193 y(bool, con->urgent);
195 if (con->mark != NULL) {
201 y(bool, (con == focused));
207 switch (con->layout) {
209 DLOG("About to dump layout=default, this is a bug in the code.\n");
232 ystr("last_split_layout");
233 switch (con->layout) {
243 switch (con->border_style) {
255 dump_rect(gen, "rect", con->rect);
256 dump_rect(gen, "window_rect", con->window_rect);
257 dump_rect(gen, "geometry", con->geometry);
260 if (con->window && con->window->name_json)
261 ystr(con->window->name_json);
265 if (con->type == CT_WORKSPACE) {
267 y(integer, con->num);
272 y(integer, con->window->id);
278 if (con->type != CT_DOCKAREA || !inplace_restart) {
279 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
280 dump_node(gen, node, inplace_restart);
285 ystr("floating_nodes");
287 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
288 dump_node(gen, node, inplace_restart);
294 TAILQ_FOREACH(node, &(con->focus_head), focused) {
295 y(integer, (long int)node);
299 ystr("fullscreen_mode");
300 y(integer, con->fullscreen_mode);
303 switch (con->floating) {
304 case FLOATING_AUTO_OFF:
307 case FLOATING_AUTO_ON:
310 case FLOATING_USER_OFF:
313 case FLOATING_USER_ON:
321 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
322 if (match->dock != -1) {
325 y(integer, match->dock);
326 ystr("insert_where");
327 y(integer, match->insert_where);
331 /* TODO: the other swallow keys */
334 if (inplace_restart) {
335 if (con->window != NULL) {
338 y(integer, con->window->id);
339 ystr("restart_mode");
350 setlocale(LC_NUMERIC, "C");
352 yajl_gen gen = yajl_gen_alloc(NULL);
354 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
356 dump_node(gen, croot, false);
357 setlocale(LC_NUMERIC, "");
359 const unsigned char *payload;
365 y(get_buf, &payload, &length);
367 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
373 * Formats the reply message for a GET_WORKSPACES request and sends it to the
377 IPC_HANDLER(get_workspaces) {
379 yajl_gen gen = yajl_gen_alloc(NULL);
381 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
385 Con *focused_ws = con_get_workspace(focused);
388 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
389 if (output->name[0] == '_' && output->name[1] == '_')
392 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
393 assert(ws->type == CT_WORKSPACE);
399 else y(integer, ws->num);
405 y(bool, workspace_is_visible(ws));
408 y(bool, ws == focused_ws);
413 y(integer, ws->rect.x);
415 y(integer, ws->rect.y);
417 y(integer, ws->rect.width);
419 y(integer, ws->rect.height);
434 const unsigned char *payload;
440 y(get_buf, &payload, &length);
442 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
447 * Formats the reply message for a GET_OUTPUTS request and sends it to the
451 IPC_HANDLER(get_outputs) {
453 yajl_gen gen = yajl_gen_alloc(NULL);
455 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
460 TAILQ_FOREACH(output, &outputs, outputs) {
467 y(bool, output->active);
470 y(bool, output->primary);
475 y(integer, output->rect.x);
477 y(integer, output->rect.y);
479 y(integer, output->rect.width);
481 y(integer, output->rect.height);
484 ystr("current_workspace");
486 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
495 const unsigned char *payload;
501 y(get_buf, &payload, &length);
503 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
508 * Formats the reply message for a GET_MARKS request and sends it to the
512 IPC_HANDLER(get_marks) {
514 yajl_gen gen = yajl_gen_alloc(NULL);
516 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
521 TAILQ_FOREACH(con, &all_cons, all_cons)
522 if (con->mark != NULL)
527 const unsigned char *payload;
533 y(get_buf, &payload, &length);
535 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
540 * Returns the version of i3
543 IPC_HANDLER(get_version) {
545 yajl_gen gen = yajl_gen_alloc(NULL);
547 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
552 y(integer, MAJOR_VERSION);
555 y(integer, MINOR_VERSION);
558 y(integer, PATCH_VERSION);
560 ystr("human_readable");
565 const unsigned char *payload;
571 y(get_buf, &payload, &length);
573 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
578 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
582 IPC_HANDLER(get_bar_config) {
584 yajl_gen gen = yajl_gen_alloc(NULL);
586 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
589 /* If no ID was passed, we return a JSON array with all IDs */
590 if (message_size == 0) {
593 TAILQ_FOREACH(current, &barconfigs, configs) {
598 const unsigned char *payload;
604 y(get_buf, &payload, &length);
606 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
611 /* To get a properly terminated buffer, we copy
612 * message_size bytes out of the buffer */
613 char *bar_id = scalloc(message_size + 1);
614 strncpy(bar_id, (const char*)message, message_size);
615 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
616 Barconfig *current, *config = NULL;
617 TAILQ_FOREACH(current, &barconfigs, configs) {
618 if (strcmp(current->id, bar_id) != 0)
628 /* If we did not find a config for the given ID, the reply will contain
629 * a null 'id' field. */
636 if (config->num_outputs > 0) {
639 for (int c = 0; c < config->num_outputs; c++)
640 ystr(config->outputs[c]);
644 #define YSTR_IF_SET(name) \
646 if (config->name) { \
648 ystr(config->name); \
652 YSTR_IF_SET(tray_output);
653 YSTR_IF_SET(socket_path);
656 if (config->mode == M_HIDE)
661 switch (config->modifier) {
691 if (config->position == P_BOTTOM)
695 YSTR_IF_SET(status_command);
698 ystr("workspace_buttons");
699 y(bool, !config->hide_workspace_buttons);
702 y(bool, config->verbose);
705 #define YSTR_IF_SET(name) \
707 if (config->colors.name) { \
709 ystr(config->colors.name); \
715 YSTR_IF_SET(background);
716 YSTR_IF_SET(statusline);
717 YSTR_IF_SET(focused_workspace_border);
718 YSTR_IF_SET(focused_workspace_bg);
719 YSTR_IF_SET(focused_workspace_text);
720 YSTR_IF_SET(active_workspace_border);
721 YSTR_IF_SET(active_workspace_bg);
722 YSTR_IF_SET(active_workspace_text);
723 YSTR_IF_SET(inactive_workspace_border);
724 YSTR_IF_SET(inactive_workspace_bg);
725 YSTR_IF_SET(inactive_workspace_text);
726 YSTR_IF_SET(urgent_workspace_border);
727 YSTR_IF_SET(urgent_workspace_bg);
728 YSTR_IF_SET(urgent_workspace_text);
736 const unsigned char *payload;
742 y(get_buf, &payload, &length);
744 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
749 * Callback for the YAJL parser (will be called when a string is parsed).
753 static int add_subscription(void *extra, const unsigned char *s,
756 static int add_subscription(void *extra, const unsigned char *s,
759 ipc_client *client = extra;
761 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
762 int event = client->num_events;
764 client->num_events++;
765 client->events = realloc(client->events, client->num_events * sizeof(char*));
766 /* We copy the string because it is not null-terminated and strndup()
767 * is missing on some BSD systems */
768 client->events[event] = scalloc(len+1);
769 memcpy(client->events[event], s, len);
771 DLOG("client is now subscribed to:\n");
772 for (int i = 0; i < client->num_events; i++)
773 DLOG("event %s\n", client->events[i]);
780 * Subscribes this connection to the event types which were given as a JSON
781 * serialized array in the payload field of the message.
784 IPC_HANDLER(subscribe) {
786 yajl_callbacks callbacks;
788 ipc_client *current, *client = NULL;
790 /* Search the ipc_client structure for this connection */
791 TAILQ_FOREACH(current, &all_clients, clients) {
792 if (current->fd != fd)
799 if (client == NULL) {
800 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
804 /* Setup the JSON parser */
805 memset(&callbacks, 0, sizeof(yajl_callbacks));
806 callbacks.yajl_string = add_subscription;
809 p = yajl_alloc(&callbacks, NULL, (void*)client);
811 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
813 stat = yajl_parse(p, (const unsigned char*)message, message_size);
814 if (stat != yajl_status_ok) {
816 err = yajl_get_error(p, true, (const unsigned char*)message,
818 ELOG("YAJL parse error: %s\n", err);
819 yajl_free_error(p, err);
821 const char *reply = "{\"success\":false}";
822 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
827 const char *reply = "{\"success\":true}";
828 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
831 /* The index of each callback function corresponds to the numeric
832 * value of the message type (see include/i3/ipc.h) */
833 handler_t handlers[8] = {
835 handle_get_workspaces,
840 handle_get_bar_config,
845 * Handler for activity on a client connection, receives a message from a
848 * For now, the maximum message size is 2048. I’m not sure for what the
849 * IPC interface will be used in the future, thus I’m not implementing a
850 * mechanism for arbitrarily long messages, as it seems like overkill
854 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
856 int n = read(w->fd, buf, sizeof(buf));
858 /* On error or an empty message, we close the connection */
861 /* FIXME: I get these when closing a client socket,
862 * therefore we just treat them as an error. Is this
864 if (errno == EAGAIN || errno == EWOULDBLOCK)
868 /* If not, there was some kind of error. We don’t bother
869 * and close the connection */
872 /* Delete the client from the list of clients */
874 TAILQ_FOREACH(current, &all_clients, clients) {
875 if (current->fd != w->fd)
878 for (int i = 0; i < current->num_events; i++)
879 free(current->events[i]);
880 /* We can call TAILQ_REMOVE because we break out of the
881 * TAILQ_FOREACH afterwards */
882 TAILQ_REMOVE(&all_clients, current, clients);
890 DLOG("IPC: client disconnected\n");
894 /* Terminate the message correctly */
897 /* Check if the message starts with the i3 IPC magic code */
898 if (n < strlen(I3_IPC_MAGIC)) {
899 DLOG("IPC: message too short, ignoring\n");
903 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
904 DLOG("IPC: message does not start with the IPC magic\n");
908 uint8_t *message = (uint8_t*)buf;
910 DLOG("IPC: n = %d\n", n);
911 message += strlen(I3_IPC_MAGIC);
912 n -= strlen(I3_IPC_MAGIC);
914 /* The next 32 bit after the magic are the message size */
915 uint32_t message_size;
916 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
917 message += sizeof(uint32_t);
918 n -= sizeof(uint32_t);
920 if (message_size > n) {
921 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
925 /* The last 32 bits of the header are the message type */
926 uint32_t message_type;
927 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
928 message += sizeof(uint32_t);
929 n -= sizeof(uint32_t);
931 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
932 DLOG("Unhandled message type: %d\n", message_type);
934 handler_t h = handlers[message_type];
935 h(w->fd, message, n, message_size, message_type);
938 message += message_size;
943 * Handler for activity on the listening socket, meaning that a new client
944 * has just connected and we should accept() him. Sets up the event handler
945 * for activity on the new connection and inserts the file descriptor into
946 * the list of clients.
949 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
950 struct sockaddr_un peer;
951 socklen_t len = sizeof(struct sockaddr_un);
953 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
956 else perror("accept()");
960 /* Close this file descriptor on exec() */
961 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
963 set_nonblock(client);
965 struct ev_io *package = scalloc(sizeof(struct ev_io));
966 ev_io_init(package, ipc_receive_message, client, EV_READ);
967 ev_io_start(EV_A_ package);
969 DLOG("IPC: new client connected on fd %d\n", w->fd);
971 ipc_client *new = scalloc(sizeof(ipc_client));
974 TAILQ_INSERT_TAIL(&all_clients, new, clients);
978 * Creates the UNIX domain socket at the given path, sets it to non-blocking
979 * mode, bind()s and listen()s on it.
982 int ipc_create_socket(const char *filename) {
985 FREE(current_socketpath);
987 char *resolved = resolve_tilde(filename);
988 DLOG("Creating IPC-socket at %s\n", resolved);
989 char *copy = sstrdup(resolved);
990 const char *dir = dirname(copy);
991 if (!path_exists(dir))
995 /* Unlink the unix domain socket before */
998 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1004 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1006 struct sockaddr_un addr;
1007 memset(&addr, 0, sizeof(struct sockaddr_un));
1008 addr.sun_family = AF_LOCAL;
1009 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1010 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1016 set_nonblock(sockfd);
1018 if (listen(sockfd, 5) < 0) {
1024 current_socketpath = resolved;