]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-bus/bus-socket.c
07179e070523493a507ce676e276fe38fb78cb42
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
);
506 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred
))) control
= {};
509 .msg_iov
= b
->auth_iovec
+ b
->auth_index
,
510 .msg_iovlen
= ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
,
513 if (uid_is_valid(b
->connect_as_uid
) || gid_is_valid(b
->connect_as_gid
)) {
515 /* If we shall connect under some specific UID/GID, then synthesize an
516 * SCM_CREDENTIALS record accordingly. After all we want to adopt this UID/GID both
517 * for SO_PEERCRED (where we have to fork()) and SCM_CREDENTIALS (where we can just
518 * fake it via sendmsg()) */
520 struct ucred ucred
= {
521 .pid
= getpid_cached(),
522 .uid
= uid_is_valid(b
->connect_as_uid
) ? b
->connect_as_uid
: getuid(),
523 .gid
= gid_is_valid(b
->connect_as_gid
) ? b
->connect_as_gid
: getgid(),
526 mh
.msg_control
= &control
;
527 mh
.msg_controllen
= sizeof(control
);
528 struct cmsghdr
*cmsg
= CMSG_FIRSTHDR(&mh
);
529 *cmsg
= (struct cmsghdr
) {
530 .cmsg_level
= SOL_SOCKET
,
531 .cmsg_type
= SCM_CREDENTIALS
,
532 .cmsg_len
= CMSG_LEN(sizeof(struct ucred
)),
535 memcpy(CMSG_DATA(cmsg
), &ucred
, sizeof(struct ucred
));
538 k
= sendmsg(b
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
539 if (k
< 0 && errno
== ENOTSOCK
) {
540 b
->prefer_writev
= true;
541 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
546 return ERRNO_IS_TRANSIENT(errno
) ? 0 : -errno
;
548 iovec_advance(b
->auth_iovec
, &b
->auth_index
, (size_t) k
);
550 /* Now crank the state machine since we might be able to make progress after writing. For example,
551 * the server only processes "BEGIN" when the write buffer is empty.
553 return bus_socket_auth_verify(b
);
556 static int bus_socket_read_auth(sd_bus
*b
) {
558 struct iovec iov
= {};
563 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
564 bool handle_cmsg
= false;
567 assert(b
->state
== BUS_AUTHENTICATING
);
569 r
= bus_socket_auth_verify(b
);
573 n
= MAX(256u, b
->rbuffer_size
* 2);
575 if (n
> BUS_AUTH_SIZE_MAX
)
576 n
= BUS_AUTH_SIZE_MAX
;
578 if (b
->rbuffer_size
>= n
)
581 p
= realloc(b
->rbuffer
, n
);
587 iov
= IOVEC_MAKE((uint8_t *)b
->rbuffer
+ b
->rbuffer_size
, n
- b
->rbuffer_size
);
589 if (b
->prefer_readv
) {
590 k
= readv(b
->input_fd
, &iov
, 1);
594 mh
= (struct msghdr
) {
597 .msg_control
= &control
,
598 .msg_controllen
= sizeof(control
),
601 k
= recvmsg_safe(b
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
602 if (k
== -ENOTSOCK
) {
603 b
->prefer_readv
= true;
604 k
= readv(b
->input_fd
, &iov
, 1);
610 if (ERRNO_IS_NEG_TRANSIENT(k
))
616 cmsg_close_all(&mh
); /* paranoia, we shouldn't have gotten any fds on EOF */
620 b
->rbuffer_size
+= k
;
623 struct cmsghdr
*cmsg
;
625 CMSG_FOREACH(cmsg
, &mh
)
626 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
627 cmsg
->cmsg_type
== SCM_RIGHTS
) {
630 /* Whut? We received fds during the auth
631 * protocol? Somebody is playing games with
632 * us. Close them all, and fail */
633 j
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
634 close_many(CMSG_TYPED_DATA(cmsg
, int), j
);
637 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
638 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
641 r
= bus_socket_auth_verify(b
);
648 void bus_socket_setup(sd_bus
*b
) {
651 /* Increase the buffers to 8 MB */
652 (void) fd_increase_rxbuf(b
->input_fd
, SNDBUF_SIZE
);
653 (void) fd_inc_sndbuf(b
->output_fd
, SNDBUF_SIZE
);
655 b
->message_version
= 1;
656 b
->message_endian
= 0;
659 static void bus_get_peercred(sd_bus
*b
) {
663 assert(!b
->ucred_valid
);
665 assert(b
->n_groups
== SIZE_MAX
);
667 /* Get the peer for socketpair() sockets */
668 b
->ucred_valid
= getpeercred(b
->input_fd
, &b
->ucred
) >= 0;
670 /* Get the SELinux context of the peer */
671 r
= getpeersec(b
->input_fd
, &b
->label
);
672 if (r
< 0 && !IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
673 log_debug_errno(r
, "Failed to determine peer security context, ignoring: %m");
675 /* Get the list of auxiliary groups of the peer */
676 r
= getpeergroups(b
->input_fd
, &b
->groups
);
678 b
->n_groups
= (size_t) r
;
679 else if (!IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
680 log_debug_errno(r
, "Failed to determine peer's group list, ignoring: %m");
682 r
= getpeerpidfd(b
->input_fd
);
684 log_debug_errno(r
, "Failed to determine peer pidfd, ignoring: %m");
686 close_and_replace(b
->pidfd
, r
);
688 /* Let's query the peers socket address, it might carry information such as the peer's comm or
689 * description string */
690 zero(b
->sockaddr_peer
);
691 b
->sockaddr_size_peer
= 0;
693 socklen_t l
= sizeof(b
->sockaddr_peer
) - 1; /* Leave space for a NUL */
694 if (getpeername(b
->input_fd
, &b
->sockaddr_peer
.sa
, &l
) < 0)
695 log_debug_errno(errno
, "Failed to get peer's socket address, ignoring: %m");
697 b
->sockaddr_size_peer
= l
;
700 static int bus_socket_start_auth_client(sd_bus
*b
) {
701 static const char sasl_auth_anonymous
[] = {
703 * We use an arbitrary trace-string for the ANONYMOUS authentication. It can be used by the
704 * message broker to aid debugging of clients. We fully anonymize the connection and use a
707 /* HEX a n o n y m o u s */
708 "\0AUTH ANONYMOUS 616e6f6e796d6f7573\r\n"
710 static const char sasl_auth_external
[] = {
711 "\0AUTH EXTERNAL\r\n"
714 static const char sasl_negotiate_unix_fd
[] = {
715 "NEGOTIATE_UNIX_FD\r\n"
717 static const char sasl_begin
[] = {
724 if (b
->anonymous_auth
)
725 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_anonymous
, sizeof(sasl_auth_anonymous
) - 1);
727 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_external
, sizeof(sasl_auth_external
) - 1);
730 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd
);
732 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_begin
);
734 return bus_socket_write_auth(b
);
737 int bus_socket_start_auth(sd_bus
*b
) {
742 bus_set_state(b
, BUS_AUTHENTICATING
);
743 b
->auth_timeout
= now(CLOCK_MONOTONIC
) + BUS_AUTH_TIMEOUT
;
745 if (sd_is_socket(b
->input_fd
, AF_UNIX
, 0, 0) <= 0)
746 b
->accept_fd
= false;
748 if (b
->output_fd
!= b
->input_fd
)
749 if (sd_is_socket(b
->output_fd
, AF_UNIX
, 0, 0) <= 0)
750 b
->accept_fd
= false;
753 return bus_socket_read_auth(b
);
755 return bus_socket_start_auth_client(b
);
758 static int bus_socket_inotify_setup(sd_bus
*b
) {
759 _cleanup_free_
int *new_watches
= NULL
;
760 _cleanup_free_
char *absolute
= NULL
;
761 size_t n
= 0, done
= 0, i
;
762 unsigned max_follow
= 32;
767 assert(b
->watch_bind
);
768 assert(b
->sockaddr
.sa
.sa_family
== AF_UNIX
);
769 assert(b
->sockaddr
.un
.sun_path
[0] != 0);
771 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system
772 * socket appears before connecting to it. The implemented is pretty simplistic: we just subscribe to
773 * relevant changes to all components of the path, and every time we get an event for that we try to
774 * reconnect again, without actually caring what precisely the event we got told us. If we still
775 * can't connect we re-subscribe to all relevant changes of anything in the path, so that our watches
776 * include any possibly newly created path components. */
778 if (b
->inotify_fd
< 0) {
779 b
->inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
780 if (b
->inotify_fd
< 0)
783 b
->inotify_fd
= fd_move_above_stdio(b
->inotify_fd
);
786 /* Make sure the path is NUL terminated */
787 p
= strndupa_safe(b
->sockaddr
.un
.sun_path
,
788 sizeof(b
->sockaddr
.un
.sun_path
));
790 /* Make sure the path is absolute */
791 r
= path_make_absolute_cwd(p
, &absolute
);
795 /* Watch all components of the path, and don't mind any prefix that doesn't exist yet. For the
796 * innermost directory that exists we want to know when files are created or moved into it. For all
797 * parents of it we just care if they are removed or renamed. */
799 if (!GREEDY_REALLOC(new_watches
, n
+ 1)) {
804 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a
805 * symlink, and always exists */
806 wd
= inotify_add_watch(b
->inotify_fd
, "/", IN_CREATE
|IN_MOVED_TO
);
808 r
= log_debug_errno(errno
, "Failed to add inotify watch on /: %m");
811 new_watches
[n
++] = wd
;
814 _cleanup_free_
char *component
= NULL
, *prefix
= NULL
, *destination
= NULL
;
815 size_t n_slashes
, n_component
;
818 n_slashes
= strspn(absolute
+ done
, "/");
819 n_component
= n_slashes
+ strcspn(absolute
+ done
+ n_slashes
, "/");
821 if (n_component
== 0) /* The end */
824 component
= strndup(absolute
+ done
, n_component
);
830 /* A trailing slash? That's a directory, and not a socket then */
831 if (path_equal(component
, "/")) {
836 /* A single dot? Let's eat this up */
837 if (path_equal(component
, "/.")) {
842 prefix
= strndup(absolute
, done
+ n_component
);
848 if (!GREEDY_REALLOC(new_watches
, n
+ 1)) {
853 wd
= inotify_add_watch(b
->inotify_fd
, prefix
, IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CREATE
|IN_MOVED_TO
|IN_DONT_FOLLOW
);
854 log_debug("Added inotify watch for %s on bus %s: %i", prefix
, strna(b
->description
), wd
);
857 if (IN_SET(errno
, ENOENT
, ELOOP
))
858 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
860 r
= log_debug_errno(errno
, "Failed to add inotify watch on %s: %m", empty_to_root(prefix
));
863 new_watches
[n
++] = wd
;
865 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
866 r
= readlink_malloc(prefix
, &destination
);
867 if (r
== -EINVAL
) { /* not a symlink */
874 if (isempty(destination
)) { /* Empty symlink target? Yuck! */
879 if (max_follow
<= 0) { /* Let's make sure we don't follow symlinks forever */
884 if (path_is_absolute(destination
)) {
885 /* For absolute symlinks we build the new path and start anew */
886 c
= strjoin(destination
, absolute
+ done
+ n_component
);
889 _cleanup_free_
char *t
= NULL
;
891 /* For relative symlinks we replace the last component, and try again */
892 t
= strndup(absolute
, done
);
896 c
= strjoin(t
, "/", destination
, absolute
+ done
+ n_component
);
903 free_and_replace(absolute
, c
);
908 /* And now, let's remove all watches from the previous iteration we don't need anymore */
909 for (i
= 0; i
< b
->n_inotify_watches
; i
++) {
913 for (j
= 0; j
< n
; j
++)
914 if (new_watches
[j
] == b
->inotify_watches
[i
]) {
922 (void) inotify_rm_watch(b
->inotify_fd
, b
->inotify_watches
[i
]);
925 free_and_replace(b
->inotify_watches
, new_watches
);
926 b
->n_inotify_watches
= n
;
931 bus_close_inotify_fd(b
);
935 static int bind_description(sd_bus
*b
, int fd
, int family
) {
936 _cleanup_free_
char *bind_name
= NULL
, *comm
= NULL
;
937 union sockaddr_union bsa
;
938 const char *d
= NULL
;
944 /* If this is an AF_UNIX socket, let's set our client's socket address to carry the description
945 * string for this bus connection. This is useful for debugging things, as the connection name is
946 * visible in various socket-related tools, and can even be queried by the server side. */
948 if (family
!= AF_UNIX
)
951 (void) sd_bus_get_description(b
, &d
);
953 /* Generate a recognizable source address in the abstract namespace. We'll include:
954 * - a random 64-bit value (to avoid collisions)
955 * - our "comm" process name (suppressed if contains "/" to avoid parsing issues)
956 * - the description string of the bus connection. */
957 (void) pid_get_comm(0, &comm
);
958 if (comm
&& strchr(comm
, '/'))
961 if (!d
&& !comm
) /* skip if we don't have either field, rely on kernel autobind instead */
964 if (asprintf(&bind_name
, "@%" PRIx64
"/bus/%s/%s", random_u64(), strempty(comm
), strempty(d
)) < 0)
967 strshorten(bind_name
, sizeof_field(struct sockaddr_un
, sun_path
));
969 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
973 if (bind(fd
, &bsa
.sa
, r
) < 0)
979 static int connect_as(int fd
, const struct sockaddr
*sa
, socklen_t salen
, uid_t uid
, gid_t gid
) {
980 _cleanup_(close_pairp
) int pfd
[2] = EBADF_PAIR
;
984 /* Shortcut if we are not supposed to drop privileges */
985 if (!uid_is_valid(uid
) && !gid_is_valid(gid
))
986 return RET_NERRNO(connect(fd
, sa
, salen
));
988 /* This changes identity to the specified uid/gid and issues connect() as that. This is useful to
989 * make sure SO_PEERCRED reports the selected UID/GID rather than the usual one of the caller. */
991 if (pipe2(pfd
, O_CLOEXEC
) < 0)
994 r
= safe_fork("(sd-setresuid)", FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGKILL
|FORK_WAIT
, /* ret_pid= */ NULL
);
1000 pfd
[0] = safe_close(pfd
[0]);
1002 r
= RET_NERRNO(setgroups(0, NULL
));
1006 if (gid_is_valid(gid
)) {
1007 r
= RET_NERRNO(setresgid(gid
, gid
, gid
));
1012 if (uid_is_valid(uid
)) {
1013 r
= RET_NERRNO(setresuid(uid
, uid
, uid
));
1018 r
= RET_NERRNO(connect(fd
, sa
, salen
));
1025 n
= write(pfd
[1], &r
, sizeof(r
));
1027 _exit(EXIT_FAILURE
);
1029 _exit(EXIT_SUCCESS
);
1032 n
= read(pfd
[0], &r
, sizeof(r
));
1039 int bus_socket_connect(sd_bus
*b
) {
1040 bool inotify_done
= false;
1046 assert(b
->input_fd
< 0);
1047 assert(b
->output_fd
< 0);
1048 assert(b
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
);
1050 if (DEBUG_LOGGING
) {
1051 _cleanup_free_
char *pretty
= NULL
;
1052 (void) sockaddr_pretty(&b
->sockaddr
.sa
, b
->sockaddr_size
, false, true, &pretty
);
1053 log_debug("sd-bus: starting bus%s%s by connecting to %s...",
1054 b
->description
? " " : "", strempty(b
->description
), strnull(pretty
));
1057 b
->input_fd
= socket(b
->sockaddr
.sa
.sa_family
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
1058 if (b
->input_fd
< 0)
1061 r
= bind_description(b
, b
->input_fd
, b
->sockaddr
.sa
.sa_family
);
1065 b
->input_fd
= fd_move_above_stdio(b
->input_fd
);
1067 b
->output_fd
= b
->input_fd
;
1068 bus_socket_setup(b
);
1070 r
= connect_as(b
->input_fd
, &b
->sockaddr
.sa
, b
->sockaddr_size
, b
->connect_as_uid
, b
->connect_as_gid
);
1072 if (r
== -EINPROGRESS
) {
1074 /* If we have any inotify watches open, close them now, we don't need them anymore, as
1075 * we have successfully initiated a connection */
1076 bus_close_inotify_fd(b
);
1078 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
1079 * we start parsing the address string. The only reason we set the state explicitly
1080 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
1081 bus_set_state(b
, BUS_OPENING
);
1085 if (IN_SET(r
, -ENOENT
, -ECONNREFUSED
) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
1087 b
->sockaddr
.sa
.sa_family
== AF_UNIX
&&
1088 b
->sockaddr
.un
.sun_path
[0] != 0) {
1090 /* This connection attempt failed, let's release the socket for now, and start with a
1091 * fresh one when reconnecting. */
1092 bus_close_io_fds(b
);
1095 /* inotify set up already, don't do it again, just return now, and remember
1096 * that we are waiting for inotify events now. */
1097 bus_set_state(b
, BUS_WATCH_BIND
);
1101 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
1102 r
= bus_socket_inotify_setup(b
);
1106 /* Let's now try to connect a second time, because in theory there's otherwise a race
1107 * here: the socket might have been created in the time between our first connect() and
1108 * the time we set up the inotify logic. But let's remember that we set up inotify now,
1109 * so that we don't do the connect() more than twice. */
1110 inotify_done
= true;
1118 /* Yay, established, we don't need no inotify anymore! */
1119 bus_close_inotify_fd(b
);
1121 return bus_socket_start_auth(b
);
1124 int bus_socket_exec(sd_bus
*b
) {
1128 assert(b
->input_fd
< 0);
1129 assert(b
->output_fd
< 0);
1130 assert(b
->exec_path
);
1131 assert(b
->busexec_pid
== 0);
1133 if (DEBUG_LOGGING
) {
1134 _cleanup_free_
char *line
= NULL
;
1137 line
= quote_command_line(b
->exec_argv
, SHELL_ESCAPE_EMPTY
);
1139 log_debug("sd-bus: starting bus%s%s with %s%s",
1140 b
->description
? " " : "", strempty(b
->description
),
1141 line
?: b
->exec_path
,
1142 b
->exec_argv
&& !line
? "…" : "");
1145 r
= socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_NONBLOCK
|SOCK_CLOEXEC
, 0, s
);
1149 r
= safe_fork_full("(sd-busexec)",
1150 (int[]) { s
[1], s
[1], STDERR_FILENO
},
1152 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_REARRANGE_STDIO
|FORK_RLIMIT_NOFILE_SAFE
, &b
->busexec_pid
);
1161 execvp(b
->exec_path
, b
->exec_argv
);
1163 execvp(b
->exec_path
, STRV_MAKE(b
->exec_path
));
1165 _exit(EXIT_FAILURE
);
1169 b
->output_fd
= b
->input_fd
= fd_move_above_stdio(s
[0]);
1171 bus_socket_setup(b
);
1173 return bus_socket_start_auth(b
);
1176 int bus_socket_take_fd(sd_bus
*b
) {
1179 bus_socket_setup(b
);
1181 return bus_socket_start_auth(b
);
1184 int bus_socket_write_message(sd_bus
*bus
, sd_bus_message
*m
, size_t *idx
) {
1194 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1196 if (*idx
>= BUS_MESSAGE_SIZE(m
))
1199 r
= bus_message_setup_iovec(m
);
1203 n
= m
->n_iovec
* sizeof(struct iovec
);
1204 iov
= newa(struct iovec
, n
);
1205 memcpy_safe(iov
, m
->iovec
, n
);
1208 iovec_advance(iov
, &j
, *idx
);
1210 if (bus
->prefer_writev
)
1211 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1213 struct msghdr mh
= {
1215 .msg_iovlen
= m
->n_iovec
,
1218 if (m
->n_fds
> 0 && *idx
== 0) {
1219 struct cmsghdr
*control
;
1221 mh
.msg_controllen
= CMSG_SPACE(sizeof(int) * m
->n_fds
);
1222 mh
.msg_control
= alloca0(mh
.msg_controllen
);
1223 control
= CMSG_FIRSTHDR(&mh
);
1224 control
->cmsg_len
= CMSG_LEN(sizeof(int) * m
->n_fds
);
1225 control
->cmsg_level
= SOL_SOCKET
;
1226 control
->cmsg_type
= SCM_RIGHTS
;
1227 memcpy(CMSG_DATA(control
), m
->fds
, sizeof(int) * m
->n_fds
);
1230 k
= sendmsg(bus
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
1231 if (k
< 0 && errno
== ENOTSOCK
) {
1232 bus
->prefer_writev
= true;
1233 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1238 return ERRNO_IS_TRANSIENT(errno
) ? 0 : -errno
;
1244 static int bus_socket_read_message_need(sd_bus
*bus
, size_t *need
) {
1251 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1253 if (bus
->rbuffer_size
< sizeof(struct bus_header
)) {
1254 *need
= sizeof(struct bus_header
) + 8;
1256 /* Minimum message size:
1260 * Method Call: +2 string headers
1261 * Signal: +3 string headers
1262 * Method Error: +1 string headers
1264 * Method Reply: +1 uint32 headers
1266 * A string header is at least 9 bytes
1267 * A uint32 header is at least 8 bytes
1269 * Hence the minimum message size of a valid message
1270 * is header + 8 bytes */
1275 a
= ((const uint32_t*) bus
->rbuffer
)[1];
1276 b
= ((const uint32_t*) bus
->rbuffer
)[3];
1278 e
= ((const uint8_t*) bus
->rbuffer
)[0];
1279 if (e
== BUS_LITTLE_ENDIAN
) {
1282 } else if (e
== BUS_BIG_ENDIAN
) {
1288 sum
= (uint64_t) sizeof(struct bus_header
) + (uint64_t) ALIGN8(b
) + (uint64_t) a
;
1289 if (sum
>= BUS_MESSAGE_SIZE_MAX
)
1292 *need
= (size_t) sum
;
1296 static int bus_socket_make_message(sd_bus
*bus
, size_t size
) {
1297 sd_bus_message
*t
= NULL
;
1302 assert(bus
->rbuffer_size
>= size
);
1303 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1305 r
= bus_rqueue_make_room(bus
);
1309 if (bus
->rbuffer_size
> size
) {
1310 b
= memdup((const uint8_t*) bus
->rbuffer
+ size
,
1311 bus
->rbuffer_size
- size
);
1317 r
= bus_message_from_malloc(bus
,
1319 bus
->fds
, bus
->n_fds
,
1322 if (r
== -EBADMSG
) {
1323 log_debug_errno(r
, "Received invalid message from connection %s, dropping.", strna(bus
->description
));
1324 free(bus
->rbuffer
); /* We want to drop current rbuffer and proceed with whatever remains in b */
1330 /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
1332 bus
->rbuffer_size
-= size
;
1338 t
->read_counter
= ++bus
->read_counter
;
1339 bus
->rqueue
[bus
->rqueue_size
++] = bus_message_ref_queued(t
, bus
);
1340 sd_bus_message_unref(t
);
1346 int bus_socket_read_message(sd_bus
*bus
) {
1348 struct iovec iov
= {};
1353 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
1354 bool handle_cmsg
= false;
1357 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1359 r
= bus_socket_read_message_need(bus
, &need
);
1363 if (bus
->rbuffer_size
>= need
)
1364 return bus_socket_make_message(bus
, need
);
1366 b
= realloc(bus
->rbuffer
, need
);
1372 iov
= IOVEC_MAKE((uint8_t *)bus
->rbuffer
+ bus
->rbuffer_size
, need
- bus
->rbuffer_size
);
1374 if (bus
->prefer_readv
) {
1375 k
= readv(bus
->input_fd
, &iov
, 1);
1379 mh
= (struct msghdr
) {
1382 .msg_control
= &control
,
1383 .msg_controllen
= sizeof(control
),
1386 k
= recvmsg_safe(bus
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
1387 if (k
== -ENOTSOCK
) {
1388 bus
->prefer_readv
= true;
1389 k
= readv(bus
->input_fd
, &iov
, 1);
1395 if (ERRNO_IS_NEG_TRANSIENT(k
))
1401 cmsg_close_all(&mh
); /* On EOF we shouldn't have gotten an fd, but let's make sure */
1405 bus
->rbuffer_size
+= k
;
1408 struct cmsghdr
*cmsg
;
1410 CMSG_FOREACH(cmsg
, &mh
)
1411 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1412 cmsg
->cmsg_type
== SCM_RIGHTS
) {
1415 n
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1417 if (!bus
->can_fds
) {
1418 /* Whut? We received fds but this
1419 * isn't actually enabled? Close them,
1422 close_many(CMSG_TYPED_DATA(cmsg
, int), n
);
1426 f
= reallocarray(bus
->fds
, bus
->n_fds
+ n
, sizeof(int));
1428 close_many(CMSG_TYPED_DATA(cmsg
, int), n
);
1432 for (i
= 0; i
< n
; i
++)
1433 f
[bus
->n_fds
++] = fd_move_above_stdio(CMSG_TYPED_DATA(cmsg
, int)[i
]);
1436 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1437 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
1440 r
= bus_socket_read_message_need(bus
, &need
);
1444 if (bus
->rbuffer_size
>= need
)
1445 return bus_socket_make_message(bus
, need
);
1450 int bus_socket_process_opening(sd_bus
*b
) {
1451 int error
= 0, events
, r
;
1452 socklen_t slen
= sizeof(error
);
1454 assert(b
->state
== BUS_OPENING
);
1456 events
= fd_wait_for_event(b
->output_fd
, POLLOUT
, 0);
1457 if (ERRNO_IS_NEG_TRANSIENT(events
))
1461 if (!(events
& (POLLOUT
|POLLERR
|POLLHUP
)))
1464 r
= getsockopt(b
->output_fd
, SOL_SOCKET
, SO_ERROR
, &error
, &slen
);
1466 b
->last_connect_error
= errno
;
1467 else if (error
!= 0)
1468 b
->last_connect_error
= error
;
1469 else if (events
& (POLLERR
|POLLHUP
))
1470 b
->last_connect_error
= ECONNREFUSED
;
1472 return bus_socket_start_auth(b
);
1474 return bus_next_address(b
);
1477 int bus_socket_process_authenticating(sd_bus
*b
) {
1481 assert(b
->state
== BUS_AUTHENTICATING
);
1483 if (now(CLOCK_MONOTONIC
) >= b
->auth_timeout
)
1486 r
= bus_socket_write_auth(b
);
1490 return bus_socket_read_auth(b
);
1493 int bus_socket_process_watch_bind(sd_bus
*b
) {
1497 assert(b
->state
== BUS_WATCH_BIND
);
1498 assert(b
->inotify_fd
>= 0);
1500 r
= flush_fd(b
->inotify_fd
);
1504 log_debug("Got inotify event on bus %s.", strna(b
->description
));
1506 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1509 r
= bus_socket_connect(b
);
1513 q
= bus_attach_io_events(b
);
1517 q
= bus_attach_inotify_event(b
);