2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2011 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() {
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 char *reply = parse_cmd((const char*)command);
123 char *save_reply = reply;
126 /* If no reply was provided, we just use the default success message */
128 reply = "{\"success\":true}";
129 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_COMMAND, (const uint8_t*)reply);
134 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
144 y(integer, r.height);
148 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
151 y(integer, (long int)con);
154 y(integer, con->type);
157 switch (con->orientation) {
169 ystr("scratchpad_state");
170 switch (con->scratchpad_state) {
171 case SCRATCHPAD_NONE:
174 case SCRATCHPAD_FRESH:
177 case SCRATCHPAD_CHANGED:
183 if (con->percent == 0.0)
185 else y(double, con->percent);
188 y(bool, con->urgent);
190 if (con->mark != NULL) {
196 y(bool, (con == focused));
199 switch (con->layout) {
218 switch (con->border_style) {
230 dump_rect(gen, "rect", con->rect);
231 dump_rect(gen, "window_rect", con->window_rect);
232 dump_rect(gen, "geometry", con->geometry);
235 if (con->window && con->window->name_json)
236 ystr(con->window->name_json);
240 if (con->type == CT_WORKSPACE) {
242 y(integer, con->num);
247 y(integer, con->window->id);
253 if (con->type != CT_DOCKAREA || !inplace_restart) {
254 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
255 dump_node(gen, node, inplace_restart);
260 ystr("floating_nodes");
262 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
263 dump_node(gen, node, inplace_restart);
269 TAILQ_FOREACH(node, &(con->focus_head), focused) {
270 y(integer, (long int)node);
274 ystr("fullscreen_mode");
275 y(integer, con->fullscreen_mode);
278 switch (con->floating) {
279 case FLOATING_AUTO_OFF:
282 case FLOATING_AUTO_ON:
285 case FLOATING_USER_OFF:
288 case FLOATING_USER_ON:
296 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
297 if (match->dock != -1) {
300 y(integer, match->dock);
301 ystr("insert_where");
302 y(integer, match->insert_where);
306 /* TODO: the other swallow keys */
309 if (inplace_restart) {
310 if (con->window != NULL) {
313 y(integer, con->window->id);
323 setlocale(LC_NUMERIC, "C");
325 yajl_gen gen = yajl_gen_alloc(NULL);
327 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
329 dump_node(gen, croot, false);
330 setlocale(LC_NUMERIC, "");
332 const unsigned char *payload;
338 y(get_buf, &payload, &length);
340 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
346 * Formats the reply message for a GET_WORKSPACES request and sends it to the
350 IPC_HANDLER(get_workspaces) {
352 yajl_gen gen = yajl_gen_alloc(NULL);
354 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
358 Con *focused_ws = con_get_workspace(focused);
361 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
362 if (output->name[0] == '_' && output->name[1] == '_')
365 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
366 assert(ws->type == CT_WORKSPACE);
372 else y(integer, ws->num);
378 y(bool, workspace_is_visible(ws));
381 y(bool, ws == focused_ws);
386 y(integer, ws->rect.x);
388 y(integer, ws->rect.y);
390 y(integer, ws->rect.width);
392 y(integer, ws->rect.height);
407 const unsigned char *payload;
413 y(get_buf, &payload, &length);
415 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
420 * Formats the reply message for a GET_OUTPUTS request and sends it to the
424 IPC_HANDLER(get_outputs) {
426 yajl_gen gen = yajl_gen_alloc(NULL);
428 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
433 TAILQ_FOREACH(output, &outputs, outputs) {
440 y(bool, output->active);
445 y(integer, output->rect.x);
447 y(integer, output->rect.y);
449 y(integer, output->rect.width);
451 y(integer, output->rect.height);
454 ystr("current_workspace");
456 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
465 const unsigned char *payload;
471 y(get_buf, &payload, &length);
473 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
478 * Formats the reply message for a GET_MARKS request and sends it to the
482 IPC_HANDLER(get_marks) {
484 yajl_gen gen = yajl_gen_alloc(NULL);
486 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
491 TAILQ_FOREACH(con, &all_cons, all_cons)
492 if (con->mark != NULL)
497 const unsigned char *payload;
503 y(get_buf, &payload, &length);
505 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
510 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
514 IPC_HANDLER(get_bar_config) {
516 yajl_gen gen = yajl_gen_alloc(NULL);
518 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
521 /* If no ID was passed, we return a JSON array with all IDs */
522 if (message_size == 0) {
525 TAILQ_FOREACH(current, &barconfigs, configs) {
530 const unsigned char *payload;
536 y(get_buf, &payload, &length);
538 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
543 /* To get a properly terminated buffer, we copy
544 * message_size bytes out of the buffer */
545 char *bar_id = scalloc(message_size + 1);
546 strncpy(bar_id, (const char*)message, message_size);
547 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
548 Barconfig *current, *config = NULL;
549 TAILQ_FOREACH(current, &barconfigs, configs) {
550 if (strcmp(current->id, bar_id) != 0)
560 /* If we did not find a config for the given ID, the reply will contain
561 * a null 'id' field. */
568 if (config->num_outputs > 0) {
571 for (int c = 0; c < config->num_outputs; c++)
572 ystr(config->outputs[c]);
576 #define YSTR_IF_SET(name) \
578 if (config->name) { \
580 ystr(config->name); \
584 YSTR_IF_SET(tray_output);
585 YSTR_IF_SET(socket_path);
588 if (config->mode == M_HIDE)
593 switch (config->modifier) {
623 if (config->position == P_BOTTOM)
627 YSTR_IF_SET(status_command);
630 ystr("workspace_buttons");
631 y(bool, !config->hide_workspace_buttons);
634 y(bool, config->verbose);
637 #define YSTR_IF_SET(name) \
639 if (config->colors.name) { \
641 ystr(config->colors.name); \
647 YSTR_IF_SET(background);
648 YSTR_IF_SET(statusline);
649 YSTR_IF_SET(focused_workspace_text);
650 YSTR_IF_SET(focused_workspace_bg);
651 YSTR_IF_SET(active_workspace_text);
652 YSTR_IF_SET(active_workspace_bg);
653 YSTR_IF_SET(inactive_workspace_text);
654 YSTR_IF_SET(inactive_workspace_bg);
655 YSTR_IF_SET(urgent_workspace_text);
656 YSTR_IF_SET(urgent_workspace_bg);
664 const unsigned char *payload;
670 y(get_buf, &payload, &length);
672 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
677 * Callback for the YAJL parser (will be called when a string is parsed).
681 static int add_subscription(void *extra, const unsigned char *s,
684 static int add_subscription(void *extra, const unsigned char *s,
687 ipc_client *client = extra;
689 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
690 int event = client->num_events;
692 client->num_events++;
693 client->events = realloc(client->events, client->num_events * sizeof(char*));
694 /* We copy the string because it is not null-terminated and strndup()
695 * is missing on some BSD systems */
696 client->events[event] = scalloc(len+1);
697 memcpy(client->events[event], s, len);
699 DLOG("client is now subscribed to:\n");
700 for (int i = 0; i < client->num_events; i++)
701 DLOG("event %s\n", client->events[i]);
708 * Subscribes this connection to the event types which were given as a JSON
709 * serialized array in the payload field of the message.
712 IPC_HANDLER(subscribe) {
714 yajl_callbacks callbacks;
716 ipc_client *current, *client = NULL;
718 /* Search the ipc_client structure for this connection */
719 TAILQ_FOREACH(current, &all_clients, clients) {
720 if (current->fd != fd)
727 if (client == NULL) {
728 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
732 /* Setup the JSON parser */
733 memset(&callbacks, 0, sizeof(yajl_callbacks));
734 callbacks.yajl_string = add_subscription;
737 p = yajl_alloc(&callbacks, NULL, (void*)client);
739 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
741 stat = yajl_parse(p, (const unsigned char*)message, message_size);
742 if (stat != yajl_status_ok) {
744 err = yajl_get_error(p, true, (const unsigned char*)message,
746 ELOG("YAJL parse error: %s\n", err);
747 yajl_free_error(p, err);
749 const char *reply = "{\"success\":false}";
750 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
755 const char *reply = "{\"success\":true}";
756 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
759 /* The index of each callback function corresponds to the numeric
760 * value of the message type (see include/i3/ipc.h) */
761 handler_t handlers[7] = {
763 handle_get_workspaces,
768 handle_get_bar_config,
772 * Handler for activity on a client connection, receives a message from a
775 * For now, the maximum message size is 2048. I’m not sure for what the
776 * IPC interface will be used in the future, thus I’m not implementing a
777 * mechanism for arbitrarily long messages, as it seems like overkill
781 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
783 int n = read(w->fd, buf, sizeof(buf));
785 /* On error or an empty message, we close the connection */
788 /* FIXME: I get these when closing a client socket,
789 * therefore we just treat them as an error. Is this
791 if (errno == EAGAIN || errno == EWOULDBLOCK)
795 /* If not, there was some kind of error. We don’t bother
796 * and close the connection */
799 /* Delete the client from the list of clients */
801 TAILQ_FOREACH(current, &all_clients, clients) {
802 if (current->fd != w->fd)
805 for (int i = 0; i < current->num_events; i++)
806 free(current->events[i]);
807 /* We can call TAILQ_REMOVE because we break out of the
808 * TAILQ_FOREACH afterwards */
809 TAILQ_REMOVE(&all_clients, current, clients);
817 DLOG("IPC: client disconnected\n");
821 /* Terminate the message correctly */
824 /* Check if the message starts with the i3 IPC magic code */
825 if (n < strlen(I3_IPC_MAGIC)) {
826 DLOG("IPC: message too short, ignoring\n");
830 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
831 DLOG("IPC: message does not start with the IPC magic\n");
835 uint8_t *message = (uint8_t*)buf;
837 DLOG("IPC: n = %d\n", n);
838 message += strlen(I3_IPC_MAGIC);
839 n -= strlen(I3_IPC_MAGIC);
841 /* The next 32 bit after the magic are the message size */
842 uint32_t message_size;
843 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
844 message += sizeof(uint32_t);
845 n -= sizeof(uint32_t);
847 if (message_size > n) {
848 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
852 /* The last 32 bits of the header are the message type */
853 uint32_t message_type;
854 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
855 message += sizeof(uint32_t);
856 n -= sizeof(uint32_t);
858 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
859 DLOG("Unhandled message type: %d\n", message_type);
861 handler_t h = handlers[message_type];
862 h(w->fd, message, n, message_size, message_type);
865 message += message_size;
870 * Handler for activity on the listening socket, meaning that a new client
871 * has just connected and we should accept() him. Sets up the event handler
872 * for activity on the new connection and inserts the file descriptor into
873 * the list of clients.
876 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
877 struct sockaddr_un peer;
878 socklen_t len = sizeof(struct sockaddr_un);
880 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
883 else perror("accept()");
887 /* Close this file descriptor on exec() */
888 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
890 set_nonblock(client);
892 struct ev_io *package = scalloc(sizeof(struct ev_io));
893 ev_io_init(package, ipc_receive_message, client, EV_READ);
894 ev_io_start(EV_A_ package);
896 DLOG("IPC: new client connected on fd %d\n", w->fd);
898 ipc_client *new = scalloc(sizeof(ipc_client));
901 TAILQ_INSERT_TAIL(&all_clients, new, clients);
905 * Creates the UNIX domain socket at the given path, sets it to non-blocking
906 * mode, bind()s and listen()s on it.
909 int ipc_create_socket(const char *filename) {
912 FREE(current_socketpath);
914 char *resolved = resolve_tilde(filename);
915 DLOG("Creating IPC-socket at %s\n", resolved);
916 char *copy = sstrdup(resolved);
917 const char *dir = dirname(copy);
918 if (!path_exists(dir))
922 /* Unlink the unix domain socket before */
925 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
931 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
933 struct sockaddr_un addr;
934 memset(&addr, 0, sizeof(struct sockaddr_un));
935 addr.sun_family = AF_LOCAL;
936 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
937 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
943 set_nonblock(sockfd);
945 if (listen(sockfd, 5) < 0) {
951 current_socketpath = resolved;