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