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