]> 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-2012 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * ipc.c: UNIX domain socket IPC (initialization, client handling, protocol).
10  *
11  */
12 #include "all.h"
13 #include "yajl_utils.h"
14
15 #include <sys/socket.h>
16 #include <sys/un.h>
17 #include <fcntl.h>
18 #include <libgen.h>
19 #include <ev.h>
20 #include <yajl/yajl_gen.h>
21 #include <yajl/yajl_parse.h>
22
23 char *current_socketpath = NULL;
24
25 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
26
27 /*
28  * Puts the given socket file descriptor into non-blocking mode or dies if
29  * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
30  * IPC model because we should by no means block the window manager.
31  *
32  */
33 static void set_nonblock(int sockfd) {
34     int flags = fcntl(sockfd, F_GETFL, 0);
35     flags |= O_NONBLOCK;
36     if (fcntl(sockfd, F_SETFL, flags) < 0)
37         err(-1, "Could not set O_NONBLOCK");
38 }
39
40 /*
41  * Emulates mkdir -p (creates any missing folders)
42  *
43  */
44 static bool mkdirp(const char *path) {
45     if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
46         return true;
47     if (errno != ENOENT) {
48         ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
49         return false;
50     }
51     char *copy = sstrdup(path);
52     /* strip trailing slashes, if any */
53     while (copy[strlen(copy)-1] == '/')
54         copy[strlen(copy)-1] = '\0';
55
56     char *sep = strrchr(copy, '/');
57     if (sep == NULL) {
58         FREE(copy);
59         return false;
60     }
61     *sep = '\0';
62     bool result = false;
63     if (mkdirp(copy))
64         result = mkdirp(path);
65     free(copy);
66
67     return result;
68 }
69
70 /*
71  * Sends the specified event to all IPC clients which are currently connected
72  * and subscribed to this kind of event.
73  *
74  */
75 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
76     ipc_client *current;
77     TAILQ_FOREACH(current, &all_clients, clients) {
78         /* see if this client is interested in this event */
79         bool interested = false;
80         for (int i = 0; i < current->num_events; i++) {
81             if (strcasecmp(current->events[i], event) != 0)
82                 continue;
83             interested = true;
84             break;
85         }
86         if (!interested)
87             continue;
88
89         ipc_send_message(current->fd, strlen(payload), message_type, (const uint8_t*)payload);
90     }
91 }
92
93 /*
94  * Calls shutdown() on each socket and closes it. This function to be called
95  * when exiting or restarting only!
96  *
97  */
98 void ipc_shutdown(void) {
99     ipc_client *current;
100     while (!TAILQ_EMPTY(&all_clients)) {
101         current = TAILQ_FIRST(&all_clients);
102         shutdown(current->fd, SHUT_RDWR);
103         close(current->fd);
104         TAILQ_REMOVE(&all_clients, current, clients);
105         free(current);
106     }
107 }
108
109 /*
110  * Executes the command and returns whether it could be successfully parsed
111  * or not (at the moment, always returns true).
112  *
113  */
114 IPC_HANDLER(command) {
115     /* To get a properly terminated buffer, we copy
116      * message_size bytes out of the buffer */
117     char *command = scalloc(message_size + 1);
118     strncpy(command, (const char*)message, message_size);
119     LOG("IPC: received: *%s*\n", command);
120     struct CommandResult *command_output = parse_command((const char*)command);
121     free(command);
122
123     if (command_output->needs_tree_render)
124         tree_render();
125
126     const unsigned char *reply;
127     ylength length;
128     yajl_gen_get_buf(command_output->json_gen, &reply, &length);
129
130     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_COMMAND,
131                      (const uint8_t*)reply);
132
133     yajl_gen_free(command_output->json_gen);
134 }
135
136 static void dump_rect(yajl_gen gen, const char *name, Rect r) {
137     ystr(name);
138     y(map_open);
139     ystr("x");
140     y(integer, r.x);
141     ystr("y");
142     y(integer, r.y);
143     ystr("width");
144     y(integer, r.width);
145     ystr("height");
146     y(integer, r.height);
147     y(map_close);
148 }
149
150 void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart) {
151     y(map_open);
152     ystr("id");
153     y(integer, (long int)con);
154
155     ystr("type");
156     switch (con->type) {
157         case CT_ROOT:
158             ystr("root");
159             break;
160         case CT_OUTPUT:
161             ystr("output");
162             break;
163         case CT_CON:
164             ystr("con");
165             break;
166         case CT_FLOATING_CON:
167             ystr("floating_con");
168             break;
169         case CT_WORKSPACE:
170             ystr("workspace");
171             break;
172         case CT_DOCKAREA:
173             ystr("dockarea");
174             break;
175         default:
176             DLOG("About to dump unknown container type=%d. This is a bug.\n", con->type);
177             assert(false);
178             break;
179     }
180
181     /* provided for backwards compatibility only. */
182     ystr("orientation");
183     if (!con_is_split(con))
184         ystr("none");
185     else {
186         if (con_orientation(con) == HORIZ)
187             ystr("horizontal");
188         else ystr("vertical");
189     }
190
191     ystr("scratchpad_state");
192     switch (con->scratchpad_state) {
193         case SCRATCHPAD_NONE:
194             ystr("none");
195             break;
196         case SCRATCHPAD_FRESH:
197             ystr("fresh");
198             break;
199         case SCRATCHPAD_CHANGED:
200             ystr("changed");
201             break;
202     }
203
204     ystr("percent");
205     if (con->percent == 0.0)
206         y(null);
207     else y(double, con->percent);
208
209     ystr("urgent");
210     y(bool, con->urgent);
211
212     if (con->mark != NULL) {
213         ystr("mark");
214         ystr(con->mark);
215     }
216
217     ystr("focused");
218     y(bool, (con == focused));
219
220     ystr("layout");
221     switch (con->layout) {
222         case L_DEFAULT:
223             DLOG("About to dump layout=default, this is a bug in the code.\n");
224             assert(false);
225             break;
226         case L_SPLITV:
227             ystr("splitv");
228             break;
229         case L_SPLITH:
230             ystr("splith");
231             break;
232         case L_STACKED:
233             ystr("stacked");
234             break;
235         case L_TABBED:
236             ystr("tabbed");
237             break;
238         case L_DOCKAREA:
239             ystr("dockarea");
240             break;
241         case L_OUTPUT:
242             ystr("output");
243             break;
244     }
245
246     ystr("workspace_layout");
247     switch (con->workspace_layout) {
248         case L_DEFAULT:
249             ystr("default");
250             break;
251         case L_STACKED:
252             ystr("stacked");
253             break;
254         case L_TABBED:
255             ystr("tabbed");
256             break;
257         default:
258             DLOG("About to dump workspace_layout=%d (none of default/stacked/tabbed), this is a bug.\n", con->workspace_layout);
259             assert(false);
260             break;
261     }
262
263     ystr("last_split_layout");
264     switch (con->layout) {
265         case L_SPLITV:
266             ystr("splitv");
267             break;
268         default:
269             ystr("splith");
270             break;
271     }
272
273     ystr("border");
274     switch (con->border_style) {
275         case BS_NORMAL:
276             ystr("normal");
277             break;
278         case BS_NONE:
279             ystr("none");
280             break;
281         case BS_PIXEL:
282             ystr("pixel");
283             break;
284     }
285
286     ystr("current_border_width");
287     y(integer, con->current_border_width);
288
289     dump_rect(gen, "rect", con->rect);
290     dump_rect(gen, "window_rect", con->window_rect);
291     dump_rect(gen, "geometry", con->geometry);
292
293     ystr("name");
294     if (con->window && con->window->name)
295         ystr(i3string_as_utf8(con->window->name));
296     else
297         ystr(con->name);
298
299     if (con->type == CT_WORKSPACE) {
300         ystr("num");
301         y(integer, con->num);
302     }
303
304     ystr("window");
305     if (con->window)
306         y(integer, con->window->id);
307     else y(null);
308
309     if (con->window && !inplace_restart) {
310         /* Window properties are useless to preserve when restarting because
311          * they will be queried again anyway. However, for i3-save-tree(1),
312          * they are very useful and save i3-save-tree dealing with X11. */
313         ystr("window_properties");
314         y(map_open);
315
316 #define DUMP_PROPERTY(key, prop_name) do { \
317     if (con->window->prop_name != NULL) { \
318         ystr(key); \
319         ystr(con->window->prop_name); \
320     } \
321 } while (0)
322
323         DUMP_PROPERTY("class", class_class);
324         DUMP_PROPERTY("instance", class_instance);
325         DUMP_PROPERTY("window_role", role);
326
327         if (con->window->name != NULL) {
328             ystr("title");
329             ystr(i3string_as_utf8(con->window->name));
330         }
331
332         y(map_close);
333     }
334
335     ystr("nodes");
336     y(array_open);
337     Con *node;
338     if (con->type != CT_DOCKAREA || !inplace_restart) {
339         TAILQ_FOREACH(node, &(con->nodes_head), nodes) {
340             dump_node(gen, node, inplace_restart);
341         }
342     }
343     y(array_close);
344
345     ystr("floating_nodes");
346     y(array_open);
347     TAILQ_FOREACH(node, &(con->floating_head), floating_windows) {
348         dump_node(gen, node, inplace_restart);
349     }
350     y(array_close);
351
352     ystr("focus");
353     y(array_open);
354     TAILQ_FOREACH(node, &(con->focus_head), focused) {
355         y(integer, (long int)node);
356     }
357     y(array_close);
358
359     ystr("fullscreen_mode");
360     y(integer, con->fullscreen_mode);
361
362     ystr("floating");
363     switch (con->floating) {
364         case FLOATING_AUTO_OFF:
365             ystr("auto_off");
366             break;
367         case FLOATING_AUTO_ON:
368             ystr("auto_on");
369             break;
370         case FLOATING_USER_OFF:
371             ystr("user_off");
372             break;
373         case FLOATING_USER_ON:
374             ystr("user_on");
375             break;
376     }
377
378     ystr("swallows");
379     y(array_open);
380     Match *match;
381     TAILQ_FOREACH(match, &(con->swallow_head), matches) {
382         y(map_open);
383         if (match->dock != -1) {
384             ystr("dock");
385             y(integer, match->dock);
386             ystr("insert_where");
387             y(integer, match->insert_where);
388         }
389
390 #define DUMP_REGEX(re_name) do { \
391     if (match->re_name != NULL) { \
392         ystr(# re_name); \
393         ystr(match->re_name->pattern); \
394     } \
395 } while (0)
396
397         DUMP_REGEX(class);
398         DUMP_REGEX(instance);
399         DUMP_REGEX(window_role);
400         DUMP_REGEX(title);
401
402 #undef DUMP_REGEX
403         y(map_close);
404     }
405
406     if (inplace_restart) {
407         if (con->window != NULL) {
408             y(map_open);
409             ystr("id");
410             y(integer, con->window->id);
411             ystr("restart_mode");
412             y(bool, true);
413             y(map_close);
414         }
415     }
416     y(array_close);
417
418     if (inplace_restart && con->window != NULL) {
419         ystr("depth");
420         y(integer, con->depth);
421     }
422
423     y(map_close);
424 }
425
426 IPC_HANDLER(tree) {
427     setlocale(LC_NUMERIC, "C");
428     yajl_gen gen = ygenalloc();
429     dump_node(gen, croot, false);
430     setlocale(LC_NUMERIC, "");
431
432     const unsigned char *payload;
433     ylength length;
434     y(get_buf, &payload, &length);
435
436     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_TREE, payload);
437     y(free);
438 }
439
440
441 /*
442  * Formats the reply message for a GET_WORKSPACES request and sends it to the
443  * client
444  *
445  */
446 IPC_HANDLER(get_workspaces) {
447     yajl_gen gen = ygenalloc();
448     y(array_open);
449
450     Con *focused_ws = con_get_workspace(focused);
451
452     Con *output;
453     TAILQ_FOREACH(output, &(croot->nodes_head), nodes) {
454         if (con_is_internal(output))
455             continue;
456         Con *ws;
457         TAILQ_FOREACH(ws, &(output_get_content(output)->nodes_head), nodes) {
458             assert(ws->type == CT_WORKSPACE);
459             y(map_open);
460
461             ystr("num");
462             if (ws->num == -1)
463                 y(null);
464             else y(integer, ws->num);
465
466             ystr("name");
467             ystr(ws->name);
468
469             ystr("visible");
470             y(bool, workspace_is_visible(ws));
471
472             ystr("focused");
473             y(bool, ws == focused_ws);
474
475             ystr("rect");
476             y(map_open);
477             ystr("x");
478             y(integer, ws->rect.x);
479             ystr("y");
480             y(integer, ws->rect.y);
481             ystr("width");
482             y(integer, ws->rect.width);
483             ystr("height");
484             y(integer, ws->rect.height);
485             y(map_close);
486
487             ystr("output");
488             ystr(output->name);
489
490             ystr("urgent");
491             y(bool, ws->urgent);
492
493             y(map_close);
494         }
495     }
496
497     y(array_close);
498
499     const unsigned char *payload;
500     ylength length;
501     y(get_buf, &payload, &length);
502
503     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_WORKSPACES, payload);
504     y(free);
505 }
506
507 /*
508  * Formats the reply message for a GET_OUTPUTS request and sends it to the
509  * client
510  *
511  */
512 IPC_HANDLER(get_outputs) {
513     yajl_gen gen = ygenalloc();
514     y(array_open);
515
516     Output *output;
517     TAILQ_FOREACH(output, &outputs, outputs) {
518         y(map_open);
519
520         ystr("name");
521         ystr(output->name);
522
523         ystr("active");
524         y(bool, output->active);
525
526         ystr("primary");
527         y(bool, output->primary);
528
529         ystr("rect");
530         y(map_open);
531         ystr("x");
532         y(integer, output->rect.x);
533         ystr("y");
534         y(integer, output->rect.y);
535         ystr("width");
536         y(integer, output->rect.width);
537         ystr("height");
538         y(integer, output->rect.height);
539         y(map_close);
540
541         ystr("current_workspace");
542         Con *ws = NULL;
543         if (output->con && (ws = con_get_fullscreen_con(output->con, CF_OUTPUT)))
544             ystr(ws->name);
545         else y(null);
546
547         y(map_close);
548     }
549
550     y(array_close);
551
552     const unsigned char *payload;
553     ylength length;
554     y(get_buf, &payload, &length);
555
556     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_OUTPUTS, payload);
557     y(free);
558 }
559
560 /*
561  * Formats the reply message for a GET_MARKS request and sends it to the
562  * client
563  *
564  */
565 IPC_HANDLER(get_marks) {
566     yajl_gen gen = ygenalloc();
567     y(array_open);
568
569     Con *con;
570     TAILQ_FOREACH(con, &all_cons, all_cons)
571         if (con->mark != NULL)
572             ystr(con->mark);
573
574     y(array_close);
575
576     const unsigned char *payload;
577     ylength length;
578     y(get_buf, &payload, &length);
579
580     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_MARKS, payload);
581     y(free);
582 }
583
584 /*
585  * Returns the version of i3
586  *
587  */
588 IPC_HANDLER(get_version) {
589     yajl_gen gen = ygenalloc();
590     y(map_open);
591
592     ystr("major");
593     y(integer, MAJOR_VERSION);
594
595     ystr("minor");
596     y(integer, MINOR_VERSION);
597
598     ystr("patch");
599     y(integer, PATCH_VERSION);
600
601     ystr("human_readable");
602     ystr(I3_VERSION);
603
604     y(map_close);
605
606     const unsigned char *payload;
607     ylength length;
608     y(get_buf, &payload, &length);
609
610     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_VERSION, payload);
611     y(free);
612 }
613
614 /*
615  * Formats the reply message for a GET_BAR_CONFIG request and sends it to the
616  * client.
617  *
618  */
619 IPC_HANDLER(get_bar_config) {
620     yajl_gen gen = ygenalloc();
621
622     /* If no ID was passed, we return a JSON array with all IDs */
623     if (message_size == 0) {
624         y(array_open);
625         Barconfig *current;
626         TAILQ_FOREACH(current, &barconfigs, configs) {
627             ystr(current->id);
628         }
629         y(array_close);
630
631         const unsigned char *payload;
632         ylength length;
633         y(get_buf, &payload, &length);
634
635         ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
636         y(free);
637         return;
638     }
639
640     /* To get a properly terminated buffer, we copy
641      * message_size bytes out of the buffer */
642     char *bar_id = scalloc(message_size + 1);
643     strncpy(bar_id, (const char*)message, message_size);
644     LOG("IPC: looking for config for bar ID \"%s\"\n", bar_id);
645     Barconfig *current, *config = NULL;
646     TAILQ_FOREACH(current, &barconfigs, configs) {
647         if (strcmp(current->id, bar_id) != 0)
648             continue;
649
650         config = current;
651         break;
652     }
653
654     y(map_open);
655
656     if (!config) {
657         /* If we did not find a config for the given ID, the reply will contain
658          * a null 'id' field. */
659         ystr("id");
660         y(null);
661     } else {
662         ystr("id");
663         ystr(config->id);
664
665         if (config->num_outputs > 0) {
666             ystr("outputs");
667             y(array_open);
668             for (int c = 0; c < config->num_outputs; c++)
669                 ystr(config->outputs[c]);
670             y(array_close);
671         }
672
673 #define YSTR_IF_SET(name) \
674         do { \
675             if (config->name) { \
676                 ystr( # name); \
677                 ystr(config->name); \
678             } \
679         } while (0)
680
681         YSTR_IF_SET(tray_output);
682         YSTR_IF_SET(socket_path);
683
684         ystr("mode");
685         switch (config->mode) {
686             case M_HIDE:
687                 ystr("hide");
688                 break;
689             case M_INVISIBLE:
690                 ystr("invisible");
691                 break;
692             case M_DOCK:
693             default:
694                 ystr("dock");
695                 break;
696         }
697
698         ystr("hidden_state");
699         switch (config->hidden_state) {
700             case S_SHOW:
701                 ystr("show");
702                 break;
703             case S_HIDE:
704             default:
705                 ystr("hide");
706                 break;
707         }
708
709         ystr("modifier");
710         switch (config->modifier) {
711             case M_CONTROL:
712                 ystr("ctrl");
713                 break;
714             case M_SHIFT:
715                 ystr("shift");
716                 break;
717             case M_MOD1:
718                 ystr("Mod1");
719                 break;
720             case M_MOD2:
721                 ystr("Mod2");
722                 break;
723             case M_MOD3:
724                 ystr("Mod3");
725                 break;
726             /*
727             case M_MOD4:
728                 ystr("Mod4");
729                 break;
730             */
731             case M_MOD5:
732                 ystr("Mod5");
733                 break;
734             default:
735                 ystr("Mod4");
736                 break;
737         }
738
739         ystr("position");
740         if (config->position == P_BOTTOM)
741             ystr("bottom");
742         else ystr("top");
743
744         YSTR_IF_SET(status_command);
745         YSTR_IF_SET(font);
746
747         ystr("workspace_buttons");
748         y(bool, !config->hide_workspace_buttons);
749
750         ystr("binding_mode_indicator");
751         y(bool, !config->hide_binding_mode_indicator);
752
753         ystr("verbose");
754         y(bool, config->verbose);
755
756 #undef YSTR_IF_SET
757 #define YSTR_IF_SET(name) \
758         do { \
759             if (config->colors.name) { \
760                 ystr( # name); \
761                 ystr(config->colors.name); \
762             } \
763         } while (0)
764
765         ystr("colors");
766         y(map_open);
767         YSTR_IF_SET(background);
768         YSTR_IF_SET(statusline);
769         YSTR_IF_SET(separator);
770         YSTR_IF_SET(focused_workspace_border);
771         YSTR_IF_SET(focused_workspace_bg);
772         YSTR_IF_SET(focused_workspace_text);
773         YSTR_IF_SET(active_workspace_border);
774         YSTR_IF_SET(active_workspace_bg);
775         YSTR_IF_SET(active_workspace_text);
776         YSTR_IF_SET(inactive_workspace_border);
777         YSTR_IF_SET(inactive_workspace_bg);
778         YSTR_IF_SET(inactive_workspace_text);
779         YSTR_IF_SET(urgent_workspace_border);
780         YSTR_IF_SET(urgent_workspace_bg);
781         YSTR_IF_SET(urgent_workspace_text);
782         y(map_close);
783
784 #undef YSTR_IF_SET
785     }
786
787     y(map_close);
788
789     const unsigned char *payload;
790     ylength length;
791     y(get_buf, &payload, &length);
792
793     ipc_send_message(fd, length, I3_IPC_REPLY_TYPE_BAR_CONFIG, payload);
794     y(free);
795 }
796
797 /*
798  * Callback for the YAJL parser (will be called when a string is parsed).
799  *
800  */
801 static int add_subscription(void *extra, const unsigned char *s,
802                             ylength len) {
803     ipc_client *client = extra;
804
805     DLOG("should add subscription to extra %p, sub %.*s\n", client, (int)len, s);
806     int event = client->num_events;
807
808     client->num_events++;
809     client->events = realloc(client->events, client->num_events * sizeof(char*));
810     /* We copy the string because it is not null-terminated and strndup()
811      * is missing on some BSD systems */
812     client->events[event] = scalloc(len+1);
813     memcpy(client->events[event], s, len);
814
815     DLOG("client is now subscribed to:\n");
816     for (int i = 0; i < client->num_events; i++)
817         DLOG("event %s\n", client->events[i]);
818     DLOG("(done)\n");
819
820     return 1;
821 }
822
823 /*
824  * Subscribes this connection to the event types which were given as a JSON
825  * serialized array in the payload field of the message.
826  *
827  */
828 IPC_HANDLER(subscribe) {
829     yajl_handle p;
830     yajl_status stat;
831     ipc_client *current, *client = NULL;
832
833     /* Search the ipc_client structure for this connection */
834     TAILQ_FOREACH(current, &all_clients, clients) {
835         if (current->fd != fd)
836             continue;
837
838         client = current;
839         break;
840     }
841
842     if (client == NULL) {
843         ELOG("Could not find ipc_client data structure for fd %d\n", fd);
844         return;
845     }
846
847     /* Setup the JSON parser */
848     static yajl_callbacks callbacks = {
849         .yajl_string = add_subscription,
850     };
851
852     p = yalloc(&callbacks, (void*)client);
853     stat = yajl_parse(p, (const unsigned char*)message, message_size);
854     if (stat != yajl_status_ok) {
855         unsigned char *err;
856         err = yajl_get_error(p, true, (const unsigned char*)message,
857                              message_size);
858         ELOG("YAJL parse error: %s\n", err);
859         yajl_free_error(p, err);
860
861         const char *reply = "{\"success\":false}";
862         ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
863         yajl_free(p);
864         return;
865     }
866     yajl_free(p);
867     const char *reply = "{\"success\":true}";
868     ipc_send_message(fd, strlen(reply), I3_IPC_REPLY_TYPE_SUBSCRIBE, (const uint8_t*)reply);
869 }
870
871 /* The index of each callback function corresponds to the numeric
872  * value of the message type (see include/i3/ipc.h) */
873 handler_t handlers[8] = {
874     handle_command,
875     handle_get_workspaces,
876     handle_subscribe,
877     handle_get_outputs,
878     handle_tree,
879     handle_get_marks,
880     handle_get_bar_config,
881     handle_get_version,
882 };
883
884 /*
885  * Handler for activity on a client connection, receives a message from a
886  * client.
887  *
888  * For now, the maximum message size is 2048. I’m not sure for what the
889  * IPC interface will be used in the future, thus I’m not implementing a
890  * mechanism for arbitrarily long messages, as it seems like overkill
891  * at the moment.
892  *
893  */
894 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
895     uint32_t message_type;
896     uint32_t message_length;
897     uint8_t *message;
898
899     int ret = ipc_recv_message(w->fd, &message_type, &message_length, &message);
900     /* EOF or other error */
901     if (ret < 0) {
902         /* Was this a spurious read? See ev(3) */
903         if (ret == -1 && errno == EAGAIN)
904             return;
905
906         /* If not, there was some kind of error. We don’t bother
907          * and close the connection */
908         close(w->fd);
909
910         /* Delete the client from the list of clients */
911         ipc_client *current;
912         TAILQ_FOREACH(current, &all_clients, clients) {
913             if (current->fd != w->fd)
914                 continue;
915
916             for (int i = 0; i < current->num_events; i++)
917                 free(current->events[i]);
918             /* We can call TAILQ_REMOVE because we break out of the
919              * TAILQ_FOREACH afterwards */
920             TAILQ_REMOVE(&all_clients, current, clients);
921             free(current);
922             break;
923         }
924
925         ev_io_stop(EV_A_ w);
926         free(w);
927
928         DLOG("IPC: client disconnected\n");
929         return;
930     }
931
932     if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
933         DLOG("Unhandled message type: %d\n", message_type);
934     else {
935         handler_t h = handlers[message_type];
936         h(w->fd, message, 0, message_length, message_type);
937     }
938 }
939
940 /*
941  * Handler for activity on the listening socket, meaning that a new client
942  * has just connected and we should accept() him. Sets up the event handler
943  * for activity on the new connection and inserts the file descriptor into
944  * the list of clients.
945  *
946  */
947 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
948     struct sockaddr_un peer;
949     socklen_t len = sizeof(struct sockaddr_un);
950     int client;
951     if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
952         if (errno == EINTR)
953             return;
954         else perror("accept()");
955         return;
956     }
957
958     /* Close this file descriptor on exec() */
959     (void)fcntl(client, F_SETFD, FD_CLOEXEC);
960
961     set_nonblock(client);
962
963     struct ev_io *package = scalloc(sizeof(struct ev_io));
964     ev_io_init(package, ipc_receive_message, client, EV_READ);
965     ev_io_start(EV_A_ package);
966
967     DLOG("IPC: new client connected on fd %d\n", w->fd);
968
969     ipc_client *new = scalloc(sizeof(ipc_client));
970     new->fd = client;
971
972     TAILQ_INSERT_TAIL(&all_clients, new, clients);
973 }
974
975 /*
976  * Creates the UNIX domain socket at the given path, sets it to non-blocking
977  * mode, bind()s and listen()s on it.
978  *
979  */
980 int ipc_create_socket(const char *filename) {
981     int sockfd;
982
983     FREE(current_socketpath);
984
985     char *resolved = resolve_tilde(filename);
986     DLOG("Creating IPC-socket at %s\n", resolved);
987     char *copy = sstrdup(resolved);
988     const char *dir = dirname(copy);
989     if (!path_exists(dir))
990         mkdirp(dir);
991     free(copy);
992
993     /* Unlink the unix domain socket before */
994     unlink(resolved);
995
996     if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
997         perror("socket()");
998         free(resolved);
999         return -1;
1000     }
1001
1002     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
1003
1004     struct sockaddr_un addr;
1005     memset(&addr, 0, sizeof(struct sockaddr_un));
1006     addr.sun_family = AF_LOCAL;
1007     strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
1008     if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
1009         perror("bind()");
1010         free(resolved);
1011         return -1;
1012     }
1013
1014     set_nonblock(sockfd);
1015
1016     if (listen(sockfd, 5) < 0) {
1017         perror("listen()");
1018         free(resolved);
1019         return -1;
1020     }
1021
1022     current_socketpath = resolved;
1023     return sockfd;
1024 }