1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
14 #include "sd-daemon.h"
16 #include "alloc-util.h"
17 #include "bus-internal.h"
18 #include "bus-message.h"
19 #include "bus-socket.h"
21 #include "format-util.h"
23 #include "hexdecoct.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "selinux-util.h"
30 #include "signal-util.h"
31 #include "stdio-util.h"
32 #include "string-util.h"
33 #include "user-util.h"
37 #define SNDBUF_SIZE (8*1024*1024)
39 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
42 struct iovec *i = iov + *idx;
44 if (i->iov_len > size) {
45 i->iov_base = (uint8_t*) i->iov_base + size;
59 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
64 m->iovec[m->n_iovec].iov_base = (void*) p;
65 m->iovec[m->n_iovec].iov_len = sz;
71 static int bus_message_setup_iovec(sd_bus_message *m) {
72 struct bus_body_part *part;
84 n = 1 + m->n_body_parts;
85 if (n < ELEMENTSOF(m->iovec_fixed))
86 m->iovec = m->iovec_fixed;
88 m->iovec = new(struct iovec, n);
95 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
99 MESSAGE_FOREACH_PART(part, i, m) {
100 r = bus_body_part_map(part);
104 r = append_iovec(m, part->data, part->size);
109 assert(n == m->n_iovec);
118 bool bus_socket_auth_needs_write(sd_bus *b) {
122 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
125 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
126 struct iovec *j = b->auth_iovec + i;
135 static int bus_socket_write_auth(sd_bus *b) {
139 assert(b->state == BUS_AUTHENTICATING);
141 if (!bus_socket_auth_needs_write(b))
144 if (b->prefer_writev)
145 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
150 mh.msg_iov = b->auth_iovec + b->auth_index;
151 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
153 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
154 if (k < 0 && errno == ENOTSOCK) {
155 b->prefer_writev = true;
156 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
161 return errno == EAGAIN ? 0 : -errno;
163 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
167 static int bus_socket_auth_verify_client(sd_bus *b) {
175 /* We expect two response lines: "OK" and possibly
178 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
183 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
193 /* Nice! We got all the lines we need. First check the OK
196 if (e - (char*) b->rbuffer != 3 + 32)
199 if (memcmp(b->rbuffer, "OK ", 3))
202 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
204 for (i = 0; i < 32; i += 2) {
207 x = unhexchar(((char*) b->rbuffer)[3 + i]);
208 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
213 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
216 if (!sd_id128_is_null(b->server_id) &&
217 !sd_id128_equal(b->server_id, peer))
222 /* And possibly check the second line, too */
226 (f - e == STRLEN("\r\nAGREE_UNIX_FD")) &&
227 memcmp(e + 2, "AGREE_UNIX_FD",
228 STRLEN("AGREE_UNIX_FD")) == 0;
230 b->rbuffer_size -= (start - (char*) b->rbuffer);
231 memmove(b->rbuffer, start, b->rbuffer_size);
233 r = bus_start_running(b);
240 static bool line_equals(const char *s, size_t m, const char *line) {
247 return memcmp(s, line, l) == 0;
250 static bool line_begins(const char *s, size_t m, const char *word) {
253 p = memory_startswith(s, m, word);
257 return IN_SET(*p, 0, ' ');
260 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
261 _cleanup_free_ char *token = NULL;
265 if (!b->anonymous_auth)
277 r = unhexmem(p, l, (void **) &token, &len);
281 if (memchr(token, 0, len))
284 return !!utf8_is_valid(token);
287 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
288 _cleanup_free_ char *token = NULL;
293 /* We don't do any real authentication here. Instead, we if
294 * the owner of this bus wanted authentication he should have
295 * checked SO_PEERCRED before even creating the bus object. */
297 if (!b->anonymous_auth && !b->ucred_valid)
309 r = unhexmem(p, l, (void**) &token, &len);
313 if (memchr(token, 0, len))
316 r = parse_uid(token, &u);
320 /* We ignore the passed value if anonymous authentication is
322 if (!b->anonymous_auth && u != b->ucred.uid)
328 static int bus_socket_auth_write(sd_bus *b, const char *t) {
335 /* We only make use of the first iovec */
336 assert(IN_SET(b->auth_index, 0, 1));
339 p = malloc(b->auth_iovec[0].iov_len + l);
343 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
344 memcpy(p + b->auth_iovec[0].iov_len, t, l);
346 b->auth_iovec[0].iov_base = p;
347 b->auth_iovec[0].iov_len += l;
349 free(b->auth_buffer);
355 static int bus_socket_auth_write_ok(sd_bus *b) {
356 char t[3 + 32 + 2 + 1];
360 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
362 return bus_socket_auth_write(b, t);
365 static int bus_socket_auth_verify_server(sd_bus *b) {
369 bool processed = false;
374 if (b->rbuffer_size < 1)
377 /* First char must be a NUL byte */
378 if (*(char*) b->rbuffer != 0)
381 if (b->rbuffer_size < 3)
384 /* Begin with the first line */
385 if (b->auth_rbegin <= 0)
389 /* Check if line is complete */
390 line = (char*) b->rbuffer + b->auth_rbegin;
391 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
397 if (line_begins(line, l, "AUTH ANONYMOUS")) {
399 r = verify_anonymous_token(b, line + 14, l - 14);
403 r = bus_socket_auth_write(b, "REJECTED\r\n");
405 b->auth = BUS_AUTH_ANONYMOUS;
406 r = bus_socket_auth_write_ok(b);
409 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
411 r = verify_external_token(b, line + 13, l - 13);
415 r = bus_socket_auth_write(b, "REJECTED\r\n");
417 b->auth = BUS_AUTH_EXTERNAL;
418 r = bus_socket_auth_write_ok(b);
421 } else if (line_begins(line, l, "AUTH"))
422 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
423 else if (line_equals(line, l, "CANCEL") ||
424 line_begins(line, l, "ERROR")) {
426 b->auth = _BUS_AUTH_INVALID;
427 r = bus_socket_auth_write(b, "REJECTED\r\n");
429 } else if (line_equals(line, l, "BEGIN")) {
431 if (b->auth == _BUS_AUTH_INVALID)
432 r = bus_socket_auth_write(b, "ERROR\r\n");
434 /* We can't leave from the auth phase
435 * before we haven't written
436 * everything queued, so let's check
439 if (bus_socket_auth_needs_write(b))
442 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
443 memmove(b->rbuffer, e + 2, b->rbuffer_size);
444 return bus_start_running(b);
447 } else if (line_begins(line, l, "DATA")) {
449 if (b->auth == _BUS_AUTH_INVALID)
450 r = bus_socket_auth_write(b, "ERROR\r\n");
452 if (b->auth == BUS_AUTH_ANONYMOUS)
453 r = verify_anonymous_token(b, line + 4, l - 4);
455 r = verify_external_token(b, line + 4, l - 4);
460 b->auth = _BUS_AUTH_INVALID;
461 r = bus_socket_auth_write(b, "REJECTED\r\n");
463 r = bus_socket_auth_write_ok(b);
465 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
466 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
467 r = bus_socket_auth_write(b, "ERROR\r\n");
470 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
473 r = bus_socket_auth_write(b, "ERROR\r\n");
478 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
484 static int bus_socket_auth_verify(sd_bus *b) {
488 return bus_socket_auth_verify_server(b);
490 return bus_socket_auth_verify_client(b);
493 static int bus_socket_read_auth(sd_bus *b) {
495 struct iovec iov = {};
501 struct cmsghdr cmsghdr;
502 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
504 bool handle_cmsg = false;
507 assert(b->state == BUS_AUTHENTICATING);
509 r = bus_socket_auth_verify(b);
513 n = MAX(256u, b->rbuffer_size * 2);
515 if (n > BUS_AUTH_SIZE_MAX)
516 n = BUS_AUTH_SIZE_MAX;
518 if (b->rbuffer_size >= n)
521 p = realloc(b->rbuffer, n);
527 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
528 iov.iov_len = n - b->rbuffer_size;
531 k = readv(b->input_fd, &iov, 1);
536 mh.msg_control = &control;
537 mh.msg_controllen = sizeof(control);
539 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
540 if (k < 0 && errno == ENOTSOCK) {
541 b->prefer_readv = true;
542 k = readv(b->input_fd, &iov, 1);
547 return errno == EAGAIN ? 0 : -errno;
551 b->rbuffer_size += k;
554 struct cmsghdr *cmsg;
556 CMSG_FOREACH(cmsg, &mh)
557 if (cmsg->cmsg_level == SOL_SOCKET &&
558 cmsg->cmsg_type == SCM_RIGHTS) {
561 /* Whut? We received fds during the auth
562 * protocol? Somebody is playing games with
563 * us. Close them all, and fail */
564 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
565 close_many((int*) CMSG_DATA(cmsg), j);
568 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
569 cmsg->cmsg_level, cmsg->cmsg_type);
572 r = bus_socket_auth_verify(b);
579 void bus_socket_setup(sd_bus *b) {
582 /* Increase the buffers to 8 MB */
583 (void) fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
584 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
586 b->message_version = 1;
587 b->message_endian = 0;
590 static void bus_get_peercred(sd_bus *b) {
594 assert(!b->ucred_valid);
596 assert(b->n_groups == (size_t) -1);
598 /* Get the peer for socketpair() sockets */
599 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
601 /* Get the SELinux context of the peer */
602 r = getpeersec(b->input_fd, &b->label);
603 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
604 log_debug_errno(r, "Failed to determine peer security context: %m");
606 /* Get the list of auxiliary groups of the peer */
607 r = getpeergroups(b->input_fd, &b->groups);
609 b->n_groups = (size_t) r;
610 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
611 log_debug_errno(r, "Failed to determine peer's group list: %m");
614 static int bus_socket_start_auth_client(sd_bus *b) {
616 const char *auth_suffix, *auth_prefix;
620 if (b->anonymous_auth) {
621 auth_prefix = "\0AUTH ANONYMOUS ";
623 /* For ANONYMOUS auth we send some arbitrary "trace" string */
625 b->auth_buffer = hexmem("anonymous", l);
627 char text[DECIMAL_STR_MAX(uid_t) + 1];
629 auth_prefix = "\0AUTH EXTERNAL ";
631 xsprintf(text, UID_FMT, geteuid());
634 b->auth_buffer = hexmem(text, l);
641 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
643 auth_suffix = "\r\nBEGIN\r\n";
645 b->auth_iovec[0].iov_base = (void*) auth_prefix;
646 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
647 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
648 b->auth_iovec[1].iov_len = l * 2;
649 b->auth_iovec[2].iov_base = (void*) auth_suffix;
650 b->auth_iovec[2].iov_len = strlen(auth_suffix);
652 return bus_socket_write_auth(b);
655 int bus_socket_start_auth(sd_bus *b) {
660 bus_set_state(b, BUS_AUTHENTICATING);
661 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
663 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
664 b->accept_fd = false;
666 if (b->output_fd != b->input_fd)
667 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
668 b->accept_fd = false;
671 return bus_socket_read_auth(b);
673 return bus_socket_start_auth_client(b);
676 static int bus_socket_inotify_setup(sd_bus *b) {
677 _cleanup_free_ int *new_watches = NULL;
678 _cleanup_free_ char *absolute = NULL;
679 size_t n_allocated = 0, n = 0, done = 0, i;
680 unsigned max_follow = 32;
685 assert(b->watch_bind);
686 assert(b->sockaddr.sa.sa_family == AF_UNIX);
687 assert(b->sockaddr.un.sun_path[0] != 0);
689 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
690 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
691 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
692 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
693 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
696 if (b->inotify_fd < 0) {
697 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
698 if (b->inotify_fd < 0)
701 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
704 /* Make sure the path is NUL terminated */
705 p = strndupa(b->sockaddr.un.sun_path, sizeof(b->sockaddr.un.sun_path));
707 /* Make sure the path is absolute */
708 r = path_make_absolute_cwd(p, &absolute);
712 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
713 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
714 * they are removed or renamed. */
716 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
721 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
723 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
725 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
728 new_watches[n++] = wd;
731 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
732 size_t n_slashes, n_component;
735 n_slashes = strspn(absolute + done, "/");
736 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
738 if (n_component == 0) /* The end */
741 component = strndup(absolute + done, n_component);
747 /* A trailing slash? That's a directory, and not a socket then */
748 if (path_equal(component, "/")) {
753 /* A single dot? Let's eat this up */
754 if (path_equal(component, "/.")) {
759 prefix = strndup(absolute, done + n_component);
765 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
770 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
771 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
774 if (IN_SET(errno, ENOENT, ELOOP))
775 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
777 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", empty_to_root(prefix));
780 new_watches[n++] = wd;
782 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
783 r = readlink_malloc(prefix, &destination);
784 if (r == -EINVAL) { /* not a symlink */
791 if (isempty(destination)) { /* Empty symlink target? Yuck! */
796 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
801 if (path_is_absolute(destination)) {
802 /* For absolute symlinks we build the new path and start anew */
803 c = strjoin(destination, absolute + done + n_component);
806 _cleanup_free_ char *t = NULL;
808 /* For relative symlinks we replace the last component, and try again */
809 t = strndup(absolute, done);
813 c = strjoin(t, "/", destination, absolute + done + n_component);
826 /* And now, let's remove all watches from the previous iteration we don't need anymore */
827 for (i = 0; i < b->n_inotify_watches; i++) {
831 for (j = 0; j < n; j++)
832 if (new_watches[j] == b->inotify_watches[i]) {
840 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
843 free_and_replace(b->inotify_watches, new_watches);
844 b->n_inotify_watches = n;
849 bus_close_inotify_fd(b);
853 int bus_socket_connect(sd_bus *b) {
854 bool inotify_done = false;
860 assert(b->input_fd < 0);
861 assert(b->output_fd < 0);
862 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
864 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
868 b->input_fd = fd_move_above_stdio(b->input_fd);
870 b->output_fd = b->input_fd;
873 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
874 if (errno == EINPROGRESS) {
876 /* If we have any inotify watches open, close them now, we don't need them anymore, as
877 * we have successfully initiated a connection */
878 bus_close_inotify_fd(b);
880 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
881 * we start parsing the address string. The only reason we set the state explicitly
882 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
883 bus_set_state(b, BUS_OPENING);
887 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
889 b->sockaddr.sa.sa_family == AF_UNIX &&
890 b->sockaddr.un.sun_path[0] != 0) {
892 /* This connection attempt failed, let's release the socket for now, and start with a
893 * fresh one when reconnecting. */
897 /* inotify set up already, don't do it again, just return now, and remember
898 * that we are waiting for inotify events now. */
899 bus_set_state(b, BUS_WATCH_BIND);
903 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
904 r = bus_socket_inotify_setup(b);
908 /* Let's now try to connect a second time, because in theory there's otherwise a race
909 * here: the socket might have been created in the time between our first connect() and
910 * the time we set up the inotify logic. But let's remember that we set up inotify now,
911 * so that we don't do the connect() more than twice. */
920 /* Yay, established, we don't need no inotify anymore! */
921 bus_close_inotify_fd(b);
923 return bus_socket_start_auth(b);
926 int bus_socket_exec(sd_bus *b) {
930 assert(b->input_fd < 0);
931 assert(b->output_fd < 0);
932 assert(b->exec_path);
933 assert(b->busexec_pid == 0);
935 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
939 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &b->busexec_pid);
947 if (rearrange_stdio(s[1], s[1], STDERR_FILENO) < 0)
951 execvp(b->exec_path, b->exec_argv);
953 const char *argv[] = { b->exec_path, NULL };
954 execvp(b->exec_path, (char**) argv);
961 b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
965 return bus_socket_start_auth(b);
968 int bus_socket_take_fd(sd_bus *b) {
973 return bus_socket_start_auth(b);
976 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
986 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
988 if (*idx >= BUS_MESSAGE_SIZE(m))
991 r = bus_message_setup_iovec(m);
995 n = m->n_iovec * sizeof(struct iovec);
997 memcpy_safe(iov, m->iovec, n);
1000 iovec_advance(iov, &j, *idx);
1002 if (bus->prefer_writev)
1003 k = writev(bus->output_fd, iov, m->n_iovec);
1005 struct msghdr mh = {
1007 .msg_iovlen = m->n_iovec,
1010 if (m->n_fds > 0 && *idx == 0) {
1011 struct cmsghdr *control;
1013 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
1014 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
1015 control->cmsg_level = SOL_SOCKET;
1016 control->cmsg_type = SCM_RIGHTS;
1017 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1020 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1021 if (k < 0 && errno == ENOTSOCK) {
1022 bus->prefer_writev = true;
1023 k = writev(bus->output_fd, iov, m->n_iovec);
1028 return errno == EAGAIN ? 0 : -errno;
1034 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1041 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1043 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1044 *need = sizeof(struct bus_header) + 8;
1046 /* Minimum message size:
1050 * Method Call: +2 string headers
1051 * Signal: +3 string headers
1052 * Method Error: +1 string headers
1054 * Method Reply: +1 uint32 headers
1056 * A string header is at least 9 bytes
1057 * A uint32 header is at least 8 bytes
1059 * Hence the minimum message size of a valid message
1060 * is header + 8 bytes */
1065 a = ((const uint32_t*) bus->rbuffer)[1];
1066 b = ((const uint32_t*) bus->rbuffer)[3];
1068 e = ((const uint8_t*) bus->rbuffer)[0];
1069 if (e == BUS_LITTLE_ENDIAN) {
1072 } else if (e == BUS_BIG_ENDIAN) {
1078 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
1079 if (sum >= BUS_MESSAGE_SIZE_MAX)
1082 *need = (size_t) sum;
1086 static int bus_socket_make_message(sd_bus *bus, size_t size) {
1092 assert(bus->rbuffer_size >= size);
1093 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1095 r = bus_rqueue_make_room(bus);
1099 if (bus->rbuffer_size > size) {
1100 b = memdup((const uint8_t*) bus->rbuffer + size,
1101 bus->rbuffer_size - size);
1107 r = bus_message_from_malloc(bus,
1109 bus->fds, bus->n_fds,
1118 bus->rbuffer_size -= size;
1123 bus->rqueue[bus->rqueue_size++] = t;
1128 int bus_socket_read_message(sd_bus *bus) {
1130 struct iovec iov = {};
1136 struct cmsghdr cmsghdr;
1137 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
1139 bool handle_cmsg = false;
1142 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1144 r = bus_socket_read_message_need(bus, &need);
1148 if (bus->rbuffer_size >= need)
1149 return bus_socket_make_message(bus, need);
1151 b = realloc(bus->rbuffer, need);
1157 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
1158 iov.iov_len = need - bus->rbuffer_size;
1160 if (bus->prefer_readv)
1161 k = readv(bus->input_fd, &iov, 1);
1166 mh.msg_control = &control;
1167 mh.msg_controllen = sizeof(control);
1169 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
1170 if (k < 0 && errno == ENOTSOCK) {
1171 bus->prefer_readv = true;
1172 k = readv(bus->input_fd, &iov, 1);
1177 return errno == EAGAIN ? 0 : -errno;
1181 bus->rbuffer_size += k;
1184 struct cmsghdr *cmsg;
1186 CMSG_FOREACH(cmsg, &mh)
1187 if (cmsg->cmsg_level == SOL_SOCKET &&
1188 cmsg->cmsg_type == SCM_RIGHTS) {
1191 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1193 if (!bus->can_fds) {
1194 /* Whut? We received fds but this
1195 * isn't actually enabled? Close them,
1198 close_many((int*) CMSG_DATA(cmsg), n);
1202 f = reallocarray(bus->fds, bus->n_fds + n, sizeof(int));
1204 close_many((int*) CMSG_DATA(cmsg), n);
1208 for (i = 0; i < n; i++)
1209 f[bus->n_fds++] = fd_move_above_stdio(((int*) CMSG_DATA(cmsg))[i]);
1212 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1213 cmsg->cmsg_level, cmsg->cmsg_type);
1216 r = bus_socket_read_message_need(bus, &need);
1220 if (bus->rbuffer_size >= need)
1221 return bus_socket_make_message(bus, need);
1226 int bus_socket_process_opening(sd_bus *b) {
1228 socklen_t slen = sizeof(error);
1235 assert(b->state == BUS_OPENING);
1241 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1244 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1246 b->last_connect_error = errno;
1247 else if (error != 0)
1248 b->last_connect_error = error;
1249 else if (p.revents & (POLLERR|POLLHUP))
1250 b->last_connect_error = ECONNREFUSED;
1252 return bus_socket_start_auth(b);
1254 return bus_next_address(b);
1257 int bus_socket_process_authenticating(sd_bus *b) {
1261 assert(b->state == BUS_AUTHENTICATING);
1263 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1266 r = bus_socket_write_auth(b);
1270 return bus_socket_read_auth(b);
1273 int bus_socket_process_watch_bind(sd_bus *b) {
1277 assert(b->state == BUS_WATCH_BIND);
1278 assert(b->inotify_fd >= 0);
1280 r = flush_fd(b->inotify_fd);
1284 log_debug("Got inotify event on bus %s.", strna(b->description));
1286 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1289 r = bus_socket_connect(b);
1293 q = bus_attach_io_events(b);
1297 q = bus_attach_inotify_event(b);