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