]>
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"
22 #include "memory-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
25 #include "random-util.h"
26 #include "signal-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "user-util.h"
32 #define SNDBUF_SIZE (8*1024*1024)
34 static void iovec_advance(struct iovec iov
[], unsigned *idx
, size_t size
) {
37 struct iovec
*i
= iov
+ *idx
;
39 if (i
->iov_len
> size
) {
40 i
->iov_base
= (uint8_t*) i
->iov_base
+ size
;
47 *i
= IOVEC_MAKE(NULL
, 0);
53 static int append_iovec(sd_bus_message
*m
, const void *p
, size_t sz
) {
58 m
->iovec
[m
->n_iovec
++] = IOVEC_MAKE((void*) p
, sz
);
63 static int bus_message_setup_iovec(sd_bus_message
*m
) {
64 struct bus_body_part
*part
;
76 n
= 1 + m
->n_body_parts
;
77 if (n
< ELEMENTSOF(m
->iovec_fixed
))
78 m
->iovec
= m
->iovec_fixed
;
80 m
->iovec
= new(struct iovec
, n
);
87 r
= append_iovec(m
, m
->header
, BUS_MESSAGE_BODY_BEGIN(m
));
91 MESSAGE_FOREACH_PART(part
, i
, m
) {
92 r
= bus_body_part_map(part
);
96 r
= append_iovec(m
, part
->data
, part
->size
);
101 assert(n
== m
->n_iovec
);
110 bool bus_socket_auth_needs_write(sd_bus
*b
) {
114 if (b
->auth_index
>= ELEMENTSOF(b
->auth_iovec
))
117 for (i
= b
->auth_index
; i
< ELEMENTSOF(b
->auth_iovec
); i
++) {
118 struct iovec
*j
= b
->auth_iovec
+ i
;
127 static int bus_socket_auth_verify_client(sd_bus
*b
) {
128 char *l
, *lines
[4] = {};
136 * We expect up to three response lines:
137 * "DATA\r\n" (optional)
138 * "OK <server-id>\r\n"
139 * "AGREE_UNIX_FD\r\n" (optional)
143 lines
[n
] = b
->rbuffer
;
144 for (i
= 0; i
< 3; ++i
) {
145 l
= memmem_safe(lines
[n
], b
->rbuffer_size
- (lines
[n
] - (char*) b
->rbuffer
), "\r\n", 2);
153 * If we sent a non-empty initial response, then we just expect an OK
154 * reply. We currently do this if, and only if, we picked ANONYMOUS.
155 * If we did not send an initial response, then we expect a DATA
156 * challenge, reply with our own DATA, and expect an OK reply. We do
158 * If FD negotiation was requested, we additionally expect
159 * an AGREE_UNIX_FD response in all cases.
161 if (n
< (b
->anonymous_auth
? 1U : 2U) + !!b
->accept_fd
)
162 return 0; /* wait for more data */
166 /* In case of EXTERNAL, verify the first response was DATA. */
167 if (!b
->anonymous_auth
) {
169 if (lines
[i
] - l
== 4 + 2) {
170 if (memcmp(l
, "DATA", 4))
172 } else if (lines
[i
] - l
== 3 + 32 + 2) {
174 * Old versions of the server-side implementation of
175 * `sd-bus` replied with "OK <id>" to "AUTH" requests
176 * from a client, even if the "AUTH" line did not
177 * contain inlined arguments. Therefore, we also accept
178 * "OK <id>" here, even though it is technically the
179 * wrong reply. We ignore the "<id>" parameter, though,
180 * since it has no real value.
182 if (memcmp(l
, "OK ", 3))
188 /* Now check the OK line. */
191 if (lines
[i
] - l
!= 3 + 32 + 2)
193 if (memcmp(l
, "OK ", 3))
196 b
->auth
= b
->anonymous_auth
? BUS_AUTH_ANONYMOUS
: BUS_AUTH_EXTERNAL
;
198 for (unsigned j
= 0; j
< 32; j
+= 2) {
201 x
= unhexchar(l
[3 + j
]);
202 y
= unhexchar(l
[3 + j
+ 1]);
207 peer
.bytes
[j
/2] = ((uint8_t) x
<< 4 | (uint8_t) y
);
210 if (!sd_id128_is_null(b
->server_id
) &&
211 !sd_id128_equal(b
->server_id
, peer
))
216 /* And possibly check the third line, too */
219 b
->can_fds
= !!memory_startswith(l
, lines
[i
] - l
, "AGREE_UNIX_FD");
224 b
->rbuffer_size
-= (lines
[i
] - (char*) b
->rbuffer
);
225 memmove(b
->rbuffer
, lines
[i
], b
->rbuffer_size
);
227 r
= bus_start_running(b
);
234 static bool line_equals(const char *s
, size_t m
, const char *line
) {
241 return memcmp(s
, line
, l
) == 0;
244 static bool line_begins(const char *s
, size_t m
, const char *word
) {
247 p
= memory_startswith(s
, m
, word
);
248 return p
&& (p
== (s
+ m
) || *p
== ' ');
251 static int verify_anonymous_token(sd_bus
*b
, const char *p
, size_t l
) {
252 _cleanup_free_
char *token
= NULL
;
256 if (!b
->anonymous_auth
)
268 r
= unhexmem(p
, l
, (void **) &token
, &len
);
272 if (memchr(token
, 0, len
))
275 return !!utf8_is_valid(token
);
278 static int verify_external_token(sd_bus
*b
, const char *p
, size_t l
) {
279 _cleanup_free_
char *token
= NULL
;
284 /* We don't do any real authentication here. Instead, if
285 * the owner of this bus wanted authentication they should have
286 * checked SO_PEERCRED before even creating the bus object. */
288 if (!b
->anonymous_auth
&& !b
->ucred_valid
)
300 r
= unhexmem(p
, l
, (void**) &token
, &len
);
304 if (memchr(token
, 0, len
))
307 r
= parse_uid(token
, &u
);
311 /* We ignore the passed value if anonymous authentication is
313 if (!b
->anonymous_auth
&& u
!= b
->ucred
.uid
)
319 static int bus_socket_auth_write(sd_bus
*b
, const char *t
) {
326 /* We only make use of the first iovec */
327 assert(IN_SET(b
->auth_index
, 0, 1));
330 p
= malloc(b
->auth_iovec
[0].iov_len
+ l
);
334 memcpy_safe(p
, b
->auth_iovec
[0].iov_base
, b
->auth_iovec
[0].iov_len
);
335 memcpy(p
+ b
->auth_iovec
[0].iov_len
, t
, l
);
337 b
->auth_iovec
[0].iov_base
= p
;
338 b
->auth_iovec
[0].iov_len
+= l
;
340 free_and_replace(b
->auth_buffer
, p
);
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_safe(line
, b
->rbuffer_size
- b
->auth_rbegin
, "\r\n", 2);
387 if (line_begins(line
, l
, "AUTH ANONYMOUS")) {
389 r
= verify_anonymous_token(b
,
390 line
+ strlen("AUTH ANONYMOUS"),
391 l
- strlen("AUTH ANONYMOUS"));
395 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
397 b
->auth
= BUS_AUTH_ANONYMOUS
;
398 if (l
<= strlen("AUTH ANONYMOUS"))
399 r
= bus_socket_auth_write(b
, "DATA\r\n");
401 r
= bus_socket_auth_write_ok(b
);
404 } else if (line_begins(line
, l
, "AUTH EXTERNAL")) {
406 r
= verify_external_token(b
,
407 line
+ strlen("AUTH EXTERNAL"),
408 l
- strlen("AUTH EXTERNAL"));
412 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
414 b
->auth
= BUS_AUTH_EXTERNAL
;
415 if (l
<= strlen("AUTH EXTERNAL"))
416 r
= bus_socket_auth_write(b
, "DATA\r\n");
418 r
= bus_socket_auth_write_ok(b
);
421 } else if (line_begins(line
, l
, "AUTH"))
422 r
= bus_socket_auth_write(b
, "REJECTED EXTERNAL ANONYMOUS\r\n");
423 else if (line_equals(line
, l
, "CANCEL") ||
424 line_begins(line
, l
, "ERROR")) {
426 b
->auth
= _BUS_AUTH_INVALID
;
427 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
429 } else if (line_equals(line
, l
, "BEGIN")) {
431 if (b
->auth
== _BUS_AUTH_INVALID
)
432 r
= bus_socket_auth_write(b
, "ERROR\r\n");
434 /* We can't leave from the auth phase
435 * before we haven't written
436 * everything queued, so let's check
439 if (bus_socket_auth_needs_write(b
))
442 b
->rbuffer_size
-= (e
+ 2 - (char*) b
->rbuffer
);
443 memmove(b
->rbuffer
, e
+ 2, b
->rbuffer_size
);
444 return bus_start_running(b
);
447 } else if (line_begins(line
, l
, "DATA")) {
449 if (b
->auth
== _BUS_AUTH_INVALID
)
450 r
= bus_socket_auth_write(b
, "ERROR\r\n");
452 if (b
->auth
== BUS_AUTH_ANONYMOUS
)
453 r
= verify_anonymous_token(b
, line
+ 4, l
- 4);
455 r
= verify_external_token(b
, line
+ 4, l
- 4);
460 b
->auth
= _BUS_AUTH_INVALID
;
461 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
463 r
= bus_socket_auth_write_ok(b
);
465 } else if (line_equals(line
, l
, "NEGOTIATE_UNIX_FD")) {
466 if (b
->auth
== _BUS_AUTH_INVALID
|| !b
->accept_fd
)
467 r
= bus_socket_auth_write(b
, "ERROR\r\n");
470 r
= bus_socket_auth_write(b
, "AGREE_UNIX_FD\r\n");
473 r
= bus_socket_auth_write(b
, "ERROR\r\n");
478 b
->auth_rbegin
= e
+ 2 - (char*) b
->rbuffer
;
484 static int bus_socket_auth_verify(sd_bus
*b
) {
488 return bus_socket_auth_verify_server(b
);
490 return bus_socket_auth_verify_client(b
);
493 static int bus_socket_write_auth(sd_bus
*b
) {
497 assert(b
->state
== BUS_AUTHENTICATING
);
499 if (!bus_socket_auth_needs_write(b
))
502 if (b
->prefer_writev
)
503 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
506 .msg_iov
= b
->auth_iovec
+ b
->auth_index
,
507 .msg_iovlen
= ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
,
510 k
= sendmsg(b
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
511 if (k
< 0 && errno
== ENOTSOCK
) {
512 b
->prefer_writev
= true;
513 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
518 return ERRNO_IS_TRANSIENT(errno
) ? 0 : -errno
;
520 iovec_advance(b
->auth_iovec
, &b
->auth_index
, (size_t) k
);
522 /* Now crank the state machine since we might be able to make progress after writing. For example,
523 * the server only processes "BEGIN" when the write buffer is empty.
525 return bus_socket_auth_verify(b
);
528 static int bus_socket_read_auth(sd_bus
*b
) {
530 struct iovec iov
= {};
535 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
536 bool handle_cmsg
= false;
539 assert(b
->state
== BUS_AUTHENTICATING
);
541 r
= bus_socket_auth_verify(b
);
545 n
= MAX(256u, b
->rbuffer_size
* 2);
547 if (n
> BUS_AUTH_SIZE_MAX
)
548 n
= BUS_AUTH_SIZE_MAX
;
550 if (b
->rbuffer_size
>= n
)
553 p
= realloc(b
->rbuffer
, n
);
559 iov
= IOVEC_MAKE((uint8_t *)b
->rbuffer
+ b
->rbuffer_size
, n
- b
->rbuffer_size
);
561 if (b
->prefer_readv
) {
562 k
= readv(b
->input_fd
, &iov
, 1);
566 mh
= (struct msghdr
) {
569 .msg_control
= &control
,
570 .msg_controllen
= sizeof(control
),
573 k
= recvmsg_safe(b
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
574 if (k
== -ENOTSOCK
) {
575 b
->prefer_readv
= true;
576 k
= readv(b
->input_fd
, &iov
, 1);
583 if (ERRNO_IS_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: %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: %m");
655 /* Let's query the peers socket address, it might carry information such as the peer's comm or
656 * description string */
657 zero(b
->sockaddr_peer
);
658 b
->sockaddr_size_peer
= 0;
660 socklen_t l
= sizeof(b
->sockaddr_peer
) - 1; /* Leave space for a NUL */
661 if (getpeername(b
->input_fd
, &b
->sockaddr_peer
.sa
, &l
) < 0)
662 log_debug_errno(errno
, "Failed to get peer's socket address, ignoring: %m");
664 b
->sockaddr_size_peer
= l
;
667 static int bus_socket_start_auth_client(sd_bus
*b
) {
668 static const char sasl_auth_anonymous
[] = {
670 * We use an arbitrary trace-string for the ANONYMOUS authentication. It can be used by the
671 * message broker to aid debugging of clients. We fully anonymize the connection and use a
674 /* HEX a n o n y m o u s */
675 "\0AUTH ANONYMOUS 616e6f6e796d6f7573\r\n"
677 static const char sasl_auth_external
[] = {
678 "\0AUTH EXTERNAL\r\n"
681 static const char sasl_negotiate_unix_fd
[] = {
682 "NEGOTIATE_UNIX_FD\r\n"
684 static const char sasl_begin
[] = {
691 if (b
->anonymous_auth
)
692 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_anonymous
, sizeof(sasl_auth_anonymous
) - 1);
694 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_external
, sizeof(sasl_auth_external
) - 1);
697 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd
);
699 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_begin
);
701 return bus_socket_write_auth(b
);
704 int bus_socket_start_auth(sd_bus
*b
) {
709 bus_set_state(b
, BUS_AUTHENTICATING
);
710 b
->auth_timeout
= now(CLOCK_MONOTONIC
) + BUS_AUTH_TIMEOUT
;
712 if (sd_is_socket(b
->input_fd
, AF_UNIX
, 0, 0) <= 0)
713 b
->accept_fd
= false;
715 if (b
->output_fd
!= b
->input_fd
)
716 if (sd_is_socket(b
->output_fd
, AF_UNIX
, 0, 0) <= 0)
717 b
->accept_fd
= false;
720 return bus_socket_read_auth(b
);
722 return bus_socket_start_auth_client(b
);
725 static int bus_socket_inotify_setup(sd_bus
*b
) {
726 _cleanup_free_
int *new_watches
= NULL
;
727 _cleanup_free_
char *absolute
= NULL
;
728 size_t n
= 0, done
= 0, i
;
729 unsigned max_follow
= 32;
734 assert(b
->watch_bind
);
735 assert(b
->sockaddr
.sa
.sa_family
== AF_UNIX
);
736 assert(b
->sockaddr
.un
.sun_path
[0] != 0);
738 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
739 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
740 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
741 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
742 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
745 if (b
->inotify_fd
< 0) {
746 b
->inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
747 if (b
->inotify_fd
< 0)
750 b
->inotify_fd
= fd_move_above_stdio(b
->inotify_fd
);
753 /* Make sure the path is NUL terminated */
754 p
= strndupa_safe(b
->sockaddr
.un
.sun_path
,
755 sizeof(b
->sockaddr
.un
.sun_path
));
757 /* Make sure the path is absolute */
758 r
= path_make_absolute_cwd(p
, &absolute
);
762 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
763 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
764 * they are removed or renamed. */
766 if (!GREEDY_REALLOC(new_watches
, n
+ 1)) {
771 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
773 wd
= inotify_add_watch(b
->inotify_fd
, "/", IN_CREATE
|IN_MOVED_TO
);
775 r
= log_debug_errno(errno
, "Failed to add inotify watch on /: %m");
778 new_watches
[n
++] = wd
;
781 _cleanup_free_
char *component
= NULL
, *prefix
= NULL
, *destination
= NULL
;
782 size_t n_slashes
, n_component
;
785 n_slashes
= strspn(absolute
+ done
, "/");
786 n_component
= n_slashes
+ strcspn(absolute
+ done
+ n_slashes
, "/");
788 if (n_component
== 0) /* The end */
791 component
= strndup(absolute
+ done
, n_component
);
797 /* A trailing slash? That's a directory, and not a socket then */
798 if (path_equal(component
, "/")) {
803 /* A single dot? Let's eat this up */
804 if (path_equal(component
, "/.")) {
809 prefix
= strndup(absolute
, done
+ n_component
);
815 if (!GREEDY_REALLOC(new_watches
, n
+ 1)) {
820 wd
= inotify_add_watch(b
->inotify_fd
, prefix
, IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CREATE
|IN_MOVED_TO
|IN_DONT_FOLLOW
);
821 log_debug("Added inotify watch for %s on bus %s: %i", prefix
, strna(b
->description
), wd
);
824 if (IN_SET(errno
, ENOENT
, ELOOP
))
825 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
827 r
= log_debug_errno(errno
, "Failed to add inotify watch on %s: %m", empty_to_root(prefix
));
830 new_watches
[n
++] = wd
;
832 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
833 r
= readlink_malloc(prefix
, &destination
);
834 if (r
== -EINVAL
) { /* not a symlink */
841 if (isempty(destination
)) { /* Empty symlink target? Yuck! */
846 if (max_follow
<= 0) { /* Let's make sure we don't follow symlinks forever */
851 if (path_is_absolute(destination
)) {
852 /* For absolute symlinks we build the new path and start anew */
853 c
= strjoin(destination
, absolute
+ done
+ n_component
);
856 _cleanup_free_
char *t
= NULL
;
858 /* For relative symlinks we replace the last component, and try again */
859 t
= strndup(absolute
, done
);
863 c
= strjoin(t
, "/", destination
, absolute
+ done
+ n_component
);
870 free_and_replace(absolute
, c
);
875 /* And now, let's remove all watches from the previous iteration we don't need anymore */
876 for (i
= 0; i
< b
->n_inotify_watches
; i
++) {
880 for (j
= 0; j
< n
; j
++)
881 if (new_watches
[j
] == b
->inotify_watches
[i
]) {
889 (void) inotify_rm_watch(b
->inotify_fd
, b
->inotify_watches
[i
]);
892 free_and_replace(b
->inotify_watches
, new_watches
);
893 b
->n_inotify_watches
= n
;
898 bus_close_inotify_fd(b
);
902 static int bind_description(sd_bus
*b
, int fd
, int family
) {
903 _cleanup_free_
char *bind_name
= NULL
, *comm
= NULL
;
904 union sockaddr_union bsa
;
905 const char *d
= NULL
;
911 /* If this is an AF_UNIX socket, let's set our client's socket address to carry the description
912 * string for this bus connection. This is useful for debugging things, as the connection name is
913 * visible in various socket-related tools, and can even be queried by the server side. */
915 if (family
!= AF_UNIX
)
918 (void) sd_bus_get_description(b
, &d
);
920 /* Generate a recognizable source address in the abstract namespace. We'll include:
921 * - a random 64bit value (to avoid collisions)
922 * - our "comm" process name (suppressed if contains "/" to avoid parsing issues)
923 * - the description string of the bus connection. */
924 (void) get_process_comm(0, &comm
);
925 if (comm
&& strchr(comm
, '/'))
928 if (!d
&& !comm
) /* skip if we don't have either field, rely on kernel autobind instead */
931 if (asprintf(&bind_name
, "@%" PRIx64
"/bus/%s/%s", random_u64(), strempty(comm
), strempty(d
)) < 0)
934 strshorten(bind_name
, sizeof_field(struct sockaddr_un
, sun_path
));
936 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
940 if (bind(fd
, &bsa
.sa
, r
) < 0)
946 int bus_socket_connect(sd_bus
*b
) {
947 bool inotify_done
= false;
953 assert(b
->input_fd
< 0);
954 assert(b
->output_fd
< 0);
955 assert(b
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
);
958 _cleanup_free_
char *pretty
= NULL
;
959 (void) sockaddr_pretty(&b
->sockaddr
.sa
, b
->sockaddr_size
, false, true, &pretty
);
960 log_debug("sd-bus: starting bus%s%s by connecting to %s...",
961 b
->description
? " " : "", strempty(b
->description
), strnull(pretty
));
964 b
->input_fd
= socket(b
->sockaddr
.sa
.sa_family
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
968 r
= bind_description(b
, b
->input_fd
, b
->sockaddr
.sa
.sa_family
);
972 b
->input_fd
= fd_move_above_stdio(b
->input_fd
);
974 b
->output_fd
= b
->input_fd
;
977 if (connect(b
->input_fd
, &b
->sockaddr
.sa
, b
->sockaddr_size
) < 0) {
978 if (errno
== EINPROGRESS
) {
980 /* If we have any inotify watches open, close them now, we don't need them anymore, as
981 * we have successfully initiated a connection */
982 bus_close_inotify_fd(b
);
984 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
985 * we start parsing the address string. The only reason we set the state explicitly
986 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
987 bus_set_state(b
, BUS_OPENING
);
991 if (IN_SET(errno
, ENOENT
, ECONNREFUSED
) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
993 b
->sockaddr
.sa
.sa_family
== AF_UNIX
&&
994 b
->sockaddr
.un
.sun_path
[0] != 0) {
996 /* This connection attempt failed, let's release the socket for now, and start with a
997 * fresh one when reconnecting. */
1001 /* inotify set up already, don't do it again, just return now, and remember
1002 * that we are waiting for inotify events now. */
1003 bus_set_state(b
, BUS_WATCH_BIND
);
1007 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
1008 r
= bus_socket_inotify_setup(b
);
1012 /* Let's now try to connect a second time, because in theory there's otherwise a race
1013 * here: the socket might have been created in the time between our first connect() and
1014 * the time we set up the inotify logic. But let's remember that we set up inotify now,
1015 * so that we don't do the connect() more than twice. */
1016 inotify_done
= true;
1024 /* Yay, established, we don't need no inotify anymore! */
1025 bus_close_inotify_fd(b
);
1027 return bus_socket_start_auth(b
);
1030 int bus_socket_exec(sd_bus
*b
) {
1034 assert(b
->input_fd
< 0);
1035 assert(b
->output_fd
< 0);
1036 assert(b
->exec_path
);
1037 assert(b
->busexec_pid
== 0);
1039 if (DEBUG_LOGGING
) {
1040 _cleanup_free_
char *line
= NULL
;
1043 line
= quote_command_line(b
->exec_argv
, SHELL_ESCAPE_EMPTY
);
1045 log_debug("sd-bus: starting bus%s%s with %s%s",
1046 b
->description
? " " : "", strempty(b
->description
),
1047 line
?: b
->exec_path
,
1048 b
->exec_argv
&& !line
? "…" : "");
1051 r
= socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_NONBLOCK
|SOCK_CLOEXEC
, 0, s
);
1055 r
= safe_fork_full("(sd-busexec)",
1056 (int[]) { s
[1], s
[1], STDERR_FILENO
},
1058 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_REARRANGE_STDIO
|FORK_RLIMIT_NOFILE_SAFE
, &b
->busexec_pid
);
1067 execvp(b
->exec_path
, b
->exec_argv
);
1069 execvp(b
->exec_path
, STRV_MAKE(b
->exec_path
));
1071 _exit(EXIT_FAILURE
);
1075 b
->output_fd
= b
->input_fd
= fd_move_above_stdio(s
[0]);
1077 bus_socket_setup(b
);
1079 return bus_socket_start_auth(b
);
1082 int bus_socket_take_fd(sd_bus
*b
) {
1085 bus_socket_setup(b
);
1087 return bus_socket_start_auth(b
);
1090 int bus_socket_write_message(sd_bus
*bus
, sd_bus_message
*m
, size_t *idx
) {
1100 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1102 if (*idx
>= BUS_MESSAGE_SIZE(m
))
1105 r
= bus_message_setup_iovec(m
);
1109 n
= m
->n_iovec
* sizeof(struct iovec
);
1110 iov
= newa(struct iovec
, n
);
1111 memcpy_safe(iov
, m
->iovec
, n
);
1114 iovec_advance(iov
, &j
, *idx
);
1116 if (bus
->prefer_writev
)
1117 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1119 struct msghdr mh
= {
1121 .msg_iovlen
= m
->n_iovec
,
1124 if (m
->n_fds
> 0 && *idx
== 0) {
1125 struct cmsghdr
*control
;
1127 mh
.msg_controllen
= CMSG_SPACE(sizeof(int) * m
->n_fds
);
1128 mh
.msg_control
= alloca0(mh
.msg_controllen
);
1129 control
= CMSG_FIRSTHDR(&mh
);
1130 control
->cmsg_len
= CMSG_LEN(sizeof(int) * m
->n_fds
);
1131 control
->cmsg_level
= SOL_SOCKET
;
1132 control
->cmsg_type
= SCM_RIGHTS
;
1133 memcpy(CMSG_DATA(control
), m
->fds
, sizeof(int) * m
->n_fds
);
1136 k
= sendmsg(bus
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
1137 if (k
< 0 && errno
== ENOTSOCK
) {
1138 bus
->prefer_writev
= true;
1139 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1144 return ERRNO_IS_TRANSIENT(errno
) ? 0 : -errno
;
1150 static int bus_socket_read_message_need(sd_bus
*bus
, size_t *need
) {
1157 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1159 if (bus
->rbuffer_size
< sizeof(struct bus_header
)) {
1160 *need
= sizeof(struct bus_header
) + 8;
1162 /* Minimum message size:
1166 * Method Call: +2 string headers
1167 * Signal: +3 string headers
1168 * Method Error: +1 string headers
1170 * Method Reply: +1 uint32 headers
1172 * A string header is at least 9 bytes
1173 * A uint32 header is at least 8 bytes
1175 * Hence the minimum message size of a valid message
1176 * is header + 8 bytes */
1181 a
= ((const uint32_t*) bus
->rbuffer
)[1];
1182 b
= ((const uint32_t*) bus
->rbuffer
)[3];
1184 e
= ((const uint8_t*) bus
->rbuffer
)[0];
1185 if (e
== BUS_LITTLE_ENDIAN
) {
1188 } else if (e
== BUS_BIG_ENDIAN
) {
1194 sum
= (uint64_t) sizeof(struct bus_header
) + (uint64_t) ALIGN8(b
) + (uint64_t) a
;
1195 if (sum
>= BUS_MESSAGE_SIZE_MAX
)
1198 *need
= (size_t) sum
;
1202 static int bus_socket_make_message(sd_bus
*bus
, size_t size
) {
1203 sd_bus_message
*t
= NULL
;
1208 assert(bus
->rbuffer_size
>= size
);
1209 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1211 r
= bus_rqueue_make_room(bus
);
1215 if (bus
->rbuffer_size
> size
) {
1216 b
= memdup((const uint8_t*) bus
->rbuffer
+ size
,
1217 bus
->rbuffer_size
- size
);
1223 r
= bus_message_from_malloc(bus
,
1225 bus
->fds
, bus
->n_fds
,
1228 if (r
== -EBADMSG
) {
1229 log_debug_errno(r
, "Received invalid message from connection %s, dropping.", strna(bus
->description
));
1230 free(bus
->rbuffer
); /* We want to drop current rbuffer and proceed with whatever remains in b */
1236 /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
1238 bus
->rbuffer_size
-= size
;
1244 t
->read_counter
= ++bus
->read_counter
;
1245 bus
->rqueue
[bus
->rqueue_size
++] = bus_message_ref_queued(t
, bus
);
1246 sd_bus_message_unref(t
);
1252 int bus_socket_read_message(sd_bus
*bus
) {
1254 struct iovec iov
= {};
1259 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
1260 bool handle_cmsg
= false;
1263 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1265 r
= bus_socket_read_message_need(bus
, &need
);
1269 if (bus
->rbuffer_size
>= need
)
1270 return bus_socket_make_message(bus
, need
);
1272 b
= realloc(bus
->rbuffer
, need
);
1278 iov
= IOVEC_MAKE((uint8_t *)bus
->rbuffer
+ bus
->rbuffer_size
, need
- bus
->rbuffer_size
);
1280 if (bus
->prefer_readv
) {
1281 k
= readv(bus
->input_fd
, &iov
, 1);
1285 mh
= (struct msghdr
) {
1288 .msg_control
= &control
,
1289 .msg_controllen
= sizeof(control
),
1292 k
= recvmsg_safe(bus
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
1293 if (k
== -ENOTSOCK
) {
1294 bus
->prefer_readv
= true;
1295 k
= readv(bus
->input_fd
, &iov
, 1);
1302 if (ERRNO_IS_TRANSIENT(k
))
1308 cmsg_close_all(&mh
); /* On EOF we shouldn't have gotten an fd, but let's make sure */
1312 bus
->rbuffer_size
+= k
;
1315 struct cmsghdr
*cmsg
;
1317 CMSG_FOREACH(cmsg
, &mh
)
1318 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1319 cmsg
->cmsg_type
== SCM_RIGHTS
) {
1322 n
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1324 if (!bus
->can_fds
) {
1325 /* Whut? We received fds but this
1326 * isn't actually enabled? Close them,
1329 close_many(CMSG_TYPED_DATA(cmsg
, int), n
);
1333 f
= reallocarray(bus
->fds
, bus
->n_fds
+ n
, sizeof(int));
1335 close_many(CMSG_TYPED_DATA(cmsg
, int), n
);
1339 for (i
= 0; i
< n
; i
++)
1340 f
[bus
->n_fds
++] = fd_move_above_stdio(CMSG_TYPED_DATA(cmsg
, int)[i
]);
1343 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1344 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
1347 r
= bus_socket_read_message_need(bus
, &need
);
1351 if (bus
->rbuffer_size
>= need
)
1352 return bus_socket_make_message(bus
, need
);
1357 int bus_socket_process_opening(sd_bus
*b
) {
1358 int error
= 0, events
, r
;
1359 socklen_t slen
= sizeof(error
);
1361 assert(b
->state
== BUS_OPENING
);
1363 events
= fd_wait_for_event(b
->output_fd
, POLLOUT
, 0);
1365 if (ERRNO_IS_TRANSIENT(events
))
1369 if (!(events
& (POLLOUT
|POLLERR
|POLLHUP
)))
1372 r
= getsockopt(b
->output_fd
, SOL_SOCKET
, SO_ERROR
, &error
, &slen
);
1374 b
->last_connect_error
= errno
;
1375 else if (error
!= 0)
1376 b
->last_connect_error
= error
;
1377 else if (events
& (POLLERR
|POLLHUP
))
1378 b
->last_connect_error
= ECONNREFUSED
;
1380 return bus_socket_start_auth(b
);
1382 return bus_next_address(b
);
1385 int bus_socket_process_authenticating(sd_bus
*b
) {
1389 assert(b
->state
== BUS_AUTHENTICATING
);
1391 if (now(CLOCK_MONOTONIC
) >= b
->auth_timeout
)
1394 r
= bus_socket_write_auth(b
);
1398 return bus_socket_read_auth(b
);
1401 int bus_socket_process_watch_bind(sd_bus
*b
) {
1405 assert(b
->state
== BUS_WATCH_BIND
);
1406 assert(b
->inotify_fd
>= 0);
1408 r
= flush_fd(b
->inotify_fd
);
1412 log_debug("Got inotify event on bus %s.", strna(b
->description
));
1414 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1417 r
= bus_socket_connect(b
);
1421 q
= bus_attach_io_events(b
);
1425 q
= bus_attach_inotify_event(b
);