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("last_split_layout");
235 switch (con->layout) {
245 switch (con->border_style) {
257 dump_rect(gen, "rect", con->rect);
258 dump_rect(gen, "window_rect", con->window_rect);
259 dump_rect(gen, "geometry", con->geometry);
262 if (con->window && con->window->name)
263 ystr(i3string_as_utf8(con->window->name));
267 if (con->type == CT_WORKSPACE) {
269 y(integer, con->num);
274 y(integer, con->window->id);
280 if (con->type != CT_DOCKAREA || !inplace_restart) {
281 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
282 dump_node(gen, node, inplace_restart);
287 ystr("floating_nodes");
289 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
290 dump_node(gen, node, inplace_restart);
296 TAILQ_FOREACH(node, &(con->focus_head), focused) {
297 y(integer, (long int)node);
301 ystr("fullscreen_mode");
302 y(integer, con->fullscreen_mode);
305 switch (con->floating) {
306 case FLOATING_AUTO_OFF:
309 case FLOATING_AUTO_ON:
312 case FLOATING_USER_OFF:
315 case FLOATING_USER_ON:
323 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
324 if (match->dock != -1) {
327 y(integer, match->dock);
328 ystr("insert_where");
329 y(integer, match->insert_where);
333 /* TODO: the other swallow keys */
336 if (inplace_restart) {
337 if (con->window != NULL) {
340 y(integer, con->window->id);
341 ystr("restart_mode");
352 setlocale(LC_NUMERIC, "C");
354 yajl_gen gen = yajl_gen_alloc(NULL);
356 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
358 dump_node(gen, croot, false);
359 setlocale(LC_NUMERIC, "");
361 const unsigned char *payload;
367 y(get_buf, &payload, &length);
369 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
375 * Formats the reply message for a GET_WORKSPACES request and sends it to the
379 IPC_HANDLER(get_workspaces) {
381 yajl_gen gen = yajl_gen_alloc(NULL);
383 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
387 Con *focused_ws = con_get_workspace(focused);
390 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
391 if (output->name[0] == '_' && output->name[1] == '_')
394 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
395 assert(ws->type == CT_WORKSPACE);
401 else y(integer, ws->num);
407 y(bool, workspace_is_visible(ws));
410 y(bool, ws == focused_ws);
415 y(integer, ws->rect.x);
417 y(integer, ws->rect.y);
419 y(integer, ws->rect.width);
421 y(integer, ws->rect.height);
436 const unsigned char *payload;
442 y(get_buf, &payload, &length);
444 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
449 * Formats the reply message for a GET_OUTPUTS request and sends it to the
453 IPC_HANDLER(get_outputs) {
455 yajl_gen gen = yajl_gen_alloc(NULL);
457 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
462 TAILQ_FOREACH(output, &outputs, outputs) {
469 y(bool, output->active);
472 y(bool, output->primary);
477 y(integer, output->rect.x);
479 y(integer, output->rect.y);
481 y(integer, output->rect.width);
483 y(integer, output->rect.height);
486 ystr("current_workspace");
488 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
497 const unsigned char *payload;
503 y(get_buf, &payload, &length);
505 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
510 * Formats the reply message for a GET_MARKS request and sends it to the
514 IPC_HANDLER(get_marks) {
516 yajl_gen gen = yajl_gen_alloc(NULL);
518 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
523 TAILQ_FOREACH(con, &all_cons, all_cons)
524 if (con->mark != NULL)
529 const unsigned char *payload;
535 y(get_buf, &payload, &length);
537 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
542 * Returns the version of i3
545 IPC_HANDLER(get_version) {
547 yajl_gen gen = yajl_gen_alloc(NULL);
549 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
554 y(integer, MAJOR_VERSION);
557 y(integer, MINOR_VERSION);
560 y(integer, PATCH_VERSION);
562 ystr("human_readable");
567 const unsigned char *payload;
573 y(get_buf, &payload, &length);
575 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
580 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
584 IPC_HANDLER(get_bar_config) {
586 yajl_gen gen = yajl_gen_alloc(NULL);
588 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
591 /* If no ID was passed, we return a JSON array with all IDs */
592 if (message_size == 0) {
595 TAILQ_FOREACH(current, &barconfigs, configs) {
600 const unsigned char *payload;
606 y(get_buf, &payload, &length);
608 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
613 /* To get a properly terminated buffer, we copy
614 * message_size bytes out of the buffer */
615 char *bar_id = scalloc(message_size + 1);
616 strncpy(bar_id, (const char*)message, message_size);
617 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
618 Barconfig *current, *config = NULL;
619 TAILQ_FOREACH(current, &barconfigs, configs) {
620 if (strcmp(current->id, bar_id) != 0)
630 /* If we did not find a config for the given ID, the reply will contain
631 * a null 'id' field. */
638 if (config->num_outputs > 0) {
641 for (int c = 0; c < config->num_outputs; c++)
642 ystr(config->outputs[c]);
646 #define YSTR_IF_SET(name) \
648 if (config->name) { \
650 ystr(config->name); \
654 YSTR_IF_SET(tray_output);
655 YSTR_IF_SET(socket_path);
658 if (config->mode == M_HIDE)
663 switch (config->modifier) {
693 if (config->position == P_BOTTOM)
697 YSTR_IF_SET(status_command);
700 ystr("workspace_buttons");
701 y(bool, !config->hide_workspace_buttons);
704 y(bool, config->verbose);
707 #define YSTR_IF_SET(name) \
709 if (config->colors.name) { \
711 ystr(config->colors.name); \
717 YSTR_IF_SET(background);
718 YSTR_IF_SET(statusline);
719 YSTR_IF_SET(focused_workspace_border);
720 YSTR_IF_SET(focused_workspace_bg);
721 YSTR_IF_SET(focused_workspace_text);
722 YSTR_IF_SET(active_workspace_border);
723 YSTR_IF_SET(active_workspace_bg);
724 YSTR_IF_SET(active_workspace_text);
725 YSTR_IF_SET(inactive_workspace_border);
726 YSTR_IF_SET(inactive_workspace_bg);
727 YSTR_IF_SET(inactive_workspace_text);
728 YSTR_IF_SET(urgent_workspace_border);
729 YSTR_IF_SET(urgent_workspace_bg);
730 YSTR_IF_SET(urgent_workspace_text);
738 const unsigned char *payload;
744 y(get_buf, &payload, &length);
746 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
751 * Callback for the YAJL parser (will be called when a string is parsed).
755 static int add_subscription(void *extra, const unsigned char *s,
758 static int add_subscription(void *extra, const unsigned char *s,
761 ipc_client *client = extra;
763 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
764 int event = client->num_events;
766 client->num_events++;
767 client->events = realloc(client->events, client->num_events * sizeof(char*));
768 /* We copy the string because it is not null-terminated and strndup()
769 * is missing on some BSD systems */
770 client->events[event] = scalloc(len+1);
771 memcpy(client->events[event], s, len);
773 DLOG("client is now subscribed to:\n");
774 for (int i = 0; i < client->num_events; i++)
775 DLOG("event %s\n", client->events[i]);
782 * Subscribes this connection to the event types which were given as a JSON
783 * serialized array in the payload field of the message.
786 IPC_HANDLER(subscribe) {
788 yajl_callbacks callbacks;
790 ipc_client *current, *client = NULL;
792 /* Search the ipc_client structure for this connection */
793 TAILQ_FOREACH(current, &all_clients, clients) {
794 if (current->fd != fd)
801 if (client == NULL) {
802 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
806 /* Setup the JSON parser */
807 memset(&callbacks, 0, sizeof(yajl_callbacks));
808 callbacks.yajl_string = add_subscription;
811 p = yajl_alloc(&callbacks, NULL, (void*)client);
813 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
815 stat = yajl_parse(p, (const unsigned char*)message, message_size);
816 if (stat != yajl_status_ok) {
818 err = yajl_get_error(p, true, (const unsigned char*)message,
820 ELOG("YAJL parse error: %s\n", err);
821 yajl_free_error(p, err);
823 const char *reply = "{\"success\":false}";
824 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
829 const char *reply = "{\"success\":true}";
830 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
833 /* The index of each callback function corresponds to the numeric
834 * value of the message type (see include/i3/ipc.h) */
835 handler_t handlers[8] = {
837 handle_get_workspaces,
842 handle_get_bar_config,
847 * Handler for activity on a client connection, receives a message from a
850 * For now, the maximum message size is 2048. I’m not sure for what the
851 * IPC interface will be used in the future, thus I’m not implementing a
852 * mechanism for arbitrarily long messages, as it seems like overkill
856 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
858 int n = read(w->fd, buf, sizeof(buf));
860 /* On error or an empty message, we close the connection */
863 /* FIXME: I get these when closing a client socket,
864 * therefore we just treat them as an error. Is this
866 if (errno == EAGAIN || errno == EWOULDBLOCK)
870 /* If not, there was some kind of error. We don’t bother
871 * and close the connection */
874 /* Delete the client from the list of clients */
876 TAILQ_FOREACH(current, &all_clients, clients) {
877 if (current->fd != w->fd)
880 for (int i = 0; i < current->num_events; i++)
881 free(current->events[i]);
882 /* We can call TAILQ_REMOVE because we break out of the
883 * TAILQ_FOREACH afterwards */
884 TAILQ_REMOVE(&all_clients, current, clients);
892 DLOG("IPC: client disconnected\n");
896 /* Terminate the message correctly */
899 /* Check if the message starts with the i3 IPC magic code */
900 if (n < strlen(I3_IPC_MAGIC)) {
901 DLOG("IPC: message too short, ignoring\n");
905 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
906 DLOG("IPC: message does not start with the IPC magic\n");
910 uint8_t *message = (uint8_t*)buf;
912 DLOG("IPC: n = %d\n", n);
913 message += strlen(I3_IPC_MAGIC);
914 n -= strlen(I3_IPC_MAGIC);
916 /* The next 32 bit after the magic are the message size */
917 uint32_t message_size;
918 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
919 message += sizeof(uint32_t);
920 n -= sizeof(uint32_t);
922 if (message_size > n) {
923 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
927 /* The last 32 bits of the header are the message type */
928 uint32_t message_type;
929 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
930 message += sizeof(uint32_t);
931 n -= sizeof(uint32_t);
933 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
934 DLOG("Unhandled message type: %d\n", message_type);
936 handler_t h = handlers[message_type];
937 h(w->fd, message, n, message_size, message_type);
940 message += message_size;
945 * Handler for activity on the listening socket, meaning that a new client
946 * has just connected and we should accept() him. Sets up the event handler
947 * for activity on the new connection and inserts the file descriptor into
948 * the list of clients.
951 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
952 struct sockaddr_un peer;
953 socklen_t len = sizeof(struct sockaddr_un);
955 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
958 else perror("accept()");
962 /* Close this file descriptor on exec() */
963 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
965 set_nonblock(client);
967 struct ev_io *package = scalloc(sizeof(struct ev_io));
968 ev_io_init(package, ipc_receive_message, client, EV_READ);
969 ev_io_start(EV_A_ package);
971 DLOG("IPC: new client connected on fd %d\n", w->fd);
973 ipc_client *new = scalloc(sizeof(ipc_client));
976 TAILQ_INSERT_TAIL(&all_clients, new, clients);
980 * Creates the UNIX domain socket at the given path, sets it to non-blocking
981 * mode, bind()s and listen()s on it.
984 int ipc_create_socket(const char *filename) {
987 FREE(current_socketpath);
989 char *resolved = resolve_tilde(filename);
990 DLOG("Creating IPC-socket at %s\n", resolved);
991 char *copy = sstrdup(resolved);
992 const char *dir = dirname(copy);
993 if (!path_exists(dir))
997 /* Unlink the unix domain socket before */
1000 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1006 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1008 struct sockaddr_un addr;
1009 memset(&addr, 0, sizeof(struct sockaddr_un));
1010 addr.sun_family = AF_LOCAL;
1011 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1012 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1018 set_nonblock(sockfd);
1020 if (listen(sockfd, 5) < 0) {
1026 current_socketpath = resolved;