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