4 * i3 - an improved dynamic tiling window manager
6 * © 2009-2010 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/types.h>
14 #include <sys/socket.h>
25 #include <yajl/yajl_gen.h>
26 #include <yajl/yajl_parse.h>
37 /* Shorter names for all those yajl_gen_* functions */
38 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
39 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
41 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
44 * Puts the given socket file descriptor into non-blocking mode or dies if
45 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
46 * IPC model because we should by no means block the window manager.
49 static void set_nonblock(int sockfd) {
50 int flags = fcntl(sockfd, F_GETFL, 0);
52 if (fcntl(sockfd, F_SETFL, flags) < 0)
53 err(-1, "Could not set O_NONBLOCK");
56 static void ipc_send_message(int fd, const unsigned char *payload,
57 int message_type, int message_size) {
58 int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
59 sizeof(uint32_t) + message_size;
60 char msg[buffer_size];
63 strcpy(walk, "i3-ipc");
64 walk += strlen("i3-ipc");
65 memcpy(walk, &message_size, sizeof(uint32_t));
66 walk += sizeof(uint32_t);
67 memcpy(walk, &message_type, sizeof(uint32_t));
68 walk += sizeof(uint32_t);
69 memcpy(walk, payload, message_size);
72 int bytes_to_go = buffer_size;
73 while (sent_bytes < bytes_to_go) {
74 int n = write(fd, msg + sent_bytes, bytes_to_go);
76 DLOG("write() failed: %s\n", strerror(errno));
86 * Sends the specified event to all IPC clients which are currently connected
87 * and subscribed to this kind of event.
90 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
92 TAILQ_FOREACH(current, &all_clients, clients) {
93 /* see if this client is interested in this event */
94 bool interested = false;
95 for (int i = 0; i < current->num_events; i++) {
96 if (strcasecmp(current->events[i], event) != 0)
104 ipc_send_message(current->fd, (const unsigned char*)payload,
105 message_type, strlen(payload));
110 * Calls shutdown() on each socket and closes it. This function to be called
111 * when exiting or restarting only!
114 void ipc_shutdown() {
116 TAILQ_FOREACH(current, &all_clients, clients) {
117 shutdown(current->fd, SHUT_RDWR);
123 * Executes the command and returns whether it could be successfully parsed
124 * or not (at the moment, always returns true).
127 IPC_HANDLER(command) {
128 /* To get a properly terminated buffer, we copy
129 * message_size bytes out of the buffer */
130 char *command = scalloc(message_size);
131 strncpy(command, (const char*)message, message_size);
132 parse_command(global_conn, (const char*)command);
135 /* For now, every command gets a positive acknowledge
136 * (will change with the new command parser) */
137 const char *reply = "{\"success\":true}";
138 ipc_send_message(fd, (const unsigned char*)reply,
139 I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
143 * Formats the reply message for a GET_WORKSPACES request and sends it to the
147 IPC_HANDLER(get_workspaces) {
150 Client *last_focused = SLIST_FIRST(&(c_ws->focus_stack));
151 if (last_focused == SLIST_END(&(c_ws->focus_stack)))
154 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
157 TAILQ_FOREACH(ws, workspaces, workspaces) {
158 if (ws->output == NULL)
163 y(integer, ws->num + 1);
169 y(bool, ws->output->current_workspace == ws);
177 y(integer, ws->rect.x);
179 y(integer, ws->rect.y);
181 y(integer, ws->rect.width);
183 y(integer, ws->rect.height);
187 ystr(ws->output->name);
197 const unsigned char *payload;
199 y(get_buf, &payload, &length);
201 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
206 * Formats the reply message for a GET_OUTPUTS request and sends it to the
210 IPC_HANDLER(get_outputs) {
213 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
216 TAILQ_FOREACH(output, &outputs, outputs) {
223 y(bool, output->active);
228 y(integer, output->rect.x);
230 y(integer, output->rect.y);
232 y(integer, output->rect.width);
234 y(integer, output->rect.height);
237 ystr("current_workspace");
238 if (output->current_workspace == NULL)
240 else y(integer, output->current_workspace->num + 1);
247 const unsigned char *payload;
249 y(get_buf, &payload, &length);
251 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
256 * Callback for the YAJL parser (will be called when a string is parsed).
259 static int add_subscription(void *extra, const unsigned char *s,
261 ipc_client *client = extra;
263 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
264 int event = client->num_events;
266 client->num_events++;
267 client->events = realloc(client->events, client->num_events * sizeof(char*));
268 /* We copy the string because it is not null-terminated and strndup()
269 * is missing on some BSD systems */
270 client->events[event] = scalloc(len+1);
271 memcpy(client->events[event], s, len);
273 DLOG("client is now subscribed to:\n");
274 for (int i = 0; i < client->num_events; i++)
275 DLOG("event %s\n", client->events[i]);
282 * Subscribes this connection to the event types which were given as a JSON
283 * serialized array in the payload field of the message.
286 IPC_HANDLER(subscribe) {
288 yajl_callbacks callbacks;
290 ipc_client *current, *client = NULL;
292 /* Search the ipc_client structure for this connection */
293 TAILQ_FOREACH(current, &all_clients, clients) {
294 if (current->fd != fd)
301 if (client == NULL) {
302 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
306 /* Setup the JSON parser */
307 memset(&callbacks, 0, sizeof(yajl_callbacks));
308 callbacks.yajl_string = add_subscription;
310 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
311 stat = yajl_parse(p, (const unsigned char*)message, message_size);
312 if (stat != yajl_status_ok) {
314 err = yajl_get_error(p, true, (const unsigned char*)message,
316 ELOG("YAJL parse error: %s\n", err);
317 yajl_free_error(p, err);
319 const char *reply = "{\"success\":false}";
320 ipc_send_message(fd, (const unsigned char*)reply,
321 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
326 const char *reply = "{\"success\":true}";
327 ipc_send_message(fd, (const unsigned char*)reply,
328 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
331 /* The index of each callback function corresponds to the numeric
332 * value of the message type (see include/i3/ipc.h) */
333 handler_t handlers[4] = {
335 handle_get_workspaces,
341 * Handler for activity on a client connection, receives a message from a
344 * For now, the maximum message size is 2048. I’m not sure for what the
345 * IPC interface will be used in the future, thus I’m not implementing a
346 * mechanism for arbitrarily long messages, as it seems like overkill
350 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
352 int n = read(w->fd, buf, sizeof(buf));
354 /* On error or an empty message, we close the connection */
357 /* FIXME: I get these when closing a client socket,
358 * therefore we just treat them as an error. Is this
360 if (errno == EAGAIN || errno == EWOULDBLOCK)
364 /* If not, there was some kind of error. We don’t bother
365 * and close the connection */
368 /* Delete the client from the list of clients */
370 TAILQ_FOREACH(current, &all_clients, clients) {
371 if (current->fd != w->fd)
374 for (int i = 0; i < current->num_events; i++)
375 free(current->events[i]);
376 /* We can call TAILQ_REMOVE because we break out of the
377 * TAILQ_FOREACH afterwards */
378 TAILQ_REMOVE(&all_clients, current, clients);
384 DLOG("IPC: client disconnected\n");
388 /* Terminate the message correctly */
391 /* Check if the message starts with the i3 IPC magic code */
392 if (n < strlen(I3_IPC_MAGIC)) {
393 DLOG("IPC: message too short, ignoring\n");
397 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
398 DLOG("IPC: message does not start with the IPC magic\n");
402 uint8_t *message = (uint8_t*)buf;
404 DLOG("IPC: n = %d\n", n);
405 message += strlen(I3_IPC_MAGIC);
406 n -= strlen(I3_IPC_MAGIC);
408 /* The next 32 bit after the magic are the message size */
409 uint32_t message_size = *((uint32_t*)message);
410 message += sizeof(uint32_t);
411 n -= sizeof(uint32_t);
413 if (message_size > n) {
414 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
418 /* The last 32 bits of the header are the message type */
419 uint32_t message_type = *((uint32_t*)message);
420 message += sizeof(uint32_t);
421 n -= sizeof(uint32_t);
423 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
424 DLOG("Unhandled message type: %d\n", message_type);
426 handler_t h = handlers[message_type];
427 h(w->fd, message, n, message_size, message_type);
430 message += message_size;
435 * Handler for activity on the listening socket, meaning that a new client
436 * has just connected and we should accept() him. Sets up the event handler
437 * for activity on the new connection and inserts the file descriptor into
438 * the list of clients.
441 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
442 struct sockaddr_un peer;
443 socklen_t len = sizeof(struct sockaddr_un);
445 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
448 else perror("accept()");
452 set_nonblock(client);
454 struct ev_io *package = scalloc(sizeof(struct ev_io));
455 ev_io_init(package, ipc_receive_message, client, EV_READ);
456 ev_io_start(EV_A_ package);
458 DLOG("IPC: new client connected\n");
460 ipc_client *new = scalloc(sizeof(ipc_client));
463 TAILQ_INSERT_TAIL(&all_clients, new, clients);
467 * Creates the UNIX domain socket at the given path, sets it to non-blocking
468 * mode, bind()s and listen()s on it.
471 int ipc_create_socket(const char *filename) {
474 /* Unlink the unix domain socket before */
477 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
482 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
484 struct sockaddr_un addr;
485 memset(&addr, 0, sizeof(struct sockaddr_un));
486 addr.sun_family = AF_LOCAL;
487 strcpy(addr.sun_path, filename);
488 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
493 set_nonblock(sockfd);
495 if (listen(sockfd, 5) < 0) {