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