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