]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Merge pull request #1816 from tcreech/tcreech-for-illumos
[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 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  * Sends the specified event to all IPC clients which are currently connected
42  * and subscribed to this kind of event.
43  *
44  */
45 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
46     ipc_client *current;
47     TAILQ_FOREACH(current, &all_clients, clients) {
48         /* see if this client is interested in this event */
49         bool interested = false;
50         for (int i = 0; i < current->num_events; i++) {
51             if (strcasecmp(current->events[i], event) != 0)
52                 continue;
53             interested = true;
54             break;
55         }
56         if (!interested)
57             continue;
58
59         ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t *)payload);
60     }
61 }
62
63 /*
64  * Calls shutdown() on each socket and closes it. This function to be called
65  * when exiting or restarting only!
66  *
67  */
68 void ipc_shutdown(void) {
69     ipc_client *current;
70     while (!TAILQ_EMPTY(&all_clients)) {
71         current = TAILQ_FIRST(&all_clients);
72         shutdown(current->fd, SHUT_RDWR);
73         close(current->fd);
74         TAILQ_REMOVE(&all_clients, current, clients);
75         free(current);
76     }
77 }
78
79 /*
80  * Executes the command and returns whether it could be successfully parsed
81  * or not (at the moment, always returns true).
82  *
83  */
84 IPC_HANDLER(command) {
85     /* To get a properly terminated buffer, we copy
86      * message_size bytes out of the buffer */
87     char *command = scalloc(message_size + 1, 1);
88     strncpy(command, (const char *)message, message_size);
89     LOG("IPC: received: *%s*\n", command);
90     yajl_gen gen = yajl_gen_alloc(NULL);
91
92     CommandResult *result = parse_command((const char *)command, gen);
93     free(command);
94
95     if (result->needs_tree_render)
96         tree_render();
97
98     command_result_free(result);
99
100     const unsigned char *reply;
101     ylength length;
102     yajl_gen_get_buf(gen, &reply, &length);
103
104     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
105                      (const uint8_t *)reply);
106
107     yajl_gen_free(gen);
108 }
109
110 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
111     ystr(name);
112     y(map_open);
113     ystr("x");
114     y(integer, r.x);
115     ystr("y");
116     y(integer, r.y);
117     ystr("width");
118     y(integer, r.width);
119     ystr("height");
120     y(integer, r.height);
121     y(map_close);
122 }
123
124 static void dump_binding(yajl_gen gen, Binding *bind) {
125     y(map_open);
126     ystr("input_code");
127     y(integer, bind->keycode);
128
129     ystr("input_type");
130     ystr((const char *)(bind->input_type == B_KEYBOARD ? "keyboard" : "mouse"));
131
132     ystr("symbol");
133     if (bind->symbol == NULL)
134         y(null);
135     else
136         ystr(bind->symbol);
137
138     ystr("command");
139     ystr(bind->command);
140
141     ystr("mods");
142     y(array_open);
143     for (int i = 0; i < 8; i++) {
144         if (bind->mods & (1 << i)) {
145             switch (1 << i) {
146                 case XCB_MOD_MASK_SHIFT:
147                     ystr("shift");
148                     break;
149                 case XCB_MOD_MASK_LOCK:
150                     ystr("lock");
151                     break;
152                 case XCB_MOD_MASK_CONTROL:
153                     ystr("ctrl");
154                     break;
155                 case XCB_MOD_MASK_1:
156                     ystr("Mod1");
157                     break;
158                 case XCB_MOD_MASK_2:
159                     ystr("Mod2");
160                     break;
161                 case XCB_MOD_MASK_3:
162                     ystr("Mod3");
163                     break;
164                 case XCB_MOD_MASK_4:
165                     ystr("Mod4");
166                     break;
167                 case XCB_MOD_MASK_5:
168                     ystr("Mod5");
169                     break;
170             }
171         }
172     }
173     y(array_close);
174
175     y(map_close);
176 }
177
178 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
179     y(map_open);
180     ystr("id");
181     y(integer, (long int)con);
182
183     ystr("type");
184     switch (con->type) {
185         case CT_ROOT:
186             ystr("root");
187             break;
188         case CT_OUTPUT:
189             ystr("output");
190             break;
191         case CT_CON:
192             ystr("con");
193             break;
194         case CT_FLOATING_CON:
195             ystr("floating_con");
196             break;
197         case CT_WORKSPACE:
198             ystr("workspace");
199             break;
200         case CT_DOCKAREA:
201             ystr("dockarea");
202             break;
203         default:
204             DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
205             assert(false);
206             break;
207     }
208
209     /* provided for backwards compatibility only. */
210     ystr("orientation");
211     if (!con_is_split(con))
212         ystr("none");
213     else {
214         if (con_orientation(con) == HORIZ)
215             ystr("horizontal");
216         else
217             ystr("vertical");
218     }
219
220     ystr("scratchpad_state");
221     switch (con->scratchpad_state) {
222         case SCRATCHPAD_NONE:
223             ystr("none");
224             break;
225         case SCRATCHPAD_FRESH:
226             ystr("fresh");
227             break;
228         case SCRATCHPAD_CHANGED:
229             ystr("changed");
230             break;
231     }
232
233     ystr("percent");
234     if (con->percent == 0.0)
235         y(null);
236     else
237         y(double, con->percent);
238
239     ystr("urgent");
240     y(bool, con->urgent);
241
242     if (con->mark != NULL) {
243         ystr("mark");
244         ystr(con->mark);
245     }
246
247     ystr("focused");
248     y(bool, (con == focused));
249
250     ystr("layout");
251     switch (con->layout) {
252         case L_DEFAULT:
253             DLOG("About to dump layout=default, this is a bug in the code.\n");
254             assert(false);
255             break;
256         case L_SPLITV:
257             ystr("splitv");
258             break;
259         case L_SPLITH:
260             ystr("splith");
261             break;
262         case L_STACKED:
263             ystr("stacked");
264             break;
265         case L_TABBED:
266             ystr("tabbed");
267             break;
268         case L_DOCKAREA:
269             ystr("dockarea");
270             break;
271         case L_OUTPUT:
272             ystr("output");
273             break;
274     }
275
276     ystr("workspace_layout");
277     switch (con->workspace_layout) {
278         case L_DEFAULT:
279             ystr("default");
280             break;
281         case L_STACKED:
282             ystr("stacked");
283             break;
284         case L_TABBED:
285             ystr("tabbed");
286             break;
287         default:
288             DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
289             assert(false);
290             break;
291     }
292
293     ystr("last_split_layout");
294     switch (con->layout) {
295         case L_SPLITV:
296             ystr("splitv");
297             break;
298         default:
299             ystr("splith");
300             break;
301     }
302
303     ystr("border");
304     switch (con->border_style) {
305         case BS_NORMAL:
306             ystr("normal");
307             break;
308         case BS_NONE:
309             ystr("none");
310             break;
311         case BS_PIXEL:
312             ystr("pixel");
313             break;
314     }
315
316     ystr("current_border_width");
317     y(integer, con->current_border_width);
318
319     dump_rect(gen, "rect", con->rect);
320     dump_rect(gen, "deco_rect", con->deco_rect);
321     dump_rect(gen, "window_rect", con->window_rect);
322     dump_rect(gen, "geometry", con->geometry);
323
324     ystr("name");
325     if (con->window && con->window->name)
326         ystr(i3string_as_utf8(con->window->name));
327     else if (con->name != NULL)
328         ystr(con->name);
329     else
330         y(null);
331
332     if (con->type == CT_WORKSPACE) {
333         ystr("num");
334         y(integer, con->num);
335     }
336
337     ystr("window");
338     if (con->window)
339         y(integer, con->window->id);
340     else
341         y(null);
342
343     if (con->window && !inplace_restart) {
344         /* Window properties are useless to preserve when restarting because
345          * they will be queried again anyway. However, for i3-save-tree(1),
346          * they are very useful and save i3-save-tree dealing with X11. */
347         ystr("window_properties");
348         y(map_open);
349
350 #define DUMP_PROPERTY(key, prop_name)         \
351     do {                                      \
352         if (con->window->prop_name != NULL) { \
353             ystr(key);                        \
354             ystr(con->window->prop_name);     \
355         }                                     \
356     } while (0)
357
358         DUMP_PROPERTY("class", class_class);
359         DUMP_PROPERTY("instance", class_instance);
360         DUMP_PROPERTY("window_role", role);
361
362         if (con->window->name != NULL) {
363             ystr("title");
364             ystr(i3string_as_utf8(con->window->name));
365         }
366
367         ystr("transient_for");
368         if (con->window->transient_for == XCB_NONE)
369             y(null);
370         else
371             y(integer, con->window->transient_for);
372
373         y(map_close);
374     }
375
376     ystr("nodes");
377     y(array_open);
378     Con *node;
379     if (con->type != CT_DOCKAREA || !inplace_restart) {
380         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
381             dump_node(gen, node, inplace_restart);
382         }
383     }
384     y(array_close);
385
386     ystr("floating_nodes");
387     y(array_open);
388     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
389         dump_node(gen, node, inplace_restart);
390     }
391     y(array_close);
392
393     ystr("focus");
394     y(array_open);
395     TAILQ_FOREACH(node, &(con->focus_head), focused) {
396         y(integer, (long int)node);
397     }
398     y(array_close);
399
400     ystr("fullscreen_mode");
401     y(integer, con->fullscreen_mode);
402
403     ystr("floating");
404     switch (con->floating) {
405         case FLOATING_AUTO_OFF:
406             ystr("auto_off");
407             break;
408         case FLOATING_AUTO_ON:
409             ystr("auto_on");
410             break;
411         case FLOATING_USER_OFF:
412             ystr("user_off");
413             break;
414         case FLOATING_USER_ON:
415             ystr("user_on");
416             break;
417     }
418
419     ystr("swallows");
420     y(array_open);
421     Match *match;
422     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
423         /* We will generate a new restart_mode match specification after this
424          * loop, so skip this one. */
425         if (match->restart_mode)
426             continue;
427         y(map_open);
428         if (match->dock != -1) {
429             ystr("dock");
430             y(integer, match->dock);
431             ystr("insert_where");
432             y(integer, match->insert_where);
433         }
434
435 #define DUMP_REGEX(re_name)                \
436     do {                                   \
437         if (match->re_name != NULL) {      \
438             ystr(#re_name);                \
439             ystr(match->re_name->pattern); \
440         }                                  \
441     } while (0)
442
443         DUMP_REGEX(class);
444         DUMP_REGEX(instance);
445         DUMP_REGEX(window_role);
446         DUMP_REGEX(title);
447
448 #undef DUMP_REGEX
449         y(map_close);
450     }
451
452     if (inplace_restart) {
453         if (con->window != NULL) {
454             y(map_open);
455             ystr("id");
456             y(integer, con->window->id);
457             ystr("restart_mode");
458             y(bool, true);
459             y(map_close);
460         }
461     }
462     y(array_close);
463
464     if (inplace_restart && con->window != NULL) {
465         ystr("depth");
466         y(integer, con->depth);
467     }
468
469     y(map_close);
470 }
471
472 static void dump_bar_bindings(yajl_gen gen, Barconfig *config) {
473     if (TAILQ_EMPTY(&(config->bar_bindings)))
474         return;
475
476     ystr("bindings");
477     y(array_open);
478
479     struct Barbinding *current;
480     TAILQ_FOREACH(current, &(config->bar_bindings), bindings) {
481         y(map_open);
482
483         ystr("input_code");
484         y(integer, current->input_code);
485         ystr("command");
486         ystr(current->command);
487
488         y(map_close);
489     }
490
491     y(array_close);
492 }
493
494 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
495     y(map_open);
496
497     ystr("id");
498     ystr(config->id);
499
500     if (config->num_outputs > 0) {
501         ystr("outputs");
502         y(array_open);
503         for (int c = 0; c < config->num_outputs; c++)
504             ystr(config->outputs[c]);
505         y(array_close);
506     }
507
508 #define YSTR_IF_SET(name)       \
509     do {                        \
510         if (config->name) {     \
511             ystr(#name);        \
512             ystr(config->name); \
513         }                       \
514     } while (0)
515
516     YSTR_IF_SET(tray_output);
517
518     ystr("tray_padding");
519     y(integer, config->tray_padding);
520
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     dump_bar_bindings(gen, config);
579
580     ystr("position");
581     if (config->position == P_BOTTOM)
582         ystr("bottom");
583     else
584         ystr("top");
585
586     YSTR_IF_SET(status_command);
587     YSTR_IF_SET(font);
588
589     if (config->separator_symbol) {
590         ystr("separator_symbol");
591         ystr(config->separator_symbol);
592     }
593
594     ystr("workspace_buttons");
595     y(bool, !config->hide_workspace_buttons);
596
597     ystr("strip_workspace_numbers");
598     y(bool, config->strip_workspace_numbers);
599
600     ystr("binding_mode_indicator");
601     y(bool, !config->hide_binding_mode_indicator);
602
603     ystr("verbose");
604     y(bool, config->verbose);
605
606 #undef YSTR_IF_SET
607 #define YSTR_IF_SET(name)              \
608     do {                               \
609         if (config->colors.name) {     \
610             ystr(#name);               \
611             ystr(config->colors.name); \
612         }                              \
613     } while (0)
614
615     ystr("colors");
616     y(map_open);
617     YSTR_IF_SET(background);
618     YSTR_IF_SET(statusline);
619     YSTR_IF_SET(separator);
620     YSTR_IF_SET(focused_workspace_border);
621     YSTR_IF_SET(focused_workspace_bg);
622     YSTR_IF_SET(focused_workspace_text);
623     YSTR_IF_SET(active_workspace_border);
624     YSTR_IF_SET(active_workspace_bg);
625     YSTR_IF_SET(active_workspace_text);
626     YSTR_IF_SET(inactive_workspace_border);
627     YSTR_IF_SET(inactive_workspace_bg);
628     YSTR_IF_SET(inactive_workspace_text);
629     YSTR_IF_SET(urgent_workspace_border);
630     YSTR_IF_SET(urgent_workspace_bg);
631     YSTR_IF_SET(urgent_workspace_text);
632     YSTR_IF_SET(binding_mode_border);
633     YSTR_IF_SET(binding_mode_bg);
634     YSTR_IF_SET(binding_mode_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     ystr("loaded_config_file_name");
818     ystr(current_configpath);
819
820     y(map_close);
821
822     const unsigned char *payload;
823     ylength length;
824     y(get_buf, &payload, &length);
825
826     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
827     y(free);
828 }
829
830 /*
831  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
832  * client.
833  *
834  */
835 IPC_HANDLER(get_bar_config) {
836     yajl_gen gen = ygenalloc();
837
838     /* If no ID was passed, we return a JSON array with all IDs */
839     if (message_size == 0) {
840         y(array_open);
841         Barconfig *current;
842         TAILQ_FOREACH(current, &barconfigs, configs) {
843             ystr(current->id);
844         }
845         y(array_close);
846
847         const unsigned char *payload;
848         ylength length;
849         y(get_buf, &payload, &length);
850
851         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
852         y(free);
853         return;
854     }
855
856     /* To get a properly terminated buffer, we copy
857      * message_size bytes out of the buffer */
858     char *bar_id = scalloc(message_size + 1, 1);
859     strncpy(bar_id, (const char *)message, message_size);
860     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
861     Barconfig *current, *config = NULL;
862     TAILQ_FOREACH(current, &barconfigs, configs) {
863         if (strcmp(current->id, bar_id) != 0)
864             continue;
865
866         config = current;
867         break;
868     }
869
870     if (!config) {
871         /* If we did not find a config for the given ID, the reply will contain
872          * a null 'id' field. */
873         y(map_open);
874
875         ystr("id");
876         y(null);
877
878         y(map_close);
879     } else {
880         dump_bar_config(gen, config);
881     }
882
883     const unsigned char *payload;
884     ylength length;
885     y(get_buf, &payload, &length);
886
887     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
888     y(free);
889 }
890
891 /*
892  * Callback for the YAJL parser (will be called when a string is parsed).
893  *
894  */
895 static int add_subscription(void *extra, const unsigned char *s,
896                             ylength len) {
897     ipc_client *client = extra;
898
899     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
900     int event = client->num_events;
901
902     client->num_events++;
903     client->events = srealloc(client->events, client->num_events * sizeof(char *));
904     /* We copy the string because it is not null-terminated and strndup()
905      * is missing on some BSD systems */
906     client->events[event] = scalloc(len + 1, 1);
907     memcpy(client->events[event], s, len);
908
909     DLOG("client is now subscribed to:\n");
910     for (int i = 0; i < client->num_events; i++)
911         DLOG("event %s\n", client->events[i]);
912     DLOG("(done)\n");
913
914     return 1;
915 }
916
917 /*
918  * Subscribes this connection to the event types which were given as a JSON
919  * serialized array in the payload field of the message.
920  *
921  */
922 IPC_HANDLER(subscribe) {
923     yajl_handle p;
924     yajl_status stat;
925     ipc_client *current, *client = NULL;
926
927     /* Search the ipc_client structure for this connection */
928     TAILQ_FOREACH(current, &all_clients, clients) {
929         if (current->fd != fd)
930             continue;
931
932         client = current;
933         break;
934     }
935
936     if (client == NULL) {
937         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
938         return;
939     }
940
941     /* Setup the JSON parser */
942     static yajl_callbacks callbacks = {
943         .yajl_string = add_subscription,
944     };
945
946     p = yalloc(&callbacks, (void *)client);
947     stat = yajl_parse(p, (const unsigned char *)message, message_size);
948     if (stat != yajl_status_ok) {
949         unsigned char *err;
950         err = yajl_get_error(p, true, (const unsigned char *)message,
951                              message_size);
952         ELOG("YAJL parse error: %s\n", err);
953         yajl_free_error(p, err);
954
955         const char *reply = "{\"success\":false}";
956         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
957         yajl_free(p);
958         return;
959     }
960     yajl_free(p);
961     const char *reply = "{\"success\":true}";
962     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
963 }
964
965 /* The index of each callback function corresponds to the numeric
966  * value of the message type (see include/i3/ipc.h) */
967 handler_t handlers[8] = {
968     handle_command,
969     handle_get_workspaces,
970     handle_subscribe,
971     handle_get_outputs,
972     handle_tree,
973     handle_get_marks,
974     handle_get_bar_config,
975     handle_get_version,
976 };
977
978 /*
979  * Handler for activity on a client connection, receives a message from a
980  * client.
981  *
982  * For now, the maximum message size is 2048. I’m not sure for what the
983  * IPC interface will be used in the future, thus I’m not implementing a
984  * mechanism for arbitrarily long messages, as it seems like overkill
985  * at the moment.
986  *
987  */
988 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
989     uint32_t message_type;
990     uint32_t message_length;
991     uint8_t *message = NULL;
992
993     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
994     /* EOF or other error */
995     if (ret < 0) {
996         /* Was this a spurious read? See ev(3) */
997         if (ret == -1 && errno == EAGAIN) {
998             FREE(message);
999             return;
1000         }
1001
1002         /* If not, there was some kind of error. We don’t bother
1003          * and close the connection */
1004         close(w->fd);
1005
1006         /* Delete the client from the list of clients */
1007         ipc_client *current;
1008         TAILQ_FOREACH(current, &all_clients, clients) {
1009             if (current->fd != w->fd)
1010                 continue;
1011
1012             for (int i = 0; i < current->num_events; i++)
1013                 free(current->events[i]);
1014             /* We can call TAILQ_REMOVE because we break out of the
1015              * TAILQ_FOREACH afterwards */
1016             TAILQ_REMOVE(&all_clients, current, clients);
1017             free(current);
1018             break;
1019         }
1020
1021         ev_io_stop(EV_A_ w);
1022         free(w);
1023         FREE(message);
1024
1025         DLOG("IPC: client disconnected\n");
1026         return;
1027     }
1028
1029     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1030         DLOG("Unhandled message type: %d\n", message_type);
1031     else {
1032         handler_t h = handlers[message_type];
1033         h(w->fd, message, 0, message_length, message_type);
1034     }
1035
1036     FREE(message);
1037 }
1038
1039 /*
1040  * Handler for activity on the listening socket, meaning that a new client
1041  * has just connected and we should accept() him. Sets up the event handler
1042  * for activity on the new connection and inserts the file descriptor into
1043  * the list of clients.
1044  *
1045  */
1046 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1047     struct sockaddr_un peer;
1048     socklen_t len = sizeof(struct sockaddr_un);
1049     int client;
1050     if ((client = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1051         if (errno == EINTR)
1052             return;
1053         else
1054             perror("accept()");
1055         return;
1056     }
1057
1058     /* Close this file descriptor on exec() */
1059     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
1060
1061     set_nonblock(client);
1062
1063     struct ev_io *package = scalloc(1, sizeof(struct ev_io));
1064     ev_io_init(package, ipc_receive_message, client, EV_READ);
1065     ev_io_start(EV_A_ package);
1066
1067     DLOG("IPC: new client connected on fd %d\n", w->fd);
1068
1069     ipc_client *new = scalloc(1, sizeof(ipc_client));
1070     new->fd = client;
1071
1072     TAILQ_INSERT_TAIL(&all_clients, new, clients);
1073 }
1074
1075 /*
1076  * Creates the UNIX domain socket at the given path, sets it to non-blocking
1077  * mode, bind()s and listen()s on it.
1078  *
1079  */
1080 int ipc_create_socket(const char *filename) {
1081     int sockfd;
1082
1083     FREE(current_socketpath);
1084
1085     char *resolved = resolve_tilde(filename);
1086     DLOG("Creating IPC-socket at %s\n", resolved);
1087     char *copy = sstrdup(resolved);
1088     const char *dir = dirname(copy);
1089     if (!path_exists(dir))
1090         mkdirp(dir, DEFAULT_DIR_MODE);
1091     free(copy);
1092
1093     /* Unlink the unix domain socket before */
1094     unlink(resolved);
1095
1096     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1097         perror("socket()");
1098         free(resolved);
1099         return -1;
1100     }
1101
1102     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1103
1104     struct sockaddr_un addr;
1105     memset(&addr, 0, sizeof(struct sockaddr_un));
1106     addr.sun_family = AF_LOCAL;
1107     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1108     if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1109         perror("bind()");
1110         free(resolved);
1111         return -1;
1112     }
1113
1114     set_nonblock(sockfd);
1115
1116     if (listen(sockfd, 5) < 0) {
1117         perror("listen()");
1118         free(resolved);
1119         return -1;
1120     }
1121
1122     current_socketpath = resolved;
1123     return sockfd;
1124 }
1125
1126 /*
1127  * Generates a json workspace event. Returns a dynamically allocated yajl
1128  * generator. Free with yajl_gen_free().
1129  */
1130 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1131     setlocale(LC_NUMERIC, "C");
1132     yajl_gen gen = ygenalloc();
1133
1134     y(map_open);
1135
1136     ystr("change");
1137     ystr(change);
1138
1139     ystr("current");
1140     if (current == NULL)
1141         y(null);
1142     else
1143         dump_node(gen, current, false);
1144
1145     ystr("old");
1146     if (old == NULL)
1147         y(null);
1148     else
1149         dump_node(gen, old, false);
1150
1151     y(map_close);
1152
1153     setlocale(LC_NUMERIC, "");
1154
1155     return gen;
1156 }
1157
1158 /*
1159  * For the workspace events we send, along with the usual "change" field, also
1160  * the workspace container in "current". For focus events, we send the
1161  * previously focused workspace in "old".
1162  */
1163 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1164     yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1165
1166     const unsigned char *payload;
1167     ylength length;
1168     y(get_buf, &payload, &length);
1169
1170     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1171
1172     y(free);
1173 }
1174
1175 /**
1176  * For the window events we send, along the usual "change" field,
1177  * also the window container, in "container".
1178  */
1179 void ipc_send_window_event(const char *property, Con *con) {
1180     DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1181          property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1182
1183     setlocale(LC_NUMERIC, "C");
1184     yajl_gen gen = ygenalloc();
1185
1186     y(map_open);
1187
1188     ystr("change");
1189     ystr(property);
1190
1191     ystr("container");
1192     dump_node(gen, con, false);
1193
1194     y(map_close);
1195
1196     const unsigned char *payload;
1197     ylength length;
1198     y(get_buf, &payload, &length);
1199
1200     ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1201     y(free);
1202     setlocale(LC_NUMERIC, "");
1203 }
1204
1205 /**
1206  * For the barconfig update events, we send the serialized barconfig.
1207  */
1208 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1209     DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1210     setlocale(LC_NUMERIC, "C");
1211     yajl_gen gen = ygenalloc();
1212
1213     dump_bar_config(gen, barconfig);
1214
1215     const unsigned char *payload;
1216     ylength length;
1217     y(get_buf, &payload, &length);
1218
1219     ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1220     y(free);
1221     setlocale(LC_NUMERIC, "");
1222 }
1223
1224 /*
1225  * For the binding events, we send the serialized binding struct.
1226  */
1227 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1228     DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1229
1230     setlocale(LC_NUMERIC, "C");
1231
1232     yajl_gen gen = ygenalloc();
1233
1234     y(map_open);
1235
1236     ystr("change");
1237     ystr(event_type);
1238
1239     ystr("binding");
1240     dump_binding(gen, bind);
1241
1242     y(map_close);
1243
1244     const unsigned char *payload;
1245     ylength length;
1246     y(get_buf, &payload, &length);
1247
1248     ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1249
1250     y(free);
1251     setlocale(LC_NUMERIC, "");
1252 }