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