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