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