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