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 CommandResult *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);
156 y(integer, con->type);
158 /* provided for backwards compatibility only. */
160 if (!con_is_split(con))
163 if (con_orientation(con) == HORIZ)
165 else ystr("vertical");
168 ystr("scratchpad_state");
169 switch (con->scratchpad_state) {
170 case SCRATCHPAD_NONE:
173 case SCRATCHPAD_FRESH:
176 case SCRATCHPAD_CHANGED:
182 if (con->percent == 0.0)
184 else y(double, con->percent);
187 y(bool, con->urgent);
189 if (con->mark != NULL) {
195 y(bool, (con == focused));
198 switch (con->layout) {
200 DLOG("About to dump layout=default, this is a bug in the code.\n");
223 ystr("workspace_layout");
224 switch (con->workspace_layout) {
235 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
240 ystr("last_split_layout");
241 switch (con->layout) {
251 switch (con->border_style) {
263 ystr("current_border_width");
264 y(integer, con->current_border_width);
266 dump_rect(gen, "rect", con->rect);
267 dump_rect(gen, "window_rect", con->window_rect);
268 dump_rect(gen, "geometry", con->geometry);
271 if (con->window && con->window->name)
272 ystr(i3string_as_utf8(con->window->name));
276 if (con->type == CT_WORKSPACE) {
278 y(integer, con->num);
283 y(integer, con->window->id);
289 if (con->type != CT_DOCKAREA || !inplace_restart) {
290 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
291 dump_node(gen, node, inplace_restart);
296 ystr("floating_nodes");
298 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
299 dump_node(gen, node, inplace_restart);
305 TAILQ_FOREACH(node, &(con->focus_head), focused) {
306 y(integer, (long int)node);
310 ystr("fullscreen_mode");
311 y(integer, con->fullscreen_mode);
314 switch (con->floating) {
315 case FLOATING_AUTO_OFF:
318 case FLOATING_AUTO_ON:
321 case FLOATING_USER_OFF:
324 case FLOATING_USER_ON:
332 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
333 if (match->dock != -1) {
336 y(integer, match->dock);
337 ystr("insert_where");
338 y(integer, match->insert_where);
342 /* TODO: the other swallow keys */
345 if (inplace_restart) {
346 if (con->window != NULL) {
349 y(integer, con->window->id);
350 ystr("restart_mode");
357 if (inplace_restart && con->window != NULL) {
359 y(integer, con->depth);
366 setlocale(LC_NUMERIC, "C");
367 yajl_gen gen = ygenalloc();
368 dump_node(gen, croot, false);
369 setlocale(LC_NUMERIC, "");
371 const unsigned char *payload;
373 y(get_buf, &payload, &length);
375 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
381 * Formats the reply message for a GET_WORKSPACES request and sends it to the
385 IPC_HANDLER(get_workspaces) {
386 yajl_gen gen = ygenalloc();
389 Con *focused_ws = con_get_workspace(focused);
392 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
393 if (con_is_internal(output))
396 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
397 assert(ws->type == CT_WORKSPACE);
403 else y(integer, ws->num);
409 y(bool, workspace_is_visible(ws));
412 y(bool, ws == focused_ws);
417 y(integer, ws->rect.x);
419 y(integer, ws->rect.y);
421 y(integer, ws->rect.width);
423 y(integer, ws->rect.height);
438 const unsigned char *payload;
440 y(get_buf, &payload, &length);
442 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
447 * Formats the reply message for a GET_OUTPUTS request and sends it to the
451 IPC_HANDLER(get_outputs) {
452 yajl_gen gen = ygenalloc();
456 TAILQ_FOREACH(output, &outputs, outputs) {
463 y(bool, output->active);
466 y(bool, output->primary);
471 y(integer, output->rect.x);
473 y(integer, output->rect.y);
475 y(integer, output->rect.width);
477 y(integer, output->rect.height);
480 ystr("current_workspace");
482 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
491 const unsigned char *payload;
493 y(get_buf, &payload, &length);
495 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
500 * Formats the reply message for a GET_MARKS request and sends it to the
504 IPC_HANDLER(get_marks) {
505 yajl_gen gen = ygenalloc();
509 TAILQ_FOREACH(con, &all_cons, all_cons)
510 if (con->mark != NULL)
515 const unsigned char *payload;
517 y(get_buf, &payload, &length);
519 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
524 * Returns the version of i3
527 IPC_HANDLER(get_version) {
528 yajl_gen gen = ygenalloc();
532 y(integer, MAJOR_VERSION);
535 y(integer, MINOR_VERSION);
538 y(integer, PATCH_VERSION);
540 ystr("human_readable");
545 const unsigned char *payload;
547 y(get_buf, &payload, &length);
549 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
554 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
558 IPC_HANDLER(get_bar_config) {
559 yajl_gen gen = ygenalloc();
561 /* If no ID was passed, we return a JSON array with all IDs */
562 if (message_size == 0) {
565 TAILQ_FOREACH(current, &barconfigs, configs) {
570 const unsigned char *payload;
572 y(get_buf, &payload, &length);
574 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
579 /* To get a properly terminated buffer, we copy
580 * message_size bytes out of the buffer */
581 char *bar_id = scalloc(message_size + 1);
582 strncpy(bar_id, (const char*)message, message_size);
583 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
584 Barconfig *current, *config = NULL;
585 TAILQ_FOREACH(current, &barconfigs, configs) {
586 if (strcmp(current->id, bar_id) != 0)
596 /* If we did not find a config for the given ID, the reply will contain
597 * a null 'id' field. */
604 if (config->num_outputs > 0) {
607 for (int c = 0; c < config->num_outputs; c++)
608 ystr(config->outputs[c]);
612 #define YSTR_IF_SET(name) \
614 if (config->name) { \
616 ystr(config->name); \
620 YSTR_IF_SET(tray_output);
621 YSTR_IF_SET(socket_path);
624 if (config->mode == M_HIDE)
629 switch (config->modifier) {
659 if (config->position == P_BOTTOM)
663 YSTR_IF_SET(status_command);
666 ystr("workspace_buttons");
667 y(bool, !config->hide_workspace_buttons);
670 y(bool, config->verbose);
673 #define YSTR_IF_SET(name) \
675 if (config->colors.name) { \
677 ystr(config->colors.name); \
683 YSTR_IF_SET(background);
684 YSTR_IF_SET(statusline);
685 YSTR_IF_SET(separator);
686 YSTR_IF_SET(focused_workspace_border);
687 YSTR_IF_SET(focused_workspace_bg);
688 YSTR_IF_SET(focused_workspace_text);
689 YSTR_IF_SET(active_workspace_border);
690 YSTR_IF_SET(active_workspace_bg);
691 YSTR_IF_SET(active_workspace_text);
692 YSTR_IF_SET(inactive_workspace_border);
693 YSTR_IF_SET(inactive_workspace_bg);
694 YSTR_IF_SET(inactive_workspace_text);
695 YSTR_IF_SET(urgent_workspace_border);
696 YSTR_IF_SET(urgent_workspace_bg);
697 YSTR_IF_SET(urgent_workspace_text);
705 const unsigned char *payload;
707 y(get_buf, &payload, &length);
709 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
714 * Callback for the YAJL parser (will be called when a string is parsed).
717 static int add_subscription(void *extra, const unsigned char *s,
719 ipc_client *client = extra;
721 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
722 int event = client->num_events;
724 client->num_events++;
725 client->events = realloc(client->events, client->num_events * sizeof(char*));
726 /* We copy the string because it is not null-terminated and strndup()
727 * is missing on some BSD systems */
728 client->events[event] = scalloc(len+1);
729 memcpy(client->events[event], s, len);
731 DLOG("client is now subscribed to:\n");
732 for (int i = 0; i < client->num_events; i++)
733 DLOG("event %s\n", client->events[i]);
740 * Subscribes this connection to the event types which were given as a JSON
741 * serialized array in the payload field of the message.
744 IPC_HANDLER(subscribe) {
746 yajl_callbacks callbacks;
748 ipc_client *current, *client = NULL;
750 /* Search the ipc_client structure for this connection */
751 TAILQ_FOREACH(current, &all_clients, clients) {
752 if (current->fd != fd)
759 if (client == NULL) {
760 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
764 /* Setup the JSON parser */
765 memset(&callbacks, 0, sizeof(yajl_callbacks));
766 callbacks.yajl_string = add_subscription;
768 p = yalloc(&callbacks, (void*)client);
769 stat = yajl_parse(p, (const unsigned char*)message, message_size);
770 if (stat != yajl_status_ok) {
772 err = yajl_get_error(p, true, (const unsigned char*)message,
774 ELOG("YAJL parse error: %s\n", err);
775 yajl_free_error(p, err);
777 const char *reply = "{\"success\":false}";
778 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
783 const char *reply = "{\"success\":true}";
784 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
787 /* The index of each callback function corresponds to the numeric
788 * value of the message type (see include/i3/ipc.h) */
789 handler_t handlers[8] = {
791 handle_get_workspaces,
796 handle_get_bar_config,
801 * Handler for activity on a client connection, receives a message from a
804 * For now, the maximum message size is 2048. I’m not sure for what the
805 * IPC interface will be used in the future, thus I’m not implementing a
806 * mechanism for arbitrarily long messages, as it seems like overkill
810 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
811 uint32_t message_type;
812 uint32_t message_length;
815 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
816 /* EOF or other error */
818 /* Was this a spurious read? See ev(3) */
819 if (ret == -1 && errno == EAGAIN)
822 /* If not, there was some kind of error. We don’t bother
823 * and close the connection */
826 /* Delete the client from the list of clients */
828 TAILQ_FOREACH(current, &all_clients, clients) {
829 if (current->fd != w->fd)
832 for (int i = 0; i < current->num_events; i++)
833 free(current->events[i]);
834 /* We can call TAILQ_REMOVE because we break out of the
835 * TAILQ_FOREACH afterwards */
836 TAILQ_REMOVE(&all_clients, current, clients);
844 DLOG("IPC: client disconnected\n");
848 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
849 DLOG("Unhandled message type: %d\n", message_type);
851 handler_t h = handlers[message_type];
852 h(w->fd, message, 0, message_length, message_type);
857 * Handler for activity on the listening socket, meaning that a new client
858 * has just connected and we should accept() him. Sets up the event handler
859 * for activity on the new connection and inserts the file descriptor into
860 * the list of clients.
863 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
864 struct sockaddr_un peer;
865 socklen_t len = sizeof(struct sockaddr_un);
867 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
870 else perror("accept()");
874 /* Close this file descriptor on exec() */
875 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
877 set_nonblock(client);
879 struct ev_io *package = scalloc(sizeof(struct ev_io));
880 ev_io_init(package, ipc_receive_message, client, EV_READ);
881 ev_io_start(EV_A_ package);
883 DLOG("IPC: new client connected on fd %d\n", w->fd);
885 ipc_client *new = scalloc(sizeof(ipc_client));
888 TAILQ_INSERT_TAIL(&all_clients, new, clients);
892 * Creates the UNIX domain socket at the given path, sets it to non-blocking
893 * mode, bind()s and listen()s on it.
896 int ipc_create_socket(const char *filename) {
899 FREE(current_socketpath);
901 char *resolved = resolve_tilde(filename);
902 DLOG("Creating IPC-socket at %s\n", resolved);
903 char *copy = sstrdup(resolved);
904 const char *dir = dirname(copy);
905 if (!path_exists(dir))
909 /* Unlink the unix domain socket before */
912 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
918 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
920 struct sockaddr_un addr;
921 memset(&addr, 0, sizeof(struct sockaddr_un));
922 addr.sun_family = AF_LOCAL;
923 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
924 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
930 set_nonblock(sockfd);
932 if (listen(sockfd, 5) < 0) {
938 current_socketpath = resolved;