]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
i3bar: implement custom mouse wheel commands
[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
303         ystr(con->name);
304
305     if (con->type == CT_WORKSPACE) {
306         ystr("num");
307         y(integer, con->num);
308     }
309
310     ystr("window");
311     if (con->window)
312         y(integer, con->window->id);
313     else
314         y(null);
315
316     if (con->window && !inplace_restart) {
317         /* Window properties are useless to preserve when restarting because
318          * they will be queried again anyway. However, for i3-save-tree(1),
319          * they are very useful and save i3-save-tree dealing with X11. */
320         ystr("window_properties");
321         y(map_open);
322
323 #define DUMP_PROPERTY(key, prop_name)         \
324     do {                                      \
325         if (con->window->prop_name != NULL) { \
326             ystr(key);                        \
327             ystr(con->window->prop_name);     \
328         }                                     \
329     } while (0)
330
331         DUMP_PROPERTY("class", class_class);
332         DUMP_PROPERTY("instance", class_instance);
333         DUMP_PROPERTY("window_role", role);
334
335         if (con->window->name != NULL) {
336             ystr("title");
337             ystr(i3string_as_utf8(con->window->name));
338         }
339
340         y(map_close);
341     }
342
343     ystr("nodes");
344     y(array_open);
345     Con *node;
346     if (con->type != CT_DOCKAREA || !inplace_restart) {
347         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
348             dump_node(gen, node, inplace_restart);
349         }
350     }
351     y(array_close);
352
353     ystr("floating_nodes");
354     y(array_open);
355     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
356         dump_node(gen, node, inplace_restart);
357     }
358     y(array_close);
359
360     ystr("focus");
361     y(array_open);
362     TAILQ_FOREACH(node, &(con->focus_head), focused) {
363         y(integer, (long int)node);
364     }
365     y(array_close);
366
367     ystr("fullscreen_mode");
368     y(integer, con->fullscreen_mode);
369
370     ystr("floating");
371     switch (con->floating) {
372         case FLOATING_AUTO_OFF:
373             ystr("auto_off");
374             break;
375         case FLOATING_AUTO_ON:
376             ystr("auto_on");
377             break;
378         case FLOATING_USER_OFF:
379             ystr("user_off");
380             break;
381         case FLOATING_USER_ON:
382             ystr("user_on");
383             break;
384     }
385
386     ystr("swallows");
387     y(array_open);
388     Match *match;
389     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
390         y(map_open);
391         if (match->dock != -1) {
392             ystr("dock");
393             y(integer, match->dock);
394             ystr("insert_where");
395             y(integer, match->insert_where);
396         }
397
398 #define DUMP_REGEX(re_name)                \
399     do {                                   \
400         if (match->re_name != NULL) {      \
401             ystr(#re_name);                \
402             ystr(match->re_name->pattern); \
403         }                                  \
404     } while (0)
405
406         DUMP_REGEX(class);
407         DUMP_REGEX(instance);
408         DUMP_REGEX(window_role);
409         DUMP_REGEX(title);
410
411 #undef DUMP_REGEX
412         y(map_close);
413     }
414
415     if (inplace_restart) {
416         if (con->window != NULL) {
417             y(map_open);
418             ystr("id");
419             y(integer, con->window->id);
420             ystr("restart_mode");
421             y(bool, true);
422             y(map_close);
423         }
424     }
425     y(array_close);
426
427     if (inplace_restart && con->window != NULL) {
428         ystr("depth");
429         y(integer, con->depth);
430     }
431
432     y(map_close);
433 }
434
435 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
436     y(map_open);
437
438     ystr("id");
439     ystr(config->id);
440
441     if (config->num_outputs > 0) {
442         ystr("outputs");
443         y(array_open);
444         for (int c = 0; c < config->num_outputs; c++)
445             ystr(config->outputs[c]);
446         y(array_close);
447     }
448
449 #define YSTR_IF_SET(name)       \
450     do {                        \
451         if (config->name) {     \
452             ystr(#name);        \
453             ystr(config->name); \
454         }                       \
455     } while (0)
456
457     YSTR_IF_SET(tray_output);
458     YSTR_IF_SET(socket_path);
459
460     ystr("mode");
461     switch (config->mode) {
462         case M_HIDE:
463             ystr("hide");
464             break;
465         case M_INVISIBLE:
466             ystr("invisible");
467             break;
468         case M_DOCK:
469         default:
470             ystr("dock");
471             break;
472     }
473
474     ystr("hidden_state");
475     switch (config->hidden_state) {
476         case S_SHOW:
477             ystr("show");
478             break;
479         case S_HIDE:
480         default:
481             ystr("hide");
482             break;
483     }
484
485     ystr("modifier");
486     switch (config->modifier) {
487         case M_CONTROL:
488             ystr("ctrl");
489             break;
490         case M_SHIFT:
491             ystr("shift");
492             break;
493         case M_MOD1:
494             ystr("Mod1");
495             break;
496         case M_MOD2:
497             ystr("Mod2");
498             break;
499         case M_MOD3:
500             ystr("Mod3");
501             break;
502         /*
503                case M_MOD4:
504                ystr("Mod4");
505                break;
506                */
507         case M_MOD5:
508             ystr("Mod5");
509             break;
510         default:
511             ystr("Mod4");
512             break;
513     }
514
515     if (config->wheel_up_cmd) {
516         ystr("wheel_up_cmd");
517         ystr(config->wheel_up_cmd);
518     }
519
520     if (config->wheel_down_cmd) {
521         ystr("wheel_down_cmd");
522         ystr(config->wheel_down_cmd);
523     }
524
525     ystr("position");
526     if (config->position == P_BOTTOM)
527         ystr("bottom");
528     else
529         ystr("top");
530
531     YSTR_IF_SET(status_command);
532     YSTR_IF_SET(font);
533
534     ystr("workspace_buttons");
535     y(bool, !config->hide_workspace_buttons);
536
537     ystr("strip_workspace_numbers");
538     y(bool, config->strip_workspace_numbers);
539
540     ystr("binding_mode_indicator");
541     y(bool, !config->hide_binding_mode_indicator);
542
543     ystr("verbose");
544     y(bool, config->verbose);
545
546 #undef YSTR_IF_SET
547 #define YSTR_IF_SET(name)              \
548     do {                               \
549         if (config->colors.name) {     \
550             ystr(#name);               \
551             ystr(config->colors.name); \
552         }                              \
553     } while (0)
554
555     ystr("colors");
556     y(map_open);
557     YSTR_IF_SET(background);
558     YSTR_IF_SET(statusline);
559     YSTR_IF_SET(separator);
560     YSTR_IF_SET(focused_workspace_border);
561     YSTR_IF_SET(focused_workspace_bg);
562     YSTR_IF_SET(focused_workspace_text);
563     YSTR_IF_SET(active_workspace_border);
564     YSTR_IF_SET(active_workspace_bg);
565     YSTR_IF_SET(active_workspace_text);
566     YSTR_IF_SET(inactive_workspace_border);
567     YSTR_IF_SET(inactive_workspace_bg);
568     YSTR_IF_SET(inactive_workspace_text);
569     YSTR_IF_SET(urgent_workspace_border);
570     YSTR_IF_SET(urgent_workspace_bg);
571     YSTR_IF_SET(urgent_workspace_text);
572     y(map_close);
573
574     y(map_close);
575 #undef YSTR_IF_SET
576 }
577
578 IPC_HANDLER(tree) {
579     setlocale(LC_NUMERIC, "C");
580     yajl_gen gen = ygenalloc();
581     dump_node(gen, croot, false);
582     setlocale(LC_NUMERIC, "");
583
584     const unsigned char *payload;
585     ylength length;
586     y(get_buf, &payload, &length);
587
588     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
589     y(free);
590 }
591
592 /*
593  * Formats the reply message for a GET_WORKSPACES request and sends it to the
594  * client
595  *
596  */
597 IPC_HANDLER(get_workspaces) {
598     yajl_gen gen = ygenalloc();
599     y(array_open);
600
601     Con *focused_ws = con_get_workspace(focused);
602
603     Con *output;
604     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
605         if (con_is_internal(output))
606             continue;
607         Con *ws;
608         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
609             assert(ws->type == CT_WORKSPACE);
610             y(map_open);
611
612             ystr("num");
613             if (ws->num == -1)
614                 y(null);
615             else
616                 y(integer, ws->num);
617
618             ystr("name");
619             ystr(ws->name);
620
621             ystr("visible");
622             y(bool, workspace_is_visible(ws));
623
624             ystr("focused");
625             y(bool, ws == focused_ws);
626
627             ystr("rect");
628             y(map_open);
629             ystr("x");
630             y(integer, ws->rect.x);
631             ystr("y");
632             y(integer, ws->rect.y);
633             ystr("width");
634             y(integer, ws->rect.width);
635             ystr("height");
636             y(integer, ws->rect.height);
637             y(map_close);
638
639             ystr("output");
640             ystr(output->name);
641
642             ystr("urgent");
643             y(bool, ws->urgent);
644
645             y(map_close);
646         }
647     }
648
649     y(array_close);
650
651     const unsigned char *payload;
652     ylength length;
653     y(get_buf, &payload, &length);
654
655     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
656     y(free);
657 }
658
659 /*
660  * Formats the reply message for a GET_OUTPUTS request and sends it to the
661  * client
662  *
663  */
664 IPC_HANDLER(get_outputs) {
665     yajl_gen gen = ygenalloc();
666     y(array_open);
667
668     Output *output;
669     TAILQ_FOREACH(output, &outputs, outputs) {
670         y(map_open);
671
672         ystr("name");
673         ystr(output->name);
674
675         ystr("active");
676         y(bool, output->active);
677
678         ystr("primary");
679         y(bool, output->primary);
680
681         ystr("rect");
682         y(map_open);
683         ystr("x");
684         y(integer, output->rect.x);
685         ystr("y");
686         y(integer, output->rect.y);
687         ystr("width");
688         y(integer, output->rect.width);
689         ystr("height");
690         y(integer, output->rect.height);
691         y(map_close);
692
693         ystr("current_workspace");
694         Con *ws = NULL;
695         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
696             ystr(ws->name);
697         else
698             y(null);
699
700         y(map_close);
701     }
702
703     y(array_close);
704
705     const unsigned char *payload;
706     ylength length;
707     y(get_buf, &payload, &length);
708
709     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
710     y(free);
711 }
712
713 /*
714  * Formats the reply message for a GET_MARKS request and sends it to the
715  * client
716  *
717  */
718 IPC_HANDLER(get_marks) {
719     yajl_gen gen = ygenalloc();
720     y(array_open);
721
722     Con *con;
723     TAILQ_FOREACH(con, &all_cons, all_cons)
724     if (con->mark != NULL)
725         ystr(con->mark);
726
727     y(array_close);
728
729     const unsigned char *payload;
730     ylength length;
731     y(get_buf, &payload, &length);
732
733     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
734     y(free);
735 }
736
737 /*
738  * Returns the version of i3
739  *
740  */
741 IPC_HANDLER(get_version) {
742     yajl_gen gen = ygenalloc();
743     y(map_open);
744
745     ystr("major");
746     y(integer, MAJOR_VERSION);
747
748     ystr("minor");
749     y(integer, MINOR_VERSION);
750
751     ystr("patch");
752     y(integer, PATCH_VERSION);
753
754     ystr("human_readable");
755     ystr(I3_VERSION);
756
757     y(map_close);
758
759     const unsigned char *payload;
760     ylength length;
761     y(get_buf, &payload, &length);
762
763     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
764     y(free);
765 }
766
767 /*
768  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
769  * client.
770  *
771  */
772 IPC_HANDLER(get_bar_config) {
773     yajl_gen gen = ygenalloc();
774
775     /* If no ID was passed, we return a JSON array with all IDs */
776     if (message_size == 0) {
777         y(array_open);
778         Barconfig *current;
779         TAILQ_FOREACH(current, &barconfigs, configs) {
780             ystr(current->id);
781         }
782         y(array_close);
783
784         const unsigned char *payload;
785         ylength length;
786         y(get_buf, &payload, &length);
787
788         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
789         y(free);
790         return;
791     }
792
793     /* To get a properly terminated buffer, we copy
794      * message_size bytes out of the buffer */
795     char *bar_id = scalloc(message_size + 1);
796     strncpy(bar_id, (const char *)message, message_size);
797     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
798     Barconfig *current, *config = NULL;
799     TAILQ_FOREACH(current, &barconfigs, configs) {
800         if (strcmp(current->id, bar_id) != 0)
801             continue;
802
803         config = current;
804         break;
805     }
806
807     if (!config) {
808         /* If we did not find a config for the given ID, the reply will contain
809          * a null 'id' field. */
810         y(map_open);
811
812         ystr("id");
813         y(null);
814
815         y(map_close);
816     } else {
817         dump_bar_config(gen, config);
818     }
819
820     const unsigned char *payload;
821     ylength length;
822     y(get_buf, &payload, &length);
823
824     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
825     y(free);
826 }
827
828 /*
829  * Callback for the YAJL parser (will be called when a string is parsed).
830  *
831  */
832 static int add_subscription(void *extra, const unsigned char *s,
833                             ylength len) {
834     ipc_client *client = extra;
835
836     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
837     int event = client->num_events;
838
839     client->num_events++;
840     client->events = realloc(client->events, client->num_events * sizeof(char *));
841     /* We copy the string because it is not null-terminated and strndup()
842      * is missing on some BSD systems */
843     client->events[event] = scalloc(len + 1);
844     memcpy(client->events[event], s, len);
845
846     DLOG("client is now subscribed to:\n");
847     for (int i = 0; i < client->num_events; i++)
848         DLOG("event %s\n", client->events[i]);
849     DLOG("(done)\n");
850
851     return 1;
852 }
853
854 /*
855  * Subscribes this connection to the event types which were given as a JSON
856  * serialized array in the payload field of the message.
857  *
858  */
859 IPC_HANDLER(subscribe) {
860     yajl_handle p;
861     yajl_status stat;
862     ipc_client *current, *client = NULL;
863
864     /* Search the ipc_client structure for this connection */
865     TAILQ_FOREACH(current, &all_clients, clients) {
866         if (current->fd != fd)
867             continue;
868
869         client = current;
870         break;
871     }
872
873     if (client == NULL) {
874         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
875         return;
876     }
877
878     /* Setup the JSON parser */
879     static yajl_callbacks callbacks = {
880         .yajl_string = add_subscription,
881     };
882
883     p = yalloc(&callbacks, (void *)client);
884     stat = yajl_parse(p, (const unsigned char *)message, message_size);
885     if (stat != yajl_status_ok) {
886         unsigned char *err;
887         err = yajl_get_error(p, true, (const unsigned char *)message,
888                              message_size);
889         ELOG("YAJL parse error: %s\n", err);
890         yajl_free_error(p, err);
891
892         const char *reply = "{\"success\":false}";
893         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
894         yajl_free(p);
895         return;
896     }
897     yajl_free(p);
898     const char *reply = "{\"success\":true}";
899     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
900 }
901
902 /* The index of each callback function corresponds to the numeric
903  * value of the message type (see include/i3/ipc.h) */
904 handler_t handlers[8] = {
905     handle_command,
906     handle_get_workspaces,
907     handle_subscribe,
908     handle_get_outputs,
909     handle_tree,
910     handle_get_marks,
911     handle_get_bar_config,
912     handle_get_version,
913 };
914
915 /*
916  * Handler for activity on a client connection, receives a message from a
917  * client.
918  *
919  * For now, the maximum message size is 2048. I’m not sure for what the
920  * IPC interface will be used in the future, thus I’m not implementing a
921  * mechanism for arbitrarily long messages, as it seems like overkill
922  * at the moment.
923  *
924  */
925 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
926     uint32_t message_type;
927     uint32_t message_length;
928     uint8_t *message = NULL;
929
930     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
931     /* EOF or other error */
932     if (ret < 0) {
933         /* Was this a spurious read? See ev(3) */
934         if (ret == -1 && errno == EAGAIN) {
935             FREE(message);
936             return;
937         }
938
939         /* If not, there was some kind of error. We don’t bother
940          * and close the connection */
941         close(w->fd);
942
943         /* Delete the client from the list of clients */
944         ipc_client *current;
945         TAILQ_FOREACH(current, &all_clients, clients) {
946             if (current->fd != w->fd)
947                 continue;
948
949             for (int i = 0; i < current->num_events; i++)
950                 free(current->events[i]);
951             /* We can call TAILQ_REMOVE because we break out of the
952              * TAILQ_FOREACH afterwards */
953             TAILQ_REMOVE(&all_clients, current, clients);
954             free(current);
955             break;
956         }
957
958         ev_io_stop(EV_A_ w);
959         free(w);
960         FREE(message);
961
962         DLOG("IPC: client disconnected\n");
963         return;
964     }
965
966     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
967         DLOG("Unhandled message type: %d\n", message_type);
968     else {
969         handler_t h = handlers[message_type];
970         h(w->fd, message, 0, message_length, message_type);
971     }
972
973     FREE(message);
974 }
975
976 /*
977  * Handler for activity on the listening socket, meaning that a new client
978  * has just connected and we should accept() him. Sets up the event handler
979  * for activity on the new connection and inserts the file descriptor into
980  * the list of clients.
981  *
982  */
983 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
984     struct sockaddr_un peer;
985     socklen_t len = sizeof(struct sockaddr_un);
986     int client;
987     if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
988         if (errno == EINTR)
989             return;
990         else
991             perror("accept()");
992         return;
993     }
994
995     /* Close this file descriptor on exec() */
996     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
997
998     set_nonblock(client);
999
1000     struct ev_io *package = scalloc(sizeof(struct ev_io));
1001     ev_io_init(package, ipc_receive_message, client, EV_READ);
1002     ev_io_start(EV_A_ package);
1003
1004     DLOG("IPC: new client connected on fd %d\n", w->fd);
1005
1006     ipc_client *new = scalloc(sizeof(ipc_client));
1007     new->fd = client;
1008
1009     TAILQ_INSERT_TAIL(&all_clients, new, clients);
1010 }
1011
1012 /*
1013  * Creates the UNIX domain socket at the given path, sets it to non-blocking
1014  * mode, bind()s and listen()s on it.
1015  *
1016  */
1017 int ipc_create_socket(const char *filename) {
1018     int sockfd;
1019
1020     FREE(current_socketpath);
1021
1022     char *resolved = resolve_tilde(filename);
1023     DLOG("Creating IPC-socket at %s\n", resolved);
1024     char *copy = sstrdup(resolved);
1025     const char *dir = dirname(copy);
1026     if (!path_exists(dir))
1027         mkdirp(dir);
1028     free(copy);
1029
1030     /* Unlink the unix domain socket before */
1031     unlink(resolved);
1032
1033     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1034         perror("socket()");
1035         free(resolved);
1036         return -1;
1037     }
1038
1039     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1040
1041     struct sockaddr_un addr;
1042     memset(&addr, 0, sizeof(struct sockaddr_un));
1043     addr.sun_family = AF_LOCAL;
1044     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1045     if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1046         perror("bind()");
1047         free(resolved);
1048         return -1;
1049     }
1050
1051     set_nonblock(sockfd);
1052
1053     if (listen(sockfd, 5) < 0) {
1054         perror("listen()");
1055         free(resolved);
1056         return -1;
1057     }
1058
1059     current_socketpath = resolved;
1060     return sockfd;
1061 }
1062
1063 /*
1064  * For the workspace "focus" event we send, along the usual "change" field,
1065  * also the current and previous workspace, in "current" and "old"
1066  * respectively.
1067  */
1068 void ipc_send_workspace_focus_event(Con *current, Con *old) {
1069     setlocale(LC_NUMERIC, "C");
1070     yajl_gen gen = ygenalloc();
1071
1072     y(map_open);
1073
1074     ystr("change");
1075     ystr("focus");
1076
1077     ystr("current");
1078     dump_node(gen, current, false);
1079
1080     ystr("old");
1081     if (old == NULL)
1082         y(null);
1083     else
1084         dump_node(gen, old, false);
1085
1086     y(map_close);
1087
1088     const unsigned char *payload;
1089     ylength length;
1090     y(get_buf, &payload, &length);
1091
1092     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1093     y(free);
1094     setlocale(LC_NUMERIC, "");
1095 }
1096
1097 /**
1098  * For the window events we send, along the usual "change" field,
1099  * also the window container, in "container".
1100  */
1101 void ipc_send_window_event(const char *property, Con *con) {
1102     DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1103          property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1104
1105     setlocale(LC_NUMERIC, "C");
1106     yajl_gen gen = ygenalloc();
1107
1108     y(map_open);
1109
1110     ystr("change");
1111     ystr(property);
1112
1113     ystr("container");
1114     dump_node(gen, con, false);
1115
1116     y(map_close);
1117
1118     const unsigned char *payload;
1119     ylength length;
1120     y(get_buf, &payload, &length);
1121
1122     ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1123     y(free);
1124     setlocale(LC_NUMERIC, "");
1125 }
1126
1127 /**
1128  * For the barconfig update events, we send the serialized barconfig.
1129  */
1130 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1131     DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1132     setlocale(LC_NUMERIC, "C");
1133     yajl_gen gen = ygenalloc();
1134
1135     dump_bar_config(gen, barconfig);
1136
1137     const unsigned char *payload;
1138     ylength length;
1139     y(get_buf, &payload, &length);
1140
1141     ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1142     y(free);
1143     setlocale(LC_NUMERIC, "");
1144 }