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