]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Bugfix: skip restart_mode swallow specifications
[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         /* We will generate a new restart_mode match specification after this
454          * loop, so skip this one. */
455         if (match->restart_mode)
456             continue;
457         y(map_open);
458         if (match->dock != -1) {
459             ystr("dock");
460             y(integer, match->dock);
461             ystr("insert_where");
462             y(integer, match->insert_where);
463         }
464
465 #define DUMP_REGEX(re_name)                \
466     do {                                   \
467         if (match->re_name != NULL) {      \
468             ystr(#re_name);                \
469             ystr(match->re_name->pattern); \
470         }                                  \
471     } while (0)
472
473         DUMP_REGEX(class);
474         DUMP_REGEX(instance);
475         DUMP_REGEX(window_role);
476         DUMP_REGEX(title);
477
478 #undef DUMP_REGEX
479         y(map_close);
480     }
481
482     if (inplace_restart) {
483         if (con->window != NULL) {
484             y(map_open);
485             ystr("id");
486             y(integer, con->window->id);
487             ystr("restart_mode");
488             y(bool, true);
489             y(map_close);
490         }
491     }
492     y(array_close);
493
494     if (inplace_restart && con->window != NULL) {
495         ystr("depth");
496         y(integer, con->depth);
497     }
498
499     y(map_close);
500 }
501
502 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
503     y(map_open);
504
505     ystr("id");
506     ystr(config->id);
507
508     if (config->num_outputs > 0) {
509         ystr("outputs");
510         y(array_open);
511         for (int c = 0; c < config->num_outputs; c++)
512             ystr(config->outputs[c]);
513         y(array_close);
514     }
515
516 #define YSTR_IF_SET(name)       \
517     do {                        \
518         if (config->name) {     \
519             ystr(#name);        \
520             ystr(config->name); \
521         }                       \
522     } while (0)
523
524     YSTR_IF_SET(tray_output);
525     YSTR_IF_SET(socket_path);
526
527     ystr("mode");
528     switch (config->mode) {
529         case M_HIDE:
530             ystr("hide");
531             break;
532         case M_INVISIBLE:
533             ystr("invisible");
534             break;
535         case M_DOCK:
536         default:
537             ystr("dock");
538             break;
539     }
540
541     ystr("hidden_state");
542     switch (config->hidden_state) {
543         case S_SHOW:
544             ystr("show");
545             break;
546         case S_HIDE:
547         default:
548             ystr("hide");
549             break;
550     }
551
552     ystr("modifier");
553     switch (config->modifier) {
554         case M_CONTROL:
555             ystr("ctrl");
556             break;
557         case M_SHIFT:
558             ystr("shift");
559             break;
560         case M_MOD1:
561             ystr("Mod1");
562             break;
563         case M_MOD2:
564             ystr("Mod2");
565             break;
566         case M_MOD3:
567             ystr("Mod3");
568             break;
569         /*
570                case M_MOD4:
571                ystr("Mod4");
572                break;
573                */
574         case M_MOD5:
575             ystr("Mod5");
576             break;
577         default:
578             ystr("Mod4");
579             break;
580     }
581
582     if (config->wheel_up_cmd) {
583         ystr("wheel_up_cmd");
584         ystr(config->wheel_up_cmd);
585     }
586
587     if (config->wheel_down_cmd) {
588         ystr("wheel_down_cmd");
589         ystr(config->wheel_down_cmd);
590     }
591
592     ystr("position");
593     if (config->position == P_BOTTOM)
594         ystr("bottom");
595     else
596         ystr("top");
597
598     YSTR_IF_SET(status_command);
599     YSTR_IF_SET(font);
600
601     ystr("workspace_buttons");
602     y(bool, !config->hide_workspace_buttons);
603
604     ystr("strip_workspace_numbers");
605     y(bool, config->strip_workspace_numbers);
606
607     ystr("binding_mode_indicator");
608     y(bool, !config->hide_binding_mode_indicator);
609
610     ystr("verbose");
611     y(bool, config->verbose);
612
613 #undef YSTR_IF_SET
614 #define YSTR_IF_SET(name)              \
615     do {                               \
616         if (config->colors.name) {     \
617             ystr(#name);               \
618             ystr(config->colors.name); \
619         }                              \
620     } while (0)
621
622     ystr("colors");
623     y(map_open);
624     YSTR_IF_SET(background);
625     YSTR_IF_SET(statusline);
626     YSTR_IF_SET(separator);
627     YSTR_IF_SET(focused_workspace_border);
628     YSTR_IF_SET(focused_workspace_bg);
629     YSTR_IF_SET(focused_workspace_text);
630     YSTR_IF_SET(active_workspace_border);
631     YSTR_IF_SET(active_workspace_bg);
632     YSTR_IF_SET(active_workspace_text);
633     YSTR_IF_SET(inactive_workspace_border);
634     YSTR_IF_SET(inactive_workspace_bg);
635     YSTR_IF_SET(inactive_workspace_text);
636     YSTR_IF_SET(urgent_workspace_border);
637     YSTR_IF_SET(urgent_workspace_bg);
638     YSTR_IF_SET(urgent_workspace_text);
639     y(map_close);
640
641     y(map_close);
642 #undef YSTR_IF_SET
643 }
644
645 IPC_HANDLER(tree) {
646     setlocale(LC_NUMERIC, "C");
647     yajl_gen gen = ygenalloc();
648     dump_node(gen, croot, false);
649     setlocale(LC_NUMERIC, "");
650
651     const unsigned char *payload;
652     ylength length;
653     y(get_buf, &payload, &length);
654
655     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
656     y(free);
657 }
658
659 /*
660  * Formats the reply message for a GET_WORKSPACES request and sends it to the
661  * client
662  *
663  */
664 IPC_HANDLER(get_workspaces) {
665     yajl_gen gen = ygenalloc();
666     y(array_open);
667
668     Con *focused_ws = con_get_workspace(focused);
669
670     Con *output;
671     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
672         if (con_is_internal(output))
673             continue;
674         Con *ws;
675         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
676             assert(ws->type == CT_WORKSPACE);
677             y(map_open);
678
679             ystr("num");
680             y(integer, ws->num);
681
682             ystr("name");
683             ystr(ws->name);
684
685             ystr("visible");
686             y(bool, workspace_is_visible(ws));
687
688             ystr("focused");
689             y(bool, ws == focused_ws);
690
691             ystr("rect");
692             y(map_open);
693             ystr("x");
694             y(integer, ws->rect.x);
695             ystr("y");
696             y(integer, ws->rect.y);
697             ystr("width");
698             y(integer, ws->rect.width);
699             ystr("height");
700             y(integer, ws->rect.height);
701             y(map_close);
702
703             ystr("output");
704             ystr(output->name);
705
706             ystr("urgent");
707             y(bool, ws->urgent);
708
709             y(map_close);
710         }
711     }
712
713     y(array_close);
714
715     const unsigned char *payload;
716     ylength length;
717     y(get_buf, &payload, &length);
718
719     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
720     y(free);
721 }
722
723 /*
724  * Formats the reply message for a GET_OUTPUTS request and sends it to the
725  * client
726  *
727  */
728 IPC_HANDLER(get_outputs) {
729     yajl_gen gen = ygenalloc();
730     y(array_open);
731
732     Output *output;
733     TAILQ_FOREACH(output, &outputs, outputs) {
734         y(map_open);
735
736         ystr("name");
737         ystr(output->name);
738
739         ystr("active");
740         y(bool, output->active);
741
742         ystr("primary");
743         y(bool, output->primary);
744
745         ystr("rect");
746         y(map_open);
747         ystr("x");
748         y(integer, output->rect.x);
749         ystr("y");
750         y(integer, output->rect.y);
751         ystr("width");
752         y(integer, output->rect.width);
753         ystr("height");
754         y(integer, output->rect.height);
755         y(map_close);
756
757         ystr("current_workspace");
758         Con *ws = NULL;
759         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
760             ystr(ws->name);
761         else
762             y(null);
763
764         y(map_close);
765     }
766
767     y(array_close);
768
769     const unsigned char *payload;
770     ylength length;
771     y(get_buf, &payload, &length);
772
773     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
774     y(free);
775 }
776
777 /*
778  * Formats the reply message for a GET_MARKS request and sends it to the
779  * client
780  *
781  */
782 IPC_HANDLER(get_marks) {
783     yajl_gen gen = ygenalloc();
784     y(array_open);
785
786     Con *con;
787     TAILQ_FOREACH(con, &all_cons, all_cons)
788     if (con->mark != NULL)
789         ystr(con->mark);
790
791     y(array_close);
792
793     const unsigned char *payload;
794     ylength length;
795     y(get_buf, &payload, &length);
796
797     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
798     y(free);
799 }
800
801 /*
802  * Returns the version of i3
803  *
804  */
805 IPC_HANDLER(get_version) {
806     yajl_gen gen = ygenalloc();
807     y(map_open);
808
809     ystr("major");
810     y(integer, MAJOR_VERSION);
811
812     ystr("minor");
813     y(integer, MINOR_VERSION);
814
815     ystr("patch");
816     y(integer, PATCH_VERSION);
817
818     ystr("human_readable");
819     ystr(I3_VERSION);
820
821     y(map_close);
822
823     const unsigned char *payload;
824     ylength length;
825     y(get_buf, &payload, &length);
826
827     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
828     y(free);
829 }
830
831 /*
832  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
833  * client.
834  *
835  */
836 IPC_HANDLER(get_bar_config) {
837     yajl_gen gen = ygenalloc();
838
839     /* If no ID was passed, we return a JSON array with all IDs */
840     if (message_size == 0) {
841         y(array_open);
842         Barconfig *current;
843         TAILQ_FOREACH(current, &barconfigs, configs) {
844             ystr(current->id);
845         }
846         y(array_close);
847
848         const unsigned char *payload;
849         ylength length;
850         y(get_buf, &payload, &length);
851
852         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
853         y(free);
854         return;
855     }
856
857     /* To get a properly terminated buffer, we copy
858      * message_size bytes out of the buffer */
859     char *bar_id = scalloc(message_size + 1);
860     strncpy(bar_id, (const char *)message, message_size);
861     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
862     Barconfig *current, *config = NULL;
863     TAILQ_FOREACH(current, &barconfigs, configs) {
864         if (strcmp(current->id, bar_id) != 0)
865             continue;
866
867         config = current;
868         break;
869     }
870
871     if (!config) {
872         /* If we did not find a config for the given ID, the reply will contain
873          * a null 'id' field. */
874         y(map_open);
875
876         ystr("id");
877         y(null);
878
879         y(map_close);
880     } else {
881         dump_bar_config(gen, config);
882     }
883
884     const unsigned char *payload;
885     ylength length;
886     y(get_buf, &payload, &length);
887
888     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
889     y(free);
890 }
891
892 /*
893  * Callback for the YAJL parser (will be called when a string is parsed).
894  *
895  */
896 static int add_subscription(void *extra, const unsigned char *s,
897                             ylength len) {
898     ipc_client *client = extra;
899
900     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
901     int event = client->num_events;
902
903     client->num_events++;
904     client->events = realloc(client->events, client->num_events * sizeof(char *));
905     /* We copy the string because it is not null-terminated and strndup()
906      * is missing on some BSD systems */
907     client->events[event] = scalloc(len + 1);
908     memcpy(client->events[event], s, len);
909
910     DLOG("client is now subscribed to:\n");
911     for (int i = 0; i < client->num_events; i++)
912         DLOG("event %s\n", client->events[i]);
913     DLOG("(done)\n");
914
915     return 1;
916 }
917
918 /*
919  * Subscribes this connection to the event types which were given as a JSON
920  * serialized array in the payload field of the message.
921  *
922  */
923 IPC_HANDLER(subscribe) {
924     yajl_handle p;
925     yajl_status stat;
926     ipc_client *current, *client = NULL;
927
928     /* Search the ipc_client structure for this connection */
929     TAILQ_FOREACH(current, &all_clients, clients) {
930         if (current->fd != fd)
931             continue;
932
933         client = current;
934         break;
935     }
936
937     if (client == NULL) {
938         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
939         return;
940     }
941
942     /* Setup the JSON parser */
943     static yajl_callbacks callbacks = {
944         .yajl_string = add_subscription,
945     };
946
947     p = yalloc(&callbacks, (void *)client);
948     stat = yajl_parse(p, (const unsigned char *)message, message_size);
949     if (stat != yajl_status_ok) {
950         unsigned char *err;
951         err = yajl_get_error(p, true, (const unsigned char *)message,
952                              message_size);
953         ELOG("YAJL parse error: %s\n", err);
954         yajl_free_error(p, err);
955
956         const char *reply = "{\"success\":false}";
957         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
958         yajl_free(p);
959         return;
960     }
961     yajl_free(p);
962     const char *reply = "{\"success\":true}";
963     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
964 }
965
966 /* The index of each callback function corresponds to the numeric
967  * value of the message type (see include/i3/ipc.h) */
968 handler_t handlers[8] = {
969     handle_command,
970     handle_get_workspaces,
971     handle_subscribe,
972     handle_get_outputs,
973     handle_tree,
974     handle_get_marks,
975     handle_get_bar_config,
976     handle_get_version,
977 };
978
979 /*
980  * Handler for activity on a client connection, receives a message from a
981  * client.
982  *
983  * For now, the maximum message size is 2048. I’m not sure for what the
984  * IPC interface will be used in the future, thus I’m not implementing a
985  * mechanism for arbitrarily long messages, as it seems like overkill
986  * at the moment.
987  *
988  */
989 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
990     uint32_t message_type;
991     uint32_t message_length;
992     uint8_t *message = NULL;
993
994     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
995     /* EOF or other error */
996     if (ret < 0) {
997         /* Was this a spurious read? See ev(3) */
998         if (ret == -1 && errno == EAGAIN) {
999             FREE(message);
1000             return;
1001         }
1002
1003         /* If not, there was some kind of error. We don’t bother
1004          * and close the connection */
1005         close(w->fd);
1006
1007         /* Delete the client from the list of clients */
1008         ipc_client *current;
1009         TAILQ_FOREACH(current, &all_clients, clients) {
1010             if (current->fd != w->fd)
1011                 continue;
1012
1013             for (int i = 0; i < current->num_events; i++)
1014                 free(current->events[i]);
1015             /* We can call TAILQ_REMOVE because we break out of the
1016              * TAILQ_FOREACH afterwards */
1017             TAILQ_REMOVE(&all_clients, current, clients);
1018             free(current);
1019             break;
1020         }
1021
1022         ev_io_stop(EV_A_ w);
1023         free(w);
1024         FREE(message);
1025
1026         DLOG("IPC: client disconnected\n");
1027         return;
1028     }
1029
1030     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1031         DLOG("Unhandled message type: %d\n", message_type);
1032     else {
1033         handler_t h = handlers[message_type];
1034         h(w->fd, message, 0, message_length, message_type);
1035     }
1036
1037     FREE(message);
1038 }
1039
1040 /*
1041  * Handler for activity on the listening socket, meaning that a new client
1042  * has just connected and we should accept() him. Sets up the event handler
1043  * for activity on the new connection and inserts the file descriptor into
1044  * the list of clients.
1045  *
1046  */
1047 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1048     struct sockaddr_un peer;
1049     socklen_t len = sizeof(struct sockaddr_un);
1050     int client;
1051     if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1052         if (errno == EINTR)
1053             return;
1054         else
1055             perror("accept()");
1056         return;
1057     }
1058
1059     /* Close this file descriptor on exec() */
1060     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1061
1062     set_nonblock(client);
1063
1064     struct ev_io *package = scalloc(sizeof(struct ev_io));
1065     ev_io_init(package, ipc_receive_message, client, EV_READ);
1066     ev_io_start(EV_A_ package);
1067
1068     DLOG("IPC: new client connected on fd %d\n", w->fd);
1069
1070     ipc_client *new = scalloc(sizeof(ipc_client));
1071     new->fd = client;
1072
1073     TAILQ_INSERT_TAIL(&all_clients, new, clients);
1074 }
1075
1076 /*
1077  * Creates the UNIX domain socket at the given path, sets it to non-blocking
1078  * mode, bind()s and listen()s on it.
1079  *
1080  */
1081 int ipc_create_socket(const char *filename) {
1082     int sockfd;
1083
1084     FREE(current_socketpath);
1085
1086     char *resolved = resolve_tilde(filename);
1087     DLOG("Creating IPC-socket at %s\n", resolved);
1088     char *copy = sstrdup(resolved);
1089     const char *dir = dirname(copy);
1090     if (!path_exists(dir))
1091         mkdirp(dir);
1092     free(copy);
1093
1094     /* Unlink the unix domain socket before */
1095     unlink(resolved);
1096
1097     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1098         perror("socket()");
1099         free(resolved);
1100         return -1;
1101     }
1102
1103     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1104
1105     struct sockaddr_un addr;
1106     memset(&addr, 0, sizeof(struct sockaddr_un));
1107     addr.sun_family = AF_LOCAL;
1108     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1109     if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1110         perror("bind()");
1111         free(resolved);
1112         return -1;
1113     }
1114
1115     set_nonblock(sockfd);
1116
1117     if (listen(sockfd, 5) < 0) {
1118         perror("listen()");
1119         free(resolved);
1120         return -1;
1121     }
1122
1123     current_socketpath = resolved;
1124     return sockfd;
1125 }
1126
1127 /*
1128  * Generates a json workspace event. Returns a dynamically allocated yajl
1129  * generator. Free with yajl_gen_free().
1130  */
1131 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1132     setlocale(LC_NUMERIC, "C");
1133     yajl_gen gen = ygenalloc();
1134
1135     y(map_open);
1136
1137     ystr("change");
1138     ystr(change);
1139
1140     ystr("current");
1141     if (current == NULL)
1142         y(null);
1143     else
1144         dump_node(gen, current, false);
1145
1146     ystr("old");
1147     if (old == NULL)
1148         y(null);
1149     else
1150         dump_node(gen, old, false);
1151
1152     y(map_close);
1153
1154     setlocale(LC_NUMERIC, "");
1155
1156     return gen;
1157 }
1158
1159 /*
1160  * For the workspace events we send, along with the usual "change" field, also
1161  * the workspace container in "current". For focus events, we send the
1162  * previously focused workspace in "old".
1163  */
1164 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1165     yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1166
1167     const unsigned char *payload;
1168     ylength length;
1169     y(get_buf, &payload, &length);
1170
1171     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1172
1173     y(free);
1174 }
1175
1176 /**
1177  * For the window events we send, along the usual "change" field,
1178  * also the window container, in "container".
1179  */
1180 void ipc_send_window_event(const char *property, Con *con) {
1181     DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1182          property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1183
1184     setlocale(LC_NUMERIC, "C");
1185     yajl_gen gen = ygenalloc();
1186
1187     y(map_open);
1188
1189     ystr("change");
1190     ystr(property);
1191
1192     ystr("container");
1193     dump_node(gen, con, false);
1194
1195     y(map_close);
1196
1197     const unsigned char *payload;
1198     ylength length;
1199     y(get_buf, &payload, &length);
1200
1201     ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1202     y(free);
1203     setlocale(LC_NUMERIC, "");
1204 }
1205
1206 /**
1207  * For the barconfig update events, we send the serialized barconfig.
1208  */
1209 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1210     DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1211     setlocale(LC_NUMERIC, "C");
1212     yajl_gen gen = ygenalloc();
1213
1214     dump_bar_config(gen, barconfig);
1215
1216     const unsigned char *payload;
1217     ylength length;
1218     y(get_buf, &payload, &length);
1219
1220     ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1221     y(free);
1222     setlocale(LC_NUMERIC, "");
1223 }
1224
1225 /*
1226  * For the binding events, we send the serialized binding struct.
1227  */
1228 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1229     DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1230
1231     setlocale(LC_NUMERIC, "C");
1232
1233     yajl_gen gen = ygenalloc();
1234
1235     y(map_open);
1236
1237     ystr("change");
1238     ystr(event_type);
1239
1240     ystr("binding");
1241     dump_binding(gen, bind);
1242
1243     y(map_close);
1244
1245     const unsigned char *payload;
1246     ylength length;
1247     y(get_buf, &payload, &length);
1248
1249     ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1250
1251     y(free);
1252     setlocale(LC_NUMERIC, "");
1253 }