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