]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Merge pull request #2649 from s3rb31/next
[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(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 void dump_bar_config(yajl_gen gen, Barconfig *config) {
583     y(map_open);
584
585     ystr("id");
586     ystr(config->id);
587
588     if (config->num_outputs > 0) {
589         ystr("outputs");
590         y(array_open);
591         for (int c = 0; c < config->num_outputs; c++)
592             ystr(config->outputs[c]);
593         y(array_close);
594     }
595
596     if (!TAILQ_EMPTY(&(config->tray_outputs))) {
597         ystr("tray_outputs");
598         y(array_open);
599
600         struct tray_output_t *tray_output;
601         TAILQ_FOREACH(tray_output, &(config->tray_outputs), tray_outputs) {
602             ystr(tray_output->output);
603         }
604
605         y(array_close);
606     }
607
608 #define YSTR_IF_SET(name)       \
609     do {                        \
610         if (config->name) {     \
611             ystr(#name);        \
612             ystr(config->name); \
613         }                       \
614     } while (0)
615
616     ystr("tray_padding");
617     y(integer, config->tray_padding);
618
619     YSTR_IF_SET(socket_path);
620
621     ystr("mode");
622     switch (config->mode) {
623         case M_HIDE:
624             ystr("hide");
625             break;
626         case M_INVISIBLE:
627             ystr("invisible");
628             break;
629         case M_DOCK:
630         default:
631             ystr("dock");
632             break;
633     }
634
635     ystr("hidden_state");
636     switch (config->hidden_state) {
637         case S_SHOW:
638             ystr("show");
639             break;
640         case S_HIDE:
641         default:
642             ystr("hide");
643             break;
644     }
645
646     ystr("modifier");
647     switch (config->modifier) {
648         case M_NONE:
649             ystr("none");
650             break;
651         case M_CONTROL:
652             ystr("ctrl");
653             break;
654         case M_SHIFT:
655             ystr("shift");
656             break;
657         case M_MOD1:
658             ystr("Mod1");
659             break;
660         case M_MOD2:
661             ystr("Mod2");
662             break;
663         case M_MOD3:
664             ystr("Mod3");
665             break;
666         case M_MOD5:
667             ystr("Mod5");
668             break;
669         default:
670             ystr("Mod4");
671             break;
672     }
673
674     dump_bar_bindings(gen, config);
675
676     ystr("position");
677     if (config->position == P_BOTTOM)
678         ystr("bottom");
679     else
680         ystr("top");
681
682     YSTR_IF_SET(status_command);
683     YSTR_IF_SET(font);
684
685     if (config->separator_symbol) {
686         ystr("separator_symbol");
687         ystr(config->separator_symbol);
688     }
689
690     ystr("workspace_buttons");
691     y(bool, !config->hide_workspace_buttons);
692
693     ystr("strip_workspace_numbers");
694     y(bool, config->strip_workspace_numbers);
695
696     ystr("binding_mode_indicator");
697     y(bool, !config->hide_binding_mode_indicator);
698
699     ystr("verbose");
700     y(bool, config->verbose);
701
702 #undef YSTR_IF_SET
703 #define YSTR_IF_SET(name)              \
704     do {                               \
705         if (config->colors.name) {     \
706             ystr(#name);               \
707             ystr(config->colors.name); \
708         }                              \
709     } while (0)
710
711     ystr("colors");
712     y(map_open);
713     YSTR_IF_SET(background);
714     YSTR_IF_SET(statusline);
715     YSTR_IF_SET(separator);
716     YSTR_IF_SET(focused_background);
717     YSTR_IF_SET(focused_statusline);
718     YSTR_IF_SET(focused_separator);
719     YSTR_IF_SET(focused_workspace_border);
720     YSTR_IF_SET(focused_workspace_bg);
721     YSTR_IF_SET(focused_workspace_text);
722     YSTR_IF_SET(active_workspace_border);
723     YSTR_IF_SET(active_workspace_bg);
724     YSTR_IF_SET(active_workspace_text);
725     YSTR_IF_SET(inactive_workspace_border);
726     YSTR_IF_SET(inactive_workspace_bg);
727     YSTR_IF_SET(inactive_workspace_text);
728     YSTR_IF_SET(urgent_workspace_border);
729     YSTR_IF_SET(urgent_workspace_bg);
730     YSTR_IF_SET(urgent_workspace_text);
731     YSTR_IF_SET(binding_mode_border);
732     YSTR_IF_SET(binding_mode_bg);
733     YSTR_IF_SET(binding_mode_text);
734     y(map_close);
735
736     y(map_close);
737 #undef YSTR_IF_SET
738 }
739
740 IPC_HANDLER(tree) {
741     setlocale(LC_NUMERIC, "C");
742     yajl_gen gen = ygenalloc();
743     dump_node(gen, croot, false);
744     setlocale(LC_NUMERIC, "");
745
746     const unsigned char *payload;
747     ylength length;
748     y(get_buf, &payload, &length);
749
750     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
751     y(free);
752 }
753
754 /*
755  * Formats the reply message for a GET_WORKSPACES request and sends it to the
756  * client
757  *
758  */
759 IPC_HANDLER(get_workspaces) {
760     yajl_gen gen = ygenalloc();
761     y(array_open);
762
763     Con *focused_ws = con_get_workspace(focused);
764
765     Con *output;
766     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
767         if (con_is_internal(output))
768             continue;
769         Con *ws;
770         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
771             assert(ws->type == CT_WORKSPACE);
772             y(map_open);
773
774             ystr("num");
775             y(integer, ws->num);
776
777             ystr("name");
778             ystr(ws->name);
779
780             ystr("visible");
781             y(bool, workspace_is_visible(ws));
782
783             ystr("focused");
784             y(bool, ws == focused_ws);
785
786             ystr("rect");
787             y(map_open);
788             ystr("x");
789             y(integer, ws->rect.x);
790             ystr("y");
791             y(integer, ws->rect.y);
792             ystr("width");
793             y(integer, ws->rect.width);
794             ystr("height");
795             y(integer, ws->rect.height);
796             y(map_close);
797
798             ystr("output");
799             ystr(output->name);
800
801             ystr("urgent");
802             y(bool, ws->urgent);
803
804             y(map_close);
805         }
806     }
807
808     y(array_close);
809
810     const unsigned char *payload;
811     ylength length;
812     y(get_buf, &payload, &length);
813
814     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
815     y(free);
816 }
817
818 /*
819  * Formats the reply message for a GET_OUTPUTS request and sends it to the
820  * client
821  *
822  */
823 IPC_HANDLER(get_outputs) {
824     yajl_gen gen = ygenalloc();
825     y(array_open);
826
827     Output *output;
828     TAILQ_FOREACH(output, &outputs, outputs) {
829         y(map_open);
830
831         ystr("name");
832         ystr(output->name);
833
834         ystr("active");
835         y(bool, output->active);
836
837         ystr("primary");
838         y(bool, output->primary);
839
840         ystr("rect");
841         y(map_open);
842         ystr("x");
843         y(integer, output->rect.x);
844         ystr("y");
845         y(integer, output->rect.y);
846         ystr("width");
847         y(integer, output->rect.width);
848         ystr("height");
849         y(integer, output->rect.height);
850         y(map_close);
851
852         ystr("current_workspace");
853         Con *ws = NULL;
854         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
855             ystr(ws->name);
856         else
857             y(null);
858
859         y(map_close);
860     }
861
862     y(array_close);
863
864     const unsigned char *payload;
865     ylength length;
866     y(get_buf, &payload, &length);
867
868     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
869     y(free);
870 }
871
872 /*
873  * Formats the reply message for a GET_MARKS request and sends it to the
874  * client
875  *
876  */
877 IPC_HANDLER(get_marks) {
878     yajl_gen gen = ygenalloc();
879     y(array_open);
880
881     Con *con;
882     TAILQ_FOREACH(con, &all_cons, all_cons) {
883         mark_t *mark;
884         TAILQ_FOREACH(mark, &(con->marks_head), marks) {
885             ystr(mark->name);
886         }
887     }
888
889     y(array_close);
890
891     const unsigned char *payload;
892     ylength length;
893     y(get_buf, &payload, &length);
894
895     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
896     y(free);
897 }
898
899 /*
900  * Returns the version of i3
901  *
902  */
903 IPC_HANDLER(get_version) {
904     yajl_gen gen = ygenalloc();
905     y(map_open);
906
907     ystr("major");
908     y(integer, MAJOR_VERSION);
909
910     ystr("minor");
911     y(integer, MINOR_VERSION);
912
913     ystr("patch");
914     y(integer, PATCH_VERSION);
915
916     ystr("human_readable");
917     ystr(i3_version);
918
919     ystr("loaded_config_file_name");
920     ystr(current_configpath);
921
922     y(map_close);
923
924     const unsigned char *payload;
925     ylength length;
926     y(get_buf, &payload, &length);
927
928     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
929     y(free);
930 }
931
932 /*
933  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
934  * client.
935  *
936  */
937 IPC_HANDLER(get_bar_config) {
938     yajl_gen gen = ygenalloc();
939
940     /* If no ID was passed, we return a JSON array with all IDs */
941     if (message_size == 0) {
942         y(array_open);
943         Barconfig *current;
944         TAILQ_FOREACH(current, &barconfigs, configs) {
945             ystr(current->id);
946         }
947         y(array_close);
948
949         const unsigned char *payload;
950         ylength length;
951         y(get_buf, &payload, &length);
952
953         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
954         y(free);
955         return;
956     }
957
958     /* To get a properly terminated buffer, we copy
959      * message_size bytes out of the buffer */
960     char *bar_id = NULL;
961     sasprintf(&bar_id, "%.*s", message_size, message);
962     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
963     Barconfig *current, *config = NULL;
964     TAILQ_FOREACH(current, &barconfigs, configs) {
965         if (strcmp(current->id, bar_id) != 0)
966             continue;
967
968         config = current;
969         break;
970     }
971     free(bar_id);
972
973     if (!config) {
974         /* If we did not find a config for the given ID, the reply will contain
975          * a null 'id' field. */
976         y(map_open);
977
978         ystr("id");
979         y(null);
980
981         y(map_close);
982     } else {
983         dump_bar_config(gen, config);
984     }
985
986     const unsigned char *payload;
987     ylength length;
988     y(get_buf, &payload, &length);
989
990     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
991     y(free);
992 }
993
994 /*
995  * Returns a list of configured binding modes
996  *
997  */
998 IPC_HANDLER(get_binding_modes) {
999     yajl_gen gen = ygenalloc();
1000
1001     y(array_open);
1002     struct Mode *mode;
1003     SLIST_FOREACH(mode, &modes, modes) {
1004         ystr(mode->name);
1005     }
1006     y(array_close);
1007
1008     const unsigned char *payload;
1009     ylength length;
1010     y(get_buf, &payload, &length);
1011
1012     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BINDING_MODES, payload);
1013     y(free);
1014 }
1015
1016 /*
1017  * Callback for the YAJL parser (will be called when a string is parsed).
1018  *
1019  */
1020 static int add_subscription(void *extra, const unsigned char *s,
1021                             ylength len) {
1022     ipc_client *client = extra;
1023
1024     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
1025     int event = client->num_events;
1026
1027     client->num_events++;
1028     client->events = srealloc(client->events, client->num_events * sizeof(char *));
1029     /* We copy the string because it is not null-terminated and strndup()
1030      * is missing on some BSD systems */
1031     client->events[event] = scalloc(len + 1, 1);
1032     memcpy(client->events[event], s, len);
1033
1034     DLOG("client is now subscribed to:\n");
1035     for (int i = 0; i < client->num_events; i++)
1036         DLOG("event %s\n", client->events[i]);
1037     DLOG("(done)\n");
1038
1039     return 1;
1040 }
1041
1042 /*
1043  * Subscribes this connection to the event types which were given as a JSON
1044  * serialized array in the payload field of the message.
1045  *
1046  */
1047 IPC_HANDLER(subscribe) {
1048     yajl_handle p;
1049     yajl_status stat;
1050     ipc_client *current, *client = NULL;
1051
1052     /* Search the ipc_client structure for this connection */
1053     TAILQ_FOREACH(current, &all_clients, clients) {
1054         if (current->fd != fd)
1055             continue;
1056
1057         client = current;
1058         break;
1059     }
1060
1061     if (client == NULL) {
1062         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
1063         return;
1064     }
1065
1066     /* Setup the JSON parser */
1067     static yajl_callbacks callbacks = {
1068         .yajl_string = add_subscription,
1069     };
1070
1071     p = yalloc(&callbacks, (void *)client);
1072     stat = yajl_parse(p, (const unsigned char *)message, message_size);
1073     if (stat != yajl_status_ok) {
1074         unsigned char *err;
1075         err = yajl_get_error(p, true, (const unsigned char *)message,
1076                              message_size);
1077         ELOG("YAJL parse error: %s\n", err);
1078         yajl_free_error(p, err);
1079
1080         const char *reply = "{\"success\":false}";
1081         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1082         yajl_free(p);
1083         return;
1084     }
1085     yajl_free(p);
1086     const char *reply = "{\"success\":true}";
1087     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1088 }
1089
1090 /* The index of each callback function corresponds to the numeric
1091  * value of the message type (see include/i3/ipc.h) */
1092 handler_t handlers[9] = {
1093     handle_command,
1094     handle_get_workspaces,
1095     handle_subscribe,
1096     handle_get_outputs,
1097     handle_tree,
1098     handle_get_marks,
1099     handle_get_bar_config,
1100     handle_get_version,
1101     handle_get_binding_modes,
1102 };
1103
1104 /*
1105  * Handler for activity on a client connection, receives a message from a
1106  * client.
1107  *
1108  * For now, the maximum message size is 2048. I’m not sure for what the
1109  * IPC interface will be used in the future, thus I’m not implementing a
1110  * mechanism for arbitrarily long messages, as it seems like overkill
1111  * at the moment.
1112  *
1113  */
1114 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
1115     uint32_t message_type;
1116     uint32_t message_length;
1117     uint8_t *message = NULL;
1118
1119     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
1120     /* EOF or other error */
1121     if (ret < 0) {
1122         /* Was this a spurious read? See ev(3) */
1123         if (ret == -1 && errno == EAGAIN) {
1124             FREE(message);
1125             return;
1126         }
1127
1128         /* If not, there was some kind of error. We don’t bother
1129          * and close the connection */
1130         close(w->fd);
1131
1132         /* Delete the client from the list of clients */
1133         ipc_client *current;
1134         TAILQ_FOREACH(current, &all_clients, clients) {
1135             if (current->fd != w->fd)
1136                 continue;
1137
1138             for (int i = 0; i < current->num_events; i++)
1139                 free(current->events[i]);
1140             free(current->events);
1141             /* We can call TAILQ_REMOVE because we break out of the
1142              * TAILQ_FOREACH afterwards */
1143             TAILQ_REMOVE(&all_clients, current, clients);
1144             free(current);
1145             break;
1146         }
1147
1148         ev_io_stop(EV_A_ w);
1149         free(w);
1150         FREE(message);
1151
1152         DLOG("IPC: client disconnected\n");
1153         return;
1154     }
1155
1156     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1157         DLOG("Unhandled message type: %d\n", message_type);
1158     else {
1159         handler_t h = handlers[message_type];
1160         h(w->fd, message, 0, message_length, message_type);
1161     }
1162
1163     FREE(message);
1164 }
1165
1166 /*
1167  * Handler for activity on the listening socket, meaning that a new client
1168  * has just connected and we should accept() him. Sets up the event handler
1169  * for activity on the new connection and inserts the file descriptor into
1170  * the list of clients.
1171  *
1172  */
1173 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1174     struct sockaddr_un peer;
1175     socklen_t len = sizeof(struct sockaddr_un);
1176     int client;
1177     if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1178         if (errno == EINTR)
1179             return;
1180         else
1181             perror("accept()");
1182         return;
1183     }
1184
1185     /* Close this file descriptor on exec() */
1186     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1187
1188     set_nonblock(client);
1189
1190     struct ev_io *package = scalloc(1, sizeof(struct ev_io));
1191     ev_io_init(package, ipc_receive_message, client, EV_READ);
1192     ev_io_start(EV_A_ package);
1193
1194     DLOG("IPC: new client connected on fd %d\n", w->fd);
1195
1196     ipc_client *new = scalloc(1, sizeof(ipc_client));
1197     new->fd = client;
1198
1199     TAILQ_INSERT_TAIL(&all_clients, new, clients);
1200 }
1201
1202 /*
1203  * Creates the UNIX domain socket at the given path, sets it to non-blocking
1204  * mode, bind()s and listen()s on it.
1205  *
1206  */
1207 int ipc_create_socket(const char *filename) {
1208     int sockfd;
1209
1210     FREE(current_socketpath);
1211
1212     char *resolved = resolve_tilde(filename);
1213     DLOG("Creating IPC-socket at %s\n", resolved);
1214     char *copy = sstrdup(resolved);
1215     const char *dir = dirname(copy);
1216     if (!path_exists(dir))
1217         mkdirp(dir, DEFAULT_DIR_MODE);
1218     free(copy);
1219
1220     /* Unlink the unix domain socket before */
1221     unlink(resolved);
1222
1223     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1224         perror("socket()");
1225         free(resolved);
1226         return -1;
1227     }
1228
1229     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1230
1231     struct sockaddr_un addr;
1232     memset(&addr, 0, sizeof(struct sockaddr_un));
1233     addr.sun_family = AF_LOCAL;
1234     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1235     if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1236         perror("bind()");
1237         free(resolved);
1238         return -1;
1239     }
1240
1241     set_nonblock(sockfd);
1242
1243     if (listen(sockfd, 5) < 0) {
1244         perror("listen()");
1245         free(resolved);
1246         return -1;
1247     }
1248
1249     current_socketpath = resolved;
1250     return sockfd;
1251 }
1252
1253 /*
1254  * Generates a json workspace event. Returns a dynamically allocated yajl
1255  * generator. Free with yajl_gen_free().
1256  */
1257 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1258     setlocale(LC_NUMERIC, "C");
1259     yajl_gen gen = ygenalloc();
1260
1261     y(map_open);
1262
1263     ystr("change");
1264     ystr(change);
1265
1266     ystr("current");
1267     if (current == NULL)
1268         y(null);
1269     else
1270         dump_node(gen, current, false);
1271
1272     ystr("old");
1273     if (old == NULL)
1274         y(null);
1275     else
1276         dump_node(gen, old, false);
1277
1278     y(map_close);
1279
1280     setlocale(LC_NUMERIC, "");
1281
1282     return gen;
1283 }
1284
1285 /*
1286  * For the workspace events we send, along with the usual "change" field, also
1287  * the workspace container in "current". For focus events, we send the
1288  * previously focused workspace in "old".
1289  */
1290 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1291     yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1292
1293     const unsigned char *payload;
1294     ylength length;
1295     y(get_buf, &payload, &length);
1296
1297     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1298
1299     y(free);
1300 }
1301
1302 /**
1303  * For the window events we send, along the usual "change" field,
1304  * also the window container, in "container".
1305  */
1306 void ipc_send_window_event(const char *property, Con *con) {
1307     DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1308          property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1309
1310     setlocale(LC_NUMERIC, "C");
1311     yajl_gen gen = ygenalloc();
1312
1313     y(map_open);
1314
1315     ystr("change");
1316     ystr(property);
1317
1318     ystr("container");
1319     dump_node(gen, con, false);
1320
1321     y(map_close);
1322
1323     const unsigned char *payload;
1324     ylength length;
1325     y(get_buf, &payload, &length);
1326
1327     ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1328     y(free);
1329     setlocale(LC_NUMERIC, "");
1330 }
1331
1332 /**
1333  * For the barconfig update events, we send the serialized barconfig.
1334  */
1335 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1336     DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1337     setlocale(LC_NUMERIC, "C");
1338     yajl_gen gen = ygenalloc();
1339
1340     dump_bar_config(gen, barconfig);
1341
1342     const unsigned char *payload;
1343     ylength length;
1344     y(get_buf, &payload, &length);
1345
1346     ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1347     y(free);
1348     setlocale(LC_NUMERIC, "");
1349 }
1350
1351 /*
1352  * For the binding events, we send the serialized binding struct.
1353  */
1354 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1355     DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1356
1357     setlocale(LC_NUMERIC, "C");
1358
1359     yajl_gen gen = ygenalloc();
1360
1361     y(map_open);
1362
1363     ystr("change");
1364     ystr(event_type);
1365
1366     ystr("binding");
1367     dump_binding(gen, bind);
1368
1369     y(map_close);
1370
1371     const unsigned char *payload;
1372     ylength length;
1373     y(get_buf, &payload, &length);
1374
1375     ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1376
1377     y(free);
1378     setlocale(LC_NUMERIC, "");
1379 }