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