]>
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"
21 #include "memory-util.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"
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_write_auth(sd_bus
*b
) {
131 assert(b
->state
== BUS_AUTHENTICATING
);
133 if (!bus_socket_auth_needs_write(b
))
136 if (b
->prefer_writev
)
137 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
140 .msg_iov
= b
->auth_iovec
+ b
->auth_index
,
141 .msg_iovlen
= ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
,
144 k
= sendmsg(b
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
145 if (k
< 0 && errno
== ENOTSOCK
) {
146 b
->prefer_writev
= true;
147 k
= writev(b
->output_fd
, b
->auth_iovec
+ b
->auth_index
, ELEMENTSOF(b
->auth_iovec
) - b
->auth_index
);
152 return errno
== EAGAIN
? 0 : -errno
;
154 iovec_advance(b
->auth_iovec
, &b
->auth_index
, (size_t) k
);
158 static int bus_socket_auth_verify_client(sd_bus
*b
) {
159 char *d
, *e
, *f
, *start
;
166 * We expect three response lines:
168 * "OK <server-id>\r\n"
169 * "AGREE_UNIX_FD\r\n" (optional)
172 d
= memmem_safe(b
->rbuffer
, b
->rbuffer_size
, "\r\n", 2);
176 e
= memmem(d
+ 2, b
->rbuffer_size
- (d
- (char*) b
->rbuffer
) - 2, "\r\n", 2);
181 f
= memmem(e
+ 2, b
->rbuffer_size
- (e
- (char*) b
->rbuffer
) - 2, "\r\n", 2);
191 /* Nice! We got all the lines we need. First check the DATA line. */
193 if (d
- (char*) b
->rbuffer
== 4) {
194 if (memcmp(b
->rbuffer
, "DATA", 4))
196 } else if (d
- (char*) b
->rbuffer
== 3 + 32) {
198 * Old versions of the server-side implementation of `sd-bus` replied with "OK <id>" to
199 * "AUTH" requests from a client, even if the "AUTH" line did not contain inlined
200 * arguments. Therefore, we also accept "OK <id>" here, even though it is technically the
201 * wrong reply. We ignore the "<id>" parameter, though, since it has no real value.
203 if (memcmp(b
->rbuffer
, "OK ", 3))
208 /* Now check the OK line. */
210 if (e
- d
!= 2 + 3 + 32)
213 if (memcmp(d
+ 2, "OK ", 3))
216 b
->auth
= b
->anonymous_auth
? BUS_AUTH_ANONYMOUS
: BUS_AUTH_EXTERNAL
;
218 for (unsigned i
= 0; i
< 32; i
+= 2) {
221 x
= unhexchar(d
[2 + 3 + i
]);
222 y
= unhexchar(d
[2 + 3 + i
+ 1]);
227 peer
.bytes
[i
/2] = ((uint8_t) x
<< 4 | (uint8_t) y
);
230 if (!sd_id128_is_null(b
->server_id
) &&
231 !sd_id128_equal(b
->server_id
, peer
))
236 /* And possibly check the third line, too */
240 (f
- e
== STRLEN("\r\nAGREE_UNIX_FD")) &&
241 memcmp(e
+ 2, "AGREE_UNIX_FD",
242 STRLEN("AGREE_UNIX_FD")) == 0;
244 b
->rbuffer_size
-= (start
- (char*) b
->rbuffer
);
245 memmove(b
->rbuffer
, start
, b
->rbuffer_size
);
247 r
= bus_start_running(b
);
254 static bool line_equals(const char *s
, size_t m
, const char *line
) {
261 return memcmp(s
, line
, l
) == 0;
264 static bool line_begins(const char *s
, size_t m
, const char *word
) {
267 p
= memory_startswith(s
, m
, word
);
268 return p
&& (p
== (s
+ m
) || *p
== ' ');
271 static int verify_anonymous_token(sd_bus
*b
, const char *p
, size_t l
) {
272 _cleanup_free_
char *token
= NULL
;
276 if (!b
->anonymous_auth
)
288 r
= unhexmem(p
, l
, (void **) &token
, &len
);
292 if (memchr(token
, 0, len
))
295 return !!utf8_is_valid(token
);
298 static int verify_external_token(sd_bus
*b
, const char *p
, size_t l
) {
299 _cleanup_free_
char *token
= NULL
;
304 /* We don't do any real authentication here. Instead, we if
305 * the owner of this bus wanted authentication he should have
306 * checked SO_PEERCRED before even creating the bus object. */
308 if (!b
->anonymous_auth
&& !b
->ucred_valid
)
320 r
= unhexmem(p
, l
, (void**) &token
, &len
);
324 if (memchr(token
, 0, len
))
327 r
= parse_uid(token
, &u
);
331 /* We ignore the passed value if anonymous authentication is
333 if (!b
->anonymous_auth
&& u
!= b
->ucred
.uid
)
339 static int bus_socket_auth_write(sd_bus
*b
, const char *t
) {
346 /* We only make use of the first iovec */
347 assert(IN_SET(b
->auth_index
, 0, 1));
350 p
= malloc(b
->auth_iovec
[0].iov_len
+ l
);
354 memcpy_safe(p
, b
->auth_iovec
[0].iov_base
, b
->auth_iovec
[0].iov_len
);
355 memcpy(p
+ b
->auth_iovec
[0].iov_len
, t
, l
);
357 b
->auth_iovec
[0].iov_base
= p
;
358 b
->auth_iovec
[0].iov_len
+= l
;
360 free(b
->auth_buffer
);
366 static int bus_socket_auth_write_ok(sd_bus
*b
) {
367 char t
[3 + 32 + 2 + 1];
371 xsprintf(t
, "OK " SD_ID128_FORMAT_STR
"\r\n", SD_ID128_FORMAT_VAL(b
->server_id
));
373 return bus_socket_auth_write(b
, t
);
376 static int bus_socket_auth_verify_server(sd_bus
*b
) {
380 bool processed
= false;
385 if (b
->rbuffer_size
< 1)
388 /* First char must be a NUL byte */
389 if (*(char*) b
->rbuffer
!= 0)
392 if (b
->rbuffer_size
< 3)
395 /* Begin with the first line */
396 if (b
->auth_rbegin
<= 0)
400 /* Check if line is complete */
401 line
= (char*) b
->rbuffer
+ b
->auth_rbegin
;
402 e
= memmem(line
, b
->rbuffer_size
- b
->auth_rbegin
, "\r\n", 2);
408 if (line_begins(line
, l
, "AUTH ANONYMOUS")) {
410 r
= verify_anonymous_token(b
,
411 line
+ strlen("AUTH ANONYMOUS"),
412 l
- strlen("AUTH ANONYMOUS"));
416 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
418 b
->auth
= BUS_AUTH_ANONYMOUS
;
419 if (l
<= strlen("AUTH ANONYMOUS"))
420 r
= bus_socket_auth_write(b
, "DATA\r\n");
422 r
= bus_socket_auth_write_ok(b
);
425 } else if (line_begins(line
, l
, "AUTH EXTERNAL")) {
427 r
= verify_external_token(b
,
428 line
+ strlen("AUTH EXTERNAL"),
429 l
- strlen("AUTH EXTERNAL"));
433 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
435 b
->auth
= BUS_AUTH_EXTERNAL
;
436 if (l
<= strlen("AUTH EXTERNAL"))
437 r
= bus_socket_auth_write(b
, "DATA\r\n");
439 r
= bus_socket_auth_write_ok(b
);
442 } else if (line_begins(line
, l
, "AUTH"))
443 r
= bus_socket_auth_write(b
, "REJECTED EXTERNAL ANONYMOUS\r\n");
444 else if (line_equals(line
, l
, "CANCEL") ||
445 line_begins(line
, l
, "ERROR")) {
447 b
->auth
= _BUS_AUTH_INVALID
;
448 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
450 } else if (line_equals(line
, l
, "BEGIN")) {
452 if (b
->auth
== _BUS_AUTH_INVALID
)
453 r
= bus_socket_auth_write(b
, "ERROR\r\n");
455 /* We can't leave from the auth phase
456 * before we haven't written
457 * everything queued, so let's check
460 if (bus_socket_auth_needs_write(b
))
463 b
->rbuffer_size
-= (e
+ 2 - (char*) b
->rbuffer
);
464 memmove(b
->rbuffer
, e
+ 2, b
->rbuffer_size
);
465 return bus_start_running(b
);
468 } else if (line_begins(line
, l
, "DATA")) {
470 if (b
->auth
== _BUS_AUTH_INVALID
)
471 r
= bus_socket_auth_write(b
, "ERROR\r\n");
473 if (b
->auth
== BUS_AUTH_ANONYMOUS
)
474 r
= verify_anonymous_token(b
, line
+ 4, l
- 4);
476 r
= verify_external_token(b
, line
+ 4, l
- 4);
481 b
->auth
= _BUS_AUTH_INVALID
;
482 r
= bus_socket_auth_write(b
, "REJECTED\r\n");
484 r
= bus_socket_auth_write_ok(b
);
486 } else if (line_equals(line
, l
, "NEGOTIATE_UNIX_FD")) {
487 if (b
->auth
== _BUS_AUTH_INVALID
|| !b
->accept_fd
)
488 r
= bus_socket_auth_write(b
, "ERROR\r\n");
491 r
= bus_socket_auth_write(b
, "AGREE_UNIX_FD\r\n");
494 r
= bus_socket_auth_write(b
, "ERROR\r\n");
499 b
->auth_rbegin
= e
+ 2 - (char*) b
->rbuffer
;
505 static int bus_socket_auth_verify(sd_bus
*b
) {
509 return bus_socket_auth_verify_server(b
);
511 return bus_socket_auth_verify_client(b
);
514 static int bus_socket_read_auth(sd_bus
*b
) {
516 struct iovec iov
= {};
521 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
522 bool handle_cmsg
= false;
525 assert(b
->state
== BUS_AUTHENTICATING
);
527 r
= bus_socket_auth_verify(b
);
531 n
= MAX(256u, b
->rbuffer_size
* 2);
533 if (n
> BUS_AUTH_SIZE_MAX
)
534 n
= BUS_AUTH_SIZE_MAX
;
536 if (b
->rbuffer_size
>= n
)
539 p
= realloc(b
->rbuffer
, n
);
545 iov
= IOVEC_MAKE((uint8_t *)b
->rbuffer
+ b
->rbuffer_size
, n
- b
->rbuffer_size
);
547 if (b
->prefer_readv
) {
548 k
= readv(b
->input_fd
, &iov
, 1);
552 mh
= (struct msghdr
) {
555 .msg_control
= &control
,
556 .msg_controllen
= sizeof(control
),
559 k
= recvmsg_safe(b
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
560 if (k
== -ENOTSOCK
) {
561 b
->prefer_readv
= true;
562 k
= readv(b
->input_fd
, &iov
, 1);
574 cmsg_close_all(&mh
); /* paranoia, we shouldn't have gotten any fds on EOF */
578 b
->rbuffer_size
+= k
;
581 struct cmsghdr
*cmsg
;
583 CMSG_FOREACH(cmsg
, &mh
)
584 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
585 cmsg
->cmsg_type
== SCM_RIGHTS
) {
588 /* Whut? We received fds during the auth
589 * protocol? Somebody is playing games with
590 * us. Close them all, and fail */
591 j
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
592 close_many((int*) CMSG_DATA(cmsg
), j
);
595 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
596 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
599 r
= bus_socket_auth_verify(b
);
606 void bus_socket_setup(sd_bus
*b
) {
609 /* Increase the buffers to 8 MB */
610 (void) fd_inc_rcvbuf(b
->input_fd
, SNDBUF_SIZE
);
611 (void) fd_inc_sndbuf(b
->output_fd
, SNDBUF_SIZE
);
613 b
->message_version
= 1;
614 b
->message_endian
= 0;
617 static void bus_get_peercred(sd_bus
*b
) {
621 assert(!b
->ucred_valid
);
623 assert(b
->n_groups
== (size_t) -1);
625 /* Get the peer for socketpair() sockets */
626 b
->ucred_valid
= getpeercred(b
->input_fd
, &b
->ucred
) >= 0;
628 /* Get the SELinux context of the peer */
629 r
= getpeersec(b
->input_fd
, &b
->label
);
630 if (r
< 0 && !IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
631 log_debug_errno(r
, "Failed to determine peer security context: %m");
633 /* Get the list of auxiliary groups of the peer */
634 r
= getpeergroups(b
->input_fd
, &b
->groups
);
636 b
->n_groups
= (size_t) r
;
637 else if (!IN_SET(r
, -EOPNOTSUPP
, -ENOPROTOOPT
))
638 log_debug_errno(r
, "Failed to determine peer's group list: %m");
641 static int bus_socket_start_auth_client(sd_bus
*b
) {
642 static const char sasl_auth_anonymous
[] = {
644 * We use an arbitrary trace-string for the ANONYMOUS authentication. It can be used by the
645 * message broker to aid debugging of clients. We fully anonymize the connection and use a
648 "\0AUTH ANONYMOUS\r\n"
649 /* HEX a n o n y m o u s */
650 "DATA 616e6f6e796d6f7573\r\n"
652 static const char sasl_auth_external
[] = {
653 "\0AUTH EXTERNAL\r\n"
656 static const char sasl_negotiate_unix_fd
[] = {
657 "NEGOTIATE_UNIX_FD\r\n"
659 static const char sasl_begin
[] = {
666 if (b
->anonymous_auth
)
667 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_anonymous
, sizeof(sasl_auth_anonymous
) - 1);
669 b
->auth_iovec
[i
++] = IOVEC_MAKE((char*) sasl_auth_external
, sizeof(sasl_auth_external
) - 1);
672 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd
);
674 b
->auth_iovec
[i
++] = IOVEC_MAKE_STRING(sasl_begin
);
676 return bus_socket_write_auth(b
);
679 int bus_socket_start_auth(sd_bus
*b
) {
684 bus_set_state(b
, BUS_AUTHENTICATING
);
685 b
->auth_timeout
= now(CLOCK_MONOTONIC
) + BUS_AUTH_TIMEOUT
;
687 if (sd_is_socket(b
->input_fd
, AF_UNIX
, 0, 0) <= 0)
688 b
->accept_fd
= false;
690 if (b
->output_fd
!= b
->input_fd
)
691 if (sd_is_socket(b
->output_fd
, AF_UNIX
, 0, 0) <= 0)
692 b
->accept_fd
= false;
695 return bus_socket_read_auth(b
);
697 return bus_socket_start_auth_client(b
);
700 static int bus_socket_inotify_setup(sd_bus
*b
) {
701 _cleanup_free_
int *new_watches
= NULL
;
702 _cleanup_free_
char *absolute
= NULL
;
703 size_t n_allocated
= 0, n
= 0, done
= 0, i
;
704 unsigned max_follow
= 32;
709 assert(b
->watch_bind
);
710 assert(b
->sockaddr
.sa
.sa_family
== AF_UNIX
);
711 assert(b
->sockaddr
.un
.sun_path
[0] != 0);
713 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
714 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
715 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
716 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
717 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
720 if (b
->inotify_fd
< 0) {
721 b
->inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
722 if (b
->inotify_fd
< 0)
725 b
->inotify_fd
= fd_move_above_stdio(b
->inotify_fd
);
728 /* Make sure the path is NUL terminated */
729 p
= strndupa(b
->sockaddr
.un
.sun_path
, sizeof(b
->sockaddr
.un
.sun_path
));
731 /* Make sure the path is absolute */
732 r
= path_make_absolute_cwd(p
, &absolute
);
736 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
737 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
738 * they are removed or renamed. */
740 if (!GREEDY_REALLOC(new_watches
, n_allocated
, n
+ 1)) {
745 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
747 wd
= inotify_add_watch(b
->inotify_fd
, "/", IN_CREATE
|IN_MOVED_TO
);
749 r
= log_debug_errno(errno
, "Failed to add inotify watch on /: %m");
752 new_watches
[n
++] = wd
;
755 _cleanup_free_
char *component
= NULL
, *prefix
= NULL
, *destination
= NULL
;
756 size_t n_slashes
, n_component
;
759 n_slashes
= strspn(absolute
+ done
, "/");
760 n_component
= n_slashes
+ strcspn(absolute
+ done
+ n_slashes
, "/");
762 if (n_component
== 0) /* The end */
765 component
= strndup(absolute
+ done
, n_component
);
771 /* A trailing slash? That's a directory, and not a socket then */
772 if (path_equal(component
, "/")) {
777 /* A single dot? Let's eat this up */
778 if (path_equal(component
, "/.")) {
783 prefix
= strndup(absolute
, done
+ n_component
);
789 if (!GREEDY_REALLOC(new_watches
, n_allocated
, n
+ 1)) {
794 wd
= inotify_add_watch(b
->inotify_fd
, prefix
, IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CREATE
|IN_MOVED_TO
|IN_DONT_FOLLOW
);
795 log_debug("Added inotify watch for %s on bus %s: %i", prefix
, strna(b
->description
), wd
);
798 if (IN_SET(errno
, ENOENT
, ELOOP
))
799 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
801 r
= log_debug_errno(errno
, "Failed to add inotify watch on %s: %m", empty_to_root(prefix
));
804 new_watches
[n
++] = wd
;
806 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
807 r
= readlink_malloc(prefix
, &destination
);
808 if (r
== -EINVAL
) { /* not a symlink */
815 if (isempty(destination
)) { /* Empty symlink target? Yuck! */
820 if (max_follow
<= 0) { /* Let's make sure we don't follow symlinks forever */
825 if (path_is_absolute(destination
)) {
826 /* For absolute symlinks we build the new path and start anew */
827 c
= strjoin(destination
, absolute
+ done
+ n_component
);
830 _cleanup_free_
char *t
= NULL
;
832 /* For relative symlinks we replace the last component, and try again */
833 t
= strndup(absolute
, done
);
837 c
= strjoin(t
, "/", destination
, absolute
+ done
+ n_component
);
850 /* And now, let's remove all watches from the previous iteration we don't need anymore */
851 for (i
= 0; i
< b
->n_inotify_watches
; i
++) {
855 for (j
= 0; j
< n
; j
++)
856 if (new_watches
[j
] == b
->inotify_watches
[i
]) {
864 (void) inotify_rm_watch(b
->inotify_fd
, b
->inotify_watches
[i
]);
867 free_and_replace(b
->inotify_watches
, new_watches
);
868 b
->n_inotify_watches
= n
;
873 bus_close_inotify_fd(b
);
877 int bus_socket_connect(sd_bus
*b
) {
878 bool inotify_done
= false;
884 assert(b
->input_fd
< 0);
885 assert(b
->output_fd
< 0);
886 assert(b
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
);
888 b
->input_fd
= socket(b
->sockaddr
.sa
.sa_family
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
892 b
->input_fd
= fd_move_above_stdio(b
->input_fd
);
894 b
->output_fd
= b
->input_fd
;
897 if (connect(b
->input_fd
, &b
->sockaddr
.sa
, b
->sockaddr_size
) < 0) {
898 if (errno
== EINPROGRESS
) {
900 /* If we have any inotify watches open, close them now, we don't need them anymore, as
901 * we have successfully initiated a connection */
902 bus_close_inotify_fd(b
);
904 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
905 * we start parsing the address string. The only reason we set the state explicitly
906 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
907 bus_set_state(b
, BUS_OPENING
);
911 if (IN_SET(errno
, ENOENT
, ECONNREFUSED
) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
913 b
->sockaddr
.sa
.sa_family
== AF_UNIX
&&
914 b
->sockaddr
.un
.sun_path
[0] != 0) {
916 /* This connection attempt failed, let's release the socket for now, and start with a
917 * fresh one when reconnecting. */
921 /* inotify set up already, don't do it again, just return now, and remember
922 * that we are waiting for inotify events now. */
923 bus_set_state(b
, BUS_WATCH_BIND
);
927 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
928 r
= bus_socket_inotify_setup(b
);
932 /* Let's now try to connect a second time, because in theory there's otherwise a race
933 * here: the socket might have been created in the time between our first connect() and
934 * the time we set up the inotify logic. But let's remember that we set up inotify now,
935 * so that we don't do the connect() more than twice. */
944 /* Yay, established, we don't need no inotify anymore! */
945 bus_close_inotify_fd(b
);
947 return bus_socket_start_auth(b
);
950 int bus_socket_exec(sd_bus
*b
) {
954 assert(b
->input_fd
< 0);
955 assert(b
->output_fd
< 0);
956 assert(b
->exec_path
);
957 assert(b
->busexec_pid
== 0);
959 r
= socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_NONBLOCK
|SOCK_CLOEXEC
, 0, s
);
963 r
= safe_fork_full("(sd-busexec)", s
+1, 1, FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
, &b
->busexec_pid
);
971 if (rearrange_stdio(s
[1], s
[1], STDERR_FILENO
) < 0)
974 (void) rlimit_nofile_safe();
977 execvp(b
->exec_path
, b
->exec_argv
);
979 const char *argv
[] = { b
->exec_path
, NULL
};
980 execvp(b
->exec_path
, (char**) argv
);
987 b
->output_fd
= b
->input_fd
= fd_move_above_stdio(s
[0]);
991 return bus_socket_start_auth(b
);
994 int bus_socket_take_fd(sd_bus
*b
) {
999 return bus_socket_start_auth(b
);
1002 int bus_socket_write_message(sd_bus
*bus
, sd_bus_message
*m
, size_t *idx
) {
1012 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1014 if (*idx
>= BUS_MESSAGE_SIZE(m
))
1017 r
= bus_message_setup_iovec(m
);
1021 n
= m
->n_iovec
* sizeof(struct iovec
);
1022 iov
= newa(struct iovec
, n
);
1023 memcpy_safe(iov
, m
->iovec
, n
);
1026 iovec_advance(iov
, &j
, *idx
);
1028 if (bus
->prefer_writev
)
1029 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1031 struct msghdr mh
= {
1033 .msg_iovlen
= m
->n_iovec
,
1036 if (m
->n_fds
> 0 && *idx
== 0) {
1037 struct cmsghdr
*control
;
1039 mh
.msg_controllen
= CMSG_SPACE(sizeof(int) * m
->n_fds
);
1040 mh
.msg_control
= alloca0(mh
.msg_controllen
);
1041 control
= CMSG_FIRSTHDR(&mh
);
1042 control
->cmsg_len
= CMSG_LEN(sizeof(int) * m
->n_fds
);
1043 control
->cmsg_level
= SOL_SOCKET
;
1044 control
->cmsg_type
= SCM_RIGHTS
;
1045 memcpy(CMSG_DATA(control
), m
->fds
, sizeof(int) * m
->n_fds
);
1048 k
= sendmsg(bus
->output_fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
1049 if (k
< 0 && errno
== ENOTSOCK
) {
1050 bus
->prefer_writev
= true;
1051 k
= writev(bus
->output_fd
, iov
, m
->n_iovec
);
1056 return errno
== EAGAIN
? 0 : -errno
;
1062 static int bus_socket_read_message_need(sd_bus
*bus
, size_t *need
) {
1069 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1071 if (bus
->rbuffer_size
< sizeof(struct bus_header
)) {
1072 *need
= sizeof(struct bus_header
) + 8;
1074 /* Minimum message size:
1078 * Method Call: +2 string headers
1079 * Signal: +3 string headers
1080 * Method Error: +1 string headers
1082 * Method Reply: +1 uint32 headers
1084 * A string header is at least 9 bytes
1085 * A uint32 header is at least 8 bytes
1087 * Hence the minimum message size of a valid message
1088 * is header + 8 bytes */
1093 a
= ((const uint32_t*) bus
->rbuffer
)[1];
1094 b
= ((const uint32_t*) bus
->rbuffer
)[3];
1096 e
= ((const uint8_t*) bus
->rbuffer
)[0];
1097 if (e
== BUS_LITTLE_ENDIAN
) {
1100 } else if (e
== BUS_BIG_ENDIAN
) {
1106 sum
= (uint64_t) sizeof(struct bus_header
) + (uint64_t) ALIGN_TO(b
, 8) + (uint64_t) a
;
1107 if (sum
>= BUS_MESSAGE_SIZE_MAX
)
1110 *need
= (size_t) sum
;
1114 static int bus_socket_make_message(sd_bus
*bus
, size_t size
) {
1115 sd_bus_message
*t
= NULL
;
1120 assert(bus
->rbuffer_size
>= size
);
1121 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1123 r
= bus_rqueue_make_room(bus
);
1127 if (bus
->rbuffer_size
> size
) {
1128 b
= memdup((const uint8_t*) bus
->rbuffer
+ size
,
1129 bus
->rbuffer_size
- size
);
1135 r
= bus_message_from_malloc(bus
,
1137 bus
->fds
, bus
->n_fds
,
1140 if (r
== -EBADMSG
) {
1141 log_debug_errno(r
, "Received invalid message from connection %s, dropping.", strna(bus
->description
));
1142 free(bus
->rbuffer
); /* We want to drop current rbuffer and proceed with whatever remains in b */
1148 /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
1150 bus
->rbuffer_size
-= size
;
1156 t
->read_counter
= ++bus
->read_counter
;
1157 bus
->rqueue
[bus
->rqueue_size
++] = bus_message_ref_queued(t
, bus
);
1158 sd_bus_message_unref(t
);
1164 int bus_socket_read_message(sd_bus
*bus
) {
1166 struct iovec iov
= {};
1171 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX
)) control
;
1172 bool handle_cmsg
= false;
1175 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
1177 r
= bus_socket_read_message_need(bus
, &need
);
1181 if (bus
->rbuffer_size
>= need
)
1182 return bus_socket_make_message(bus
, need
);
1184 b
= realloc(bus
->rbuffer
, need
);
1190 iov
= IOVEC_MAKE((uint8_t *)bus
->rbuffer
+ bus
->rbuffer_size
, need
- bus
->rbuffer_size
);
1192 if (bus
->prefer_readv
) {
1193 k
= readv(bus
->input_fd
, &iov
, 1);
1197 mh
= (struct msghdr
) {
1200 .msg_control
= &control
,
1201 .msg_controllen
= sizeof(control
),
1204 k
= recvmsg_safe(bus
->input_fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
1205 if (k
== -ENOTSOCK
) {
1206 bus
->prefer_readv
= true;
1207 k
= readv(bus
->input_fd
, &iov
, 1);
1219 cmsg_close_all(&mh
); /* On EOF we shouldn't have gotten an fd, but let's make sure */
1223 bus
->rbuffer_size
+= k
;
1226 struct cmsghdr
*cmsg
;
1228 CMSG_FOREACH(cmsg
, &mh
)
1229 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
1230 cmsg
->cmsg_type
== SCM_RIGHTS
) {
1233 n
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1235 if (!bus
->can_fds
) {
1236 /* Whut? We received fds but this
1237 * isn't actually enabled? Close them,
1240 close_many((int*) CMSG_DATA(cmsg
), n
);
1244 f
= reallocarray(bus
->fds
, bus
->n_fds
+ n
, sizeof(int));
1246 close_many((int*) CMSG_DATA(cmsg
), n
);
1250 for (i
= 0; i
< n
; i
++)
1251 f
[bus
->n_fds
++] = fd_move_above_stdio(((int*) CMSG_DATA(cmsg
))[i
]);
1254 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1255 cmsg
->cmsg_level
, cmsg
->cmsg_type
);
1258 r
= bus_socket_read_message_need(bus
, &need
);
1262 if (bus
->rbuffer_size
>= need
)
1263 return bus_socket_make_message(bus
, need
);
1268 int bus_socket_process_opening(sd_bus
*b
) {
1269 int error
= 0, events
, r
;
1270 socklen_t slen
= sizeof(error
);
1272 assert(b
->state
== BUS_OPENING
);
1274 events
= fd_wait_for_event(b
->output_fd
, POLLOUT
, 0);
1277 if (!(events
& (POLLOUT
|POLLERR
|POLLHUP
)))
1280 r
= getsockopt(b
->output_fd
, SOL_SOCKET
, SO_ERROR
, &error
, &slen
);
1282 b
->last_connect_error
= errno
;
1283 else if (error
!= 0)
1284 b
->last_connect_error
= error
;
1285 else if (events
& (POLLERR
|POLLHUP
))
1286 b
->last_connect_error
= ECONNREFUSED
;
1288 return bus_socket_start_auth(b
);
1290 return bus_next_address(b
);
1293 int bus_socket_process_authenticating(sd_bus
*b
) {
1297 assert(b
->state
== BUS_AUTHENTICATING
);
1299 if (now(CLOCK_MONOTONIC
) >= b
->auth_timeout
)
1302 r
= bus_socket_write_auth(b
);
1306 return bus_socket_read_auth(b
);
1309 int bus_socket_process_watch_bind(sd_bus
*b
) {
1313 assert(b
->state
== BUS_WATCH_BIND
);
1314 assert(b
->inotify_fd
>= 0);
1316 r
= flush_fd(b
->inotify_fd
);
1320 log_debug("Got inotify event on bus %s.", strna(b
->description
));
1322 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1325 r
= bus_socket_connect(b
);
1329 q
= bus_attach_io_events(b
);
1333 q
= bus_attach_inotify_event(b
);