]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-bus/bus-socket.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include "alloc-util.h"
12 #include "bus-internal.h"
13 #include "bus-message.h"
14 #include "bus-socket.h"
16 #include "format-util.h"
18 #include "hexdecoct.h"
22 #include "path-util.h"
23 #include "process-util.h"
24 #include "rlimit-util.h"
25 #include "selinux-util.h"
26 #include "signal-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "user-util.h"
33 #define SNDBUF_SIZE (8*1024*1024)
35 static void iovec_advance(struct iovec iov
[], unsigned *idx
, size_t size
) {
38 struct iovec
*i
= iov
+ *idx
;
40 if (i
->iov_len
> size
) {
41 i
->iov_base
= (uint8_t*) i
->iov_base
+ size
;
48 *i
= IOVEC_MAKE(NULL
, 0);
54 static int append_iovec(sd_bus_message
*m
, const void *p
, size_t sz
) {
59 m
->iovec
[m
->n_iovec
++] = IOVEC_MAKE((void*) p
, sz
);
64 static int bus_message_setup_iovec(sd_bus_message
*m
) {
65 struct bus_body_part
*part
;
77 n
= 1 + m
->n_body_parts
;
78 if (n
< ELEMENTSOF(m
->iovec_fixed
))
79 m
->iovec
= m
->iovec_fixed
;
81 m
->iovec
= new(struct iovec
, n
);
88 r
= append_iovec(m
, m
->header
, BUS_MESSAGE_BODY_BEGIN(m
));
92 MESSAGE_FOREACH_PART(part
, i
, m
) {
93 r
= bus_body_part_map(part
);
97 r
= append_iovec(m
, part
->data
, part
->size
);
102 assert(n
== m
->n_iovec
);
111 bool bus_socket_auth_needs_write(sd_bus
*b
) {
115 if (b
->auth_index
>= ELEMENTSOF(b
->auth_iovec
))
118 for (i
= b
->auth_index
; i
< ELEMENTSOF(b
->auth_iovec
); i
++) {
119 struct iovec
*j
= b
->auth_iovec
+ i
;
128 static int bus_socket_write_auth(sd_bus
*b
) {
132 assert(b
->state
== BUS_AUTHENTICATING
);
134 if (!bus_socket_auth_needs_write(b
))
137 if (b
->prefer_writev
)
138 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
143 mh
.msg_iov
= b
->auth_iovec
+ b
->auth_index
;
144 mh
.msg_iovlen
= ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
;
146 k
= sendmsg(b
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
147 if (k
< 0 && errno
== ENOTSOCK
) {
148 b
->prefer_writev
= true;
149 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
154 return errno
== EAGAIN
? 0 : -errno
;
156 iovec_advance(b
->auth_iovec
, &b
->auth_index
, (size_t) k
);
160 static int bus_socket_auth_verify_client(sd_bus
*b
) {
168 /* We expect two response lines: "OK" and possibly
171 e
= memmem_safe(b
->rbuffer
, b
->rbuffer_size
, "\r\n", 2);
176 f
= memmem(e
+ 2, b
->rbuffer_size
- (e
- (char*) b
->rbuffer
) - 2, "\r\n", 2);
186 /* Nice! We got all the lines we need. First check the OK
189 if (e
- (char*) b
->rbuffer
!= 3 + 32)
192 if (memcmp(b
->rbuffer
, "OK ", 3))
195 b
->auth
= b
->anonymous_auth
? BUS_AUTH_ANONYMOUS
: BUS_AUTH_EXTERNAL
;
197 for (i
= 0; i
< 32; i
+= 2) {
200 x
= unhexchar(((char*) b
->rbuffer
)[3 + i
]);
201 y
= unhexchar(((char*) b
->rbuffer
)[3 + i
+ 1]);
206 peer
.bytes
[i
/2] = ((uint8_t) x
<< 4 | (uint8_t) y
);
209 if (!sd_id128_is_null(b
->server_id
) &&
210 !sd_id128_equal(b
->server_id
, peer
))
215 /* And possibly check the second line, too */
219 (f
- e
== STRLEN("\r\nAGREE_UNIX_FD")) &&
220 memcmp(e
+ 2, "AGREE_UNIX_FD",
221 STRLEN("AGREE_UNIX_FD")) == 0;
223 b
->rbuffer_size
-= (start
- (char*) b
->rbuffer
);
224 memmove(b
->rbuffer
, start
, b
->rbuffer_size
);
226 r
= bus_start_running(b
);
233 static bool line_equals(const char *s
, size_t m
, const char *line
) {
240 return memcmp(s
, line
, l
) == 0;
243 static bool line_begins(const char *s
, size_t m
, const char *word
) {
246 p
= memory_startswith(s
, m
, word
);
247 return p
&& (p
== (s
+ m
) || *p
== ' ');
250 static int verify_anonymous_token(sd_bus
*b
, const char *p
, size_t l
) {
251 _cleanup_free_
char *token
= NULL
;
255 if (!b
->anonymous_auth
)
267 r
= unhexmem(p
, l
, (void **) &token
, &len
);
271 if (memchr(token
, 0, len
))
274 return !!utf8_is_valid(token
);
277 static int verify_external_token(sd_bus
*b
, const char *p
, size_t l
) {
278 _cleanup_free_
char *token
= NULL
;
283 /* We don't do any real authentication here. Instead, we if
284 * the owner of this bus wanted authentication he should have
285 * checked SO_PEERCRED before even creating the bus object. */
287 if (!b
->anonymous_auth
&& !b
->ucred_valid
)
299 r
= unhexmem(p
, l
, (void**) &token
, &len
);
303 if (memchr(token
, 0, len
))
306 r
= parse_uid(token
, &u
);
310 /* We ignore the passed value if anonymous authentication is
312 if (!b
->anonymous_auth
&& u
!= b
->ucred
.uid
)
318 static int bus_socket_auth_write(sd_bus
*b
, const char *t
) {
325 /* We only make use of the first iovec */
326 assert(IN_SET(b
->auth_index
, 0, 1));
329 p
= malloc(b
->auth_iovec
[0].iov_len
+ l
);
333 memcpy_safe(p
, b
->auth_iovec
[0].iov_base
, b
->auth_iovec
[0].iov_len
);
334 memcpy(p
+ b
->auth_iovec
[0].iov_len
, t
, l
);
336 b
->auth_iovec
[0].iov_base
= p
;
337 b
->auth_iovec
[0].iov_len
+= l
;
339 free(b
->auth_buffer
);
345 static int bus_socket_auth_write_ok(sd_bus
*b
) {
346 char t
[3 + 32 + 2 + 1];
350 xsprintf(t
, "OK " SD_ID128_FORMAT_STR
"\r\n", SD_ID128_FORMAT_VAL(b
->server_id
));
352 return bus_socket_auth_write(b
, t
);
355 static int bus_socket_auth_verify_server(sd_bus
*b
) {
359 bool processed
= false;
364 if (b
->rbuffer_size
< 1)
367 /* First char must be a NUL byte */
368 if (*(char*) b
->rbuffer
!= 0)
371 if (b
->rbuffer_size
< 3)
374 /* Begin with the first line */
375 if (b
->auth_rbegin
<= 0)
379 /* Check if line is complete */
380 line
= (char*) b
->rbuffer
+ b
->auth_rbegin
;
381 e
= memmem(line
, b
->rbuffer_size
- b
->auth_rbegin
, "\r\n", 2);
387 if (line_begins(line
, l
, "AUTH ANONYMOUS")) {
389 r
= verify_anonymous_token(b
, line
+ 14, l
- 14);
393 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
395 b
->auth
= BUS_AUTH_ANONYMOUS
;
396 r
= bus_socket_auth_write_ok(b
);
399 } else if (line_begins(line
, l
, "AUTH EXTERNAL")) {
401 r
= verify_external_token(b
, line
+ 13, l
- 13);
405 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
407 b
->auth
= BUS_AUTH_EXTERNAL
;
408 r
= bus_socket_auth_write_ok(b
);
411 } else if (line_begins(line
, l
, "AUTH"))
412 r
= bus_socket_auth_write(b
, "REJECTED EXTERNAL ANONYMOUS\r\n");
413 else if (line_equals(line
, l
, "CANCEL") ||
414 line_begins(line
, l
, "ERROR")) {
416 b
->auth
= _BUS_AUTH_INVALID
;
417 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
419 } else if (line_equals(line
, l
, "BEGIN")) {
421 if (b
->auth
== _BUS_AUTH_INVALID
)
422 r
= bus_socket_auth_write(b
, "ERROR\r\n");
424 /* We can't leave from the auth phase
425 * before we haven't written
426 * everything queued, so let's check
429 if (bus_socket_auth_needs_write(b
))
432 b
->rbuffer_size
-= (e
+ 2 - (char*) b
->rbuffer
);
433 memmove(b
->rbuffer
, e
+ 2, b
->rbuffer_size
);
434 return bus_start_running(b
);
437 } else if (line_begins(line
, l
, "DATA")) {
439 if (b
->auth
== _BUS_AUTH_INVALID
)
440 r
= bus_socket_auth_write(b
, "ERROR\r\n");
442 if (b
->auth
== BUS_AUTH_ANONYMOUS
)
443 r
= verify_anonymous_token(b
, line
+ 4, l
- 4);
445 r
= verify_external_token(b
, line
+ 4, l
- 4);
450 b
->auth
= _BUS_AUTH_INVALID
;
451 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
453 r
= bus_socket_auth_write_ok(b
);
455 } else if (line_equals(line
, l
, "NEGOTIATE_UNIX_FD")) {
456 if (b
->auth
== _BUS_AUTH_INVALID
|| !b
->accept_fd
)
457 r
= bus_socket_auth_write(b
, "ERROR\r\n");
460 r
= bus_socket_auth_write(b
, "AGREE_UNIX_FD\r\n");
463 r
= bus_socket_auth_write(b
, "ERROR\r\n");
468 b
->auth_rbegin
= e
+ 2 - (char*) b
->rbuffer
;
474 static int bus_socket_auth_verify(sd_bus
*b
) {
478 return bus_socket_auth_verify_server(b
);
480 return bus_socket_auth_verify_client(b
);
483 static int bus_socket_read_auth(sd_bus
*b
) {
485 struct iovec iov
= {};
491 struct cmsghdr cmsghdr
;
492 uint8_t buf
[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)];
494 bool handle_cmsg
= false;
497 assert(b
->state
== BUS_AUTHENTICATING
);
499 r
= bus_socket_auth_verify(b
);
503 n
= MAX(256u, b
->rbuffer_size
* 2);
505 if (n
> BUS_AUTH_SIZE_MAX
)
506 n
= BUS_AUTH_SIZE_MAX
;
508 if (b
->rbuffer_size
>= n
)
511 p
= realloc(b
->rbuffer
, n
);
517 iov
= IOVEC_MAKE((uint8_t *)b
->rbuffer
+ b
->rbuffer_size
, n
- b
->rbuffer_size
);
520 k
= readv(b
->input_fd
, &iov
, 1);
525 mh
.msg_control
= &control
;
526 mh
.msg_controllen
= sizeof(control
);
528 k
= recvmsg(b
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
529 if (k
< 0 && errno
== ENOTSOCK
) {
530 b
->prefer_readv
= true;
531 k
= readv(b
->input_fd
, &iov
, 1);
536 return errno
== EAGAIN
? 0 : -errno
;
540 b
->rbuffer_size
+= k
;
543 struct cmsghdr
*cmsg
;
545 CMSG_FOREACH(cmsg
, &mh
)
546 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
547 cmsg
->cmsg_type
== SCM_RIGHTS
) {
550 /* Whut? We received fds during the auth
551 * protocol? Somebody is playing games with
552 * us. Close them all, and fail */
553 j
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
554 close_many((int*) CMSG_DATA(cmsg
), j
);
557 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
558 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
561 r
= bus_socket_auth_verify(b
);
568 void bus_socket_setup(sd_bus
*b
) {
571 /* Increase the buffers to 8 MB */
572 (void) fd_inc_rcvbuf(b
->input_fd
, SNDBUF_SIZE
);
573 (void) fd_inc_sndbuf(b
->output_fd
, SNDBUF_SIZE
);
575 b
->message_version
= 1;
576 b
->message_endian
= 0;
579 static void bus_get_peercred(sd_bus
*b
) {
583 assert(!b
->ucred_valid
);
585 assert(b
->n_groups
== (size_t) -1);
587 /* Get the peer for socketpair() sockets */
588 b
->ucred_valid
= getpeercred(b
->input_fd
, &b
->ucred
) >= 0;
590 /* Get the SELinux context of the peer */
591 r
= getpeersec(b
->input_fd
, &b
->label
);
592 if (r
< 0 && !IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
593 log_debug_errno(r
, "Failed to determine peer security context: %m");
595 /* Get the list of auxiliary groups of the peer */
596 r
= getpeergroups(b
->input_fd
, &b
->groups
);
598 b
->n_groups
= (size_t) r
;
599 else if (!IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
600 log_debug_errno(r
, "Failed to determine peer's group list: %m");
603 static int bus_socket_start_auth_client(sd_bus
*b
) {
605 const char *auth_suffix
, *auth_prefix
;
609 if (b
->anonymous_auth
) {
610 auth_prefix
= "\0AUTH ANONYMOUS ";
612 /* For ANONYMOUS auth we send some arbitrary "trace" string */
614 b
->auth_buffer
= hexmem("anonymous", l
);
616 char text
[DECIMAL_STR_MAX(uid_t
) + 1];
618 auth_prefix
= "\0AUTH EXTERNAL ";
620 xsprintf(text
, UID_FMT
, geteuid());
623 b
->auth_buffer
= hexmem(text
, l
);
630 auth_suffix
= "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
632 auth_suffix
= "\r\nBEGIN\r\n";
634 b
->auth_iovec
[0] = IOVEC_MAKE((void*) auth_prefix
, 1 + strlen(auth_prefix
+ 1));
635 b
->auth_iovec
[1] = IOVEC_MAKE(b
->auth_buffer
, l
* 2);
636 b
->auth_iovec
[2] = IOVEC_MAKE_STRING(auth_suffix
);
638 return bus_socket_write_auth(b
);
641 int bus_socket_start_auth(sd_bus
*b
) {
646 bus_set_state(b
, BUS_AUTHENTICATING
);
647 b
->auth_timeout
= now(CLOCK_MONOTONIC
) + BUS_AUTH_TIMEOUT
;
649 if (sd_is_socket(b
->input_fd
, AF_UNIX
, 0, 0) <= 0)
650 b
->accept_fd
= false;
652 if (b
->output_fd
!= b
->input_fd
)
653 if (sd_is_socket(b
->output_fd
, AF_UNIX
, 0, 0) <= 0)
654 b
->accept_fd
= false;
657 return bus_socket_read_auth(b
);
659 return bus_socket_start_auth_client(b
);
662 static int bus_socket_inotify_setup(sd_bus
*b
) {
663 _cleanup_free_
int *new_watches
= NULL
;
664 _cleanup_free_
char *absolute
= NULL
;
665 size_t n_allocated
= 0, n
= 0, done
= 0, i
;
666 unsigned max_follow
= 32;
671 assert(b
->watch_bind
);
672 assert(b
->sockaddr
.sa
.sa_family
== AF_UNIX
);
673 assert(b
->sockaddr
.un
.sun_path
[0] != 0);
675 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
676 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
677 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
678 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
679 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
682 if (b
->inotify_fd
< 0) {
683 b
->inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
684 if (b
->inotify_fd
< 0)
687 b
->inotify_fd
= fd_move_above_stdio(b
->inotify_fd
);
690 /* Make sure the path is NUL terminated */
691 p
= strndupa(b
->sockaddr
.un
.sun_path
, sizeof(b
->sockaddr
.un
.sun_path
));
693 /* Make sure the path is absolute */
694 r
= path_make_absolute_cwd(p
, &absolute
);
698 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
699 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
700 * they are removed or renamed. */
702 if (!GREEDY_REALLOC(new_watches
, n_allocated
, n
+ 1)) {
707 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
709 wd
= inotify_add_watch(b
->inotify_fd
, "/", IN_CREATE
|IN_MOVED_TO
);
711 r
= log_debug_errno(errno
, "Failed to add inotify watch on /: %m");
714 new_watches
[n
++] = wd
;
717 _cleanup_free_
char *component
= NULL
, *prefix
= NULL
, *destination
= NULL
;
718 size_t n_slashes
, n_component
;
721 n_slashes
= strspn(absolute
+ done
, "/");
722 n_component
= n_slashes
+ strcspn(absolute
+ done
+ n_slashes
, "/");
724 if (n_component
== 0) /* The end */
727 component
= strndup(absolute
+ done
, n_component
);
733 /* A trailing slash? That's a directory, and not a socket then */
734 if (path_equal(component
, "/")) {
739 /* A single dot? Let's eat this up */
740 if (path_equal(component
, "/.")) {
745 prefix
= strndup(absolute
, done
+ n_component
);
751 if (!GREEDY_REALLOC(new_watches
, n_allocated
, n
+ 1)) {
756 wd
= inotify_add_watch(b
->inotify_fd
, prefix
, IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CREATE
|IN_MOVED_TO
|IN_DONT_FOLLOW
);
757 log_debug("Added inotify watch for %s on bus %s: %i", prefix
, strna(b
->description
), wd
);
760 if (IN_SET(errno
, ENOENT
, ELOOP
))
761 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
763 r
= log_debug_errno(errno
, "Failed to add inotify watch on %s: %m", empty_to_root(prefix
));
766 new_watches
[n
++] = wd
;
768 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
769 r
= readlink_malloc(prefix
, &destination
);
770 if (r
== -EINVAL
) { /* not a symlink */
777 if (isempty(destination
)) { /* Empty symlink target? Yuck! */
782 if (max_follow
<= 0) { /* Let's make sure we don't follow symlinks forever */
787 if (path_is_absolute(destination
)) {
788 /* For absolute symlinks we build the new path and start anew */
789 c
= strjoin(destination
, absolute
+ done
+ n_component
);
792 _cleanup_free_
char *t
= NULL
;
794 /* For relative symlinks we replace the last component, and try again */
795 t
= strndup(absolute
, done
);
799 c
= strjoin(t
, "/", destination
, absolute
+ done
+ n_component
);
812 /* And now, let's remove all watches from the previous iteration we don't need anymore */
813 for (i
= 0; i
< b
->n_inotify_watches
; i
++) {
817 for (j
= 0; j
< n
; j
++)
818 if (new_watches
[j
] == b
->inotify_watches
[i
]) {
826 (void) inotify_rm_watch(b
->inotify_fd
, b
->inotify_watches
[i
]);
829 free_and_replace(b
->inotify_watches
, new_watches
);
830 b
->n_inotify_watches
= n
;
835 bus_close_inotify_fd(b
);
839 int bus_socket_connect(sd_bus
*b
) {
840 bool inotify_done
= false;
846 assert(b
->input_fd
< 0);
847 assert(b
->output_fd
< 0);
848 assert(b
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
);
850 b
->input_fd
= socket(b
->sockaddr
.sa
.sa_family
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
854 b
->input_fd
= fd_move_above_stdio(b
->input_fd
);
856 b
->output_fd
= b
->input_fd
;
859 if (connect(b
->input_fd
, &b
->sockaddr
.sa
, b
->sockaddr_size
) < 0) {
860 if (errno
== EINPROGRESS
) {
862 /* If we have any inotify watches open, close them now, we don't need them anymore, as
863 * we have successfully initiated a connection */
864 bus_close_inotify_fd(b
);
866 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
867 * we start parsing the address string. The only reason we set the state explicitly
868 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
869 bus_set_state(b
, BUS_OPENING
);
873 if (IN_SET(errno
, ENOENT
, ECONNREFUSED
) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
875 b
->sockaddr
.sa
.sa_family
== AF_UNIX
&&
876 b
->sockaddr
.un
.sun_path
[0] != 0) {
878 /* This connection attempt failed, let's release the socket for now, and start with a
879 * fresh one when reconnecting. */
883 /* inotify set up already, don't do it again, just return now, and remember
884 * that we are waiting for inotify events now. */
885 bus_set_state(b
, BUS_WATCH_BIND
);
889 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
890 r
= bus_socket_inotify_setup(b
);
894 /* Let's now try to connect a second time, because in theory there's otherwise a race
895 * here: the socket might have been created in the time between our first connect() and
896 * the time we set up the inotify logic. But let's remember that we set up inotify now,
897 * so that we don't do the connect() more than twice. */
906 /* Yay, established, we don't need no inotify anymore! */
907 bus_close_inotify_fd(b
);
909 return bus_socket_start_auth(b
);
912 int bus_socket_exec(sd_bus
*b
) {
916 assert(b
->input_fd
< 0);
917 assert(b
->output_fd
< 0);
918 assert(b
->exec_path
);
919 assert(b
->busexec_pid
== 0);
921 r
= socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_NONBLOCK
|SOCK_CLOEXEC
, 0, s
);
925 r
= safe_fork_full("(sd-busexec)", s
+1, 1, FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
, &b
->busexec_pid
);
933 if (rearrange_stdio(s
[1], s
[1], STDERR_FILENO
) < 0)
936 (void) rlimit_nofile_safe();
939 execvp(b
->exec_path
, b
->exec_argv
);
941 const char *argv
[] = { b
->exec_path
, NULL
};
942 execvp(b
->exec_path
, (char**) argv
);
949 b
->output_fd
= b
->input_fd
= fd_move_above_stdio(s
[0]);
953 return bus_socket_start_auth(b
);
956 int bus_socket_take_fd(sd_bus
*b
) {
961 return bus_socket_start_auth(b
);
964 int bus_socket_write_message(sd_bus
*bus
, sd_bus_message
*m
, size_t *idx
) {
974 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
976 if (*idx
>= BUS_MESSAGE_SIZE(m
))
979 r
= bus_message_setup_iovec(m
);
983 n
= m
->n_iovec
* sizeof(struct iovec
);
984 iov
= newa(struct iovec
, n
);
985 memcpy_safe(iov
, m
->iovec
, n
);
988 iovec_advance(iov
, &j
, *idx
);
990 if (bus
->prefer_writev
)
991 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
995 .msg_iovlen
= m
->n_iovec
,
998 if (m
->n_fds
> 0 && *idx
== 0) {
999 struct cmsghdr
*control
;
1001 mh
.msg_control
= control
= alloca(CMSG_SPACE(sizeof(int) * m
->n_fds
));
1002 mh
.msg_controllen
= control
->cmsg_len
= CMSG_LEN(sizeof(int) * m
->n_fds
);
1003 control
->cmsg_level
= SOL_SOCKET
;
1004 control
->cmsg_type
= SCM_RIGHTS
;
1005 memcpy(CMSG_DATA(control
), m
->fds
, sizeof(int) * m
->n_fds
);
1008 k
= sendmsg(bus
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
1009 if (k
< 0 && errno
== ENOTSOCK
) {
1010 bus
->prefer_writev
= true;
1011 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1016 return errno
== EAGAIN
? 0 : -errno
;
1022 static int bus_socket_read_message_need(sd_bus
*bus
, size_t *need
) {
1029 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1031 if (bus
->rbuffer_size
< sizeof(struct bus_header
)) {
1032 *need
= sizeof(struct bus_header
) + 8;
1034 /* Minimum message size:
1038 * Method Call: +2 string headers
1039 * Signal: +3 string headers
1040 * Method Error: +1 string headers
1042 * Method Reply: +1 uint32 headers
1044 * A string header is at least 9 bytes
1045 * A uint32 header is at least 8 bytes
1047 * Hence the minimum message size of a valid message
1048 * is header + 8 bytes */
1053 a
= ((const uint32_t*) bus
->rbuffer
)[1];
1054 b
= ((const uint32_t*) bus
->rbuffer
)[3];
1056 e
= ((const uint8_t*) bus
->rbuffer
)[0];
1057 if (e
== BUS_LITTLE_ENDIAN
) {
1060 } else if (e
== BUS_BIG_ENDIAN
) {
1066 sum
= (uint64_t) sizeof(struct bus_header
) + (uint64_t) ALIGN_TO(b
, 8) + (uint64_t) a
;
1067 if (sum
>= BUS_MESSAGE_SIZE_MAX
)
1070 *need
= (size_t) sum
;
1074 static int bus_socket_make_message(sd_bus
*bus
, size_t size
) {
1080 assert(bus
->rbuffer_size
>= size
);
1081 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1083 r
= bus_rqueue_make_room(bus
);
1087 if (bus
->rbuffer_size
> size
) {
1088 b
= memdup((const uint8_t*) bus
->rbuffer
+ size
,
1089 bus
->rbuffer_size
- size
);
1095 r
= bus_message_from_malloc(bus
,
1097 bus
->fds
, bus
->n_fds
,
1106 bus
->rbuffer_size
-= size
;
1111 bus
->rqueue
[bus
->rqueue_size
++] = t
;
1116 int bus_socket_read_message(sd_bus
*bus
) {
1118 struct iovec iov
= {};
1124 struct cmsghdr cmsghdr
;
1125 uint8_t buf
[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)];
1127 bool handle_cmsg
= false;
1130 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1132 r
= bus_socket_read_message_need(bus
, &need
);
1136 if (bus
->rbuffer_size
>= need
)
1137 return bus_socket_make_message(bus
, need
);
1139 b
= realloc(bus
->rbuffer
, need
);
1145 iov
= IOVEC_MAKE((uint8_t *)bus
->rbuffer
+ bus
->rbuffer_size
, need
- bus
->rbuffer_size
);
1147 if (bus
->prefer_readv
)
1148 k
= readv(bus
->input_fd
, &iov
, 1);
1153 mh
.msg_control
= &control
;
1154 mh
.msg_controllen
= sizeof(control
);
1156 k
= recvmsg(bus
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
1157 if (k
< 0 && errno
== ENOTSOCK
) {
1158 bus
->prefer_readv
= true;
1159 k
= readv(bus
->input_fd
, &iov
, 1);
1164 return errno
== EAGAIN
? 0 : -errno
;
1168 bus
->rbuffer_size
+= k
;
1171 struct cmsghdr
*cmsg
;
1173 CMSG_FOREACH(cmsg
, &mh
)
1174 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1175 cmsg
->cmsg_type
== SCM_RIGHTS
) {
1178 n
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1180 if (!bus
->can_fds
) {
1181 /* Whut? We received fds but this
1182 * isn't actually enabled? Close them,
1185 close_many((int*) CMSG_DATA(cmsg
), n
);
1189 f
= reallocarray(bus
->fds
, bus
->n_fds
+ n
, sizeof(int));
1191 close_many((int*) CMSG_DATA(cmsg
), n
);
1195 for (i
= 0; i
< n
; i
++)
1196 f
[bus
->n_fds
++] = fd_move_above_stdio(((int*) CMSG_DATA(cmsg
))[i
]);
1199 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1200 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
1203 r
= bus_socket_read_message_need(bus
, &need
);
1207 if (bus
->rbuffer_size
>= need
)
1208 return bus_socket_make_message(bus
, need
);
1213 int bus_socket_process_opening(sd_bus
*b
) {
1215 socklen_t slen
= sizeof(error
);
1222 assert(b
->state
== BUS_OPENING
);
1228 if (!(p
.revents
& (POLLOUT
|POLLERR
|POLLHUP
)))
1231 r
= getsockopt(b
->output_fd
, SOL_SOCKET
, SO_ERROR
, &error
, &slen
);
1233 b
->last_connect_error
= errno
;
1234 else if (error
!= 0)
1235 b
->last_connect_error
= error
;
1236 else if (p
.revents
& (POLLERR
|POLLHUP
))
1237 b
->last_connect_error
= ECONNREFUSED
;
1239 return bus_socket_start_auth(b
);
1241 return bus_next_address(b
);
1244 int bus_socket_process_authenticating(sd_bus
*b
) {
1248 assert(b
->state
== BUS_AUTHENTICATING
);
1250 if (now(CLOCK_MONOTONIC
) >= b
->auth_timeout
)
1253 r
= bus_socket_write_auth(b
);
1257 return bus_socket_read_auth(b
);
1260 int bus_socket_process_watch_bind(sd_bus
*b
) {
1264 assert(b
->state
== BUS_WATCH_BIND
);
1265 assert(b
->inotify_fd
>= 0);
1267 r
= flush_fd(b
->inotify_fd
);
1271 log_debug("Got inotify event on bus %s.", strna(b
->description
));
1273 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1276 r
= bus_socket_connect(b
);
1280 q
= bus_attach_io_events(b
);
1284 q
= bus_attach_inotify_event(b
);