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 = sstrdup(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 ystr("current_border_width");
275 y(integer, con->current_border_width);
277 dump_rect(gen, "rect", con->rect);
278 dump_rect(gen, "window_rect", con->window_rect);
279 dump_rect(gen, "geometry", con->geometry);
282 if (con->window && con->window->name)
283 ystr(i3string_as_utf8(con->window->name));
287 if (con->type == CT_WORKSPACE) {
289 y(integer, con->num);
294 y(integer, con->window->id);
300 if (con->type != CT_DOCKAREA || !inplace_restart) {
301 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
302 dump_node(gen, node, inplace_restart);
307 ystr("floating_nodes");
309 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
310 dump_node(gen, node, inplace_restart);
316 TAILQ_FOREACH(node, &(con->focus_head), focused) {
317 y(integer, (long int)node);
321 ystr("fullscreen_mode");
322 y(integer, con->fullscreen_mode);
325 switch (con->floating) {
326 case FLOATING_AUTO_OFF:
329 case FLOATING_AUTO_ON:
332 case FLOATING_USER_OFF:
335 case FLOATING_USER_ON:
343 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
344 if (match->dock != -1) {
347 y(integer, match->dock);
348 ystr("insert_where");
349 y(integer, match->insert_where);
353 /* TODO: the other swallow keys */
356 if (inplace_restart) {
357 if (con->window != NULL) {
360 y(integer, con->window->id);
361 ystr("restart_mode");
372 setlocale(LC_NUMERIC, "C");
374 yajl_gen gen = yajl_gen_alloc(NULL);
376 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
378 dump_node(gen, croot, false);
379 setlocale(LC_NUMERIC, "");
381 const unsigned char *payload;
387 y(get_buf, &payload, &length);
389 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
395 * Formats the reply message for a GET_WORKSPACES request and sends it to the
399 IPC_HANDLER(get_workspaces) {
401 yajl_gen gen = yajl_gen_alloc(NULL);
403 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
407 Con *focused_ws = con_get_workspace(focused);
410 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
411 if (con_is_internal(output))
414 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
415 assert(ws->type == CT_WORKSPACE);
421 else y(integer, ws->num);
427 y(bool, workspace_is_visible(ws));
430 y(bool, ws == focused_ws);
435 y(integer, ws->rect.x);
437 y(integer, ws->rect.y);
439 y(integer, ws->rect.width);
441 y(integer, ws->rect.height);
456 const unsigned char *payload;
462 y(get_buf, &payload, &length);
464 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
469 * Formats the reply message for a GET_OUTPUTS request and sends it to the
473 IPC_HANDLER(get_outputs) {
475 yajl_gen gen = yajl_gen_alloc(NULL);
477 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
482 TAILQ_FOREACH(output, &outputs, outputs) {
489 y(bool, output->active);
492 y(bool, output->primary);
497 y(integer, output->rect.x);
499 y(integer, output->rect.y);
501 y(integer, output->rect.width);
503 y(integer, output->rect.height);
506 ystr("current_workspace");
508 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
517 const unsigned char *payload;
523 y(get_buf, &payload, &length);
525 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
530 * Formats the reply message for a GET_MARKS request and sends it to the
534 IPC_HANDLER(get_marks) {
536 yajl_gen gen = yajl_gen_alloc(NULL);
538 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
543 TAILQ_FOREACH(con, &all_cons, all_cons)
544 if (con->mark != NULL)
549 const unsigned char *payload;
555 y(get_buf, &payload, &length);
557 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
562 * Returns the version of i3
565 IPC_HANDLER(get_version) {
567 yajl_gen gen = yajl_gen_alloc(NULL);
569 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
574 y(integer, MAJOR_VERSION);
577 y(integer, MINOR_VERSION);
580 y(integer, PATCH_VERSION);
582 ystr("human_readable");
587 const unsigned char *payload;
593 y(get_buf, &payload, &length);
595 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
600 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
604 IPC_HANDLER(get_bar_config) {
606 yajl_gen gen = yajl_gen_alloc(NULL);
608 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
611 /* If no ID was passed, we return a JSON array with all IDs */
612 if (message_size == 0) {
615 TAILQ_FOREACH(current, &barconfigs, configs) {
620 const unsigned char *payload;
626 y(get_buf, &payload, &length);
628 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
633 /* To get a properly terminated buffer, we copy
634 * message_size bytes out of the buffer */
635 char *bar_id = scalloc(message_size + 1);
636 strncpy(bar_id, (const char*)message, message_size);
637 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
638 Barconfig *current, *config = NULL;
639 TAILQ_FOREACH(current, &barconfigs, configs) {
640 if (strcmp(current->id, bar_id) != 0)
650 /* If we did not find a config for the given ID, the reply will contain
651 * a null 'id' field. */
658 if (config->num_outputs > 0) {
661 for (int c = 0; c < config->num_outputs; c++)
662 ystr(config->outputs[c]);
666 #define YSTR_IF_SET(name) \
668 if (config->name) { \
670 ystr(config->name); \
674 YSTR_IF_SET(tray_output);
675 YSTR_IF_SET(socket_path);
678 if (config->mode == M_HIDE)
683 switch (config->modifier) {
713 if (config->position == P_BOTTOM)
717 YSTR_IF_SET(status_command);
720 ystr("workspace_buttons");
721 y(bool, !config->hide_workspace_buttons);
724 y(bool, config->verbose);
727 #define YSTR_IF_SET(name) \
729 if (config->colors.name) { \
731 ystr(config->colors.name); \
737 YSTR_IF_SET(background);
738 YSTR_IF_SET(statusline);
739 YSTR_IF_SET(focused_workspace_border);
740 YSTR_IF_SET(focused_workspace_bg);
741 YSTR_IF_SET(focused_workspace_text);
742 YSTR_IF_SET(active_workspace_border);
743 YSTR_IF_SET(active_workspace_bg);
744 YSTR_IF_SET(active_workspace_text);
745 YSTR_IF_SET(inactive_workspace_border);
746 YSTR_IF_SET(inactive_workspace_bg);
747 YSTR_IF_SET(inactive_workspace_text);
748 YSTR_IF_SET(urgent_workspace_border);
749 YSTR_IF_SET(urgent_workspace_bg);
750 YSTR_IF_SET(urgent_workspace_text);
758 const unsigned char *payload;
764 y(get_buf, &payload, &length);
766 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
771 * Callback for the YAJL parser (will be called when a string is parsed).
775 static int add_subscription(void *extra, const unsigned char *s,
778 static int add_subscription(void *extra, const unsigned char *s,
781 ipc_client *client = extra;
783 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
784 int event = client->num_events;
786 client->num_events++;
787 client->events = realloc(client->events, client->num_events * sizeof(char*));
788 /* We copy the string because it is not null-terminated and strndup()
789 * is missing on some BSD systems */
790 client->events[event] = scalloc(len+1);
791 memcpy(client->events[event], s, len);
793 DLOG("client is now subscribed to:\n");
794 for (int i = 0; i < client->num_events; i++)
795 DLOG("event %s\n", client->events[i]);
802 * Subscribes this connection to the event types which were given as a JSON
803 * serialized array in the payload field of the message.
806 IPC_HANDLER(subscribe) {
808 yajl_callbacks callbacks;
810 ipc_client *current, *client = NULL;
812 /* Search the ipc_client structure for this connection */
813 TAILQ_FOREACH(current, &all_clients, clients) {
814 if (current->fd != fd)
821 if (client == NULL) {
822 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
826 /* Setup the JSON parser */
827 memset(&callbacks, 0, sizeof(yajl_callbacks));
828 callbacks.yajl_string = add_subscription;
831 p = yajl_alloc(&callbacks, NULL, (void*)client);
833 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
835 stat = yajl_parse(p, (const unsigned char*)message, message_size);
836 if (stat != yajl_status_ok) {
838 err = yajl_get_error(p, true, (const unsigned char*)message,
840 ELOG("YAJL parse error: %s\n", err);
841 yajl_free_error(p, err);
843 const char *reply = "{\"success\":false}";
844 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
849 const char *reply = "{\"success\":true}";
850 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
853 /* The index of each callback function corresponds to the numeric
854 * value of the message type (see include/i3/ipc.h) */
855 handler_t handlers[8] = {
857 handle_get_workspaces,
862 handle_get_bar_config,
867 * Handler for activity on a client connection, receives a message from a
870 * For now, the maximum message size is 2048. I’m not sure for what the
871 * IPC interface will be used in the future, thus I’m not implementing a
872 * mechanism for arbitrarily long messages, as it seems like overkill
876 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
878 int n = read(w->fd, buf, sizeof(buf));
880 /* On error or an empty message, we close the connection */
883 /* FIXME: I get these when closing a client socket,
884 * therefore we just treat them as an error. Is this
886 if (errno == EAGAIN || errno == EWOULDBLOCK)
890 /* If not, there was some kind of error. We don’t bother
891 * and close the connection */
894 /* Delete the client from the list of clients */
896 TAILQ_FOREACH(current, &all_clients, clients) {
897 if (current->fd != w->fd)
900 for (int i = 0; i < current->num_events; i++)
901 free(current->events[i]);
902 /* We can call TAILQ_REMOVE because we break out of the
903 * TAILQ_FOREACH afterwards */
904 TAILQ_REMOVE(&all_clients, current, clients);
912 DLOG("IPC: client disconnected\n");
916 /* Terminate the message correctly */
919 /* Check if the message starts with the i3 IPC magic code */
920 if (n < strlen(I3_IPC_MAGIC)) {
921 DLOG("IPC: message too short, ignoring\n");
925 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
926 DLOG("IPC: message does not start with the IPC magic\n");
930 uint8_t *message = (uint8_t*)buf;
932 DLOG("IPC: n = %d\n", n);
933 message += strlen(I3_IPC_MAGIC);
934 n -= strlen(I3_IPC_MAGIC);
936 /* The next 32 bit after the magic are the message size */
937 uint32_t message_size;
938 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
939 message += sizeof(uint32_t);
940 n -= sizeof(uint32_t);
942 if (message_size > n) {
943 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
947 /* The last 32 bits of the header are the message type */
948 uint32_t message_type;
949 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
950 message += sizeof(uint32_t);
951 n -= sizeof(uint32_t);
953 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
954 DLOG("Unhandled message type: %d\n", message_type);
956 handler_t h = handlers[message_type];
957 h(w->fd, message, n, message_size, message_type);
960 message += message_size;
965 * Handler for activity on the listening socket, meaning that a new client
966 * has just connected and we should accept() him. Sets up the event handler
967 * for activity on the new connection and inserts the file descriptor into
968 * the list of clients.
971 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
972 struct sockaddr_un peer;
973 socklen_t len = sizeof(struct sockaddr_un);
975 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
978 else perror("accept()");
982 /* Close this file descriptor on exec() */
983 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
985 set_nonblock(client);
987 struct ev_io *package = scalloc(sizeof(struct ev_io));
988 ev_io_init(package, ipc_receive_message, client, EV_READ);
989 ev_io_start(EV_A_ package);
991 DLOG("IPC: new client connected on fd %d\n", w->fd);
993 ipc_client *new = scalloc(sizeof(ipc_client));
996 TAILQ_INSERT_TAIL(&all_clients, new, clients);
1000 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1001 * mode, bind()s and listen()s on it.
1004 int ipc_create_socket(const char *filename) {
1007 FREE(current_socketpath);
1009 char *resolved = resolve_tilde(filename);
1010 DLOG("Creating IPC-socket at %s\n", resolved);
1011 char *copy = sstrdup(resolved);
1012 const char *dir = dirname(copy);
1013 if (!path_exists(dir))
1017 /* Unlink the unix domain socket before */
1020 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1026 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1028 struct sockaddr_un addr;
1029 memset(&addr, 0, sizeof(struct sockaddr_un));
1030 addr.sun_family = AF_LOCAL;
1031 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1032 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1038 set_nonblock(sockfd);
1040 if (listen(sockfd, 5) < 0) {
1046 current_socketpath = resolved;