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 const unsigned char *reply;
134 yajl_gen_get_buf(command_output->json_gen, &reply, &length);
136 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
137 (const uint8_t*)reply);
139 yajl_gen_free(command_output->json_gen);
142 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
152 y(integer, r.height);
156 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
159 y(integer, (long int)con);
162 y(integer, con->type);
165 switch (con->orientation) {
177 ystr("scratchpad_state");
178 switch (con->scratchpad_state) {
179 case SCRATCHPAD_NONE:
182 case SCRATCHPAD_FRESH:
185 case SCRATCHPAD_CHANGED:
191 if (con->percent == 0.0)
193 else y(double, con->percent);
196 y(bool, con->urgent);
198 if (con->mark != NULL) {
204 y(bool, (con == focused));
207 switch (con->layout) {
226 switch (con->border_style) {
238 dump_rect(gen, "rect", con->rect);
239 dump_rect(gen, "window_rect", con->window_rect);
240 dump_rect(gen, "geometry", con->geometry);
243 if (con->window && con->window->name_json)
244 ystr(con->window->name_json);
248 if (con->type == CT_WORKSPACE) {
250 y(integer, con->num);
255 y(integer, con->window->id);
261 if (con->type != CT_DOCKAREA || !inplace_restart) {
262 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
263 dump_node(gen, node, inplace_restart);
268 ystr("floating_nodes");
270 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
271 dump_node(gen, node, inplace_restart);
277 TAILQ_FOREACH(node, &(con->focus_head), focused) {
278 y(integer, (long int)node);
282 ystr("fullscreen_mode");
283 y(integer, con->fullscreen_mode);
286 switch (con->floating) {
287 case FLOATING_AUTO_OFF:
290 case FLOATING_AUTO_ON:
293 case FLOATING_USER_OFF:
296 case FLOATING_USER_ON:
304 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
305 if (match->dock != -1) {
308 y(integer, match->dock);
309 ystr("insert_where");
310 y(integer, match->insert_where);
314 /* TODO: the other swallow keys */
317 if (inplace_restart) {
318 if (con->window != NULL) {
321 y(integer, con->window->id);
322 ystr("restart_mode");
333 setlocale(LC_NUMERIC, "C");
335 yajl_gen gen = yajl_gen_alloc(NULL);
337 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
339 dump_node(gen, croot, false);
340 setlocale(LC_NUMERIC, "");
342 const unsigned char *payload;
348 y(get_buf, &payload, &length);
350 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
356 * Formats the reply message for a GET_WORKSPACES request and sends it to the
360 IPC_HANDLER(get_workspaces) {
362 yajl_gen gen = yajl_gen_alloc(NULL);
364 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
368 Con *focused_ws = con_get_workspace(focused);
371 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
372 if (output->name[0] == '_' && output->name[1] == '_')
375 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
376 assert(ws->type == CT_WORKSPACE);
382 else y(integer, ws->num);
388 y(bool, workspace_is_visible(ws));
391 y(bool, ws == focused_ws);
396 y(integer, ws->rect.x);
398 y(integer, ws->rect.y);
400 y(integer, ws->rect.width);
402 y(integer, ws->rect.height);
417 const unsigned char *payload;
423 y(get_buf, &payload, &length);
425 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
430 * Formats the reply message for a GET_OUTPUTS request and sends it to the
434 IPC_HANDLER(get_outputs) {
436 yajl_gen gen = yajl_gen_alloc(NULL);
438 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
443 TAILQ_FOREACH(output, &outputs, outputs) {
450 y(bool, output->active);
453 y(bool, output->primary);
458 y(integer, output->rect.x);
460 y(integer, output->rect.y);
462 y(integer, output->rect.width);
464 y(integer, output->rect.height);
467 ystr("current_workspace");
469 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
478 const unsigned char *payload;
484 y(get_buf, &payload, &length);
486 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
491 * Formats the reply message for a GET_MARKS request and sends it to the
495 IPC_HANDLER(get_marks) {
497 yajl_gen gen = yajl_gen_alloc(NULL);
499 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
504 TAILQ_FOREACH(con, &all_cons, all_cons)
505 if (con->mark != NULL)
510 const unsigned char *payload;
516 y(get_buf, &payload, &length);
518 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
523 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
527 IPC_HANDLER(get_bar_config) {
529 yajl_gen gen = yajl_gen_alloc(NULL);
531 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
534 /* If no ID was passed, we return a JSON array with all IDs */
535 if (message_size == 0) {
538 TAILQ_FOREACH(current, &barconfigs, configs) {
543 const unsigned char *payload;
549 y(get_buf, &payload, &length);
551 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
556 /* To get a properly terminated buffer, we copy
557 * message_size bytes out of the buffer */
558 char *bar_id = scalloc(message_size + 1);
559 strncpy(bar_id, (const char*)message, message_size);
560 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
561 Barconfig *current, *config = NULL;
562 TAILQ_FOREACH(current, &barconfigs, configs) {
563 if (strcmp(current->id, bar_id) != 0)
573 /* If we did not find a config for the given ID, the reply will contain
574 * a null 'id' field. */
581 if (config->num_outputs > 0) {
584 for (int c = 0; c < config->num_outputs; c++)
585 ystr(config->outputs[c]);
589 #define YSTR_IF_SET(name) \
591 if (config->name) { \
593 ystr(config->name); \
597 YSTR_IF_SET(tray_output);
598 YSTR_IF_SET(socket_path);
601 if (config->mode == M_HIDE)
606 switch (config->modifier) {
636 if (config->position == P_BOTTOM)
640 YSTR_IF_SET(status_command);
643 ystr("workspace_buttons");
644 y(bool, !config->hide_workspace_buttons);
647 y(bool, config->verbose);
650 #define YSTR_IF_SET(name) \
652 if (config->colors.name) { \
654 ystr(config->colors.name); \
660 YSTR_IF_SET(background);
661 YSTR_IF_SET(statusline);
662 YSTR_IF_SET(focused_workspace_border);
663 YSTR_IF_SET(focused_workspace_bg);
664 YSTR_IF_SET(focused_workspace_text);
665 YSTR_IF_SET(active_workspace_border);
666 YSTR_IF_SET(active_workspace_bg);
667 YSTR_IF_SET(active_workspace_text);
668 YSTR_IF_SET(inactive_workspace_border);
669 YSTR_IF_SET(inactive_workspace_bg);
670 YSTR_IF_SET(inactive_workspace_text);
671 YSTR_IF_SET(urgent_workspace_border);
672 YSTR_IF_SET(urgent_workspace_bg);
673 YSTR_IF_SET(urgent_workspace_text);
681 const unsigned char *payload;
687 y(get_buf, &payload, &length);
689 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
694 * Callback for the YAJL parser (will be called when a string is parsed).
698 static int add_subscription(void *extra, const unsigned char *s,
701 static int add_subscription(void *extra, const unsigned char *s,
704 ipc_client *client = extra;
706 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
707 int event = client->num_events;
709 client->num_events++;
710 client->events = realloc(client->events, client->num_events * sizeof(char*));
711 /* We copy the string because it is not null-terminated and strndup()
712 * is missing on some BSD systems */
713 client->events[event] = scalloc(len+1);
714 memcpy(client->events[event], s, len);
716 DLOG("client is now subscribed to:\n");
717 for (int i = 0; i < client->num_events; i++)
718 DLOG("event %s\n", client->events[i]);
725 * Subscribes this connection to the event types which were given as a JSON
726 * serialized array in the payload field of the message.
729 IPC_HANDLER(subscribe) {
731 yajl_callbacks callbacks;
733 ipc_client *current, *client = NULL;
735 /* Search the ipc_client structure for this connection */
736 TAILQ_FOREACH(current, &all_clients, clients) {
737 if (current->fd != fd)
744 if (client == NULL) {
745 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
749 /* Setup the JSON parser */
750 memset(&callbacks, 0, sizeof(yajl_callbacks));
751 callbacks.yajl_string = add_subscription;
754 p = yajl_alloc(&callbacks, NULL, (void*)client);
756 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
758 stat = yajl_parse(p, (const unsigned char*)message, message_size);
759 if (stat != yajl_status_ok) {
761 err = yajl_get_error(p, true, (const unsigned char*)message,
763 ELOG("YAJL parse error: %s\n", err);
764 yajl_free_error(p, err);
766 const char *reply = "{\"success\":false}";
767 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
772 const char *reply = "{\"success\":true}";
773 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
776 /* The index of each callback function corresponds to the numeric
777 * value of the message type (see include/i3/ipc.h) */
778 handler_t handlers[7] = {
780 handle_get_workspaces,
785 handle_get_bar_config,
789 * Handler for activity on a client connection, receives a message from a
792 * For now, the maximum message size is 2048. I’m not sure for what the
793 * IPC interface will be used in the future, thus I’m not implementing a
794 * mechanism for arbitrarily long messages, as it seems like overkill
798 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
800 int n = read(w->fd, buf, sizeof(buf));
802 /* On error or an empty message, we close the connection */
805 /* FIXME: I get these when closing a client socket,
806 * therefore we just treat them as an error. Is this
808 if (errno == EAGAIN || errno == EWOULDBLOCK)
812 /* If not, there was some kind of error. We don’t bother
813 * and close the connection */
816 /* Delete the client from the list of clients */
818 TAILQ_FOREACH(current, &all_clients, clients) {
819 if (current->fd != w->fd)
822 for (int i = 0; i < current->num_events; i++)
823 free(current->events[i]);
824 /* We can call TAILQ_REMOVE because we break out of the
825 * TAILQ_FOREACH afterwards */
826 TAILQ_REMOVE(&all_clients, current, clients);
834 DLOG("IPC: client disconnected\n");
838 /* Terminate the message correctly */
841 /* Check if the message starts with the i3 IPC magic code */
842 if (n < strlen(I3_IPC_MAGIC)) {
843 DLOG("IPC: message too short, ignoring\n");
847 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
848 DLOG("IPC: message does not start with the IPC magic\n");
852 uint8_t *message = (uint8_t*)buf;
854 DLOG("IPC: n = %d\n", n);
855 message += strlen(I3_IPC_MAGIC);
856 n -= strlen(I3_IPC_MAGIC);
858 /* The next 32 bit after the magic are the message size */
859 uint32_t message_size;
860 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
861 message += sizeof(uint32_t);
862 n -= sizeof(uint32_t);
864 if (message_size > n) {
865 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
869 /* The last 32 bits of the header are the message type */
870 uint32_t message_type;
871 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
872 message += sizeof(uint32_t);
873 n -= sizeof(uint32_t);
875 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
876 DLOG("Unhandled message type: %d\n", message_type);
878 handler_t h = handlers[message_type];
879 h(w->fd, message, n, message_size, message_type);
882 message += message_size;
887 * Handler for activity on the listening socket, meaning that a new client
888 * has just connected and we should accept() him. Sets up the event handler
889 * for activity on the new connection and inserts the file descriptor into
890 * the list of clients.
893 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
894 struct sockaddr_un peer;
895 socklen_t len = sizeof(struct sockaddr_un);
897 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
900 else perror("accept()");
904 /* Close this file descriptor on exec() */
905 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
907 set_nonblock(client);
909 struct ev_io *package = scalloc(sizeof(struct ev_io));
910 ev_io_init(package, ipc_receive_message, client, EV_READ);
911 ev_io_start(EV_A_ package);
913 DLOG("IPC: new client connected on fd %d\n", w->fd);
915 ipc_client *new = scalloc(sizeof(ipc_client));
918 TAILQ_INSERT_TAIL(&all_clients, new, clients);
922 * Creates the UNIX domain socket at the given path, sets it to non-blocking
923 * mode, bind()s and listen()s on it.
926 int ipc_create_socket(const char *filename) {
929 FREE(current_socketpath);
931 char *resolved = resolve_tilde(filename);
932 DLOG("Creating IPC-socket at %s\n", resolved);
933 char *copy = sstrdup(resolved);
934 const char *dir = dirname(copy);
935 if (!path_exists(dir))
939 /* Unlink the unix domain socket before */
942 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
948 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
950 struct sockaddr_un addr;
951 memset(&addr, 0, sizeof(struct sockaddr_un));
952 addr.sun_family = AF_LOCAL;
953 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
954 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
960 set_nonblock(sockfd);
962 if (listen(sockfd, 5) < 0) {
968 current_socketpath = resolved;