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"));
163 if (bind->symbol == NULL)
173 for (int i = 0; i < 8; i++) {
174 if (bind->mods & (1 << i)) {
176 case XCB_MOD_MASK_SHIFT:
179 case XCB_MOD_MASK_LOCK:
182 case XCB_MOD_MASK_CONTROL:
208 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
211 y(integer, (long int)con);
224 case CT_FLOATING_CON:
225 ystr("floating_con");
234 DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
239 /* provided for backwards compatibility only. */
241 if (!con_is_split(con))
244 if (con_orientation(con) == HORIZ)
250 ystr("scratchpad_state");
251 switch (con->scratchpad_state) {
252 case SCRATCHPAD_NONE:
255 case SCRATCHPAD_FRESH:
258 case SCRATCHPAD_CHANGED:
264 if (con->percent == 0.0)
267 y(double, con->percent);
270 y(bool, con->urgent);
272 if (con->mark != NULL) {
278 y(bool, (con == focused));
281 switch (con->layout) {
283 DLOG("About to dump layout=default, this is a bug in the code.\n");
306 ystr("workspace_layout");
307 switch (con->workspace_layout) {
318 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
323 ystr("last_split_layout");
324 switch (con->layout) {
334 switch (con->border_style) {
346 ystr("current_border_width");
347 y(integer, con->current_border_width);
349 dump_rect(gen, "rect", con->rect);
350 dump_rect(gen, "deco_rect", con->deco_rect);
351 dump_rect(gen, "window_rect", con->window_rect);
352 dump_rect(gen, "geometry", con->geometry);
355 if (con->window && con->window->name)
356 ystr(i3string_as_utf8(con->window->name));
357 else if (con->name != NULL)
362 if (con->type == CT_WORKSPACE) {
364 y(integer, con->num);
369 y(integer, con->window->id);
373 if (con->window && !inplace_restart) {
374 /* Window properties are useless to preserve when restarting because
375 * they will be queried again anyway. However, for i3-save-tree(1),
376 * they are very useful and save i3-save-tree dealing with X11. */
377 ystr("window_properties");
380 #define DUMP_PROPERTY(key, prop_name) \
382 if (con->window->prop_name != NULL) { \
384 ystr(con->window->prop_name); \
388 DUMP_PROPERTY("class", class_class);
389 DUMP_PROPERTY("instance", class_instance);
390 DUMP_PROPERTY("window_role", role);
392 if (con->window->name != NULL) {
394 ystr(i3string_as_utf8(con->window->name));
397 ystr("transient_for");
398 if (con->window->transient_for == XCB_NONE)
401 y(integer, con->window->transient_for);
409 if (con->type != CT_DOCKAREA || !inplace_restart) {
410 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
411 dump_node(gen, node, inplace_restart);
416 ystr("floating_nodes");
418 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
419 dump_node(gen, node, inplace_restart);
425 TAILQ_FOREACH(node, &(con->focus_head), focused) {
426 y(integer, (long int)node);
430 ystr("fullscreen_mode");
431 y(integer, con->fullscreen_mode);
434 switch (con->floating) {
435 case FLOATING_AUTO_OFF:
438 case FLOATING_AUTO_ON:
441 case FLOATING_USER_OFF:
444 case FLOATING_USER_ON:
452 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
453 /* We will generate a new restart_mode match specification after this
454 * loop, so skip this one. */
455 if (match->restart_mode)
458 if (match->dock != -1) {
460 y(integer, match->dock);
461 ystr("insert_where");
462 y(integer, match->insert_where);
465 #define DUMP_REGEX(re_name) \
467 if (match->re_name != NULL) { \
469 ystr(match->re_name->pattern); \
474 DUMP_REGEX(instance);
475 DUMP_REGEX(window_role);
482 if (inplace_restart) {
483 if (con->window != NULL) {
486 y(integer, con->window->id);
487 ystr("restart_mode");
494 if (inplace_restart && con->window != NULL) {
496 y(integer, con->depth);
502 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
508 if (config->num_outputs > 0) {
511 for (int c = 0; c < config->num_outputs; c++)
512 ystr(config->outputs[c]);
516 #define YSTR_IF_SET(name) \
518 if (config->name) { \
520 ystr(config->name); \
524 YSTR_IF_SET(tray_output);
525 YSTR_IF_SET(socket_path);
528 switch (config->mode) {
541 ystr("hidden_state");
542 switch (config->hidden_state) {
553 switch (config->modifier) {
582 if (config->wheel_up_cmd) {
583 ystr("wheel_up_cmd");
584 ystr(config->wheel_up_cmd);
587 if (config->wheel_down_cmd) {
588 ystr("wheel_down_cmd");
589 ystr(config->wheel_down_cmd);
593 if (config->position == P_BOTTOM)
598 YSTR_IF_SET(status_command);
601 if (config->separator_symbol) {
602 ystr("separator_symbol");
603 ystr(config->separator_symbol);
606 ystr("workspace_buttons");
607 y(bool, !config->hide_workspace_buttons);
609 ystr("strip_workspace_numbers");
610 y(bool, config->strip_workspace_numbers);
612 ystr("binding_mode_indicator");
613 y(bool, !config->hide_binding_mode_indicator);
616 y(bool, config->verbose);
619 #define YSTR_IF_SET(name) \
621 if (config->colors.name) { \
623 ystr(config->colors.name); \
629 YSTR_IF_SET(background);
630 YSTR_IF_SET(statusline);
631 YSTR_IF_SET(separator);
632 YSTR_IF_SET(focused_workspace_border);
633 YSTR_IF_SET(focused_workspace_bg);
634 YSTR_IF_SET(focused_workspace_text);
635 YSTR_IF_SET(active_workspace_border);
636 YSTR_IF_SET(active_workspace_bg);
637 YSTR_IF_SET(active_workspace_text);
638 YSTR_IF_SET(inactive_workspace_border);
639 YSTR_IF_SET(inactive_workspace_bg);
640 YSTR_IF_SET(inactive_workspace_text);
641 YSTR_IF_SET(urgent_workspace_border);
642 YSTR_IF_SET(urgent_workspace_bg);
643 YSTR_IF_SET(urgent_workspace_text);
651 setlocale(LC_NUMERIC, "C");
652 yajl_gen gen = ygenalloc();
653 dump_node(gen, croot, false);
654 setlocale(LC_NUMERIC, "");
656 const unsigned char *payload;
658 y(get_buf, &payload, &length);
660 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
665 * Formats the reply message for a GET_WORKSPACES request and sends it to the
669 IPC_HANDLER(get_workspaces) {
670 yajl_gen gen = ygenalloc();
673 Con *focused_ws = con_get_workspace(focused);
676 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
677 if (con_is_internal(output))
680 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
681 assert(ws->type == CT_WORKSPACE);
691 y(bool, workspace_is_visible(ws));
694 y(bool, ws == focused_ws);
699 y(integer, ws->rect.x);
701 y(integer, ws->rect.y);
703 y(integer, ws->rect.width);
705 y(integer, ws->rect.height);
720 const unsigned char *payload;
722 y(get_buf, &payload, &length);
724 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
729 * Formats the reply message for a GET_OUTPUTS request and sends it to the
733 IPC_HANDLER(get_outputs) {
734 yajl_gen gen = ygenalloc();
738 TAILQ_FOREACH(output, &outputs, outputs) {
745 y(bool, output->active);
748 y(bool, output->primary);
753 y(integer, output->rect.x);
755 y(integer, output->rect.y);
757 y(integer, output->rect.width);
759 y(integer, output->rect.height);
762 ystr("current_workspace");
764 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
774 const unsigned char *payload;
776 y(get_buf, &payload, &length);
778 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
783 * Formats the reply message for a GET_MARKS request and sends it to the
787 IPC_HANDLER(get_marks) {
788 yajl_gen gen = ygenalloc();
792 TAILQ_FOREACH(con, &all_cons, all_cons)
793 if (con->mark != NULL)
798 const unsigned char *payload;
800 y(get_buf, &payload, &length);
802 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
807 * Returns the version of i3
810 IPC_HANDLER(get_version) {
811 yajl_gen gen = ygenalloc();
815 y(integer, MAJOR_VERSION);
818 y(integer, MINOR_VERSION);
821 y(integer, PATCH_VERSION);
823 ystr("human_readable");
828 const unsigned char *payload;
830 y(get_buf, &payload, &length);
832 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
837 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
841 IPC_HANDLER(get_bar_config) {
842 yajl_gen gen = ygenalloc();
844 /* If no ID was passed, we return a JSON array with all IDs */
845 if (message_size == 0) {
848 TAILQ_FOREACH(current, &barconfigs, configs) {
853 const unsigned char *payload;
855 y(get_buf, &payload, &length);
857 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
862 /* To get a properly terminated buffer, we copy
863 * message_size bytes out of the buffer */
864 char *bar_id = scalloc(message_size + 1);
865 strncpy(bar_id, (const char *)message, message_size);
866 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
867 Barconfig *current, *config = NULL;
868 TAILQ_FOREACH(current, &barconfigs, configs) {
869 if (strcmp(current->id, bar_id) != 0)
877 /* If we did not find a config for the given ID, the reply will contain
878 * a null 'id' field. */
886 dump_bar_config(gen, config);
889 const unsigned char *payload;
891 y(get_buf, &payload, &length);
893 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
898 * Callback for the YAJL parser (will be called when a string is parsed).
901 static int add_subscription(void *extra, const unsigned char *s,
903 ipc_client *client = extra;
905 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
906 int event = client->num_events;
908 client->num_events++;
909 client->events = realloc(client->events, client->num_events * sizeof(char *));
910 /* We copy the string because it is not null-terminated and strndup()
911 * is missing on some BSD systems */
912 client->events[event] = scalloc(len + 1);
913 memcpy(client->events[event], s, len);
915 DLOG("client is now subscribed to:\n");
916 for (int i = 0; i < client->num_events; i++)
917 DLOG("event %s\n", client->events[i]);
924 * Subscribes this connection to the event types which were given as a JSON
925 * serialized array in the payload field of the message.
928 IPC_HANDLER(subscribe) {
931 ipc_client *current, *client = NULL;
933 /* Search the ipc_client structure for this connection */
934 TAILQ_FOREACH(current, &all_clients, clients) {
935 if (current->fd != fd)
942 if (client == NULL) {
943 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
947 /* Setup the JSON parser */
948 static yajl_callbacks callbacks = {
949 .yajl_string = add_subscription,
952 p = yalloc(&callbacks, (void *)client);
953 stat = yajl_parse(p, (const unsigned char *)message, message_size);
954 if (stat != yajl_status_ok) {
956 err = yajl_get_error(p, true, (const unsigned char *)message,
958 ELOG("YAJL parse error: %s\n", err);
959 yajl_free_error(p, err);
961 const char *reply = "{\"success\":false}";
962 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
967 const char *reply = "{\"success\":true}";
968 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
971 /* The index of each callback function corresponds to the numeric
972 * value of the message type (see include/i3/ipc.h) */
973 handler_t handlers[8] = {
975 handle_get_workspaces,
980 handle_get_bar_config,
985 * Handler for activity on a client connection, receives a message from a
988 * For now, the maximum message size is 2048. I’m not sure for what the
989 * IPC interface will be used in the future, thus I’m not implementing a
990 * mechanism for arbitrarily long messages, as it seems like overkill
994 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
995 uint32_t message_type;
996 uint32_t message_length;
997 uint8_t *message = NULL;
999 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
1000 /* EOF or other error */
1002 /* Was this a spurious read? See ev(3) */
1003 if (ret == -1 && errno == EAGAIN) {
1008 /* If not, there was some kind of error. We don’t bother
1009 * and close the connection */
1012 /* Delete the client from the list of clients */
1013 ipc_client *current;
1014 TAILQ_FOREACH(current, &all_clients, clients) {
1015 if (current->fd != w->fd)
1018 for (int i = 0; i < current->num_events; i++)
1019 free(current->events[i]);
1020 /* We can call TAILQ_REMOVE because we break out of the
1021 * TAILQ_FOREACH afterwards */
1022 TAILQ_REMOVE(&all_clients, current, clients);
1027 ev_io_stop(EV_A_ w);
1031 DLOG("IPC: client disconnected\n");
1035 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1036 DLOG("Unhandled message type: %d\n", message_type);
1038 handler_t h = handlers[message_type];
1039 h(w->fd, message, 0, message_length, message_type);
1046 * Handler for activity on the listening socket, meaning that a new client
1047 * has just connected and we should accept() him. Sets up the event handler
1048 * for activity on the new connection and inserts the file descriptor into
1049 * the list of clients.
1052 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1053 struct sockaddr_un peer;
1054 socklen_t len = sizeof(struct sockaddr_un);
1056 if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1064 /* Close this file descriptor on exec() */
1065 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1067 set_nonblock(client);
1069 struct ev_io *package = scalloc(sizeof(struct ev_io));
1070 ev_io_init(package, ipc_receive_message, client, EV_READ);
1071 ev_io_start(EV_A_ package);
1073 DLOG("IPC: new client connected on fd %d\n", w->fd);
1075 ipc_client *new = scalloc(sizeof(ipc_client));
1078 TAILQ_INSERT_TAIL(&all_clients, new, clients);
1082 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1083 * mode, bind()s and listen()s on it.
1086 int ipc_create_socket(const char *filename) {
1089 FREE(current_socketpath);
1091 char *resolved = resolve_tilde(filename);
1092 DLOG("Creating IPC-socket at %s\n", resolved);
1093 char *copy = sstrdup(resolved);
1094 const char *dir = dirname(copy);
1095 if (!path_exists(dir))
1099 /* Unlink the unix domain socket before */
1102 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1108 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1110 struct sockaddr_un addr;
1111 memset(&addr, 0, sizeof(struct sockaddr_un));
1112 addr.sun_family = AF_LOCAL;
1113 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1114 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1120 set_nonblock(sockfd);
1122 if (listen(sockfd, 5) < 0) {
1128 current_socketpath = resolved;
1133 * Generates a json workspace event. Returns a dynamically allocated yajl
1134 * generator. Free with yajl_gen_free().
1136 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1137 setlocale(LC_NUMERIC, "C");
1138 yajl_gen gen = ygenalloc();
1146 if (current == NULL)
1149 dump_node(gen, current, false);
1155 dump_node(gen, old, false);
1159 setlocale(LC_NUMERIC, "");
1165 * For the workspace events we send, along with the usual "change" field, also
1166 * the workspace container in "current". For focus events, we send the
1167 * previously focused workspace in "old".
1169 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1170 yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1172 const unsigned char *payload;
1174 y(get_buf, &payload, &length);
1176 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1182 * For the window events we send, along the usual "change" field,
1183 * also the window container, in "container".
1185 void ipc_send_window_event(const char *property, Con *con) {
1186 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1187 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1189 setlocale(LC_NUMERIC, "C");
1190 yajl_gen gen = ygenalloc();
1198 dump_node(gen, con, false);
1202 const unsigned char *payload;
1204 y(get_buf, &payload, &length);
1206 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1208 setlocale(LC_NUMERIC, "");
1212 * For the barconfig update events, we send the serialized barconfig.
1214 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1215 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1216 setlocale(LC_NUMERIC, "C");
1217 yajl_gen gen = ygenalloc();
1219 dump_bar_config(gen, barconfig);
1221 const unsigned char *payload;
1223 y(get_buf, &payload, &length);
1225 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1227 setlocale(LC_NUMERIC, "");
1231 * For the binding events, we send the serialized binding struct.
1233 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1234 DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1236 setlocale(LC_NUMERIC, "C");
1238 yajl_gen gen = ygenalloc();
1246 dump_binding(gen, bind);
1250 const unsigned char *payload;
1252 y(get_buf, &payload, &length);
1254 ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1257 setlocale(LC_NUMERIC, "");