]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
fd4f4fd8e1e6ab94e012b3f7e10593b4de7cfeec
[i3/i3] / src / ipc.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009-2010 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  * ipc.c: Everything about the UNIX domain sockets for IPC
11  *
12  */
13 #include <sys/socket.h>
14 #include <sys/un.h>
15 #include <fcntl.h>
16 #include <libgen.h>
17 #include <ev.h>
18 #include <yajl/yajl_gen.h>
19 #include <yajl/yajl_parse.h>
20
21 #include "all.h"
22
23 /* Shorter names for all those yajl_gen_* functions */
24 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
25 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
26
27 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
28
29 /*
30  * Puts the given socket file descriptor into non-blocking mode or dies if
31  * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
32  * IPC model because we should by no means block the window manager.
33  *
34  */
35 static void set_nonblock(int sockfd) {
36         int flags = fcntl(sockfd, F_GETFL, 0);
37         flags |= O_NONBLOCK;
38         if (fcntl(sockfd, F_SETFL, flags) < 0)
39                 err(-1, "Could not set O_NONBLOCK");
40 }
41
42 /*
43  * Emulates mkdir -p (creates any missing folders)
44  *
45  */
46 static bool mkdirp(const char *path) {
47         if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
48                 return true;
49         if (errno != ENOENT) {
50                 ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
51                 return false;
52         }
53         char *copy = strdup(path);
54         /* strip trailing slashes, if any */
55         while (copy[strlen(copy)-1] == '/')
56                 copy[strlen(copy)-1] = '\0';
57
58         char *sep = strrchr(copy, '/');
59         if (sep == NULL)
60                 return false;
61         *sep = '\0';
62         bool result = false;
63         if (mkdirp(copy))
64                 result = mkdirp(path);
65         free(copy);
66
67         return result;
68 }
69
70 static void ipc_send_message(int fd, const unsigned char *payload,
71                              int message_type, int message_size) {
72         int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
73                           sizeof(uint32_t) + message_size;
74         char msg[buffer_size];
75         char *walk = msg;
76
77         strcpy(walk, "i3-ipc");
78         walk += strlen("i3-ipc");
79         memcpy(walk, &message_size, sizeof(uint32_t));
80         walk += sizeof(uint32_t);
81         memcpy(walk, &message_type, sizeof(uint32_t));
82         walk += sizeof(uint32_t);
83         memcpy(walk, payload, message_size);
84
85         int sent_bytes = 0;
86         int bytes_to_go = buffer_size;
87         while (sent_bytes < bytes_to_go) {
88                 int n = write(fd, msg + sent_bytes, bytes_to_go);
89                 if (n == -1) {
90                         DLOG("write() failed: %s\n", strerror(errno));
91                         return;
92                 }
93
94                 sent_bytes += n;
95                 bytes_to_go -= n;
96         }
97 }
98
99 /*
100  * Sends the specified event to all IPC clients which are currently connected
101  * and subscribed to this kind of event.
102  *
103  */
104 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
105         ipc_client *current;
106         TAILQ_FOREACH(current, &all_clients, clients) {
107                 /* see if this client is interested in this event */
108                 bool interested = false;
109                 for (int i = 0; i < current->num_events; i++) {
110                         if (strcasecmp(current->events[i], event) != 0)
111                                 continue;
112                         interested = true;
113                         break;
114                 }
115                 if (!interested)
116                         continue;
117
118                 ipc_send_message(current->fd, (const unsigned char*)payload,
119                                  message_type, strlen(payload));
120         }
121 }
122
123 /*
124  * Calls shutdown() on each socket and closes it. This function to be called
125  * when exiting or restarting only!
126  *
127  */
128 void ipc_shutdown() {
129         ipc_client *current;
130         TAILQ_FOREACH(current, &all_clients, clients) {
131                 shutdown(current->fd, SHUT_RDWR);
132                 close(current->fd);
133         }
134 }
135
136 /*
137  * Executes the command and returns whether it could be successfully parsed
138  * or not (at the moment, always returns true).
139  *
140  */
141 IPC_HANDLER(command) {
142         /* To get a properly terminated buffer, we copy
143          * message_size bytes out of the buffer */
144         char *command = scalloc(message_size + 1);
145         strncpy(command, (const char*)message, message_size);
146         LOG("IPC: received: *%s*\n", command);
147         const char *reply = parse_cmd((const char*)command);
148         tree_render();
149         free(command);
150
151         /* If no reply was provided, we just use the default success message */
152         if (reply == NULL)
153                 reply = "{\"success\":true}";
154         ipc_send_message(fd, (const unsigned char*)reply,
155                          I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
156 }
157
158 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
159         y(map_open);
160         ystr("id");
161         y(integer, (long int)con);
162
163         ystr("type");
164         y(integer, con->type);
165
166         ystr("orientation");
167         y(integer, con->orientation);
168
169         ystr("urgent");
170         y(integer, con->urgent);
171
172         ystr("focused");
173         y(integer, (con == focused));
174
175         ystr("layout");
176         y(integer, con->layout);
177
178         ystr("border");
179         y(integer, con->border_style);
180
181         ystr("rect");
182         y(map_open);
183         ystr("x");
184         y(integer, con->rect.x);
185         ystr("y");
186         y(integer, con->rect.y);
187         ystr("width");
188         y(integer, con->rect.width);
189         ystr("height");
190         y(integer, con->rect.height);
191         y(map_close);
192
193         ystr("name");
194         ystr(con->name);
195
196         ystr("window");
197         if (con->window)
198                 y(integer, con->window->id);
199         else y(null);
200
201         ystr("nodes");
202         y(array_open);
203         Con *node;
204         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
205                 dump_node(gen, node, inplace_restart);
206         }
207         y(array_close);
208
209         ystr("floating_nodes");
210         y(array_open);
211         TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
212                 dump_node(gen, node, inplace_restart);
213         }
214         y(array_close);
215
216         ystr("focus");
217         y(array_open);
218         TAILQ_FOREACH(node, &(con->focus_head), nodes) {
219                 y(integer, (long int)node);
220         }
221         y(array_close);
222
223         ystr("fullscreen_mode");
224         y(integer, con->fullscreen_mode);
225
226         if (inplace_restart) {
227                 if (con->window != NULL) {
228                         ystr("swallows");
229                         y(array_open);
230                         y(map_open);
231                         ystr("id");
232                         y(integer, con->window->id);
233                         y(map_close);
234                         y(array_close);
235                 }
236         }
237
238         y(map_close);
239 }
240
241 IPC_HANDLER(tree) {
242         printf("tree\n");
243         yajl_gen gen = yajl_gen_alloc(NULL, NULL);
244         dump_node(gen, croot, false);
245
246         const unsigned char *payload;
247         unsigned int length;
248         y(get_buf, &payload, &length);
249
250         ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
251         y(free);
252
253 }
254
255 #if 0
256 /*
257  * Formats the reply message for a GET_WORKSPACES request and sends it to the
258  * client
259  *
260  */
261 IPC_HANDLER(get_workspaces) {
262         Workspace *ws;
263
264         Client *last_focused = SLIST_FIRST(&(c_ws->focus_stack));
265         if (last_focused == SLIST_END(&(c_ws->focus_stack)))
266                 last_focused = NULL;
267
268         yajl_gen gen = yajl_gen_alloc(NULL, NULL);
269         y(array_open);
270
271         TAILQ_FOREACH(ws, workspaces, workspaces) {
272                 if (ws->output == NULL)
273                         continue;
274
275                 y(map_open);
276                 ystr("num");
277                 y(integer, ws->num + 1);
278
279                 ystr("name");
280                 ystr(ws->utf8_name);
281
282                 ystr("visible");
283                 y(bool, ws->output->current_workspace == ws);
284
285                 ystr("focused");
286                 y(bool, c_ws == ws);
287
288                 ystr("rect");
289                 y(map_open);
290                 ystr("x");
291                 y(integer, ws->rect.x);
292                 ystr("y");
293                 y(integer, ws->rect.y);
294                 ystr("width");
295                 y(integer, ws->rect.width);
296                 ystr("height");
297                 y(integer, ws->rect.height);
298                 y(map_close);
299
300                 ystr("output");
301                 ystr(ws->output->name);
302
303                 ystr("urgent");
304                 y(bool, ws->urgent);
305
306                 y(map_close);
307         }
308
309         y(array_close);
310
311         const unsigned char *payload;
312         unsigned int length;
313         y(get_buf, &payload, &length);
314
315         ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
316         y(free);
317 }
318
319 /*
320  * Formats the reply message for a GET_OUTPUTS request and sends it to the
321  * client
322  *
323  */
324 IPC_HANDLER(get_outputs) {
325         Output *output;
326
327         yajl_gen gen = yajl_gen_alloc(NULL, NULL);
328         y(array_open);
329
330         TAILQ_FOREACH(output, &outputs, outputs) {
331                 y(map_open);
332
333                 ystr("name");
334                 ystr(output->name);
335
336                 ystr("active");
337                 y(bool, output->active);
338
339                 ystr("rect");
340                 y(map_open);
341                 ystr("x");
342                 y(integer, output->rect.x);
343                 ystr("y");
344                 y(integer, output->rect.y);
345                 ystr("width");
346                 y(integer, output->rect.width);
347                 ystr("height");
348                 y(integer, output->rect.height);
349                 y(map_close);
350
351                 ystr("current_workspace");
352                 if (output->current_workspace == NULL)
353                         y(null);
354                 else y(integer, output->current_workspace->num + 1);
355
356                 y(map_close);
357         }
358
359         y(array_close);
360
361         const unsigned char *payload;
362         unsigned int length;
363         y(get_buf, &payload, &length);
364
365         ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
366         y(free);
367 }
368
369 /*
370  * Callback for the YAJL parser (will be called when a string is parsed).
371  *
372  */
373 static int add_subscription(void *extra, const unsigned char *s,
374                             unsigned int len) {
375         ipc_client *client = extra;
376
377         DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
378         int event = client->num_events;
379
380         client->num_events++;
381         client->events = realloc(client->events, client->num_events * sizeof(char*));
382         /* We copy the string because it is not null-terminated and strndup()
383          * is missing on some BSD systems */
384         client->events[event] = scalloc(len+1);
385         memcpy(client->events[event], s, len);
386
387         DLOG("client is now subscribed to:\n");
388         for (int i = 0; i < client->num_events; i++)
389                 DLOG("event %s\n", client->events[i]);
390         DLOG("(done)\n");
391
392         return 1;
393 }
394
395 /*
396  * Subscribes this connection to the event types which were given as a JSON
397  * serialized array in the payload field of the message.
398  *
399  */
400 IPC_HANDLER(subscribe) {
401         yajl_handle p;
402         yajl_callbacks callbacks;
403         yajl_status stat;
404         ipc_client *current, *client = NULL;
405
406         /* Search the ipc_client structure for this connection */
407         TAILQ_FOREACH(current, &all_clients, clients) {
408                 if (current->fd != fd)
409                         continue;
410
411                 client = current;
412                 break;
413         }
414
415         if (client == NULL) {
416                 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
417                 return;
418         }
419
420         /* Setup the JSON parser */
421         memset(&callbacks, 0, sizeof(yajl_callbacks));
422         callbacks.yajl_string = add_subscription;
423
424         p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
425         stat = yajl_parse(p, (const unsigned char*)message, message_size);
426         if (stat != yajl_status_ok) {
427                 unsigned char *err;
428                 err = yajl_get_error(p, true, (const unsigned char*)message,
429                                      message_size);
430                 ELOG("YAJL parse error: %s\n", err);
431                 yajl_free_error(p, err);
432
433                 const char *reply = "{\"success\":false}";
434                 ipc_send_message(fd, (const unsigned char*)reply,
435                                  I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
436                 yajl_free(p);
437                 return;
438         }
439         yajl_free(p);
440         const char *reply = "{\"success\":true}";
441         ipc_send_message(fd, (const unsigned char*)reply,
442                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
443 }
444 #endif
445
446 /* The index of each callback function corresponds to the numeric
447  * value of the message type (see include/i3/ipc.h) */
448 handler_t handlers[2] = {
449         handle_command,
450         handle_tree
451 };
452
453 /*
454  * Handler for activity on a client connection, receives a message from a
455  * client.
456  *
457  * For now, the maximum message size is 2048. I’m not sure for what the
458  * IPC interface will be used in the future, thus I’m not implementing a
459  * mechanism for arbitrarily long messages, as it seems like overkill
460  * at the moment.
461  *
462  */
463 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
464         char buf[2048];
465         int n = read(w->fd, buf, sizeof(buf));
466
467         /* On error or an empty message, we close the connection */
468         if (n <= 0) {
469 #if 0
470                 /* FIXME: I get these when closing a client socket,
471                  * therefore we just treat them as an error. Is this
472                  * correct? */
473                 if (errno == EAGAIN || errno == EWOULDBLOCK)
474                         return;
475 #endif
476
477                 /* If not, there was some kind of error. We don’t bother
478                  * and close the connection */
479                 close(w->fd);
480
481                 /* Delete the client from the list of clients */
482                 ipc_client *current;
483                 TAILQ_FOREACH(current, &all_clients, clients) {
484                         if (current->fd != w->fd)
485                                 continue;
486
487                         for (int i = 0; i < current->num_events; i++)
488                                 free(current->events[i]);
489                         /* We can call TAILQ_REMOVE because we break out of the
490                          * TAILQ_FOREACH afterwards */
491                         TAILQ_REMOVE(&all_clients, current, clients);
492                         break;
493                 }
494
495                 ev_io_stop(EV_A_ w);
496
497                 DLOG("IPC: client disconnected\n");
498                 return;
499         }
500
501         /* Terminate the message correctly */
502         buf[n] = '\0';
503
504         /* Check if the message starts with the i3 IPC magic code */
505         if (n < strlen(I3_IPC_MAGIC)) {
506                 DLOG("IPC: message too short, ignoring\n");
507                 return;
508         }
509
510         if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
511                 DLOG("IPC: message does not start with the IPC magic\n");
512                 return;
513         }
514
515         uint8_t *message = (uint8_t*)buf;
516         while (n > 0) {
517                 DLOG("IPC: n = %d\n", n);
518                 message += strlen(I3_IPC_MAGIC);
519                 n -= strlen(I3_IPC_MAGIC);
520
521                 /* The next 32 bit after the magic are the message size */
522                 uint32_t message_size = *((uint32_t*)message);
523                 message += sizeof(uint32_t);
524                 n -= sizeof(uint32_t);
525
526                 if (message_size > n) {
527                         DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
528                         return;
529                 }
530
531                 /* The last 32 bits of the header are the message type */
532                 uint32_t message_type = *((uint32_t*)message);
533                 message += sizeof(uint32_t);
534                 n -= sizeof(uint32_t);
535
536                 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
537                         DLOG("Unhandled message type: %d\n", message_type);
538                 else {
539                         handler_t h = handlers[message_type];
540                         h(w->fd, message, n, message_size, message_type);
541                 }
542                 n -= message_size;
543                 message += message_size;
544         }
545 }
546
547 /*
548  * Handler for activity on the listening socket, meaning that a new client
549  * has just connected and we should accept() him. Sets up the event handler
550  * for activity on the new connection and inserts the file descriptor into
551  * the list of clients.
552  *
553  */
554 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
555         struct sockaddr_un peer;
556         socklen_t len = sizeof(struct sockaddr_un);
557         int client;
558         if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
559                 if (errno == EINTR)
560                         return;
561                 else perror("accept()");
562                 return;
563         }
564
565         set_nonblock(client);
566
567         struct ev_io *package = scalloc(sizeof(struct ev_io));
568         ev_io_init(package, ipc_receive_message, client, EV_READ);
569         ev_io_start(EV_A_ package);
570
571         DLOG("IPC: new client connected\n");
572
573         ipc_client *new = scalloc(sizeof(ipc_client));
574         new->fd = client;
575
576         TAILQ_INSERT_TAIL(&all_clients, new, clients);
577 }
578
579 /*
580  * Creates the UNIX domain socket at the given path, sets it to non-blocking
581  * mode, bind()s and listen()s on it.
582  *
583  */
584 int ipc_create_socket(const char *filename) {
585         int sockfd;
586
587         char *resolved = resolve_tilde(filename);
588         DLOG("Creating IPC-socket at %s\n", resolved);
589         char *copy = sstrdup(resolved);
590         const char *dir = dirname(copy);
591         if (!path_exists(dir))
592                 mkdirp(dir);
593         free(copy);
594
595         /* Unlink the unix domain socket before */
596         unlink(filename);
597
598         if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
599                 perror("socket()");
600                 free(resolved);
601                 return -1;
602         }
603
604         (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
605
606         struct sockaddr_un addr;
607         memset(&addr, 0, sizeof(struct sockaddr_un));
608         addr.sun_family = AF_LOCAL;
609         strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
610         if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
611                 perror("bind()");
612                 free(resolved);
613                 return -1;
614         }
615
616         free(resolved);
617         set_nonblock(sockfd);
618
619         if (listen(sockfd, 5) < 0) {
620                 perror("listen()");
621                 return -1;
622         }
623
624         return sockfd;
625 }