2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
7 * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
12 #include <sys/socket.h>
17 #include <yajl/yajl_gen.h>
18 #include <yajl/yajl_parse.h>
19 #include <yajl/yajl_version.h>
21 char *current_socketpath = NULL;
23 /* Shorter names for all those yajl_gen_* functions */
24 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
25 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
27 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
30 * Puts the given socket file descriptor into non-blocking mode or dies if
31 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
32 * IPC model because we should by no means block the window manager.
35 static void set_nonblock(int sockfd) {
36 int flags = fcntl(sockfd, F_GETFL, 0);
38 if (fcntl(sockfd, F_SETFL, flags) < 0)
39 err(-1, "Could not set O_NONBLOCK");
43 * Emulates mkdir -p (creates any missing folders)
46 static bool mkdirp(const char *path) {
47 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
49 if (errno != ENOENT) {
50 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
53 char *copy = strdup(path);
54 /* strip trailing slashes, if any */
55 while (copy[strlen(copy)-1] == '/')
56 copy[strlen(copy)-1] = '\0';
58 char *sep = strrchr(copy, '/');
66 result = mkdirp(path);
73 * Sends the specified event to all IPC clients which are currently connected
74 * and subscribed to this kind of event.
77 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
79 TAILQ_FOREACH(current, &all_clients, clients) {
80 /* see if this client is interested in this event */
81 bool interested = false;
82 for (int i = 0; i < current->num_events; i++) {
83 if (strcasecmp(current->events[i], event) != 0)
91 ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t*)payload);
96 * Calls shutdown() on each socket and closes it. This function to be called
97 * when exiting or restarting only!
100 void ipc_shutdown(void) {
102 while (!TAILQ_EMPTY(&all_clients)) {
103 current = TAILQ_FIRST(&all_clients);
104 shutdown(current->fd, SHUT_RDWR);
106 TAILQ_REMOVE(&all_clients, current, clients);
112 * Executes the command and returns whether it could be successfully parsed
113 * or not (at the moment, always returns true).
116 IPC_HANDLER(command) {
117 /* To get a properly terminated buffer, we copy
118 * message_size bytes out of the buffer */
119 char *command = scalloc(message_size + 1);
120 strncpy(command, (const char*)message, message_size);
121 LOG("IPC: received: *%s*\n", command);
122 struct CommandResult *command_output = parse_command((const char*)command);
125 if (command_output->needs_tree_render)
128 /* If no reply was provided, we just use the default success message */
129 ipc_send_message(fd, strlen(command_output->json_output),
130 I3_IPC_REPLY_TYPE_COMMAND,
131 (const uint8_t*)command_output->json_output);
133 free(command_output->json_output);
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);
159 switch (con->orientation) {
171 ystr("scratchpad_state");
172 switch (con->scratchpad_state) {
173 case SCRATCHPAD_NONE:
176 case SCRATCHPAD_FRESH:
179 case SCRATCHPAD_CHANGED:
185 if (con->percent == 0.0)
187 else y(double, con->percent);
190 y(bool, con->urgent);
192 if (con->mark != NULL) {
198 y(bool, (con == focused));
201 switch (con->layout) {
220 switch (con->border_style) {
232 dump_rect(gen, "rect", con->rect);
233 dump_rect(gen, "window_rect", con->window_rect);
234 dump_rect(gen, "geometry", con->geometry);
237 if (con->window && con->window->name_json)
238 ystr(con->window->name_json);
242 if (con->type == CT_WORKSPACE) {
244 y(integer, con->num);
249 y(integer, con->window->id);
255 if (con->type != CT_DOCKAREA || !inplace_restart) {
256 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
257 dump_node(gen, node, inplace_restart);
262 ystr("floating_nodes");
264 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
265 dump_node(gen, node, inplace_restart);
271 TAILQ_FOREACH(node, &(con->focus_head), focused) {
272 y(integer, (long int)node);
276 ystr("fullscreen_mode");
277 y(integer, con->fullscreen_mode);
280 switch (con->floating) {
281 case FLOATING_AUTO_OFF:
284 case FLOATING_AUTO_ON:
287 case FLOATING_USER_OFF:
290 case FLOATING_USER_ON:
298 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
299 if (match->dock != -1) {
302 y(integer, match->dock);
303 ystr("insert_where");
304 y(integer, match->insert_where);
308 /* TODO: the other swallow keys */
311 if (inplace_restart) {
312 if (con->window != NULL) {
315 y(integer, con->window->id);
316 ystr("restart_mode");
327 setlocale(LC_NUMERIC, "C");
329 yajl_gen gen = yajl_gen_alloc(NULL);
331 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
333 dump_node(gen, croot, false);
334 setlocale(LC_NUMERIC, "");
336 const unsigned char *payload;
342 y(get_buf, &payload, &length);
344 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
350 * Formats the reply message for a GET_WORKSPACES request and sends it to the
354 IPC_HANDLER(get_workspaces) {
356 yajl_gen gen = yajl_gen_alloc(NULL);
358 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
362 Con *focused_ws = con_get_workspace(focused);
365 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
366 if (output->name[0] == '_' && output->name[1] == '_')
369 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
370 assert(ws->type == CT_WORKSPACE);
376 else y(integer, ws->num);
382 y(bool, workspace_is_visible(ws));
385 y(bool, ws == focused_ws);
390 y(integer, ws->rect.x);
392 y(integer, ws->rect.y);
394 y(integer, ws->rect.width);
396 y(integer, ws->rect.height);
411 const unsigned char *payload;
417 y(get_buf, &payload, &length);
419 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
424 * Formats the reply message for a GET_OUTPUTS request and sends it to the
428 IPC_HANDLER(get_outputs) {
430 yajl_gen gen = yajl_gen_alloc(NULL);
432 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
437 TAILQ_FOREACH(output, &outputs, outputs) {
444 y(bool, output->active);
447 y(bool, output->primary);
452 y(integer, output->rect.x);
454 y(integer, output->rect.y);
456 y(integer, output->rect.width);
458 y(integer, output->rect.height);
461 ystr("current_workspace");
463 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
472 const unsigned char *payload;
478 y(get_buf, &payload, &length);
480 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
485 * Formats the reply message for a GET_MARKS request and sends it to the
489 IPC_HANDLER(get_marks) {
491 yajl_gen gen = yajl_gen_alloc(NULL);
493 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
498 TAILQ_FOREACH(con, &all_cons, all_cons)
499 if (con->mark != NULL)
504 const unsigned char *payload;
510 y(get_buf, &payload, &length);
512 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
517 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
521 IPC_HANDLER(get_bar_config) {
523 yajl_gen gen = yajl_gen_alloc(NULL);
525 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
528 /* If no ID was passed, we return a JSON array with all IDs */
529 if (message_size == 0) {
532 TAILQ_FOREACH(current, &barconfigs, configs) {
537 const unsigned char *payload;
543 y(get_buf, &payload, &length);
545 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
550 /* To get a properly terminated buffer, we copy
551 * message_size bytes out of the buffer */
552 char *bar_id = scalloc(message_size + 1);
553 strncpy(bar_id, (const char*)message, message_size);
554 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
555 Barconfig *current, *config = NULL;
556 TAILQ_FOREACH(current, &barconfigs, configs) {
557 if (strcmp(current->id, bar_id) != 0)
567 /* If we did not find a config for the given ID, the reply will contain
568 * a null 'id' field. */
575 if (config->num_outputs > 0) {
578 for (int c = 0; c < config->num_outputs; c++)
579 ystr(config->outputs[c]);
583 #define YSTR_IF_SET(name) \
585 if (config->name) { \
587 ystr(config->name); \
591 YSTR_IF_SET(tray_output);
592 YSTR_IF_SET(socket_path);
595 if (config->mode == M_HIDE)
600 switch (config->modifier) {
630 if (config->position == P_BOTTOM)
634 YSTR_IF_SET(status_command);
637 ystr("workspace_buttons");
638 y(bool, !config->hide_workspace_buttons);
641 y(bool, config->verbose);
644 #define YSTR_IF_SET(name) \
646 if (config->colors.name) { \
648 ystr(config->colors.name); \
654 YSTR_IF_SET(background);
655 YSTR_IF_SET(statusline);
656 YSTR_IF_SET(focused_workspace_border);
657 YSTR_IF_SET(focused_workspace_bg);
658 YSTR_IF_SET(focused_workspace_text);
659 YSTR_IF_SET(active_workspace_border);
660 YSTR_IF_SET(active_workspace_bg);
661 YSTR_IF_SET(active_workspace_text);
662 YSTR_IF_SET(inactive_workspace_border);
663 YSTR_IF_SET(inactive_workspace_bg);
664 YSTR_IF_SET(inactive_workspace_text);
665 YSTR_IF_SET(urgent_workspace_border);
666 YSTR_IF_SET(urgent_workspace_bg);
667 YSTR_IF_SET(urgent_workspace_text);
675 const unsigned char *payload;
681 y(get_buf, &payload, &length);
683 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
688 * Callback for the YAJL parser (will be called when a string is parsed).
692 static int add_subscription(void *extra, const unsigned char *s,
695 static int add_subscription(void *extra, const unsigned char *s,
698 ipc_client *client = extra;
700 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
701 int event = client->num_events;
703 client->num_events++;
704 client->events = realloc(client->events, client->num_events * sizeof(char*));
705 /* We copy the string because it is not null-terminated and strndup()
706 * is missing on some BSD systems */
707 client->events[event] = scalloc(len+1);
708 memcpy(client->events[event], s, len);
710 DLOG("client is now subscribed to:\n");
711 for (int i = 0; i < client->num_events; i++)
712 DLOG("event %s\n", client->events[i]);
719 * Subscribes this connection to the event types which were given as a JSON
720 * serialized array in the payload field of the message.
723 IPC_HANDLER(subscribe) {
725 yajl_callbacks callbacks;
727 ipc_client *current, *client = NULL;
729 /* Search the ipc_client structure for this connection */
730 TAILQ_FOREACH(current, &all_clients, clients) {
731 if (current->fd != fd)
738 if (client == NULL) {
739 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
743 /* Setup the JSON parser */
744 memset(&callbacks, 0, sizeof(yajl_callbacks));
745 callbacks.yajl_string = add_subscription;
748 p = yajl_alloc(&callbacks, NULL, (void*)client);
750 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
752 stat = yajl_parse(p, (const unsigned char*)message, message_size);
753 if (stat != yajl_status_ok) {
755 err = yajl_get_error(p, true, (const unsigned char*)message,
757 ELOG("YAJL parse error: %s\n", err);
758 yajl_free_error(p, err);
760 const char *reply = "{\"success\":false}";
761 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
766 const char *reply = "{\"success\":true}";
767 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
770 /* The index of each callback function corresponds to the numeric
771 * value of the message type (see include/i3/ipc.h) */
772 handler_t handlers[7] = {
774 handle_get_workspaces,
779 handle_get_bar_config,
783 * Handler for activity on a client connection, receives a message from a
786 * For now, the maximum message size is 2048. I’m not sure for what the
787 * IPC interface will be used in the future, thus I’m not implementing a
788 * mechanism for arbitrarily long messages, as it seems like overkill
792 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
794 int n = read(w->fd, buf, sizeof(buf));
796 /* On error or an empty message, we close the connection */
799 /* FIXME: I get these when closing a client socket,
800 * therefore we just treat them as an error. Is this
802 if (errno == EAGAIN || errno == EWOULDBLOCK)
806 /* If not, there was some kind of error. We don’t bother
807 * and close the connection */
810 /* Delete the client from the list of clients */
812 TAILQ_FOREACH(current, &all_clients, clients) {
813 if (current->fd != w->fd)
816 for (int i = 0; i < current->num_events; i++)
817 free(current->events[i]);
818 /* We can call TAILQ_REMOVE because we break out of the
819 * TAILQ_FOREACH afterwards */
820 TAILQ_REMOVE(&all_clients, current, clients);
828 DLOG("IPC: client disconnected\n");
832 /* Terminate the message correctly */
835 /* Check if the message starts with the i3 IPC magic code */
836 if (n < strlen(I3_IPC_MAGIC)) {
837 DLOG("IPC: message too short, ignoring\n");
841 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
842 DLOG("IPC: message does not start with the IPC magic\n");
846 uint8_t *message = (uint8_t*)buf;
848 DLOG("IPC: n = %d\n", n);
849 message += strlen(I3_IPC_MAGIC);
850 n -= strlen(I3_IPC_MAGIC);
852 /* The next 32 bit after the magic are the message size */
853 uint32_t message_size;
854 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
855 message += sizeof(uint32_t);
856 n -= sizeof(uint32_t);
858 if (message_size > n) {
859 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
863 /* The last 32 bits of the header are the message type */
864 uint32_t message_type;
865 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
866 message += sizeof(uint32_t);
867 n -= sizeof(uint32_t);
869 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
870 DLOG("Unhandled message type: %d\n", message_type);
872 handler_t h = handlers[message_type];
873 h(w->fd, message, n, message_size, message_type);
876 message += message_size;
881 * Handler for activity on the listening socket, meaning that a new client
882 * has just connected and we should accept() him. Sets up the event handler
883 * for activity on the new connection and inserts the file descriptor into
884 * the list of clients.
887 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
888 struct sockaddr_un peer;
889 socklen_t len = sizeof(struct sockaddr_un);
891 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
894 else perror("accept()");
898 /* Close this file descriptor on exec() */
899 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
901 set_nonblock(client);
903 struct ev_io *package = scalloc(sizeof(struct ev_io));
904 ev_io_init(package, ipc_receive_message, client, EV_READ);
905 ev_io_start(EV_A_ package);
907 DLOG("IPC: new client connected on fd %d\n", w->fd);
909 ipc_client *new = scalloc(sizeof(ipc_client));
912 TAILQ_INSERT_TAIL(&all_clients, new, clients);
916 * Creates the UNIX domain socket at the given path, sets it to non-blocking
917 * mode, bind()s and listen()s on it.
920 int ipc_create_socket(const char *filename) {
923 FREE(current_socketpath);
925 char *resolved = resolve_tilde(filename);
926 DLOG("Creating IPC-socket at %s\n", resolved);
927 char *copy = sstrdup(resolved);
928 const char *dir = dirname(copy);
929 if (!path_exists(dir))
933 /* Unlink the unix domain socket before */
936 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
942 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
944 struct sockaddr_un addr;
945 memset(&addr, 0, sizeof(struct sockaddr_un));
946 addr.sun_family = AF_LOCAL;
947 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
948 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
954 set_nonblock(sockfd);
956 if (listen(sockfd, 5) < 0) {
962 current_socketpath = resolved;