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