]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Merge branch 'master' 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("floating");
278     switch (con->floating) {
279         case FLOATING_AUTO_OFF:
280             ystr("auto_off");
281             break;
282         case FLOATING_AUTO_ON:
283             ystr("auto_on");
284             break;
285         case FLOATING_USER_OFF:
286             ystr("user_off");
287             break;
288         case FLOATING_USER_ON:
289             ystr("user_on");
290             break;
291     }
292
293     ystr("swallows");
294     y(array_open);
295     Match *match;
296     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
297         if (match->dock != -1) {
298             y(map_open);
299             ystr("dock");
300             y(integer, match->dock);
301             ystr("insert_where");
302             y(integer, match->insert_where);
303             y(map_close);
304         }
305
306         /* TODO: the other swallow keys */
307     }
308
309     if (inplace_restart) {
310         if (con->window != NULL) {
311             y(map_open);
312             ystr("id");
313             y(integer, con->window->id);
314             y(map_close);
315         }
316     }
317     y(array_close);
318
319     y(map_close);
320 }
321
322 IPC_HANDLER(tree) {
323     setlocale(LC_NUMERIC, "C");
324 #if YAJL_MAJOR >= 2
325     yajl_gen gen = yajl_gen_alloc(NULL);
326 #else
327     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
328 #endif
329     dump_node(gen, croot, false);
330     setlocale(LC_NUMERIC, "");
331
332     const unsigned char *payload;
333 #if YAJL_MAJOR >= 2
334     size_t length;
335 #else
336     unsigned int length;
337 #endif
338     y(get_buf, &payload, &length);
339
340     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
341     y(free);
342 }
343
344
345 /*
346  * Formats the reply message for a GET_WORKSPACES request and sends it to the
347  * client
348  *
349  */
350 IPC_HANDLER(get_workspaces) {
351 #if YAJL_MAJOR >= 2
352     yajl_gen gen = yajl_gen_alloc(NULL);
353 #else
354     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
355 #endif
356     y(array_open);
357
358     Con *focused_ws = con_get_workspace(focused);
359
360     Con *output;
361     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
362         if (output->name[0] == '_' && output->name[1] == '_')
363             continue;
364         Con *ws;
365         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
366             assert(ws->type == CT_WORKSPACE);
367             y(map_open);
368
369             ystr("num");
370             if (ws->num == -1)
371                 y(null);
372             else y(integer, ws->num);
373
374             ystr("name");
375             ystr(ws->name);
376
377             ystr("visible");
378             y(bool, workspace_is_visible(ws));
379
380             ystr("focused");
381             y(bool, ws == focused_ws);
382
383             ystr("rect");
384             y(map_open);
385             ystr("x");
386             y(integer, ws->rect.x);
387             ystr("y");
388             y(integer, ws->rect.y);
389             ystr("width");
390             y(integer, ws->rect.width);
391             ystr("height");
392             y(integer, ws->rect.height);
393             y(map_close);
394
395             ystr("output");
396             ystr(output->name);
397
398             ystr("urgent");
399             y(bool, ws->urgent);
400
401             y(map_close);
402         }
403     }
404
405     y(array_close);
406
407     const unsigned char *payload;
408 #if YAJL_MAJOR >= 2
409     size_t length;
410 #else
411     unsigned int length;
412 #endif
413     y(get_buf, &payload, &length);
414
415     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
416     y(free);
417 }
418
419 /*
420  * Formats the reply message for a GET_OUTPUTS request and sends it to the
421  * client
422  *
423  */
424 IPC_HANDLER(get_outputs) {
425 #if YAJL_MAJOR >= 2
426     yajl_gen gen = yajl_gen_alloc(NULL);
427 #else
428     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
429 #endif
430     y(array_open);
431
432     Output *output;
433     TAILQ_FOREACH(output, &outputs, outputs) {
434         y(map_open);
435
436         ystr("name");
437         ystr(output->name);
438
439         ystr("active");
440         y(bool, output->active);
441
442         ystr("rect");
443         y(map_open);
444         ystr("x");
445         y(integer, output->rect.x);
446         ystr("y");
447         y(integer, output->rect.y);
448         ystr("width");
449         y(integer, output->rect.width);
450         ystr("height");
451         y(integer, output->rect.height);
452         y(map_close);
453
454         ystr("current_workspace");
455         Con *ws = NULL;
456         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
457             ystr(ws->name);
458         else y(null);
459
460         y(map_close);
461     }
462
463     y(array_close);
464
465     const unsigned char *payload;
466 #if YAJL_MAJOR >= 2
467     size_t length;
468 #else
469     unsigned int length;
470 #endif
471     y(get_buf, &payload, &length);
472
473     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
474     y(free);
475 }
476
477 /*
478  * Formats the reply message for a GET_MARKS request and sends it to the
479  * client
480  *
481  */
482 IPC_HANDLER(get_marks) {
483 #if YAJL_MAJOR >= 2
484     yajl_gen gen = yajl_gen_alloc(NULL);
485 #else
486     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
487 #endif
488     y(array_open);
489
490     Con *con;
491     TAILQ_FOREACH(con, &all_cons, all_cons)
492         if (con->mark != NULL)
493             ystr(con->mark);
494
495     y(array_close);
496
497     const unsigned char *payload;
498 #if YAJL_MAJOR >= 2
499     size_t length;
500 #else
501     unsigned int length;
502 #endif
503     y(get_buf, &payload, &length);
504
505     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
506     y(free);
507 }
508
509 /*
510  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
511  * client.
512  *
513  */
514 IPC_HANDLER(get_bar_config) {
515 #if YAJL_MAJOR >= 2
516     yajl_gen gen = yajl_gen_alloc(NULL);
517 #else
518     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
519 #endif
520
521     /* If no ID was passed, we return a JSON array with all IDs */
522     if (message_size == 0) {
523         y(array_open);
524         Barconfig *current;
525         TAILQ_FOREACH(current, &barconfigs, configs) {
526             ystr(current->id);
527         }
528         y(array_close);
529
530         const unsigned char *payload;
531 #if YAJL_MAJOR >= 2
532         size_t length;
533 #else
534         unsigned int length;
535 #endif
536         y(get_buf, &payload, &length);
537
538         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
539         y(free);
540         return;
541     }
542
543     /* To get a properly terminated buffer, we copy
544      * message_size bytes out of the buffer */
545     char *bar_id = scalloc(message_size + 1);
546     strncpy(bar_id, (const char*)message, message_size);
547     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
548     Barconfig *current, *config = NULL;
549     TAILQ_FOREACH(current, &barconfigs, configs) {
550         if (strcmp(current->id, bar_id) != 0)
551             continue;
552
553         config = current;
554         break;
555     }
556
557     y(map_open);
558
559     if (!config) {
560         /* If we did not find a config for the given ID, the reply will contain
561          * a null 'id' field. */
562         ystr("id");
563         y(null);
564     } else {
565         ystr("id");
566         ystr(config->id);
567
568         if (config->num_outputs > 0) {
569             ystr("outputs");
570             y(array_open);
571             for (int c = 0; c < config->num_outputs; c++)
572                 ystr(config->outputs[c]);
573             y(array_close);
574         }
575
576 #define YSTR_IF_SET(name) \
577         do { \
578             if (config->name) { \
579                 ystr( # name); \
580                 ystr(config->name); \
581             } \
582         } while (0)
583
584         YSTR_IF_SET(tray_output);
585         YSTR_IF_SET(socket_path);
586
587         ystr("mode");
588         if (config->mode == M_HIDE)
589             ystr("hide");
590         else ystr("dock");
591
592         ystr("modifier");
593         switch (config->modifier) {
594             case M_CONTROL:
595                 ystr("ctrl");
596                 break;
597             case M_SHIFT:
598                 ystr("shift");
599                 break;
600             case M_MOD1:
601                 ystr("Mod1");
602                 break;
603             case M_MOD2:
604                 ystr("Mod2");
605                 break;
606             case M_MOD3:
607                 ystr("Mod3");
608                 break;
609             /*
610             case M_MOD4:
611                 ystr("Mod4");
612                 break;
613             */
614             case M_MOD5:
615                 ystr("Mod5");
616                 break;
617             default:
618                 ystr("Mod4");
619                 break;
620         }
621
622         ystr("position");
623         if (config->position == P_BOTTOM)
624             ystr("bottom");
625         else ystr("top");
626
627         YSTR_IF_SET(status_command);
628         YSTR_IF_SET(font);
629
630         ystr("workspace_buttons");
631         y(bool, !config->hide_workspace_buttons);
632
633         ystr("verbose");
634         y(bool, config->verbose);
635
636 #undef YSTR_IF_SET
637 #define YSTR_IF_SET(name) \
638         do { \
639             if (config->colors.name) { \
640                 ystr( # name); \
641                 ystr(config->colors.name); \
642             } \
643         } while (0)
644
645         ystr("colors");
646         y(map_open);
647         YSTR_IF_SET(background);
648         YSTR_IF_SET(statusline);
649         YSTR_IF_SET(focused_workspace_border);
650         YSTR_IF_SET(focused_workspace_bg);
651         YSTR_IF_SET(focused_workspace_text);
652         YSTR_IF_SET(active_workspace_border);
653         YSTR_IF_SET(active_workspace_bg);
654         YSTR_IF_SET(active_workspace_text);
655         YSTR_IF_SET(inactive_workspace_border);
656         YSTR_IF_SET(inactive_workspace_bg);
657         YSTR_IF_SET(inactive_workspace_text);
658         YSTR_IF_SET(urgent_workspace_border);
659         YSTR_IF_SET(urgent_workspace_bg);
660         YSTR_IF_SET(urgent_workspace_text);
661         y(map_close);
662
663 #undef YSTR_IF_SET
664     }
665
666     y(map_close);
667
668     const unsigned char *payload;
669 #if YAJL_MAJOR >= 2
670     size_t length;
671 #else
672     unsigned int length;
673 #endif
674     y(get_buf, &payload, &length);
675
676     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
677     y(free);
678 }
679
680 /*
681  * Callback for the YAJL parser (will be called when a string is parsed).
682  *
683  */
684 #if YAJL_MAJOR < 2
685 static int add_subscription(void *extra, const unsigned char *s,
686                             unsigned int len) {
687 #else
688 static int add_subscription(void *extra, const unsigned char *s,
689                             size_t len) {
690 #endif
691     ipc_client *client = extra;
692
693     DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
694     int event = client->num_events;
695
696     client->num_events++;
697     client->events = realloc(client->events, client->num_events * sizeof(char*));
698     /* We copy the string because it is not null-terminated and strndup()
699      * is missing on some BSD systems */
700     client->events[event] = scalloc(len+1);
701     memcpy(client->events[event], s, len);
702
703     DLOG("client is now subscribed to:\n");
704     for (int i = 0; i < client->num_events; i++)
705         DLOG("event %s\n", client->events[i]);
706     DLOG("(done)\n");
707
708     return 1;
709 }
710
711 /*
712  * Subscribes this connection to the event types which were given as a JSON
713  * serialized array in the payload field of the message.
714  *
715  */
716 IPC_HANDLER(subscribe) {
717     yajl_handle p;
718     yajl_callbacks callbacks;
719     yajl_status stat;
720     ipc_client *current, *client = NULL;
721
722     /* Search the ipc_client structure for this connection */
723     TAILQ_FOREACH(current, &all_clients, clients) {
724         if (current->fd != fd)
725             continue;
726
727         client = current;
728         break;
729     }
730
731     if (client == NULL) {
732         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
733         return;
734     }
735
736     /* Setup the JSON parser */
737     memset(&callbacks, 0, sizeof(yajl_callbacks));
738     callbacks.yajl_string = add_subscription;
739
740 #if YAJL_MAJOR >= 2
741     p = yajl_alloc(&callbacks, NULL, (void*)client);
742 #else
743     p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
744 #endif
745     stat = yajl_parse(p, (const unsigned char*)message, message_size);
746     if (stat != yajl_status_ok) {
747         unsigned char *err;
748         err = yajl_get_error(p, true, (const unsigned char*)message,
749                              message_size);
750         ELOG("YAJL parse error: %s\n", err);
751         yajl_free_error(p, err);
752
753         const char *reply = "{\"success\":false}";
754         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
755         yajl_free(p);
756         return;
757     }
758     yajl_free(p);
759     const char *reply = "{\"success\":true}";
760     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
761 }
762
763 /* The index of each callback function corresponds to the numeric
764  * value of the message type (see include/i3/ipc.h) */
765 handler_t handlers[7] = {
766     handle_command,
767     handle_get_workspaces,
768     handle_subscribe,
769     handle_get_outputs,
770     handle_tree,
771     handle_get_marks,
772     handle_get_bar_config,
773 };
774
775 /*
776  * Handler for activity on a client connection, receives a message from a
777  * client.
778  *
779  * For now, the maximum message size is 2048. I’m not sure for what the
780  * IPC interface will be used in the future, thus I’m not implementing a
781  * mechanism for arbitrarily long messages, as it seems like overkill
782  * at the moment.
783  *
784  */
785 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
786     char buf[2048];
787     int n = read(w->fd, buf, sizeof(buf));
788
789     /* On error or an empty message, we close the connection */
790     if (n <= 0) {
791 #if 0
792         /* FIXME: I get these when closing a client socket,
793          * therefore we just treat them as an error. Is this
794          * correct? */
795         if (errno == EAGAIN || errno == EWOULDBLOCK)
796                 return;
797 #endif
798
799         /* If not, there was some kind of error. We don’t bother
800          * and close the connection */
801         close(w->fd);
802
803         /* Delete the client from the list of clients */
804         ipc_client *current;
805         TAILQ_FOREACH(current, &all_clients, clients) {
806             if (current->fd != w->fd)
807                 continue;
808
809             for (int i = 0; i < current->num_events; i++)
810                 free(current->events[i]);
811             /* We can call TAILQ_REMOVE because we break out of the
812              * TAILQ_FOREACH afterwards */
813             TAILQ_REMOVE(&all_clients, current, clients);
814             free(current);
815             break;
816         }
817
818         ev_io_stop(EV_A_ w);
819         free(w);
820
821         DLOG("IPC: client disconnected\n");
822         return;
823     }
824
825     /* Terminate the message correctly */
826     buf[n] = '\0';
827
828     /* Check if the message starts with the i3 IPC magic code */
829     if (n < strlen(I3_IPC_MAGIC)) {
830         DLOG("IPC: message too short, ignoring\n");
831         return;
832     }
833
834     if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
835         DLOG("IPC: message does not start with the IPC magic\n");
836         return;
837     }
838
839     uint8_t *message = (uint8_t*)buf;
840     while (n > 0) {
841         DLOG("IPC: n = %d\n", n);
842         message += strlen(I3_IPC_MAGIC);
843         n -= strlen(I3_IPC_MAGIC);
844
845         /* The next 32 bit after the magic are the message size */
846         uint32_t message_size;
847         memcpy(&message_size, (uint32_t*)message, sizeof(uint32_t));
848         message += sizeof(uint32_t);
849         n -= sizeof(uint32_t);
850
851         if (message_size > n) {
852             DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
853             return;
854         }
855
856         /* The last 32 bits of the header are the message type */
857         uint32_t message_type;
858         memcpy(&message_type, (uint32_t*)message, sizeof(uint32_t));
859         message += sizeof(uint32_t);
860         n -= sizeof(uint32_t);
861
862         if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
863             DLOG("Unhandled message type: %d\n", message_type);
864         else {
865             handler_t h = handlers[message_type];
866             h(w->fd, message, n, message_size, message_type);
867         }
868         n -= message_size;
869         message += message_size;
870     }
871 }
872
873 /*
874  * Handler for activity on the listening socket, meaning that a new client
875  * has just connected and we should accept() him. Sets up the event handler
876  * for activity on the new connection and inserts the file descriptor into
877  * the list of clients.
878  *
879  */
880 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
881     struct sockaddr_un peer;
882     socklen_t len = sizeof(struct sockaddr_un);
883     int client;
884     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
885         if (errno == EINTR)
886             return;
887         else perror("accept()");
888         return;
889     }
890
891     /* Close this file descriptor on exec() */
892     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
893
894     set_nonblock(client);
895
896     struct ev_io *package = scalloc(sizeof(struct ev_io));
897     ev_io_init(package, ipc_receive_message, client, EV_READ);
898     ev_io_start(EV_A_ package);
899
900     DLOG("IPC: new client connected on fd %d\n", w->fd);
901
902     ipc_client *new = scalloc(sizeof(ipc_client));
903     new->fd = client;
904
905     TAILQ_INSERT_TAIL(&all_clients, new, clients);
906 }
907
908 /*
909  * Creates the UNIX domain socket at the given path, sets it to non-blocking
910  * mode, bind()s and listen()s on it.
911  *
912  */
913 int ipc_create_socket(const char *filename) {
914     int sockfd;
915
916     FREE(current_socketpath);
917
918     char *resolved = resolve_tilde(filename);
919     DLOG("Creating IPC-socket at %s\n", resolved);
920     char *copy = sstrdup(resolved);
921     const char *dir = dirname(copy);
922     if (!path_exists(dir))
923         mkdirp(dir);
924     free(copy);
925
926     /* Unlink the unix domain socket before */
927     unlink(resolved);
928
929     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
930         perror("socket()");
931         free(resolved);
932         return -1;
933     }
934
935     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
936
937     struct sockaddr_un addr;
938     memset(&addr, 0, sizeof(struct sockaddr_un));
939     addr.sun_family = AF_LOCAL;
940     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
941     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
942         perror("bind()");
943         free(resolved);
944         return -1;
945     }
946
947     set_nonblock(sockfd);
948
949     if (listen(sockfd, 5) < 0) {
950         perror("listen()");
951         free(resolved);
952         return -1;
953     }
954
955     current_socketpath = resolved;
956     return sockfd;
957 }