]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
ipc: change border_style to human-readable string instead of enum value
[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     strcpy(walk, "i3-ipc");
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     const char *reply = parse_cmd((const char*)command);
151     tree_render();
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
161 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
162     ystr(name);
163     y(map_open);
164     ystr("x");
165     y(integer, r.x);
166     ystr("y");
167     y(integer, r.y);
168     ystr("width");
169     y(integer, r.width);
170     ystr("height");
171     y(integer, r.height);
172     y(map_close);
173 }
174
175 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
176     y(map_open);
177     ystr("id");
178     y(integer, (long int)con);
179
180     ystr("type");
181     y(integer, con->type);
182
183     ystr("orientation");
184     switch (con->orientation) {
185         case NO_ORIENTATION:
186             ystr("none");
187             break;
188         case HORIZ:
189             ystr("horizontal");
190             break;
191         case VERT:
192             ystr("vertical");
193             break;
194     }
195
196     ystr("percent");
197     y(double, con->percent);
198
199     ystr("urgent");
200     y(integer, con->urgent);
201
202     ystr("focused");
203     y(integer, (con == focused));
204
205     ystr("layout");
206     y(integer, con->layout);
207
208     ystr("border");
209     switch (con->border_style) {
210         case BS_NORMAL:
211             ystr("normal");
212             break;
213         case BS_NONE:
214             ystr("none");
215             break;
216         case BS_1PIXEL:
217             ystr("1pixel");
218             break;
219     }
220
221     dump_rect(gen, "rect", con->rect);
222     dump_rect(gen, "window_rect", con->window_rect);
223     dump_rect(gen, "geometry", con->geometry);
224
225     ystr("name");
226     ystr(con->name);
227
228     if (con->type == CT_WORKSPACE) {
229         ystr("num");
230         y(integer, con->num);
231     }
232
233     ystr("window");
234     if (con->window)
235         y(integer, con->window->id);
236     else y(null);
237
238     ystr("nodes");
239     y(array_open);
240     Con *node;
241     if (con->type != CT_DOCKAREA || !inplace_restart) {
242         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
243             dump_node(gen, node, inplace_restart);
244         }
245     }
246     y(array_close);
247
248     ystr("floating_nodes");
249     y(array_open);
250     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
251         dump_node(gen, node, inplace_restart);
252     }
253     y(array_close);
254
255     ystr("focus");
256     y(array_open);
257     TAILQ_FOREACH(node, &(con->focus_head), nodes) {
258         y(integer, (long int)node);
259     }
260     y(array_close);
261
262     ystr("fullscreen_mode");
263     y(integer, con->fullscreen_mode);
264
265     ystr("swallows");
266     y(array_open);
267     Match *match;
268     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
269         if (match->dock != -1) {
270             y(map_open);
271             ystr("dock");
272             y(integer, match->dock);
273             ystr("insert_where");
274             y(integer, match->insert_where);
275             y(map_close);
276         }
277
278         /* TODO: the other swallow keys */
279     }
280
281     if (inplace_restart) {
282         if (con->window != NULL) {
283             y(map_open);
284             ystr("id");
285             y(integer, con->window->id);
286             y(map_close);
287         }
288     }
289     y(array_close);
290
291     y(map_close);
292 }
293
294 IPC_HANDLER(tree) {
295     setlocale(LC_NUMERIC, "C");
296 #if YAJL_MAJOR >= 2
297     yajl_gen gen = yajl_gen_alloc(NULL);
298 #else
299     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
300 #endif
301     dump_node(gen, croot, false);
302     setlocale(LC_NUMERIC, "");
303
304     const unsigned char *payload;
305 #if YAJL_MAJOR >= 2
306     size_t length;
307 #else
308     unsigned int length;
309 #endif
310     y(get_buf, &payload, &length);
311
312     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_TREE, length);
313     y(free);
314 }
315
316 /*
317  * Formats the reply message for a GET_WORKSPACES request and sends it to the
318  * client
319  *
320  */
321 IPC_HANDLER(get_workspaces) {
322 #if YAJL_MAJOR >= 2
323     yajl_gen gen = yajl_gen_alloc(NULL);
324 #else
325     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
326 #endif
327     y(array_open);
328
329     Con *focused_ws = con_get_workspace(focused);
330
331     Con *output;
332     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
333         Con *ws;
334         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
335             assert(ws->type == CT_WORKSPACE);
336             y(map_open);
337
338             ystr("num");
339             if (ws->num == -1)
340                 y(null);
341             else y(integer, ws->num);
342
343             ystr("name");
344             ystr(ws->name);
345
346             ystr("visible");
347             y(bool, workspace_is_visible(ws));
348
349             ystr("focused");
350             y(bool, ws == focused_ws);
351
352             ystr("rect");
353             y(map_open);
354             ystr("x");
355             y(integer, ws->rect.x);
356             ystr("y");
357             y(integer, ws->rect.y);
358             ystr("width");
359             y(integer, ws->rect.width);
360             ystr("height");
361             y(integer, ws->rect.height);
362             y(map_close);
363
364             ystr("output");
365             ystr(output->name);
366
367             ystr("urgent");
368             y(bool, ws->urgent);
369
370             y(map_close);
371         }
372     }
373
374     y(array_close);
375
376     const unsigned char *payload;
377 #if YAJL_MAJOR >= 2
378     size_t length;
379 #else
380     unsigned int length;
381 #endif
382     y(get_buf, &payload, &length);
383
384     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
385     y(free);
386 }
387
388 /*
389  * Formats the reply message for a GET_OUTPUTS request and sends it to the
390  * client
391  *
392  */
393 IPC_HANDLER(get_outputs) {
394 #if YAJL_MAJOR >= 2
395     yajl_gen gen = yajl_gen_alloc(NULL);
396 #else
397     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
398 #endif
399     y(array_open);
400
401     Output *output;
402     TAILQ_FOREACH(output, &outputs, outputs) {
403         y(map_open);
404
405         ystr("name");
406         ystr(output->name);
407
408         ystr("active");
409         y(bool, output->active);
410
411         ystr("rect");
412         y(map_open);
413         ystr("x");
414         y(integer, output->rect.x);
415         ystr("y");
416         y(integer, output->rect.y);
417         ystr("width");
418         y(integer, output->rect.width);
419         ystr("height");
420         y(integer, output->rect.height);
421         y(map_close);
422
423         ystr("current_workspace");
424         Con *ws = NULL;
425         if (output->con && (ws = con_get_fullscreen_con(output->con)))
426             ystr(ws->name);
427         else y(null);
428
429         y(map_close);
430     }
431
432     y(array_close);
433
434     const unsigned char *payload;
435 #if YAJL_MAJOR >= 2
436     size_t length;
437 #else
438     unsigned int length;
439 #endif
440     y(get_buf, &payload, &length);
441
442     ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
443     y(free);
444 }
445
446 /*
447  * Callback for the YAJL parser (will be called when a string is parsed).
448  *
449  */
450 #if YAJL_MAJOR < 2
451 static int add_subscription(void *extra, const unsigned char *s,
452                             unsigned int len) {
453 #else
454 static int add_subscription(void *extra, const unsigned char *s,
455                             size_t len) {
456 #endif
457     ipc_client *client = extra;
458
459     DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
460     int event = client->num_events;
461
462     client->num_events++;
463     client->events = realloc(client->events, client->num_events * sizeof(char*));
464     /* We copy the string because it is not null-terminated and strndup()
465      * is missing on some BSD systems */
466     client->events[event] = scalloc(len+1);
467     memcpy(client->events[event], s, len);
468
469     DLOG("client is now subscribed to:\n");
470     for (int i = 0; i < client->num_events; i++)
471         DLOG("event %s\n", client->events[i]);
472     DLOG("(done)\n");
473
474     return 1;
475 }
476
477 /*
478  * Subscribes this connection to the event types which were given as a JSON
479  * serialized array in the payload field of the message.
480  *
481  */
482 IPC_HANDLER(subscribe) {
483     yajl_handle p;
484     yajl_callbacks callbacks;
485     yajl_status stat;
486     ipc_client *current, *client = NULL;
487
488     /* Search the ipc_client structure for this connection */
489     TAILQ_FOREACH(current, &all_clients, clients) {
490         if (current->fd != fd)
491             continue;
492
493         client = current;
494         break;
495     }
496
497     if (client == NULL) {
498         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
499         return;
500     }
501
502     /* Setup the JSON parser */
503     memset(&callbacks, 0, sizeof(yajl_callbacks));
504     callbacks.yajl_string = add_subscription;
505
506 #if YAJL_MAJOR >= 2
507     p = yajl_alloc(&callbacks, NULL, (void*)client);
508 #else
509     p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
510 #endif
511     stat = yajl_parse(p, (const unsigned char*)message, message_size);
512     if (stat != yajl_status_ok) {
513         unsigned char *err;
514         err = yajl_get_error(p, true, (const unsigned char*)message,
515                              message_size);
516         ELOG("YAJL parse error: %s\n", err);
517         yajl_free_error(p, err);
518
519         const char *reply = "{\"success\":false}";
520         ipc_send_message(fd, (const unsigned char*)reply,
521                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
522         yajl_free(p);
523         return;
524     }
525     yajl_free(p);
526     const char *reply = "{\"success\":true}";
527     ipc_send_message(fd, (const unsigned char*)reply,
528                      I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
529 }
530
531 /* The index of each callback function corresponds to the numeric
532  * value of the message type (see include/i3/ipc.h) */
533 handler_t handlers[5] = {
534     handle_command,
535     handle_get_workspaces,
536     handle_subscribe,
537     handle_get_outputs,
538     handle_tree
539 };
540
541 /*
542  * Handler for activity on a client connection, receives a message from a
543  * client.
544  *
545  * For now, the maximum message size is 2048. I’m not sure for what the
546  * IPC interface will be used in the future, thus I’m not implementing a
547  * mechanism for arbitrarily long messages, as it seems like overkill
548  * at the moment.
549  *
550  */
551 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
552     char buf[2048];
553     int n = read(w->fd, buf, sizeof(buf));
554
555     /* On error or an empty message, we close the connection */
556     if (n <= 0) {
557 #if 0
558         /* FIXME: I get these when closing a client socket,
559          * therefore we just treat them as an error. Is this
560          * correct? */
561         if (errno == EAGAIN || errno == EWOULDBLOCK)
562                 return;
563 #endif
564
565         /* If not, there was some kind of error. We don’t bother
566          * and close the connection */
567         close(w->fd);
568
569         /* Delete the client from the list of clients */
570         ipc_client *current;
571         TAILQ_FOREACH(current, &all_clients, clients) {
572             if (current->fd != w->fd)
573                 continue;
574
575             for (int i = 0; i < current->num_events; i++)
576                 free(current->events[i]);
577             /* We can call TAILQ_REMOVE because we break out of the
578              * TAILQ_FOREACH afterwards */
579             TAILQ_REMOVE(&all_clients, current, clients);
580             break;
581         }
582
583         ev_io_stop(EV_A_ w);
584
585         DLOG("IPC: client disconnected\n");
586         return;
587     }
588
589     /* Terminate the message correctly */
590     buf[n] = '\0';
591
592     /* Check if the message starts with the i3 IPC magic code */
593     if (n < strlen(I3_IPC_MAGIC)) {
594         DLOG("IPC: message too short, ignoring\n");
595         return;
596     }
597
598     if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
599         DLOG("IPC: message does not start with the IPC magic\n");
600         return;
601     }
602
603     uint8_t *message = (uint8_t*)buf;
604     while (n > 0) {
605         DLOG("IPC: n = %d\n", n);
606         message += strlen(I3_IPC_MAGIC);
607         n -= strlen(I3_IPC_MAGIC);
608
609         /* The next 32 bit after the magic are the message size */
610         uint32_t message_size;
611         memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
612         message += sizeof(uint32_t);
613         n -= sizeof(uint32_t);
614
615         if (message_size > n) {
616             DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
617             return;
618         }
619
620         /* The last 32 bits of the header are the message type */
621         uint32_t message_type;
622         memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
623         message += sizeof(uint32_t);
624         n -= sizeof(uint32_t);
625
626         if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
627             DLOG("Unhandled message type: %d\n", message_type);
628         else {
629             handler_t h = handlers[message_type];
630             h(w->fd, message, n, message_size, message_type);
631         }
632         n -= message_size;
633         message += message_size;
634     }
635 }
636
637 /*
638  * Handler for activity on the listening socket, meaning that a new client
639  * has just connected and we should accept() him. Sets up the event handler
640  * for activity on the new connection and inserts the file descriptor into
641  * the list of clients.
642  *
643  */
644 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
645     struct sockaddr_un peer;
646     socklen_t len = sizeof(struct sockaddr_un);
647     int client;
648     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
649         if (errno == EINTR)
650             return;
651         else perror("accept()");
652         return;
653     }
654
655     set_nonblock(client);
656
657     struct ev_io *package = scalloc(sizeof(struct ev_io));
658     ev_io_init(package, ipc_receive_message, client, EV_READ);
659     ev_io_start(EV_A_ package);
660
661     DLOG("IPC: new client connected\n");
662
663     ipc_client *new = scalloc(sizeof(ipc_client));
664     new->fd = client;
665
666     TAILQ_INSERT_TAIL(&all_clients, new, clients);
667 }
668
669 /*
670  * Creates the UNIX domain socket at the given path, sets it to non-blocking
671  * mode, bind()s and listen()s on it.
672  *
673  */
674 int ipc_create_socket(const char *filename) {
675     int sockfd;
676
677     FREE(current_socketpath);
678
679     char *resolved = resolve_tilde(filename);
680     DLOG("Creating IPC-socket at %s\n", resolved);
681     char *copy = sstrdup(resolved);
682     const char *dir = dirname(copy);
683     if (!path_exists(dir))
684         mkdirp(dir);
685     free(copy);
686
687     /* Unlink the unix domain socket before */
688     unlink(resolved);
689
690     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
691         perror("socket()");
692         free(resolved);
693         return -1;
694     }
695
696     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
697
698     struct sockaddr_un addr;
699     memset(&addr, 0, sizeof(struct sockaddr_un));
700     addr.sun_family = AF_LOCAL;
701     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
702     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
703         perror("bind()");
704         free(resolved);
705         return -1;
706     }
707
708     set_nonblock(sockfd);
709
710     if (listen(sockfd, 5) < 0) {
711         perror("listen()");
712         free(resolved);
713         return -1;
714     }
715
716     current_socketpath = resolved;
717     return sockfd;
718 }