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