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