HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/libsystemd/sd-bus/bus-socket.c

52,286 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 638d650336b11f7a94d2842c1a26cfa7226f1d2f

Lines 1001–1550 of 1,550

 
        /* Generate a recognizable source address in the abstract namespace. We'll include:
         * - a random 64-bit value (to avoid collisions)
         * - our "comm" process name (suppressed if contains "/" to avoid parsing issues)
         * - the description string of the bus connection. */
        (void) pid_get_comm(0, &comm);
        if (comm && strchr(comm, '/'))
                comm = mfree(comm);
 
        if (!d && !comm) /* skip if we don't have either field, rely on kernel autobind instead */
                return 0;
 
        if (asprintf(&bind_name, "@%" PRIx64 "/bus/%s/%s", random_u64(), strempty(comm), strempty(d)) < 0)
                return -ENOMEM;
 
        strshorten(bind_name, sizeof_field(struct sockaddr_un, sun_path));
 
        r = sockaddr_un_set_path(&bsa.un, bind_name);
        if (r < 0)
                return r;
 
        if (bind(fd, &bsa.sa, r) < 0)
                return -errno;
 
        return 0;
}
 
static int connect_as(int fd, const struct sockaddr *sa, socklen_t salen, uid_t uid, gid_t gid) {
        _cleanup_close_pair_ int pfd[2] = EBADF_PAIR;
        ssize_t n;
        int r;
 
        /* Shortcut if we are not supposed to drop privileges */
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
                return RET_NERRNO(connect(fd, sa, salen));
 
        /* This changes identity to the specified uid/gid and issues connect() as that. This is useful to
         * make sure SO_PEERCRED reports the selected UID/GID rather than the usual one of the caller. */
 
        if (pipe2(pfd, O_CLOEXEC) < 0)
                return -errno;
 
        r = pidref_safe_fork(
                        "(sd-setresuid)",
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
                        /* ret= */ NULL);
        if (r < 0)
                return r;
        if (r == 0) {
                /* child */
 
                pfd[0] = safe_close(pfd[0]);
 
                r = RET_NERRNO(setgroups(0, NULL));
                if (r < 0)
                        goto child_finish;
 
                if (gid_is_valid(gid)) {
                        r = RET_NERRNO(setresgid(gid, gid, gid));
                        if (r < 0)
                                goto child_finish;
                }
 
                if (uid_is_valid(uid)) {
                        r = RET_NERRNO(setresuid(uid, uid, uid));
                        if (r < 0)
                                goto child_finish;
                }
 
                r = RET_NERRNO(connect(fd, sa, salen));
                if (r < 0)
                        goto child_finish;
 
                r = 0;
 
        child_finish:
                n = write(pfd[1], &r, sizeof(r));
                if (n != sizeof(r))
                        _exit(EXIT_FAILURE);
 
                _exit(EXIT_SUCCESS);
        }
 
        n = read(pfd[0], &r, sizeof(r));
        if (n != sizeof(r))
                return -EIO;
 
        return r;
}
 
