]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-bus/bus-socket.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "alloc-util.h"
12 #include "bus-internal.h"
13 #include "bus-message.h"
14 #include "bus-socket.h"
17 #include "format-util.h"
19 #include "hexdecoct.h"
21 #include "iovec-util.h"
23 #include "memory-util.h"
24 #include "path-util.h"
25 #include "process-util.h"
26 #include "random-util.h"
27 #include "signal-util.h"
28 #include "stdio-util.h"
29 #include "string-util.h"
30 #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_auth_verify_client(sd_bus
*b
) {
129 char *l
, *lines
[4] = {};
137 * We expect up to three response lines:
138 * "DATA\r\n" (optional)
139 * "OK <server-id>\r\n"
140 * "AGREE_UNIX_FD\r\n" (optional)
144 lines
[n
] = b
->rbuffer
;
145 for (i
= 0; i
< 3; ++i
) {
146 l
= memmem_safe(lines
[n
], b
->rbuffer_size
- (lines
[n
] - (char*) b
->rbuffer
), "\r\n", 2);
154 * If we sent a non-empty initial response, then we just expect an OK
155 * reply. We currently do this if, and only if, we picked ANONYMOUS.
156 * If we did not send an initial response, then we expect a DATA
157 * challenge, reply with our own DATA, and expect an OK reply. We do
159 * If FD negotiation was requested, we additionally expect
160 * an AGREE_UNIX_FD response in all cases.
162 if (n
< (b
->anonymous_auth
? 1U : 2U) + !!b
->accept_fd
)
163 return 0; /* wait for more data */
167 /* In case of EXTERNAL, verify the first response was DATA. */
168 if (!b
->anonymous_auth
) {
170 if (lines
[i
] - l
== 4 + 2) {
171 if (memcmp(l
, "DATA", 4))
173 } else if (lines
[i
] - l
== 3 + 32 + 2) {
175 * Old versions of the server-side implementation of
176 * `sd-bus` replied with "OK <id>" to "AUTH" requests
177 * from a client, even if the "AUTH" line did not
178 * contain inlined arguments. Therefore, we also accept
179 * "OK <id>" here, even though it is technically the
180 * wrong reply. We ignore the "<id>" parameter, though,
181 * since it has no real value.
183 if (memcmp(l
, "OK ", 3))
189 /* Now check the OK line. */
192 if (lines
[i
] - l
!= 3 + 32 + 2)
194 if (memcmp(l
, "OK ", 3))
197 b
->auth
= b
->anonymous_auth
? BUS_AUTH_ANONYMOUS
: BUS_AUTH_EXTERNAL
;
199 for (unsigned j
= 0; j
< 32; j
+= 2) {
202 x
= unhexchar(l
[3 + j
]);
203 y
= unhexchar(l
[3 + j
+ 1]);
208 peer
.bytes
[j
/2] = ((uint8_t) x
<< 4 | (uint8_t) y
);
211 if (!sd_id128_is_null(b
->server_id
) &&
212 !sd_id128_equal(b
->server_id
, peer
))
217 /* And possibly check the third line, too */
220 b
->can_fds
= memory_startswith(l
, lines
[i
] - l
, "AGREE_UNIX_FD");
225 b
->rbuffer_size
-= (lines
[i
] - (char*) b
->rbuffer
);
226 memmove(b
->rbuffer
, lines
[i
], b
->rbuffer_size
);
228 r
= bus_start_running(b
);
235 static bool line_equals(const char *s
, size_t m
, const char *line
) {
242 return memcmp(s
, line
, l
) == 0;
245 static bool line_begins(const char *s
, size_t m
, const char *word
) {
248 p
= memory_startswith(s
, m
, word
);
249 return p
&& (p
== (s
+ m
) || *p
== ' ');
252 static int verify_anonymous_token(sd_bus
*b
, const char *p
, size_t l
) {
253 _cleanup_free_
char *token
= NULL
;
257 if (!b
->anonymous_auth
)
269 r
= unhexmem_full(p
, l
, /* secure = */ false, (void**) &token
, &len
);
273 if (memchr(token
, 0, len
))
276 return !!utf8_is_valid(token
);
279 static int verify_external_token(sd_bus
*b
, const char *p
, size_t l
) {
280 _cleanup_free_
char *token
= NULL
;
285 /* We don't do any real authentication here. Instead, if
286 * the owner of this bus wanted authentication they should have
287 * checked SO_PEERCRED before even creating the bus object. */
289 if (!b
->anonymous_auth
&& !b
->ucred_valid
)
301 r
= unhexmem_full(p
, l
, /* secure = */ false, (void**) &token
, &len
);
305 if (memchr(token
, 0, len
))
308 r
= parse_uid(token
, &u
);
312 /* We ignore the passed value if anonymous authentication is
314 if (!b
->anonymous_auth
&& u
!= b
->ucred
.uid
)
320 static int bus_socket_auth_write(sd_bus
*b
, const char *t
) {
327 /* We only make use of the first iovec */
328 assert(IN_SET(b
->auth_index
, 0, 1));
331 p
= malloc(b
->auth_iovec
[0].iov_len
+ l
);
335 memcpy_safe(p
, b
->auth_iovec
[0].iov_base
, b
->auth_iovec
[0].iov_len
);
336 memcpy(p
+ b
->auth_iovec
[0].iov_len
, t
, l
);
338 b
->auth_iovec
[0].iov_base
= p
;
339 b
->auth_iovec
[0].iov_len
+= l
;
341 free_and_replace(b
->auth_buffer
, p
);
346 static int bus_socket_auth_write_ok(sd_bus
*b
) {
347 char t
[3 + 32 + 2 + 1];
351 xsprintf(t
, "OK " SD_ID128_FORMAT_STR
"\r\n", SD_ID128_FORMAT_VAL(b
->server_id
));
353 return bus_socket_auth_write(b
, t
);
356 static int bus_socket_auth_verify_server(sd_bus
*b
) {
360 bool processed
= false;
365 if (b
->rbuffer_size
< 1)
368 /* First char must be a NUL byte */
369 if (*(char*) b
->rbuffer
!= 0)
372 if (b
->rbuffer_size
< 3)
375 /* Begin with the first line */
376 if (b
->auth_rbegin
<= 0)
380 /* Check if line is complete */
381 line
= (char*) b
->rbuffer
+ b
->auth_rbegin
;
382 e
= memmem_safe(line
, b
->rbuffer_size
- b
->auth_rbegin
, "\r\n", 2);
388 if (line_begins(line
, l
, "AUTH ANONYMOUS")) {
390 r
= verify_anonymous_token(b
,
391 line
+ strlen("AUTH ANONYMOUS"),
392 l
- strlen("AUTH ANONYMOUS"));
396 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
398 b
->auth
= BUS_AUTH_ANONYMOUS
;
399 if (l
<= strlen("AUTH ANONYMOUS"))
400 r
= bus_socket_auth_write(b
, "DATA\r\n");
402 r
= bus_socket_auth_write_ok(b
);
405 } else if (line_begins(line
, l
, "AUTH EXTERNAL")) {
407 r
= verify_external_token(b
,
408 line
+ strlen("AUTH EXTERNAL"),
409 l
- strlen("AUTH EXTERNAL"));
413 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
415 b
->auth
= BUS_AUTH_EXTERNAL
;
416 if (l
<= strlen("AUTH EXTERNAL"))
417 r
= bus_socket_auth_write(b
, "DATA\r\n");
419 r
= bus_socket_auth_write_ok(b
);
422 } else if (line_begins(line
, l
, "AUTH"))
423 r
= bus_socket_auth_write(b
, "REJECTED EXTERNAL ANONYMOUS\r\n");
424 else if (line_equals(line
, l
, "CANCEL") ||
425 line_begins(line
, l
, "ERROR")) {
427 b
->auth
= _BUS_AUTH_INVALID
;
428 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
430 } else if (line_equals(line
, l
, "BEGIN")) {
432 if (b
->auth
== _BUS_AUTH_INVALID
)
433 r
= bus_socket_auth_write(b
, "ERROR\r\n");
435 /* We can't leave from the auth phase
436 * before we haven't written
437 * everything queued, so let's check
440 if (bus_socket_auth_needs_write(b
))
443 b
->rbuffer_size
-= (e
+ 2 - (char*) b
->rbuffer
);
444 memmove(b
->rbuffer
, e
+ 2, b
->rbuffer_size
);
445 return bus_start_running(b
);
448 } else if (line_begins(line
, l
, "DATA")) {
450 if (b
->auth
== _BUS_AUTH_INVALID
)
451 r
= bus_socket_auth_write(b
, "ERROR\r\n");
453 if (b
->auth
== BUS_AUTH_ANONYMOUS
)
454 r
= verify_anonymous_token(b
, line
+ 4, l
- 4);
456 r
= verify_external_token(b
, line
+ 4, l
- 4);
461 b
->auth
= _BUS_AUTH_INVALID
;
462 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
464 r
= bus_socket_auth_write_ok(b
);
466 } else if (line_equals(line
, l
, "NEGOTIATE_UNIX_FD")) {
467 if (b
->auth
== _BUS_AUTH_INVALID
|| !b
->accept_fd
)
468 r
= bus_socket_auth_write(b
, "ERROR\r\n");
471 r
= bus_socket_auth_write(b
, "AGREE_UNIX_FD\r\n");
474 r
= bus_socket_auth_write(b
, "ERROR\r\n");
479 b
->auth_rbegin
= e
+ 2 - (char*) b
->rbuffer
;
485 static int bus_socket_auth_verify(sd_bus
*b
) {
489 return bus_socket_auth_verify_server(b
);
491 return bus_socket_auth_verify_client(b
);
494 static int bus_socket_write_auth(sd_bus
*b
) {
498 assert(b
->state
== BUS_AUTHENTICATING
);
500 if (!bus_socket_auth_needs_write(b
))
503 if (b
->prefer_writev
)
504 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
507 .msg_iov
= b
->auth_iovec
+ b
->auth_index
,
508 .msg_iovlen
= ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
,
511 k
= sendmsg(b
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
512 if (k
< 0 && errno
== ENOTSOCK
) {
513 b
->prefer_writev
= true;
514 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
519 return ERRNO_IS_TRANSIENT(errno
) ? 0 : -errno
;
521 iovec_advance(b
->auth_iovec
, &b
->auth_index
, (size_t) k
);
523 /* Now crank the state machine since we might be able to make progress after writing. For example,
524 * the server only processes "BEGIN" when the write buffer is empty.
526 return bus_socket_auth_verify(b
);
529 static int bus_socket_read_auth(sd_bus
*b
) {
531 struct iovec iov
= {};
536 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
537 bool handle_cmsg
= false;
540 assert(b
->state
== BUS_AUTHENTICATING
);
542 r
= bus_socket_auth_verify(b
);
546 n
= MAX(256u, b
->rbuffer_size
* 2);
548 if (n
> BUS_AUTH_SIZE_MAX
)
549 n
= BUS_AUTH_SIZE_MAX
;
551 if (b
->rbuffer_size
>= n
)
554 p
= realloc(b
->rbuffer
, n
);
560 iov
= IOVEC_MAKE((uint8_t *)b
->rbuffer
+ b
->rbuffer_size
, n
- b
->rbuffer_size
);
562 if (b
->prefer_readv
) {
563 k
= readv(b
->input_fd
, &iov
, 1);
567 mh
= (struct msghdr
) {
570 .msg_control
= &control
,
571 .msg_controllen
= sizeof(control
),
574 k
= recvmsg_safe(b
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
575 if (k
== -ENOTSOCK
) {
576 b
->prefer_readv
= true;
577 k
= readv(b
->input_fd
, &iov
, 1);
583 if (ERRNO_IS_NEG_TRANSIENT(k
))
589 cmsg_close_all(&mh
); /* paranoia, we shouldn't have gotten any fds on EOF */
593 b
->rbuffer_size
+= k
;
596 struct cmsghdr
*cmsg
;
598 CMSG_FOREACH(cmsg
, &mh
)
599 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
600 cmsg
->cmsg_type
== SCM_RIGHTS
) {
603 /* Whut? We received fds during the auth
604 * protocol? Somebody is playing games with
605 * us. Close them all, and fail */
606 j
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
607 close_many(CMSG_TYPED_DATA(cmsg
, int), j
);
610 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
611 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
614 r
= bus_socket_auth_verify(b
);
621 void bus_socket_setup(sd_bus
*b
) {
624 /* Increase the buffers to 8 MB */
625 (void) fd_increase_rxbuf(b
->input_fd
, SNDBUF_SIZE
);
626 (void) fd_inc_sndbuf(b
->output_fd
, SNDBUF_SIZE
);
628 b
->message_version
= 1;
629 b
->message_endian
= 0;
632 static void bus_get_peercred(sd_bus
*b
) {
636 assert(!b
->ucred_valid
);
638 assert(b
->n_groups
== SIZE_MAX
);
640 /* Get the peer for socketpair() sockets */
641 b
->ucred_valid
= getpeercred(b
->input_fd
, &b
->ucred
) >= 0;
643 /* Get the SELinux context of the peer */
644 r
= getpeersec(b
->input_fd
, &b
->label
);
645 if (r
< 0 && !IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
646 log_debug_errno(r
, "Failed to determine peer security context, ignoring: %m");
648 /* Get the list of auxiliary groups of the peer */
649 r
= getpeergroups(b
->input_fd
, &b
->groups
);
651 b
->n_groups
= (size_t) r
;
652 else if (!IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
653 log_debug_errno(r
, "Failed to determine peer's group list, ignoring: %m");
655 r
= getpeerpidfd(b
->input_fd
);
657 log_debug_errno(r
, "Failed to determin peer pidfd, ignoring: %m");
659 close_and_replace(b
->pidfd
, r
);
661 /* Let's query the peers socket address, it might carry information such as the peer's comm or
662 * description string */
663 zero(b
->sockaddr_peer
);
664 b
->sockaddr_size_peer
= 0;
666 socklen_t l
= sizeof(b
->sockaddr_peer
) - 1; /* Leave space for a NUL */
667 if (getpeername(b
->input_fd
, &b
->sockaddr_peer
.sa
, &l
) < 0)
668 log_debug_errno(errno
, "Failed to get peer's socket address, ignoring: %m");
670 b
->sockaddr_size_peer
= l
;
673 static int bus_socket_start_auth_client(sd_bus
*b
) {
674 static const char sasl_auth_anonymous
[] = {
676 * We use an arbitrary trace-string for the ANONYMOUS authentication. It can be used by the
677 * message broker to aid debugging of clients. We fully anonymize the connection and use a
680 /* HEX a n o n y m o u s */
681 "\0AUTH ANONYMOUS 616e6f6e796d6f7573\r\n"
683 static const char sasl_auth_external
[] = {
684 "\0AUTH EXTERNAL\r\n"
687 static const char sasl_negotiate_unix_fd
[] = {
688 "NEGOTIATE_UNIX_FD\r\n"
690 static const char sasl_begin
[] = {
697 if (b
->anonymous_auth
)
698 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_anonymous
, sizeof(sasl_auth_anonymous
) - 1);
700 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_external
, sizeof(sasl_auth_external
) - 1);
703 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd
);
705 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_begin
);
707 return bus_socket_write_auth(b
);
710 int bus_socket_start_auth(sd_bus
*b
) {
715 bus_set_state(b
, BUS_AUTHENTICATING
);
716 b
->auth_timeout
= now(CLOCK_MONOTONIC
) + BUS_AUTH_TIMEOUT
;
718 if (sd_is_socket(b
->input_fd
, AF_UNIX
, 0, 0) <= 0)
719 b
->accept_fd
= false;
721 if (b
->output_fd
!= b
->input_fd
)
722 if (sd_is_socket(b
->output_fd
, AF_UNIX
, 0, 0) <= 0)
723 b
->accept_fd
= false;
726 return bus_socket_read_auth(b
);
728 return bus_socket_start_auth_client(b
);
731 static int bus_socket_inotify_setup(sd_bus
*b
) {
732 _cleanup_free_
int *new_watches
= NULL
;
733 _cleanup_free_
char *absolute
= NULL
;
734 size_t n
= 0, done
= 0, i
;
735 unsigned max_follow
= 32;
740 assert(b
->watch_bind
);
741 assert(b
->sockaddr
.sa
.sa_family
== AF_UNIX
);
742 assert(b
->sockaddr
.un
.sun_path
[0] != 0);
744 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system
745 * socket appears before connecting to it. The implemented is pretty simplistic: we just subscribe to
746 * relevant changes to all components of the path, and every time we get an event for that we try to
747 * reconnect again, without actually caring what precisely the event we got told us. If we still
748 * can't connect we re-subscribe to all relevant changes of anything in the path, so that our watches
749 * include any possibly newly created path components. */
751 if (b
->inotify_fd
< 0) {
752 b
->inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
753 if (b
->inotify_fd
< 0)
756 b
->inotify_fd
= fd_move_above_stdio(b
->inotify_fd
);
759 /* Make sure the path is NUL terminated */
760 p
= strndupa_safe(b
->sockaddr
.un
.sun_path
,
761 sizeof(b
->sockaddr
.un
.sun_path
));
763 /* Make sure the path is absolute */
764 r
= path_make_absolute_cwd(p
, &absolute
);
768 /* Watch all components of the path, and don't mind any prefix that doesn't exist yet. For the
769 * innermost directory that exists we want to know when files are created or moved into it. For all
770 * parents of it we just care if they are removed or renamed. */
772 if (!GREEDY_REALLOC(new_watches
, n
+ 1)) {
777 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a
778 * symlink, and always exists */
779 wd
= inotify_add_watch(b
->inotify_fd
, "/", IN_CREATE
|IN_MOVED_TO
);
781 r
= log_debug_errno(errno
, "Failed to add inotify watch on /: %m");
784 new_watches
[n
++] = wd
;
787 _cleanup_free_
char *component
= NULL
, *prefix
= NULL
, *destination
= NULL
;
788 size_t n_slashes
, n_component
;
791 n_slashes
= strspn(absolute
+ done
, "/");
792 n_component
= n_slashes
+ strcspn(absolute
+ done
+ n_slashes
, "/");
794 if (n_component
== 0) /* The end */
797 component
= strndup(absolute
+ done
, n_component
);
803 /* A trailing slash? That's a directory, and not a socket then */
804 if (path_equal(component
, "/")) {
809 /* A single dot? Let's eat this up */
810 if (path_equal(component
, "/.")) {
815 prefix
= strndup(absolute
, done
+ n_component
);
821 if (!GREEDY_REALLOC(new_watches
, n
+ 1)) {
826 wd
= inotify_add_watch(b
->inotify_fd
, prefix
, IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CREATE
|IN_MOVED_TO
|IN_DONT_FOLLOW
);
827 log_debug("Added inotify watch for %s on bus %s: %i", prefix
, strna(b
->description
), wd
);
830 if (IN_SET(errno
, ENOENT
, ELOOP
))
831 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
833 r
= log_debug_errno(errno
, "Failed to add inotify watch on %s: %m", empty_to_root(prefix
));
836 new_watches
[n
++] = wd
;
838 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
839 r
= readlink_malloc(prefix
, &destination
);
840 if (r
== -EINVAL
) { /* not a symlink */
847 if (isempty(destination
)) { /* Empty symlink target? Yuck! */
852 if (max_follow
<= 0) { /* Let's make sure we don't follow symlinks forever */
857 if (path_is_absolute(destination
)) {
858 /* For absolute symlinks we build the new path and start anew */
859 c
= strjoin(destination
, absolute
+ done
+ n_component
);
862 _cleanup_free_
char *t
= NULL
;
864 /* For relative symlinks we replace the last component, and try again */
865 t
= strndup(absolute
, done
);
869 c
= strjoin(t
, "/", destination
, absolute
+ done
+ n_component
);
876 free_and_replace(absolute
, c
);
881 /* And now, let's remove all watches from the previous iteration we don't need anymore */
882 for (i
= 0; i
< b
->n_inotify_watches
; i
++) {
886 for (j
= 0; j
< n
; j
++)
887 if (new_watches
[j
] == b
->inotify_watches
[i
]) {
895 (void) inotify_rm_watch(b
->inotify_fd
, b
->inotify_watches
[i
]);
898 free_and_replace(b
->inotify_watches
, new_watches
);
899 b
->n_inotify_watches
= n
;
904 bus_close_inotify_fd(b
);
908 static int bind_description(sd_bus
*b
, int fd
, int family
) {
909 _cleanup_free_
char *bind_name
= NULL
, *comm
= NULL
;
910 union sockaddr_union bsa
;
911 const char *d
= NULL
;
917 /* If this is an AF_UNIX socket, let's set our client's socket address to carry the description
918 * string for this bus connection. This is useful for debugging things, as the connection name is
919 * visible in various socket-related tools, and can even be queried by the server side. */
921 if (family
!= AF_UNIX
)
924 (void) sd_bus_get_description(b
, &d
);
926 /* Generate a recognizable source address in the abstract namespace. We'll include:
927 * - a random 64-bit value (to avoid collisions)
928 * - our "comm" process name (suppressed if contains "/" to avoid parsing issues)
929 * - the description string of the bus connection. */
930 (void) pid_get_comm(0, &comm
);
931 if (comm
&& strchr(comm
, '/'))
934 if (!d
&& !comm
) /* skip if we don't have either field, rely on kernel autobind instead */
937 if (asprintf(&bind_name
, "@%" PRIx64
"/bus/%s/%s", random_u64(), strempty(comm
), strempty(d
)) < 0)
940 strshorten(bind_name
, sizeof_field(struct sockaddr_un
, sun_path
));
942 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
946 if (bind(fd
, &bsa
.sa
, r
) < 0)
952 int bus_socket_connect(sd_bus
*b
) {
953 bool inotify_done
= false;
959 assert(b
->input_fd
< 0);
960 assert(b
->output_fd
< 0);
961 assert(b
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
);
964 _cleanup_free_
char *pretty
= NULL
;
965 (void) sockaddr_pretty(&b
->sockaddr
.sa
, b
->sockaddr_size
, false, true, &pretty
);
966 log_debug("sd-bus: starting bus%s%s by connecting to %s...",
967 b
->description
? " " : "", strempty(b
->description
), strnull(pretty
));
970 b
->input_fd
= socket(b
->sockaddr
.sa
.sa_family
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
974 r
= bind_description(b
, b
->input_fd
, b
->sockaddr
.sa
.sa_family
);
978 b
->input_fd
= fd_move_above_stdio(b
->input_fd
);
980 b
->output_fd
= b
->input_fd
;
983 if (connect(b
->input_fd
, &b
->sockaddr
.sa
, b
->sockaddr_size
) < 0) {
984 if (errno
== EINPROGRESS
) {
986 /* If we have any inotify watches open, close them now, we don't need them anymore, as
987 * we have successfully initiated a connection */
988 bus_close_inotify_fd(b
);
990 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
991 * we start parsing the address string. The only reason we set the state explicitly
992 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
993 bus_set_state(b
, BUS_OPENING
);
997 if (IN_SET(errno
, ENOENT
, ECONNREFUSED
) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
999 b
->sockaddr
.sa
.sa_family
== AF_UNIX
&&
1000 b
->sockaddr
.un
.sun_path
[0] != 0) {
1002 /* This connection attempt failed, let's release the socket for now, and start with a
1003 * fresh one when reconnecting. */
1004 bus_close_io_fds(b
);
1007 /* inotify set up already, don't do it again, just return now, and remember
1008 * that we are waiting for inotify events now. */
1009 bus_set_state(b
, BUS_WATCH_BIND
);
1013 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
1014 r
= bus_socket_inotify_setup(b
);
1018 /* Let's now try to connect a second time, because in theory there's otherwise a race
1019 * here: the socket might have been created in the time between our first connect() and
1020 * the time we set up the inotify logic. But let's remember that we set up inotify now,
1021 * so that we don't do the connect() more than twice. */
1022 inotify_done
= true;
1030 /* Yay, established, we don't need no inotify anymore! */
1031 bus_close_inotify_fd(b
);
1033 return bus_socket_start_auth(b
);
1036 int bus_socket_exec(sd_bus
*b
) {
1040 assert(b
->input_fd
< 0);
1041 assert(b
->output_fd
< 0);
1042 assert(b
->exec_path
);
1043 assert(b
->busexec_pid
== 0);
1045 if (DEBUG_LOGGING
) {
1046 _cleanup_free_
char *line
= NULL
;
1049 line
= quote_command_line(b
->exec_argv
, SHELL_ESCAPE_EMPTY
);
1051 log_debug("sd-bus: starting bus%s%s with %s%s",
1052 b
->description
? " " : "", strempty(b
->description
),
1053 line
?: b
->exec_path
,
1054 b
->exec_argv
&& !line
? "…" : "");
1057 r
= socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_NONBLOCK
|SOCK_CLOEXEC
, 0, s
);
1061 r
= safe_fork_full("(sd-busexec)",
1062 (int[]) { s
[1], s
[1], STDERR_FILENO
},
1064 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_REARRANGE_STDIO
|FORK_RLIMIT_NOFILE_SAFE
, &b
->busexec_pid
);
1073 execvp(b
->exec_path
, b
->exec_argv
);
1075 execvp(b
->exec_path
, STRV_MAKE(b
->exec_path
));
1077 _exit(EXIT_FAILURE
);
1081 b
->output_fd
= b
->input_fd
= fd_move_above_stdio(s
[0]);
1083 bus_socket_setup(b
);
1085 return bus_socket_start_auth(b
);
1088 int bus_socket_take_fd(sd_bus
*b
) {
1091 bus_socket_setup(b
);
1093 return bus_socket_start_auth(b
);
1096 int bus_socket_write_message(sd_bus
*bus
, sd_bus_message
*m
, size_t *idx
) {
1106 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1108 if (*idx
>= BUS_MESSAGE_SIZE(m
))
1111 r
= bus_message_setup_iovec(m
);
1115 n
= m
->n_iovec
* sizeof(struct iovec
);
1116 iov
= newa(struct iovec
, n
);
1117 memcpy_safe(iov
, m
->iovec
, n
);
1120 iovec_advance(iov
, &j
, *idx
);
1122 if (bus
->prefer_writev
)
1123 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1125 struct msghdr mh
= {
1127 .msg_iovlen
= m
->n_iovec
,
1130 if (m
->n_fds
> 0 && *idx
== 0) {
1131 struct cmsghdr
*control
;
1133 mh
.msg_controllen
= CMSG_SPACE(sizeof(int) * m
->n_fds
);
1134 mh
.msg_control
= alloca0(mh
.msg_controllen
);
1135 control
= CMSG_FIRSTHDR(&mh
);
1136 control
->cmsg_len
= CMSG_LEN(sizeof(int) * m
->n_fds
);
1137 control
->cmsg_level
= SOL_SOCKET
;
1138 control
->cmsg_type
= SCM_RIGHTS
;
1139 memcpy(CMSG_DATA(control
), m
->fds
, sizeof(int) * m
->n_fds
);
1142 k
= sendmsg(bus
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
1143 if (k
< 0 && errno
== ENOTSOCK
) {
1144 bus
->prefer_writev
= true;
1145 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1150 return ERRNO_IS_TRANSIENT(errno
) ? 0 : -errno
;
1156 static int bus_socket_read_message_need(sd_bus
*bus
, size_t *need
) {
1163 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1165 if (bus
->rbuffer_size
< sizeof(struct bus_header
)) {
1166 *need
= sizeof(struct bus_header
) + 8;
1168 /* Minimum message size:
1172 * Method Call: +2 string headers
1173 * Signal: +3 string headers
1174 * Method Error: +1 string headers
1176 * Method Reply: +1 uint32 headers
1178 * A string header is at least 9 bytes
1179 * A uint32 header is at least 8 bytes
1181 * Hence the minimum message size of a valid message
1182 * is header + 8 bytes */
1187 a
= ((const uint32_t*) bus
->rbuffer
)[1];
1188 b
= ((const uint32_t*) bus
->rbuffer
)[3];
1190 e
= ((const uint8_t*) bus
->rbuffer
)[0];
1191 if (e
== BUS_LITTLE_ENDIAN
) {
1194 } else if (e
== BUS_BIG_ENDIAN
) {
1200 sum
= (uint64_t) sizeof(struct bus_header
) + (uint64_t) ALIGN8(b
) + (uint64_t) a
;
1201 if (sum
>= BUS_MESSAGE_SIZE_MAX
)
1204 *need
= (size_t) sum
;
1208 static int bus_socket_make_message(sd_bus
*bus
, size_t size
) {
1209 sd_bus_message
*t
= NULL
;
1214 assert(bus
->rbuffer_size
>= size
);
1215 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1217 r
= bus_rqueue_make_room(bus
);
1221 if (bus
->rbuffer_size
> size
) {
1222 b
= memdup((const uint8_t*) bus
->rbuffer
+ size
,
1223 bus
->rbuffer_size
- size
);
1229 r
= bus_message_from_malloc(bus
,
1231 bus
->fds
, bus
->n_fds
,
1234 if (r
== -EBADMSG
) {
1235 log_debug_errno(r
, "Received invalid message from connection %s, dropping.", strna(bus
->description
));
1236 free(bus
->rbuffer
); /* We want to drop current rbuffer and proceed with whatever remains in b */
1242 /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
1244 bus
->rbuffer_size
-= size
;
1250 t
->read_counter
= ++bus
->read_counter
;
1251 bus
->rqueue
[bus
->rqueue_size
++] = bus_message_ref_queued(t
, bus
);
1252 sd_bus_message_unref(t
);
1258 int bus_socket_read_message(sd_bus
*bus
) {
1260 struct iovec iov
= {};
1265 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
1266 bool handle_cmsg
= false;
1269 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1271 r
= bus_socket_read_message_need(bus
, &need
);
1275 if (bus
->rbuffer_size
>= need
)
1276 return bus_socket_make_message(bus
, need
);
1278 b
= realloc(bus
->rbuffer
, need
);
1284 iov
= IOVEC_MAKE((uint8_t *)bus
->rbuffer
+ bus
->rbuffer_size
, need
- bus
->rbuffer_size
);
1286 if (bus
->prefer_readv
) {
1287 k
= readv(bus
->input_fd
, &iov
, 1);
1291 mh
= (struct msghdr
) {
1294 .msg_control
= &control
,
1295 .msg_controllen
= sizeof(control
),
1298 k
= recvmsg_safe(bus
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
1299 if (k
== -ENOTSOCK
) {
1300 bus
->prefer_readv
= true;
1301 k
= readv(bus
->input_fd
, &iov
, 1);
1307 if (ERRNO_IS_NEG_TRANSIENT(k
))
1313 cmsg_close_all(&mh
); /* On EOF we shouldn't have gotten an fd, but let's make sure */
1317 bus
->rbuffer_size
+= k
;
1320 struct cmsghdr
*cmsg
;
1322 CMSG_FOREACH(cmsg
, &mh
)
1323 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1324 cmsg
->cmsg_type
== SCM_RIGHTS
) {
1327 n
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1329 if (!bus
->can_fds
) {
1330 /* Whut? We received fds but this
1331 * isn't actually enabled? Close them,
1334 close_many(CMSG_TYPED_DATA(cmsg
, int), n
);
1338 f
= reallocarray(bus
->fds
, bus
->n_fds
+ n
, sizeof(int));
1340 close_many(CMSG_TYPED_DATA(cmsg
, int), n
);
1344 for (i
= 0; i
< n
; i
++)
1345 f
[bus
->n_fds
++] = fd_move_above_stdio(CMSG_TYPED_DATA(cmsg
, int)[i
]);
1348 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1349 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
1352 r
= bus_socket_read_message_need(bus
, &need
);
1356 if (bus
->rbuffer_size
>= need
)
1357 return bus_socket_make_message(bus
, need
);
1362 int bus_socket_process_opening(sd_bus
*b
) {
1363 int error
= 0, events
, r
;
1364 socklen_t slen
= sizeof(error
);
1366 assert(b
->state
== BUS_OPENING
);
1368 events
= fd_wait_for_event(b
->output_fd
, POLLOUT
, 0);
1369 if (ERRNO_IS_NEG_TRANSIENT(events
))
1373 if (!(events
& (POLLOUT
|POLLERR
|POLLHUP
)))
1376 r
= getsockopt(b
->output_fd
, SOL_SOCKET
, SO_ERROR
, &error
, &slen
);
1378 b
->last_connect_error
= errno
;
1379 else if (error
!= 0)
1380 b
->last_connect_error
= error
;
1381 else if (events
& (POLLERR
|POLLHUP
))
1382 b
->last_connect_error
= ECONNREFUSED
;
1384 return bus_socket_start_auth(b
);
1386 return bus_next_address(b
);
1389 int bus_socket_process_authenticating(sd_bus
*b
) {
1393 assert(b
->state
== BUS_AUTHENTICATING
);
1395 if (now(CLOCK_MONOTONIC
) >= b
->auth_timeout
)
1398 r
= bus_socket_write_auth(b
);
1402 return bus_socket_read_auth(b
);
1405 int bus_socket_process_watch_bind(sd_bus
*b
) {
1409 assert(b
->state
== BUS_WATCH_BIND
);
1410 assert(b
->inotify_fd
>= 0);
1412 r
= flush_fd(b
->inotify_fd
);
1416 log_debug("Got inotify event on bus %s.", strna(b
->description
));
1418 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1421 r
= bus_socket_connect(b
);
1425 q
= bus_attach_io_events(b
);
1429 q
= bus_attach_inotify_event(b
);