2 #define I3__FILE__ "ipc.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009 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 * Sends the specified event to all IPC clients which are currently connected
42 * and subscribed to this kind of event.
45 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
47 TAILQ_FOREACH(current, &all_clients, clients) {
48 /* see if this client is interested in this event */
49 bool interested = false;
50 for (int i = 0; i < current->num_events; i++) {
51 if (strcasecmp(current->events[i], event) != 0)
59 ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t *)payload);
64 * Calls shutdown() on each socket and closes it. This function to be called
65 * when exiting or restarting only!
68 void ipc_shutdown(void) {
70 while (!TAILQ_EMPTY(&all_clients)) {
71 current = TAILQ_FIRST(&all_clients);
72 shutdown(current->fd, SHUT_RDWR);
74 TAILQ_REMOVE(&all_clients, current, clients);
80 * Executes the command and returns whether it could be successfully parsed
81 * or not (at the moment, always returns true).
84 IPC_HANDLER(command) {
85 /* To get a properly terminated buffer, we copy
86 * message_size bytes out of the buffer */
87 char *command = scalloc(message_size + 1);
88 strncpy(command, (const char *)message, message_size);
89 LOG("IPC: received: *%s*\n", command);
90 yajl_gen gen = yajl_gen_alloc(NULL);
92 CommandResult *result = parse_command((const char *)command, gen);
95 if (result->needs_tree_render)
98 command_result_free(result);
100 const unsigned char *reply;
102 yajl_gen_get_buf(gen, &reply, &length);
104 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
105 (const uint8_t *)reply);
110 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
120 y(integer, r.height);
124 static void dump_binding(yajl_gen gen, Binding *bind) {
127 y(integer, bind->keycode);
130 ystr((const char *)(bind->input_type == B_KEYBOARD ? "keyboard" : "mouse"));
133 if (bind->symbol == NULL)
143 for (int i = 0; i < 8; i++) {
144 if (bind->mods & (1 << i)) {
146 case XCB_MOD_MASK_SHIFT:
149 case XCB_MOD_MASK_LOCK:
152 case XCB_MOD_MASK_CONTROL:
178 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
181 y(integer, (long int)con);
194 case CT_FLOATING_CON:
195 ystr("floating_con");
204 DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
209 /* provided for backwards compatibility only. */
211 if (!con_is_split(con))
214 if (con_orientation(con) == HORIZ)
220 ystr("scratchpad_state");
221 switch (con->scratchpad_state) {
222 case SCRATCHPAD_NONE:
225 case SCRATCHPAD_FRESH:
228 case SCRATCHPAD_CHANGED:
234 if (con->percent == 0.0)
237 y(double, con->percent);
240 y(bool, con->urgent);
242 if (con->mark != NULL) {
248 y(bool, (con == focused));
251 switch (con->layout) {
253 DLOG("About to dump layout=default, this is a bug in the code.\n");
276 ystr("workspace_layout");
277 switch (con->workspace_layout) {
288 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
293 ystr("last_split_layout");
294 switch (con->layout) {
304 switch (con->border_style) {
316 ystr("current_border_width");
317 y(integer, con->current_border_width);
319 dump_rect(gen, "rect", con->rect);
320 dump_rect(gen, "deco_rect", con->deco_rect);
321 dump_rect(gen, "window_rect", con->window_rect);
322 dump_rect(gen, "geometry", con->geometry);
325 if (con->window && con->window->name)
326 ystr(i3string_as_utf8(con->window->name));
327 else if (con->name != NULL)
332 if (con->type == CT_WORKSPACE) {
334 y(integer, con->num);
339 y(integer, con->window->id);
343 if (con->window && !inplace_restart) {
344 /* Window properties are useless to preserve when restarting because
345 * they will be queried again anyway. However, for i3-save-tree(1),
346 * they are very useful and save i3-save-tree dealing with X11. */
347 ystr("window_properties");
350 #define DUMP_PROPERTY(key, prop_name) \
352 if (con->window->prop_name != NULL) { \
354 ystr(con->window->prop_name); \
358 DUMP_PROPERTY("class", class_class);
359 DUMP_PROPERTY("instance", class_instance);
360 DUMP_PROPERTY("window_role", role);
362 if (con->window->name != NULL) {
364 ystr(i3string_as_utf8(con->window->name));
367 ystr("transient_for");
368 if (con->window->transient_for == XCB_NONE)
371 y(integer, con->window->transient_for);
379 if (con->type != CT_DOCKAREA || !inplace_restart) {
380 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
381 dump_node(gen, node, inplace_restart);
386 ystr("floating_nodes");
388 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
389 dump_node(gen, node, inplace_restart);
395 TAILQ_FOREACH(node, &(con->focus_head), focused) {
396 y(integer, (long int)node);
400 ystr("fullscreen_mode");
401 y(integer, con->fullscreen_mode);
404 switch (con->floating) {
405 case FLOATING_AUTO_OFF:
408 case FLOATING_AUTO_ON:
411 case FLOATING_USER_OFF:
414 case FLOATING_USER_ON:
422 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
423 /* We will generate a new restart_mode match specification after this
424 * loop, so skip this one. */
425 if (match->restart_mode)
428 if (match->dock != -1) {
430 y(integer, match->dock);
431 ystr("insert_where");
432 y(integer, match->insert_where);
435 #define DUMP_REGEX(re_name) \
437 if (match->re_name != NULL) { \
439 ystr(match->re_name->pattern); \
444 DUMP_REGEX(instance);
445 DUMP_REGEX(window_role);
452 if (inplace_restart) {
453 if (con->window != NULL) {
456 y(integer, con->window->id);
457 ystr("restart_mode");
464 if (inplace_restart && con->window != NULL) {
466 y(integer, con->depth);
472 static void dump_mouse_commands(yajl_gen gen, Barconfig *config) {
473 ystr("mouse_commands");
476 struct Mousecommand *current;
477 TAILQ_FOREACH(current, &(config->mouse_commands), commands) {
478 ystr(current->button);
479 ystr(current->command);
485 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
491 if (config->num_outputs > 0) {
494 for (int c = 0; c < config->num_outputs; c++)
495 ystr(config->outputs[c]);
499 #define YSTR_IF_SET(name) \
501 if (config->name) { \
503 ystr(config->name); \
507 YSTR_IF_SET(tray_output);
508 YSTR_IF_SET(socket_path);
511 switch (config->mode) {
524 ystr("hidden_state");
525 switch (config->hidden_state) {
536 switch (config->modifier) {
565 dump_mouse_commands(gen, config);
568 if (config->position == P_BOTTOM)
573 YSTR_IF_SET(status_command);
576 if (config->separator_symbol) {
577 ystr("separator_symbol");
578 ystr(config->separator_symbol);
581 ystr("workspace_buttons");
582 y(bool, !config->hide_workspace_buttons);
584 ystr("strip_workspace_numbers");
585 y(bool, config->strip_workspace_numbers);
587 ystr("binding_mode_indicator");
588 y(bool, !config->hide_binding_mode_indicator);
591 y(bool, config->verbose);
594 #define YSTR_IF_SET(name) \
596 if (config->colors.name) { \
598 ystr(config->colors.name); \
604 YSTR_IF_SET(background);
605 YSTR_IF_SET(statusline);
606 YSTR_IF_SET(separator);
607 YSTR_IF_SET(focused_workspace_border);
608 YSTR_IF_SET(focused_workspace_bg);
609 YSTR_IF_SET(focused_workspace_text);
610 YSTR_IF_SET(active_workspace_border);
611 YSTR_IF_SET(active_workspace_bg);
612 YSTR_IF_SET(active_workspace_text);
613 YSTR_IF_SET(inactive_workspace_border);
614 YSTR_IF_SET(inactive_workspace_bg);
615 YSTR_IF_SET(inactive_workspace_text);
616 YSTR_IF_SET(urgent_workspace_border);
617 YSTR_IF_SET(urgent_workspace_bg);
618 YSTR_IF_SET(urgent_workspace_text);
619 YSTR_IF_SET(binding_mode_border);
620 YSTR_IF_SET(binding_mode_bg);
621 YSTR_IF_SET(binding_mode_text);
629 setlocale(LC_NUMERIC, "C");
630 yajl_gen gen = ygenalloc();
631 dump_node(gen, croot, false);
632 setlocale(LC_NUMERIC, "");
634 const unsigned char *payload;
636 y(get_buf, &payload, &length);
638 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
643 * Formats the reply message for a GET_WORKSPACES request and sends it to the
647 IPC_HANDLER(get_workspaces) {
648 yajl_gen gen = ygenalloc();
651 Con *focused_ws = con_get_workspace(focused);
654 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
655 if (con_is_internal(output))
658 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
659 assert(ws->type == CT_WORKSPACE);
669 y(bool, workspace_is_visible(ws));
672 y(bool, ws == focused_ws);
677 y(integer, ws->rect.x);
679 y(integer, ws->rect.y);
681 y(integer, ws->rect.width);
683 y(integer, ws->rect.height);
698 const unsigned char *payload;
700 y(get_buf, &payload, &length);
702 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
707 * Formats the reply message for a GET_OUTPUTS request and sends it to the
711 IPC_HANDLER(get_outputs) {
712 yajl_gen gen = ygenalloc();
716 TAILQ_FOREACH(output, &outputs, outputs) {
723 y(bool, output->active);
726 y(bool, output->primary);
731 y(integer, output->rect.x);
733 y(integer, output->rect.y);
735 y(integer, output->rect.width);
737 y(integer, output->rect.height);
740 ystr("current_workspace");
742 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
752 const unsigned char *payload;
754 y(get_buf, &payload, &length);
756 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
761 * Formats the reply message for a GET_MARKS request and sends it to the
765 IPC_HANDLER(get_marks) {
766 yajl_gen gen = ygenalloc();
770 TAILQ_FOREACH(con, &all_cons, all_cons)
771 if (con->mark != NULL)
776 const unsigned char *payload;
778 y(get_buf, &payload, &length);
780 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
785 * Returns the version of i3
788 IPC_HANDLER(get_version) {
789 yajl_gen gen = ygenalloc();
793 y(integer, MAJOR_VERSION);
796 y(integer, MINOR_VERSION);
799 y(integer, PATCH_VERSION);
801 ystr("human_readable");
806 const unsigned char *payload;
808 y(get_buf, &payload, &length);
810 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
815 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
819 IPC_HANDLER(get_bar_config) {
820 yajl_gen gen = ygenalloc();
822 /* If no ID was passed, we return a JSON array with all IDs */
823 if (message_size == 0) {
826 TAILQ_FOREACH(current, &barconfigs, configs) {
831 const unsigned char *payload;
833 y(get_buf, &payload, &length);
835 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
840 /* To get a properly terminated buffer, we copy
841 * message_size bytes out of the buffer */
842 char *bar_id = scalloc(message_size + 1);
843 strncpy(bar_id, (const char *)message, message_size);
844 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
845 Barconfig *current, *config = NULL;
846 TAILQ_FOREACH(current, &barconfigs, configs) {
847 if (strcmp(current->id, bar_id) != 0)
855 /* If we did not find a config for the given ID, the reply will contain
856 * a null 'id' field. */
864 dump_bar_config(gen, config);
867 const unsigned char *payload;
869 y(get_buf, &payload, &length);
871 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
876 * Callback for the YAJL parser (will be called when a string is parsed).
879 static int add_subscription(void *extra, const unsigned char *s,
881 ipc_client *client = extra;
883 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
884 int event = client->num_events;
886 client->num_events++;
887 client->events = realloc(client->events, client->num_events * sizeof(char *));
888 /* We copy the string because it is not null-terminated and strndup()
889 * is missing on some BSD systems */
890 client->events[event] = scalloc(len + 1);
891 memcpy(client->events[event], s, len);
893 DLOG("client is now subscribed to:\n");
894 for (int i = 0; i < client->num_events; i++)
895 DLOG("event %s\n", client->events[i]);
902 * Subscribes this connection to the event types which were given as a JSON
903 * serialized array in the payload field of the message.
906 IPC_HANDLER(subscribe) {
909 ipc_client *current, *client = NULL;
911 /* Search the ipc_client structure for this connection */
912 TAILQ_FOREACH(current, &all_clients, clients) {
913 if (current->fd != fd)
920 if (client == NULL) {
921 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
925 /* Setup the JSON parser */
926 static yajl_callbacks callbacks = {
927 .yajl_string = add_subscription,
930 p = yalloc(&callbacks, (void *)client);
931 stat = yajl_parse(p, (const unsigned char *)message, message_size);
932 if (stat != yajl_status_ok) {
934 err = yajl_get_error(p, true, (const unsigned char *)message,
936 ELOG("YAJL parse error: %s\n", err);
937 yajl_free_error(p, err);
939 const char *reply = "{\"success\":false}";
940 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
945 const char *reply = "{\"success\":true}";
946 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
949 /* The index of each callback function corresponds to the numeric
950 * value of the message type (see include/i3/ipc.h) */
951 handler_t handlers[8] = {
953 handle_get_workspaces,
958 handle_get_bar_config,
963 * Handler for activity on a client connection, receives a message from a
966 * For now, the maximum message size is 2048. I’m not sure for what the
967 * IPC interface will be used in the future, thus I’m not implementing a
968 * mechanism for arbitrarily long messages, as it seems like overkill
972 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
973 uint32_t message_type;
974 uint32_t message_length;
975 uint8_t *message = NULL;
977 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
978 /* EOF or other error */
980 /* Was this a spurious read? See ev(3) */
981 if (ret == -1 && errno == EAGAIN) {
986 /* If not, there was some kind of error. We don’t bother
987 * and close the connection */
990 /* Delete the client from the list of clients */
992 TAILQ_FOREACH(current, &all_clients, clients) {
993 if (current->fd != w->fd)
996 for (int i = 0; i < current->num_events; i++)
997 free(current->events[i]);
998 /* We can call TAILQ_REMOVE because we break out of the
999 * TAILQ_FOREACH afterwards */
1000 TAILQ_REMOVE(&all_clients, current, clients);
1005 ev_io_stop(EV_A_ w);
1009 DLOG("IPC: client disconnected\n");
1013 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1014 DLOG("Unhandled message type: %d\n", message_type);
1016 handler_t h = handlers[message_type];
1017 h(w->fd, message, 0, message_length, message_type);
1024 * Handler for activity on the listening socket, meaning that a new client
1025 * has just connected and we should accept() him. Sets up the event handler
1026 * for activity on the new connection and inserts the file descriptor into
1027 * the list of clients.
1030 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1031 struct sockaddr_un peer;
1032 socklen_t len = sizeof(struct sockaddr_un);
1034 if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1042 /* Close this file descriptor on exec() */
1043 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1045 set_nonblock(client);
1047 struct ev_io *package = scalloc(sizeof(struct ev_io));
1048 ev_io_init(package, ipc_receive_message, client, EV_READ);
1049 ev_io_start(EV_A_ package);
1051 DLOG("IPC: new client connected on fd %d\n", w->fd);
1053 ipc_client *new = scalloc(sizeof(ipc_client));
1056 TAILQ_INSERT_TAIL(&all_clients, new, clients);
1060 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1061 * mode, bind()s and listen()s on it.
1064 int ipc_create_socket(const char *filename) {
1067 FREE(current_socketpath);
1069 char *resolved = resolve_tilde(filename);
1070 DLOG("Creating IPC-socket at %s\n", resolved);
1071 char *copy = sstrdup(resolved);
1072 const char *dir = dirname(copy);
1073 if (!path_exists(dir))
1077 /* Unlink the unix domain socket before */
1080 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1086 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1088 struct sockaddr_un addr;
1089 memset(&addr, 0, sizeof(struct sockaddr_un));
1090 addr.sun_family = AF_LOCAL;
1091 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1092 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1098 set_nonblock(sockfd);
1100 if (listen(sockfd, 5) < 0) {
1106 current_socketpath = resolved;
1111 * Generates a json workspace event. Returns a dynamically allocated yajl
1112 * generator. Free with yajl_gen_free().
1114 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1115 setlocale(LC_NUMERIC, "C");
1116 yajl_gen gen = ygenalloc();
1124 if (current == NULL)
1127 dump_node(gen, current, false);
1133 dump_node(gen, old, false);
1137 setlocale(LC_NUMERIC, "");
1143 * For the workspace events we send, along with the usual "change" field, also
1144 * the workspace container in "current". For focus events, we send the
1145 * previously focused workspace in "old".
1147 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1148 yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1150 const unsigned char *payload;
1152 y(get_buf, &payload, &length);
1154 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1160 * For the window events we send, along the usual "change" field,
1161 * also the window container, in "container".
1163 void ipc_send_window_event(const char *property, Con *con) {
1164 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1165 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1167 setlocale(LC_NUMERIC, "C");
1168 yajl_gen gen = ygenalloc();
1176 dump_node(gen, con, false);
1180 const unsigned char *payload;
1182 y(get_buf, &payload, &length);
1184 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1186 setlocale(LC_NUMERIC, "");
1190 * For the barconfig update events, we send the serialized barconfig.
1192 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1193 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1194 setlocale(LC_NUMERIC, "C");
1195 yajl_gen gen = ygenalloc();
1197 dump_bar_config(gen, barconfig);
1199 const unsigned char *payload;
1201 y(get_buf, &payload, &length);
1203 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1205 setlocale(LC_NUMERIC, "");
1209 * For the binding events, we send the serialized binding struct.
1211 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1212 DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1214 setlocale(LC_NUMERIC, "C");
1216 yajl_gen gen = ygenalloc();
1224 dump_binding(gen, bind);
1228 const unsigned char *payload;
1230 y(get_buf, &payload, &length);
1232 ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1235 setlocale(LC_NUMERIC, "");