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 = sstrndup((const char *)message, message_size);
219 LOG("IPC: received: *%s*\n", command);
220 yajl_gen gen = yajl_gen_alloc(NULL);
222 CommandResult *result = parse_command(command, gen);
225 if (result->needs_tree_render)
228 command_result_free(result);
230 const unsigned char *reply;
232 yajl_gen_get_buf(gen, &reply, &length);
234 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_COMMAND,
235 (const uint8_t *)reply);
240 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
250 y(integer, r.height);
254 static void dump_event_state_mask(yajl_gen gen, Binding *bind) {
256 for (int i = 0; i < 20; i++) {
257 if (bind->event_state_mask & (1 << i)) {
259 case XCB_KEY_BUT_MASK_SHIFT:
262 case XCB_KEY_BUT_MASK_LOCK:
265 case XCB_KEY_BUT_MASK_CONTROL:
268 case XCB_KEY_BUT_MASK_MOD_1:
271 case XCB_KEY_BUT_MASK_MOD_2:
274 case XCB_KEY_BUT_MASK_MOD_3:
277 case XCB_KEY_BUT_MASK_MOD_4:
280 case XCB_KEY_BUT_MASK_MOD_5:
283 case XCB_KEY_BUT_MASK_BUTTON_1:
286 case XCB_KEY_BUT_MASK_BUTTON_2:
289 case XCB_KEY_BUT_MASK_BUTTON_3:
292 case XCB_KEY_BUT_MASK_BUTTON_4:
295 case XCB_KEY_BUT_MASK_BUTTON_5:
298 case (I3_XKB_GROUP_MASK_1 << 16):
301 case (I3_XKB_GROUP_MASK_2 << 16):
304 case (I3_XKB_GROUP_MASK_3 << 16):
307 case (I3_XKB_GROUP_MASK_4 << 16):
316 static void dump_binding(yajl_gen gen, Binding *bind) {
319 y(integer, bind->keycode);
322 ystr((const char *)(bind->input_type == B_KEYBOARD ? "keyboard" : "mouse"));
325 if (bind->symbol == NULL)
333 // This key is only provided for compatibility, new programs should use
334 // event_state_mask instead.
336 dump_event_state_mask(gen, bind);
338 ystr("event_state_mask");
339 dump_event_state_mask(gen, bind);
344 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
347 y(integer, (uintptr_t)con);
360 case CT_FLOATING_CON:
361 ystr("floating_con");
371 /* provided for backwards compatibility only. */
373 if (!con_is_split(con))
376 if (con_orientation(con) == HORIZ)
382 ystr("scratchpad_state");
383 switch (con->scratchpad_state) {
384 case SCRATCHPAD_NONE:
387 case SCRATCHPAD_FRESH:
390 case SCRATCHPAD_CHANGED:
396 if (con->percent == 0.0)
399 y(double, con->percent);
402 y(bool, con->urgent);
404 if (!TAILQ_EMPTY(&(con->marks_head))) {
409 TAILQ_FOREACH(mark, &(con->marks_head), marks) {
417 y(bool, (con == focused));
419 if (con->type != CT_ROOT && con->type != CT_OUTPUT) {
421 ystr(con_get_output(con)->name);
425 switch (con->layout) {
427 DLOG("About to dump layout=default, this is a bug in the code.\n");
450 ystr("workspace_layout");
451 switch (con->workspace_layout) {
462 DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
467 ystr("last_split_layout");
468 switch (con->layout) {
478 switch (con->border_style) {
490 ystr("current_border_width");
491 y(integer, con->current_border_width);
493 dump_rect(gen, "rect", con->rect);
494 dump_rect(gen, "deco_rect", con->deco_rect);
495 dump_rect(gen, "window_rect", con->window_rect);
496 dump_rect(gen, "geometry", con->geometry);
499 if (con->window && con->window->name)
500 ystr(i3string_as_utf8(con->window->name));
501 else if (con->name != NULL)
506 if (con->title_format != NULL) {
507 ystr("title_format");
508 ystr(con->title_format);
511 if (con->type == CT_WORKSPACE) {
513 y(integer, con->num);
518 y(integer, con->window->id);
522 if (con->window && !inplace_restart) {
523 /* Window properties are useless to preserve when restarting because
524 * they will be queried again anyway. However, for i3-save-tree(1),
525 * they are very useful and save i3-save-tree dealing with X11. */
526 ystr("window_properties");
529 #define DUMP_PROPERTY(key, prop_name) \
531 if (con->window->prop_name != NULL) { \
533 ystr(con->window->prop_name); \
537 DUMP_PROPERTY("class", class_class);
538 DUMP_PROPERTY("instance", class_instance);
539 DUMP_PROPERTY("window_role", role);
541 if (con->window->name != NULL) {
543 ystr(i3string_as_utf8(con->window->name));
546 ystr("transient_for");
547 if (con->window->transient_for == XCB_NONE)
550 y(integer, con->window->transient_for);
558 if (con->type != CT_DOCKAREA || !inplace_restart) {
559 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
560 dump_node(gen, node, inplace_restart);
565 ystr("floating_nodes");
567 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
568 dump_node(gen, node, inplace_restart);
574 TAILQ_FOREACH(node, &(con->focus_head), focused) {
575 y(integer, (uintptr_t)node);
579 ystr("fullscreen_mode");
580 y(integer, con->fullscreen_mode);
583 y(bool, con->sticky);
586 switch (con->floating) {
587 case FLOATING_AUTO_OFF:
590 case FLOATING_AUTO_ON:
593 case FLOATING_USER_OFF:
596 case FLOATING_USER_ON:
604 TAILQ_FOREACH(match, &(con->swallow_head), matches) {
605 /* We will generate a new restart_mode match specification after this
606 * loop, so skip this one. */
607 if (match->restart_mode)
610 if (match->dock != M_DONTCHECK) {
612 y(integer, match->dock);
613 ystr("insert_where");
614 y(integer, match->insert_where);
617 #define DUMP_REGEX(re_name) \
619 if (match->re_name != NULL) { \
621 ystr(match->re_name->pattern); \
626 DUMP_REGEX(instance);
627 DUMP_REGEX(window_role);
634 if (inplace_restart) {
635 if (con->window != NULL) {
638 y(integer, con->window->id);
639 ystr("restart_mode");
646 if (inplace_restart && con->window != NULL) {
648 y(integer, con->depth);
651 if (inplace_restart && con->type == CT_ROOT && previous_workspace_name) {
652 ystr("previous_workspace_name");
653 ystr(previous_workspace_name);
659 static void dump_bar_bindings(yajl_gen gen, Barconfig *config) {
660 if (TAILQ_EMPTY(&(config->bar_bindings)))
666 struct Barbinding *current;
667 TAILQ_FOREACH(current, &(config->bar_bindings), bindings) {
671 y(integer, current->input_code);
673 ystr(current->command);
675 y(bool, current->release == B_UPON_KEYRELEASE);
683 static char *canonicalize_output_name(char *name) {
684 /* Do not canonicalize special output names. */
685 if (strcasecmp(name, "primary") == 0) {
688 Output *output = get_output_by_name(name, false);
689 return output ? output_primary_name(output) : name;
692 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
698 if (config->num_outputs > 0) {
701 for (int c = 0; c < config->num_outputs; c++) {
702 /* Convert monitor names (RandR ≥ 1.5) or output names
703 * (RandR < 1.5) into monitor names. This way, existing
704 * configs which use output names transparently keep
706 ystr(canonicalize_output_name(config->outputs[c]));
711 if (!TAILQ_EMPTY(&(config->tray_outputs))) {
712 ystr("tray_outputs");
715 struct tray_output_t *tray_output;
716 TAILQ_FOREACH(tray_output, &(config->tray_outputs), tray_outputs) {
717 ystr(canonicalize_output_name(tray_output->output));
723 #define YSTR_IF_SET(name) \
725 if (config->name) { \
727 ystr(config->name); \
731 ystr("tray_padding");
732 y(integer, config->tray_padding);
734 YSTR_IF_SET(socket_path);
737 switch (config->mode) {
750 ystr("hidden_state");
751 switch (config->hidden_state) {
762 y(integer, config->modifier);
764 dump_bar_bindings(gen, config);
767 if (config->position == P_BOTTOM)
772 YSTR_IF_SET(status_command);
775 if (config->separator_symbol) {
776 ystr("separator_symbol");
777 ystr(config->separator_symbol);
780 ystr("workspace_buttons");
781 y(bool, !config->hide_workspace_buttons);
783 ystr("strip_workspace_numbers");
784 y(bool, config->strip_workspace_numbers);
786 ystr("strip_workspace_name");
787 y(bool, config->strip_workspace_name);
789 ystr("binding_mode_indicator");
790 y(bool, !config->hide_binding_mode_indicator);
793 y(bool, config->verbose);
796 #define YSTR_IF_SET(name) \
798 if (config->colors.name) { \
800 ystr(config->colors.name); \
806 YSTR_IF_SET(background);
807 YSTR_IF_SET(statusline);
808 YSTR_IF_SET(separator);
809 YSTR_IF_SET(focused_background);
810 YSTR_IF_SET(focused_statusline);
811 YSTR_IF_SET(focused_separator);
812 YSTR_IF_SET(focused_workspace_border);
813 YSTR_IF_SET(focused_workspace_bg);
814 YSTR_IF_SET(focused_workspace_text);
815 YSTR_IF_SET(active_workspace_border);
816 YSTR_IF_SET(active_workspace_bg);
817 YSTR_IF_SET(active_workspace_text);
818 YSTR_IF_SET(inactive_workspace_border);
819 YSTR_IF_SET(inactive_workspace_bg);
820 YSTR_IF_SET(inactive_workspace_text);
821 YSTR_IF_SET(urgent_workspace_border);
822 YSTR_IF_SET(urgent_workspace_bg);
823 YSTR_IF_SET(urgent_workspace_text);
824 YSTR_IF_SET(binding_mode_border);
825 YSTR_IF_SET(binding_mode_bg);
826 YSTR_IF_SET(binding_mode_text);
834 setlocale(LC_NUMERIC, "C");
835 yajl_gen gen = ygenalloc();
836 dump_node(gen, croot, false);
837 setlocale(LC_NUMERIC, "");
839 const unsigned char *payload;
841 y(get_buf, &payload, &length);
843 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_TREE, payload);
848 * Formats the reply message for a GET_WORKSPACES request and sends it to the
852 IPC_HANDLER(get_workspaces) {
853 yajl_gen gen = ygenalloc();
856 Con *focused_ws = con_get_workspace(focused);
859 TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
860 if (con_is_internal(output))
863 TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
864 assert(ws->type == CT_WORKSPACE);
874 y(bool, workspace_is_visible(ws));
877 y(bool, ws == focused_ws);
882 y(integer, ws->rect.x);
884 y(integer, ws->rect.y);
886 y(integer, ws->rect.width);
888 y(integer, ws->rect.height);
903 const unsigned char *payload;
905 y(get_buf, &payload, &length);
907 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
912 * Formats the reply message for a GET_OUTPUTS request and sends it to the
916 IPC_HANDLER(get_outputs) {
917 yajl_gen gen = ygenalloc();
921 TAILQ_FOREACH(output, &outputs, outputs) {
925 ystr(output_primary_name(output));
928 y(bool, output->active);
931 y(bool, output->primary);
936 y(integer, output->rect.x);
938 y(integer, output->rect.y);
940 y(integer, output->rect.width);
942 y(integer, output->rect.height);
945 ystr("current_workspace");
947 if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
957 const unsigned char *payload;
959 y(get_buf, &payload, &length);
961 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
966 * Formats the reply message for a GET_MARKS request and sends it to the
970 IPC_HANDLER(get_marks) {
971 yajl_gen gen = ygenalloc();
975 TAILQ_FOREACH(con, &all_cons, all_cons) {
977 TAILQ_FOREACH(mark, &(con->marks_head), marks) {
984 const unsigned char *payload;
986 y(get_buf, &payload, &length);
988 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_MARKS, payload);
993 * Returns the version of i3
996 IPC_HANDLER(get_version) {
997 yajl_gen gen = ygenalloc();
1001 y(integer, MAJOR_VERSION);
1004 y(integer, MINOR_VERSION);
1007 y(integer, PATCH_VERSION);
1009 ystr("human_readable");
1012 ystr("loaded_config_file_name");
1013 ystr(current_configpath);
1017 const unsigned char *payload;
1019 y(get_buf, &payload, &length);
1021 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_VERSION, payload);
1026 * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
1030 IPC_HANDLER(get_bar_config) {
1031 yajl_gen gen = ygenalloc();
1033 /* If no ID was passed, we return a JSON array with all IDs */
1034 if (message_size == 0) {
1037 TAILQ_FOREACH(current, &barconfigs, configs) {
1042 const unsigned char *payload;
1044 y(get_buf, &payload, &length);
1046 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1051 /* To get a properly terminated buffer, we copy
1052 * message_size bytes out of the buffer */
1053 char *bar_id = NULL;
1054 sasprintf(&bar_id, "%.*s", message_size, message);
1055 LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
1056 Barconfig *current, *config = NULL;
1057 TAILQ_FOREACH(current, &barconfigs, configs) {
1058 if (strcmp(current->id, bar_id) != 0)
1067 /* If we did not find a config for the given ID, the reply will contain
1068 * a null 'id' field. */
1076 dump_bar_config(gen, config);
1079 const unsigned char *payload;
1081 y(get_buf, &payload, &length);
1083 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1088 * Returns a list of configured binding modes
1091 IPC_HANDLER(get_binding_modes) {
1092 yajl_gen gen = ygenalloc();
1096 SLIST_FOREACH(mode, &modes, modes) {
1101 const unsigned char *payload;
1103 y(get_buf, &payload, &length);
1105 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BINDING_MODES, payload);
1110 * Callback for the YAJL parser (will be called when a string is parsed).
1113 static int add_subscription(void *extra, const unsigned char *s,
1115 ipc_client *client = extra;
1117 DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
1118 int event = client->num_events;
1120 client->num_events++;
1121 client->events = srealloc(client->events, client->num_events * sizeof(char *));
1122 /* We copy the string because it is not null-terminated and strndup()
1123 * is missing on some BSD systems */
1124 client->events[event] = scalloc(len + 1, 1);
1125 memcpy(client->events[event], s, len);
1127 DLOG("client is now subscribed to:\n");
1128 for (int i = 0; i < client->num_events; i++) {
1129 DLOG("event %s\n", client->events[i]);
1137 * Subscribes this connection to the event types which were given as a JSON
1138 * serialized array in the payload field of the message.
1141 IPC_HANDLER(subscribe) {
1145 /* Setup the JSON parser */
1146 static yajl_callbacks callbacks = {
1147 .yajl_string = add_subscription,
1150 p = yalloc(&callbacks, (void *)client);
1151 stat = yajl_parse(p, (const unsigned char *)message, message_size);
1152 if (stat != yajl_status_ok) {
1154 err = yajl_get_error(p, true, (const unsigned char *)message,
1156 ELOG("YAJL parse error: %s\n", err);
1157 yajl_free_error(p, err);
1159 const char *reply = "{\"success\":false}";
1160 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1165 const char *reply = "{\"success\":true}";
1166 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1168 if (client->first_tick_sent) {
1172 bool is_tick = false;
1173 for (int i = 0; i < client->num_events; i++) {
1174 if (strcmp(client->events[i], "tick") == 0) {
1183 client->first_tick_sent = true;
1184 const char *payload = "{\"first\":true,\"payload\":\"\"}";
1185 ipc_send_client_message(client, strlen(payload), I3_IPC_EVENT_TICK, (const uint8_t *)payload);
1189 * Returns the raw last loaded i3 configuration file contents.
1191 IPC_HANDLER(get_config) {
1192 yajl_gen gen = ygenalloc();
1197 ystr(current_config);
1201 const unsigned char *payload;
1203 y(get_buf, &payload, &length);
1205 ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_CONFIG, payload);
1210 * Sends the tick event from the message payload to subscribers. Establishes a
1211 * synchronization point in event-related tests.
1213 IPC_HANDLER(send_tick) {
1214 yajl_gen gen = ygenalloc();
1222 yajl_gen_string(gen, (unsigned char *)message, message_size);
1226 const unsigned char *payload;
1228 y(get_buf, &payload, &length);
1230 ipc_send_event("tick", I3_IPC_EVENT_TICK, (const char *)payload);
1233 const char *reply = "{\"success\":true}";
1234 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_TICK, (const uint8_t *)reply);
1235 DLOG("Sent tick event\n");
1241 xcb_window_t window;
1244 static int _sync_json_key(void *extra, const unsigned char *val, size_t len) {
1245 struct sync_state *state = extra;
1246 FREE(state->last_key);
1247 state->last_key = scalloc(len + 1, 1);
1248 memcpy(state->last_key, val, len);
1252 static int _sync_json_int(void *extra, long long val) {
1253 struct sync_state *state = extra;
1254 if (strcasecmp(state->last_key, "rnd") == 0) {
1256 } else if (strcasecmp(state->last_key, "window") == 0) {
1257 state->window = (xcb_window_t)val;
1266 /* Setup the JSON parser */
1267 static yajl_callbacks callbacks = {
1268 .yajl_map_key = _sync_json_key,
1269 .yajl_integer = _sync_json_int,
1272 struct sync_state state;
1273 memset(&state, '\0', sizeof(struct sync_state));
1274 p = yalloc(&callbacks, (void *)&state);
1275 stat = yajl_parse(p, (const unsigned char *)message, message_size);
1276 FREE(state.last_key);
1277 if (stat != yajl_status_ok) {
1279 err = yajl_get_error(p, true, (const unsigned char *)message,
1281 ELOG("YAJL parse error: %s\n", err);
1282 yajl_free_error(p, err);
1284 const char *reply = "{\"success\":false}";
1285 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1291 DLOG("received IPC sync request (rnd = %d, window = 0x%08x)\n", state.rnd, state.window);
1292 sync_respond(state.window, state.rnd);
1293 const char *reply = "{\"success\":true}";
1294 ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1297 /* The index of each callback function corresponds to the numeric
1298 * value of the message type (see include/i3/ipc.h) */
1299 handler_t handlers[12] = {
1301 handle_get_workspaces,
1306 handle_get_bar_config,
1308 handle_get_binding_modes,
1315 * Handler for activity on a client connection, receives a message from a
1318 * For now, the maximum message size is 2048. I’m not sure for what the
1319 * IPC interface will be used in the future, thus I’m not implementing a
1320 * mechanism for arbitrarily long messages, as it seems like overkill
1324 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
1325 uint32_t message_type;
1326 uint32_t message_length;
1327 uint8_t *message = NULL;
1328 ipc_client *client = (ipc_client *)w->data;
1329 assert(client->fd == w->fd);
1331 int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
1332 /* EOF or other error */
1334 /* Was this a spurious read? See ev(3) */
1335 if (ret == -1 && errno == EAGAIN) {
1340 /* If not, there was some kind of error. We don’t bother and close the
1341 * connection. Delete the client from the list of clients. */
1342 free_ipc_client(client);
1347 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1348 DLOG("Unhandled message type: %d\n", message_type);
1350 handler_t h = handlers[message_type];
1351 h(client, message, 0, message_length, message_type);
1357 static void ipc_client_timeout(EV_P_ ev_timer *w, int revents) {
1358 /* No need to be polite and check for writeability, the other callback would
1359 * have been called by now. */
1360 ipc_client *client = (ipc_client *)w->data;
1362 char *cmdline = NULL;
1363 #if defined(__linux__) && defined(SO_PEERCRED)
1364 struct ucred peercred;
1365 socklen_t so_len = sizeof(peercred);
1366 if (getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0) {
1370 sasprintf(&exepath, "/proc/%d/cmdline", peercred.pid);
1372 int fd = open(exepath, O_RDONLY);
1377 char buf[512] = {'\0'}; /* cut off cmdline for the error message. */
1378 const ssize_t n = read(fd, buf, sizeof(buf));
1383 for (char *walk = buf; walk < buf + n - 1; walk++) {
1384 if (*walk == '\0') {
1391 ELOG("client %p with pid %d and cmdline '%s' on fd %d timed out, killing\n", client, peercred.pid, cmdline, client->fd);
1397 ELOG("client %p on fd %d timed out, killing\n", client, client->fd);
1400 free_ipc_client(client);
1403 static void ipc_socket_writeable_cb(EV_P_ ev_io *w, int revents) {
1404 DLOG("fd %d writeable\n", w->fd);
1405 ipc_client *client = (ipc_client *)w->data;
1407 /* If this callback is called then there should be a corresponding active
1409 assert(client->timeout != NULL);
1410 ipc_push_pending(client);
1414 * Handler for activity on the listening socket, meaning that a new client
1415 * has just connected and we should accept() him. Sets up the event handler
1416 * for activity on the new connection and inserts the file descriptor into
1417 * the list of clients.
1420 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1421 struct sockaddr_un peer;
1422 socklen_t len = sizeof(struct sockaddr_un);
1424 if ((fd = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1425 if (errno != EINTR) {
1431 /* Close this file descriptor on exec() */
1432 (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
1436 ipc_client *client = scalloc(1, sizeof(ipc_client));
1439 client->read_callback = scalloc(1, sizeof(struct ev_io));
1440 client->read_callback->data = client;
1441 ev_io_init(client->read_callback, ipc_receive_message, fd, EV_READ);
1442 ev_io_start(EV_A_ client->read_callback);
1444 client->write_callback = scalloc(1, sizeof(struct ev_io));
1445 client->write_callback->data = client;
1446 ev_io_init(client->write_callback, ipc_socket_writeable_cb, fd, EV_WRITE);
1448 DLOG("IPC: new client connected on fd %d\n", w->fd);
1449 TAILQ_INSERT_TAIL(&all_clients, client, clients);
1453 * Creates the UNIX domain socket at the given path, sets it to non-blocking
1454 * mode, bind()s and listen()s on it.
1457 int ipc_create_socket(const char *filename) {
1460 FREE(current_socketpath);
1462 char *resolved = resolve_tilde(filename);
1463 DLOG("Creating IPC-socket at %s\n", resolved);
1464 char *copy = sstrdup(resolved);
1465 const char *dir = dirname(copy);
1466 if (!path_exists(dir))
1467 mkdirp(dir, DEFAULT_DIR_MODE);
1470 /* Unlink the unix domain socket before */
1473 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1479 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1481 struct sockaddr_un addr;
1482 memset(&addr, 0, sizeof(struct sockaddr_un));
1483 addr.sun_family = AF_LOCAL;
1484 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1485 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1491 set_nonblock(sockfd);
1493 if (listen(sockfd, 5) < 0) {
1499 current_socketpath = resolved;
1504 * Generates a json workspace event. Returns a dynamically allocated yajl
1505 * generator. Free with yajl_gen_free().
1507 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1508 setlocale(LC_NUMERIC, "C");
1509 yajl_gen gen = ygenalloc();
1517 if (current == NULL)
1520 dump_node(gen, current, false);
1526 dump_node(gen, old, false);
1530 setlocale(LC_NUMERIC, "");
1536 * For the workspace events we send, along with the usual "change" field, also
1537 * the workspace container in "current". For focus events, we send the
1538 * previously focused workspace in "old".
1540 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1541 yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1543 const unsigned char *payload;
1545 y(get_buf, &payload, &length);
1547 ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1553 * For the window events we send, along the usual "change" field,
1554 * also the window container, in "container".
1556 void ipc_send_window_event(const char *property, Con *con) {
1557 DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1558 property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1560 setlocale(LC_NUMERIC, "C");
1561 yajl_gen gen = ygenalloc();
1569 dump_node(gen, con, false);
1573 const unsigned char *payload;
1575 y(get_buf, &payload, &length);
1577 ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1579 setlocale(LC_NUMERIC, "");
1583 * For the barconfig update events, we send the serialized barconfig.
1585 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1586 DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1587 setlocale(LC_NUMERIC, "C");
1588 yajl_gen gen = ygenalloc();
1590 dump_bar_config(gen, barconfig);
1592 const unsigned char *payload;
1594 y(get_buf, &payload, &length);
1596 ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1598 setlocale(LC_NUMERIC, "");
1602 * For the binding events, we send the serialized binding struct.
1604 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1605 DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1607 setlocale(LC_NUMERIC, "C");
1609 yajl_gen gen = ygenalloc();
1617 dump_binding(gen, bind);
1621 const unsigned char *payload;
1623 y(get_buf, &payload, &length);
1625 ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1628 setlocale(LC_NUMERIC, "");