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