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