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