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