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