1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2013 Lennart Poettering
12 #include "sd-daemon.h"
14 #include "alloc-util.h"
15 #include "bus-internal.h"
16 #include "bus-message.h"
17 #include "bus-socket.h"
19 #include "format-util.h"
21 #include "hexdecoct.h"
25 #include "path-util.h"
26 #include "process-util.h"
27 #include "selinux-util.h"
28 #include "signal-util.h"
29 #include "stdio-util.h"
30 #include "string-util.h"
31 #include "user-util.h"
35 #define SNDBUF_SIZE (8*1024*1024)
37 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
40 struct iovec *i = iov + *idx;
42 if (i->iov_len > size) {
43 i->iov_base = (uint8_t*) i->iov_base + size;
57 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
62 m->iovec[m->n_iovec].iov_base = (void*) p;
63 m->iovec[m->n_iovec].iov_len = sz;
69 static int bus_message_setup_iovec(sd_bus_message *m) {
70 struct bus_body_part *part;
82 n = 1 + m->n_body_parts;
83 if (n < ELEMENTSOF(m->iovec_fixed))
84 m->iovec = m->iovec_fixed;
86 m->iovec = new(struct iovec, n);
93 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
97 MESSAGE_FOREACH_PART(part, i, m) {
98 r = bus_body_part_map(part);
102 r = append_iovec(m, part->data, part->size);
107 assert(n == m->n_iovec);
116 bool bus_socket_auth_needs_write(sd_bus *b) {
120 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
123 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
124 struct iovec *j = b->auth_iovec + i;
133 static int bus_socket_write_auth(sd_bus *b) {
137 assert(b->state == BUS_AUTHENTICATING);
139 if (!bus_socket_auth_needs_write(b))
142 if (b->prefer_writev)
143 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
148 mh.msg_iov = b->auth_iovec + b->auth_index;
149 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
151 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
152 if (k < 0 && errno == ENOTSOCK) {
153 b->prefer_writev = true;
154 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
159 return errno == EAGAIN ? 0 : -errno;
161 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
165 static int bus_socket_auth_verify_client(sd_bus *b) {
173 /* We expect two response lines: "OK" and possibly
176 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
181 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
191 /* Nice! We got all the lines we need. First check the OK
194 if (e - (char*) b->rbuffer != 3 + 32)
197 if (memcmp(b->rbuffer, "OK ", 3))
200 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
202 for (i = 0; i < 32; i += 2) {
205 x = unhexchar(((char*) b->rbuffer)[3 + i]);
206 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
211 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
214 if (!sd_id128_is_null(b->server_id) &&
215 !sd_id128_equal(b->server_id, peer))
220 /* And possibly check the second line, too */
224 (f - e == STRLEN("\r\nAGREE_UNIX_FD")) &&
225 memcmp(e + 2, "AGREE_UNIX_FD",
226 STRLEN("AGREE_UNIX_FD")) == 0;
228 b->rbuffer_size -= (start - (char*) b->rbuffer);
229 memmove(b->rbuffer, start, b->rbuffer_size);
231 r = bus_start_running(b);
238 static bool line_equals(const char *s, size_t m, const char *line) {
245 return memcmp(s, line, l) == 0;
248 static bool line_begins(const char *s, size_t m, const char *word) {
251 p = memory_startswith(s, m, word);
255 return IN_SET(*p, 0, ' ');
258 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
259 _cleanup_free_ char *token = NULL;
263 if (!b->anonymous_auth)
275 r = unhexmem(p, l, (void **) &token, &len);
279 if (memchr(token, 0, len))
282 return !!utf8_is_valid(token);
285 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
286 _cleanup_free_ char *token = NULL;
291 /* We don't do any real authentication here. Instead, we if
292 * the owner of this bus wanted authentication he should have
293 * checked SO_PEERCRED before even creating the bus object. */
295 if (!b->anonymous_auth && !b->ucred_valid)
307 r = unhexmem(p, l, (void**) &token, &len);
311 if (memchr(token, 0, len))
314 r = parse_uid(token, &u);
318 /* We ignore the passed value if anonymous authentication is
320 if (!b->anonymous_auth && u != b->ucred.uid)
326 static int bus_socket_auth_write(sd_bus *b, const char *t) {
333 /* We only make use of the first iovec */
334 assert(IN_SET(b->auth_index, 0, 1));
337 p = malloc(b->auth_iovec[0].iov_len + l);
341 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
342 memcpy(p + b->auth_iovec[0].iov_len, t, l);
344 b->auth_iovec[0].iov_base = p;
345 b->auth_iovec[0].iov_len += l;
347 free(b->auth_buffer);
353 static int bus_socket_auth_write_ok(sd_bus *b) {
354 char t[3 + 32 + 2 + 1];
358 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
360 return bus_socket_auth_write(b, t);
363 static int bus_socket_auth_verify_server(sd_bus *b) {
367 bool processed = false;
372 if (b->rbuffer_size < 1)
375 /* First char must be a NUL byte */
376 if (*(char*) b->rbuffer != 0)
379 if (b->rbuffer_size < 3)
382 /* Begin with the first line */
383 if (b->auth_rbegin <= 0)
387 /* Check if line is complete */
388 line = (char*) b->rbuffer + b->auth_rbegin;
389 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
395 if (line_begins(line, l, "AUTH ANONYMOUS")) {
397 r = verify_anonymous_token(b, line + 14, l - 14);
401 r = bus_socket_auth_write(b, "REJECTED\r\n");
403 b->auth = BUS_AUTH_ANONYMOUS;
404 r = bus_socket_auth_write_ok(b);
407 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
409 r = verify_external_token(b, line + 13, l - 13);
413 r = bus_socket_auth_write(b, "REJECTED\r\n");
415 b->auth = BUS_AUTH_EXTERNAL;
416 r = bus_socket_auth_write_ok(b);
419 } else if (line_begins(line, l, "AUTH"))
420 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
421 else if (line_equals(line, l, "CANCEL") ||
422 line_begins(line, l, "ERROR")) {
424 b->auth = _BUS_AUTH_INVALID;
425 r = bus_socket_auth_write(b, "REJECTED\r\n");
427 } else if (line_equals(line, l, "BEGIN")) {
429 if (b->auth == _BUS_AUTH_INVALID)
430 r = bus_socket_auth_write(b, "ERROR\r\n");
432 /* We can't leave from the auth phase
433 * before we haven't written
434 * everything queued, so let's check
437 if (bus_socket_auth_needs_write(b))
440 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
441 memmove(b->rbuffer, e + 2, b->rbuffer_size);
442 return bus_start_running(b);
445 } else if (line_begins(line, l, "DATA")) {
447 if (b->auth == _BUS_AUTH_INVALID)
448 r = bus_socket_auth_write(b, "ERROR\r\n");
450 if (b->auth == BUS_AUTH_ANONYMOUS)
451 r = verify_anonymous_token(b, line + 4, l - 4);
453 r = verify_external_token(b, line + 4, l - 4);
458 b->auth = _BUS_AUTH_INVALID;
459 r = bus_socket_auth_write(b, "REJECTED\r\n");
461 r = bus_socket_auth_write_ok(b);
463 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
464 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
465 r = bus_socket_auth_write(b, "ERROR\r\n");
468 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
471 r = bus_socket_auth_write(b, "ERROR\r\n");
476 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
482 static int bus_socket_auth_verify(sd_bus *b) {
486 return bus_socket_auth_verify_server(b);
488 return bus_socket_auth_verify_client(b);
491 static int bus_socket_read_auth(sd_bus *b) {
493 struct iovec iov = {};
499 struct cmsghdr cmsghdr;
500 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
502 bool handle_cmsg = false;
505 assert(b->state == BUS_AUTHENTICATING);
507 r = bus_socket_auth_verify(b);
511 n = MAX(256u, b->rbuffer_size * 2);
513 if (n > BUS_AUTH_SIZE_MAX)
514 n = BUS_AUTH_SIZE_MAX;
516 if (b->rbuffer_size >= n)
519 p = realloc(b->rbuffer, n);
525 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
526 iov.iov_len = n - b->rbuffer_size;
529 k = readv(b->input_fd, &iov, 1);
534 mh.msg_control = &control;
535 mh.msg_controllen = sizeof(control);
537 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
538 if (k < 0 && errno == ENOTSOCK) {
539 b->prefer_readv = true;
540 k = readv(b->input_fd, &iov, 1);
545 return errno == EAGAIN ? 0 : -errno;
549 b->rbuffer_size += k;
552 struct cmsghdr *cmsg;
554 CMSG_FOREACH(cmsg, &mh)
555 if (cmsg->cmsg_level == SOL_SOCKET &&
556 cmsg->cmsg_type == SCM_RIGHTS) {
559 /* Whut? We received fds during the auth
560 * protocol? Somebody is playing games with
561 * us. Close them all, and fail */
562 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
563 close_many((int*) CMSG_DATA(cmsg), j);
566 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
567 cmsg->cmsg_level, cmsg->cmsg_type);
570 r = bus_socket_auth_verify(b);
577 void bus_socket_setup(sd_bus *b) {
580 /* Increase the buffers to 8 MB */
581 (void) fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
582 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
584 b->message_version = 1;
585 b->message_endian = 0;
588 static void bus_get_peercred(sd_bus *b) {
592 assert(!b->ucred_valid);
594 assert(b->n_groups == (size_t) -1);
596 /* Get the peer for socketpair() sockets */
597 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
599 /* Get the SELinux context of the peer */
600 r = getpeersec(b->input_fd, &b->label);
601 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
602 log_debug_errno(r, "Failed to determine peer security context: %m");
604 /* Get the list of auxiliary groups of the peer */
605 r = getpeergroups(b->input_fd, &b->groups);
607 b->n_groups = (size_t) r;
608 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
609 log_debug_errno(r, "Failed to determine peer's group list: %m");
612 static int bus_socket_start_auth_client(sd_bus *b) {
614 const char *auth_suffix, *auth_prefix;
618 if (b->anonymous_auth) {
619 auth_prefix = "\0AUTH ANONYMOUS ";
621 /* For ANONYMOUS auth we send some arbitrary "trace" string */
623 b->auth_buffer = hexmem("anonymous", l);
625 char text[DECIMAL_STR_MAX(uid_t) + 1];
627 auth_prefix = "\0AUTH EXTERNAL ";
629 xsprintf(text, UID_FMT, geteuid());
632 b->auth_buffer = hexmem(text, l);
639 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
641 auth_suffix = "\r\nBEGIN\r\n";
643 b->auth_iovec[0].iov_base = (void*) auth_prefix;
644 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
645 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
646 b->auth_iovec[1].iov_len = l * 2;
647 b->auth_iovec[2].iov_base = (void*) auth_suffix;
648 b->auth_iovec[2].iov_len = strlen(auth_suffix);
650 return bus_socket_write_auth(b);
653 int bus_socket_start_auth(sd_bus *b) {
658 bus_set_state(b, BUS_AUTHENTICATING);
659 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
661 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
662 b->accept_fd = false;
664 if (b->output_fd != b->input_fd)
665 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
666 b->accept_fd = false;
669 return bus_socket_read_auth(b);
671 return bus_socket_start_auth_client(b);
674 static int bus_socket_inotify_setup(sd_bus *b) {
675 _cleanup_free_ int *new_watches = NULL;
676 _cleanup_free_ char *absolute = NULL;
677 size_t n_allocated = 0, n = 0, done = 0, i;
678 unsigned max_follow = 32;
683 assert(b->watch_bind);
684 assert(b->sockaddr.sa.sa_family == AF_UNIX);
685 assert(b->sockaddr.un.sun_path[0] != 0);
687 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
688 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
689 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
690 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
691 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
694 if (b->inotify_fd < 0) {
695 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
696 if (b->inotify_fd < 0)
699 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
702 /* Make sure the path is NUL terminated */
703 p = strndupa(b->sockaddr.un.sun_path, sizeof(b->sockaddr.un.sun_path));
705 /* Make sure the path is absolute */
706 r = path_make_absolute_cwd(p, &absolute);
710 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
711 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
712 * they are removed or renamed. */
714 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
719 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
721 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
723 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
726 new_watches[n++] = wd;
729 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
730 size_t n_slashes, n_component;
733 n_slashes = strspn(absolute + done, "/");
734 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
736 if (n_component == 0) /* The end */
739 component = strndup(absolute + done, n_component);
745 /* A trailing slash? That's a directory, and not a socket then */
746 if (path_equal(component, "/")) {
751 /* A single dot? Let's eat this up */
752 if (path_equal(component, "/.")) {
757 prefix = strndup(absolute, done + n_component);
763 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
768 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
769 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
772 if (IN_SET(errno, ENOENT, ELOOP))
773 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
775 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", empty_to_root(prefix));
778 new_watches[n++] = wd;
780 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
781 r = readlink_malloc(prefix, &destination);
782 if (r == -EINVAL) { /* not a symlink */
789 if (isempty(destination)) { /* Empty symlink target? Yuck! */
794 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
799 if (path_is_absolute(destination)) {
800 /* For absolute symlinks we build the new path and start anew */
801 c = strjoin(destination, absolute + done + n_component);
804 _cleanup_free_ char *t = NULL;
806 /* For relative symlinks we replace the last component, and try again */
807 t = strndup(absolute, done);
811 c = strjoin(t, "/", destination, absolute + done + n_component);
824 /* And now, let's remove all watches from the previous iteration we don't need anymore */
825 for (i = 0; i < b->n_inotify_watches; i++) {
829 for (j = 0; j < n; j++)
830 if (new_watches[j] == b->inotify_watches[i]) {
838 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
841 free_and_replace(b->inotify_watches, new_watches);
842 b->n_inotify_watches = n;
847 bus_close_inotify_fd(b);
851 int bus_socket_connect(sd_bus *b) {
852 bool inotify_done = false;
858 assert(b->input_fd < 0);
859 assert(b->output_fd < 0);
860 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
862 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
866 b->input_fd = fd_move_above_stdio(b->input_fd);
868 b->output_fd = b->input_fd;
871 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
872 if (errno == EINPROGRESS) {
874 /* If we have any inotify watches open, close them now, we don't need them anymore, as
875 * we have successfully initiated a connection */
876 bus_close_inotify_fd(b);
878 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
879 * we start parsing the address string. The only reason we set the state explicitly
880 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
881 bus_set_state(b, BUS_OPENING);
885 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
887 b->sockaddr.sa.sa_family == AF_UNIX &&
888 b->sockaddr.un.sun_path[0] != 0) {
890 /* This connection attempt failed, let's release the socket for now, and start with a
891 * fresh one when reconnecting. */
895 /* inotify set up already, don't do it again, just return now, and remember
896 * that we are waiting for inotify events now. */
897 bus_set_state(b, BUS_WATCH_BIND);
901 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
902 r = bus_socket_inotify_setup(b);
906 /* Let's now try to connect a second time, because in theory there's otherwise a race
907 * here: the socket might have been created in the time between our first connect() and
908 * the time we set up the inotify logic. But let's remember that we set up inotify now,
909 * so that we don't do the connect() more than twice. */
918 /* Yay, established, we don't need no inotify anymore! */
919 bus_close_inotify_fd(b);
921 return bus_socket_start_auth(b);
924 int bus_socket_exec(sd_bus *b) {
928 assert(b->input_fd < 0);
929 assert(b->output_fd < 0);
930 assert(b->exec_path);
931 assert(b->busexec_pid == 0);
933 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
937 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &b->busexec_pid);
945 if (rearrange_stdio(s[1], s[1], STDERR_FILENO) < 0)
949 execvp(b->exec_path, b->exec_argv);
951 const char *argv[] = { b->exec_path, NULL };
952 execvp(b->exec_path, (char**) argv);
959 b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
963 return bus_socket_start_auth(b);
966 int bus_socket_take_fd(sd_bus *b) {
971 return bus_socket_start_auth(b);
974 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
984 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
986 if (*idx >= BUS_MESSAGE_SIZE(m))
989 r = bus_message_setup_iovec(m);
993 n = m->n_iovec * sizeof(struct iovec);
995 memcpy_safe(iov, m->iovec, n);
998 iovec_advance(iov, &j, *idx);
1000 if (bus->prefer_writev)
1001 k = writev(bus->output_fd, iov, m->n_iovec);
1003 struct msghdr mh = {
1005 .msg_iovlen = m->n_iovec,
1008 if (m->n_fds > 0 && *idx == 0) {
1009 struct cmsghdr *control;
1011 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
1012 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
1013 control->cmsg_level = SOL_SOCKET;
1014 control->cmsg_type = SCM_RIGHTS;
1015 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1018 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1019 if (k < 0 && errno == ENOTSOCK) {
1020 bus->prefer_writev = true;
1021 k = writev(bus->output_fd, iov, m->n_iovec);
1026 return errno == EAGAIN ? 0 : -errno;
1032 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1039 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1041 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1042 *need = sizeof(struct bus_header) + 8;
1044 /* Minimum message size:
1048 * Method Call: +2 string headers
1049 * Signal: +3 string headers
1050 * Method Error: +1 string headers
1052 * Method Reply: +1 uint32 headers
1054 * A string header is at least 9 bytes
1055 * A uint32 header is at least 8 bytes
1057 * Hence the minimum message size of a valid message
1058 * is header + 8 bytes */
1063 a = ((const uint32_t*) bus->rbuffer)[1];
1064 b = ((const uint32_t*) bus->rbuffer)[3];
1066 e = ((const uint8_t*) bus->rbuffer)[0];
1067 if (e == BUS_LITTLE_ENDIAN) {
1070 } else if (e == BUS_BIG_ENDIAN) {
1076 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
1077 if (sum >= BUS_MESSAGE_SIZE_MAX)
1080 *need = (size_t) sum;
1084 static int bus_socket_make_message(sd_bus *bus, size_t size) {
1090 assert(bus->rbuffer_size >= size);
1091 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1093 r = bus_rqueue_make_room(bus);
1097 if (bus->rbuffer_size > size) {
1098 b = memdup((const uint8_t*) bus->rbuffer + size,
1099 bus->rbuffer_size - size);
1105 r = bus_message_from_malloc(bus,
1107 bus->fds, bus->n_fds,
1116 bus->rbuffer_size -= size;
1121 bus->rqueue[bus->rqueue_size++] = t;
1126 int bus_socket_read_message(sd_bus *bus) {
1128 struct iovec iov = {};
1134 struct cmsghdr cmsghdr;
1135 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
1137 bool handle_cmsg = false;
1140 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1142 r = bus_socket_read_message_need(bus, &need);
1146 if (bus->rbuffer_size >= need)
1147 return bus_socket_make_message(bus, need);
1149 b = realloc(bus->rbuffer, need);
1155 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
1156 iov.iov_len = need - bus->rbuffer_size;
1158 if (bus->prefer_readv)
1159 k = readv(bus->input_fd, &iov, 1);
1164 mh.msg_control = &control;
1165 mh.msg_controllen = sizeof(control);
1167 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
1168 if (k < 0 && errno == ENOTSOCK) {
1169 bus->prefer_readv = true;
1170 k = readv(bus->input_fd, &iov, 1);
1175 return errno == EAGAIN ? 0 : -errno;
1179 bus->rbuffer_size += k;
1182 struct cmsghdr *cmsg;
1184 CMSG_FOREACH(cmsg, &mh)
1185 if (cmsg->cmsg_level == SOL_SOCKET &&
1186 cmsg->cmsg_type == SCM_RIGHTS) {
1189 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1191 if (!bus->can_fds) {
1192 /* Whut? We received fds but this
1193 * isn't actually enabled? Close them,
1196 close_many((int*) CMSG_DATA(cmsg), n);
1200 f = reallocarray(bus->fds, bus->n_fds + n, sizeof(int));
1202 close_many((int*) CMSG_DATA(cmsg), n);
1206 for (i = 0; i < n; i++)
1207 f[bus->n_fds++] = fd_move_above_stdio(((int*) CMSG_DATA(cmsg))[i]);
1210 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1211 cmsg->cmsg_level, cmsg->cmsg_type);
1214 r = bus_socket_read_message_need(bus, &need);
1218 if (bus->rbuffer_size >= need)
1219 return bus_socket_make_message(bus, need);
1224 int bus_socket_process_opening(sd_bus *b) {
1226 socklen_t slen = sizeof(error);
1233 assert(b->state == BUS_OPENING);
1239 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1242 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1244 b->last_connect_error = errno;
1245 else if (error != 0)
1246 b->last_connect_error = error;
1247 else if (p.revents & (POLLERR|POLLHUP))
1248 b->last_connect_error = ECONNREFUSED;
1250 return bus_socket_start_auth(b);
1252 return bus_next_address(b);
1255 int bus_socket_process_authenticating(sd_bus *b) {
1259 assert(b->state == BUS_AUTHENTICATING);
1261 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1264 r = bus_socket_write_auth(b);
1268 return bus_socket_read_auth(b);
1271 int bus_socket_process_watch_bind(sd_bus *b) {
1275 assert(b->state == BUS_WATCH_BIND);
1276 assert(b->inotify_fd >= 0);
1278 r = flush_fd(b->inotify_fd);
1282 log_debug("Got inotify event on bus %s.", strna(b->description));
1284 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1287 r = bus_socket_connect(b);
1291 q = bus_attach_io_events(b);
1295 q = bus_attach_inotify_event(b);