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");
41 static void ipc_client_timeout(EV_P_ ev_timer *w, int revents);
42 static void ipc_socket_writeable_cb(EV_P_ struct ev_io *w, int revents);
44 static ev_tstamp kill_timeout = 10.0;
46 void ipc_set_kill_timeout(ev_tstamp new) {
51 * Try to write the contents of the pending buffer to the client's subscription
52 * socket. Will set, reset or clear the timeout and io write callbacks depending
53 * on the result of the write operation.
56 static void ipc_push_pending(ipc_client *client) {
57 const ssize_t result = writeall_nonblock(client->fd, client->buffer, client->buffer_size);
62 if ((size_t)result == client->buffer_size) {
63 /* Everything was written successfully: clear the timer and stop the io
66 client->buffer_size = 0;
67 if (client->timeout) {
68 ev_timer_stop(main_loop, client->timeout);
69 FREE(client->timeout);
71 ev_io_stop(main_loop, client->write_callback);
75 /* Otherwise, make sure that the io callback is enabled and create a new
77 ev_io_start(main_loop, client->write_callback);
79 if (!client->timeout) {
80 struct ev_timer *timeout = scalloc(1, sizeof(struct ev_timer));
81 ev_timer_init(timeout, ipc_client_timeout, kill_timeout, 0.);
82 timeout->data = client;
83 client->timeout = timeout;
84 ev_set_priority(timeout, EV_MINPRI);
85 ev_timer_start(main_loop, client->timeout);
86 } else if (result > 0) {
87 /* Keep the old timeout when nothing is written. Otherwise, we would
88 * keep a dead connection by continuously renewing its timeouts. */
89 ev_timer_stop(main_loop, client->timeout);
90 ev_timer_set(client->timeout, kill_timeout, 0.0);
91 ev_timer_start(main_loop, client->timeout);
97 /* Shift the buffer to the left and reduce the allocated space. */
98 client->buffer_size -= (size_t)result;
99 memmove(client->buffer, client->buffer + result, client->buffer_size);
100 client->buffer = srealloc(client->buffer, client->buffer_size);
104 * Given a message and a message type, create the corresponding header, merge it
105 * with the message and append it to the given client's output buffer. Also,
106 * send the message if the client's buffer was empty.
109 static void ipc_send_client_message(ipc_client *client, size_t size, const uint32_t message_type, const uint8_t *payload) {
110 const i3_ipc_header_t header = {
111 .magic = {'i', '3', '-', 'i', 'p', 'c'},
113 .type = message_type};
114 const size_t header_size = sizeof(i3_ipc_header_t);
115 const size_t message_size = header_size + size;
117 const bool push_now = (client->buffer_size == 0);
118 client->buffer = srealloc(client->buffer, client->buffer_size + message_size);
119 memcpy(client->buffer + client->buffer_size, ((void *)&header), header_size);
120 memcpy(client->buffer + client->buffer_size + header_size, payload, size);
121 client->buffer_size += message_size;
124 ipc_push_pending(client);
128 static void free_ipc_client(ipc_client *client) {
129 DLOG("Disconnecting client on fd %d\n", client->fd);
132 ev_io_stop(main_loop, client->read_callback);
133 FREE(client->read_callback);
134 ev_io_stop(main_loop, client->write_callback);
135 FREE(client->write_callback);
136 if (client->timeout) {
137 ev_timer_stop(main_loop, client->timeout);
138 FREE(client->timeout);
141 free(client->buffer);
143 for (int i = 0; i < client->num_events; i++) {
144 free(client->events[i]);
146 free(client->events);
147 TAILQ_REMOVE(&all_clients, client, clients);
152 * Sends the specified event to all IPC clients which are currently connected
153 * and subscribed to this kind of event.
156 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
158 TAILQ_FOREACH(current, &all_clients, clients) {
159 for (int i = 0; i < current->num_events; i++) {
160 if (strcasecmp(current->events[i], event) == 0) {
161 ipc_send_client_message(current, strlen(payload), message_type, (uint8_t *)payload);
169 * For shutdown events, we send the reason for the shutdown.
171 static void ipc_send_shutdown_event(shutdown_reason_t reason) {
172 yajl_gen gen = ygenalloc();
177 if (reason == SHUTDOWN_REASON_RESTART) {
179 } else if (reason == SHUTDOWN_REASON_EXIT) {
185 const unsigned char *payload;
188 y(get_buf, &payload, &length);
189 ipc_send_event("shutdown", I3_IPC_EVENT_SHUTDOWN, (const char *)payload);
195 * Calls shutdown() on each socket and closes it. This function is to be called
196 * when exiting or restarting only!
199 void ipc_shutdown(shutdown_reason_t reason) {
200 ipc_send_shutdown_event(reason);
203 while (!TAILQ_EMPTY(&all_clients)) {
204 current = TAILQ_FIRST(&all_clients);
205 shutdown(current->fd, SHUT_RDWR);
206 free_ipc_client(current);
211 * Executes the command and returns whether it could be successfully parsed
212 * or not (at the moment, always returns true).
215 IPC_HANDLER(run_command) {
216 /* To get a properly terminated buffer, we copy
217 * message_size bytes out of the buffer */
218 char *command = scalloc(message_size + 1, 1);
219 strncpy(command, (const char *)message, message_size);
220 LOG("IPC: received: *%s*\n", command);
221 yajl_gen gen = yajl_gen_alloc(NULL);
223 CommandResult *result = parse_command((const char *)command, gen);
226 if (result->needs_tree_render)
229 command_result_free(result);
231 const unsigned char *reply;
233 yajl_gen_get_buf(gen, &reply, &length);
235 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_COMMAND,
236 (const uint8_t *)reply);
241 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
251 y(integer, r.height);
255 static void dump_event_state_mask(yajl_gen gen, Binding *bind) {
257 for (int i = 0; i < 20; i++) {
258 if (bind->event_state_mask & (1 << i)) {
260 case XCB_KEY_BUT_MASK_SHIFT:
263 case XCB_KEY_BUT_MASK_LOCK:
266 case XCB_KEY_BUT_MASK_CONTROL:
269 case XCB_KEY_BUT_MASK_MOD_1:
272 case XCB_KEY_BUT_MASK_MOD_2:
275 case XCB_KEY_BUT_MASK_MOD_3:
278 case XCB_KEY_BUT_MASK_MOD_4:
281 case XCB_KEY_BUT_MASK_MOD_5:
284 case XCB_KEY_BUT_MASK_BUTTON_1:
287 case XCB_KEY_BUT_MASK_BUTTON_2:
290 case XCB_KEY_BUT_MASK_BUTTON_3:
293 case XCB_KEY_BUT_MASK_BUTTON_4:
296 case XCB_KEY_BUT_MASK_BUTTON_5:
299 case (I3_XKB_GROUP_MASK_1 << 16):
302 case (I3_XKB_GROUP_MASK_2 << 16):
305 case (I3_XKB_GROUP_MASK_3 << 16):
308 case (I3_XKB_GROUP_MASK_4 << 16):
317 static void dump_binding(yajl_gen gen, Binding *bind) {
320 y(integer, bind->keycode);
323 ystr((const char *)(bind->input_type == B_KEYBOARD ? "keyboard" : "mouse"));
326 if (bind->symbol == NULL)
334 // This key is only provided for compatibility, new programs should use
335 // event_state_mask instead.
337 dump_event_state_mask(gen, bind);
339 ystr("event_state_mask");
340 dump_event_state_mask(gen, bind);
345 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
348 y(integer, (uintptr_t)con);
361 case CT_FLOATING_CON:
362 ystr("floating_con");
372 /* provided for backwards compatibility only. */
374 if (!con_is_split(con))
377 if (con_orientation(con) == HORIZ)
383 ystr("scratchpad_state");
384 switch (con->scratchpad_state) {
385 case SCRATCHPAD_NONE:
388 case SCRATCHPAD_FRESH:
391 case SCRATCHPAD_CHANGED:
397 if (con->percent == 0.0)
400 y(double, con->percent);
403 y(bool, con->urgent);
405 if (!TAILQ_EMPTY(&(con->marks_head))) {
410 TAILQ_FOREACH(mark, &(con->marks_head), marks) {
418 y(bool, (con == focused));
420 if (con->type != CT_ROOT && con->type != CT_OUTPUT) {
422 ystr(con_get_output(con)->name);
426 switch (con->layout) {
428 DLOG("About to dump layout=default, this is a bug in the code.\n");
451 ystr("workspace_layout");
452 switch (con->workspace_layout) {
463 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
468 ystr("last_split_layout");
469 switch (con->layout) {
479 switch (con->border_style) {
491 ystr("current_border_width");
492 y(integer, con->current_border_width);
494 dump_rect(gen, "rect", con->rect);
495 dump_rect(gen, "deco_rect", con->deco_rect);
496 dump_rect(gen, "window_rect", con->window_rect);
497 dump_rect(gen, "geometry", con->geometry);
500 if (con->window && con->window->name)
501 ystr(i3string_as_utf8(con->window->name));
502 else if (con->name != NULL)
507 if (con->title_format != NULL) {
508 ystr("title_format");
509 ystr(con->title_format);
512 if (con->type == CT_WORKSPACE) {
514 y(integer, con->num);
519 y(integer, con->window->id);
523 if (con->window && !inplace_restart) {
524 /* Window properties are useless to preserve when restarting because
525 * they will be queried again anyway. However, for i3-save-tree(1),
526 * they are very useful and save i3-save-tree dealing with X11. */
527 ystr("window_properties");
530 #define DUMP_PROPERTY(key, prop_name) \
532 if (con->window->prop_name != NULL) { \
534 ystr(con->window->prop_name); \
538 DUMP_PROPERTY("class", class_class);
539 DUMP_PROPERTY("instance", class_instance);
540 DUMP_PROPERTY("window_role", role);
542 if (con->window->name != NULL) {
544 ystr(i3string_as_utf8(con->window->name));
547 ystr("transient_for");
548 if (con->window->transient_for == XCB_NONE)
551 y(integer, con->window->transient_for);
559 if (con->type != CT_DOCKAREA || !inplace_restart) {
560 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
561 dump_node(gen, node, inplace_restart);
566 ystr("floating_nodes");
568 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
569 dump_node(gen, node, inplace_restart);
575 TAILQ_FOREACH(node, &(con->focus_head), focused) {
576 y(integer, (uintptr_t)node);
580 ystr("fullscreen_mode");
581 y(integer, con->fullscreen_mode);
584 y(bool, con->sticky);
587 switch (con->floating) {
588 case FLOATING_AUTO_OFF:
591 case FLOATING_AUTO_ON:
594 case FLOATING_USER_OFF:
597 case FLOATING_USER_ON:
605 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
606 /* We will generate a new restart_mode match specification after this
607 * loop, so skip this one. */
608 if (match->restart_mode)
611 if (match->dock != M_DONTCHECK) {
613 y(integer, match->dock);
614 ystr("insert_where");
615 y(integer, match->insert_where);
618 #define DUMP_REGEX(re_name) \
620 if (match->re_name != NULL) { \
622 ystr(match->re_name->pattern); \
627 DUMP_REGEX(instance);
628 DUMP_REGEX(window_role);
635 if (inplace_restart) {
636 if (con->window != NULL) {
639 y(integer, con->window->id);
640 ystr("restart_mode");
647 if (inplace_restart && con->window != NULL) {
649 y(integer, con->depth);
652 if (inplace_restart && con->type == CT_ROOT && previous_workspace_name) {
653 ystr("previous_workspace_name");
654 ystr(previous_workspace_name);
660 static void dump_bar_bindings(yajl_gen gen, Barconfig *config) {
661 if (TAILQ_EMPTY(&(config->bar_bindings)))
667 struct Barbinding *current;
668 TAILQ_FOREACH(current, &(config->bar_bindings), bindings) {
672 y(integer, current->input_code);
674 ystr(current->command);
676 y(bool, current->release == B_UPON_KEYRELEASE);
684 static char *canonicalize_output_name(char *name) {
685 /* Do not canonicalize special output names. */
686 if (strcasecmp(name, "primary") == 0) {
689 Output *output = get_output_by_name(name, false);
690 return output ? output_primary_name(output) : name;
693 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
699 if (config->num_outputs > 0) {
702 for (int c = 0; c < config->num_outputs; c++) {
703 /* Convert monitor names (RandR ≥ 1.5) or output names
704 * (RandR < 1.5) into monitor names. This way, existing
705 * configs which use output names transparently keep
707 ystr(canonicalize_output_name(config->outputs[c]));
712 if (!TAILQ_EMPTY(&(config->tray_outputs))) {
713 ystr("tray_outputs");
716 struct tray_output_t *tray_output;
717 TAILQ_FOREACH(tray_output, &(config->tray_outputs), tray_outputs) {
718 ystr(canonicalize_output_name(tray_output->output));
724 #define YSTR_IF_SET(name) \
726 if (config->name) { \
728 ystr(config->name); \
732 ystr("tray_padding");
733 y(integer, config->tray_padding);
735 YSTR_IF_SET(socket_path);
738 switch (config->mode) {
751 ystr("hidden_state");
752 switch (config->hidden_state) {
763 y(integer, config->modifier);
765 dump_bar_bindings(gen, config);
768 if (config->position == P_BOTTOM)
773 YSTR_IF_SET(status_command);
776 if (config->separator_symbol) {
777 ystr("separator_symbol");
778 ystr(config->separator_symbol);
781 ystr("workspace_buttons");
782 y(bool, !config->hide_workspace_buttons);
784 ystr("strip_workspace_numbers");
785 y(bool, config->strip_workspace_numbers);
787 ystr("strip_workspace_name");
788 y(bool, config->strip_workspace_name);
790 ystr("binding_mode_indicator");
791 y(bool, !config->hide_binding_mode_indicator);
794 y(bool, config->verbose);
797 #define YSTR_IF_SET(name) \
799 if (config->colors.name) { \
801 ystr(config->colors.name); \
807 YSTR_IF_SET(background);
808 YSTR_IF_SET(statusline);
809 YSTR_IF_SET(separator);
810 YSTR_IF_SET(focused_background);
811 YSTR_IF_SET(focused_statusline);
812 YSTR_IF_SET(focused_separator);
813 YSTR_IF_SET(focused_workspace_border);
814 YSTR_IF_SET(focused_workspace_bg);
815 YSTR_IF_SET(focused_workspace_text);
816 YSTR_IF_SET(active_workspace_border);
817 YSTR_IF_SET(active_workspace_bg);
818 YSTR_IF_SET(active_workspace_text);
819 YSTR_IF_SET(inactive_workspace_border);
820 YSTR_IF_SET(inactive_workspace_bg);
821 YSTR_IF_SET(inactive_workspace_text);
822 YSTR_IF_SET(urgent_workspace_border);
823 YSTR_IF_SET(urgent_workspace_bg);
824 YSTR_IF_SET(urgent_workspace_text);
825 YSTR_IF_SET(binding_mode_border);
826 YSTR_IF_SET(binding_mode_bg);
827 YSTR_IF_SET(binding_mode_text);
835 setlocale(LC_NUMERIC, "C");
836 yajl_gen gen = ygenalloc();
837 dump_node(gen, croot, false);
838 setlocale(LC_NUMERIC, "");
840 const unsigned char *payload;
842 y(get_buf, &payload, &length);
844 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_TREE, payload);
849 * Formats the reply message for a GET_WORKSPACES request and sends it to the
853 IPC_HANDLER(get_workspaces) {
854 yajl_gen gen = ygenalloc();
857 Con *focused_ws = con_get_workspace(focused);
860 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
861 if (con_is_internal(output))
864 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
865 assert(ws->type == CT_WORKSPACE);
875 y(bool, workspace_is_visible(ws));
878 y(bool, ws == focused_ws);
883 y(integer, ws->rect.x);
885 y(integer, ws->rect.y);
887 y(integer, ws->rect.width);
889 y(integer, ws->rect.height);
904 const unsigned char *payload;
906 y(get_buf, &payload, &length);
908 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
913 * Formats the reply message for a GET_OUTPUTS request and sends it to the
917 IPC_HANDLER(get_outputs) {
918 yajl_gen gen = ygenalloc();
922 TAILQ_FOREACH(output, &outputs, outputs) {
926 ystr(output_primary_name(output));
929 y(bool, output->active);
932 y(bool, output->primary);
937 y(integer, output->rect.x);
939 y(integer, output->rect.y);
941 y(integer, output->rect.width);
943 y(integer, output->rect.height);
946 ystr("current_workspace");
948 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
958 const unsigned char *payload;
960 y(get_buf, &payload, &length);
962 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
967 * Formats the reply message for a GET_MARKS request and sends it to the
971 IPC_HANDLER(get_marks) {
972 yajl_gen gen = ygenalloc();
976 TAILQ_FOREACH(con, &all_cons, all_cons) {
978 TAILQ_FOREACH(mark, &(con->marks_head), marks) {
985 const unsigned char *payload;
987 y(get_buf, &payload, &length);
989 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_MARKS, payload);
994 * Returns the version of i3
997 IPC_HANDLER(get_version) {
998 yajl_gen gen = ygenalloc();
1002 y(integer, MAJOR_VERSION);
1005 y(integer, MINOR_VERSION);
1008 y(integer, PATCH_VERSION);
1010 ystr("human_readable");
1013 ystr("loaded_config_file_name");
1014 ystr(current_configpath);
1018 const unsigned char *payload;
1020 y(get_buf, &payload, &length);
1022 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_VERSION, payload);
1027 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
1031 IPC_HANDLER(get_bar_config) {
1032 yajl_gen gen = ygenalloc();
1034 /* If no ID was passed, we return a JSON array with all IDs */
1035 if (message_size == 0) {
1038 TAILQ_FOREACH(current, &barconfigs, configs) {
1043 const unsigned char *payload;
1045 y(get_buf, &payload, &length);
1047 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1052 /* To get a properly terminated buffer, we copy
1053 * message_size bytes out of the buffer */
1054 char *bar_id = NULL;
1055 sasprintf(&bar_id, "%.*s", message_size, message);
1056 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
1057 Barconfig *current, *config = NULL;
1058 TAILQ_FOREACH(current, &barconfigs, configs) {
1059 if (strcmp(current->id, bar_id) != 0)
1068 /* If we did not find a config for the given ID, the reply will contain
1069 * a null 'id' field. */
1077 dump_bar_config(gen, config);
1080 const unsigned char *payload;
1082 y(get_buf, &payload, &length);
1084 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1089 * Returns a list of configured binding modes
1092 IPC_HANDLER(get_binding_modes) {
1093 yajl_gen gen = ygenalloc();
1097 SLIST_FOREACH(mode, &modes, modes) {
1102 const unsigned char *payload;
1104 y(get_buf, &payload, &length);
1106 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BINDING_MODES, payload);
1111 * Callback for the YAJL parser (will be called when a string is parsed).
1114 static int add_subscription(void *extra, const unsigned char *s,
1116 ipc_client *client = extra;
1118 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
1119 int event = client->num_events;
1121 client->num_events++;
1122 client->events = srealloc(client->events, client->num_events * sizeof(char *));
1123 /* We copy the string because it is not null-terminated and strndup()
1124 * is missing on some BSD systems */
1125 client->events[event] = scalloc(len + 1, 1);
1126 memcpy(client->events[event], s, len);
1128 DLOG("client is now subscribed to:\n");
1129 for (int i = 0; i < client->num_events; i++) {
1130 DLOG("event %s\n", client->events[i]);
1138 * Subscribes this connection to the event types which were given as a JSON
1139 * serialized array in the payload field of the message.
1142 IPC_HANDLER(subscribe) {
1146 /* Setup the JSON parser */
1147 static yajl_callbacks callbacks = {
1148 .yajl_string = add_subscription,
1151 p = yalloc(&callbacks, (void *)client);
1152 stat = yajl_parse(p, (const unsigned char *)message, message_size);
1153 if (stat != yajl_status_ok) {
1155 err = yajl_get_error(p, true, (const unsigned char *)message,
1157 ELOG("YAJL parse error: %s\n", err);
1158 yajl_free_error(p, err);
1160 const char *reply = "{\"success\":false}";
1161 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1166 const char *reply = "{\"success\":true}";
1167 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1169 if (client->first_tick_sent) {
1173 bool is_tick = false;
1174 for (int i = 0; i < client->num_events; i++) {
1175 if (strcmp(client->events[i], "tick") == 0) {
1184 client->first_tick_sent = true;
1185 const char *payload = "{\"first\":true,\"payload\":\"\"}";
1186 ipc_send_client_message(client, strlen(payload), I3_IPC_EVENT_TICK, (const uint8_t *)payload);
1190 * Returns the raw last loaded i3 configuration file contents.
1192 IPC_HANDLER(get_config) {
1193 yajl_gen gen = ygenalloc();
1198 ystr(current_config);
1202 const unsigned char *payload;
1204 y(get_buf, &payload, &length);
1206 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_CONFIG, payload);
1211 * Sends the tick event from the message payload to subscribers. Establishes a
1212 * synchronization point in event-related tests.
1214 IPC_HANDLER(send_tick) {
1215 yajl_gen gen = ygenalloc();
1223 yajl_gen_string(gen, (unsigned char *)message, message_size);
1227 const unsigned char *payload;
1229 y(get_buf, &payload, &length);
1231 ipc_send_event("tick", I3_IPC_EVENT_TICK, (const char *)payload);
1234 const char *reply = "{\"success\":true}";
1235 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_TICK, (const uint8_t *)reply);
1236 DLOG("Sent tick event\n");
1242 xcb_window_t window;
1245 static int _sync_json_key(void *extra, const unsigned char *val, size_t len) {
1246 struct sync_state *state = extra;
1247 FREE(state->last_key);
1248 state->last_key = scalloc(len + 1, 1);
1249 memcpy(state->last_key, val, len);
1253 static int _sync_json_int(void *extra, long long val) {
1254 struct sync_state *state = extra;
1255 if (strcasecmp(state->last_key, "rnd") == 0) {
1257 } else if (strcasecmp(state->last_key, "window") == 0) {
1258 state->window = (xcb_window_t)val;
1267 /* Setup the JSON parser */
1268 static yajl_callbacks callbacks = {
1269 .yajl_map_key = _sync_json_key,
1270 .yajl_integer = _sync_json_int,
1273 struct sync_state state;
1274 memset(&state, '\0', sizeof(struct sync_state));
1275 p = yalloc(&callbacks, (void *)&state);
1276 stat = yajl_parse(p, (const unsigned char *)message, message_size);
1277 FREE(state.last_key);
1278 if (stat != yajl_status_ok) {
1280 err = yajl_get_error(p, true, (const unsigned char *)message,
1282 ELOG("YAJL parse error: %s\n", err);
1283 yajl_free_error(p, err);
1285 const char *reply = "{\"success\":false}";
1286 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1292 DLOG("received IPC sync request (rnd = %d, window = 0x%08x)\n", state.rnd, state.window);
1293 sync_respond(state.window, state.rnd);
1294 const char *reply = "{\"success\":true}";
1295 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1298 /* The index of each callback function corresponds to the numeric
1299 * value of the message type (see include/i3/ipc.h) */
1300 handler_t handlers[12] = {
1302 handle_get_workspaces,
1307 handle_get_bar_config,
1309 handle_get_binding_modes,
1316 * Handler for activity on a client connection, receives a message from a
1319 * For now, the maximum message size is 2048. I’m not sure for what the
1320 * IPC interface will be used in the future, thus I’m not implementing a
1321 * mechanism for arbitrarily long messages, as it seems like overkill
1325 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
1326 uint32_t message_type;
1327 uint32_t message_length;
1328 uint8_t *message = NULL;
1329 ipc_client *client = (ipc_client *)w->data;
1330 assert(client->fd == w->fd);
1332 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
1333 /* EOF or other error */
1335 /* Was this a spurious read? See ev(3) */
1336 if (ret == -1 && errno == EAGAIN) {
1341 /* If not, there was some kind of error. We don’t bother and close the
1342 * connection. Delete the client from the list of clients. */
1343 free_ipc_client(client);
1348 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1349 DLOG("Unhandled message type: %d\n", message_type);
1351 handler_t h = handlers[message_type];
1352 h(client, message, 0, message_length, message_type);
1358 static void ipc_client_timeout(EV_P_ ev_timer *w, int revents) {
1359 /* No need to be polite and check for writeability, the other callback would
1360 * have been called by now. */
1361 ipc_client *client = (ipc_client *)w->data;
1363 char *cmdline = NULL;
1364 #if defined(__linux__) && defined(SO_PEERCRED)
1365 struct ucred peercred;
1366 socklen_t so_len = sizeof(peercred);
1367 if (getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0) {
1371 sasprintf(&exepath, "/proc/%d/cmdline", peercred.pid);
1373 int fd = open(exepath, O_RDONLY);
1378 char buf[512] = {'\0'}; /* cut off cmdline for the error message. */
1379 const ssize_t n = read(fd, buf, sizeof(buf));
1384 for (char *walk = buf; walk < buf + n - 1; walk++) {
1385 if (*walk == '\0') {
1392 ELOG("client %p with pid %d and cmdline '%s' on fd %d timed out, killing\n", client, peercred.pid, cmdline, client->fd);
1398 ELOG("client %p on fd %d timed out, killing\n", client, client->fd);
1401 free_ipc_client(client);
1404 static void ipc_socket_writeable_cb(EV_P_ ev_io *w, int revents) {
1405 DLOG("fd %d writeable\n", w->fd);
1406 ipc_client *client = (ipc_client *)w->data;
1408 /* If this callback is called then there should be a corresponding active
1410 assert(client->timeout != NULL);
1411 ipc_push_pending(client);
1415 * Handler for activity on the listening socket, meaning that a new client
1416 * has just connected and we should accept() him. Sets up the event handler
1417 * for activity on the new connection and inserts the file descriptor into
1418 * the list of clients.
1421 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1422 struct sockaddr_un peer;
1423 socklen_t len = sizeof(struct sockaddr_un);
1425 if ((fd = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1426 if (errno != EINTR) {
1432 /* Close this file descriptor on exec() */
1433 (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
1437 ipc_client *client = scalloc(1, sizeof(ipc_client));
1440 client->read_callback = scalloc(1, sizeof(struct ev_io));
1441 client->read_callback->data = client;
1442 ev_io_init(client->read_callback, ipc_receive_message, fd, EV_READ);
1443 ev_io_start(EV_A_ client->read_callback);
1445 client->write_callback = scalloc(1, sizeof(struct ev_io));
1446 client->write_callback->data = client;
1447 ev_io_init(client->write_callback, ipc_socket_writeable_cb, fd, EV_WRITE);
1449 DLOG("IPC: new client connected on fd %d\n", w->fd);
1450 TAILQ_INSERT_TAIL(&all_clients, client, clients);
1454 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1455 * mode, bind()s and listen()s on it.
1458 int ipc_create_socket(const char *filename) {
1461 FREE(current_socketpath);
1463 char *resolved = resolve_tilde(filename);
1464 DLOG("Creating IPC-socket at %s\n", resolved);
1465 char *copy = sstrdup(resolved);
1466 const char *dir = dirname(copy);
1467 if (!path_exists(dir))
1468 mkdirp(dir, DEFAULT_DIR_MODE);
1471 /* Unlink the unix domain socket before */
1474 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1480 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1482 struct sockaddr_un addr;
1483 memset(&addr, 0, sizeof(struct sockaddr_un));
1484 addr.sun_family = AF_LOCAL;
1485 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1486 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1492 set_nonblock(sockfd);
1494 if (listen(sockfd, 5) < 0) {
1500 current_socketpath = resolved;
1505 * Generates a json workspace event. Returns a dynamically allocated yajl
1506 * generator. Free with yajl_gen_free().
1508 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1509 setlocale(LC_NUMERIC, "C");
1510 yajl_gen gen = ygenalloc();
1518 if (current == NULL)
1521 dump_node(gen, current, false);
1527 dump_node(gen, old, false);
1531 setlocale(LC_NUMERIC, "");
1537 * For the workspace events we send, along with the usual "change" field, also
1538 * the workspace container in "current". For focus events, we send the
1539 * previously focused workspace in "old".
1541 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1542 yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1544 const unsigned char *payload;
1546 y(get_buf, &payload, &length);
1548 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1554 * For the window events we send, along the usual "change" field,
1555 * also the window container, in "container".
1557 void ipc_send_window_event(const char *property, Con *con) {
1558 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1559 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1561 setlocale(LC_NUMERIC, "C");
1562 yajl_gen gen = ygenalloc();
1570 dump_node(gen, con, false);
1574 const unsigned char *payload;
1576 y(get_buf, &payload, &length);
1578 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1580 setlocale(LC_NUMERIC, "");
1584 * For the barconfig update events, we send the serialized barconfig.
1586 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1587 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1588 setlocale(LC_NUMERIC, "C");
1589 yajl_gen gen = ygenalloc();
1591 dump_bar_config(gen, barconfig);
1593 const unsigned char *payload;
1595 y(get_buf, &payload, &length);
1597 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1599 setlocale(LC_NUMERIC, "");
1603 * For the binding events, we send the serialized binding struct.
1605 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1606 DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1608 setlocale(LC_NUMERIC, "C");
1610 yajl_gen gen = ygenalloc();
1618 dump_binding(gen, bind);
1622 const unsigned char *payload;
1624 y(get_buf, &payload, &length);
1626 ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1629 setlocale(LC_NUMERIC, "");