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