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