]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
66c63f78f376f6df9854403ab4a74e72d0cefabe
[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 CommandResult *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("binding_mode_indicator");
518     y(bool, !config->hide_binding_mode_indicator);
519
520     ystr("verbose");
521     y(bool, config->verbose);
522
523 #undef YSTR_IF_SET
524 #define YSTR_IF_SET(name) \
525     do { \
526         if (config->colors.name) { \
527             ystr( # name); \
528             ystr(config->colors.name); \
529         } \
530     } while (0)
531
532     ystr("colors");
533     y(map_open);
534     YSTR_IF_SET(background);
535     YSTR_IF_SET(statusline);
536     YSTR_IF_SET(separator);
537     YSTR_IF_SET(focused_workspace_border);
538     YSTR_IF_SET(focused_workspace_bg);
539     YSTR_IF_SET(focused_workspace_text);
540     YSTR_IF_SET(active_workspace_border);
541     YSTR_IF_SET(active_workspace_bg);
542     YSTR_IF_SET(active_workspace_text);
543     YSTR_IF_SET(inactive_workspace_border);
544     YSTR_IF_SET(inactive_workspace_bg);
545     YSTR_IF_SET(inactive_workspace_text);
546     YSTR_IF_SET(urgent_workspace_border);
547     YSTR_IF_SET(urgent_workspace_bg);
548     YSTR_IF_SET(urgent_workspace_text);
549     y(map_close);
550
551     y(map_close);
552 #undef YSTR_IF_SET
553 }
554
555 IPC_HANDLER(tree) {
556     setlocale(LC_NUMERIC, "C");
557     yajl_gen gen = ygenalloc();
558     dump_node(gen, croot, false);
559     setlocale(LC_NUMERIC, "");
560
561     const unsigned char *payload;
562     ylength length;
563     y(get_buf, &payload, &length);
564
565     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
566     y(free);
567 }
568
569
570 /*
571  * Formats the reply message for a GET_WORKSPACES request and sends it to the
572  * client
573  *
574  */
575 IPC_HANDLER(get_workspaces) {
576     yajl_gen gen = ygenalloc();
577     y(array_open);
578
579     Con *focused_ws = con_get_workspace(focused);
580
581     Con *output;
582     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
583         if (con_is_internal(output))
584             continue;
585         Con *ws;
586         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
587             assert(ws->type == CT_WORKSPACE);
588             y(map_open);
589
590             ystr("num");
591             if (ws->num == -1)
592                 y(null);
593             else y(integer, ws->num);
594
595             ystr("name");
596             ystr(ws->name);
597
598             ystr("visible");
599             y(bool, workspace_is_visible(ws));
600
601             ystr("focused");
602             y(bool, ws == focused_ws);
603
604             ystr("rect");
605             y(map_open);
606             ystr("x");
607             y(integer, ws->rect.x);
608             ystr("y");
609             y(integer, ws->rect.y);
610             ystr("width");
611             y(integer, ws->rect.width);
612             ystr("height");
613             y(integer, ws->rect.height);
614             y(map_close);
615
616             ystr("output");
617             ystr(output->name);
618
619             ystr("urgent");
620             y(bool, ws->urgent);
621
622             y(map_close);
623         }
624     }
625
626     y(array_close);
627
628     const unsigned char *payload;
629     ylength length;
630     y(get_buf, &payload, &length);
631
632     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
633     y(free);
634 }
635
636 /*
637  * Formats the reply message for a GET_OUTPUTS request and sends it to the
638  * client
639  *
640  */
641 IPC_HANDLER(get_outputs) {
642     yajl_gen gen = ygenalloc();
643     y(array_open);
644
645     Output *output;
646     TAILQ_FOREACH(output, &outputs, outputs) {
647         y(map_open);
648
649         ystr("name");
650         ystr(output->name);
651
652         ystr("active");
653         y(bool, output->active);
654
655         ystr("primary");
656         y(bool, output->primary);
657
658         ystr("rect");
659         y(map_open);
660         ystr("x");
661         y(integer, output->rect.x);
662         ystr("y");
663         y(integer, output->rect.y);
664         ystr("width");
665         y(integer, output->rect.width);
666         ystr("height");
667         y(integer, output->rect.height);
668         y(map_close);
669
670         ystr("current_workspace");
671         Con *ws = NULL;
672         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
673             ystr(ws->name);
674         else y(null);
675
676         y(map_close);
677     }
678
679     y(array_close);
680
681     const unsigned char *payload;
682     ylength length;
683     y(get_buf, &payload, &length);
684
685     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
686     y(free);
687 }
688
689 /*
690  * Formats the reply message for a GET_MARKS request and sends it to the
691  * client
692  *
693  */
694 IPC_HANDLER(get_marks) {
695     yajl_gen gen = ygenalloc();
696     y(array_open);
697
698     Con *con;
699     TAILQ_FOREACH(con, &all_cons, all_cons)
700         if (con->mark != NULL)
701             ystr(con->mark);
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_MARKS, payload);
710     y(free);
711 }
712
713 /*
714  * Returns the version of i3
715  *
716  */
717 IPC_HANDLER(get_version) {
718     yajl_gen gen = ygenalloc();
719     y(map_open);
720
721     ystr("major");
722     y(integer, MAJOR_VERSION);
723
724     ystr("minor");
725     y(integer, MINOR_VERSION);
726
727     ystr("patch");
728     y(integer, PATCH_VERSION);
729
730     ystr("human_readable");
731     ystr(I3_VERSION);
732
733     y(map_close);
734
735     const unsigned char *payload;
736     ylength length;
737     y(get_buf, &payload, &length);
738
739     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
740     y(free);
741 }
742
743 /*
744  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
745  * client.
746  *
747  */
748 IPC_HANDLER(get_bar_config) {
749     yajl_gen gen = ygenalloc();
750
751     /* If no ID was passed, we return a JSON array with all IDs */
752     if (message_size == 0) {
753         y(array_open);
754         Barconfig *current;
755         TAILQ_FOREACH(current, &barconfigs, configs) {
756             ystr(current->id);
757         }
758         y(array_close);
759
760         const unsigned char *payload;
761         ylength length;
762         y(get_buf, &payload, &length);
763
764         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
765         y(free);
766         return;
767     }
768
769     /* To get a properly terminated buffer, we copy
770      * message_size bytes out of the buffer */
771     char *bar_id = scalloc(message_size + 1);
772     strncpy(bar_id, (const char*)message, message_size);
773     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
774     Barconfig *current, *config = NULL;
775     TAILQ_FOREACH(current, &barconfigs, configs) {
776         if (strcmp(current->id, bar_id) != 0)
777             continue;
778
779         config = current;
780         break;
781     }
782
783     if (!config) {
784         /* If we did not find a config for the given ID, the reply will contain
785          * a null 'id' field. */
786         y(map_open);
787
788         ystr("id");
789         y(null);
790
791         y(map_close);
792     } else {
793         dump_bar_config(gen, config);
794     }
795
796     const unsigned char *payload;
797     ylength length;
798     y(get_buf, &payload, &length);
799
800     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
801     y(free);
802 }
803
804 /*
805  * Callback for the YAJL parser (will be called when a string is parsed).
806  *
807  */
808 static int add_subscription(void *extra, const unsigned char *s,
809                             ylength len) {
810     ipc_client *client = extra;
811
812     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
813     int event = client->num_events;
814
815     client->num_events++;
816     client->events = realloc(client->events, client->num_events * sizeof(char*));
817     /* We copy the string because it is not null-terminated and strndup()
818      * is missing on some BSD systems */
819     client->events[event] = scalloc(len+1);
820     memcpy(client->events[event], s, len);
821
822     DLOG("client is now subscribed to:\n");
823     for (int i = 0; i < client->num_events; i++)
824         DLOG("event %s\n", client->events[i]);
825     DLOG("(done)\n");
826
827     return 1;
828 }
829
830 /*
831  * Subscribes this connection to the event types which were given as a JSON
832  * serialized array in the payload field of the message.
833  *
834  */
835 IPC_HANDLER(subscribe) {
836     yajl_handle p;
837     yajl_status stat;
838     ipc_client *current, *client = NULL;
839
840     /* Search the ipc_client structure for this connection */
841     TAILQ_FOREACH(current, &all_clients, clients) {
842         if (current->fd != fd)
843             continue;
844
845         client = current;
846         break;
847     }
848
849     if (client == NULL) {
850         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
851         return;
852     }
853
854     /* Setup the JSON parser */
855     static yajl_callbacks callbacks = {
856         .yajl_string = add_subscription,
857     };
858
859     p = yalloc(&callbacks, (void*)client);
860     stat = yajl_parse(p, (const unsigned char*)message, message_size);
861     if (stat != yajl_status_ok) {
862         unsigned char *err;
863         err = yajl_get_error(p, true, (const unsigned char*)message,
864                              message_size);
865         ELOG("YAJL parse error: %s\n", err);
866         yajl_free_error(p, err);
867
868         const char *reply = "{\"success\":false}";
869         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
870         yajl_free(p);
871         return;
872     }
873     yajl_free(p);
874     const char *reply = "{\"success\":true}";
875     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
876 }
877
878 /* The index of each callback function corresponds to the numeric
879  * value of the message type (see include/i3/ipc.h) */
880 handler_t handlers[8] = {
881     handle_command,
882     handle_get_workspaces,
883     handle_subscribe,
884     handle_get_outputs,
885     handle_tree,
886     handle_get_marks,
887     handle_get_bar_config,
888     handle_get_version,
889 };
890
891 /*
892  * Handler for activity on a client connection, receives a message from a
893  * client.
894  *
895  * For now, the maximum message size is 2048. I’m not sure for what the
896  * IPC interface will be used in the future, thus I’m not implementing a
897  * mechanism for arbitrarily long messages, as it seems like overkill
898  * at the moment.
899  *
900  */
901 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
902     uint32_t message_type;
903     uint32_t message_length;
904     uint8_t *message = NULL;
905
906     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
907     /* EOF or other error */
908     if (ret < 0) {
909         /* Was this a spurious read? See ev(3) */
910         if (ret == -1 && errno == EAGAIN) {
911             FREE(message);
912             return;
913         }
914
915         /* If not, there was some kind of error. We don’t bother
916          * and close the connection */
917         close(w->fd);
918
919         /* Delete the client from the list of clients */
920         ipc_client *current;
921         TAILQ_FOREACH(current, &all_clients, clients) {
922             if (current->fd != w->fd)
923                 continue;
924
925             for (int i = 0; i < current->num_events; i++)
926                 free(current->events[i]);
927             /* We can call TAILQ_REMOVE because we break out of the
928              * TAILQ_FOREACH afterwards */
929             TAILQ_REMOVE(&all_clients, current, clients);
930             free(current);
931             break;
932         }
933
934         ev_io_stop(EV_A_ w);
935         free(w);
936         FREE(message);
937
938         DLOG("IPC: client disconnected\n");
939         return;
940     }
941
942     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
943         DLOG("Unhandled message type: %d\n", message_type);
944     else {
945         handler_t h = handlers[message_type];
946         h(w->fd, message, 0, message_length, message_type);
947     }
948
949     FREE(message);
950 }
951
952 /*
953  * Handler for activity on the listening socket, meaning that a new client
954  * has just connected and we should accept() him. Sets up the event handler
955  * for activity on the new connection and inserts the file descriptor into
956  * the list of clients.
957  *
958  */
959 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
960     struct sockaddr_un peer;
961     socklen_t len = sizeof(struct sockaddr_un);
962     int client;
963     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
964         if (errno == EINTR)
965             return;
966         else perror("accept()");
967         return;
968     }
969
970     /* Close this file descriptor on exec() */
971     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
972
973     set_nonblock(client);
974
975     struct ev_io *package = scalloc(sizeof(struct ev_io));
976     ev_io_init(package, ipc_receive_message, client, EV_READ);
977     ev_io_start(EV_A_ package);
978
979     DLOG("IPC: new client connected on fd %d\n", w->fd);
980
981     ipc_client *new = scalloc(sizeof(ipc_client));
982     new->fd = client;
983
984     TAILQ_INSERT_TAIL(&all_clients, new, clients);
985 }
986
987 /*
988  * Creates the UNIX domain socket at the given path, sets it to non-blocking
989  * mode, bind()s and listen()s on it.
990  *
991  */
992 int ipc_create_socket(const char *filename) {
993     int sockfd;
994
995     FREE(current_socketpath);
996
997     char *resolved = resolve_tilde(filename);
998     DLOG("Creating IPC-socket at %s\n", resolved);
999     char *copy = sstrdup(resolved);
1000     const char *dir = dirname(copy);
1001     if (!path_exists(dir))
1002         mkdirp(dir);
1003     free(copy);
1004
1005     /* Unlink the unix domain socket before */
1006     unlink(resolved);
1007
1008     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1009         perror("socket()");
1010         free(resolved);
1011         return -1;
1012     }
1013
1014     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1015
1016     struct sockaddr_un addr;
1017     memset(&addr, 0, sizeof(struct sockaddr_un));
1018     addr.sun_family = AF_LOCAL;
1019     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1020     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1021         perror("bind()");
1022         free(resolved);
1023         return -1;
1024     }
1025
1026     set_nonblock(sockfd);
1027
1028     if (listen(sockfd, 5) < 0) {
1029         perror("listen()");
1030         free(resolved);
1031         return -1;
1032     }
1033
1034     current_socketpath = resolved;
1035     return sockfd;
1036 }
1037
1038 /*
1039  * For the workspace "focus" event we send, along the usual "change" field,
1040  * also the current and previous workspace, in "current" and "old"
1041  * respectively.
1042  */
1043 void ipc_send_workspace_focus_event(Con *current, Con *old) {
1044     setlocale(LC_NUMERIC, "C");
1045     yajl_gen gen = ygenalloc();
1046
1047     y(map_open);
1048
1049     ystr("change");
1050     ystr("focus");
1051
1052     ystr("current");
1053     dump_node(gen, current, false);
1054
1055     ystr("old");
1056     if (old == NULL)
1057         y(null);
1058     else
1059         dump_node(gen, old, false);
1060
1061     y(map_close);
1062
1063     const unsigned char *payload;
1064     ylength length;
1065     y(get_buf, &payload, &length);
1066
1067     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1068     y(free);
1069     setlocale(LC_NUMERIC, "");
1070 }
1071
1072 /**
1073  * For the window events we send, along the usual "change" field,
1074  * also the window container, in "container".
1075  */
1076 void ipc_send_window_event(const char *property, Con *con) {
1077     DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1078             property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1079
1080     setlocale(LC_NUMERIC, "C");
1081     yajl_gen gen = ygenalloc();
1082
1083     y(map_open);
1084
1085     ystr("change");
1086     ystr(property);
1087
1088     ystr("container");
1089     dump_node(gen, con, false);
1090
1091     y(map_close);
1092
1093     const unsigned char *payload;
1094     ylength length;
1095     y(get_buf, &payload, &length);
1096
1097     ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1098     y(free);
1099     setlocale(LC_NUMERIC, "");
1100 }
1101
1102 /**
1103  * For the barconfig update events, we send the serialized barconfig.
1104  */
1105 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1106     DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1107     setlocale(LC_NUMERIC, "C");
1108     yajl_gen gen = ygenalloc();
1109
1110     dump_bar_config(gen, barconfig);
1111
1112     const unsigned char *payload;
1113     ylength length;
1114     y(get_buf, &payload, &length);
1115
1116     ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1117     y(free);
1118     setlocale(LC_NUMERIC, "");
1119 }