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