| // SPDX-License-Identifier: GPL-2.0-only | |
| // Copyright (c) 2026 Jarkko Sakkinen | |
| #include <string.h> | |
| #include <sys/socket.h> | |
| #include "base.h" | |
| #include "fdpass.h" | |
| int fd_pair(int fds[2]) | |
| { | |
| if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, fds) < 0) | |
| return err_ctx(-errno, "socketpair"); | |
| return 0; | |
| } | |
| int send_fd(int socket, int fd) | |
| { | |
| alignas(struct cmsghdr) char control[CMSG_SPACE(sizeof(int))] = {}; | |
| char payload = 0; | |
| struct iovec iov = {.iov_base = &payload, .iov_len = 1}; | |
| struct msghdr msg = { | |
| .msg_iov = &iov, | |
| .msg_iovlen = 1, | |
| .msg_control = control, | |
| .msg_controllen = sizeof(control), | |
| }; | |
| struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); | |
| ssize_t ret; | |
| cmsg->cmsg_level = SOL_SOCKET; | |
| cmsg->cmsg_type = SCM_RIGHTS; | |
| cmsg->cmsg_len = CMSG_LEN(sizeof(fd)); | |
| memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd)); | |
| do { | |
| ret = sendmsg(socket, &msg, MSG_NOSIGNAL); | |
| } while (ret < 0 && errno == EINTR); | |
| if (ret < 0) | |
| return err_ctx(-errno, "sendmsg SCM_RIGHTS"); | |
| return 0; | |
| } | |
| int recv_fd(int socket) | |
| { | |
| alignas(struct cmsghdr) char control[CMSG_SPACE(sizeof(int))] = {}; | |
| char payload = 0; | |
| struct iovec iov = {.iov_base = &payload, .iov_len = 1}; | |
| struct msghdr msg = { | |
| .msg_iov = &iov, | |
| .msg_iovlen = 1, | |
| .msg_control = control, | |
| .msg_controllen = sizeof(control), | |
| }; | |
| struct cmsghdr *cmsg; | |
| int received = -1; | |
| size_t nr_fds = 0; | |
| ssize_t bytes; | |
| int ret; | |
| do { | |
| bytes = recvmsg(socket, &msg, MSG_CMSG_CLOEXEC); | |
| } while (bytes < 0 && errno == EINTR); | |
| if (bytes < 0) | |
| return err_ctx(-errno, "recvmsg SCM_RIGHTS"); | |
| for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { | |
| size_t count; | |
| if (cmsg->cmsg_level != SOL_SOCKET || | |
| cmsg->cmsg_type != SCM_RIGHTS || | |
| cmsg->cmsg_len < CMSG_LEN(0)) | |
| continue; | |
| count = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int); | |
| for (size_t i = 0; i < count; i++) { | |
| int fd; | |
| memcpy(&fd, CMSG_DATA(cmsg) + i * sizeof(fd), | |
| sizeof(fd)); | |
| if (nr_fds++ == 0) | |
| received = fd; | |
| else | |
| close_fd(fd); | |
| } | |
| } | |
| if (!bytes) | |
| ret = err_ctx(-EPIPE, "recvmsg SCM_RIGHTS: peer closed"); | |
| else if (msg.msg_flags & MSG_CTRUNC) | |
| ret = err_ctx(-ENOBUFS, | |
| "recvmsg SCM_RIGHTS: control data truncated"); | |
| else if (msg.msg_flags & MSG_TRUNC) | |
| ret = err_ctx(-EMSGSIZE, | |
| "recvmsg SCM_RIGHTS: payload truncated"); | |
| else if (nr_fds != 1) | |
| ret = err_ctx(-EBADMSG, | |
| "recvmsg SCM_RIGHTS: expected one descriptor"); | |
| else | |
| return received; | |
| close_fd(received); | |
| return ret; | |
| } |