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