int bus_socket_connect(sd_bus *b) {
        bool inotify_done = false;
        int r;
 
        assert(b);
 
        for (;;) {
                assert(b->input_fd < 0);
                assert(b->output_fd < 0);
                assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
 
                if (DEBUG_LOGGING) {
                        _cleanup_free_ char *pretty = NULL;
                        (void) sockaddr_pretty(&b->sockaddr.sa, b->sockaddr_size, false, true, &pretty);
                        log_debug("sd-bus: starting bus%s%s by connecting to %s...",
                                  b->description ? " " : "", strempty(b->description), strnull(pretty));
                }
 
                b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
                if (b->input_fd < 0)
                        return -errno;
 
                r = bind_description(b, b->input_fd, b->sockaddr.sa.sa_family);
                if (r < 0)
                        return r;
 
                b->input_fd = fd_move_above_stdio(b->input_fd);
 
                b->output_fd = b->input_fd;
                bus_socket_setup(b);
 
                r = connect_as(b->input_fd, &b->sockaddr.sa, b->sockaddr_size, b->connect_as_uid, b->connect_as_gid);
                if (r < 0) {
                        if (r == -EINPROGRESS) {
 
                                /* If we have any inotify watches open, close them now, we don't need them anymore, as
                                 * we have successfully initiated a connection */
                                bus_close_inotify_fd(b);
 
                                /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
                                 * we start parsing the address string. The only reason we set the state explicitly
                                 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
                                bus_set_state(b, BUS_OPENING);
                                return 1;
                        }
 
                        if (IN_SET(r, -ENOENT, -ECONNREFUSED) &&  /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
                            b->watch_bind &&
                            b->sockaddr.sa.sa_family == AF_UNIX &&
                            b->sockaddr.un.sun_path[0] != 0) {
 
                                /* This connection attempt failed, let's release the socket for now, and start with a
                                 * fresh one when reconnecting. */
                                bus_close_io_fds(b);
 
                                if (inotify_done) {
                                        /* inotify set up already, don't do it again, just return now, and remember
                                         * that we are waiting for inotify events now. */
                                        bus_set_state(b, BUS_WATCH_BIND);
                                        return 1;
                                }
 
                                /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
                                r = bus_socket_inotify_setup(b);
                                if (r < 0)
                                        return r;
 
                                /* Let's now try to connect a second time, because in theory there's otherwise a race
                                 * here: the socket might have been created in the time between our first connect() and
                                 * the time we set up the inotify logic. But let's remember that we set up inotify now,
                                 * so that we don't do the connect() more than twice. */
                                inotify_done = true;
 
                        } else
                                return r;
                } else
                        break;
        }
 
        /* Yay, established, we don't need no inotify anymore! */
        bus_close_inotify_fd(b);
 
        return bus_socket_start_auth(b);
}
 
int bus_socket_exec(sd_bus *b) {
        int s[2], r;
 
        assert(b);
        assert(b->input_fd < 0);
        assert(b->output_fd < 0);
        assert(b->exec_path);
        assert(!pidref_is_set(&b->busexec_pidref));
 
        if (DEBUG_LOGGING) {
                _cleanup_free_ char *line = NULL;
 
                if (b->exec_argv)
                        line = quote_command_line(b->exec_argv, SHELL_ESCAPE_EMPTY);
 
                log_debug("sd-bus: starting bus%s%s with %s%s",
                          b->description ? " " : "", strempty(b->description),
                          line ?: b->exec_path,
                          b->exec_argv && !line ? "…" : "");
        }
 
        r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
        if (r < 0)
                return -errno;
 
        r = pidref_safe_fork_full(
                        "(sd-busexec)",
                        (int[]) { s[1], s[1], STDERR_FILENO },
                        NULL, 0,
                        FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_REARRANGE_STDIO|FORK_RLIMIT_NOFILE_SAFE,
                        &b->busexec_pidref);
        if (r < 0) {
                safe_close_pair(s);
                return r;
        }
        if (r == 0) {
                /* Child */
 
                if (b->exec_argv)
                        execvp(b->exec_path, b->exec_argv);
                else
                        execvp(b->exec_path, STRV_MAKE(b->exec_path));
 
                _exit(EXIT_FAILURE);
        }
 
        safe_close(s[1]);
        b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
 
        bus_socket_setup(b);
 
        return bus_socket_start_auth(b);
}
 
int bus_socket_take_fd(sd_bus *b) {
        assert(b);
 
        bus_socket_setup(b);
 
        return bus_socket_start_auth(b);
}
 
