3 * vim:ts=4:sw=4:expandtab
5 * i3 - an improved dynamic tiling window manager
6 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8 * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
13 #include <sys/socket.h>
18 #include <yajl/yajl_gen.h>
19 #include <yajl/yajl_parse.h>
20 #include <yajl/yajl_version.h>
22 char *current_socketpath = NULL;
24 /* Shorter names for all those yajl_gen_* functions */
25 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
26 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
28 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
31 * Puts the given socket file descriptor into non-blocking mode or dies if
32 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
33 * IPC model because we should by no means block the window manager.
36 static void set_nonblock(int sockfd) {
37 int flags = fcntl(sockfd, F_GETFL, 0);
39 if (fcntl(sockfd, F_SETFL, flags) < 0)
40 err(-1, "Could not set O_NONBLOCK");
44 * Emulates mkdir -p (creates any missing folders)
47 static bool mkdirp(const char *path) {
48 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
50 if (errno != ENOENT) {
51 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
54 char *copy = strdup(path);
55 /* strip trailing slashes, if any */
56 while (copy[strlen(copy)-1] == '/')
57 copy[strlen(copy)-1] = '\0';
59 char *sep = strrchr(copy, '/');
67 result = mkdirp(path);
74 * Sends the specified event to all IPC clients which are currently connected
75 * and subscribed to this kind of event.
78 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
80 TAILQ_FOREACH(current, &all_clients, clients) {
81 /* see if this client is interested in this event */
82 bool interested = false;
83 for (int i = 0; i < current->num_events; i++) {
84 if (strcasecmp(current->events[i], event) != 0)
92 ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t*)payload);
97 * Calls shutdown() on each socket and closes it. This function to be called
98 * when exiting or restarting only!
101 void ipc_shutdown(void) {
103 while (!TAILQ_EMPTY(&all_clients)) {
104 current = TAILQ_FIRST(&all_clients);
105 shutdown(current->fd, SHUT_RDWR);
107 TAILQ_REMOVE(&all_clients, current, clients);
113 * Executes the command and returns whether it could be successfully parsed
114 * or not (at the moment, always returns true).
117 IPC_HANDLER(command) {
118 /* To get a properly terminated buffer, we copy
119 * message_size bytes out of the buffer */
120 char *command = scalloc(message_size + 1);
121 strncpy(command, (const char*)message, message_size);
122 LOG("IPC: received: *%s*\n", command);
123 struct CommandResult *command_output = parse_command((const char*)command);
126 if (command_output->needs_tree_render)
129 const unsigned char *reply;
135 yajl_gen_get_buf(command_output->json_gen, &reply, &length);
137 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
138 (const uint8_t*)reply);
140 yajl_gen_free(command_output->json_gen);
143 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
153 y(integer, r.height);
157 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
160 y(integer, (long int)con);
163 y(integer, con->type);
165 /* provided for backwards compatibility only. */
170 if (con_orientation(con) == HORIZ)
172 else ystr("vertical");
175 ystr("scratchpad_state");
176 switch (con->scratchpad_state) {
177 case SCRATCHPAD_NONE:
180 case SCRATCHPAD_FRESH:
183 case SCRATCHPAD_CHANGED:
189 if (con->percent == 0.0)
191 else y(double, con->percent);
194 y(bool, con->urgent);
196 if (con->mark != NULL) {
202 y(bool, (con == focused));
208 switch (con->layout) {
210 DLOG("About to dump layout=default, this is a bug in the code.\n");
233 ystr("last_split_layout");
234 switch (con->layout) {
244 switch (con->border_style) {
256 dump_rect(gen, "rect", con->rect);
257 dump_rect(gen, "window_rect", con->window_rect);
258 dump_rect(gen, "geometry", con->geometry);
261 if (con->window && con->window->name_json)
262 ystr(con->window->name_json);
266 if (con->type == CT_WORKSPACE) {
268 y(integer, con->num);
273 y(integer, con->window->id);
279 if (con->type != CT_DOCKAREA || !inplace_restart) {
280 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
281 dump_node(gen, node, inplace_restart);
286 ystr("floating_nodes");
288 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
289 dump_node(gen, node, inplace_restart);
295 TAILQ_FOREACH(node, &(con->focus_head), focused) {
296 y(integer, (long int)node);
300 ystr("fullscreen_mode");
301 y(integer, con->fullscreen_mode);
304 switch (con->floating) {
305 case FLOATING_AUTO_OFF:
308 case FLOATING_AUTO_ON:
311 case FLOATING_USER_OFF:
314 case FLOATING_USER_ON:
322 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
323 if (match->dock != -1) {
326 y(integer, match->dock);
327 ystr("insert_where");
328 y(integer, match->insert_where);
332 /* TODO: the other swallow keys */
335 if (inplace_restart) {
336 if (con->window != NULL) {
339 y(integer, con->window->id);
340 ystr("restart_mode");
351 setlocale(LC_NUMERIC, "C");
353 yajl_gen gen = yajl_gen_alloc(NULL);
355 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
357 dump_node(gen, croot, false);
358 setlocale(LC_NUMERIC, "");
360 const unsigned char *payload;
366 y(get_buf, &payload, &length);
368 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
374 * Formats the reply message for a GET_WORKSPACES request and sends it to the
378 IPC_HANDLER(get_workspaces) {
380 yajl_gen gen = yajl_gen_alloc(NULL);
382 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
386 Con *focused_ws = con_get_workspace(focused);
389 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
390 if (output->name[0] == '_' && output->name[1] == '_')
393 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
394 assert(ws->type == CT_WORKSPACE);
400 else y(integer, ws->num);
406 y(bool, workspace_is_visible(ws));
409 y(bool, ws == focused_ws);
414 y(integer, ws->rect.x);
416 y(integer, ws->rect.y);
418 y(integer, ws->rect.width);
420 y(integer, ws->rect.height);
435 const unsigned char *payload;
441 y(get_buf, &payload, &length);
443 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
448 * Formats the reply message for a GET_OUTPUTS request and sends it to the
452 IPC_HANDLER(get_outputs) {
454 yajl_gen gen = yajl_gen_alloc(NULL);
456 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
461 TAILQ_FOREACH(output, &outputs, outputs) {
468 y(bool, output->active);
471 y(bool, output->primary);
476 y(integer, output->rect.x);
478 y(integer, output->rect.y);
480 y(integer, output->rect.width);
482 y(integer, output->rect.height);
485 ystr("current_workspace");
487 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
496 const unsigned char *payload;
502 y(get_buf, &payload, &length);
504 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
509 * Formats the reply message for a GET_MARKS request and sends it to the
513 IPC_HANDLER(get_marks) {
515 yajl_gen gen = yajl_gen_alloc(NULL);
517 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
522 TAILQ_FOREACH(con, &all_cons, all_cons)
523 if (con->mark != NULL)
528 const unsigned char *payload;
534 y(get_buf, &payload, &length);
536 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
541 * Returns the version of i3
544 IPC_HANDLER(get_version) {
546 yajl_gen gen = yajl_gen_alloc(NULL);
548 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
553 y(integer, MAJOR_VERSION);
556 y(integer, MINOR_VERSION);
559 y(integer, PATCH_VERSION);
561 ystr("human_readable");
566 const unsigned char *payload;
572 y(get_buf, &payload, &length);
574 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
579 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
583 IPC_HANDLER(get_bar_config) {
585 yajl_gen gen = yajl_gen_alloc(NULL);
587 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
590 /* If no ID was passed, we return a JSON array with all IDs */
591 if (message_size == 0) {
594 TAILQ_FOREACH(current, &barconfigs, configs) {
599 const unsigned char *payload;
605 y(get_buf, &payload, &length);
607 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
612 /* To get a properly terminated buffer, we copy
613 * message_size bytes out of the buffer */
614 char *bar_id = scalloc(message_size + 1);
615 strncpy(bar_id, (const char*)message, message_size);
616 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
617 Barconfig *current, *config = NULL;
618 TAILQ_FOREACH(current, &barconfigs, configs) {
619 if (strcmp(current->id, bar_id) != 0)
629 /* If we did not find a config for the given ID, the reply will contain
630 * a null 'id' field. */
637 if (config->num_outputs > 0) {
640 for (int c = 0; c < config->num_outputs; c++)
641 ystr(config->outputs[c]);
645 #define YSTR_IF_SET(name) \
647 if (config->name) { \
649 ystr(config->name); \
653 YSTR_IF_SET(tray_output);
654 YSTR_IF_SET(socket_path);
657 if (config->mode == M_HIDE)
662 switch (config->modifier) {
692 if (config->position == P_BOTTOM)
696 YSTR_IF_SET(status_command);
699 ystr("workspace_buttons");
700 y(bool, !config->hide_workspace_buttons);
703 y(bool, config->verbose);
706 #define YSTR_IF_SET(name) \
708 if (config->colors.name) { \
710 ystr(config->colors.name); \
716 YSTR_IF_SET(background);
717 YSTR_IF_SET(statusline);
718 YSTR_IF_SET(focused_workspace_border);
719 YSTR_IF_SET(focused_workspace_bg);
720 YSTR_IF_SET(focused_workspace_text);
721 YSTR_IF_SET(active_workspace_border);
722 YSTR_IF_SET(active_workspace_bg);
723 YSTR_IF_SET(active_workspace_text);
724 YSTR_IF_SET(inactive_workspace_border);
725 YSTR_IF_SET(inactive_workspace_bg);
726 YSTR_IF_SET(inactive_workspace_text);
727 YSTR_IF_SET(urgent_workspace_border);
728 YSTR_IF_SET(urgent_workspace_bg);
729 YSTR_IF_SET(urgent_workspace_text);
737 const unsigned char *payload;
743 y(get_buf, &payload, &length);
745 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
750 * Callback for the YAJL parser (will be called when a string is parsed).
754 static int add_subscription(void *extra, const unsigned char *s,
757 static int add_subscription(void *extra, const unsigned char *s,
760 ipc_client *client = extra;
762 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
763 int event = client->num_events;
765 client->num_events++;
766 client->events = realloc(client->events, client->num_events * sizeof(char*));
767 /* We copy the string because it is not null-terminated and strndup()
768 * is missing on some BSD systems */
769 client->events[event] = scalloc(len+1);
770 memcpy(client->events[event], s, len);
772 DLOG("client is now subscribed to:\n");
773 for (int i = 0; i < client->num_events; i++)
774 DLOG("event %s\n", client->events[i]);
781 * Subscribes this connection to the event types which were given as a JSON
782 * serialized array in the payload field of the message.
785 IPC_HANDLER(subscribe) {
787 yajl_callbacks callbacks;
789 ipc_client *current, *client = NULL;
791 /* Search the ipc_client structure for this connection */
792 TAILQ_FOREACH(current, &all_clients, clients) {
793 if (current->fd != fd)
800 if (client == NULL) {
801 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
805 /* Setup the JSON parser */
806 memset(&callbacks, 0, sizeof(yajl_callbacks));
807 callbacks.yajl_string = add_subscription;
810 p = yajl_alloc(&callbacks, NULL, (void*)client);
812 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
814 stat = yajl_parse(p, (const unsigned char*)message, message_size);
815 if (stat != yajl_status_ok) {
817 err = yajl_get_error(p, true, (const unsigned char*)message,
819 ELOG("YAJL parse error: %s\n", err);
820 yajl_free_error(p, err);
822 const char *reply = "{\"success\":false}";
823 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
828 const char *reply = "{\"success\":true}";
829 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
832 /* The index of each callback function corresponds to the numeric
833 * value of the message type (see include/i3/ipc.h) */
834 handler_t handlers[8] = {
836 handle_get_workspaces,
841 handle_get_bar_config,
846 * Handler for activity on a client connection, receives a message from a
849 * For now, the maximum message size is 2048. I’m not sure for what the
850 * IPC interface will be used in the future, thus I’m not implementing a
851 * mechanism for arbitrarily long messages, as it seems like overkill
855 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
857 int n = read(w->fd, buf, sizeof(buf));
859 /* On error or an empty message, we close the connection */
862 /* FIXME: I get these when closing a client socket,
863 * therefore we just treat them as an error. Is this
865 if (errno == EAGAIN || errno == EWOULDBLOCK)
869 /* If not, there was some kind of error. We don’t bother
870 * and close the connection */
873 /* Delete the client from the list of clients */
875 TAILQ_FOREACH(current, &all_clients, clients) {
876 if (current->fd != w->fd)
879 for (int i = 0; i < current->num_events; i++)
880 free(current->events[i]);
881 /* We can call TAILQ_REMOVE because we break out of the
882 * TAILQ_FOREACH afterwards */
883 TAILQ_REMOVE(&all_clients, current, clients);
891 DLOG("IPC: client disconnected\n");
895 /* Terminate the message correctly */
898 /* Check if the message starts with the i3 IPC magic code */
899 if (n < strlen(I3_IPC_MAGIC)) {
900 DLOG("IPC: message too short, ignoring\n");
904 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
905 DLOG("IPC: message does not start with the IPC magic\n");
909 uint8_t *message = (uint8_t*)buf;
911 DLOG("IPC: n = %d\n", n);
912 message += strlen(I3_IPC_MAGIC);
913 n -= strlen(I3_IPC_MAGIC);
915 /* The next 32 bit after the magic are the message size */
916 uint32_t message_size;
917 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
918 message += sizeof(uint32_t);
919 n -= sizeof(uint32_t);
921 if (message_size > n) {
922 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
926 /* The last 32 bits of the header are the message type */
927 uint32_t message_type;
928 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
929 message += sizeof(uint32_t);
930 n -= sizeof(uint32_t);
932 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
933 DLOG("Unhandled message type: %d\n", message_type);
935 handler_t h = handlers[message_type];
936 h(w->fd, message, n, message_size, message_type);
939 message += message_size;
944 * Handler for activity on the listening socket, meaning that a new client
945 * has just connected and we should accept() him. Sets up the event handler
946 * for activity on the new connection and inserts the file descriptor into
947 * the list of clients.
950 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
951 struct sockaddr_un peer;
952 socklen_t len = sizeof(struct sockaddr_un);
954 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
957 else perror("accept()");
961 /* Close this file descriptor on exec() */
962 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
964 set_nonblock(client);
966 struct ev_io *package = scalloc(sizeof(struct ev_io));
967 ev_io_init(package, ipc_receive_message, client, EV_READ);
968 ev_io_start(EV_A_ package);
970 DLOG("IPC: new client connected on fd %d\n", w->fd);
972 ipc_client *new = scalloc(sizeof(ipc_client));
975 TAILQ_INSERT_TAIL(&all_clients, new, clients);
979 * Creates the UNIX domain socket at the given path, sets it to non-blocking
980 * mode, bind()s and listen()s on it.
983 int ipc_create_socket(const char *filename) {
986 FREE(current_socketpath);
988 char *resolved = resolve_tilde(filename);
989 DLOG("Creating IPC-socket at %s\n", resolved);
990 char *copy = sstrdup(resolved);
991 const char *dir = dirname(copy);
992 if (!path_exists(dir))
996 /* Unlink the unix domain socket before */
999 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1005 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1007 struct sockaddr_un addr;
1008 memset(&addr, 0, sizeof(struct sockaddr_un));
1009 addr.sun_family = AF_LOCAL;
1010 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1011 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1017 set_nonblock(sockfd);
1019 if (listen(sockfd, 5) < 0) {
1025 current_socketpath = resolved;