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