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