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) {
257 if (memcmp(s, word, l) != 0)
260 return m == l || (m > l && s[l] == ' ');
263 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
264 _cleanup_free_ char *token = NULL;
268 if (!b->anonymous_auth)
280 r = unhexmem(p, l, (void **) &token, &len);
284 if (memchr(token, 0, len))
287 return !!utf8_is_valid(token);
290 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
291 _cleanup_free_ char *token = NULL;
296 /* We don't do any real authentication here. Instead, we if
297 * the owner of this bus wanted authentication he should have
298 * checked SO_PEERCRED before even creating the bus object. */
300 if (!b->anonymous_auth && !b->ucred_valid)
312 r = unhexmem(p, l, (void**) &token, &len);
316 if (memchr(token, 0, len))
319 r = parse_uid(token, &u);
323 /* We ignore the passed value if anonymous authentication is
325 if (!b->anonymous_auth && u != b->ucred.uid)
331 static int bus_socket_auth_write(sd_bus *b, const char *t) {
338 /* We only make use of the first iovec */
339 assert(IN_SET(b->auth_index, 0, 1));
342 p = malloc(b->auth_iovec[0].iov_len + l);
346 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
347 memcpy(p + b->auth_iovec[0].iov_len, t, l);
349 b->auth_iovec[0].iov_base = p;
350 b->auth_iovec[0].iov_len += l;
352 free(b->auth_buffer);
358 static int bus_socket_auth_write_ok(sd_bus *b) {
359 char t[3 + 32 + 2 + 1];
363 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
365 return bus_socket_auth_write(b, t);
368 static int bus_socket_auth_verify_server(sd_bus *b) {
372 bool processed = false;
377 if (b->rbuffer_size < 1)
380 /* First char must be a NUL byte */
381 if (*(char*) b->rbuffer != 0)
384 if (b->rbuffer_size < 3)
387 /* Begin with the first line */
388 if (b->auth_rbegin <= 0)
392 /* Check if line is complete */
393 line = (char*) b->rbuffer + b->auth_rbegin;
394 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
400 if (line_begins(line, l, "AUTH ANONYMOUS")) {
402 r = verify_anonymous_token(b, line + 14, l - 14);
406 r = bus_socket_auth_write(b, "REJECTED\r\n");
408 b->auth = BUS_AUTH_ANONYMOUS;
409 r = bus_socket_auth_write_ok(b);
412 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
414 r = verify_external_token(b, line + 13, l - 13);
418 r = bus_socket_auth_write(b, "REJECTED\r\n");
420 b->auth = BUS_AUTH_EXTERNAL;
421 r = bus_socket_auth_write_ok(b);
424 } else if (line_begins(line, l, "AUTH"))
425 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
426 else if (line_equals(line, l, "CANCEL") ||
427 line_begins(line, l, "ERROR")) {
429 b->auth = _BUS_AUTH_INVALID;
430 r = bus_socket_auth_write(b, "REJECTED\r\n");
432 } else if (line_equals(line, l, "BEGIN")) {
434 if (b->auth == _BUS_AUTH_INVALID)
435 r = bus_socket_auth_write(b, "ERROR\r\n");
437 /* We can't leave from the auth phase
438 * before we haven't written
439 * everything queued, so let's check
442 if (bus_socket_auth_needs_write(b))
445 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
446 memmove(b->rbuffer, e + 2, b->rbuffer_size);
447 return bus_start_running(b);
450 } else if (line_begins(line, l, "DATA")) {
452 if (b->auth == _BUS_AUTH_INVALID)
453 r = bus_socket_auth_write(b, "ERROR\r\n");
455 if (b->auth == BUS_AUTH_ANONYMOUS)
456 r = verify_anonymous_token(b, line + 4, l - 4);
458 r = verify_external_token(b, line + 4, l - 4);
463 b->auth = _BUS_AUTH_INVALID;
464 r = bus_socket_auth_write(b, "REJECTED\r\n");
466 r = bus_socket_auth_write_ok(b);
468 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
469 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
470 r = bus_socket_auth_write(b, "ERROR\r\n");
473 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
476 r = bus_socket_auth_write(b, "ERROR\r\n");
481 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
487 static int bus_socket_auth_verify(sd_bus *b) {
491 return bus_socket_auth_verify_server(b);
493 return bus_socket_auth_verify_client(b);
496 static int bus_socket_read_auth(sd_bus *b) {
498 struct iovec iov = {};
504 struct cmsghdr cmsghdr;
505 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
507 bool handle_cmsg = false;
510 assert(b->state == BUS_AUTHENTICATING);
512 r = bus_socket_auth_verify(b);
516 n = MAX(256u, b->rbuffer_size * 2);
518 if (n > BUS_AUTH_SIZE_MAX)
519 n = BUS_AUTH_SIZE_MAX;
521 if (b->rbuffer_size >= n)
524 p = realloc(b->rbuffer, n);
530 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
531 iov.iov_len = n - b->rbuffer_size;
534 k = readv(b->input_fd, &iov, 1);
539 mh.msg_control = &control;
540 mh.msg_controllen = sizeof(control);
542 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
543 if (k < 0 && errno == ENOTSOCK) {
544 b->prefer_readv = true;
545 k = readv(b->input_fd, &iov, 1);
550 return errno == EAGAIN ? 0 : -errno;
554 b->rbuffer_size += k;
557 struct cmsghdr *cmsg;
559 CMSG_FOREACH(cmsg, &mh)
560 if (cmsg->cmsg_level == SOL_SOCKET &&
561 cmsg->cmsg_type == SCM_RIGHTS) {
564 /* Whut? We received fds during the auth
565 * protocol? Somebody is playing games with
566 * us. Close them all, and fail */
567 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
568 close_many((int*) CMSG_DATA(cmsg), j);
571 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
572 cmsg->cmsg_level, cmsg->cmsg_type);
575 r = bus_socket_auth_verify(b);
582 void bus_socket_setup(sd_bus *b) {
585 /* Increase the buffers to 8 MB */
586 (void) fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
587 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
589 b->message_version = 1;
590 b->message_endian = 0;
593 static void bus_get_peercred(sd_bus *b) {
597 assert(!b->ucred_valid);
599 assert(b->n_groups == (size_t) -1);
601 /* Get the peer for socketpair() sockets */
602 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
604 /* Get the SELinux context of the peer */
605 r = getpeersec(b->input_fd, &b->label);
606 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
607 log_debug_errno(r, "Failed to determine peer security context: %m");
609 /* Get the list of auxiliary groups of the peer */
610 r = getpeergroups(b->input_fd, &b->groups);
612 b->n_groups = (size_t) r;
613 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
614 log_debug_errno(r, "Failed to determine peer's group list: %m");
617 static int bus_socket_start_auth_client(sd_bus *b) {
619 const char *auth_suffix, *auth_prefix;
623 if (b->anonymous_auth) {
624 auth_prefix = "\0AUTH ANONYMOUS ";
626 /* For ANONYMOUS auth we send some arbitrary "trace" string */
628 b->auth_buffer = hexmem("anonymous", l);
630 char text[DECIMAL_STR_MAX(uid_t) + 1];
632 auth_prefix = "\0AUTH EXTERNAL ";
634 xsprintf(text, UID_FMT, geteuid());
637 b->auth_buffer = hexmem(text, l);
644 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
646 auth_suffix = "\r\nBEGIN\r\n";
648 b->auth_iovec[0].iov_base = (void*) auth_prefix;
649 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
650 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
651 b->auth_iovec[1].iov_len = l * 2;
652 b->auth_iovec[2].iov_base = (void*) auth_suffix;
653 b->auth_iovec[2].iov_len = strlen(auth_suffix);
655 return bus_socket_write_auth(b);
658 int bus_socket_start_auth(sd_bus *b) {
663 bus_set_state(b, BUS_AUTHENTICATING);
664 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
666 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
667 b->accept_fd = false;
669 if (b->output_fd != b->input_fd)
670 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
671 b->accept_fd = false;
674 return bus_socket_read_auth(b);
676 return bus_socket_start_auth_client(b);
679 static int bus_socket_inotify_setup(sd_bus *b) {
680 _cleanup_free_ int *new_watches = NULL;
681 _cleanup_free_ char *absolute = NULL;
682 size_t n_allocated = 0, n = 0, done = 0, i;
683 unsigned max_follow = 32;
688 assert(b->watch_bind);
689 assert(b->sockaddr.sa.sa_family == AF_UNIX);
690 assert(b->sockaddr.un.sun_path[0] != 0);
692 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
693 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
694 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
695 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
696 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
699 if (b->inotify_fd < 0) {
700 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
701 if (b->inotify_fd < 0)
704 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
707 /* Make sure the path is NUL terminated */
708 p = strndupa(b->sockaddr.un.sun_path, sizeof(b->sockaddr.un.sun_path));
710 /* Make sure the path is absolute */
711 r = path_make_absolute_cwd(p, &absolute);
715 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
716 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
717 * they are removed or renamed. */
719 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
724 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
726 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
728 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
731 new_watches[n++] = wd;
734 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
735 size_t n_slashes, n_component;
738 n_slashes = strspn(absolute + done, "/");
739 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
741 if (n_component == 0) /* The end */
744 component = strndup(absolute + done, n_component);
750 /* A trailing slash? That's a directory, and not a socket then */
751 if (path_equal(component, "/")) {
756 /* A single dot? Let's eat this up */
757 if (path_equal(component, "/.")) {
762 prefix = strndup(absolute, done + n_component);
768 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
773 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
774 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
777 if (IN_SET(errno, ENOENT, ELOOP))
778 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
780 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", isempty(prefix) ? "/" : prefix);
783 new_watches[n++] = wd;
785 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
786 r = readlink_malloc(prefix, &destination);
787 if (r == -EINVAL) { /* not a symlink */
794 if (isempty(destination)) { /* Empty symlink target? Yuck! */
799 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
804 if (path_is_absolute(destination)) {
805 /* For absolute symlinks we build the new path and start anew */
806 c = strjoin(destination, absolute + done + n_component);
809 _cleanup_free_ char *t = NULL;
811 /* For relative symlinks we replace the last component, and try again */
812 t = strndup(absolute, done);
816 c = strjoin(t, "/", destination, absolute + done + n_component);
829 /* And now, let's remove all watches from the previous iteration we don't need anymore */
830 for (i = 0; i < b->n_inotify_watches; i++) {
834 for (j = 0; j < n; j++)
835 if (new_watches[j] == b->inotify_watches[i]) {
843 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
846 free_and_replace(b->inotify_watches, new_watches);
847 b->n_inotify_watches = n;
852 bus_close_inotify_fd(b);
856 int bus_socket_connect(sd_bus *b) {
857 bool inotify_done = false;
863 assert(b->input_fd < 0);
864 assert(b->output_fd < 0);
865 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
867 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
871 b->input_fd = fd_move_above_stdio(b->input_fd);
873 b->output_fd = b->input_fd;
876 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
877 if (errno == EINPROGRESS) {
879 /* If we have any inotify watches open, close them now, we don't need them anymore, as
880 * we have successfully initiated a connection */
881 bus_close_inotify_fd(b);
883 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
884 * we start parsing the address string. The only reason we set the state explicitly
885 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
886 bus_set_state(b, BUS_OPENING);
890 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
892 b->sockaddr.sa.sa_family == AF_UNIX &&
893 b->sockaddr.un.sun_path[0] != 0) {
895 /* This connection attempt failed, let's release the socket for now, and start with a
896 * fresh one when reconnecting. */
900 /* inotify set up already, don't do it again, just return now, and remember
901 * that we are waiting for inotify events now. */
902 bus_set_state(b, BUS_WATCH_BIND);
906 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
907 r = bus_socket_inotify_setup(b);
911 /* Let's now try to connect a second time, because in theory there's otherwise a race
912 * here: the socket might have been created in the time between our first connect() and
913 * the time we set up the inotify logic. But let's remember that we set up inotify now,
914 * so that we don't do the connect() more than twice. */
923 /* Yay, established, we don't need no inotify anymore! */
924 bus_close_inotify_fd(b);
926 return bus_socket_start_auth(b);
929 int bus_socket_exec(sd_bus *b) {
933 assert(b->input_fd < 0);
934 assert(b->output_fd < 0);
935 assert(b->exec_path);
936 assert(b->busexec_pid == 0);
938 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
942 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &b->busexec_pid);
950 if (rearrange_stdio(s[1], s[1], STDERR_FILENO) < 0)
954 execvp(b->exec_path, b->exec_argv);
956 const char *argv[] = { b->exec_path, NULL };
957 execvp(b->exec_path, (char**) argv);
964 b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
968 return bus_socket_start_auth(b);
971 int bus_socket_take_fd(sd_bus *b) {
976 return bus_socket_start_auth(b);
979 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
989 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
991 if (*idx >= BUS_MESSAGE_SIZE(m))
994 r = bus_message_setup_iovec(m);
998 n = m->n_iovec * sizeof(struct iovec);
1000 memcpy_safe(iov, m->iovec, n);
1003 iovec_advance(iov, &j, *idx);
1005 if (bus->prefer_writev)
1006 k = writev(bus->output_fd, iov, m->n_iovec);
1008 struct msghdr mh = {
1010 .msg_iovlen = m->n_iovec,
1013 if (m->n_fds > 0 && *idx == 0) {
1014 struct cmsghdr *control;
1016 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
1017 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
1018 control->cmsg_level = SOL_SOCKET;
1019 control->cmsg_type = SCM_RIGHTS;
1020 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1023 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1024 if (k < 0 && errno == ENOTSOCK) {
1025 bus->prefer_writev = true;
1026 k = writev(bus->output_fd, iov, m->n_iovec);
1031 return errno == EAGAIN ? 0 : -errno;
1037 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1044 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1046 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1047 *need = sizeof(struct bus_header) + 8;
1049 /* Minimum message size:
1053 * Method Call: +2 string headers
1054 * Signal: +3 string headers
1055 * Method Error: +1 string headers
1057 * Method Reply: +1 uint32 headers
1059 * A string header is at least 9 bytes
1060 * A uint32 header is at least 8 bytes
1062 * Hence the minimum message size of a valid message
1063 * is header + 8 bytes */
1068 a = ((const uint32_t*) bus->rbuffer)[1];
1069 b = ((const uint32_t*) bus->rbuffer)[3];
1071 e = ((const uint8_t*) bus->rbuffer)[0];
1072 if (e == BUS_LITTLE_ENDIAN) {
1075 } else if (e == BUS_BIG_ENDIAN) {
1081 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
1082 if (sum >= BUS_MESSAGE_SIZE_MAX)
1085 *need = (size_t) sum;
1089 static int bus_socket_make_message(sd_bus *bus, size_t size) {
1095 assert(bus->rbuffer_size >= size);
1096 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1098 r = bus_rqueue_make_room(bus);
1102 if (bus->rbuffer_size > size) {
1103 b = memdup((const uint8_t*) bus->rbuffer + size,
1104 bus->rbuffer_size - size);
1110 r = bus_message_from_malloc(bus,
1112 bus->fds, bus->n_fds,
1121 bus->rbuffer_size -= size;
1126 bus->rqueue[bus->rqueue_size++] = t;
1131 int bus_socket_read_message(sd_bus *bus) {
1133 struct iovec iov = {};
1139 struct cmsghdr cmsghdr;
1140 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
1142 bool handle_cmsg = false;
1145 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1147 r = bus_socket_read_message_need(bus, &need);
1151 if (bus->rbuffer_size >= need)
1152 return bus_socket_make_message(bus, need);
1154 b = realloc(bus->rbuffer, need);
1160 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
1161 iov.iov_len = need - bus->rbuffer_size;
1163 if (bus->prefer_readv)
1164 k = readv(bus->input_fd, &iov, 1);
1169 mh.msg_control = &control;
1170 mh.msg_controllen = sizeof(control);
1172 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
1173 if (k < 0 && errno == ENOTSOCK) {
1174 bus->prefer_readv = true;
1175 k = readv(bus->input_fd, &iov, 1);
1180 return errno == EAGAIN ? 0 : -errno;
1184 bus->rbuffer_size += k;
1187 struct cmsghdr *cmsg;
1189 CMSG_FOREACH(cmsg, &mh)
1190 if (cmsg->cmsg_level == SOL_SOCKET &&
1191 cmsg->cmsg_type == SCM_RIGHTS) {
1194 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1196 if (!bus->can_fds) {
1197 /* Whut? We received fds but this
1198 * isn't actually enabled? Close them,
1201 close_many((int*) CMSG_DATA(cmsg), n);
1205 f = reallocarray(bus->fds, bus->n_fds + n, sizeof(int));
1207 close_many((int*) CMSG_DATA(cmsg), n);
1211 for (i = 0; i < n; i++)
1212 f[bus->n_fds++] = fd_move_above_stdio(((int*) CMSG_DATA(cmsg))[i]);
1215 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1216 cmsg->cmsg_level, cmsg->cmsg_type);
1219 r = bus_socket_read_message_need(bus, &need);
1223 if (bus->rbuffer_size >= need)
1224 return bus_socket_make_message(bus, need);
1229 int bus_socket_process_opening(sd_bus *b) {
1231 socklen_t slen = sizeof(error);
1238 assert(b->state == BUS_OPENING);
1244 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1247 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1249 b->last_connect_error = errno;
1250 else if (error != 0)
1251 b->last_connect_error = error;
1252 else if (p.revents & (POLLERR|POLLHUP))
1253 b->last_connect_error = ECONNREFUSED;
1255 return bus_socket_start_auth(b);
1257 return bus_next_address(b);
1260 int bus_socket_process_authenticating(sd_bus *b) {
1264 assert(b->state == BUS_AUTHENTICATING);
1266 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1269 r = bus_socket_write_auth(b);
1273 return bus_socket_read_auth(b);
1276 int bus_socket_process_watch_bind(sd_bus *b) {
1280 assert(b->state == BUS_WATCH_BIND);
1281 assert(b->inotify_fd >= 0);
1283 r = flush_fd(b->inotify_fd);
1287 log_debug("Got inotify event on bus %s.", strna(b->description));
1289 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1292 r = bus_socket_connect(b);
1296 q = bus_attach_io_events(b);
1300 q = bus_attach_inotify_event(b);