2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
7 * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
12 #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)
26 all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
29 * Puts the given socket file descriptor into non-blocking mode or dies if
30 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
31 * IPC model because we should by no means block the window manager.
34 static void set_nonblock(int sockfd) {
35 int flags = fcntl(sockfd, F_GETFL, 0);
37 if (fcntl(sockfd, F_SETFL, flags) < 0)
38 err(-1, "Could not set O_NONBLOCK");
42 * Given a message and a message type, create the corresponding header, merge it
43 * with the message and append it to the given client's output buffer.
46 static void append_payload(ipc_client *client, uint32_t message_type, const char *payload) {
47 const size_t size = strlen(payload);
48 const i3_ipc_header_t header = {
49 .magic = {'i', '3', '-', 'i', 'p', 'c'},
51 .type = message_type};
52 const size_t header_size = sizeof(i3_ipc_header_t);
53 const size_t message_size = header_size + size;
55 client->buffer = srealloc(client->buffer, client->buffer_size + message_size);
56 memcpy(client->buffer + client->buffer_size, ((void *)&header), header_size);
57 memcpy(client->buffer + client->buffer_size + header_size, payload, size);
58 client->buffer_size += message_size;
61 static void free_ipc_client(ipc_client *client) {
64 ev_io_stop(main_loop, client->callback);
65 FREE(client->callback);
66 if (client->timeout) {
67 ev_timer_stop(main_loop, client->timeout);
68 FREE(client->timeout);
73 for (int i = 0; i < client->num_events; i++) {
74 free(client->events[i]);
77 TAILQ_REMOVE(&all_clients, client, clients);
81 static void ipc_client_timeout(EV_P_ ev_timer *w, int revents);
82 static void ipc_socket_writeable_cb(EV_P_ struct ev_io *w, int revents);
84 static ev_tstamp kill_timeout = 10.0;
86 void ipc_set_kill_timeout(ev_tstamp new) {
91 * Try to write the contents of the pending buffer to the client's subscription
92 * socket. Will set, reset or clear the timeout and io callbacks depending on
93 * the result of the write operation.
96 static void ipc_push_pending(ipc_client *client) {
97 const ssize_t result = writeall_nonblock(client->fd, client->buffer, client->buffer_size);
102 if ((size_t)result == client->buffer_size) {
103 /* Everything was written successfully: clear the timer and stop the io
105 FREE(client->buffer);
106 client->buffer_size = 0;
107 if (client->timeout) {
108 ev_timer_stop(main_loop, client->timeout);
109 FREE(client->timeout);
111 ev_io_stop(main_loop, client->callback);
115 /* Otherwise, make sure that the io callback is enabled and create a new
116 * timer if needed. */
117 ev_io_start(main_loop, client->callback);
119 if (!client->timeout) {
120 struct ev_timer *timeout = scalloc(1, sizeof(struct ev_timer));
121 ev_timer_init(timeout, ipc_client_timeout, kill_timeout, 0.);
122 timeout->data = client;
123 client->timeout = timeout;
124 ev_set_priority(timeout, EV_MINPRI);
125 ev_timer_start(main_loop, client->timeout);
126 } else if (result > 0) {
127 /* Keep the old timeout when nothing is written. Otherwise, we would
128 * keep a dead connection by continuously renewing its timeouts. */
129 ev_timer_stop(main_loop, client->timeout);
130 ev_timer_set(client->timeout, kill_timeout, 0.0);
131 ev_timer_start(main_loop, client->timeout);
137 /* Shift the buffer to the left and reduce the allocated space. */
138 client->buffer_size -= (size_t)result;
139 memmove(client->buffer, client->buffer + result, client->buffer_size);
140 client->buffer = srealloc(client->buffer, client->buffer_size);
144 * Sends the specified event to all IPC clients which are currently connected
145 * and subscribed to this kind of event.
148 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
150 TAILQ_FOREACH(current, &all_clients, clients) {
151 /* see if this client is interested in this event */
152 bool interested = false;
153 for (int i = 0; i < current->num_events; i++) {
154 if (strcasecmp(current->events[i], event) != 0)
162 const bool push_now = (current->buffer_size == 0);
163 append_payload(current, message_type, payload);
165 ipc_push_pending(current);
171 * For shutdown events, we send the reason for the shutdown.
173 static void ipc_send_shutdown_event(shutdown_reason_t reason) {
174 yajl_gen gen = ygenalloc();
179 if (reason == SHUTDOWN_REASON_RESTART) {
181 } else if (reason == SHUTDOWN_REASON_EXIT) {
187 const unsigned char *payload;
190 y(get_buf, &payload, &length);
191 ipc_send_event("shutdown", I3_IPC_EVENT_SHUTDOWN, (const char *)payload);
197 * Calls shutdown() on each socket and closes it. This function is to be called
198 * when exiting or restarting only!
201 void ipc_shutdown(shutdown_reason_t reason) {
202 ipc_send_shutdown_event(reason);
205 while (!TAILQ_EMPTY(&all_clients)) {
206 current = TAILQ_FIRST(&all_clients);
207 shutdown(current->fd, SHUT_RDWR);
208 free_ipc_client(current);
213 * Executes the command and returns whether it could be successfully parsed
214 * or not (at the moment, always returns true).
217 IPC_HANDLER(run_command) {
218 /* To get a properly terminated buffer, we copy
219 * message_size bytes out of the buffer */
220 char *command = scalloc(message_size + 1, 1);
221 strncpy(command, (const char *)message, message_size);
222 LOG("IPC: received: *%s*\n", command);
223 yajl_gen gen = yajl_gen_alloc(NULL);
225 CommandResult *result = parse_command((const char *)command, gen);
228 if (result->needs_tree_render)
231 command_result_free(result);
233 const unsigned char *reply;
235 yajl_gen_get_buf(gen, &reply, &length);
237 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
238 (const uint8_t *)reply);
243 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
253 y(integer, r.height);
257 static void dump_event_state_mask(yajl_gen gen, Binding *bind) {
259 for (int i = 0; i < 20; i++) {
260 if (bind->event_state_mask & (1 << i)) {
262 case XCB_KEY_BUT_MASK_SHIFT:
265 case XCB_KEY_BUT_MASK_LOCK:
268 case XCB_KEY_BUT_MASK_CONTROL:
271 case XCB_KEY_BUT_MASK_MOD_1:
274 case XCB_KEY_BUT_MASK_MOD_2:
277 case XCB_KEY_BUT_MASK_MOD_3:
280 case XCB_KEY_BUT_MASK_MOD_4:
283 case XCB_KEY_BUT_MASK_MOD_5:
286 case XCB_KEY_BUT_MASK_BUTTON_1:
289 case XCB_KEY_BUT_MASK_BUTTON_2:
292 case XCB_KEY_BUT_MASK_BUTTON_3:
295 case XCB_KEY_BUT_MASK_BUTTON_4:
298 case XCB_KEY_BUT_MASK_BUTTON_5:
301 case (I3_XKB_GROUP_MASK_1 << 16):
304 case (I3_XKB_GROUP_MASK_2 << 16):
307 case (I3_XKB_GROUP_MASK_3 << 16):
310 case (I3_XKB_GROUP_MASK_4 << 16):
319 static void dump_binding(yajl_gen gen, Binding *bind) {
322 y(integer, bind->keycode);
325 ystr((const char *)(bind->input_type == B_KEYBOARD ? "keyboard" : "mouse"));
328 if (bind->symbol == NULL)
336 // This key is only provided for compatibility, new programs should use
337 // event_state_mask instead.
339 dump_event_state_mask(gen, bind);
341 ystr("event_state_mask");
342 dump_event_state_mask(gen, bind);
347 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
350 y(integer, (uintptr_t)con);
363 case CT_FLOATING_CON:
364 ystr("floating_con");
374 /* provided for backwards compatibility only. */
376 if (!con_is_split(con))
379 if (con_orientation(con) == HORIZ)
385 ystr("scratchpad_state");
386 switch (con->scratchpad_state) {
387 case SCRATCHPAD_NONE:
390 case SCRATCHPAD_FRESH:
393 case SCRATCHPAD_CHANGED:
399 if (con->percent == 0.0)
402 y(double, con->percent);
405 y(bool, con->urgent);
407 if (!TAILQ_EMPTY(&(con->marks_head))) {
412 TAILQ_FOREACH(mark, &(con->marks_head), marks) {
420 y(bool, (con == focused));
422 if (con->type != CT_ROOT && con->type != CT_OUTPUT) {
424 ystr(con_get_output(con)->name);
428 switch (con->layout) {
430 DLOG("About to dump layout=default, this is a bug in the code.\n");
453 ystr("workspace_layout");
454 switch (con->workspace_layout) {
465 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
470 ystr("last_split_layout");
471 switch (con->layout) {
481 switch (con->border_style) {
493 ystr("current_border_width");
494 y(integer, con->current_border_width);
496 dump_rect(gen, "rect", con->rect);
497 dump_rect(gen, "deco_rect", con->deco_rect);
498 dump_rect(gen, "window_rect", con->window_rect);
499 dump_rect(gen, "geometry", con->geometry);
502 if (con->window && con->window->name)
503 ystr(i3string_as_utf8(con->window->name));
504 else if (con->name != NULL)
509 if (con->title_format != NULL) {
510 ystr("title_format");
511 ystr(con->title_format);
514 if (con->type == CT_WORKSPACE) {
516 y(integer, con->num);
521 y(integer, con->window->id);
525 if (con->window && !inplace_restart) {
526 /* Window properties are useless to preserve when restarting because
527 * they will be queried again anyway. However, for i3-save-tree(1),
528 * they are very useful and save i3-save-tree dealing with X11. */
529 ystr("window_properties");
532 #define DUMP_PROPERTY(key, prop_name) \
534 if (con->window->prop_name != NULL) { \
536 ystr(con->window->prop_name); \
540 DUMP_PROPERTY("class", class_class);
541 DUMP_PROPERTY("instance", class_instance);
542 DUMP_PROPERTY("window_role", role);
544 if (con->window->name != NULL) {
546 ystr(i3string_as_utf8(con->window->name));
549 ystr("transient_for");
550 if (con->window->transient_for == XCB_NONE)
553 y(integer, con->window->transient_for);
561 if (con->type != CT_DOCKAREA || !inplace_restart) {
562 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
563 dump_node(gen, node, inplace_restart);
568 ystr("floating_nodes");
570 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
571 dump_node(gen, node, inplace_restart);
577 TAILQ_FOREACH(node, &(con->focus_head), focused) {
578 y(integer, (uintptr_t)node);
582 ystr("fullscreen_mode");
583 y(integer, con->fullscreen_mode);
586 y(bool, con->sticky);
589 switch (con->floating) {
590 case FLOATING_AUTO_OFF:
593 case FLOATING_AUTO_ON:
596 case FLOATING_USER_OFF:
599 case FLOATING_USER_ON:
607 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
608 /* We will generate a new restart_mode match specification after this
609 * loop, so skip this one. */
610 if (match->restart_mode)
613 if (match->dock != M_DONTCHECK) {
615 y(integer, match->dock);
616 ystr("insert_where");
617 y(integer, match->insert_where);
620 #define DUMP_REGEX(re_name) \
622 if (match->re_name != NULL) { \
624 ystr(match->re_name->pattern); \
629 DUMP_REGEX(instance);
630 DUMP_REGEX(window_role);
637 if (inplace_restart) {
638 if (con->window != NULL) {
641 y(integer, con->window->id);
642 ystr("restart_mode");
649 if (inplace_restart && con->window != NULL) {
651 y(integer, con->depth);
657 static void dump_bar_bindings(yajl_gen gen, Barconfig *config) {
658 if (TAILQ_EMPTY(&(config->bar_bindings)))
664 struct Barbinding *current;
665 TAILQ_FOREACH(current, &(config->bar_bindings), bindings) {
669 y(integer, current->input_code);
671 ystr(current->command);
673 y(bool, current->release == B_UPON_KEYRELEASE);
681 static char *canonicalize_output_name(char *name) {
682 /* Do not canonicalize special output names. */
683 if (strcasecmp(name, "primary") == 0) {
686 Output *output = get_output_by_name(name, false);
687 return output ? output_primary_name(output) : name;
690 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
696 if (config->num_outputs > 0) {
699 for (int c = 0; c < config->num_outputs; c++) {
700 /* Convert monitor names (RandR ≥ 1.5) or output names
701 * (RandR < 1.5) into monitor names. This way, existing
702 * configs which use output names transparently keep
704 ystr(canonicalize_output_name(config->outputs[c]));
709 if (!TAILQ_EMPTY(&(config->tray_outputs))) {
710 ystr("tray_outputs");
713 struct tray_output_t *tray_output;
714 TAILQ_FOREACH(tray_output, &(config->tray_outputs), tray_outputs) {
715 ystr(canonicalize_output_name(tray_output->output));
721 #define YSTR_IF_SET(name) \
723 if (config->name) { \
725 ystr(config->name); \
729 ystr("tray_padding");
730 y(integer, config->tray_padding);
732 YSTR_IF_SET(socket_path);
735 switch (config->mode) {
748 ystr("hidden_state");
749 switch (config->hidden_state) {
760 y(integer, config->modifier);
762 dump_bar_bindings(gen, config);
765 if (config->position == P_BOTTOM)
770 YSTR_IF_SET(status_command);
773 if (config->separator_symbol) {
774 ystr("separator_symbol");
775 ystr(config->separator_symbol);
778 ystr("workspace_buttons");
779 y(bool, !config->hide_workspace_buttons);
781 ystr("strip_workspace_numbers");
782 y(bool, config->strip_workspace_numbers);
784 ystr("strip_workspace_name");
785 y(bool, config->strip_workspace_name);
787 ystr("binding_mode_indicator");
788 y(bool, !config->hide_binding_mode_indicator);
791 y(bool, config->verbose);
794 #define YSTR_IF_SET(name) \
796 if (config->colors.name) { \
798 ystr(config->colors.name); \
804 YSTR_IF_SET(background);
805 YSTR_IF_SET(statusline);
806 YSTR_IF_SET(separator);
807 YSTR_IF_SET(focused_background);
808 YSTR_IF_SET(focused_statusline);
809 YSTR_IF_SET(focused_separator);
810 YSTR_IF_SET(focused_workspace_border);
811 YSTR_IF_SET(focused_workspace_bg);
812 YSTR_IF_SET(focused_workspace_text);
813 YSTR_IF_SET(active_workspace_border);
814 YSTR_IF_SET(active_workspace_bg);
815 YSTR_IF_SET(active_workspace_text);
816 YSTR_IF_SET(inactive_workspace_border);
817 YSTR_IF_SET(inactive_workspace_bg);
818 YSTR_IF_SET(inactive_workspace_text);
819 YSTR_IF_SET(urgent_workspace_border);
820 YSTR_IF_SET(urgent_workspace_bg);
821 YSTR_IF_SET(urgent_workspace_text);
822 YSTR_IF_SET(binding_mode_border);
823 YSTR_IF_SET(binding_mode_bg);
824 YSTR_IF_SET(binding_mode_text);
832 setlocale(LC_NUMERIC, "C");
833 yajl_gen gen = ygenalloc();
834 dump_node(gen, croot, false);
835 setlocale(LC_NUMERIC, "");
837 const unsigned char *payload;
839 y(get_buf, &payload, &length);
841 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
846 * Formats the reply message for a GET_WORKSPACES request and sends it to the
850 IPC_HANDLER(get_workspaces) {
851 yajl_gen gen = ygenalloc();
854 Con *focused_ws = con_get_workspace(focused);
857 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
858 if (con_is_internal(output))
861 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
862 assert(ws->type == CT_WORKSPACE);
872 y(bool, workspace_is_visible(ws));
875 y(bool, ws == focused_ws);
880 y(integer, ws->rect.x);
882 y(integer, ws->rect.y);
884 y(integer, ws->rect.width);
886 y(integer, ws->rect.height);
901 const unsigned char *payload;
903 y(get_buf, &payload, &length);
905 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
910 * Formats the reply message for a GET_OUTPUTS request and sends it to the
914 IPC_HANDLER(get_outputs) {
915 yajl_gen gen = ygenalloc();
919 TAILQ_FOREACH(output, &outputs, outputs) {
923 ystr(output_primary_name(output));
926 y(bool, output->active);
929 y(bool, output->primary);
934 y(integer, output->rect.x);
936 y(integer, output->rect.y);
938 y(integer, output->rect.width);
940 y(integer, output->rect.height);
943 ystr("current_workspace");
945 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
955 const unsigned char *payload;
957 y(get_buf, &payload, &length);
959 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
964 * Formats the reply message for a GET_MARKS request and sends it to the
968 IPC_HANDLER(get_marks) {
969 yajl_gen gen = ygenalloc();
973 TAILQ_FOREACH(con, &all_cons, all_cons) {
975 TAILQ_FOREACH(mark, &(con->marks_head), marks) {
982 const unsigned char *payload;
984 y(get_buf, &payload, &length);
986 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
991 * Returns the version of i3
994 IPC_HANDLER(get_version) {
995 yajl_gen gen = ygenalloc();
999 y(integer, MAJOR_VERSION);
1002 y(integer, MINOR_VERSION);
1005 y(integer, PATCH_VERSION);
1007 ystr("human_readable");
1010 ystr("loaded_config_file_name");
1011 ystr(current_configpath);
1015 const unsigned char *payload;
1017 y(get_buf, &payload, &length);
1019 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
1024 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
1028 IPC_HANDLER(get_bar_config) {
1029 yajl_gen gen = ygenalloc();
1031 /* If no ID was passed, we return a JSON array with all IDs */
1032 if (message_size == 0) {
1035 TAILQ_FOREACH(current, &barconfigs, configs) {
1040 const unsigned char *payload;
1042 y(get_buf, &payload, &length);
1044 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1049 /* To get a properly terminated buffer, we copy
1050 * message_size bytes out of the buffer */
1051 char *bar_id = NULL;
1052 sasprintf(&bar_id, "%.*s", message_size, message);
1053 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
1054 Barconfig *current, *config = NULL;
1055 TAILQ_FOREACH(current, &barconfigs, configs) {
1056 if (strcmp(current->id, bar_id) != 0)
1065 /* If we did not find a config for the given ID, the reply will contain
1066 * a null 'id' field. */
1074 dump_bar_config(gen, config);
1077 const unsigned char *payload;
1079 y(get_buf, &payload, &length);
1081 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1086 * Returns a list of configured binding modes
1089 IPC_HANDLER(get_binding_modes) {
1090 yajl_gen gen = ygenalloc();
1094 SLIST_FOREACH(mode, &modes, modes) {
1099 const unsigned char *payload;
1101 y(get_buf, &payload, &length);
1103 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BINDING_MODES, payload);
1108 * Callback for the YAJL parser (will be called when a string is parsed).
1111 static int add_subscription(void *extra, const unsigned char *s,
1113 ipc_client *client = extra;
1115 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
1116 int event = client->num_events;
1118 client->num_events++;
1119 client->events = srealloc(client->events, client->num_events * sizeof(char *));
1120 /* We copy the string because it is not null-terminated and strndup()
1121 * is missing on some BSD systems */
1122 client->events[event] = scalloc(len + 1, 1);
1123 memcpy(client->events[event], s, len);
1125 DLOG("client is now subscribed to:\n");
1126 for (int i = 0; i < client->num_events; i++) {
1127 DLOG("event %s\n", client->events[i]);
1135 * Subscribes this connection to the event types which were given as a JSON
1136 * serialized array in the payload field of the message.
1139 IPC_HANDLER(subscribe) {
1142 ipc_client *current, *client = NULL;
1144 /* Search the ipc_client structure for this connection */
1145 TAILQ_FOREACH(current, &all_clients, clients) {
1146 if (current->fd != fd)
1153 if (client == NULL) {
1154 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
1158 /* Setup the JSON parser */
1159 static yajl_callbacks callbacks = {
1160 .yajl_string = add_subscription,
1163 p = yalloc(&callbacks, (void *)client);
1164 stat = yajl_parse(p, (const unsigned char *)message, message_size);
1165 if (stat != yajl_status_ok) {
1167 err = yajl_get_error(p, true, (const unsigned char *)message,
1169 ELOG("YAJL parse error: %s\n", err);
1170 yajl_free_error(p, err);
1172 const char *reply = "{\"success\":false}";
1173 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1178 const char *reply = "{\"success\":true}";
1179 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1181 if (client->first_tick_sent) {
1185 bool is_tick = false;
1186 for (int i = 0; i < client->num_events; i++) {
1187 if (strcmp(client->events[i], "tick") == 0) {
1196 client->first_tick_sent = true;
1197 const char *payload = "{\"first\":true,\"payload\":\"\"}";
1198 ipc_send_message(client->fd, strlen(payload), I3_IPC_EVENT_TICK, (const uint8_t *)payload);
1202 * Returns the raw last loaded i3 configuration file contents.
1204 IPC_HANDLER(get_config) {
1205 yajl_gen gen = ygenalloc();
1210 ystr(current_config);
1214 const unsigned char *payload;
1216 y(get_buf, &payload, &length);
1218 ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_CONFIG, payload);
1223 * Sends the tick event from the message payload to subscribers. Establishes a
1224 * synchronization point in event-related tests.
1226 IPC_HANDLER(send_tick) {
1227 yajl_gen gen = ygenalloc();
1235 yajl_gen_string(gen, (unsigned char *)message, message_size);
1239 const unsigned char *payload;
1241 y(get_buf, &payload, &length);
1243 ipc_send_event("tick", I3_IPC_EVENT_TICK, (const char *)payload);
1246 const char *reply = "{\"success\":true}";
1247 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_TICK, (const uint8_t *)reply);
1248 DLOG("Sent tick event\n");
1254 xcb_window_t window;
1257 static int _sync_json_key(void *extra, const unsigned char *val, size_t len) {
1258 struct sync_state *state = extra;
1259 FREE(state->last_key);
1260 state->last_key = scalloc(len + 1, 1);
1261 memcpy(state->last_key, val, len);
1265 static int _sync_json_int(void *extra, long long val) {
1266 struct sync_state *state = extra;
1267 if (strcasecmp(state->last_key, "rnd") == 0) {
1269 } else if (strcasecmp(state->last_key, "window") == 0) {
1270 state->window = (xcb_window_t)val;
1279 /* Setup the JSON parser */
1280 static yajl_callbacks callbacks = {
1281 .yajl_map_key = _sync_json_key,
1282 .yajl_integer = _sync_json_int,
1285 struct sync_state state;
1286 memset(&state, '\0', sizeof(struct sync_state));
1287 p = yalloc(&callbacks, (void *)&state);
1288 stat = yajl_parse(p, (const unsigned char *)message, message_size);
1289 FREE(state.last_key);
1290 if (stat != yajl_status_ok) {
1292 err = yajl_get_error(p, true, (const unsigned char *)message,
1294 ELOG("YAJL parse error: %s\n", err);
1295 yajl_free_error(p, err);
1297 const char *reply = "{\"success\":false}";
1298 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1304 DLOG("received IPC sync request (rnd = %d, window = 0x%08x)\n", state.rnd, state.window);
1305 sync_respond(state.window, state.rnd);
1306 const char *reply = "{\"success\":true}";
1307 ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1310 /* The index of each callback function corresponds to the numeric
1311 * value of the message type (see include/i3/ipc.h) */
1312 handler_t handlers[12] = {
1314 handle_get_workspaces,
1319 handle_get_bar_config,
1321 handle_get_binding_modes,
1328 * Handler for activity on a client connection, receives a message from a
1331 * For now, the maximum message size is 2048. I’m not sure for what the
1332 * IPC interface will be used in the future, thus I’m not implementing a
1333 * mechanism for arbitrarily long messages, as it seems like overkill
1337 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
1338 uint32_t message_type;
1339 uint32_t message_length;
1340 uint8_t *message = NULL;
1342 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
1343 /* EOF or other error */
1345 /* Was this a spurious read? See ev(3) */
1346 if (ret == -1 && errno == EAGAIN) {
1351 /* If not, there was some kind of error. We don’t bother and close the
1352 * connection. Delete the client from the list of clients. */
1353 bool closed = false;
1354 ipc_client *current;
1355 TAILQ_FOREACH(current, &all_clients, clients) {
1356 if (current->fd != w->fd)
1359 free_ipc_client(current);
1367 ev_io_stop(EV_A_ w);
1371 DLOG("IPC: client disconnected\n");
1375 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1376 DLOG("Unhandled message type: %d\n", message_type);
1378 handler_t h = handlers[message_type];
1379 h(w->fd, message, 0, message_length, message_type);
1385 static void ipc_client_timeout(EV_P_ ev_timer *w, int revents) {
1386 /* No need to be polite and check for writeability, the other callback would
1387 * have been called by now. */
1388 ipc_client *client = (ipc_client *)w->data;
1390 char *cmdline = NULL;
1391 #if defined(__linux__) && defined(SO_PEERCRED)
1392 struct ucred peercred;
1393 socklen_t so_len = sizeof(peercred);
1394 if (getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0) {
1398 sasprintf(&exepath, "/proc/%d/cmdline", peercred.pid);
1400 int fd = open(exepath, O_RDONLY);
1405 char buf[512] = {'\0'}; /* cut off cmdline for the error message. */
1406 const ssize_t n = read(fd, buf, sizeof(buf));
1411 for (char *walk = buf; walk < buf + n - 1; walk++) {
1412 if (*walk == '\0') {
1419 ELOG("client %p with pid %d and cmdline '%s' on fd %d timed out, killing\n", client, peercred.pid, cmdline, client->fd);
1425 ELOG("client %p on fd %d timed out, killing\n", client, client->fd);
1428 free_ipc_client(client);
1431 static void ipc_socket_writeable_cb(EV_P_ ev_io *w, int revents) {
1432 DLOG("fd %d writeable\n", w->fd);
1433 ipc_client *client = (ipc_client *)w->data;
1435 /* If this callback is called then there should be a corresponding active
1437 assert(client->timeout != NULL);
1438 ipc_push_pending(client);
1442 * Handler for activity on the listening socket, meaning that a new client
1443 * has just connected and we should accept() him. Sets up the event handler
1444 * for activity on the new connection and inserts the file descriptor into
1445 * the list of clients.
1448 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1449 struct sockaddr_un peer;
1450 socklen_t len = sizeof(struct sockaddr_un);
1452 if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1460 /* Close this file descriptor on exec() */
1461 (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1463 set_nonblock(client);
1465 struct ev_io *package = scalloc(1, sizeof(struct ev_io));
1466 ev_io_init(package, ipc_receive_message, client, EV_READ);
1467 ev_io_start(EV_A_ package);
1469 ipc_client *new = scalloc(1, sizeof(ipc_client));
1471 package = scalloc(1, sizeof(struct ev_io));
1472 package->data = new;
1473 ev_io_init(package, ipc_socket_writeable_cb, client, EV_WRITE);
1475 DLOG("IPC: new client connected on fd %d\n", w->fd);
1478 new->callback = package;
1480 TAILQ_INSERT_TAIL(&all_clients, new, clients);
1484 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1485 * mode, bind()s and listen()s on it.
1488 int ipc_create_socket(const char *filename) {
1491 FREE(current_socketpath);
1493 char *resolved = resolve_tilde(filename);
1494 DLOG("Creating IPC-socket at %s\n", resolved);
1495 char *copy = sstrdup(resolved);
1496 const char *dir = dirname(copy);
1497 if (!path_exists(dir))
1498 mkdirp(dir, DEFAULT_DIR_MODE);
1501 /* Unlink the unix domain socket before */
1504 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1510 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1512 struct sockaddr_un addr;
1513 memset(&addr, 0, sizeof(struct sockaddr_un));
1514 addr.sun_family = AF_LOCAL;
1515 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1516 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1522 set_nonblock(sockfd);
1524 if (listen(sockfd, 5) < 0) {
1530 current_socketpath = resolved;
1535 * Generates a json workspace event. Returns a dynamically allocated yajl
1536 * generator. Free with yajl_gen_free().
1538 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1539 setlocale(LC_NUMERIC, "C");
1540 yajl_gen gen = ygenalloc();
1548 if (current == NULL)
1551 dump_node(gen, current, false);
1557 dump_node(gen, old, false);
1561 setlocale(LC_NUMERIC, "");
1567 * For the workspace events we send, along with the usual "change" field, also
1568 * the workspace container in "current". For focus events, we send the
1569 * previously focused workspace in "old".
1571 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1572 yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1574 const unsigned char *payload;
1576 y(get_buf, &payload, &length);
1578 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1584 * For the window events we send, along the usual "change" field,
1585 * also the window container, in "container".
1587 void ipc_send_window_event(const char *property, Con *con) {
1588 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1589 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1591 setlocale(LC_NUMERIC, "C");
1592 yajl_gen gen = ygenalloc();
1600 dump_node(gen, con, false);
1604 const unsigned char *payload;
1606 y(get_buf, &payload, &length);
1608 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1610 setlocale(LC_NUMERIC, "");
1614 * For the barconfig update events, we send the serialized barconfig.
1616 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1617 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1618 setlocale(LC_NUMERIC, "C");
1619 yajl_gen gen = ygenalloc();
1621 dump_bar_config(gen, barconfig);
1623 const unsigned char *payload;
1625 y(get_buf, &payload, &length);
1627 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1629 setlocale(LC_NUMERIC, "");
1633 * For the binding events, we send the serialized binding struct.
1635 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1636 DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1638 setlocale(LC_NUMERIC, "C");
1640 yajl_gen gen = ygenalloc();
1648 dump_binding(gen, bind);
1652 const unsigned char *payload;
1654 y(get_buf, &payload, &length);
1656 ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1659 setlocale(LC_NUMERIC, "");