1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2013 Lennart Poettering
9 #include "bus-container.h"
10 #include "bus-internal.h"
11 #include "bus-socket.h"
13 #include "process-util.h"
16 int bus_container_connect_socket(sd_bus *b) {
17 _cleanup_close_pair_ int pair[2] = { -1, -1 };
18 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
24 assert(b->input_fd < 0);
25 assert(b->output_fd < 0);
26 assert(b->nspid > 0 || b->machine);
29 r = container_get_leader(b->machine, &b->nspid);
34 r = namespace_open(b->nspid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
38 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
42 b->input_fd = fd_move_above_stdio(b->input_fd);
44 b->output_fd = b->input_fd;
48 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, pair) < 0)
51 r = safe_fork("(sd-buscntr)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
57 pair[0] = safe_close(pair[0]);
59 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
63 /* We just changed PID namespace, however it will only
64 * take effect on the children we now fork. Hence,
65 * let's fork another time, and connect from this
66 * grandchild, so that SO_PEERCRED of our connection
67 * comes from a process from within the container, and
68 * not outside of it */
70 r = safe_fork("(sd-buscntr2)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &grandchild);
75 r = connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size);
77 /* Try to send error up */
79 (void) write(pair[1], &error_buf, sizeof(error_buf));
86 r = wait_for_terminate_and_check("(sd-buscntr2)", grandchild, 0);
93 pair[1] = safe_close(pair[1]);
95 r = wait_for_terminate_and_check("(sd-buscntr)", child, 0);
98 if (r != EXIT_SUCCESS)
101 n = read(pair[0], &error_buf, sizeof(error_buf));
106 if (n != sizeof(error_buf))
112 if (error_buf == EINPROGRESS)
119 return bus_socket_start_auth(b);