]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Optionally change i3bar color on focused output, implements #2020
[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_background);
667     YSTR_IF_SET(focused_statusline);
668     YSTR_IF_SET(focused_separator);
669     YSTR_IF_SET(focused_workspace_border);
670     YSTR_IF_SET(focused_workspace_bg);
671     YSTR_IF_SET(focused_workspace_text);
672     YSTR_IF_SET(active_workspace_border);
673     YSTR_IF_SET(active_workspace_bg);
674     YSTR_IF_SET(active_workspace_text);
675     YSTR_IF_SET(inactive_workspace_border);
676     YSTR_IF_SET(inactive_workspace_bg);
677     YSTR_IF_SET(inactive_workspace_text);
678     YSTR_IF_SET(urgent_workspace_border);
679     YSTR_IF_SET(urgent_workspace_bg);
680     YSTR_IF_SET(urgent_workspace_text);
681     YSTR_IF_SET(binding_mode_border);
682     YSTR_IF_SET(binding_mode_bg);
683     YSTR_IF_SET(binding_mode_text);
684     y(map_close);
685
686     y(map_close);
687 #undef YSTR_IF_SET
688 }
689
690 IPC_HANDLER(tree) {
691     setlocale(LC_NUMERIC, "C");
692     yajl_gen gen = ygenalloc();
693     dump_node(gen, croot, false);
694     setlocale(LC_NUMERIC, "");
695
696     const unsigned char *payload;
697     ylength length;
698     y(get_buf, &payload, &length);
699
700     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
701     y(free);
702 }
703
704 /*
705  * Formats the reply message for a GET_WORKSPACES request and sends it to the
706  * client
707  *
708  */
709 IPC_HANDLER(get_workspaces) {
710     yajl_gen gen = ygenalloc();
711     y(array_open);
712
713     Con *focused_ws = con_get_workspace(focused);
714
715     Con *output;
716     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
717         if (con_is_internal(output))
718             continue;
719         Con *ws;
720         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
721             assert(ws->type == CT_WORKSPACE);
722             y(map_open);
723
724             ystr("num");
725             y(integer, ws->num);
726
727             ystr("name");
728             ystr(ws->name);
729
730             ystr("visible");
731             y(bool, workspace_is_visible(ws));
732
733             ystr("focused");
734             y(bool, ws == focused_ws);
735
736             ystr("rect");
737             y(map_open);
738             ystr("x");
739             y(integer, ws->rect.x);
740             ystr("y");
741             y(integer, ws->rect.y);
742             ystr("width");
743             y(integer, ws->rect.width);
744             ystr("height");
745             y(integer, ws->rect.height);
746             y(map_close);
747
748             ystr("output");
749             ystr(output->name);
750
751             ystr("urgent");
752             y(bool, ws->urgent);
753
754             y(map_close);
755         }
756     }
757
758     y(array_close);
759
760     const unsigned char *payload;
761     ylength length;
762     y(get_buf, &payload, &length);
763
764     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
765     y(free);
766 }
767
768 /*
769  * Formats the reply message for a GET_OUTPUTS request and sends it to the
770  * client
771  *
772  */
773 IPC_HANDLER(get_outputs) {
774     yajl_gen gen = ygenalloc();
775     y(array_open);
776
777     Output *output;
778     TAILQ_FOREACH(output, &outputs, outputs) {
779         y(map_open);
780
781         ystr("name");
782         ystr(output->name);
783
784         ystr("active");
785         y(bool, output->active);
786
787         ystr("primary");
788         y(bool, output->primary);
789
790         ystr("rect");
791         y(map_open);
792         ystr("x");
793         y(integer, output->rect.x);
794         ystr("y");
795         y(integer, output->rect.y);
796         ystr("width");
797         y(integer, output->rect.width);
798         ystr("height");
799         y(integer, output->rect.height);
800         y(map_close);
801
802         ystr("current_workspace");
803         Con *ws = NULL;
804         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
805             ystr(ws->name);
806         else
807             y(null);
808
809         y(map_close);
810     }
811
812     y(array_close);
813
814     const unsigned char *payload;
815     ylength length;
816     y(get_buf, &payload, &length);
817
818     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
819     y(free);
820 }
821
822 /*
823  * Formats the reply message for a GET_MARKS request and sends it to the
824  * client
825  *
826  */
827 IPC_HANDLER(get_marks) {
828     yajl_gen gen = ygenalloc();
829     y(array_open);
830
831     Con *con;
832     TAILQ_FOREACH(con, &all_cons, all_cons) {
833         mark_t *mark;
834         TAILQ_FOREACH(mark, &(con->marks_head), marks) {
835             ystr(mark->name);
836         }
837     }
838
839     y(array_close);
840
841     const unsigned char *payload;
842     ylength length;
843     y(get_buf, &payload, &length);
844
845     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
846     y(free);
847 }
848
849 /*
850  * Returns the version of i3
851  *
852  */
853 IPC_HANDLER(get_version) {
854     yajl_gen gen = ygenalloc();
855     y(map_open);
856
857     ystr("major");
858     y(integer, MAJOR_VERSION);
859
860     ystr("minor");
861     y(integer, MINOR_VERSION);
862
863     ystr("patch");
864     y(integer, PATCH_VERSION);
865
866     ystr("human_readable");
867     ystr(i3_version);
868
869     ystr("loaded_config_file_name");
870     ystr(current_configpath);
871
872     y(map_close);
873
874     const unsigned char *payload;
875     ylength length;
876     y(get_buf, &payload, &length);
877
878     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
879     y(free);
880 }
881
882 /*
883  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
884  * client.
885  *
886  */
887 IPC_HANDLER(get_bar_config) {
888     yajl_gen gen = ygenalloc();
889
890     /* If no ID was passed, we return a JSON array with all IDs */
891     if (message_size == 0) {
892         y(array_open);
893         Barconfig *current;
894         TAILQ_FOREACH(current, &barconfigs, configs) {
895             ystr(current->id);
896         }
897         y(array_close);
898
899         const unsigned char *payload;
900         ylength length;
901         y(get_buf, &payload, &length);
902
903         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
904         y(free);
905         return;
906     }
907
908     /* To get a properly terminated buffer, we copy
909      * message_size bytes out of the buffer */
910     char *bar_id = NULL;
911     sasprintf(&bar_id, "%.*s", message_size, message);
912     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
913     Barconfig *current, *config = NULL;
914     TAILQ_FOREACH(current, &barconfigs, configs) {
915         if (strcmp(current->id, bar_id) != 0)
916             continue;
917
918         config = current;
919         break;
920     }
921     free(bar_id);
922
923     if (!config) {
924         /* If we did not find a config for the given ID, the reply will contain
925          * a null 'id' field. */
926         y(map_open);
927
928         ystr("id");
929         y(null);
930
931         y(map_close);
932     } else {
933         dump_bar_config(gen, config);
934     }
935
936     const unsigned char *payload;
937     ylength length;
938     y(get_buf, &payload, &length);
939
940     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
941     y(free);
942 }
943
944 /*
945  * Callback for the YAJL parser (will be called when a string is parsed).
946  *
947  */
948 static int add_subscription(void *extra, const unsigned char *s,
949                             ylength len) {
950     ipc_client *client = extra;
951
952     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
953     int event = client->num_events;
954
955     client->num_events++;
956     client->events = srealloc(client->events, client->num_events * sizeof(char *));
957     /* We copy the string because it is not null-terminated and strndup()
958      * is missing on some BSD systems */
959     client->events[event] = scalloc(len + 1, 1);
960     memcpy(client->events[event], s, len);
961
962     DLOG("client is now subscribed to:\n");
963     for (int i = 0; i < client->num_events; i++)
964         DLOG("event %s\n", client->events[i]);
965     DLOG("(done)\n");
966
967     return 1;
968 }
969
970 /*
971  * Subscribes this connection to the event types which were given as a JSON
972  * serialized array in the payload field of the message.
973  *
974  */
975 IPC_HANDLER(subscribe) {
976     yajl_handle p;
977     yajl_status stat;
978     ipc_client *current, *client = NULL;
979
980     /* Search the ipc_client structure for this connection */
981     TAILQ_FOREACH(current, &all_clients, clients) {
982         if (current->fd != fd)
983             continue;
984
985         client = current;
986         break;
987     }
988
989     if (client == NULL) {
990         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
991         return;
992     }
993
994     /* Setup the JSON parser */
995     static yajl_callbacks callbacks = {
996         .yajl_string = add_subscription,
997     };
998
999     p = yalloc(&callbacks, (void *)client);
1000     stat = yajl_parse(p, (const unsigned char *)message, message_size);
1001     if (stat != yajl_status_ok) {
1002         unsigned char *err;
1003         err = yajl_get_error(p, true, (const unsigned char *)message,
1004                              message_size);
1005         ELOG("YAJL parse error: %s\n", err);
1006         yajl_free_error(p, err);
1007
1008         const char *reply = "{\"success\":false}";
1009         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1010         yajl_free(p);
1011         return;
1012     }
1013     yajl_free(p);
1014     const char *reply = "{\"success\":true}";
1015     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1016 }
1017
1018 /* The index of each callback function corresponds to the numeric
1019  * value of the message type (see include/i3/ipc.h) */
1020 handler_t handlers[8] = {
1021     handle_command,
1022     handle_get_workspaces,
1023     handle_subscribe,
1024     handle_get_outputs,
1025     handle_tree,
1026     handle_get_marks,
1027     handle_get_bar_config,
1028     handle_get_version,
1029 };
1030
1031 /*
1032  * Handler for activity on a client connection, receives a message from a
1033  * client.
1034  *
1035  * For now, the maximum message size is 2048. I’m not sure for what the
1036  * IPC interface will be used in the future, thus I’m not implementing a
1037  * mechanism for arbitrarily long messages, as it seems like overkill
1038  * at the moment.
1039  *
1040  */
1041 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
1042     uint32_t message_type;
1043     uint32_t message_length;
1044     uint8_t *message = NULL;
1045
1046     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
1047     /* EOF or other error */
1048     if (ret < 0) {
1049         /* Was this a spurious read? See ev(3) */
1050         if (ret == -1 && errno == EAGAIN) {
1051             FREE(message);
1052             return;
1053         }
1054
1055         /* If not, there was some kind of error. We don’t bother
1056          * and close the connection */
1057         close(w->fd);
1058
1059         /* Delete the client from the list of clients */
1060         ipc_client *current;
1061         TAILQ_FOREACH(current, &all_clients, clients) {
1062             if (current->fd != w->fd)
1063                 continue;
1064
1065             for (int i = 0; i < current->num_events; i++)
1066                 free(current->events[i]);
1067             /* We can call TAILQ_REMOVE because we break out of the
1068              * TAILQ_FOREACH afterwards */
1069             TAILQ_REMOVE(&all_clients, current, clients);
1070             free(current);
1071             break;
1072         }
1073
1074         ev_io_stop(EV_A_ w);
1075         free(w);
1076         FREE(message);
1077
1078         DLOG("IPC: client disconnected\n");
1079         return;
1080     }
1081
1082     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1083         DLOG("Unhandled message type: %d\n", message_type);
1084     else {
1085         handler_t h = handlers[message_type];
1086         h(w->fd, message, 0, message_length, message_type);
1087     }
1088
1089     FREE(message);
1090 }
1091
1092 /*
1093  * Handler for activity on the listening socket, meaning that a new client
1094  * has just connected and we should accept() him. Sets up the event handler
1095  * for activity on the new connection and inserts the file descriptor into
1096  * the list of clients.
1097  *
1098  */
1099 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1100     struct sockaddr_un peer;
1101     socklen_t len = sizeof(struct sockaddr_un);
1102     int client;
1103     if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1104         if (errno == EINTR)
1105             return;
1106         else
1107             perror("accept()");
1108         return;
1109     }
1110
1111     /* Close this file descriptor on exec() */
1112     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1113
1114     set_nonblock(client);
1115
1116     struct ev_io *package = scalloc(1, sizeof(struct ev_io));
1117     ev_io_init(package, ipc_receive_message, client, EV_READ);
1118     ev_io_start(EV_A_ package);
1119
1120     DLOG("IPC: new client connected on fd %d\n", w->fd);
1121
1122     ipc_client *new = scalloc(1, sizeof(ipc_client));
1123     new->fd = client;
1124
1125     TAILQ_INSERT_TAIL(&all_clients, new, clients);
1126 }
1127
1128 /*
1129  * Creates the UNIX domain socket at the given path, sets it to non-blocking
1130  * mode, bind()s and listen()s on it.
1131  *
1132  */
1133 int ipc_create_socket(const char *filename) {
1134     int sockfd;
1135
1136     FREE(current_socketpath);
1137
1138     char *resolved = resolve_tilde(filename);
1139     DLOG("Creating IPC-socket at %s\n", resolved);
1140     char *copy = sstrdup(resolved);
1141     const char *dir = dirname(copy);
1142     if (!path_exists(dir))
1143         mkdirp(dir, DEFAULT_DIR_MODE);
1144     free(copy);
1145
1146     /* Unlink the unix domain socket before */
1147     unlink(resolved);
1148
1149     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1150         perror("socket()");
1151         free(resolved);
1152         return -1;
1153     }
1154
1155     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1156
1157     struct sockaddr_un addr;
1158     memset(&addr, 0, sizeof(struct sockaddr_un));
1159     addr.sun_family = AF_LOCAL;
1160     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1161     if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1162         perror("bind()");
1163         free(resolved);
1164         return -1;
1165     }
1166
1167     set_nonblock(sockfd);
1168
1169     if (listen(sockfd, 5) < 0) {
1170         perror("listen()");
1171         free(resolved);
1172         return -1;
1173     }
1174
1175     current_socketpath = resolved;
1176     return sockfd;
1177 }
1178
1179 /*
1180  * Generates a json workspace event. Returns a dynamically allocated yajl
1181  * generator. Free with yajl_gen_free().
1182  */
1183 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1184     setlocale(LC_NUMERIC, "C");
1185     yajl_gen gen = ygenalloc();
1186
1187     y(map_open);
1188
1189     ystr("change");
1190     ystr(change);
1191
1192     ystr("current");
1193     if (current == NULL)
1194         y(null);
1195     else
1196         dump_node(gen, current, false);
1197
1198     ystr("old");
1199     if (old == NULL)
1200         y(null);
1201     else
1202         dump_node(gen, old, false);
1203
1204     y(map_close);
1205
1206     setlocale(LC_NUMERIC, "");
1207
1208     return gen;
1209 }
1210
1211 /*
1212  * For the workspace events we send, along with the usual "change" field, also
1213  * the workspace container in "current". For focus events, we send the
1214  * previously focused workspace in "old".
1215  */
1216 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1217     yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1218
1219     const unsigned char *payload;
1220     ylength length;
1221     y(get_buf, &payload, &length);
1222
1223     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1224
1225     y(free);
1226 }
1227
1228 /**
1229  * For the window events we send, along the usual "change" field,
1230  * also the window container, in "container".
1231  */
1232 void ipc_send_window_event(const char *property, Con *con) {
1233     DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1234          property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1235
1236     setlocale(LC_NUMERIC, "C");
1237     yajl_gen gen = ygenalloc();
1238
1239     y(map_open);
1240
1241     ystr("change");
1242     ystr(property);
1243
1244     ystr("container");
1245     dump_node(gen, con, false);
1246
1247     y(map_close);
1248
1249     const unsigned char *payload;
1250     ylength length;
1251     y(get_buf, &payload, &length);
1252
1253     ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1254     y(free);
1255     setlocale(LC_NUMERIC, "");
1256 }
1257
1258 /**
1259  * For the barconfig update events, we send the serialized barconfig.
1260  */
1261 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1262     DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1263     setlocale(LC_NUMERIC, "C");
1264     yajl_gen gen = ygenalloc();
1265
1266     dump_bar_config(gen, barconfig);
1267
1268     const unsigned char *payload;
1269     ylength length;
1270     y(get_buf, &payload, &length);
1271
1272     ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1273     y(free);
1274     setlocale(LC_NUMERIC, "");
1275 }
1276
1277 /*
1278  * For the binding events, we send the serialized binding struct.
1279  */
1280 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1281     DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1282
1283     setlocale(LC_NUMERIC, "C");
1284
1285     yajl_gen gen = ygenalloc();
1286
1287     y(map_open);
1288
1289     ystr("change");
1290     ystr(event_type);
1291
1292     ystr("binding");
1293     dump_binding(gen, bind);
1294
1295     y(map_close);
1296
1297     const unsigned char *payload;
1298     ylength length;
1299     y(get_buf, &payload, &length);
1300
1301     ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1302
1303     y(free);
1304     setlocale(LC_NUMERIC, "");
1305 }