int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
        struct iovec *iov;
        ssize_t k;
        unsigned j;
        int r;
 
        assert(bus);
        assert(m);
        assert(idx);
        assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
 
        if (*idx >= BUS_MESSAGE_SIZE(m))
                return 0;
 
        r = bus_message_setup_iovec(m);
        if (r < 0)
                return r;
 
        iov = newa(struct iovec, m->n_iovec);
        memcpy_safe(iov, m->iovec, sizeof(struct iovec) * m->n_iovec);
 
        j = 0;
        iovec_advance(iov, &j, *idx);
 
        if (bus->prefer_writev)
                k = writev(bus->output_fd, iov, m->n_iovec);
        else {
                struct msghdr mh = {
                        .msg_iov = iov,
                        .msg_iovlen = m->n_iovec,
                };
 
                if (m->n_fds > 0 && *idx == 0) {
                        struct cmsghdr *control;
 
                        mh.msg_controllen = CMSG_SPACE(sizeof(int) * m->n_fds);
                        mh.msg_control = alloca0(mh.msg_controllen);
                        control = CMSG_FIRSTHDR(&mh);
                        control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
                        control->cmsg_level = SOL_SOCKET;
                        control->cmsg_type = SCM_RIGHTS;
                        memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
                }
 
                k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
                if (k < 0 && errno == ENOTSOCK) {
                        bus->prefer_writev = true;
                        k = writev(bus->output_fd, iov, m->n_iovec);
                }
        }
 
        if (k < 0)
                return ERRNO_IS_TRANSIENT(errno) ? 0 : -errno;
 
        *idx += (size_t) k;
        return 1;
}
 
static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
        uint32_t a, b;
        uint8_t e;
        uint64_t sum;
 
        assert(bus);
        assert(need);
        assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
 
        if (bus->rbuffer_size < sizeof(BusMessageHeader)) {
                *need = sizeof(BusMessageHeader) + 8;
 
                /* Minimum message size:
                 *
                 * Header +
                 *
                 *  Method Call: +2 string headers
                 *       Signal: +3 string headers
                 * Method Error: +1 string headers
                 *               +1 uint32 headers
                 * Method Reply: +1 uint32 headers
                 *
                 * A string header is at least 9 bytes
                 * A uint32 header is at least 8 bytes
                 *
                 * Hence the minimum message size of a valid message
                 * is header + 8 bytes */
 
                return 0;
        }
 
        a = ((const uint32_t*) bus->rbuffer)[1];
        b = ((const uint32_t*) bus->rbuffer)[3];
 
        e = ((const uint8_t*) bus->rbuffer)[0];
        if (e == BUS_LITTLE_ENDIAN) {
                a = le32toh(a);
                b = le32toh(b);
        } else if (e == BUS_BIG_ENDIAN) {
                a = be32toh(a);
                b = be32toh(b);
        } else
                return -EBADMSG;
 
        sum = (uint64_t) sizeof(BusMessageHeader) + (uint64_t) ALIGN8(b) + (uint64_t) a;
        if (sum >= BUS_MESSAGE_SIZE_MAX)
                return -ENOBUFS;
 
        *need = (size_t) sum;
        return 0;
}
 
static int bus_socket_make_message(sd_bus *bus, size_t size) {
        sd_bus_message *t = NULL;
        void *b;
        int r;
 
        assert(bus);
        assert(bus->rbuffer_size >= size);
        assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
 
        r = bus_rqueue_make_room(bus);
        if (r < 0)
                return r;
 
        if (bus->rbuffer_size > size) {
                b = memdup((const uint8_t*) bus->rbuffer + size,
                           bus->rbuffer_size - size);
                if (!b)
                        return -ENOMEM;
        } else
                b = NULL;
 
        r = bus_message_from_malloc(bus,
                                    bus->rbuffer, size,
                                    bus->fds, bus->n_fds,
                                    bus->got_ctrunc,
                                    NULL,
                                    &t);
        if (r == -EBADMSG) {
                log_debug_errno(r, "Received invalid message from connection %s, dropping.", strna(bus->description));
                free(bus->rbuffer); /* We want to drop current rbuffer and proceed with whatever remains in b */
        } else if (r < 0) {
                free(b);
                return r;
        }
 
        /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
        bus->rbuffer = b;
        bus->rbuffer_size -= size;
 
        bus->fds = NULL;
        bus->n_fds = 0;
        bus->got_ctrunc = false;
 
        if (t) {
                t->read_counter = ++bus->read_counter;
                bus->rqueue[bus->rqueue_size++] = bus_message_ref_queued(t, bus);
                sd_bus_message_unref(t);
        }
 
        return 1;
}
 
