2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
6 * © 2009-2011 Michael Stapelberg and contributors
8 * See file LICENSE for license information.
10 * ipc.c: Everything about the UNIX domain sockets for IPC
13 #include <sys/socket.h>
18 #include <yajl/yajl_gen.h>
19 #include <yajl/yajl_parse.h>
20 #include <yajl/yajl_version.h>
24 char *current_socketpath = NULL;
26 /* Shorter names for all those yajl_gen_* functions */
27 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
28 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
30 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
33 * Puts the given socket file descriptor into non-blocking mode or dies if
34 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
35 * IPC model because we should by no means block the window manager.
38 static void set_nonblock(int sockfd) {
39 int flags = fcntl(sockfd, F_GETFL, 0);
41 if (fcntl(sockfd, F_SETFL, flags) < 0)
42 err(-1, "Could not set O_NONBLOCK");
46 * Emulates mkdir -p (creates any missing folders)
49 static bool mkdirp(const char *path) {
50 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
52 if (errno != ENOENT) {
53 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
56 char *copy = strdup(path);
57 /* strip trailing slashes, if any */
58 while (copy[strlen(copy)-1] == '/')
59 copy[strlen(copy)-1] = '\0';
61 char *sep = strrchr(copy, '/');
69 result = mkdirp(path);
76 * Sends the specified event to all IPC clients which are currently connected
77 * and subscribed to this kind of event.
80 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
82 TAILQ_FOREACH(current, &all_clients, clients) {
83 /* see if this client is interested in this event */
84 bool interested = false;
85 for (int i = 0; i < current->num_events; i++) {
86 if (strcasecmp(current->events[i], event) != 0)
94 ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t*)payload);
99 * Calls shutdown() on each socket and closes it. This function to be called
100 * when exiting or restarting only!
103 void ipc_shutdown() {
105 TAILQ_FOREACH(current, &all_clients, clients) {
106 shutdown(current->fd, SHUT_RDWR);
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) {
170 if (con->percent == 0.0)
172 else y(double, con->percent);
175 y(bool, con->urgent);
177 if (con->mark != NULL) {
183 y(bool, (con == focused));
186 switch (con->layout) {
205 switch (con->border_style) {
217 dump_rect(gen, "rect", con->rect);
218 dump_rect(gen, "window_rect", con->window_rect);
219 dump_rect(gen, "geometry", con->geometry);
222 if (con->window && con->window->name_json)
223 ystr(con->window->name_json);
227 if (con->type == CT_WORKSPACE) {
229 y(integer, con->num);
234 y(integer, con->window->id);
240 if (con->type != CT_DOCKAREA || !inplace_restart) {
241 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
242 dump_node(gen, node, inplace_restart);
247 ystr("floating_nodes");
249 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
250 dump_node(gen, node, inplace_restart);
256 TAILQ_FOREACH(node, &(con->focus_head), focused) {
257 y(integer, (long int)node);
261 ystr("fullscreen_mode");
262 y(integer, con->fullscreen_mode);
267 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
268 if (match->dock != -1) {
271 y(integer, match->dock);
272 ystr("insert_where");
273 y(integer, match->insert_where);
277 /* TODO: the other swallow keys */
280 if (inplace_restart) {
281 if (con->window != NULL) {
284 y(integer, con->window->id);
294 setlocale(LC_NUMERIC, "C");
296 yajl_gen gen = yajl_gen_alloc(NULL);
298 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
300 dump_node(gen, croot, false);
301 setlocale(LC_NUMERIC, "");
303 const unsigned char *payload;
309 y(get_buf, &payload, &length);
311 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
317 * Formats the reply message for a GET_WORKSPACES request and sends it to the
321 IPC_HANDLER(get_workspaces) {
323 yajl_gen gen = yajl_gen_alloc(NULL);
325 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
329 Con *focused_ws = con_get_workspace(focused);
332 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
334 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
335 assert(ws->type == CT_WORKSPACE);
341 else y(integer, ws->num);
347 y(bool, workspace_is_visible(ws));
350 y(bool, ws == focused_ws);
355 y(integer, ws->rect.x);
357 y(integer, ws->rect.y);
359 y(integer, ws->rect.width);
361 y(integer, ws->rect.height);
376 const unsigned char *payload;
382 y(get_buf, &payload, &length);
384 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
389 * Formats the reply message for a GET_OUTPUTS request and sends it to the
393 IPC_HANDLER(get_outputs) {
395 yajl_gen gen = yajl_gen_alloc(NULL);
397 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
402 TAILQ_FOREACH(output, &outputs, outputs) {
409 y(bool, output->active);
414 y(integer, output->rect.x);
416 y(integer, output->rect.y);
418 y(integer, output->rect.width);
420 y(integer, output->rect.height);
423 ystr("current_workspace");
425 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
434 const unsigned char *payload;
440 y(get_buf, &payload, &length);
442 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
447 * Formats the reply message for a GET_MARKS request and sends it to the
451 IPC_HANDLER(get_marks) {
453 yajl_gen gen = yajl_gen_alloc(NULL);
455 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
460 TAILQ_FOREACH(con, &all_cons, all_cons)
461 if (con->mark != NULL)
466 const unsigned char *payload;
472 y(get_buf, &payload, &length);
474 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
479 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
483 IPC_HANDLER(get_bar_config) {
484 /* To get a properly terminated buffer, we copy
485 * message_size bytes out of the buffer */
486 char *bar_id = scalloc(message_size + 1);
487 strncpy(bar_id, (const char*)message, message_size);
488 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
489 Barconfig *current, *config = NULL;
490 TAILQ_FOREACH(current, &barconfigs, configs) {
491 if (strcmp(current->id, bar_id) != 0)
499 yajl_gen gen = yajl_gen_alloc(NULL);
501 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
507 /* If we did not find a config for the given ID, the reply will contain
508 * a null 'id' field. */
515 if (config->num_outputs > 0) {
518 for (int c = 0; c < config->num_outputs; c++)
519 ystr(config->outputs[c]);
523 #define YSTR_IF_SET(name) \
525 if (config->name) { \
527 ystr(config->name); \
531 YSTR_IF_SET(tray_output);
532 YSTR_IF_SET(socket_path);
535 if (config->mode == M_HIDE)
540 if (config->position == P_BOTTOM)
544 YSTR_IF_SET(status_command);
547 ystr("workspace_buttons");
548 y(bool, !config->hide_workspace_buttons);
551 y(bool, config->verbose);
554 #define YSTR_IF_SET(name) \
556 if (config->colors.name) { \
558 ystr(config->colors.name); \
564 YSTR_IF_SET(background);
565 YSTR_IF_SET(statusline);
566 YSTR_IF_SET(focused_workspace_text);
567 YSTR_IF_SET(focused_workspace_bg);
568 YSTR_IF_SET(active_workspace_text);
569 YSTR_IF_SET(active_workspace_bg);
570 YSTR_IF_SET(inactive_workspace_text);
571 YSTR_IF_SET(inactive_workspace_bg);
572 YSTR_IF_SET(urgent_workspace_text);
573 YSTR_IF_SET(urgent_workspace_bg);
580 const unsigned char *payload;
586 y(get_buf, &payload, &length);
588 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
593 * Callback for the YAJL parser (will be called when a string is parsed).
597 static int add_subscription(void *extra, const unsigned char *s,
600 static int add_subscription(void *extra, const unsigned char *s,
603 ipc_client *client = extra;
605 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
606 int event = client->num_events;
608 client->num_events++;
609 client->events = realloc(client->events, client->num_events * sizeof(char*));
610 /* We copy the string because it is not null-terminated and strndup()
611 * is missing on some BSD systems */
612 client->events[event] = scalloc(len+1);
613 memcpy(client->events[event], s, len);
615 DLOG("client is now subscribed to:\n");
616 for (int i = 0; i < client->num_events; i++)
617 DLOG("event %s\n", client->events[i]);
624 * Subscribes this connection to the event types which were given as a JSON
625 * serialized array in the payload field of the message.
628 IPC_HANDLER(subscribe) {
630 yajl_callbacks callbacks;
632 ipc_client *current, *client = NULL;
634 /* Search the ipc_client structure for this connection */
635 TAILQ_FOREACH(current, &all_clients, clients) {
636 if (current->fd != fd)
643 if (client == NULL) {
644 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
648 /* Setup the JSON parser */
649 memset(&callbacks, 0, sizeof(yajl_callbacks));
650 callbacks.yajl_string = add_subscription;
653 p = yajl_alloc(&callbacks, NULL, (void*)client);
655 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
657 stat = yajl_parse(p, (const unsigned char*)message, message_size);
658 if (stat != yajl_status_ok) {
660 err = yajl_get_error(p, true, (const unsigned char*)message,
662 ELOG("YAJL parse error: %s\n", err);
663 yajl_free_error(p, err);
665 const char *reply = "{\"success\":false}";
666 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
671 const char *reply = "{\"success\":true}";
672 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
675 /* The index of each callback function corresponds to the numeric
676 * value of the message type (see include/i3/ipc.h) */
677 handler_t handlers[7] = {
679 handle_get_workspaces,
684 handle_get_bar_config
688 * Handler for activity on a client connection, receives a message from a
691 * For now, the maximum message size is 2048. I’m not sure for what the
692 * IPC interface will be used in the future, thus I’m not implementing a
693 * mechanism for arbitrarily long messages, as it seems like overkill
697 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
699 int n = read(w->fd, buf, sizeof(buf));
701 /* On error or an empty message, we close the connection */
704 /* FIXME: I get these when closing a client socket,
705 * therefore we just treat them as an error. Is this
707 if (errno == EAGAIN || errno == EWOULDBLOCK)
711 /* If not, there was some kind of error. We don’t bother
712 * and close the connection */
715 /* Delete the client from the list of clients */
717 TAILQ_FOREACH(current, &all_clients, clients) {
718 if (current->fd != w->fd)
721 for (int i = 0; i < current->num_events; i++)
722 free(current->events[i]);
723 /* We can call TAILQ_REMOVE because we break out of the
724 * TAILQ_FOREACH afterwards */
725 TAILQ_REMOVE(&all_clients, current, clients);
731 DLOG("IPC: client disconnected\n");
735 /* Terminate the message correctly */
738 /* Check if the message starts with the i3 IPC magic code */
739 if (n < strlen(I3_IPC_MAGIC)) {
740 DLOG("IPC: message too short, ignoring\n");
744 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
745 DLOG("IPC: message does not start with the IPC magic\n");
749 uint8_t *message = (uint8_t*)buf;
751 DLOG("IPC: n = %d\n", n);
752 message += strlen(I3_IPC_MAGIC);
753 n -= strlen(I3_IPC_MAGIC);
755 /* The next 32 bit after the magic are the message size */
756 uint32_t message_size;
757 memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
758 message += sizeof(uint32_t);
759 n -= sizeof(uint32_t);
761 if (message_size > n) {
762 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
766 /* The last 32 bits of the header are the message type */
767 uint32_t message_type;
768 memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
769 message += sizeof(uint32_t);
770 n -= sizeof(uint32_t);
772 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
773 DLOG("Unhandled message type: %d\n", message_type);
775 handler_t h = handlers[message_type];
776 h(w->fd, message, n, message_size, message_type);
779 message += message_size;
784 * Handler for activity on the listening socket, meaning that a new client
785 * has just connected and we should accept() him. Sets up the event handler
786 * for activity on the new connection and inserts the file descriptor into
787 * the list of clients.
790 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
791 struct sockaddr_un peer;
792 socklen_t len = sizeof(struct sockaddr_un);
794 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
797 else perror("accept()");
801 set_nonblock(client);
803 struct ev_io *package = scalloc(sizeof(struct ev_io));
804 ev_io_init(package, ipc_receive_message, client, EV_READ);
805 ev_io_start(EV_A_ package);
807 DLOG("IPC: new client connected on fd %d\n", w->fd);
809 ipc_client *new = scalloc(sizeof(ipc_client));
812 TAILQ_INSERT_TAIL(&all_clients, new, clients);
816 * Creates the UNIX domain socket at the given path, sets it to non-blocking
817 * mode, bind()s and listen()s on it.
820 int ipc_create_socket(const char *filename) {
823 FREE(current_socketpath);
825 char *resolved = resolve_tilde(filename);
826 DLOG("Creating IPC-socket at %s\n", resolved);
827 char *copy = sstrdup(resolved);
828 const char *dir = dirname(copy);
829 if (!path_exists(dir))
833 /* Unlink the unix domain socket before */
836 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
842 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
844 struct sockaddr_un addr;
845 memset(&addr, 0, sizeof(struct sockaddr_un));
846 addr.sun_family = AF_LOCAL;
847 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
848 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
854 set_nonblock(sockfd);
856 if (listen(sockfd, 5) < 0) {
862 current_socketpath = resolved;