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/socket.h>
17 #include <yajl/yajl_gen.h>
18 #include <yajl/yajl_parse.h>
22 /* Shorter names for all those yajl_gen_* functions */
23 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
24 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
26 TAILQ_HEAD(ipc_client_head, ipc_client) 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_send_message(int fd, const unsigned char *payload,
42 int message_type, int message_size) {
43 int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
44 sizeof(uint32_t) + message_size;
45 char msg[buffer_size];
48 strcpy(walk, "i3-ipc");
49 walk += strlen("i3-ipc");
50 memcpy(walk, &message_size, sizeof(uint32_t));
51 walk += sizeof(uint32_t);
52 memcpy(walk, &message_type, sizeof(uint32_t));
53 walk += sizeof(uint32_t);
54 memcpy(walk, payload, message_size);
57 int bytes_to_go = buffer_size;
58 while (sent_bytes < bytes_to_go) {
59 int n = write(fd, msg + sent_bytes, bytes_to_go);
61 DLOG("write() failed: %s\n", strerror(errno));
71 * Sends the specified event to all IPC clients which are currently connected
72 * and subscribed to this kind of event.
75 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
77 TAILQ_FOREACH(current, &all_clients, clients) {
78 /* see if this client is interested in this event */
79 bool interested = false;
80 for (int i = 0; i < current->num_events; i++) {
81 if (strcasecmp(current->events[i], event) != 0)
89 ipc_send_message(current->fd, (const unsigned char*)payload,
90 message_type, strlen(payload));
95 * Calls shutdown() on each socket and closes it. This function to be called
96 * when exiting or restarting only!
101 TAILQ_FOREACH(current, &all_clients, clients) {
102 shutdown(current->fd, SHUT_RDWR);
108 * Executes the command and returns whether it could be successfully parsed
109 * or not (at the moment, always returns true).
112 IPC_HANDLER(command) {
113 /* To get a properly terminated buffer, we copy
114 * message_size bytes out of the buffer */
115 char *command = scalloc(message_size + 1);
116 strncpy(command, (const char*)message, message_size);
117 LOG("IPC: received: *%s*\n", command);
118 const char *reply = parse_cmd((const char*)command);
122 /* If no reply was provided, we just use the default success message */
124 reply = "{\"success\":true}";
125 ipc_send_message(fd, (const unsigned char*)reply,
126 I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
129 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
132 y(integer, (long int)con);
135 y(integer, con->type);
138 y(integer, con->orientation);
141 y(integer, con->urgent);
144 y(integer, (con == focused));
147 y(integer, con->layout);
150 y(integer, con->border_style);
155 y(integer, con->rect.x);
157 y(integer, con->rect.y);
159 y(integer, con->rect.width);
161 y(integer, con->rect.height);
169 y(integer, con->window->id);
175 TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
176 dump_node(gen, node, inplace_restart);
180 ystr("floating-nodes");
182 TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
183 dump_node(gen, node, inplace_restart);
189 TAILQ_FOREACH(node, &(con->focus_head), nodes) {
190 y(integer, (long int)node);
194 ystr("fullscreen_mode");
195 y(integer, con->fullscreen_mode);
197 if (inplace_restart) {
198 if (con->window != NULL) {
203 y(integer, con->window->id);
214 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
215 dump_node(gen, croot, false);
217 const unsigned char *payload;
219 y(get_buf, &payload, &length);
221 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
228 * Formats the reply message for a GET_WORKSPACES request and sends it to the
232 IPC_HANDLER(get_workspaces) {
235 Client *last_focused = SLIST_FIRST(&(c_ws->focus_stack));
236 if (last_focused == SLIST_END(&(c_ws->focus_stack)))
239 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
242 TAILQ_FOREACH(ws, workspaces, workspaces) {
243 if (ws->output == NULL)
248 y(integer, ws->num + 1);
254 y(bool, ws->output->current_workspace == ws);
262 y(integer, ws->rect.x);
264 y(integer, ws->rect.y);
266 y(integer, ws->rect.width);
268 y(integer, ws->rect.height);
272 ystr(ws->output->name);
282 const unsigned char *payload;
284 y(get_buf, &payload, &length);
286 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
291 * Formats the reply message for a GET_OUTPUTS request and sends it to the
295 IPC_HANDLER(get_outputs) {
298 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
301 TAILQ_FOREACH(output, &outputs, outputs) {
308 y(bool, output->active);
313 y(integer, output->rect.x);
315 y(integer, output->rect.y);
317 y(integer, output->rect.width);
319 y(integer, output->rect.height);
322 ystr("current_workspace");
323 if (output->current_workspace == NULL)
325 else y(integer, output->current_workspace->num + 1);
332 const unsigned char *payload;
334 y(get_buf, &payload, &length);
336 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
341 * Callback for the YAJL parser (will be called when a string is parsed).
344 static int add_subscription(void *extra, const unsigned char *s,
346 ipc_client *client = extra;
348 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
349 int event = client->num_events;
351 client->num_events++;
352 client->events = realloc(client->events, client->num_events * sizeof(char*));
353 /* We copy the string because it is not null-terminated and strndup()
354 * is missing on some BSD systems */
355 client->events[event] = scalloc(len+1);
356 memcpy(client->events[event], s, len);
358 DLOG("client is now subscribed to:\n");
359 for (int i = 0; i < client->num_events; i++)
360 DLOG("event %s\n", client->events[i]);
367 * Subscribes this connection to the event types which were given as a JSON
368 * serialized array in the payload field of the message.
371 IPC_HANDLER(subscribe) {
373 yajl_callbacks callbacks;
375 ipc_client *current, *client = NULL;
377 /* Search the ipc_client structure for this connection */
378 TAILQ_FOREACH(current, &all_clients, clients) {
379 if (current->fd != fd)
386 if (client == NULL) {
387 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
391 /* Setup the JSON parser */
392 memset(&callbacks, 0, sizeof(yajl_callbacks));
393 callbacks.yajl_string = add_subscription;
395 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
396 stat = yajl_parse(p, (const unsigned char*)message, message_size);
397 if (stat != yajl_status_ok) {
399 err = yajl_get_error(p, true, (const unsigned char*)message,
401 ELOG("YAJL parse error: %s\n", err);
402 yajl_free_error(p, err);
404 const char *reply = "{\"success\":false}";
405 ipc_send_message(fd, (const unsigned char*)reply,
406 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
411 const char *reply = "{\"success\":true}";
412 ipc_send_message(fd, (const unsigned char*)reply,
413 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
417 /* The index of each callback function corresponds to the numeric
418 * value of the message type (see include/i3/ipc.h) */
419 handler_t handlers[2] = {
425 * Handler for activity on a client connection, receives a message from a
428 * For now, the maximum message size is 2048. I’m not sure for what the
429 * IPC interface will be used in the future, thus I’m not implementing a
430 * mechanism for arbitrarily long messages, as it seems like overkill
434 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
436 int n = read(w->fd, buf, sizeof(buf));
438 /* On error or an empty message, we close the connection */
441 /* FIXME: I get these when closing a client socket,
442 * therefore we just treat them as an error. Is this
444 if (errno == EAGAIN || errno == EWOULDBLOCK)
448 /* If not, there was some kind of error. We don’t bother
449 * and close the connection */
452 /* Delete the client from the list of clients */
454 TAILQ_FOREACH(current, &all_clients, clients) {
455 if (current->fd != w->fd)
458 for (int i = 0; i < current->num_events; i++)
459 free(current->events[i]);
460 /* We can call TAILQ_REMOVE because we break out of the
461 * TAILQ_FOREACH afterwards */
462 TAILQ_REMOVE(&all_clients, current, clients);
468 DLOG("IPC: client disconnected\n");
472 /* Terminate the message correctly */
475 /* Check if the message starts with the i3 IPC magic code */
476 if (n < strlen(I3_IPC_MAGIC)) {
477 DLOG("IPC: message too short, ignoring\n");
481 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
482 DLOG("IPC: message does not start with the IPC magic\n");
486 uint8_t *message = (uint8_t*)buf;
488 DLOG("IPC: n = %d\n", n);
489 message += strlen(I3_IPC_MAGIC);
490 n -= strlen(I3_IPC_MAGIC);
492 /* The next 32 bit after the magic are the message size */
493 uint32_t message_size = *((uint32_t*)message);
494 message += sizeof(uint32_t);
495 n -= sizeof(uint32_t);
497 if (message_size > n) {
498 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
502 /* The last 32 bits of the header are the message type */
503 uint32_t message_type = *((uint32_t*)message);
504 message += sizeof(uint32_t);
505 n -= sizeof(uint32_t);
507 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
508 DLOG("Unhandled message type: %d\n", message_type);
510 handler_t h = handlers[message_type];
511 h(w->fd, message, n, message_size, message_type);
514 message += message_size;
519 * Handler for activity on the listening socket, meaning that a new client
520 * has just connected and we should accept() him. Sets up the event handler
521 * for activity on the new connection and inserts the file descriptor into
522 * the list of clients.
525 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
526 struct sockaddr_un peer;
527 socklen_t len = sizeof(struct sockaddr_un);
529 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
532 else perror("accept()");
536 set_nonblock(client);
538 struct ev_io *package = scalloc(sizeof(struct ev_io));
539 ev_io_init(package, ipc_receive_message, client, EV_READ);
540 ev_io_start(EV_A_ package);
542 DLOG("IPC: new client connected\n");
544 ipc_client *new = scalloc(sizeof(ipc_client));
547 TAILQ_INSERT_TAIL(&all_clients, new, clients);
551 * Creates the UNIX domain socket at the given path, sets it to non-blocking
552 * mode, bind()s and listen()s on it.
555 int ipc_create_socket(const char *filename) {
558 /* Unlink the unix domain socket before */
561 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
566 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
568 struct sockaddr_un addr;
569 memset(&addr, 0, sizeof(struct sockaddr_un));
570 addr.sun_family = AF_LOCAL;
571 strcpy(addr.sun_path, filename);
572 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
577 set_nonblock(sockfd);
579 if (listen(sockfd, 5) < 0) {