]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Merge pull request #3697 from orestisf1993/ewmh
[i3/i3] / src / ipc.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
8  *
9  */
10 #include "all.h"
11
12 #include "yajl_utils.h"
13
14 #include <stdint.h>
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)
26 all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
27
28 /*
29  * Puts the given socket file descriptor into non-blocking mode or dies if
30  * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
31  * IPC model because we should by no means block the window manager.
32  *
33  */
34 static void set_nonblock(int sockfd) {
35     int flags = fcntl(sockfd, F_GETFL, 0);
36     flags |= O_NONBLOCK;
37     if (fcntl(sockfd, F_SETFL, flags) < 0)
38         err(-1, "Could not set O_NONBLOCK");
39 }
40
41 static void ipc_client_timeout(EV_P_ ev_timer *w, int revents);
42 static void ipc_socket_writeable_cb(EV_P_ struct ev_io *w, int revents);
43
44 static ev_tstamp kill_timeout = 10.0;
45
46 void ipc_set_kill_timeout(ev_tstamp new) {
47     kill_timeout = new;
48 }
49
50 /*
51  * Try to write the contents of the pending buffer to the client's subscription
52  * socket. Will set, reset or clear the timeout and io write callbacks depending
53  * on the result of the write operation.
54  *
55  */
56 static void ipc_push_pending(ipc_client *client) {
57     const ssize_t result = writeall_nonblock(client->fd, client->buffer, client->buffer_size);
58     if (result < 0) {
59         return;
60     }
61
62     if ((size_t)result == client->buffer_size) {
63         /* Everything was written successfully: clear the timer and stop the io
64          * callback. */
65         FREE(client->buffer);
66         client->buffer_size = 0;
67         if (client->timeout) {
68             ev_timer_stop(main_loop, client->timeout);
69             FREE(client->timeout);
70         }
71         ev_io_stop(main_loop, client->write_callback);
72         return;
73     }
74
75     /* Otherwise, make sure that the io callback is enabled and create a new
76      * timer if needed. */
77     ev_io_start(main_loop, client->write_callback);
78
79     if (!client->timeout) {
80         struct ev_timer *timeout = scalloc(1, sizeof(struct ev_timer));
81         ev_timer_init(timeout, ipc_client_timeout, kill_timeout, 0.);
82         timeout->data = client;
83         client->timeout = timeout;
84         ev_set_priority(timeout, EV_MINPRI);
85         ev_timer_start(main_loop, client->timeout);
86     } else if (result > 0) {
87         /* Keep the old timeout when nothing is written. Otherwise, we would
88          * keep a dead connection by continuously renewing its timeouts. */
89         ev_timer_stop(main_loop, client->timeout);
90         ev_timer_set(client->timeout, kill_timeout, 0.0);
91         ev_timer_start(main_loop, client->timeout);
92     }
93     if (result == 0) {
94         return;
95     }
96
97     /* Shift the buffer to the left and reduce the allocated space. */
98     client->buffer_size -= (size_t)result;
99     memmove(client->buffer, client->buffer + result, client->buffer_size);
100     client->buffer = srealloc(client->buffer, client->buffer_size);
101 }
102
103 /*
104  * Given a message and a message type, create the corresponding header, merge it
105  * with the message and append it to the given client's output buffer. Also,
106  * send the message if the client's buffer was empty.
107  *
108  */
109 static void ipc_send_client_message(ipc_client *client, size_t size, const uint32_t message_type, const uint8_t *payload) {
110     const i3_ipc_header_t header = {
111         .magic = {'i', '3', '-', 'i', 'p', 'c'},
112         .size = size,
113         .type = message_type};
114     const size_t header_size = sizeof(i3_ipc_header_t);
115     const size_t message_size = header_size + size;
116
117     const bool push_now = (client->buffer_size == 0);
118     client->buffer = srealloc(client->buffer, client->buffer_size + message_size);
119     memcpy(client->buffer + client->buffer_size, ((void *)&header), header_size);
120     memcpy(client->buffer + client->buffer_size + header_size, payload, size);
121     client->buffer_size += message_size;
122
123     if (push_now) {
124         ipc_push_pending(client);
125     }
126 }
127
128 static void free_ipc_client(ipc_client *client) {
129     DLOG("Disconnecting client on fd %d\n", client->fd);
130     close(client->fd);
131
132     ev_io_stop(main_loop, client->read_callback);
133     FREE(client->read_callback);
134     ev_io_stop(main_loop, client->write_callback);
135     FREE(client->write_callback);
136     if (client->timeout) {
137         ev_timer_stop(main_loop, client->timeout);
138         FREE(client->timeout);
139     }
140
141     free(client->buffer);
142
143     for (int i = 0; i < client->num_events; i++) {
144         free(client->events[i]);
145     }
146     free(client->events);
147     TAILQ_REMOVE(&all_clients, client, clients);
148     free(client);
149 }
150
151 /*
152  * Sends the specified event to all IPC clients which are currently connected
153  * and subscribed to this kind of event.
154  *
155  */
156 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
157     ipc_client *current;
158     TAILQ_FOREACH(current, &all_clients, clients) {
159         for (int i = 0; i < current->num_events; i++) {
160             if (strcasecmp(current->events[i], event) == 0) {
161                 ipc_send_client_message(current, strlen(payload), message_type, (uint8_t *)payload);
162                 break;
163             }
164         }
165     }
166 }
167
168 /*
169  * For shutdown events, we send the reason for the shutdown.
170  */
171 static void ipc_send_shutdown_event(shutdown_reason_t reason) {
172     yajl_gen gen = ygenalloc();
173     y(map_open);
174
175     ystr("change");
176
177     if (reason == SHUTDOWN_REASON_RESTART) {
178         ystr("restart");
179     } else if (reason == SHUTDOWN_REASON_EXIT) {
180         ystr("exit");
181     }
182
183     y(map_close);
184
185     const unsigned char *payload;
186     ylength length;
187
188     y(get_buf, &payload, &length);
189     ipc_send_event("shutdown", I3_IPC_EVENT_SHUTDOWN, (const char *)payload);
190
191     y(free);
192 }
193
194 /*
195  * Calls shutdown() on each socket and closes it. This function is to be called
196  * when exiting or restarting only!
197  *
198  */
199 void ipc_shutdown(shutdown_reason_t reason) {
200     ipc_send_shutdown_event(reason);
201
202     ipc_client *current;
203     while (!TAILQ_EMPTY(&all_clients)) {
204         current = TAILQ_FIRST(&all_clients);
205         shutdown(current->fd, SHUT_RDWR);
206         free_ipc_client(current);
207     }
208 }
209
210 /*
211  * Executes the command and returns whether it could be successfully parsed
212  * or not (at the moment, always returns true).
213  *
214  */
215 IPC_HANDLER(run_command) {
216     /* To get a properly terminated buffer, we copy
217      * message_size bytes out of the buffer */
218     char *command = sstrndup((const char *)message, message_size);
219     LOG("IPC: received: *%s*\n", command);
220     yajl_gen gen = yajl_gen_alloc(NULL);
221
222     CommandResult *result = parse_command(command, gen);
223     free(command);
224
225     if (result->needs_tree_render)
226         tree_render();
227
228     command_result_free(result);
229
230     const unsigned char *reply;
231     ylength length;
232     yajl_gen_get_buf(gen, &reply, &length);
233
234     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_COMMAND,
235                             (const uint8_t *)reply);
236
237     yajl_gen_free(gen);
238 }
239
240 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
241     ystr(name);
242     y(map_open);
243     ystr("x");
244     y(integer, r.x);
245     ystr("y");
246     y(integer, r.y);
247     ystr("width");
248     y(integer, r.width);
249     ystr("height");
250     y(integer, r.height);
251     y(map_close);
252 }
253
254 static void dump_event_state_mask(yajl_gen gen, Binding *bind) {
255     y(array_open);
256     for (int i = 0; i < 20; i++) {
257         if (bind->event_state_mask & (1 << i)) {
258             switch (1 << i) {
259                 case XCB_KEY_BUT_MASK_SHIFT:
260                     ystr("shift");
261                     break;
262                 case XCB_KEY_BUT_MASK_LOCK:
263                     ystr("lock");
264                     break;
265                 case XCB_KEY_BUT_MASK_CONTROL:
266                     ystr("ctrl");
267                     break;
268                 case XCB_KEY_BUT_MASK_MOD_1:
269                     ystr("Mod1");
270                     break;
271                 case XCB_KEY_BUT_MASK_MOD_2:
272                     ystr("Mod2");
273                     break;
274                 case XCB_KEY_BUT_MASK_MOD_3:
275                     ystr("Mod3");
276                     break;
277                 case XCB_KEY_BUT_MASK_MOD_4:
278                     ystr("Mod4");
279                     break;
280                 case XCB_KEY_BUT_MASK_MOD_5:
281                     ystr("Mod5");
282                     break;
283                 case XCB_KEY_BUT_MASK_BUTTON_1:
284                     ystr("Button1");
285                     break;
286                 case XCB_KEY_BUT_MASK_BUTTON_2:
287                     ystr("Button2");
288                     break;
289                 case XCB_KEY_BUT_MASK_BUTTON_3:
290                     ystr("Button3");
291                     break;
292                 case XCB_KEY_BUT_MASK_BUTTON_4:
293                     ystr("Button4");
294                     break;
295                 case XCB_KEY_BUT_MASK_BUTTON_5:
296                     ystr("Button5");
297                     break;
298                 case (I3_XKB_GROUP_MASK_1 << 16):
299                     ystr("Group1");
300                     break;
301                 case (I3_XKB_GROUP_MASK_2 << 16):
302                     ystr("Group2");
303                     break;
304                 case (I3_XKB_GROUP_MASK_3 << 16):
305                     ystr("Group3");
306                     break;
307                 case (I3_XKB_GROUP_MASK_4 << 16):
308                     ystr("Group4");
309                     break;
310             }
311         }
312     }
313     y(array_close);
314 }
315
316 static void dump_binding(yajl_gen gen, Binding *bind) {
317     y(map_open);
318     ystr("input_code");
319     y(integer, bind->keycode);
320
321     ystr("input_type");
322     ystr((const char *)(bind->input_type == B_KEYBOARD ? "keyboard" : "mouse"));
323
324     ystr("symbol");
325     if (bind->symbol == NULL)
326         y(null);
327     else
328         ystr(bind->symbol);
329
330     ystr("command");
331     ystr(bind->command);
332
333     // This key is only provided for compatibility, new programs should use
334     // event_state_mask instead.
335     ystr("mods");
336     dump_event_state_mask(gen, bind);
337
338     ystr("event_state_mask");
339     dump_event_state_mask(gen, bind);
340
341     y(map_close);
342 }
343
344 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
345     y(map_open);
346     ystr("id");
347     y(integer, (uintptr_t)con);
348
349     ystr("type");
350     switch (con->type) {
351         case CT_ROOT:
352             ystr("root");
353             break;
354         case CT_OUTPUT:
355             ystr("output");
356             break;
357         case CT_CON:
358             ystr("con");
359             break;
360         case CT_FLOATING_CON:
361             ystr("floating_con");
362             break;
363         case CT_WORKSPACE:
364             ystr("workspace");
365             break;
366         case CT_DOCKAREA:
367             ystr("dockarea");
368             break;
369     }
370
371     /* provided for backwards compatibility only. */
372     ystr("orientation");
373     if (!con_is_split(con))
374         ystr("none");
375     else {
376         if (con_orientation(con) == HORIZ)
377             ystr("horizontal");
378         else
379             ystr("vertical");
380     }
381
382     ystr("scratchpad_state");
383     switch (con->scratchpad_state) {
384         case SCRATCHPAD_NONE:
385             ystr("none");
386             break;
387         case SCRATCHPAD_FRESH:
388             ystr("fresh");
389             break;
390         case SCRATCHPAD_CHANGED:
391             ystr("changed");
392             break;
393     }
394
395     ystr("percent");
396     if (con->percent == 0.0)
397         y(null);
398     else
399         y(double, con->percent);
400
401     ystr("urgent");
402     y(bool, con->urgent);
403
404     if (!TAILQ_EMPTY(&(con->marks_head))) {
405         ystr("marks");
406         y(array_open);
407
408         mark_t *mark;
409         TAILQ_FOREACH(mark, &(con->marks_head), marks) {
410             ystr(mark->name);
411         }
412
413         y(array_close);
414     }
415
416     ystr("focused");
417     y(bool, (con == focused));
418
419     if (con->type != CT_ROOT && con->type != CT_OUTPUT) {
420         ystr("output");
421         ystr(con_get_output(con)->name);
422     }
423
424     ystr("layout");
425     switch (con->layout) {
426         case L_DEFAULT:
427             DLOG("About to dump layout=default, this is a bug in the code.\n");
428             assert(false);
429             break;
430         case L_SPLITV:
431             ystr("splitv");
432             break;
433         case L_SPLITH:
434             ystr("splith");
435             break;
436         case L_STACKED:
437             ystr("stacked");
438             break;
439         case L_TABBED:
440             ystr("tabbed");
441             break;
442         case L_DOCKAREA:
443             ystr("dockarea");
444             break;
445         case L_OUTPUT:
446             ystr("output");
447             break;
448     }
449
450     ystr("workspace_layout");
451     switch (con->workspace_layout) {
452         case L_DEFAULT:
453             ystr("default");
454             break;
455         case L_STACKED:
456             ystr("stacked");
457             break;
458         case L_TABBED:
459             ystr("tabbed");
460             break;
461         default:
462             DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
463             assert(false);
464             break;
465     }
466
467     ystr("last_split_layout");
468     switch (con->layout) {
469         case L_SPLITV:
470             ystr("splitv");
471             break;
472         default:
473             ystr("splith");
474             break;
475     }
476
477     ystr("border");
478     switch (con->border_style) {
479         case BS_NORMAL:
480             ystr("normal");
481             break;
482         case BS_NONE:
483             ystr("none");
484             break;
485         case BS_PIXEL:
486             ystr("pixel");
487             break;
488     }
489
490     ystr("current_border_width");
491     y(integer, con->current_border_width);
492
493     dump_rect(gen, "rect", con->rect);
494     dump_rect(gen, "deco_rect", con->deco_rect);
495     dump_rect(gen, "window_rect", con->window_rect);
496     dump_rect(gen, "geometry", con->geometry);
497
498     ystr("name");
499     if (con->window && con->window->name)
500         ystr(i3string_as_utf8(con->window->name));
501     else if (con->name != NULL)
502         ystr(con->name);
503     else
504         y(null);
505
506     if (con->title_format != NULL) {
507         ystr("title_format");
508         ystr(con->title_format);
509     }
510
511     if (con->type == CT_WORKSPACE) {
512         ystr("num");
513         y(integer, con->num);
514     }
515
516     ystr("window");
517     if (con->window)
518         y(integer, con->window->id);
519     else
520         y(null);
521
522     if (con->window && !inplace_restart) {
523         /* Window properties are useless to preserve when restarting because
524          * they will be queried again anyway. However, for i3-save-tree(1),
525          * they are very useful and save i3-save-tree dealing with X11. */
526         ystr("window_properties");
527         y(map_open);
528
529 #define DUMP_PROPERTY(key, prop_name)         \
530     do {                                      \
531         if (con->window->prop_name != NULL) { \
532             ystr(key);                        \
533             ystr(con->window->prop_name);     \
534         }                                     \
535     } while (0)
536
537         DUMP_PROPERTY("class", class_class);
538         DUMP_PROPERTY("instance", class_instance);
539         DUMP_PROPERTY("window_role", role);
540
541         if (con->window->name != NULL) {
542             ystr("title");
543             ystr(i3string_as_utf8(con->window->name));
544         }
545
546         ystr("transient_for");
547         if (con->window->transient_for == XCB_NONE)
548             y(null);
549         else
550             y(integer, con->window->transient_for);
551
552         y(map_close);
553     }
554
555     ystr("nodes");
556     y(array_open);
557     Con *node;
558     if (con->type != CT_DOCKAREA || !inplace_restart) {
559         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
560             dump_node(gen, node, inplace_restart);
561         }
562     }
563     y(array_close);
564
565     ystr("floating_nodes");
566     y(array_open);
567     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
568         dump_node(gen, node, inplace_restart);
569     }
570     y(array_close);
571
572     ystr("focus");
573     y(array_open);
574     TAILQ_FOREACH(node, &(con->focus_head), focused) {
575         y(integer, (uintptr_t)node);
576     }
577     y(array_close);
578
579     ystr("fullscreen_mode");
580     y(integer, con->fullscreen_mode);
581
582     ystr("sticky");
583     y(bool, con->sticky);
584
585     ystr("floating");
586     switch (con->floating) {
587         case FLOATING_AUTO_OFF:
588             ystr("auto_off");
589             break;
590         case FLOATING_AUTO_ON:
591             ystr("auto_on");
592             break;
593         case FLOATING_USER_OFF:
594             ystr("user_off");
595             break;
596         case FLOATING_USER_ON:
597             ystr("user_on");
598             break;
599     }
600
601     ystr("swallows");
602     y(array_open);
603     Match *match;
604     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
605         /* We will generate a new restart_mode match specification after this
606          * loop, so skip this one. */
607         if (match->restart_mode)
608             continue;
609         y(map_open);
610         if (match->dock != M_DONTCHECK) {
611             ystr("dock");
612             y(integer, match->dock);
613             ystr("insert_where");
614             y(integer, match->insert_where);
615         }
616
617 #define DUMP_REGEX(re_name)                \
618     do {                                   \
619         if (match->re_name != NULL) {      \
620             ystr(#re_name);                \
621             ystr(match->re_name->pattern); \
622         }                                  \
623     } while (0)
624
625         DUMP_REGEX(class);
626         DUMP_REGEX(instance);
627         DUMP_REGEX(window_role);
628         DUMP_REGEX(title);
629
630 #undef DUMP_REGEX
631         y(map_close);
632     }
633
634     if (inplace_restart) {
635         if (con->window != NULL) {
636             y(map_open);
637             ystr("id");
638             y(integer, con->window->id);
639             ystr("restart_mode");
640             y(bool, true);
641             y(map_close);
642         }
643     }
644     y(array_close);
645
646     if (inplace_restart && con->window != NULL) {
647         ystr("depth");
648         y(integer, con->depth);
649     }
650
651     if (inplace_restart && con->type == CT_ROOT && previous_workspace_name) {
652         ystr("previous_workspace_name");
653         ystr(previous_workspace_name);
654     }
655
656     y(map_close);
657 }
658
659 static void dump_bar_bindings(yajl_gen gen, Barconfig *config) {
660     if (TAILQ_EMPTY(&(config->bar_bindings)))
661         return;
662
663     ystr("bindings");
664     y(array_open);
665
666     struct Barbinding *current;
667     TAILQ_FOREACH(current, &(config->bar_bindings), bindings) {
668         y(map_open);
669
670         ystr("input_code");
671         y(integer, current->input_code);
672         ystr("command");
673         ystr(current->command);
674         ystr("release");
675         y(bool, current->release == B_UPON_KEYRELEASE);
676
677         y(map_close);
678     }
679
680     y(array_close);
681 }
682
683 static char *canonicalize_output_name(char *name) {
684     /* Do not canonicalize special output names. */
685     if (strcasecmp(name, "primary") == 0) {
686         return name;
687     }
688     Output *output = get_output_by_name(name, false);
689     return output ? output_primary_name(output) : name;
690 }
691
692 static void dump_bar_config(yajl_gen gen, Barconfig *config) {
693     y(map_open);
694
695     ystr("id");
696     ystr(config->id);
697
698     if (config->num_outputs > 0) {
699         ystr("outputs");
700         y(array_open);
701         for (int c = 0; c < config->num_outputs; c++) {
702             /* Convert monitor names (RandR ≥ 1.5) or output names
703              * (RandR < 1.5) into monitor names. This way, existing
704              * configs which use output names transparently keep
705              * working. */
706             ystr(canonicalize_output_name(config->outputs[c]));
707         }
708         y(array_close);
709     }
710
711     if (!TAILQ_EMPTY(&(config->tray_outputs))) {
712         ystr("tray_outputs");
713         y(array_open);
714
715         struct tray_output_t *tray_output;
716         TAILQ_FOREACH(tray_output, &(config->tray_outputs), tray_outputs) {
717             ystr(canonicalize_output_name(tray_output->output));
718         }
719
720         y(array_close);
721     }
722
723 #define YSTR_IF_SET(name)       \
724     do {                        \
725         if (config->name) {     \
726             ystr(#name);        \
727             ystr(config->name); \
728         }                       \
729     } while (0)
730
731     ystr("tray_padding");
732     y(integer, config->tray_padding);
733
734     YSTR_IF_SET(socket_path);
735
736     ystr("mode");
737     switch (config->mode) {
738         case M_HIDE:
739             ystr("hide");
740             break;
741         case M_INVISIBLE:
742             ystr("invisible");
743             break;
744         case M_DOCK:
745         default:
746             ystr("dock");
747             break;
748     }
749
750     ystr("hidden_state");
751     switch (config->hidden_state) {
752         case S_SHOW:
753             ystr("show");
754             break;
755         case S_HIDE:
756         default:
757             ystr("hide");
758             break;
759     }
760
761     ystr("modifier");
762     y(integer, config->modifier);
763
764     dump_bar_bindings(gen, config);
765
766     ystr("position");
767     if (config->position == P_BOTTOM)
768         ystr("bottom");
769     else
770         ystr("top");
771
772     YSTR_IF_SET(status_command);
773     YSTR_IF_SET(font);
774
775     if (config->separator_symbol) {
776         ystr("separator_symbol");
777         ystr(config->separator_symbol);
778     }
779
780     ystr("workspace_buttons");
781     y(bool, !config->hide_workspace_buttons);
782
783     ystr("strip_workspace_numbers");
784     y(bool, config->strip_workspace_numbers);
785
786     ystr("strip_workspace_name");
787     y(bool, config->strip_workspace_name);
788
789     ystr("binding_mode_indicator");
790     y(bool, !config->hide_binding_mode_indicator);
791
792     ystr("verbose");
793     y(bool, config->verbose);
794
795 #undef YSTR_IF_SET
796 #define YSTR_IF_SET(name)              \
797     do {                               \
798         if (config->colors.name) {     \
799             ystr(#name);               \
800             ystr(config->colors.name); \
801         }                              \
802     } while (0)
803
804     ystr("colors");
805     y(map_open);
806     YSTR_IF_SET(background);
807     YSTR_IF_SET(statusline);
808     YSTR_IF_SET(separator);
809     YSTR_IF_SET(focused_background);
810     YSTR_IF_SET(focused_statusline);
811     YSTR_IF_SET(focused_separator);
812     YSTR_IF_SET(focused_workspace_border);
813     YSTR_IF_SET(focused_workspace_bg);
814     YSTR_IF_SET(focused_workspace_text);
815     YSTR_IF_SET(active_workspace_border);
816     YSTR_IF_SET(active_workspace_bg);
817     YSTR_IF_SET(active_workspace_text);
818     YSTR_IF_SET(inactive_workspace_border);
819     YSTR_IF_SET(inactive_workspace_bg);
820     YSTR_IF_SET(inactive_workspace_text);
821     YSTR_IF_SET(urgent_workspace_border);
822     YSTR_IF_SET(urgent_workspace_bg);
823     YSTR_IF_SET(urgent_workspace_text);
824     YSTR_IF_SET(binding_mode_border);
825     YSTR_IF_SET(binding_mode_bg);
826     YSTR_IF_SET(binding_mode_text);
827     y(map_close);
828
829     y(map_close);
830 #undef YSTR_IF_SET
831 }
832
833 IPC_HANDLER(tree) {
834     setlocale(LC_NUMERIC, "C");
835     yajl_gen gen = ygenalloc();
836     dump_node(gen, croot, false);
837     setlocale(LC_NUMERIC, "");
838
839     const unsigned char *payload;
840     ylength length;
841     y(get_buf, &payload, &length);
842
843     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_TREE, payload);
844     y(free);
845 }
846
847 /*
848  * Formats the reply message for a GET_WORKSPACES request and sends it to the
849  * client
850  *
851  */
852 IPC_HANDLER(get_workspaces) {
853     yajl_gen gen = ygenalloc();
854     y(array_open);
855
856     Con *focused_ws = con_get_workspace(focused);
857
858     Con *output;
859     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
860         if (con_is_internal(output))
861             continue;
862         Con *ws;
863         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
864             assert(ws->type == CT_WORKSPACE);
865             y(map_open);
866
867             ystr("num");
868             y(integer, ws->num);
869
870             ystr("name");
871             ystr(ws->name);
872
873             ystr("visible");
874             y(bool, workspace_is_visible(ws));
875
876             ystr("focused");
877             y(bool, ws == focused_ws);
878
879             ystr("rect");
880             y(map_open);
881             ystr("x");
882             y(integer, ws->rect.x);
883             ystr("y");
884             y(integer, ws->rect.y);
885             ystr("width");
886             y(integer, ws->rect.width);
887             ystr("height");
888             y(integer, ws->rect.height);
889             y(map_close);
890
891             ystr("output");
892             ystr(output->name);
893
894             ystr("urgent");
895             y(bool, ws->urgent);
896
897             y(map_close);
898         }
899     }
900
901     y(array_close);
902
903     const unsigned char *payload;
904     ylength length;
905     y(get_buf, &payload, &length);
906
907     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
908     y(free);
909 }
910
911 /*
912  * Formats the reply message for a GET_OUTPUTS request and sends it to the
913  * client
914  *
915  */
916 IPC_HANDLER(get_outputs) {
917     yajl_gen gen = ygenalloc();
918     y(array_open);
919
920     Output *output;
921     TAILQ_FOREACH(output, &outputs, outputs) {
922         y(map_open);
923
924         ystr("name");
925         ystr(output_primary_name(output));
926
927         ystr("active");
928         y(bool, output->active);
929
930         ystr("primary");
931         y(bool, output->primary);
932
933         ystr("rect");
934         y(map_open);
935         ystr("x");
936         y(integer, output->rect.x);
937         ystr("y");
938         y(integer, output->rect.y);
939         ystr("width");
940         y(integer, output->rect.width);
941         ystr("height");
942         y(integer, output->rect.height);
943         y(map_close);
944
945         ystr("current_workspace");
946         Con *ws = NULL;
947         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
948             ystr(ws->name);
949         else
950             y(null);
951
952         y(map_close);
953     }
954
955     y(array_close);
956
957     const unsigned char *payload;
958     ylength length;
959     y(get_buf, &payload, &length);
960
961     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
962     y(free);
963 }
964
965 /*
966  * Formats the reply message for a GET_MARKS request and sends it to the
967  * client
968  *
969  */
970 IPC_HANDLER(get_marks) {
971     yajl_gen gen = ygenalloc();
972     y(array_open);
973
974     Con *con;
975     TAILQ_FOREACH(con, &all_cons, all_cons) {
976         mark_t *mark;
977         TAILQ_FOREACH(mark, &(con->marks_head), marks) {
978             ystr(mark->name);
979         }
980     }
981
982     y(array_close);
983
984     const unsigned char *payload;
985     ylength length;
986     y(get_buf, &payload, &length);
987
988     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_MARKS, payload);
989     y(free);
990 }
991
992 /*
993  * Returns the version of i3
994  *
995  */
996 IPC_HANDLER(get_version) {
997     yajl_gen gen = ygenalloc();
998     y(map_open);
999
1000     ystr("major");
1001     y(integer, MAJOR_VERSION);
1002
1003     ystr("minor");
1004     y(integer, MINOR_VERSION);
1005
1006     ystr("patch");
1007     y(integer, PATCH_VERSION);
1008
1009     ystr("human_readable");
1010     ystr(i3_version);
1011
1012     ystr("loaded_config_file_name");
1013     ystr(current_configpath);
1014
1015     y(map_close);
1016
1017     const unsigned char *payload;
1018     ylength length;
1019     y(get_buf, &payload, &length);
1020
1021     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_VERSION, payload);
1022     y(free);
1023 }
1024
1025 /*
1026  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
1027  * client.
1028  *
1029  */
1030 IPC_HANDLER(get_bar_config) {
1031     yajl_gen gen = ygenalloc();
1032
1033     /* If no ID was passed, we return a JSON array with all IDs */
1034     if (message_size == 0) {
1035         y(array_open);
1036         Barconfig *current;
1037         TAILQ_FOREACH(current, &barconfigs, configs) {
1038             ystr(current->id);
1039         }
1040         y(array_close);
1041
1042         const unsigned char *payload;
1043         ylength length;
1044         y(get_buf, &payload, &length);
1045
1046         ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1047         y(free);
1048         return;
1049     }
1050
1051     /* To get a properly terminated buffer, we copy
1052      * message_size bytes out of the buffer */
1053     char *bar_id = NULL;
1054     sasprintf(&bar_id, "%.*s", message_size, message);
1055     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
1056     Barconfig *current, *config = NULL;
1057     TAILQ_FOREACH(current, &barconfigs, configs) {
1058         if (strcmp(current->id, bar_id) != 0)
1059             continue;
1060
1061         config = current;
1062         break;
1063     }
1064     free(bar_id);
1065
1066     if (!config) {
1067         /* If we did not find a config for the given ID, the reply will contain
1068          * a null 'id' field. */
1069         y(map_open);
1070
1071         ystr("id");
1072         y(null);
1073
1074         y(map_close);
1075     } else {
1076         dump_bar_config(gen, config);
1077     }
1078
1079     const unsigned char *payload;
1080     ylength length;
1081     y(get_buf, &payload, &length);
1082
1083     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
1084     y(free);
1085 }
1086
1087 /*
1088  * Returns a list of configured binding modes
1089  *
1090  */
1091 IPC_HANDLER(get_binding_modes) {
1092     yajl_gen gen = ygenalloc();
1093
1094     y(array_open);
1095     struct Mode *mode;
1096     SLIST_FOREACH(mode, &modes, modes) {
1097         ystr(mode->name);
1098     }
1099     y(array_close);
1100
1101     const unsigned char *payload;
1102     ylength length;
1103     y(get_buf, &payload, &length);
1104
1105     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_BINDING_MODES, payload);
1106     y(free);
1107 }
1108
1109 /*
1110  * Callback for the YAJL parser (will be called when a string is parsed).
1111  *
1112  */
1113 static int add_subscription(void *extra, const unsigned char *s,
1114                             ylength len) {
1115     ipc_client *client = extra;
1116
1117     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
1118     int event = client->num_events;
1119
1120     client->num_events++;
1121     client->events = srealloc(client->events, client->num_events * sizeof(char *));
1122     /* We copy the string because it is not null-terminated and strndup()
1123      * is missing on some BSD systems */
1124     client->events[event] = scalloc(len + 1, 1);
1125     memcpy(client->events[event], s, len);
1126
1127     DLOG("client is now subscribed to:\n");
1128     for (int i = 0; i < client->num_events; i++) {
1129         DLOG("event %s\n", client->events[i]);
1130     }
1131     DLOG("(done)\n");
1132
1133     return 1;
1134 }
1135
1136 /*
1137  * Subscribes this connection to the event types which were given as a JSON
1138  * serialized array in the payload field of the message.
1139  *
1140  */
1141 IPC_HANDLER(subscribe) {
1142     yajl_handle p;
1143     yajl_status stat;
1144
1145     /* Setup the JSON parser */
1146     static yajl_callbacks callbacks = {
1147         .yajl_string = add_subscription,
1148     };
1149
1150     p = yalloc(&callbacks, (void *)client);
1151     stat = yajl_parse(p, (const unsigned char *)message, message_size);
1152     if (stat != yajl_status_ok) {
1153         unsigned char *err;
1154         err = yajl_get_error(p, true, (const unsigned char *)message,
1155                              message_size);
1156         ELOG("YAJL parse error: %s\n", err);
1157         yajl_free_error(p, err);
1158
1159         const char *reply = "{\"success\":false}";
1160         ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1161         yajl_free(p);
1162         return;
1163     }
1164     yajl_free(p);
1165     const char *reply = "{\"success\":true}";
1166     ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t *)reply);
1167
1168     if (client->first_tick_sent) {
1169         return;
1170     }
1171
1172     bool is_tick = false;
1173     for (int i = 0; i < client->num_events; i++) {
1174         if (strcmp(client->events[i], "tick") == 0) {
1175             is_tick = true;
1176             break;
1177         }
1178     }
1179     if (!is_tick) {
1180         return;
1181     }
1182
1183     client->first_tick_sent = true;
1184     const char *payload = "{\"first\":true,\"payload\":\"\"}";
1185     ipc_send_client_message(client, strlen(payload), I3_IPC_EVENT_TICK, (const uint8_t *)payload);
1186 }
1187
1188 /*
1189  * Returns the raw last loaded i3 configuration file contents.
1190  */
1191 IPC_HANDLER(get_config) {
1192     yajl_gen gen = ygenalloc();
1193
1194     y(map_open);
1195
1196     ystr("config");
1197     ystr(current_config);
1198
1199     y(map_close);
1200
1201     const unsigned char *payload;
1202     ylength length;
1203     y(get_buf, &payload, &length);
1204
1205     ipc_send_client_message(client, length, I3_IPC_REPLY_TYPE_CONFIG, payload);
1206     y(free);
1207 }
1208
1209 /*
1210  * Sends the tick event from the message payload to subscribers. Establishes a
1211  * synchronization point in event-related tests.
1212  */
1213 IPC_HANDLER(send_tick) {
1214     yajl_gen gen = ygenalloc();
1215
1216     y(map_open);
1217
1218     ystr("first");
1219     y(bool, false);
1220
1221     ystr("payload");
1222     yajl_gen_string(gen, (unsigned char *)message, message_size);
1223
1224     y(map_close);
1225
1226     const unsigned char *payload;
1227     ylength length;
1228     y(get_buf, &payload, &length);
1229
1230     ipc_send_event("tick", I3_IPC_EVENT_TICK, (const char *)payload);
1231     y(free);
1232
1233     const char *reply = "{\"success\":true}";
1234     ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_TICK, (const uint8_t *)reply);
1235     DLOG("Sent tick event\n");
1236 }
1237
1238 struct sync_state {
1239     char *last_key;
1240     uint32_t rnd;
1241     xcb_window_t window;
1242 };
1243
1244 static int _sync_json_key(void *extra, const unsigned char *val, size_t len) {
1245     struct sync_state *state = extra;
1246     FREE(state->last_key);
1247     state->last_key = scalloc(len + 1, 1);
1248     memcpy(state->last_key, val, len);
1249     return 1;
1250 }
1251
1252 static int _sync_json_int(void *extra, long long val) {
1253     struct sync_state *state = extra;
1254     if (strcasecmp(state->last_key, "rnd") == 0) {
1255         state->rnd = val;
1256     } else if (strcasecmp(state->last_key, "window") == 0) {
1257         state->window = (xcb_window_t)val;
1258     }
1259     return 1;
1260 }
1261
1262 IPC_HANDLER(sync) {
1263     yajl_handle p;
1264     yajl_status stat;
1265
1266     /* Setup the JSON parser */
1267     static yajl_callbacks callbacks = {
1268         .yajl_map_key = _sync_json_key,
1269         .yajl_integer = _sync_json_int,
1270     };
1271
1272     struct sync_state state;
1273     memset(&state, '\0', sizeof(struct sync_state));
1274     p = yalloc(&callbacks, (void *)&state);
1275     stat = yajl_parse(p, (const unsigned char *)message, message_size);
1276     FREE(state.last_key);
1277     if (stat != yajl_status_ok) {
1278         unsigned char *err;
1279         err = yajl_get_error(p, true, (const unsigned char *)message,
1280                              message_size);
1281         ELOG("YAJL parse error: %s\n", err);
1282         yajl_free_error(p, err);
1283
1284         const char *reply = "{\"success\":false}";
1285         ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1286         yajl_free(p);
1287         return;
1288     }
1289     yajl_free(p);
1290
1291     DLOG("received IPC sync request (rnd = %d, window = 0x%08x)\n", state.rnd, state.window);
1292     sync_respond(state.window, state.rnd);
1293     const char *reply = "{\"success\":true}";
1294     ipc_send_client_message(client, strlen(reply), I3_IPC_REPLY_TYPE_SYNC, (const uint8_t *)reply);
1295 }
1296
1297 /* The index of each callback function corresponds to the numeric
1298  * value of the message type (see include/i3/ipc.h) */
1299 handler_t handlers[12] = {
1300     handle_run_command,
1301     handle_get_workspaces,
1302     handle_subscribe,
1303     handle_get_outputs,
1304     handle_tree,
1305     handle_get_marks,
1306     handle_get_bar_config,
1307     handle_get_version,
1308     handle_get_binding_modes,
1309     handle_get_config,
1310     handle_send_tick,
1311     handle_sync,
1312 };
1313
1314 /*
1315  * Handler for activity on a client connection, receives a message from a
1316  * client.
1317  *
1318  * For now, the maximum message size is 2048. I’m not sure for what the
1319  * IPC interface will be used in the future, thus I’m not implementing a
1320  * mechanism for arbitrarily long messages, as it seems like overkill
1321  * at the moment.
1322  *
1323  */
1324 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
1325     uint32_t message_type;
1326     uint32_t message_length;
1327     uint8_t *message = NULL;
1328     ipc_client *client = (ipc_client *)w->data;
1329     assert(client->fd == w->fd);
1330
1331     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
1332     /* EOF or other error */
1333     if (ret < 0) {
1334         /* Was this a spurious read? See ev(3) */
1335         if (ret == -1 && errno == EAGAIN) {
1336             FREE(message);
1337             return;
1338         }
1339
1340         /* If not, there was some kind of error. We don’t bother and close the
1341          * connection. Delete the client from the list of clients. */
1342         free_ipc_client(client);
1343         FREE(message);
1344         return;
1345     }
1346
1347     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
1348         DLOG("Unhandled message type: %d\n", message_type);
1349     else {
1350         handler_t h = handlers[message_type];
1351         h(client, message, 0, message_length, message_type);
1352     }
1353
1354     FREE(message);
1355 }
1356
1357 static void ipc_client_timeout(EV_P_ ev_timer *w, int revents) {
1358     /* No need to be polite and check for writeability, the other callback would
1359      * have been called by now. */
1360     ipc_client *client = (ipc_client *)w->data;
1361
1362     char *cmdline = NULL;
1363 #if defined(__linux__) && defined(SO_PEERCRED)
1364     struct ucred peercred;
1365     socklen_t so_len = sizeof(peercred);
1366     if (getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0) {
1367         goto end;
1368     }
1369     char *exepath;
1370     sasprintf(&exepath, "/proc/%d/cmdline", peercred.pid);
1371
1372     int fd = open(exepath, O_RDONLY);
1373     free(exepath);
1374     if (fd == -1) {
1375         goto end;
1376     }
1377     char buf[512] = {'\0'}; /* cut off cmdline for the error message. */
1378     const ssize_t n = read(fd, buf, sizeof(buf));
1379     close(fd);
1380     if (n < 0) {
1381         goto end;
1382     }
1383     for (char *walk = buf; walk < buf + n - 1; walk++) {
1384         if (*walk == '\0') {
1385             *walk = ' ';
1386         }
1387     }
1388     cmdline = buf;
1389
1390     if (cmdline) {
1391         ELOG("client %p with pid %d and cmdline '%s' on fd %d timed out, killing\n", client, peercred.pid, cmdline, client->fd);
1392     }
1393
1394 end:
1395 #endif
1396     if (!cmdline) {
1397         ELOG("client %p on fd %d timed out, killing\n", client, client->fd);
1398     }
1399
1400     free_ipc_client(client);
1401 }
1402
1403 static void ipc_socket_writeable_cb(EV_P_ ev_io *w, int revents) {
1404     DLOG("fd %d writeable\n", w->fd);
1405     ipc_client *client = (ipc_client *)w->data;
1406
1407     /* If this callback is called then there should be a corresponding active
1408      * timer. */
1409     assert(client->timeout != NULL);
1410     ipc_push_pending(client);
1411 }
1412
1413 /*
1414  * Handler for activity on the listening socket, meaning that a new client
1415  * has just connected and we should accept() him. Sets up the event handler
1416  * for activity on the new connection and inserts the file descriptor into
1417  * the list of clients.
1418  *
1419  */
1420 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
1421     struct sockaddr_un peer;
1422     socklen_t len = sizeof(struct sockaddr_un);
1423     int fd;
1424     if ((fd = accept(w->fd, (struct sockaddr *)&peer, &len)) < 0) {
1425         if (errno != EINTR) {
1426             perror("accept()");
1427         }
1428         return;
1429     }
1430
1431     /* Close this file descriptor on exec() */
1432     (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
1433
1434     set_nonblock(fd);
1435
1436     ipc_client *client = scalloc(1, sizeof(ipc_client));
1437     client->fd = fd;
1438
1439     client->read_callback = scalloc(1, sizeof(struct ev_io));
1440     client->read_callback->data = client;
1441     ev_io_init(client->read_callback, ipc_receive_message, fd, EV_READ);
1442     ev_io_start(EV_A_ client->read_callback);
1443
1444     client->write_callback = scalloc(1, sizeof(struct ev_io));
1445     client->write_callback->data = client;
1446     ev_io_init(client->write_callback, ipc_socket_writeable_cb, fd, EV_WRITE);
1447
1448     DLOG("IPC: new client connected on fd %d\n", w->fd);
1449     TAILQ_INSERT_TAIL(&all_clients, client, clients);
1450 }
1451
1452 /*
1453  * Creates the UNIX domain socket at the given path, sets it to non-blocking
1454  * mode, bind()s and listen()s on it.
1455  *
1456  */
1457 int ipc_create_socket(const char *filename) {
1458     int sockfd;
1459
1460     FREE(current_socketpath);
1461
1462     char *resolved = resolve_tilde(filename);
1463     DLOG("Creating IPC-socket at %s\n", resolved);
1464     char *copy = sstrdup(resolved);
1465     const char *dir = dirname(copy);
1466     if (!path_exists(dir))
1467         mkdirp(dir, DEFAULT_DIR_MODE);
1468     free(copy);
1469
1470     /* Unlink the unix domain socket before */
1471     unlink(resolved);
1472
1473     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
1474         perror("socket()");
1475         free(resolved);
1476         return -1;
1477     }
1478
1479     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1480
1481     struct sockaddr_un addr;
1482     memset(&addr, 0, sizeof(struct sockaddr_un));
1483     addr.sun_family = AF_LOCAL;
1484     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1485     if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
1486         perror("bind()");
1487         free(resolved);
1488         return -1;
1489     }
1490
1491     set_nonblock(sockfd);
1492
1493     if (listen(sockfd, 5) < 0) {
1494         perror("listen()");
1495         free(resolved);
1496         return -1;
1497     }
1498
1499     current_socketpath = resolved;
1500     return sockfd;
1501 }
1502
1503 /*
1504  * Generates a json workspace event. Returns a dynamically allocated yajl
1505  * generator. Free with yajl_gen_free().
1506  */
1507 yajl_gen ipc_marshal_workspace_event(const char *change, Con *current, Con *old) {
1508     setlocale(LC_NUMERIC, "C");
1509     yajl_gen gen = ygenalloc();
1510
1511     y(map_open);
1512
1513     ystr("change");
1514     ystr(change);
1515
1516     ystr("current");
1517     if (current == NULL)
1518         y(null);
1519     else
1520         dump_node(gen, current, false);
1521
1522     ystr("old");
1523     if (old == NULL)
1524         y(null);
1525     else
1526         dump_node(gen, old, false);
1527
1528     y(map_close);
1529
1530     setlocale(LC_NUMERIC, "");
1531
1532     return gen;
1533 }
1534
1535 /*
1536  * For the workspace events we send, along with the usual "change" field, also
1537  * the workspace container in "current". For focus events, we send the
1538  * previously focused workspace in "old".
1539  */
1540 void ipc_send_workspace_event(const char *change, Con *current, Con *old) {
1541     yajl_gen gen = ipc_marshal_workspace_event(change, current, old);
1542
1543     const unsigned char *payload;
1544     ylength length;
1545     y(get_buf, &payload, &length);
1546
1547     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
1548
1549     y(free);
1550 }
1551
1552 /*
1553  * For the window events we send, along the usual "change" field,
1554  * also the window container, in "container".
1555  */
1556 void ipc_send_window_event(const char *property, Con *con) {
1557     DLOG("Issue IPC window %s event (con = %p, window = 0x%08x)\n",
1558          property, con, (con->window ? con->window->id : XCB_WINDOW_NONE));
1559
1560     setlocale(LC_NUMERIC, "C");
1561     yajl_gen gen = ygenalloc();
1562
1563     y(map_open);
1564
1565     ystr("change");
1566     ystr(property);
1567
1568     ystr("container");
1569     dump_node(gen, con, false);
1570
1571     y(map_close);
1572
1573     const unsigned char *payload;
1574     ylength length;
1575     y(get_buf, &payload, &length);
1576
1577     ipc_send_event("window", I3_IPC_EVENT_WINDOW, (const char *)payload);
1578     y(free);
1579     setlocale(LC_NUMERIC, "");
1580 }
1581
1582 /*
1583  * For the barconfig update events, we send the serialized barconfig.
1584  */
1585 void ipc_send_barconfig_update_event(Barconfig *barconfig) {
1586     DLOG("Issue barconfig_update event for id = %s\n", barconfig->id);
1587     setlocale(LC_NUMERIC, "C");
1588     yajl_gen gen = ygenalloc();
1589
1590     dump_bar_config(gen, barconfig);
1591
1592     const unsigned char *payload;
1593     ylength length;
1594     y(get_buf, &payload, &length);
1595
1596     ipc_send_event("barconfig_update", I3_IPC_EVENT_BARCONFIG_UPDATE, (const char *)payload);
1597     y(free);
1598     setlocale(LC_NUMERIC, "");
1599 }
1600
1601 /*
1602  * For the binding events, we send the serialized binding struct.
1603  */
1604 void ipc_send_binding_event(const char *event_type, Binding *bind) {
1605     DLOG("Issue IPC binding %s event (sym = %s, code = %d)\n", event_type, bind->symbol, bind->keycode);
1606
1607     setlocale(LC_NUMERIC, "C");
1608
1609     yajl_gen gen = ygenalloc();
1610
1611     y(map_open);
1612
1613     ystr("change");
1614     ystr(event_type);
1615
1616     ystr("binding");
1617     dump_binding(gen, bind);
1618
1619     y(map_close);
1620
1621     const unsigned char *payload;
1622     ylength length;
1623     y(get_buf, &payload, &length);
1624
1625     ipc_send_event("binding", I3_IPC_EVENT_BINDING, (const char *)payload);
1626
1627     y(free);
1628     setlocale(LC_NUMERIC, "");
1629 }