4 * i3 - an improved dynamic tiling window manager
6 * © 2009-2011 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>
29 #include <yajl/yajl_version.h>
41 /* Shorter names for all those yajl_gen_* functions */
42 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
43 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
45 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
48 * Puts the given socket file descriptor into non-blocking mode or dies if
49 * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
50 * IPC model because we should by no means block the window manager.
53 static void set_nonblock(int sockfd) {
54 int flags = fcntl(sockfd, F_GETFL, 0);
56 if (fcntl(sockfd, F_SETFL, flags) < 0)
57 err(-1, "Could not set O_NONBLOCK");
61 * Emulates mkdir -p (creates any missing folders)
64 static bool mkdirp(const char *path) {
65 if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
67 if (errno != ENOENT) {
68 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
71 char *copy = strdup(path);
72 /* strip trailing slashes, if any */
73 while (copy[strlen(copy)-1] == '/')
74 copy[strlen(copy)-1] = '\0';
76 char *sep = strrchr(copy, '/');
82 result = mkdirp(path);
88 static void ipc_send_message(int fd, const unsigned char *payload,
89 int message_type, int message_size) {
90 int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
91 sizeof(uint32_t) + message_size;
92 char msg[buffer_size];
95 strcpy(walk, "i3-ipc");
96 walk += strlen("i3-ipc");
97 memcpy(walk, &message_size, sizeof(uint32_t));
98 walk += sizeof(uint32_t);
99 memcpy(walk, &message_type, sizeof(uint32_t));
100 walk += sizeof(uint32_t);
101 memcpy(walk, payload, message_size);
104 int bytes_to_go = buffer_size;
105 while (sent_bytes < bytes_to_go) {
106 int n = write(fd, msg + sent_bytes, bytes_to_go);
108 DLOG("write() failed: %s\n", strerror(errno));
118 * Sends the specified event to all IPC clients which are currently connected
119 * and subscribed to this kind of event.
122 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
124 TAILQ_FOREACH(current, &all_clients, clients) {
125 /* see if this client is interested in this event */
126 bool interested = false;
127 for (int i = 0; i < current->num_events; i++) {
128 if (strcasecmp(current->events[i], event) != 0)
136 ipc_send_message(current->fd, (const unsigned char*)payload,
137 message_type, strlen(payload));
142 * Calls shutdown() on each socket and closes it. This function to be called
143 * when exiting or restarting only!
146 void ipc_shutdown() {
148 TAILQ_FOREACH(current, &all_clients, clients) {
149 shutdown(current->fd, SHUT_RDWR);
155 * Executes the command and returns whether it could be successfully parsed
156 * or not (at the moment, always returns true).
159 IPC_HANDLER(command) {
160 /* To get a properly terminated buffer, we copy
161 * message_size bytes out of the buffer */
162 char *command = scalloc(message_size);
163 strncpy(command, (const char*)message, message_size);
164 parse_command(global_conn, (const char*)command);
167 /* For now, every command gets a positive acknowledge
168 * (will change with the new command parser) */
169 const char *reply = "{\"success\":true}";
170 ipc_send_message(fd, (const unsigned char*)reply,
171 I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
175 * Formats the reply message for a GET_WORKSPACES request and sends it to the
179 IPC_HANDLER(get_workspaces) {
182 Client *last_focused = SLIST_FIRST(&(c_ws->focus_stack));
183 if (last_focused == SLIST_END(&(c_ws->focus_stack)))
187 yajl_gen gen = yajl_gen_alloc(NULL);
189 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
193 TAILQ_FOREACH(ws, workspaces, workspaces) {
194 if (ws->output == NULL)
199 y(integer, ws->num + 1);
205 y(bool, ws->output->current_workspace == ws);
213 y(integer, ws->rect.x);
215 y(integer, ws->rect.y);
217 y(integer, ws->rect.width);
219 y(integer, ws->rect.height);
223 ystr(ws->output->name);
233 const unsigned char *payload;
239 y(get_buf, &payload, &length);
241 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
246 * Formats the reply message for a GET_OUTPUTS request and sends it to the
250 IPC_HANDLER(get_outputs) {
254 yajl_gen gen = yajl_gen_alloc(NULL);
256 yajl_gen gen = yajl_gen_alloc(NULL, NULL);
260 TAILQ_FOREACH(output, &outputs, outputs) {
267 y(bool, output->active);
272 y(integer, output->rect.x);
274 y(integer, output->rect.y);
276 y(integer, output->rect.width);
278 y(integer, output->rect.height);
281 ystr("current_workspace");
282 if (output->current_workspace == NULL)
284 else y(integer, output->current_workspace->num + 1);
291 const unsigned char *payload;
297 y(get_buf, &payload, &length);
299 ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
304 * Callback for the YAJL parser (will be called when a string is parsed).
308 static int add_subscription(void *extra, const unsigned char *s,
311 static int add_subscription(void *extra, const unsigned char *s,
314 ipc_client *client = extra;
316 DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
317 int event = client->num_events;
319 client->num_events++;
320 client->events = realloc(client->events, client->num_events * sizeof(char*));
321 /* We copy the string because it is not null-terminated and strndup()
322 * is missing on some BSD systems */
323 client->events[event] = scalloc(len+1);
324 memcpy(client->events[event], s, len);
326 DLOG("client is now subscribed to:\n");
327 for (int i = 0; i < client->num_events; i++)
328 DLOG("event %s\n", client->events[i]);
335 * Subscribes this connection to the event types which were given as a JSON
336 * serialized array in the payload field of the message.
339 IPC_HANDLER(subscribe) {
341 yajl_callbacks callbacks;
343 ipc_client *current, *client = NULL;
345 /* Search the ipc_client structure for this connection */
346 TAILQ_FOREACH(current, &all_clients, clients) {
347 if (current->fd != fd)
354 if (client == NULL) {
355 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
359 /* Setup the JSON parser */
360 memset(&callbacks, 0, sizeof(yajl_callbacks));
361 callbacks.yajl_string = add_subscription;
364 p = yajl_alloc(&callbacks, NULL, (void*)client);
366 p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
368 stat = yajl_parse(p, (const unsigned char*)message, message_size);
369 if (stat != yajl_status_ok) {
371 err = yajl_get_error(p, true, (const unsigned char*)message,
373 ELOG("YAJL parse error: %s\n", err);
374 yajl_free_error(p, err);
376 const char *reply = "{\"success\":false}";
377 ipc_send_message(fd, (const unsigned char*)reply,
378 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
383 const char *reply = "{\"success\":true}";
384 ipc_send_message(fd, (const unsigned char*)reply,
385 I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
388 /* The index of each callback function corresponds to the numeric
389 * value of the message type (see include/i3/ipc.h) */
390 handler_t handlers[4] = {
392 handle_get_workspaces,
398 * Handler for activity on a client connection, receives a message from a
401 * For now, the maximum message size is 2048. I’m not sure for what the
402 * IPC interface will be used in the future, thus I’m not implementing a
403 * mechanism for arbitrarily long messages, as it seems like overkill
407 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
409 int n = read(w->fd, buf, sizeof(buf));
411 /* On error or an empty message, we close the connection */
414 /* FIXME: I get these when closing a client socket,
415 * therefore we just treat them as an error. Is this
417 if (errno == EAGAIN || errno == EWOULDBLOCK)
421 /* If not, there was some kind of error. We don’t bother
422 * and close the connection */
425 /* Delete the client from the list of clients */
427 TAILQ_FOREACH(current, &all_clients, clients) {
428 if (current->fd != w->fd)
431 for (int i = 0; i < current->num_events; i++)
432 free(current->events[i]);
433 /* We can call TAILQ_REMOVE because we break out of the
434 * TAILQ_FOREACH afterwards */
435 TAILQ_REMOVE(&all_clients, current, clients);
441 DLOG("IPC: client disconnected\n");
445 /* Terminate the message correctly */
448 /* Check if the message starts with the i3 IPC magic code */
449 if (n < strlen(I3_IPC_MAGIC)) {
450 DLOG("IPC: message too short, ignoring\n");
454 if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
455 DLOG("IPC: message does not start with the IPC magic\n");
459 uint8_t *message = (uint8_t*)buf;
461 DLOG("IPC: n = %d\n", n);
462 message += strlen(I3_IPC_MAGIC);
463 n -= strlen(I3_IPC_MAGIC);
465 /* The next 32 bit after the magic are the message size */
466 uint32_t message_size = *((uint32_t*)message);
467 message += sizeof(uint32_t);
468 n -= sizeof(uint32_t);
470 if (message_size > n) {
471 DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
475 /* The last 32 bits of the header are the message type */
476 uint32_t message_type = *((uint32_t*)message);
477 message += sizeof(uint32_t);
478 n -= sizeof(uint32_t);
480 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
481 DLOG("Unhandled message type: %d\n", message_type);
483 handler_t h = handlers[message_type];
484 h(w->fd, message, n, message_size, message_type);
487 message += message_size;
492 * Handler for activity on the listening socket, meaning that a new client
493 * has just connected and we should accept() him. Sets up the event handler
494 * for activity on the new connection and inserts the file descriptor into
495 * the list of clients.
498 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
499 struct sockaddr_un peer;
500 socklen_t len = sizeof(struct sockaddr_un);
502 if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
505 else perror("accept()");
509 set_nonblock(client);
511 struct ev_io *package = scalloc(sizeof(struct ev_io));
512 ev_io_init(package, ipc_receive_message, client, EV_READ);
513 ev_io_start(EV_A_ package);
515 DLOG("IPC: new client connected\n");
517 ipc_client *new = scalloc(sizeof(ipc_client));
520 TAILQ_INSERT_TAIL(&all_clients, new, clients);
524 * Creates the UNIX domain socket at the given path, sets it to non-blocking
525 * mode, bind()s and listen()s on it.
528 int ipc_create_socket(const char *filename) {
531 char *globbed = glob_path(filename);
532 DLOG("Creating IPC-socket at %s\n", globbed);
533 char *copy = sstrdup(globbed);
534 const char *dir = dirname(copy);
535 if (!path_exists(dir))
539 /* Unlink the unix domain socket before */
542 if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
548 (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
550 struct sockaddr_un addr;
551 memset(&addr, 0, sizeof(struct sockaddr_un));
552 addr.sun_family = AF_LOCAL;
553 strcpy(addr.sun_path, globbed);
554 if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
561 set_nonblock(sockfd);
563 if (listen(sockfd, 5) < 0) {