]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Revert "use designated initializers for yajl_callbacks struct"
[i3/i3] / src / ipc.c
1 #undef I3__FILE__
2 #define I3__FILE__ "ipc.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
10  *
11  */
12 #include "all.h"
13 #include "yajl_utils.h"
14
15 #include <sys/socket.h>
16 #include <sys/un.h>
17 #include <fcntl.h>
18 #include <libgen.h>
19 #include <ev.h>
20 #include <yajl/yajl_gen.h>
21 #include <yajl/yajl_parse.h>
22
23 char *current_socketpath = NULL;
24
25 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
26
27 /*
28  * Puts the given socket file descriptor into non-blocking mode or dies if
29  * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
30  * IPC model because we should by no means block the window manager.
31  *
32  */
33 static void set_nonblock(int sockfd) {
34     int flags = fcntl(sockfd, F_GETFL, 0);
35     flags |= O_NONBLOCK;
36     if (fcntl(sockfd, F_SETFL, flags) < 0)
37         err(-1, "Could not set O_NONBLOCK");
38 }
39
40 /*
41  * Emulates mkdir -p (creates any missing folders)
42  *
43  */
44 static bool mkdirp(const char *path) {
45     if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
46         return true;
47     if (errno != ENOENT) {
48         ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
49         return false;
50     }
51     char *copy = sstrdup(path);
52     /* strip trailing slashes, if any */
53     while (copy[strlen(copy)-1] == '/')
54         copy[strlen(copy)-1] = '\0';
55
56     char *sep = strrchr(copy, '/');
57     if (sep == NULL) {
58         FREE(copy);
59         return false;
60     }
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 /*
71  * Sends the specified event to all IPC clients which are currently connected
72  * and subscribed to this kind of event.
73  *
74  */
75 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
76     ipc_client *current;
77     TAILQ_FOREACH(current, &all_clients, clients) {
78         /* see if this client is interested in this event */
79         bool interested = false;
80         for (int i = 0; i < current->num_events; i++) {
81             if (strcasecmp(current->events[i], event) != 0)
82                 continue;
83             interested = true;
84             break;
85         }
86         if (!interested)
87             continue;
88
89         ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t*)payload);
90     }
91 }
92
93 /*
94  * Calls shutdown() on each socket and closes it. This function to be called
95  * when exiting or restarting only!
96  *
97  */
98 void ipc_shutdown(void) {
99     ipc_client *current;
100     while (!TAILQ_EMPTY(&all_clients)) {
101         current = TAILQ_FIRST(&all_clients);
102         shutdown(current->fd, SHUT_RDWR);
103         close(current->fd);
104         TAILQ_REMOVE(&all_clients, current, clients);
105         free(current);
106     }
107 }
108
109 /*
110  * Executes the command and returns whether it could be successfully parsed
111  * or not (at the moment, always returns true).
112  *
113  */
114 IPC_HANDLER(command) {
115     /* To get a properly terminated buffer, we copy
116      * message_size bytes out of the buffer */
117     char *command = scalloc(message_size + 1);
118     strncpy(command, (const char*)message, message_size);
119     LOG("IPC: received: *%s*\n", command);
120     struct CommandResult *command_output = parse_command((const char*)command);
121     free(command);
122
123     if (command_output->needs_tree_render)
124         tree_render();
125
126     const unsigned char *reply;
127     ylength length;
128     yajl_gen_get_buf(command_output->json_gen, &reply, &length);
129
130     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
131                      (const uint8_t*)reply);
132
133     yajl_gen_free(command_output->json_gen);
134 }
135
136 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
137     ystr(name);
138     y(map_open);
139     ystr("x");
140     y(integer, r.x);
141     ystr("y");
142     y(integer, r.y);
143     ystr("width");
144     y(integer, r.width);
145     ystr("height");
146     y(integer, r.height);
147     y(map_close);
148 }
149
150 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
151     y(map_open);
152     ystr("id");
153     y(integer, (long int)con);
154
155     ystr("type");
156     switch (con->type) {
157         case CT_ROOT:
158             ystr("root");
159             break;
160         case CT_OUTPUT:
161             ystr("output");
162             break;
163         case CT_CON:
164             ystr("con");
165             break;
166         case CT_FLOATING_CON:
167             ystr("floating_con");
168             break;
169         case CT_WORKSPACE:
170             ystr("workspace");
171             break;
172         case CT_DOCKAREA:
173             ystr("dockarea");
174             break;
175         default:
176             DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
177             assert(false);
178             break;
179     }
180
181     /* provided for backwards compatibility only. */
182     ystr("orientation");
183     if (!con_is_split(con))
184         ystr("none");
185     else {
186         if (con_orientation(con) == HORIZ)
187             ystr("horizontal");
188         else ystr("vertical");
189     }
190
191     ystr("scratchpad_state");
192     switch (con->scratchpad_state) {
193         case SCRATCHPAD_NONE:
194             ystr("none");
195             break;
196         case SCRATCHPAD_FRESH:
197             ystr("fresh");
198             break;
199         case SCRATCHPAD_CHANGED:
200             ystr("changed");
201             break;
202     }
203
204     ystr("percent");
205     if (con->percent == 0.0)
206         y(null);
207     else y(double, con->percent);
208
209     ystr("urgent");
210     y(bool, con->urgent);
211
212     if (con->mark != NULL) {
213         ystr("mark");
214         ystr(con->mark);
215     }
216
217     ystr("focused");
218     y(bool, (con == focused));
219
220     ystr("layout");
221     switch (con->layout) {
222         case L_DEFAULT:
223             DLOG("About to dump layout=default, this is a bug in the code.\n");
224             assert(false);
225             break;
226         case L_SPLITV:
227             ystr("splitv");
228             break;
229         case L_SPLITH:
230             ystr("splith");
231             break;
232         case L_STACKED:
233             ystr("stacked");
234             break;
235         case L_TABBED:
236             ystr("tabbed");
237             break;
238         case L_DOCKAREA:
239             ystr("dockarea");
240             break;
241         case L_OUTPUT:
242             ystr("output");
243             break;
244     }
245
246     ystr("workspace_layout");
247     switch (con->workspace_layout) {
248         case L_DEFAULT:
249             ystr("default");
250             break;
251         case L_STACKED:
252             ystr("stacked");
253             break;
254         case L_TABBED:
255             ystr("tabbed");
256             break;
257         default:
258             DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
259             assert(false);
260             break;
261     }
262
263     ystr("last_split_layout");
264     switch (con->layout) {
265         case L_SPLITV:
266             ystr("splitv");
267             break;
268         default:
269             ystr("splith");
270             break;
271     }
272
273     ystr("border");
274     switch (con->border_style) {
275         case BS_NORMAL:
276             ystr("normal");
277             break;
278         case BS_NONE:
279             ystr("none");
280             break;
281         case BS_PIXEL:
282             ystr("pixel");
283             break;
284     }
285
286     ystr("current_border_width");
287     y(integer, con->current_border_width);
288
289     dump_rect(gen, "rect", con->rect);
290     dump_rect(gen, "window_rect", con->window_rect);
291     dump_rect(gen, "geometry", con->geometry);
292
293     ystr("name");
294     if (con->window && con->window->name)
295         ystr(i3string_as_utf8(con->window->name));
296     else
297         ystr(con->name);
298
299     if (con->type == CT_WORKSPACE) {
300         ystr("num");
301         y(integer, con->num);
302     }
303
304     ystr("window");
305     if (con->window)
306         y(integer, con->window->id);
307     else y(null);
308
309     if (con->window && !inplace_restart) {
310         /* Window properties are useless to preserve when restarting because
311          * they will be queried again anyway. However, for i3-save-tree(1),
312          * they are very useful and save i3-save-tree dealing with X11. */
313         ystr("window_properties");
314         y(map_open);
315
316 #define DUMP_PROPERTY(key, prop_name) do { \
317     if (con->window->prop_name != NULL) { \
318         ystr(key); \
319         ystr(con->window->prop_name); \
320     } \
321 } while (0)
322
323         DUMP_PROPERTY("class", class_class);
324         DUMP_PROPERTY("instance", class_instance);
325         DUMP_PROPERTY("window_role", role);
326
327         if (con->window->name != NULL) {
328             ystr("title");
329             ystr(i3string_as_utf8(con->window->name));
330         }
331
332         y(map_close);
333     }
334
335     ystr("nodes");
336     y(array_open);
337     Con *node;
338     if (con->type != CT_DOCKAREA || !inplace_restart) {
339         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
340             dump_node(gen, node, inplace_restart);
341         }
342     }
343     y(array_close);
344
345     ystr("floating_nodes");
346     y(array_open);
347     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
348         dump_node(gen, node, inplace_restart);
349     }
350     y(array_close);
351
352     ystr("focus");
353     y(array_open);
354     TAILQ_FOREACH(node, &(con->focus_head), focused) {
355         y(integer, (long int)node);
356     }
357     y(array_close);
358
359     ystr("fullscreen_mode");
360     y(integer, con->fullscreen_mode);
361
362     ystr("floating");
363     switch (con->floating) {
364         case FLOATING_AUTO_OFF:
365             ystr("auto_off");
366             break;
367         case FLOATING_AUTO_ON:
368             ystr("auto_on");
369             break;
370         case FLOATING_USER_OFF:
371             ystr("user_off");
372             break;
373         case FLOATING_USER_ON:
374             ystr("user_on");
375             break;
376     }
377
378     ystr("swallows");
379     y(array_open);
380     Match *match;
381     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
382         if (match->dock != -1) {
383             y(map_open);
384             ystr("dock");
385             y(integer, match->dock);
386             ystr("insert_where");
387             y(integer, match->insert_where);
388             y(map_close);
389         }
390
391         /* TODO: the other swallow keys */
392     }
393
394     if (inplace_restart) {
395         if (con->window != NULL) {
396             y(map_open);
397             ystr("id");
398             y(integer, con->window->id);
399             ystr("restart_mode");
400             y(bool, true);
401             y(map_close);
402         }
403     }
404     y(array_close);
405
406     if (inplace_restart && con->window != NULL) {
407         ystr("depth");
408         y(integer, con->depth);
409     }
410
411     y(map_close);
412 }
413
414 IPC_HANDLER(tree) {
415     setlocale(LC_NUMERIC, "C");
416     yajl_gen gen = ygenalloc();
417     dump_node(gen, croot, false);
418     setlocale(LC_NUMERIC, "");
419
420     const unsigned char *payload;
421     ylength length;
422     y(get_buf, &payload, &length);
423
424     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
425     y(free);
426 }
427
428
429 /*
430  * Formats the reply message for a GET_WORKSPACES request and sends it to the
431  * client
432  *
433  */
434 IPC_HANDLER(get_workspaces) {
435     yajl_gen gen = ygenalloc();
436     y(array_open);
437
438     Con *focused_ws = con_get_workspace(focused);
439
440     Con *output;
441     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
442         if (con_is_internal(output))
443             continue;
444         Con *ws;
445         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
446             assert(ws->type == CT_WORKSPACE);
447             y(map_open);
448
449             ystr("num");
450             if (ws->num == -1)
451                 y(null);
452             else y(integer, ws->num);
453
454             ystr("name");
455             ystr(ws->name);
456
457             ystr("visible");
458             y(bool, workspace_is_visible(ws));
459
460             ystr("focused");
461             y(bool, ws == focused_ws);
462
463             ystr("rect");
464             y(map_open);
465             ystr("x");
466             y(integer, ws->rect.x);
467             ystr("y");
468             y(integer, ws->rect.y);
469             ystr("width");
470             y(integer, ws->rect.width);
471             ystr("height");
472             y(integer, ws->rect.height);
473             y(map_close);
474
475             ystr("output");
476             ystr(output->name);
477
478             ystr("urgent");
479             y(bool, ws->urgent);
480
481             y(map_close);
482         }
483     }
484
485     y(array_close);
486
487     const unsigned char *payload;
488     ylength length;
489     y(get_buf, &payload, &length);
490
491     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
492     y(free);
493 }
494
495 /*
496  * Formats the reply message for a GET_OUTPUTS request and sends it to the
497  * client
498  *
499  */
500 IPC_HANDLER(get_outputs) {
501     yajl_gen gen = ygenalloc();
502     y(array_open);
503
504     Output *output;
505     TAILQ_FOREACH(output, &outputs, outputs) {
506         y(map_open);
507
508         ystr("name");
509         ystr(output->name);
510
511         ystr("active");
512         y(bool, output->active);
513
514         ystr("primary");
515         y(bool, output->primary);
516
517         ystr("rect");
518         y(map_open);
519         ystr("x");
520         y(integer, output->rect.x);
521         ystr("y");
522         y(integer, output->rect.y);
523         ystr("width");
524         y(integer, output->rect.width);
525         ystr("height");
526         y(integer, output->rect.height);
527         y(map_close);
528
529         ystr("current_workspace");
530         Con *ws = NULL;
531         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
532             ystr(ws->name);
533         else y(null);
534
535         y(map_close);
536     }
537
538     y(array_close);
539
540     const unsigned char *payload;
541     ylength length;
542     y(get_buf, &payload, &length);
543
544     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
545     y(free);
546 }
547
548 /*
549  * Formats the reply message for a GET_MARKS request and sends it to the
550  * client
551  *
552  */
553 IPC_HANDLER(get_marks) {
554     yajl_gen gen = ygenalloc();
555     y(array_open);
556
557     Con *con;
558     TAILQ_FOREACH(con, &all_cons, all_cons)
559         if (con->mark != NULL)
560             ystr(con->mark);
561
562     y(array_close);
563
564     const unsigned char *payload;
565     ylength length;
566     y(get_buf, &payload, &length);
567
568     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
569     y(free);
570 }
571
572 /*
573  * Returns the version of i3
574  *
575  */
576 IPC_HANDLER(get_version) {
577     yajl_gen gen = ygenalloc();
578     y(map_open);
579
580     ystr("major");
581     y(integer, MAJOR_VERSION);
582
583     ystr("minor");
584     y(integer, MINOR_VERSION);
585
586     ystr("patch");
587     y(integer, PATCH_VERSION);
588
589     ystr("human_readable");
590     ystr(I3_VERSION);
591
592     y(map_close);
593
594     const unsigned char *payload;
595     ylength length;
596     y(get_buf, &payload, &length);
597
598     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
599     y(free);
600 }
601
602 /*
603  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
604  * client.
605  *
606  */
607 IPC_HANDLER(get_bar_config) {
608     yajl_gen gen = ygenalloc();
609
610     /* If no ID was passed, we return a JSON array with all IDs */
611     if (message_size == 0) {
612         y(array_open);
613         Barconfig *current;
614         TAILQ_FOREACH(current, &barconfigs, configs) {
615             ystr(current->id);
616         }
617         y(array_close);
618
619         const unsigned char *payload;
620         ylength length;
621         y(get_buf, &payload, &length);
622
623         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
624         y(free);
625         return;
626     }
627
628     /* To get a properly terminated buffer, we copy
629      * message_size bytes out of the buffer */
630     char *bar_id = scalloc(message_size + 1);
631     strncpy(bar_id, (const char*)message, message_size);
632     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
633     Barconfig *current, *config = NULL;
634     TAILQ_FOREACH(current, &barconfigs, configs) {
635         if (strcmp(current->id, bar_id) != 0)
636             continue;
637
638         config = current;
639         break;
640     }
641
642     y(map_open);
643
644     if (!config) {
645         /* If we did not find a config for the given ID, the reply will contain
646          * a null 'id' field. */
647         ystr("id");
648         y(null);
649     } else {
650         ystr("id");
651         ystr(config->id);
652
653         if (config->num_outputs > 0) {
654             ystr("outputs");
655             y(array_open);
656             for (int c = 0; c < config->num_outputs; c++)
657                 ystr(config->outputs[c]);
658             y(array_close);
659         }
660
661 #define YSTR_IF_SET(name) \
662         do { \
663             if (config->name) { \
664                 ystr( # name); \
665                 ystr(config->name); \
666             } \
667         } while (0)
668
669         YSTR_IF_SET(tray_output);
670         YSTR_IF_SET(socket_path);
671
672         ystr("mode");
673         switch (config->mode) {
674             case M_HIDE:
675                 ystr("hide");
676                 break;
677             case M_INVISIBLE:
678                 ystr("invisible");
679                 break;
680             case M_DOCK:
681             default:
682                 ystr("dock");
683                 break;
684         }
685
686         ystr("hidden_state");
687         switch (config->hidden_state) {
688             case S_SHOW:
689                 ystr("show");
690                 break;
691             case S_HIDE:
692             default:
693                 ystr("hide");
694                 break;
695         }
696
697         ystr("modifier");
698         switch (config->modifier) {
699             case M_CONTROL:
700                 ystr("ctrl");
701                 break;
702             case M_SHIFT:
703                 ystr("shift");
704                 break;
705             case M_MOD1:
706                 ystr("Mod1");
707                 break;
708             case M_MOD2:
709                 ystr("Mod2");
710                 break;
711             case M_MOD3:
712                 ystr("Mod3");
713                 break;
714             /*
715             case M_MOD4:
716                 ystr("Mod4");
717                 break;
718             */
719             case M_MOD5:
720                 ystr("Mod5");
721                 break;
722             default:
723                 ystr("Mod4");
724                 break;
725         }
726
727         ystr("position");
728         if (config->position == P_BOTTOM)
729             ystr("bottom");
730         else ystr("top");
731
732         YSTR_IF_SET(status_command);
733         YSTR_IF_SET(font);
734
735         ystr("workspace_buttons");
736         y(bool, !config->hide_workspace_buttons);
737
738         ystr("binding_mode_indicator");
739         y(bool, !config->hide_binding_mode_indicator);
740
741         ystr("verbose");
742         y(bool, config->verbose);
743
744 #undef YSTR_IF_SET
745 #define YSTR_IF_SET(name) \
746         do { \
747             if (config->colors.name) { \
748                 ystr( # name); \
749                 ystr(config->colors.name); \
750             } \
751         } while (0)
752
753         ystr("colors");
754         y(map_open);
755         YSTR_IF_SET(background);
756         YSTR_IF_SET(statusline);
757         YSTR_IF_SET(separator);
758         YSTR_IF_SET(focused_workspace_border);
759         YSTR_IF_SET(focused_workspace_bg);
760         YSTR_IF_SET(focused_workspace_text);
761         YSTR_IF_SET(active_workspace_border);
762         YSTR_IF_SET(active_workspace_bg);
763         YSTR_IF_SET(active_workspace_text);
764         YSTR_IF_SET(inactive_workspace_border);
765         YSTR_IF_SET(inactive_workspace_bg);
766         YSTR_IF_SET(inactive_workspace_text);
767         YSTR_IF_SET(urgent_workspace_border);
768         YSTR_IF_SET(urgent_workspace_bg);
769         YSTR_IF_SET(urgent_workspace_text);
770         y(map_close);
771
772 #undef YSTR_IF_SET
773     }
774
775     y(map_close);
776
777     const unsigned char *payload;
778     ylength length;
779     y(get_buf, &payload, &length);
780
781     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
782     y(free);
783 }
784
785 /*
786  * Callback for the YAJL parser (will be called when a string is parsed).
787  *
788  */
789 static int add_subscription(void *extra, const unsigned char *s,
790                             ylength len) {
791     ipc_client *client = extra;
792
793     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
794     int event = client->num_events;
795
796     client->num_events++;
797     client->events = realloc(client->events, client->num_events * sizeof(char*));
798     /* We copy the string because it is not null-terminated and strndup()
799      * is missing on some BSD systems */
800     client->events[event] = scalloc(len+1);
801     memcpy(client->events[event], s, len);
802
803     DLOG("client is now subscribed to:\n");
804     for (int i = 0; i < client->num_events; i++)
805         DLOG("event %s\n", client->events[i]);
806     DLOG("(done)\n");
807
808     return 1;
809 }
810
811 /*
812  * Subscribes this connection to the event types which were given as a JSON
813  * serialized array in the payload field of the message.
814  *
815  */
816 IPC_HANDLER(subscribe) {
817     yajl_handle p;
818     yajl_callbacks callbacks;
819     yajl_status stat;
820     ipc_client *current, *client = NULL;
821
822     /* Search the ipc_client structure for this connection */
823     TAILQ_FOREACH(current, &all_clients, clients) {
824         if (current->fd != fd)
825             continue;
826
827         client = current;
828         break;
829     }
830
831     if (client == NULL) {
832         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
833         return;
834     }
835
836     /* Setup the JSON parser */
837     memset(&callbacks, 0, sizeof(yajl_callbacks));
838     callbacks.yajl_string = add_subscription;
839
840     p = yalloc(&callbacks, (void*)client);
841     stat = yajl_parse(p, (const unsigned char*)message, message_size);
842     if (stat != yajl_status_ok) {
843         unsigned char *err;
844         err = yajl_get_error(p, true, (const unsigned char*)message,
845                              message_size);
846         ELOG("YAJL parse error: %s\n", err);
847         yajl_free_error(p, err);
848
849         const char *reply = "{\"success\":false}";
850         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
851         yajl_free(p);
852         return;
853     }
854     yajl_free(p);
855     const char *reply = "{\"success\":true}";
856     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
857 }
858
859 /* The index of each callback function corresponds to the numeric
860  * value of the message type (see include/i3/ipc.h) */
861 handler_t handlers[8] = {
862     handle_command,
863     handle_get_workspaces,
864     handle_subscribe,
865     handle_get_outputs,
866     handle_tree,
867     handle_get_marks,
868     handle_get_bar_config,
869     handle_get_version,
870 };
871
872 /*
873  * Handler for activity on a client connection, receives a message from a
874  * client.
875  *
876  * For now, the maximum message size is 2048. I’m not sure for what the
877  * IPC interface will be used in the future, thus I’m not implementing a
878  * mechanism for arbitrarily long messages, as it seems like overkill
879  * at the moment.
880  *
881  */
882 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
883     uint32_t message_type;
884     uint32_t message_length;
885     uint8_t *message;
886
887     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
888     /* EOF or other error */
889     if (ret < 0) {
890         /* Was this a spurious read? See ev(3) */
891         if (ret == -1 && errno == EAGAIN)
892             return;
893
894         /* If not, there was some kind of error. We don’t bother
895          * and close the connection */
896         close(w->fd);
897
898         /* Delete the client from the list of clients */
899         ipc_client *current;
900         TAILQ_FOREACH(current, &all_clients, clients) {
901             if (current->fd != w->fd)
902                 continue;
903
904             for (int i = 0; i < current->num_events; i++)
905                 free(current->events[i]);
906             /* We can call TAILQ_REMOVE because we break out of the
907              * TAILQ_FOREACH afterwards */
908             TAILQ_REMOVE(&all_clients, current, clients);
909             free(current);
910             break;
911         }
912
913         ev_io_stop(EV_A_ w);
914         free(w);
915
916         DLOG("IPC: client disconnected\n");
917         return;
918     }
919
920     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
921         DLOG("Unhandled message type: %d\n", message_type);
922     else {
923         handler_t h = handlers[message_type];
924         h(w->fd, message, 0, message_length, message_type);
925     }
926 }
927
928 /*
929  * Handler for activity on the listening socket, meaning that a new client
930  * has just connected and we should accept() him. Sets up the event handler
931  * for activity on the new connection and inserts the file descriptor into
932  * the list of clients.
933  *
934  */
935 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
936     struct sockaddr_un peer;
937     socklen_t len = sizeof(struct sockaddr_un);
938     int client;
939     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
940         if (errno == EINTR)
941             return;
942         else perror("accept()");
943         return;
944     }
945
946     /* Close this file descriptor on exec() */
947     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
948
949     set_nonblock(client);
950
951     struct ev_io *package = scalloc(sizeof(struct ev_io));
952     ev_io_init(package, ipc_receive_message, client, EV_READ);
953     ev_io_start(EV_A_ package);
954
955     DLOG("IPC: new client connected on fd %d\n", w->fd);
956
957     ipc_client *new = scalloc(sizeof(ipc_client));
958     new->fd = client;
959
960     TAILQ_INSERT_TAIL(&all_clients, new, clients);
961 }
962
963 /*
964  * Creates the UNIX domain socket at the given path, sets it to non-blocking
965  * mode, bind()s and listen()s on it.
966  *
967  */
968 int ipc_create_socket(const char *filename) {
969     int sockfd;
970
971     FREE(current_socketpath);
972
973     char *resolved = resolve_tilde(filename);
974     DLOG("Creating IPC-socket at %s\n", resolved);
975     char *copy = sstrdup(resolved);
976     const char *dir = dirname(copy);
977     if (!path_exists(dir))
978         mkdirp(dir);
979     free(copy);
980
981     /* Unlink the unix domain socket before */
982     unlink(resolved);
983
984     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
985         perror("socket()");
986         free(resolved);
987         return -1;
988     }
989
990     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
991
992     struct sockaddr_un addr;
993     memset(&addr, 0, sizeof(struct sockaddr_un));
994     addr.sun_family = AF_LOCAL;
995     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
996     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
997         perror("bind()");
998         free(resolved);
999         return -1;
1000     }
1001
1002     set_nonblock(sockfd);
1003
1004     if (listen(sockfd, 5) < 0) {
1005         perror("listen()");
1006         free(resolved);
1007         return -1;
1008     }
1009
1010     current_socketpath = resolved;
1011     return sockfd;
1012 }