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