int bus_socket_read_message(sd_bus *bus) {
        size_t need;
        int r;
 
        assert(bus);
        assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
 
        r = bus_socket_read_message_need(bus, &need);
        if (r < 0)
                return r;
 
        if (bus->rbuffer_size >= need)
                return bus_socket_make_message(bus, need);
 
        void *b = realloc(bus->rbuffer, need);
        if (!b)
                return -ENOMEM;
        bus->rbuffer = b;
 
        struct iovec iov = IOVEC_MAKE((uint8_t*) bus->rbuffer + bus->rbuffer_size, need - bus->rbuffer_size);
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)) control;
        struct msghdr mh;
        bool handle_cmsg = false;
        ssize_t k;
 
        if (!bus->prefer_readv) {
                mh = (struct msghdr) {
                        .msg_iov = &iov,
                        .msg_iovlen = 1,
                        .msg_control = &control,
                        .msg_controllen = sizeof(control),
                };
 
                k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
                if (k < 0 && errno == ENOTSOCK)
                        bus->prefer_readv = true;
                else
                        handle_cmsg = true;
        }
        if (bus->prefer_readv)
                k = readv(bus->input_fd, &iov, 1);
        if (k < 0) {
                if (ERRNO_IS_TRANSIENT(errno))
                        return 0;
 
                return -errno;
        }
        if (k == 0) {
                if (handle_cmsg)
                        cmsg_close_all(&mh); /* On EOF we shouldn't have gotten an fd, but let's make sure */
                return -ECONNRESET;
        }
        if (handle_cmsg && FLAGS_SET(mh.msg_flags, MSG_TRUNC)) {
                cmsg_close_all(&mh);
                return -EXFULL;
        }
 
        /* Silence static analyzers, k is bounded by iov size: need - rbuffer_size */
        assert((size_t) k <= need - bus->rbuffer_size);
        bus->rbuffer_size += k;
 
        if (handle_cmsg) {
                r = bus_process_cmsg(bus, &mh, bus->can_fds);
                if (r < 0)
                        return r;
        }
 
        r = bus_socket_read_message_need(bus, &need);
        if (r < 0)
                return r;
 
        if (bus->rbuffer_size >= need)
                return bus_socket_make_message(bus, need);
 
        return 1;
}
 
int bus_socket_process_opening(sd_bus *b) {
        int error = 0, events, r;
        socklen_t slen = sizeof(error);
 
        assert(b->state == BUS_OPENING);
 
        events = fd_wait_for_event(b->output_fd, POLLOUT, 0);
        if (ERRNO_IS_NEG_TRANSIENT(events))
                return 0;
        if (events < 0)
                return events;
        if (!(events & (POLLOUT|POLLERR|POLLHUP)))
                return 0;
 
        r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
        if (r < 0)
                b->last_connect_error = errno;
        else if (error != 0)
                b->last_connect_error = error;
        else if (events & (POLLERR|POLLHUP))
                b->last_connect_error = ECONNREFUSED;
        else
                return bus_socket_start_auth(b);
 
        return bus_next_address(b);
}
 
int bus_socket_process_authenticating(sd_bus *b) {
        int r;
 
        assert(b);
        assert(b->state == BUS_AUTHENTICATING);
 
        if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
                return -ETIMEDOUT;
 
        r = bus_socket_write_auth(b);
        if (r != 0)
                return r;
 
        return bus_socket_read_auth(b);
}
 
int bus_socket_process_watch_bind(sd_bus *b) {
        int r, q;
 
        assert(b);
        assert(b->state == BUS_WATCH_BIND);
        assert(b->inotify_fd >= 0);
 
        r = flush_fd(b->inotify_fd);
        if (r <= 0)
                return r;
 
        log_debug("Got inotify event on bus %s.", strna(b->description));
 
        /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
         * to it again */
 
        r = bus_socket_connect(b);
        if (r < 0)
                return r;
 
        q = bus_attach_io_events(b);
        if (q < 0)
                return q;
 
        q = bus_attach_inotify_event(b);
        if (q < 0)
                return q;
 
        return r;
}