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>
27 #include <yajl/yajl_gen.h>
28 #include <yajl/yajl_parse.h>
40 /* Shorter names for all those yajl_gen_* functions */
41 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
42 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
44 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
47 * Puts the given socket file descriptor into non-blocking mode or dies if
48 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
49 * IPC model because we should by no means block the window manager.
52 static void set_nonblock(int sockfd) {
53 int flags = fcntl(sockfd, F_GETFL, 0);
55 if (fcntl(sockfd, F_SETFL, flags) < 0)
56 err(-1, "Could not set O_NONBLOCK");
60 * Emulates mkdir -p (creates any missing folders)
63 static bool mkdirp(const char *path) {
64 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
66 if (errno != ENOENT) {
67 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
70 char *copy = strdup(path);
71 /* strip trailing slashes, if any */
72 while (copy[strlen(copy)-1] == '/')
73 copy[strlen(copy)-1] = '\0';
75 char *sep = strrchr(copy, '/');
81 result = mkdirp(path);
87 static void ipc_send_message(int fd, const unsigned char *payload,
88 int message_type, int message_size) {
89 int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
90 sizeof(uint32_t) + message_size;
91 char msg[buffer_size];
94 strncpy(walk, "i3-ipc", buffer_size - 1);
95 walk += strlen("i3-ipc");
96 memcpy(walk, &message_size, sizeof(uint32_t));
97 walk += sizeof(uint32_t);
98 memcpy(walk, &message_type, sizeof(uint32_t));
99 walk += sizeof(uint32_t);
100 memcpy(walk, payload, message_size);
103 int bytes_to_go = buffer_size;
104 while (sent_bytes < bytes_to_go) {
105 int n = write(fd, msg + sent_bytes, bytes_to_go);
107 DLOG("write() failed: %s\n", strerror(errno));
117 * Sends the specified event to all IPC clients which are currently connected
118 * and subscribed to this kind of event.
121 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
123 TAILQ_FOREACH(current, &all_clients, clients) {
124 /* see if this client is interested in this event */
125 bool interested = false;
126 for (int i = 0; i < current->num_events; i++) {
127 if (strcasecmp(current->events[i], event) != 0)
135 ipc_send_message(current->fd, (const unsigned char*)payload,
136 message_type, strlen(payload));
141 * Calls shutdown() on each socket and closes it. This function to be called
142 * when exiting or restarting only!
145 void ipc_shutdown() {
147 TAILQ_FOREACH(current, &all_clients, clients) {
148 shutdown(current->fd, SHUT_RDWR);
154 * Executes the command and returns whether it could be successfully parsed
155 * or not (at the moment, always returns true).
158 IPC_HANDLER(command) {
159 /* To get a properly terminated buffer, we copy
160 * message_size bytes out of the buffer */
161 char *command = scalloc(message_size);
162 strncpy(command, (const char*)message, message_size);
163 parse_command(global_conn, (const char*)command);
166 /* For now, every command gets a positive acknowledge
167 * (will change with the new command parser) */
168 const char *reply = "{\"success\":true}";
169 ipc_send_message(fd, (const unsigned char*)reply,
170 I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
174 * Formats the reply message for a GET_WORKSPACES request and sends it to the
178 IPC_HANDLER(get_workspaces) {
181 Client *last_focused = SLIST_FIRST(&(c_ws->focus_stack));
182 if (last_focused == SLIST_END(&(c_ws->focus_stack)))
185 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
188 TAILQ_FOREACH(ws, workspaces, workspaces) {
189 if (ws->output == NULL)
194 y(integer, ws->num + 1);
200 y(bool, ws->output->current_workspace == ws);
208 y(integer, ws->rect.x);
210 y(integer, ws->rect.y);
212 y(integer, ws->rect.width);
214 y(integer, ws->rect.height);
218 ystr(ws->output->name);
228 const unsigned char *payload;
230 y(get_buf, &payload, &length);
232 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
237 * Formats the reply message for a GET_OUTPUTS request and sends it to the
241 IPC_HANDLER(get_outputs) {
244 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
247 TAILQ_FOREACH(output, &outputs, outputs) {
254 y(bool, output->active);
259 y(integer, output->rect.x);
261 y(integer, output->rect.y);
263 y(integer, output->rect.width);
265 y(integer, output->rect.height);
268 ystr("current_workspace");
269 if (output->current_workspace == NULL)
271 else y(integer, output->current_workspace->num + 1);
278 const unsigned char *payload;
280 y(get_buf, &payload, &length);
282 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
287 * Callback for the YAJL parser (will be called when a string is parsed).
290 static int add_subscription(void *extra, const unsigned char *s,
292 ipc_client *client = extra;
294 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
295 int event = client->num_events;
297 client->num_events++;
298 client->events = realloc(client->events, client->num_events * sizeof(char*));
299 /* We copy the string because it is not null-terminated and strndup()
300 * is missing on some BSD systems */
301 client->events[event] = scalloc(len+1);
302 memcpy(client->events[event], s, len);
304 DLOG("client is now subscribed to:\n");
305 for (int i = 0; i < client->num_events; i++)
306 DLOG("event %s\n", client->events[i]);
313 * Subscribes this connection to the event types which were given as a JSON
314 * serialized array in the payload field of the message.
317 IPC_HANDLER(subscribe) {
319 yajl_callbacks callbacks;
321 ipc_client *current, *client = NULL;
323 /* Search the ipc_client structure for this connection */
324 TAILQ_FOREACH(current, &all_clients, clients) {
325 if (current->fd != fd)
332 if (client == NULL) {
333 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
337 /* Setup the JSON parser */
338 memset(&callbacks, 0, sizeof(yajl_callbacks));
339 callbacks.yajl_string = add_subscription;
341 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
342 stat = yajl_parse(p, (const unsigned char*)message, message_size);
343 if (stat != yajl_status_ok) {
345 err = yajl_get_error(p, true, (const unsigned char*)message,
347 ELOG("YAJL parse error: %s\n", err);
348 yajl_free_error(p, err);
350 const char *reply = "{\"success\":false}";
351 ipc_send_message(fd, (const unsigned char*)reply,
352 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
357 const char *reply = "{\"success\":true}";
358 ipc_send_message(fd, (const unsigned char*)reply,
359 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
362 /* The index of each callback function corresponds to the numeric
363 * value of the message type (see include/i3/ipc.h) */
364 handler_t handlers[4] = {
366 handle_get_workspaces,
372 * Handler for activity on a client connection, receives a message from a
375 * For now, the maximum message size is 2048. I’m not sure for what the
376 * IPC interface will be used in the future, thus I’m not implementing a
377 * mechanism for arbitrarily long messages, as it seems like overkill
381 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
383 int n = read(w->fd, buf, sizeof(buf));
385 /* On error or an empty message, we close the connection */
388 /* FIXME: I get these when closing a client socket,
389 * therefore we just treat them as an error. Is this
391 if (errno == EAGAIN || errno == EWOULDBLOCK)
395 /* If not, there was some kind of error. We don’t bother
396 * and close the connection */
399 /* Delete the client from the list of clients */
401 TAILQ_FOREACH(current, &all_clients, clients) {
402 if (current->fd != w->fd)
405 for (int i = 0; i < current->num_events; i++)
406 free(current->events[i]);
407 /* We can call TAILQ_REMOVE because we break out of the
408 * TAILQ_FOREACH afterwards */
409 TAILQ_REMOVE(&all_clients, current, clients);
415 DLOG("IPC: client disconnected\n");
419 /* Terminate the message correctly */
422 /* Check if the message starts with the i3 IPC magic code */
423 if (n < strlen(I3_IPC_MAGIC)) {
424 DLOG("IPC: message too short, ignoring\n");
428 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
429 DLOG("IPC: message does not start with the IPC magic\n");
433 uint8_t *message = (uint8_t*)buf;
435 DLOG("IPC: n = %d\n", n);
436 message += strlen(I3_IPC_MAGIC);
437 n -= strlen(I3_IPC_MAGIC);
439 /* The next 32 bit after the magic are the message size */
440 uint32_t message_size = *((uint32_t*)message);
441 message += sizeof(uint32_t);
442 n -= sizeof(uint32_t);
444 if (message_size > n) {
445 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
449 /* The last 32 bits of the header are the message type */
450 uint32_t message_type = *((uint32_t*)message);
451 message += sizeof(uint32_t);
452 n -= sizeof(uint32_t);
454 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
455 DLOG("Unhandled message type: %d\n", message_type);
457 handler_t h = handlers[message_type];
458 h(w->fd, message, n, message_size, message_type);
461 message += message_size;
466 * Handler for activity on the listening socket, meaning that a new client
467 * has just connected and we should accept() him. Sets up the event handler
468 * for activity on the new connection and inserts the file descriptor into
469 * the list of clients.
472 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
473 struct sockaddr_un peer;
474 socklen_t len = sizeof(struct sockaddr_un);
476 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
479 else perror("accept()");
483 set_nonblock(client);
485 struct ev_io *package = scalloc(sizeof(struct ev_io));
486 ev_io_init(package, ipc_receive_message, client, EV_READ);
487 ev_io_start(EV_A_ package);
489 DLOG("IPC: new client connected\n");
491 ipc_client *new = scalloc(sizeof(ipc_client));
494 TAILQ_INSERT_TAIL(&all_clients, new, clients);
498 * Creates the UNIX domain socket at the given path, sets it to non-blocking
499 * mode, bind()s and listen()s on it.
502 int ipc_create_socket(const char *filename) {
505 char *resolved = resolve_tilde(filename);
506 DLOG("Creating IPC-socket at %s\n", resolved);
507 char *copy = sstrdup(resolved);
508 const char *dir = dirname(copy);
509 if (!path_exists(dir))
513 /* Unlink the unix domain socket before */
516 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
522 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
524 struct sockaddr_un addr;
525 memset(&addr, 0, sizeof(struct sockaddr_un));
526 addr.sun_family = AF_LOCAL;
527 strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
528 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
535 set_nonblock(sockfd);
537 if (listen(sockfd, 5) < 0) {