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).
14 #include <sys/socket.h>
19 #include <yajl/yajl_gen.h>
20 #include <yajl/yajl_parse.h>
21 #include <yajl/yajl_version.h>
23 char *current_socketpath = NULL;
25 /* Shorter names for all those yajl_gen_* functions */
26 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
27 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
29 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
32 * Puts the given socket file descriptor into non-blocking mode or dies if
33 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
34 * IPC model because we should by no means block the window manager.
37 static void set_nonblock(int sockfd) {
38 int flags = fcntl(sockfd, F_GETFL, 0);
40 if (fcntl(sockfd, F_SETFL, flags) < 0)
41 err(-1, "Could not set O_NONBLOCK");
45 * Emulates mkdir -p (creates any missing folders)
48 static bool mkdirp(const char *path) {
49 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
51 if (errno != ENOENT) {
52 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
55 char *copy = strdup(path);
56 /* strip trailing slashes, if any */
57 while (copy[strlen(copy)-1] == '/')
58 copy[strlen(copy)-1] = '\0';
60 char *sep = strrchr(copy, '/');
68 result = mkdirp(path);
75 * Sends the specified event to all IPC clients which are currently connected
76 * and subscribed to this kind of event.
79 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
81 TAILQ_FOREACH(current, &all_clients, clients) {
82 /* see if this client is interested in this event */
83 bool interested = false;
84 for (int i = 0; i < current->num_events; i++) {
85 if (strcasecmp(current->events[i], event) != 0)
93 ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t*)payload);
98 * Calls shutdown() on each socket and closes it. This function to be called
99 * when exiting or restarting only!
102 void ipc_shutdown(void) {
104 while (!TAILQ_EMPTY(&all_clients)) {
105 current = TAILQ_FIRST(&all_clients);
106 shutdown(current->fd, SHUT_RDWR);
108 TAILQ_REMOVE(&all_clients, current, clients);
114 * Executes the command and returns whether it could be successfully parsed
115 * or not (at the moment, always returns true).
118 IPC_HANDLER(command) {
119 /* To get a properly terminated buffer, we copy
120 * message_size bytes out of the buffer */
121 char *command = scalloc(message_size + 1);
122 strncpy(command, (const char*)message, message_size);
123 LOG("IPC: received: *%s*\n", command);
124 struct CommandResult *command_output = parse_command((const char*)command);
127 if (command_output->needs_tree_render)
130 const unsigned char *reply;
136 yajl_gen_get_buf(command_output->json_gen, &reply, &length);
138 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
139 (const uint8_t*)reply);
141 yajl_gen_free(command_output->json_gen);
144 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
154 y(integer, r.height);
158 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
161 y(integer, (long int)con);
164 y(integer, con->type);
166 /* provided for backwards compatibility only. */
171 if (con_orientation(con) == HORIZ)
173 else ystr("vertical");
176 ystr("scratchpad_state");
177 switch (con->scratchpad_state) {
178 case SCRATCHPAD_NONE:
181 case SCRATCHPAD_FRESH:
184 case SCRATCHPAD_CHANGED:
190 if (con->percent == 0.0)
192 else y(double, con->percent);
195 y(bool, con->urgent);
197 if (con->mark != NULL) {
203 y(bool, (con == focused));
209 switch (con->layout) {
211 DLOG("About to dump layout=default, this is a bug in the code.\n");
234 ystr("workspace_layout");
235 switch (con->workspace_layout) {
246 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
251 ystr("last_split_layout");
252 switch (con->layout) {
262 switch (con->border_style) {
274 dump_rect(gen, "rect", con->rect);
275 dump_rect(gen, "window_rect", con->window_rect);
276 dump_rect(gen, "geometry", con->geometry);
279 if (con->window && con->window->name)
280 ystr(i3string_as_utf8(con->window->name));
284 if (con->type == CT_WORKSPACE) {
286 y(integer, con->num);
291 y(integer, con->window->id);
297 if (con->type != CT_DOCKAREA || !inplace_restart) {
298 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
299 dump_node(gen, node, inplace_restart);
304 ystr("floating_nodes");
306 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
307 dump_node(gen, node, inplace_restart);
313 TAILQ_FOREACH(node, &(con->focus_head), focused) {
314 y(integer, (long int)node);
318 ystr("fullscreen_mode");
319 y(integer, con->fullscreen_mode);
322 switch (con->floating) {
323 case FLOATING_AUTO_OFF:
326 case FLOATING_AUTO_ON:
329 case FLOATING_USER_OFF:
332 case FLOATING_USER_ON:
340 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
341 if (match->dock != -1) {
344 y(integer, match->dock);
345 ystr("insert_where");
346 y(integer, match->insert_where);
350 /* TODO: the other swallow keys */
353 if (inplace_restart) {
354 if (con->window != NULL) {
357 y(integer, con->window->id);
358 ystr("restart_mode");
369 setlocale(LC_NUMERIC, "C");
371 yajl_gen gen = yajl_gen_alloc(NULL);
373 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
375 dump_node(gen, croot, false);
376 setlocale(LC_NUMERIC, "");
378 const unsigned char *payload;
384 y(get_buf, &payload, &length);
386 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
392 * Formats the reply message for a GET_WORKSPACES request and sends it to the
396 IPC_HANDLER(get_workspaces) {
398 yajl_gen gen = yajl_gen_alloc(NULL);
400 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
404 Con *focused_ws = con_get_workspace(focused);
407 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
408 if (output->name[0] == '_' && output->name[1] == '_')
411 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
412 assert(ws->type == CT_WORKSPACE);
418 else y(integer, ws->num);
424 y(bool, workspace_is_visible(ws));
427 y(bool, ws == focused_ws);
432 y(integer, ws->rect.x);
434 y(integer, ws->rect.y);
436 y(integer, ws->rect.width);
438 y(integer, ws->rect.height);
453 const unsigned char *payload;
459 y(get_buf, &payload, &length);
461 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
466 * Formats the reply message for a GET_OUTPUTS request and sends it to the
470 IPC_HANDLER(get_outputs) {
472 yajl_gen gen = yajl_gen_alloc(NULL);
474 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
479 TAILQ_FOREACH(output, &outputs, outputs) {
486 y(bool, output->active);
489 y(bool, output->primary);
494 y(integer, output->rect.x);
496 y(integer, output->rect.y);
498 y(integer, output->rect.width);
500 y(integer, output->rect.height);
503 ystr("current_workspace");
505 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
514 const unsigned char *payload;
520 y(get_buf, &payload, &length);
522 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
527 * Formats the reply message for a GET_MARKS request and sends it to the
531 IPC_HANDLER(get_marks) {
533 yajl_gen gen = yajl_gen_alloc(NULL);
535 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
540 TAILQ_FOREACH(con, &all_cons, all_cons)
541 if (con->mark != NULL)
546 const unsigned char *payload;
552 y(get_buf, &payload, &length);
554 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
559 * Returns the version of i3
562 IPC_HANDLER(get_version) {
564 yajl_gen gen = yajl_gen_alloc(NULL);
566 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
571 y(integer, MAJOR_VERSION);
574 y(integer, MINOR_VERSION);
577 y(integer, PATCH_VERSION);
579 ystr("human_readable");
584 const unsigned char *payload;
590 y(get_buf, &payload, &length);
592 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
597 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
601 IPC_HANDLER(get_bar_config) {
603 yajl_gen gen = yajl_gen_alloc(NULL);
605 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
608 /* If no ID was passed, we return a JSON array with all IDs */
609 if (message_size == 0) {
612 TAILQ_FOREACH(current, &barconfigs, configs) {
617 const unsigned char *payload;
623 y(get_buf, &payload, &length);
625 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
630 /* To get a properly terminated buffer, we copy
631 * message_size bytes out of the buffer */
632 char *bar_id = scalloc(message_size + 1);
633 strncpy(bar_id, (const char*)message, message_size);
634 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
635 Barconfig *current, *config = NULL;
636 TAILQ_FOREACH(current, &barconfigs, configs) {
637 if (strcmp(current->id, bar_id) != 0)
647 /* If we did not find a config for the given ID, the reply will contain
648 * a null 'id' field. */
655 if (config->num_outputs > 0) {
658 for (int c = 0; c < config->num_outputs; c++)
659 ystr(config->outputs[c]);
663 #define YSTR_IF_SET(name) \
665 if (config->name) { \
667 ystr(config->name); \
671 YSTR_IF_SET(tray_output);
672 YSTR_IF_SET(socket_path);
675 if (config->mode == M_HIDE)
680 switch (config->modifier) {
710 if (config->position == P_BOTTOM)
714 YSTR_IF_SET(status_command);
717 ystr("workspace_buttons");
718 y(bool, !config->hide_workspace_buttons);
721 y(bool, config->verbose);
724 #define YSTR_IF_SET(name) \
726 if (config->colors.name) { \
728 ystr(config->colors.name); \
734 YSTR_IF_SET(background);
735 YSTR_IF_SET(statusline);
736 YSTR_IF_SET(focused_workspace_border);
737 YSTR_IF_SET(focused_workspace_bg);
738 YSTR_IF_SET(focused_workspace_text);
739 YSTR_IF_SET(active_workspace_border);
740 YSTR_IF_SET(active_workspace_bg);
741 YSTR_IF_SET(active_workspace_text);
742 YSTR_IF_SET(inactive_workspace_border);
743 YSTR_IF_SET(inactive_workspace_bg);
744 YSTR_IF_SET(inactive_workspace_text);
745 YSTR_IF_SET(urgent_workspace_border);
746 YSTR_IF_SET(urgent_workspace_bg);
747 YSTR_IF_SET(urgent_workspace_text);
755 const unsigned char *payload;
761 y(get_buf, &payload, &length);
763 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
768 * Callback for the YAJL parser (will be called when a string is parsed).
772 static int add_subscription(void *extra, const unsigned char *s,
775 static int add_subscription(void *extra, const unsigned char *s,
778 ipc_client *client = extra;
780 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
781 int event = client->num_events;
783 client->num_events++;
784 client->events = realloc(client->events, client->num_events * sizeof(char*));
785 /* We copy the string because it is not null-terminated and strndup()
786 * is missing on some BSD systems */
787 client->events[event] = scalloc(len+1);
788 memcpy(client->events[event], s, len);
790 DLOG("client is now subscribed to:\n");
791 for (int i = 0; i < client->num_events; i++)
792 DLOG("event %s\n", client->events[i]);
799 * Subscribes this connection to the event types which were given as a JSON
800 * serialized array in the payload field of the message.
803 IPC_HANDLER(subscribe) {
805 yajl_callbacks callbacks;
807 ipc_client *current, *client = NULL;
809 /* Search the ipc_client structure for this connection */
810 TAILQ_FOREACH(current, &all_clients, clients) {
811 if (current->fd != fd)
818 if (client == NULL) {
819 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
823 /* Setup the JSON parser */
824 memset(&callbacks, 0, sizeof(yajl_callbacks));
825 callbacks.yajl_string = add_subscription;
828 p = yajl_alloc(&callbacks, NULL, (void*)client);
830 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
832 stat = yajl_parse(p, (const unsigned char*)message, message_size);
833 if (stat != yajl_status_ok) {
835 err = yajl_get_error(p, true, (const unsigned char*)message,
837 ELOG("YAJL parse error: %s\n", err);
838 yajl_free_error(p, err);
840 const char *reply = "{\"success\":false}";
841 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
846 const char *reply = "{\"success\":true}";
847 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
850 /* The index of each callback function corresponds to the numeric
851 * value of the message type (see include/i3/ipc.h) */
852 handler_t handlers[8] = {
854 handle_get_workspaces,
859 handle_get_bar_config,
864 * Handler for activity on a client connection, receives a message from a
867 * For now, the maximum message size is 2048. I’m not sure for what the
868 * IPC interface will be used in the future, thus I’m not implementing a
869 * mechanism for arbitrarily long messages, as it seems like overkill
873 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
875 int n = read(w->fd, buf, sizeof(buf));
877 /* On error or an empty message, we close the connection */
880 /* FIXME: I get these when closing a client socket,
881 * therefore we just treat them as an error. Is this
883 if (errno == EAGAIN || errno == EWOULDBLOCK)
887 /* If not, there was some kind of error. We don’t bother
888 * and close the connection */
891 /* Delete the client from the list of clients */
893 TAILQ_FOREACH(current, &all_clients, clients) {
894 if (current->fd != w->fd)
897 for (int i = 0; i < current->num_events; i++)
898 free(current->events[i]);
899 /* We can call TAILQ_REMOVE because we break out of the
900 * TAILQ_FOREACH afterwards */
901 TAILQ_REMOVE(&all_clients, current, clients);
909 DLOG("IPC: client disconnected\n");
913 /* Terminate the message correctly */
916 /* Check if the message starts with the i3 IPC magic code */
917 if (n < strlen(I3_IPC_MAGIC)) {
918 DLOG("IPC: message too short, ignoring\n");
922 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
923 DLOG("IPC: message does not start with the IPC magic\n");
927 uint8_t *message = (uint8_t*)buf;
929 DLOG("IPC: n = %d\n", n);
930 message += strlen(I3_IPC_MAGIC);
931 n -= strlen(I3_IPC_MAGIC);
933 /* The next 32 bit after the magic are the message size */
934 uint32_t message_size;
935 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
936 message += sizeof(uint32_t);
937 n -= sizeof(uint32_t);
939 if (message_size > n) {
940 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
944 /* The last 32 bits of the header are the message type */
945 uint32_t message_type;
946 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
947 message += sizeof(uint32_t);
948 n -= sizeof(uint32_t);
950 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
951 DLOG("Unhandled message type: %d\n", message_type);
953 handler_t h = handlers[message_type];
954 h(w->fd, message, n, message_size, message_type);
957 message += message_size;
962 * Handler for activity on the listening socket, meaning that a new client
963 * has just connected and we should accept() him. Sets up the event handler
964 * for activity on the new connection and inserts the file descriptor into
965 * the list of clients.
968 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
969 struct sockaddr_un peer;
970 socklen_t len = sizeof(struct sockaddr_un);
972 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
975 else perror("accept()");
979 /* Close this file descriptor on exec() */
980 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
982 set_nonblock(client);
984 struct ev_io *package = scalloc(sizeof(struct ev_io));
985 ev_io_init(package, ipc_receive_message, client, EV_READ);
986 ev_io_start(EV_A_ package);
988 DLOG("IPC: new client connected on fd %d\n", w->fd);
990 ipc_client *new = scalloc(sizeof(ipc_client));
993 TAILQ_INSERT_TAIL(&all_clients, new, clients);
997 * Creates the UNIX domain socket at the given path, sets it to non-blocking
998 * mode, bind()s and listen()s on it.
1001 int ipc_create_socket(const char *filename) {
1004 FREE(current_socketpath);
1006 char *resolved = resolve_tilde(filename);
1007 DLOG("Creating IPC-socket at %s\n", resolved);
1008 char *copy = sstrdup(resolved);
1009 const char *dir = dirname(copy);
1010 if (!path_exists(dir))
1014 /* Unlink the unix domain socket before */
1017 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1023 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1025 struct sockaddr_un addr;
1026 memset(&addr, 0, sizeof(struct sockaddr_un));
1027 addr.sun_family = AF_LOCAL;
1028 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1029 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1035 set_nonblock(sockfd);
1037 if (listen(sockfd, 5) < 0) {
1043 current_socketpath = resolved;