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