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 static 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 struct CommandResultIR *command_output = parse_command((const char*)command);
123 if (command_output->needs_tree_render)
126 const unsigned char *reply;
128 yajl_gen_get_buf(command_output->json_gen, &reply, &length);
130 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
131 (const uint8_t*)reply);
133 yajl_gen_free(command_output->json_gen);
136 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
146 y(integer, r.height);
150 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
153 y(integer, (long int)con);
166 case CT_FLOATING_CON:
167 ystr("floating_con");
176 DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
181 /* provided for backwards compatibility only. */
183 if (!con_is_split(con))
186 if (con_orientation(con) == HORIZ)
188 else ystr("vertical");
191 ystr("scratchpad_state");
192 switch (con->scratchpad_state) {
193 case SCRATCHPAD_NONE:
196 case SCRATCHPAD_FRESH:
199 case SCRATCHPAD_CHANGED:
205 if (con->percent == 0.0)
207 else y(double, con->percent);
210 y(bool, con->urgent);
212 if (con->mark != NULL) {
218 y(bool, (con == focused));
221 switch (con->layout) {
223 DLOG("About to dump layout=default, this is a bug in the code.\n");
246 ystr("workspace_layout");
247 switch (con->workspace_layout) {
258 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
263 ystr("last_split_layout");
264 switch (con->layout) {
274 switch (con->border_style) {
286 ystr("current_border_width");
287 y(integer, con->current_border_width);
289 dump_rect(gen, "rect", con->rect);
290 dump_rect(gen, "window_rect", con->window_rect);
291 dump_rect(gen, "geometry", con->geometry);
294 if (con->window && con->window->name)
295 ystr(i3string_as_utf8(con->window->name));
299 if (con->type == CT_WORKSPACE) {
301 y(integer, con->num);
306 y(integer, con->window->id);
309 if (con->window && !inplace_restart) {
310 /* Window properties are useless to preserve when restarting because
311 * they will be queried again anyway. However, for i3-save-tree(1),
312 * they are very useful and save i3-save-tree dealing with X11. */
313 ystr("window_properties");
316 #define DUMP_PROPERTY(key, prop_name) do { \
317 if (con->window->prop_name != NULL) { \
319 ystr(con->window->prop_name); \
323 DUMP_PROPERTY("class", class_class);
324 DUMP_PROPERTY("instance", class_instance);
325 DUMP_PROPERTY("window_role", role);
327 if (con->window->name != NULL) {
329 ystr(i3string_as_utf8(con->window->name));
338 if (con->type != CT_DOCKAREA || !inplace_restart) {
339 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
340 dump_node(gen, node, inplace_restart);
345 ystr("floating_nodes");
347 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
348 dump_node(gen, node, inplace_restart);
354 TAILQ_FOREACH(node, &(con->focus_head), focused) {
355 y(integer, (long int)node);
359 ystr("fullscreen_mode");
360 y(integer, con->fullscreen_mode);
363 switch (con->floating) {
364 case FLOATING_AUTO_OFF:
367 case FLOATING_AUTO_ON:
370 case FLOATING_USER_OFF:
373 case FLOATING_USER_ON:
381 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
383 if (match->dock != -1) {
385 y(integer, match->dock);
386 ystr("insert_where");
387 y(integer, match->insert_where);
390 #define DUMP_REGEX(re_name) do { \
391 if (match->re_name != NULL) { \
393 ystr(match->re_name->pattern); \
398 DUMP_REGEX(instance);
399 DUMP_REGEX(window_role);
406 if (inplace_restart) {
407 if (con->window != NULL) {
410 y(integer, con->window->id);
411 ystr("restart_mode");
418 if (inplace_restart && con->window != NULL) {
420 y(integer, con->depth);
426 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
432 if (config->num_outputs > 0) {
435 for (int c = 0; c < config->num_outputs; c++)
436 ystr(config->outputs[c]);
440 #define YSTR_IF_SET(name) \
442 if (config->name) { \
444 ystr(config->name); \
448 YSTR_IF_SET(tray_output);
449 YSTR_IF_SET(socket_path);
452 switch (config->mode) {
465 ystr("hidden_state");
466 switch (config->hidden_state) {
477 switch (config->modifier) {
507 if (config->position == P_BOTTOM)
511 YSTR_IF_SET(status_command);
514 ystr("workspace_buttons");
515 y(bool, !config->hide_workspace_buttons);
517 ystr("strip_workspace_numbers");
518 y(bool, config->strip_workspace_numbers);
520 ystr("binding_mode_indicator");
521 y(bool, !config->hide_binding_mode_indicator);
524 y(bool, config->verbose);
527 #define YSTR_IF_SET(name) \
529 if (config->colors.name) { \
531 ystr(config->colors.name); \
537 YSTR_IF_SET(background);
538 YSTR_IF_SET(statusline);
539 YSTR_IF_SET(separator);
540 YSTR_IF_SET(focused_workspace_border);
541 YSTR_IF_SET(focused_workspace_bg);
542 YSTR_IF_SET(focused_workspace_text);
543 YSTR_IF_SET(active_workspace_border);
544 YSTR_IF_SET(active_workspace_bg);
545 YSTR_IF_SET(active_workspace_text);
546 YSTR_IF_SET(inactive_workspace_border);
547 YSTR_IF_SET(inactive_workspace_bg);
548 YSTR_IF_SET(inactive_workspace_text);
549 YSTR_IF_SET(urgent_workspace_border);
550 YSTR_IF_SET(urgent_workspace_bg);
551 YSTR_IF_SET(urgent_workspace_text);
559 setlocale(LC_NUMERIC, "C");
560 yajl_gen gen = ygenalloc();
561 dump_node(gen, croot, false);
562 setlocale(LC_NUMERIC, "");
564 const unsigned char *payload;
566 y(get_buf, &payload, &length);
568 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
574 * Formats the reply message for a GET_WORKSPACES request and sends it to the
578 IPC_HANDLER(get_workspaces) {
579 yajl_gen gen = ygenalloc();
582 Con *focused_ws = con_get_workspace(focused);
585 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
586 if (con_is_internal(output))
589 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
590 assert(ws->type == CT_WORKSPACE);
596 else y(integer, ws->num);
602 y(bool, workspace_is_visible(ws));
605 y(bool, ws == focused_ws);
610 y(integer, ws->rect.x);
612 y(integer, ws->rect.y);
614 y(integer, ws->rect.width);
616 y(integer, ws->rect.height);
631 const unsigned char *payload;
633 y(get_buf, &payload, &length);
635 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
640 * Formats the reply message for a GET_OUTPUTS request and sends it to the
644 IPC_HANDLER(get_outputs) {
645 yajl_gen gen = ygenalloc();
649 TAILQ_FOREACH(output, &outputs, outputs) {
656 y(bool, output->active);
659 y(bool, output->primary);
664 y(integer, output->rect.x);
666 y(integer, output->rect.y);
668 y(integer, output->rect.width);
670 y(integer, output->rect.height);
673 ystr("current_workspace");
675 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
684 const unsigned char *payload;
686 y(get_buf, &payload, &length);
688 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
693 * Formats the reply message for a GET_MARKS request and sends it to the
697 IPC_HANDLER(get_marks) {
698 yajl_gen gen = ygenalloc();
702 TAILQ_FOREACH(con, &all_cons, all_cons)
703 if (con->mark != NULL)
708 const unsigned char *payload;
710 y(get_buf, &payload, &length);
712 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
717 * Returns the version of i3
720 IPC_HANDLER(get_version) {
721 yajl_gen gen = ygenalloc();
725 y(integer, MAJOR_VERSION);
728 y(integer, MINOR_VERSION);
731 y(integer, PATCH_VERSION);
733 ystr("human_readable");
738 const unsigned char *payload;
740 y(get_buf, &payload, &length);
742 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
747 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
751 IPC_HANDLER(get_bar_config) {
752 yajl_gen gen = ygenalloc();
754 /* If no ID was passed, we return a JSON array with all IDs */
755 if (message_size == 0) {
758 TAILQ_FOREACH(current, &barconfigs, configs) {
763 const unsigned char *payload;
765 y(get_buf, &payload, &length);
767 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
772 /* To get a properly terminated buffer, we copy
773 * message_size bytes out of the buffer */
774 char *bar_id = scalloc(message_size + 1);
775 strncpy(bar_id, (const char*)message, message_size);
776 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
777 Barconfig *current, *config = NULL;
778 TAILQ_FOREACH(current, &barconfigs, configs) {
779 if (strcmp(current->id, bar_id) != 0)
787 /* If we did not find a config for the given ID, the reply will contain
788 * a null 'id' field. */
796 dump_bar_config(gen, config);
799 const unsigned char *payload;
801 y(get_buf, &payload, &length);
803 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
808 * Callback for the YAJL parser (will be called when a string is parsed).
811 static int add_subscription(void *extra, const unsigned char *s,
813 ipc_client *client = extra;
815 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
816 int event = client->num_events;
818 client->num_events++;
819 client->events = realloc(client->events, client->num_events * sizeof(char*));
820 /* We copy the string because it is not null-terminated and strndup()
821 * is missing on some BSD systems */
822 client->events[event] = scalloc(len+1);
823 memcpy(client->events[event], s, len);
825 DLOG("client is now subscribed to:\n");
826 for (int i = 0; i < client->num_events; i++)
827 DLOG("event %s\n", client->events[i]);
834 * Subscribes this connection to the event types which were given as a JSON
835 * serialized array in the payload field of the message.
838 IPC_HANDLER(subscribe) {
841 ipc_client *current, *client = NULL;
843 /* Search the ipc_client structure for this connection */
844 TAILQ_FOREACH(current, &all_clients, clients) {
845 if (current->fd != fd)
852 if (client == NULL) {
853 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
857 /* Setup the JSON parser */
858 static yajl_callbacks callbacks = {
859 .yajl_string = add_subscription,
862 p = yalloc(&callbacks, (void*)client);
863 stat = yajl_parse(p, (const unsigned char*)message, message_size);
864 if (stat != yajl_status_ok) {
866 err = yajl_get_error(p, true, (const unsigned char*)message,
868 ELOG("YAJL parse error: %s\n", err);
869 yajl_free_error(p, err);
871 const char *reply = "{\"success\":false}";
872 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
877 const char *reply = "{\"success\":true}";
878 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
881 /* The index of each callback function corresponds to the numeric
882 * value of the message type (see include/i3/ipc.h) */
883 handler_t handlers[8] = {
885 handle_get_workspaces,
890 handle_get_bar_config,
895 * Handler for activity on a client connection, receives a message from a
898 * For now, the maximum message size is 2048. I’m not sure for what the
899 * IPC interface will be used in the future, thus I’m not implementing a
900 * mechanism for arbitrarily long messages, as it seems like overkill
904 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
905 uint32_t message_type;
906 uint32_t message_length;
907 uint8_t *message = NULL;
909 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
910 /* EOF or other error */
912 /* Was this a spurious read? See ev(3) */
913 if (ret == -1 && errno == EAGAIN) {
918 /* If not, there was some kind of error. We don’t bother
919 * and close the connection */
922 /* Delete the client from the list of clients */
924 TAILQ_FOREACH(current, &all_clients, clients) {
925 if (current->fd != w->fd)
928 for (int i = 0; i < current->num_events; i++)
929 free(current->events[i]);
930 /* We can call TAILQ_REMOVE because we break out of the
931 * TAILQ_FOREACH afterwards */
932 TAILQ_REMOVE(&all_clients, current, clients);
941 DLOG("IPC: client disconnected\n");
945 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
946 DLOG("Unhandled message type: %d\n", message_type);
948 handler_t h = handlers[message_type];
949 h(w->fd, message, 0, message_length, message_type);
956 * Handler for activity on the listening socket, meaning that a new client
957 * has just connected and we should accept() him. Sets up the event handler
958 * for activity on the new connection and inserts the file descriptor into
959 * the list of clients.
962 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
963 struct sockaddr_un peer;
964 socklen_t len = sizeof(struct sockaddr_un);
966 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
969 else perror("accept()");
973 /* Close this file descriptor on exec() */
974 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
976 set_nonblock(client);
978 struct ev_io *package = scalloc(sizeof(struct ev_io));
979 ev_io_init(package, ipc_receive_message, client, EV_READ);
980 ev_io_start(EV_A_ package);
982 DLOG("IPC: new client connected on fd %d\n", w->fd);
984 ipc_client *new = scalloc(sizeof(ipc_client));
987 TAILQ_INSERT_TAIL(&all_clients, new, clients);
991 * Creates the UNIX domain socket at the given path, sets it to non-blocking
992 * mode, bind()s and listen()s on it.
995 int ipc_create_socket(const char *filename) {
998 FREE(current_socketpath);
1000 char *resolved = resolve_tilde(filename);
1001 DLOG("Creating IPC-socket at %s\n", resolved);
1002 char *copy = sstrdup(resolved);
1003 const char *dir = dirname(copy);
1004 if (!path_exists(dir))
1008 /* Unlink the unix domain socket before */
1011 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1017 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1019 struct sockaddr_un addr;
1020 memset(&addr, 0, sizeof(struct sockaddr_un));
1021 addr.sun_family = AF_LOCAL;
1022 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1023 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1029 set_nonblock(sockfd);
1031 if (listen(sockfd, 5) < 0) {
1037 current_socketpath = resolved;
1042 * For the workspace "focus" event we send, along the usual "change" field,
1043 * also the current and previous workspace, in "current" and "old"
1046 void ipc_send_workspace_focus_event(Con *current, Con *old) {
1047 setlocale(LC_NUMERIC, "C");
1048 yajl_gen gen = ygenalloc();
1056 dump_node(gen, current, false);
1062 dump_node(gen, old, false);
1066 const unsigned char *payload;
1068 y(get_buf, &payload, &length);
1070 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1072 setlocale(LC_NUMERIC, "");
1076 * For the window events we send, along the usual "change" field,
1077 * also the window container, in "container".
1079 void ipc_send_window_event(const char *property, Con *con) {
1080 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1081 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1083 setlocale(LC_NUMERIC, "C");
1084 yajl_gen gen = ygenalloc();
1092 dump_node(gen, con, false);
1096 const unsigned char *payload;
1098 y(get_buf, &payload, &length);
1100 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1102 setlocale(LC_NUMERIC, "");
1106 * For the barconfig update events, we send the serialized barconfig.
1108 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1109 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1110 setlocale(LC_NUMERIC, "C");
1111 yajl_gen gen = ygenalloc();
1113 dump_bar_config(gen, barconfig);
1115 const unsigned char *payload;
1117 y(get_buf, &payload, &length);
1119 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1121 setlocale(LC_NUMERIC, "");