2 #define I3__FILE__ "ipc.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
9 * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
13 #include "yajl_utils.h"
15 #include <sys/socket.h>
20 #include <yajl/yajl_gen.h>
21 #include <yajl/yajl_parse.h>
23 char *current_socketpath = NULL;
25 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
28 * Puts the given socket file descriptor into non-blocking mode or dies if
29 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
30 * IPC model because we should by no means block the window manager.
33 static void set_nonblock(int sockfd) {
34 int flags = fcntl(sockfd, F_GETFL, 0);
36 if (fcntl(sockfd, F_SETFL, flags) < 0)
37 err(-1, "Could not set O_NONBLOCK");
41 * Emulates mkdir -p (creates any missing folders)
44 bool mkdirp(const char *path) {
45 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
47 if (errno != ENOENT) {
48 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
51 char *copy = sstrdup(path);
52 /* strip trailing slashes, if any */
53 while (copy[strlen(copy) - 1] == '/')
54 copy[strlen(copy) - 1] = '\0';
56 char *sep = strrchr(copy, '/');
64 result = mkdirp(path);
71 * Sends the specified event to all IPC clients which are currently connected
72 * and subscribed to this kind of event.
75 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
77 TAILQ_FOREACH(current, &all_clients, clients) {
78 /* see if this client is interested in this event */
79 bool interested = false;
80 for (int i = 0; i < current->num_events; i++) {
81 if (strcasecmp(current->events[i], event) != 0)
89 ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t *)payload);
94 * Calls shutdown() on each socket and closes it. This function to be called
95 * when exiting or restarting only!
98 void ipc_shutdown(void) {
100 while (!TAILQ_EMPTY(&all_clients)) {
101 current = TAILQ_FIRST(&all_clients);
102 shutdown(current->fd, SHUT_RDWR);
104 TAILQ_REMOVE(&all_clients, current, clients);
110 * Executes the command and returns whether it could be successfully parsed
111 * or not (at the moment, always returns true).
114 IPC_HANDLER(command) {
115 /* To get a properly terminated buffer, we copy
116 * message_size bytes out of the buffer */
117 char *command = scalloc(message_size + 1);
118 strncpy(command, (const char *)message, message_size);
119 LOG("IPC: received: *%s*\n", command);
120 yajl_gen gen = yajl_gen_alloc(NULL);
122 CommandResult *result = parse_command((const char *)command, gen);
125 if (result->needs_tree_render)
128 command_result_free(result);
130 const unsigned char *reply;
132 yajl_gen_get_buf(gen, &reply, &length);
134 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
135 (const uint8_t *)reply);
140 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
150 y(integer, r.height);
154 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
157 y(integer, (long int)con);
170 case CT_FLOATING_CON:
171 ystr("floating_con");
180 DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
185 /* provided for backwards compatibility only. */
187 if (!con_is_split(con))
190 if (con_orientation(con) == HORIZ)
196 ystr("scratchpad_state");
197 switch (con->scratchpad_state) {
198 case SCRATCHPAD_NONE:
201 case SCRATCHPAD_FRESH:
204 case SCRATCHPAD_CHANGED:
210 if (con->percent == 0.0)
213 y(double, con->percent);
216 y(bool, con->urgent);
218 if (con->mark != NULL) {
224 y(bool, (con == focused));
227 switch (con->layout) {
229 DLOG("About to dump layout=default, this is a bug in the code.\n");
252 ystr("workspace_layout");
253 switch (con->workspace_layout) {
264 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
269 ystr("last_split_layout");
270 switch (con->layout) {
280 switch (con->border_style) {
292 ystr("current_border_width");
293 y(integer, con->current_border_width);
295 dump_rect(gen, "rect", con->rect);
296 dump_rect(gen, "window_rect", con->window_rect);
297 dump_rect(gen, "geometry", con->geometry);
300 if (con->window && con->window->name)
301 ystr(i3string_as_utf8(con->window->name));
302 else if (con->name != NULL)
307 if (con->type == CT_WORKSPACE) {
309 y(integer, con->num);
314 y(integer, con->window->id);
318 if (con->window && !inplace_restart) {
319 /* Window properties are useless to preserve when restarting because
320 * they will be queried again anyway. However, for i3-save-tree(1),
321 * they are very useful and save i3-save-tree dealing with X11. */
322 ystr("window_properties");
325 #define DUMP_PROPERTY(key, prop_name) \
327 if (con->window->prop_name != NULL) { \
329 ystr(con->window->prop_name); \
333 DUMP_PROPERTY("class", class_class);
334 DUMP_PROPERTY("instance", class_instance);
335 DUMP_PROPERTY("window_role", role);
337 if (con->window->name != NULL) {
339 ystr(i3string_as_utf8(con->window->name));
342 ystr("transient_for");
343 if (con->window->transient_for == XCB_NONE)
345 else y(integer, con->window->transient_for);
353 if (con->type != CT_DOCKAREA || !inplace_restart) {
354 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
355 dump_node(gen, node, inplace_restart);
360 ystr("floating_nodes");
362 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
363 dump_node(gen, node, inplace_restart);
369 TAILQ_FOREACH(node, &(con->focus_head), focused) {
370 y(integer, (long int)node);
374 ystr("fullscreen_mode");
375 y(integer, con->fullscreen_mode);
378 switch (con->floating) {
379 case FLOATING_AUTO_OFF:
382 case FLOATING_AUTO_ON:
385 case FLOATING_USER_OFF:
388 case FLOATING_USER_ON:
396 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
398 if (match->dock != -1) {
400 y(integer, match->dock);
401 ystr("insert_where");
402 y(integer, match->insert_where);
405 #define DUMP_REGEX(re_name) \
407 if (match->re_name != NULL) { \
409 ystr(match->re_name->pattern); \
414 DUMP_REGEX(instance);
415 DUMP_REGEX(window_role);
422 if (inplace_restart) {
423 if (con->window != NULL) {
426 y(integer, con->window->id);
427 ystr("restart_mode");
434 if (inplace_restart && con->window != NULL) {
436 y(integer, con->depth);
442 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
448 if (config->num_outputs > 0) {
451 for (int c = 0; c < config->num_outputs; c++)
452 ystr(config->outputs[c]);
456 #define YSTR_IF_SET(name) \
458 if (config->name) { \
460 ystr(config->name); \
464 YSTR_IF_SET(tray_output);
465 YSTR_IF_SET(socket_path);
468 switch (config->mode) {
481 ystr("hidden_state");
482 switch (config->hidden_state) {
493 switch (config->modifier) {
522 if (config->wheel_up_cmd) {
523 ystr("wheel_up_cmd");
524 ystr(config->wheel_up_cmd);
527 if (config->wheel_down_cmd) {
528 ystr("wheel_down_cmd");
529 ystr(config->wheel_down_cmd);
533 if (config->position == P_BOTTOM)
538 YSTR_IF_SET(status_command);
541 ystr("workspace_buttons");
542 y(bool, !config->hide_workspace_buttons);
544 ystr("strip_workspace_numbers");
545 y(bool, config->strip_workspace_numbers);
547 ystr("binding_mode_indicator");
548 y(bool, !config->hide_binding_mode_indicator);
551 y(bool, config->verbose);
554 #define YSTR_IF_SET(name) \
556 if (config->colors.name) { \
558 ystr(config->colors.name); \
564 YSTR_IF_SET(background);
565 YSTR_IF_SET(statusline);
566 YSTR_IF_SET(separator);
567 YSTR_IF_SET(focused_workspace_border);
568 YSTR_IF_SET(focused_workspace_bg);
569 YSTR_IF_SET(focused_workspace_text);
570 YSTR_IF_SET(active_workspace_border);
571 YSTR_IF_SET(active_workspace_bg);
572 YSTR_IF_SET(active_workspace_text);
573 YSTR_IF_SET(inactive_workspace_border);
574 YSTR_IF_SET(inactive_workspace_bg);
575 YSTR_IF_SET(inactive_workspace_text);
576 YSTR_IF_SET(urgent_workspace_border);
577 YSTR_IF_SET(urgent_workspace_bg);
578 YSTR_IF_SET(urgent_workspace_text);
586 setlocale(LC_NUMERIC, "C");
587 yajl_gen gen = ygenalloc();
588 dump_node(gen, croot, false);
589 setlocale(LC_NUMERIC, "");
591 const unsigned char *payload;
593 y(get_buf, &payload, &length);
595 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
600 * Formats the reply message for a GET_WORKSPACES request and sends it to the
604 IPC_HANDLER(get_workspaces) {
605 yajl_gen gen = ygenalloc();
608 Con *focused_ws = con_get_workspace(focused);
611 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
612 if (con_is_internal(output))
615 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
616 assert(ws->type == CT_WORKSPACE);
629 y(bool, workspace_is_visible(ws));
632 y(bool, ws == focused_ws);
637 y(integer, ws->rect.x);
639 y(integer, ws->rect.y);
641 y(integer, ws->rect.width);
643 y(integer, ws->rect.height);
658 const unsigned char *payload;
660 y(get_buf, &payload, &length);
662 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
667 * Formats the reply message for a GET_OUTPUTS request and sends it to the
671 IPC_HANDLER(get_outputs) {
672 yajl_gen gen = ygenalloc();
676 TAILQ_FOREACH(output, &outputs, outputs) {
683 y(bool, output->active);
686 y(bool, output->primary);
691 y(integer, output->rect.x);
693 y(integer, output->rect.y);
695 y(integer, output->rect.width);
697 y(integer, output->rect.height);
700 ystr("current_workspace");
702 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
712 const unsigned char *payload;
714 y(get_buf, &payload, &length);
716 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
721 * Formats the reply message for a GET_MARKS request and sends it to the
725 IPC_HANDLER(get_marks) {
726 yajl_gen gen = ygenalloc();
730 TAILQ_FOREACH(con, &all_cons, all_cons)
731 if (con->mark != NULL)
736 const unsigned char *payload;
738 y(get_buf, &payload, &length);
740 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
745 * Returns the version of i3
748 IPC_HANDLER(get_version) {
749 yajl_gen gen = ygenalloc();
753 y(integer, MAJOR_VERSION);
756 y(integer, MINOR_VERSION);
759 y(integer, PATCH_VERSION);
761 ystr("human_readable");
766 const unsigned char *payload;
768 y(get_buf, &payload, &length);
770 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
775 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
779 IPC_HANDLER(get_bar_config) {
780 yajl_gen gen = ygenalloc();
782 /* If no ID was passed, we return a JSON array with all IDs */
783 if (message_size == 0) {
786 TAILQ_FOREACH(current, &barconfigs, configs) {
791 const unsigned char *payload;
793 y(get_buf, &payload, &length);
795 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
800 /* To get a properly terminated buffer, we copy
801 * message_size bytes out of the buffer */
802 char *bar_id = scalloc(message_size + 1);
803 strncpy(bar_id, (const char *)message, message_size);
804 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
805 Barconfig *current, *config = NULL;
806 TAILQ_FOREACH(current, &barconfigs, configs) {
807 if (strcmp(current->id, bar_id) != 0)
815 /* If we did not find a config for the given ID, the reply will contain
816 * a null 'id' field. */
824 dump_bar_config(gen, config);
827 const unsigned char *payload;
829 y(get_buf, &payload, &length);
831 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
836 * Callback for the YAJL parser (will be called when a string is parsed).
839 static int add_subscription(void *extra, const unsigned char *s,
841 ipc_client *client = extra;
843 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
844 int event = client->num_events;
846 client->num_events++;
847 client->events = realloc(client->events, client->num_events * sizeof(char *));
848 /* We copy the string because it is not null-terminated and strndup()
849 * is missing on some BSD systems */
850 client->events[event] = scalloc(len + 1);
851 memcpy(client->events[event], s, len);
853 DLOG("client is now subscribed to:\n");
854 for (int i = 0; i < client->num_events; i++)
855 DLOG("event %s\n", client->events[i]);
862 * Subscribes this connection to the event types which were given as a JSON
863 * serialized array in the payload field of the message.
866 IPC_HANDLER(subscribe) {
869 ipc_client *current, *client = NULL;
871 /* Search the ipc_client structure for this connection */
872 TAILQ_FOREACH(current, &all_clients, clients) {
873 if (current->fd != fd)
880 if (client == NULL) {
881 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
885 /* Setup the JSON parser */
886 static yajl_callbacks callbacks = {
887 .yajl_string = add_subscription,
890 p = yalloc(&callbacks, (void *)client);
891 stat = yajl_parse(p, (const unsigned char *)message, message_size);
892 if (stat != yajl_status_ok) {
894 err = yajl_get_error(p, true, (const unsigned char *)message,
896 ELOG("YAJL parse error: %s\n", err);
897 yajl_free_error(p, err);
899 const char *reply = "{\"success\":false}";
900 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
905 const char *reply = "{\"success\":true}";
906 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
909 /* The index of each callback function corresponds to the numeric
910 * value of the message type (see include/i3/ipc.h) */
911 handler_t handlers[8] = {
913 handle_get_workspaces,
918 handle_get_bar_config,
923 * Handler for activity on a client connection, receives a message from a
926 * For now, the maximum message size is 2048. I’m not sure for what the
927 * IPC interface will be used in the future, thus I’m not implementing a
928 * mechanism for arbitrarily long messages, as it seems like overkill
932 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
933 uint32_t message_type;
934 uint32_t message_length;
935 uint8_t *message = NULL;
937 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
938 /* EOF or other error */
940 /* Was this a spurious read? See ev(3) */
941 if (ret == -1 && errno == EAGAIN) {
946 /* If not, there was some kind of error. We don’t bother
947 * and close the connection */
950 /* Delete the client from the list of clients */
952 TAILQ_FOREACH(current, &all_clients, clients) {
953 if (current->fd != w->fd)
956 for (int i = 0; i < current->num_events; i++)
957 free(current->events[i]);
958 /* We can call TAILQ_REMOVE because we break out of the
959 * TAILQ_FOREACH afterwards */
960 TAILQ_REMOVE(&all_clients, current, clients);
969 DLOG("IPC: client disconnected\n");
973 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
974 DLOG("Unhandled message type: %d\n", message_type);
976 handler_t h = handlers[message_type];
977 h(w->fd, message, 0, message_length, message_type);
984 * Handler for activity on the listening socket, meaning that a new client
985 * has just connected and we should accept() him. Sets up the event handler
986 * for activity on the new connection and inserts the file descriptor into
987 * the list of clients.
990 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
991 struct sockaddr_un peer;
992 socklen_t len = sizeof(struct sockaddr_un);
994 if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1002 /* Close this file descriptor on exec() */
1003 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1005 set_nonblock(client);
1007 struct ev_io *package = scalloc(sizeof(struct ev_io));
1008 ev_io_init(package, ipc_receive_message, client, EV_READ);
1009 ev_io_start(EV_A_ package);
1011 DLOG("IPC: new client connected on fd %d\n", w->fd);
1013 ipc_client *new = scalloc(sizeof(ipc_client));
1016 TAILQ_INSERT_TAIL(&all_clients, new, clients);
1020 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1021 * mode, bind()s and listen()s on it.
1024 int ipc_create_socket(const char *filename) {
1027 FREE(current_socketpath);
1029 char *resolved = resolve_tilde(filename);
1030 DLOG("Creating IPC-socket at %s\n", resolved);
1031 char *copy = sstrdup(resolved);
1032 const char *dir = dirname(copy);
1033 if (!path_exists(dir))
1037 /* Unlink the unix domain socket before */
1040 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1046 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1048 struct sockaddr_un addr;
1049 memset(&addr, 0, sizeof(struct sockaddr_un));
1050 addr.sun_family = AF_LOCAL;
1051 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1052 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1058 set_nonblock(sockfd);
1060 if (listen(sockfd, 5) < 0) {
1066 current_socketpath = resolved;
1071 * For the workspace "focus" event we send, along the usual "change" field,
1072 * also the current and previous workspace, in "current" and "old"
1075 void ipc_send_workspace_focus_event(Con *current, Con *old) {
1076 setlocale(LC_NUMERIC, "C");
1077 yajl_gen gen = ygenalloc();
1085 dump_node(gen, current, false);
1091 dump_node(gen, old, false);
1095 const unsigned char *payload;
1097 y(get_buf, &payload, &length);
1099 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1101 setlocale(LC_NUMERIC, "");
1105 * For the window events we send, along the usual "change" field,
1106 * also the window container, in "container".
1108 void ipc_send_window_event(const char *property, Con *con) {
1109 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1110 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1112 setlocale(LC_NUMERIC, "C");
1113 yajl_gen gen = ygenalloc();
1121 dump_node(gen, con, false);
1125 const unsigned char *payload;
1127 y(get_buf, &payload, &length);
1129 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1131 setlocale(LC_NUMERIC, "");
1135 * For the barconfig update events, we send the serialized barconfig.
1137 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1138 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1139 setlocale(LC_NUMERIC, "C");
1140 yajl_gen gen = ygenalloc();
1142 dump_bar_config(gen, barconfig);
1144 const unsigned char *payload;
1146 y(get_buf, &payload, &length);
1148 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1150 setlocale(LC_NUMERIC, "");