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