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 static void dump_binding(yajl_gen gen, Binding *bind) {
157 y(integer, bind->keycode);
160 ystr((const char*)(bind->input_type == B_KEYBOARD ? "keyboard" : "mouse"));
170 for (int i = 0; i < 8; i++) {
171 if (bind->mods & (1 << i)) {
173 case XCB_MOD_MASK_SHIFT:
176 case XCB_MOD_MASK_LOCK:
179 case XCB_MOD_MASK_CONTROL:
205 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
208 y(integer, (long int)con);
221 case CT_FLOATING_CON:
222 ystr("floating_con");
231 DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
236 /* provided for backwards compatibility only. */
238 if (!con_is_split(con))
241 if (con_orientation(con) == HORIZ)
247 ystr("scratchpad_state");
248 switch (con->scratchpad_state) {
249 case SCRATCHPAD_NONE:
252 case SCRATCHPAD_FRESH:
255 case SCRATCHPAD_CHANGED:
261 if (con->percent == 0.0)
264 y(double, con->percent);
267 y(bool, con->urgent);
269 if (con->mark != NULL) {
275 y(bool, (con == focused));
278 switch (con->layout) {
280 DLOG("About to dump layout=default, this is a bug in the code.\n");
303 ystr("workspace_layout");
304 switch (con->workspace_layout) {
315 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
320 ystr("last_split_layout");
321 switch (con->layout) {
331 switch (con->border_style) {
343 ystr("current_border_width");
344 y(integer, con->current_border_width);
346 dump_rect(gen, "rect", con->rect);
347 dump_rect(gen, "window_rect", con->window_rect);
348 dump_rect(gen, "geometry", con->geometry);
351 if (con->window && con->window->name)
352 ystr(i3string_as_utf8(con->window->name));
353 else if (con->name != NULL)
358 if (con->type == CT_WORKSPACE) {
360 y(integer, con->num);
365 y(integer, con->window->id);
369 if (con->window && !inplace_restart) {
370 /* Window properties are useless to preserve when restarting because
371 * they will be queried again anyway. However, for i3-save-tree(1),
372 * they are very useful and save i3-save-tree dealing with X11. */
373 ystr("window_properties");
376 #define DUMP_PROPERTY(key, prop_name) \
378 if (con->window->prop_name != NULL) { \
380 ystr(con->window->prop_name); \
384 DUMP_PROPERTY("class", class_class);
385 DUMP_PROPERTY("instance", class_instance);
386 DUMP_PROPERTY("window_role", role);
388 if (con->window->name != NULL) {
390 ystr(i3string_as_utf8(con->window->name));
393 ystr("transient_for");
394 if (con->window->transient_for == XCB_NONE)
396 else y(integer, con->window->transient_for);
404 if (con->type != CT_DOCKAREA || !inplace_restart) {
405 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
406 dump_node(gen, node, inplace_restart);
411 ystr("floating_nodes");
413 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
414 dump_node(gen, node, inplace_restart);
420 TAILQ_FOREACH(node, &(con->focus_head), focused) {
421 y(integer, (long int)node);
425 ystr("fullscreen_mode");
426 y(integer, con->fullscreen_mode);
429 switch (con->floating) {
430 case FLOATING_AUTO_OFF:
433 case FLOATING_AUTO_ON:
436 case FLOATING_USER_OFF:
439 case FLOATING_USER_ON:
447 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
449 if (match->dock != -1) {
451 y(integer, match->dock);
452 ystr("insert_where");
453 y(integer, match->insert_where);
456 #define DUMP_REGEX(re_name) \
458 if (match->re_name != NULL) { \
460 ystr(match->re_name->pattern); \
465 DUMP_REGEX(instance);
466 DUMP_REGEX(window_role);
473 if (inplace_restart) {
474 if (con->window != NULL) {
477 y(integer, con->window->id);
478 ystr("restart_mode");
485 if (inplace_restart && con->window != NULL) {
487 y(integer, con->depth);
493 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
499 if (config->num_outputs > 0) {
502 for (int c = 0; c < config->num_outputs; c++)
503 ystr(config->outputs[c]);
507 #define YSTR_IF_SET(name) \
509 if (config->name) { \
511 ystr(config->name); \
515 YSTR_IF_SET(tray_output);
516 YSTR_IF_SET(socket_path);
519 switch (config->mode) {
532 ystr("hidden_state");
533 switch (config->hidden_state) {
544 switch (config->modifier) {
573 if (config->wheel_up_cmd) {
574 ystr("wheel_up_cmd");
575 ystr(config->wheel_up_cmd);
578 if (config->wheel_down_cmd) {
579 ystr("wheel_down_cmd");
580 ystr(config->wheel_down_cmd);
584 if (config->position == P_BOTTOM)
589 YSTR_IF_SET(status_command);
592 ystr("workspace_buttons");
593 y(bool, !config->hide_workspace_buttons);
595 ystr("strip_workspace_numbers");
596 y(bool, config->strip_workspace_numbers);
598 ystr("binding_mode_indicator");
599 y(bool, !config->hide_binding_mode_indicator);
602 y(bool, config->verbose);
605 #define YSTR_IF_SET(name) \
607 if (config->colors.name) { \
609 ystr(config->colors.name); \
615 YSTR_IF_SET(background);
616 YSTR_IF_SET(statusline);
617 YSTR_IF_SET(separator);
618 YSTR_IF_SET(focused_workspace_border);
619 YSTR_IF_SET(focused_workspace_bg);
620 YSTR_IF_SET(focused_workspace_text);
621 YSTR_IF_SET(active_workspace_border);
622 YSTR_IF_SET(active_workspace_bg);
623 YSTR_IF_SET(active_workspace_text);
624 YSTR_IF_SET(inactive_workspace_border);
625 YSTR_IF_SET(inactive_workspace_bg);
626 YSTR_IF_SET(inactive_workspace_text);
627 YSTR_IF_SET(urgent_workspace_border);
628 YSTR_IF_SET(urgent_workspace_bg);
629 YSTR_IF_SET(urgent_workspace_text);
637 setlocale(LC_NUMERIC, "C");
638 yajl_gen gen = ygenalloc();
639 dump_node(gen, croot, false);
640 setlocale(LC_NUMERIC, "");
642 const unsigned char *payload;
644 y(get_buf, &payload, &length);
646 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
651 * Formats the reply message for a GET_WORKSPACES request and sends it to the
655 IPC_HANDLER(get_workspaces) {
656 yajl_gen gen = ygenalloc();
659 Con *focused_ws = con_get_workspace(focused);
662 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
663 if (con_is_internal(output))
666 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
667 assert(ws->type == CT_WORKSPACE);
677 y(bool, workspace_is_visible(ws));
680 y(bool, ws == focused_ws);
685 y(integer, ws->rect.x);
687 y(integer, ws->rect.y);
689 y(integer, ws->rect.width);
691 y(integer, ws->rect.height);
706 const unsigned char *payload;
708 y(get_buf, &payload, &length);
710 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
715 * Formats the reply message for a GET_OUTPUTS request and sends it to the
719 IPC_HANDLER(get_outputs) {
720 yajl_gen gen = ygenalloc();
724 TAILQ_FOREACH(output, &outputs, outputs) {
731 y(bool, output->active);
734 y(bool, output->primary);
739 y(integer, output->rect.x);
741 y(integer, output->rect.y);
743 y(integer, output->rect.width);
745 y(integer, output->rect.height);
748 ystr("current_workspace");
750 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
760 const unsigned char *payload;
762 y(get_buf, &payload, &length);
764 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
769 * Formats the reply message for a GET_MARKS request and sends it to the
773 IPC_HANDLER(get_marks) {
774 yajl_gen gen = ygenalloc();
778 TAILQ_FOREACH(con, &all_cons, all_cons)
779 if (con->mark != NULL)
784 const unsigned char *payload;
786 y(get_buf, &payload, &length);
788 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
793 * Returns the version of i3
796 IPC_HANDLER(get_version) {
797 yajl_gen gen = ygenalloc();
801 y(integer, MAJOR_VERSION);
804 y(integer, MINOR_VERSION);
807 y(integer, PATCH_VERSION);
809 ystr("human_readable");
814 const unsigned char *payload;
816 y(get_buf, &payload, &length);
818 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
823 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
827 IPC_HANDLER(get_bar_config) {
828 yajl_gen gen = ygenalloc();
830 /* If no ID was passed, we return a JSON array with all IDs */
831 if (message_size == 0) {
834 TAILQ_FOREACH(current, &barconfigs, configs) {
839 const unsigned char *payload;
841 y(get_buf, &payload, &length);
843 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
848 /* To get a properly terminated buffer, we copy
849 * message_size bytes out of the buffer */
850 char *bar_id = scalloc(message_size + 1);
851 strncpy(bar_id, (const char *)message, message_size);
852 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
853 Barconfig *current, *config = NULL;
854 TAILQ_FOREACH(current, &barconfigs, configs) {
855 if (strcmp(current->id, bar_id) != 0)
863 /* If we did not find a config for the given ID, the reply will contain
864 * a null 'id' field. */
872 dump_bar_config(gen, config);
875 const unsigned char *payload;
877 y(get_buf, &payload, &length);
879 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
884 * Callback for the YAJL parser (will be called when a string is parsed).
887 static int add_subscription(void *extra, const unsigned char *s,
889 ipc_client *client = extra;
891 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
892 int event = client->num_events;
894 client->num_events++;
895 client->events = realloc(client->events, client->num_events * sizeof(char *));
896 /* We copy the string because it is not null-terminated and strndup()
897 * is missing on some BSD systems */
898 client->events[event] = scalloc(len + 1);
899 memcpy(client->events[event], s, len);
901 DLOG("client is now subscribed to:\n");
902 for (int i = 0; i < client->num_events; i++)
903 DLOG("event %s\n", client->events[i]);
910 * Subscribes this connection to the event types which were given as a JSON
911 * serialized array in the payload field of the message.
914 IPC_HANDLER(subscribe) {
917 ipc_client *current, *client = NULL;
919 /* Search the ipc_client structure for this connection */
920 TAILQ_FOREACH(current, &all_clients, clients) {
921 if (current->fd != fd)
928 if (client == NULL) {
929 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
933 /* Setup the JSON parser */
934 static yajl_callbacks callbacks = {
935 .yajl_string = add_subscription,
938 p = yalloc(&callbacks, (void *)client);
939 stat = yajl_parse(p, (const unsigned char *)message, message_size);
940 if (stat != yajl_status_ok) {
942 err = yajl_get_error(p, true, (const unsigned char *)message,
944 ELOG("YAJL parse error: %s\n", err);
945 yajl_free_error(p, err);
947 const char *reply = "{\"success\":false}";
948 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
953 const char *reply = "{\"success\":true}";
954 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
957 /* The index of each callback function corresponds to the numeric
958 * value of the message type (see include/i3/ipc.h) */
959 handler_t handlers[8] = {
961 handle_get_workspaces,
966 handle_get_bar_config,
971 * Handler for activity on a client connection, receives a message from a
974 * For now, the maximum message size is 2048. I’m not sure for what the
975 * IPC interface will be used in the future, thus I’m not implementing a
976 * mechanism for arbitrarily long messages, as it seems like overkill
980 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
981 uint32_t message_type;
982 uint32_t message_length;
983 uint8_t *message = NULL;
985 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
986 /* EOF or other error */
988 /* Was this a spurious read? See ev(3) */
989 if (ret == -1 && errno == EAGAIN) {
994 /* If not, there was some kind of error. We don’t bother
995 * and close the connection */
998 /* Delete the client from the list of clients */
1000 TAILQ_FOREACH(current, &all_clients, clients) {
1001 if (current->fd != w->fd)
1004 for (int i = 0; i < current->num_events; i++)
1005 free(current->events[i]);
1006 /* We can call TAILQ_REMOVE because we break out of the
1007 * TAILQ_FOREACH afterwards */
1008 TAILQ_REMOVE(&all_clients, current, clients);
1013 ev_io_stop(EV_A_ w);
1017 DLOG("IPC: client disconnected\n");
1021 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1022 DLOG("Unhandled message type: %d\n", message_type);
1024 handler_t h = handlers[message_type];
1025 h(w->fd, message, 0, message_length, message_type);
1032 * Handler for activity on the listening socket, meaning that a new client
1033 * has just connected and we should accept() him. Sets up the event handler
1034 * for activity on the new connection and inserts the file descriptor into
1035 * the list of clients.
1038 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1039 struct sockaddr_un peer;
1040 socklen_t len = sizeof(struct sockaddr_un);
1042 if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1050 /* Close this file descriptor on exec() */
1051 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1053 set_nonblock(client);
1055 struct ev_io *package = scalloc(sizeof(struct ev_io));
1056 ev_io_init(package, ipc_receive_message, client, EV_READ);
1057 ev_io_start(EV_A_ package);
1059 DLOG("IPC: new client connected on fd %d\n", w->fd);
1061 ipc_client *new = scalloc(sizeof(ipc_client));
1064 TAILQ_INSERT_TAIL(&all_clients, new, clients);
1068 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1069 * mode, bind()s and listen()s on it.
1072 int ipc_create_socket(const char *filename) {
1075 FREE(current_socketpath);
1077 char *resolved = resolve_tilde(filename);
1078 DLOG("Creating IPC-socket at %s\n", resolved);
1079 char *copy = sstrdup(resolved);
1080 const char *dir = dirname(copy);
1081 if (!path_exists(dir))
1085 /* Unlink the unix domain socket before */
1088 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1094 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1096 struct sockaddr_un addr;
1097 memset(&addr, 0, sizeof(struct sockaddr_un));
1098 addr.sun_family = AF_LOCAL;
1099 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1100 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1106 set_nonblock(sockfd);
1108 if (listen(sockfd, 5) < 0) {
1114 current_socketpath = resolved;
1119 * For the workspace "focus" event we send, along the usual "change" field,
1120 * also the current and previous workspace, in "current" and "old"
1123 void ipc_send_workspace_focus_event(Con *current, Con *old) {
1124 setlocale(LC_NUMERIC, "C");
1125 yajl_gen gen = ygenalloc();
1133 dump_node(gen, current, false);
1139 dump_node(gen, old, false);
1143 const unsigned char *payload;
1145 y(get_buf, &payload, &length);
1147 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1149 setlocale(LC_NUMERIC, "");
1153 * For the window events we send, along the usual "change" field,
1154 * also the window container, in "container".
1156 void ipc_send_window_event(const char *property, Con *con) {
1157 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1158 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1160 setlocale(LC_NUMERIC, "C");
1161 yajl_gen gen = ygenalloc();
1169 dump_node(gen, con, false);
1173 const unsigned char *payload;
1175 y(get_buf, &payload, &length);
1177 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1179 setlocale(LC_NUMERIC, "");
1183 * For the barconfig update events, we send the serialized barconfig.
1185 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1186 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1187 setlocale(LC_NUMERIC, "C");
1188 yajl_gen gen = ygenalloc();
1190 dump_bar_config(gen, barconfig);
1192 const unsigned char *payload;
1194 y(get_buf, &payload, &length);
1196 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1198 setlocale(LC_NUMERIC, "");
1202 * For the binding events, we send the serialized binding struct.
1204 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1205 DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1207 setlocale(LC_NUMERIC, "C");
1209 yajl_gen gen = ygenalloc();
1217 dump_binding(gen, bind);
1221 const unsigned char *payload;
1223 y(get_buf, &payload, &length);
1225 ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1228 setlocale(LC_NUMERIC, "");