HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/basic/socket-util.c

61,797 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 79eabcf32077895d7ef592a5c0fc6d458522ab48

Lines 1001–1923 of 1,923

         * We need either an FD or data to send.
         * If there's nothing, return an error.
         */
        if (fd < 0 && !iov)
                return -EINVAL;
 
        if (fd >= 0) {
                struct cmsghdr *cmsg;
 
                mh.msg_control = &control;
                mh.msg_controllen = sizeof(control);
 
                cmsg = CMSG_FIRSTHDR(&mh);
                cmsg->cmsg_level = SOL_SOCKET;
                cmsg->cmsg_type = SCM_RIGHTS;
                cmsg->cmsg_len = CMSG_LEN(sizeof(int));
                memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
        }
        k = sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags);
        if (k < 0)
                return (ssize_t) -errno;
 
        return k;
}
 
int send_one_fd_sa(
                int transport_fd,
                int fd,
                const struct sockaddr *sa, socklen_t len,
                int flags) {
 
        assert(fd >= 0);
 
        return (int) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, sa, len, flags);
}
 
ssize_t receive_one_fd_iov(
                int transport_fd,
                struct iovec *iov, size_t iovlen,
                int flags,
                int *ret_fd) {
 
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
        struct msghdr mh = {
                .msg_control = &control,
                .msg_controllen = sizeof(control),
                .msg_iov = iov,
                .msg_iovlen = iovlen,
        };
        struct cmsghdr *found;
        ssize_t k;
 
        assert(transport_fd >= 0);
        assert(ret_fd);
 
        /*
         * Receive a single FD via @transport_fd. We don't care for
         * the transport-type. We retrieve a single FD at most, so for
         * packet-based transports, the caller must ensure to send
         * only a single FD per packet.  This is best used in
         * combination with send_one_fd().
         */
 
        k = recvmsg_safe(transport_fd, &mh, MSG_CMSG_CLOEXEC | flags);
        if (k < 0)
                return k;
 
        found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
        if (!found) {
                cmsg_close_all(&mh);
 
                /* If didn't receive an FD or any data, return an error. */
                if (k == 0)
                        return -EIO;
        }
 
        if (found)
                *ret_fd = *CMSG_TYPED_DATA(found, int);
        else
                *ret_fd = -EBADF;
 
        return k;
}
 
int receive_one_fd(int transport_fd, int flags) {
        int fd;
        ssize_t k;
 
        k = receive_one_fd_iov(transport_fd, NULL, 0, flags, &fd);
        if (k == 0)
                return fd;
 
        /* k must be negative, since receive_one_fd_iov() only returns
         * a positive value if data was received through the iov. */
        assert(k < 0);
        return (int) k;
}
 
ssize_t next_datagram_size_fd(int fd) {
        ssize_t l;
        int k;
 
        /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
         * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
         * do. This difference is actually of major importance as we need to be sure that the size returned here
         * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
         * the wrong size. */
 
        l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
        if (l < 0) {
                if (IN_SET(errno, EOPNOTSUPP, EFAULT))
                        goto fallback;
 
                return -errno;
        }
        if (l == 0)
                goto fallback;
 
        return l;
 
fallback:
        k = 0;
 
        /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
         * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
 
        if (ioctl(fd, FIONREAD, &k) < 0)
                return -errno;
 
        return (ssize_t) k;
}
 
/* Put a limit on how many times will attempt to call accept4(). We loop
 * only on "transient" errors, but let's make sure we don't loop forever. */
#define MAX_FLUSH_ITERATIONS 1024
 
int flush_accept(int fd) {
 
        int r, b;
        socklen_t l = sizeof(b);
 
        /* Similar to flush_fd() but flushes all incoming connections by accepting and immediately closing
         * them. */
 
        if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
                return -errno;
 
        assert(l == sizeof(b));
        if (!b) /* Let's check if this socket accepts connections before calling accept(). accept4() can
                 * return EOPNOTSUPP if the fd is not a listening socket, which we should treat as a fatal
                 * error, or in case the incoming TCP connection triggered a network issue, which we want to
                 * treat as a transient error. Thus, let's rule out the first reason for EOPNOTSUPP early, so
                 * we can loop safely on transient errors below. */
                return -ENOTTY;
 
        for (unsigned iteration = 0;; iteration++) {
                int cfd;
 
                r = fd_wait_for_event(fd, POLLIN, 0);
                if (r == -EINTR)
                        continue;
                if (r <= 0)
                        return r;
 
                if (iteration >= MAX_FLUSH_ITERATIONS)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
                                               "Failed to flush connections within " STRINGIFY(MAX_FLUSH_ITERATIONS) " iterations.");
 
                cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
                if (cfd < 0) {
                        if (errno == EAGAIN)
                                return 0;
 
                        if (ERRNO_IS_ACCEPT_AGAIN(errno))
                                continue;
 
                        return -errno;
                }
 
                safe_close(cfd);
        }
}
 
ssize_t flush_mqueue(int fd) {
        _cleanup_free_ char *buf = NULL;
        struct mq_attr attr;
        ssize_t count = 0;
        int r;
 
        assert(fd >= 0);
 
        /* Similar to flush_fd() but flushes all messages from a POSIX message queue. */
 
        for (;;) {
                ssize_t l;
 
                r = fd_wait_for_event(fd, POLLIN, /* timeout= */ 0);
                if (r == -EINTR)
                        continue;
                if (r < 0)
                        return r;
                if (r == 0)
                        return count;
 
                if (!buf) {
                        /* Buffer must be at least as large as mq_msgsize. */
                        if (mq_getattr(fd, &attr) < 0)
                                return -errno;
 
                        buf = malloc(attr.mq_msgsize);
                        if (!buf)
                                return -ENOMEM;
                }
 
                l = mq_receive(fd, buf, attr.mq_msgsize, /* msg_prio= */ NULL);
                if (l < 0) {
                        if (errno == EINTR)
                                continue;
 
                        if (errno == EAGAIN)
                                return count;
 
                        return -errno;
                }
 
                count += l;
        }
}
 
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
        struct cmsghdr *cmsg;
 
        assert(mh);
 
        CMSG_FOREACH(cmsg, mh)
                if (cmsg->cmsg_level == level &&
                    cmsg->cmsg_type == type &&
                    (length == (socklen_t) -1 || length == cmsg->cmsg_len))
                        return cmsg;
 
        return NULL;
}
 
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len) {
        struct cmsghdr *cmsg;
 
        assert(mh);
        assert(buf);
        assert(buf_len > 0);
 
        /* This is similar to cmsg_find_data(), but copy the found data to buf. This should be typically used
         * when reading possibly unaligned data such as timestamp, as time_t is 64-bit and size_t is 32-bit on
         * RISCV32. See issue #27241. */
 
        cmsg = cmsg_find(mh, level, type, CMSG_LEN(buf_len));
        if (!cmsg)
                return NULL;
 
        return memcpy_safe(buf, CMSG_DATA(cmsg), buf_len);
}
 
size_t sockaddr_ll_len(const struct sockaddr_ll *sa) {
        /* Certain hardware address types (e.g Infiniband) do not fit into sll_addr
         * (8 bytes) and run over the structure. This function returns the correct size that
         * must be passed to kernel. */
 
        assert(sa->sll_family == AF_PACKET);
 
        size_t mac_len = sizeof(sa->sll_addr);
 
        if (be16toh(sa->sll_hatype) == ARPHRD_ETHER)
                mac_len = MAX(mac_len, (size_t) ETH_ALEN);
        if (be16toh(sa->sll_hatype) == ARPHRD_INFINIBAND)
                mac_len = MAX(mac_len, (size_t) INFINIBAND_ALEN);
 
        return offsetof(struct sockaddr_ll, sll_addr) + mac_len;
}
 
size_t sockaddr_un_len(const struct sockaddr_un *sa) {
        /* Covers only file system and abstract AF_UNIX socket addresses, but not unnamed socket addresses. */
 
        assert(sa->sun_family == AF_UNIX);
 
        return offsetof(struct sockaddr_un, sun_path) +
                (sa->sun_path[0] == 0 ?
                        1 + strnlen(sa->sun_path+1, sizeof(sa->sun_path)-1) :
                        strnlen(sa->sun_path, sizeof(sa->sun_path))+1);
}
 
size_t sockaddr_len(const union sockaddr_union *sa) {
        assert(sa);
 
        switch (sa->sa.sa_family) {
        case AF_INET:
                return sizeof(struct sockaddr_in);
        case AF_INET6:
                return sizeof(struct sockaddr_in6);
        case AF_UNIX:
                return sockaddr_un_len(&sa->un);
        case AF_PACKET:
                return sockaddr_ll_len(&sa->ll);
        case AF_NETLINK:
                return sizeof(struct sockaddr_nl);
        case AF_VSOCK:
                return sizeof(struct sockaddr_vm);
        default:
                assert_not_reached();
        }
}
 
int socket_ioctl_fd(void) {
        int fd;
 
        /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
         * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
         * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
         * generic AF_NETLINK. */
 
        fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
        if (fd < 0)
                fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
        if (fd < 0)
                return -errno;
 
        return fd;
}
 
int sockaddr_un_unlink(const struct sockaddr_un *sa) {
        const char *p, * nul;
 
        assert(sa);
 
        if (sa->sun_family != AF_UNIX)
                return -EPROTOTYPE;
 
        if (sa->sun_path[0] == 0) /* Nothing to do for abstract sockets */
                return 0;
 
        /* The path in .sun_path is not necessarily NUL terminated. Let's fix that. */
        nul = memchr(sa->sun_path, 0, sizeof(sa->sun_path));
        if (nul)
                p = sa->sun_path;
        else
                p = memdupa_suffix0(sa->sun_path, sizeof(sa->sun_path));
 
        if (unlink(p) < 0)
                return -errno;
 
        return 1;
}
 
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path) {
        size_t l;
 
        assert(ret);
        assert(path);
 
        /* Initialize ret->sun_path from the specified argument. This will interpret paths starting with '@' as
         * abstract namespace sockets, and those starting with '/' as regular filesystem sockets. It won't accept
         * anything else (i.e. no relative paths), to avoid ambiguities. Note that this function cannot be used to
         * reference paths in the abstract namespace that include NUL bytes in the name. */
 
        l = strlen(path);
        if (l < 2)
                return -EINVAL;
        if (!IN_SET(path[0], '/', '@'))
                return -EINVAL;
 
        /* Don't allow paths larger than the space in sockaddr_un. Note that we are a tiny bit more restrictive than
         * the kernel is: we insist on NUL termination (both for abstract namespace and regular file system socket
         * addresses!), which the kernel doesn't. We do this to reduce chance of incompatibility with other apps that
         * do not expect non-NUL terminated file system path. */
        if (l+1 > sizeof(ret->sun_path))
                return path[0] == '@' ? -EINVAL : -ENAMETOOLONG; /* return a recognizable error if this is
                                                                  * too long to fit into a sockaddr_un, but
                                                                  * is a file system path, and thus might be
                                                                  * connectible via O_PATH indirection. */
 
        *ret = (struct sockaddr_un) {
                .sun_family = AF_UNIX,
        };
 
        if (path[0] == '@') {
                /* Abstract namespace socket */
                memcpy(ret->sun_path + 1, path + 1, l); /* copy *with* trailing NUL byte */
                return (int) (offsetof(struct sockaddr_un, sun_path) + l); /* 🔥 *don't* 🔥 include trailing NUL in size */
 
        } else {
                assert(path[0] == '/');
 
                /* File system socket */
                memcpy(ret->sun_path, path, l + 1); /* copy *with* trailing NUL byte */
                return (int) (offsetof(struct sockaddr_un, sun_path) + l + 1); /* include trailing NUL in size */
        }
}
 
int getsockopt_int(int fd, int level, int optname, int *ret) {
        int v;
        socklen_t sl = sizeof(v);
 
        assert(fd >= 0);
        assert(ret);
 
        if (getsockopt(fd, level, optname, &v, &sl) < 0)
                return negative_errno();
        if (sl != sizeof(v))
                return -EIO;
 
        *ret = v;
        return 0;
}
 
int socket_bind_to_ifname(int fd, const char *ifname) {
        assert(fd >= 0);
 
        /* Call with NULL to drop binding */
 
        return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen_ptr(ifname)));
}
 
int socket_bind_to_ifindex(int fd, int ifindex) {
        assert(fd >= 0);
 
        if (ifindex <= 0)
                /* Drop binding */
                return RET_NERRNO(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, NULL, 0));
 
        return setsockopt_int(fd, SOL_SOCKET, SO_BINDTOIFINDEX, ifindex);
}
 
int socket_autobind(int fd, char **ret_name) {
        _cleanup_free_ char *name = NULL;
        uint64_t random;
        int r;
 
        /* Generate a random abstract socket name and bind fd to it. This is modeled after the kernel
         * "autobind" feature, but uses 64-bit random number internally. */
 
        assert(fd >= 0);
 
        random = random_u64();
 
        if (asprintf(&name, "@%" PRIu64, random) < 0)
                return -ENOMEM;
 
        union sockaddr_union sa;
        assert_cc(DECIMAL_STR_MAX(uint64_t) < sizeof(sa.un.sun_path));
 
        r = sockaddr_un_set_path(&sa.un, name);
        if (r < 0)
                return r;
 
        if (bind(fd, &sa.sa, r) < 0)
                return -errno;
 
        if (ret_name)
                *ret_name = TAKE_PTR(name);
        return 0;
}
 
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags) {
        ssize_t n;
 
        /* A wrapper around recvmsg() that checks for MSG_CTRUNC and MSG_TRUNC, and turns them into an error,
         * in a reasonably safe way, closing any received fds in the error path.
         *
         * Note that unlike our usual coding style this might modify *msg on failure. */
 
        assert(sockfd >= 0);
        assert(msg);
 
        n = recvmsg(sockfd, msg, flags);
        if (n < 0)
                return -errno;
 
        if (FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ||
            (!FLAGS_SET(flags, MSG_PEEK) && FLAGS_SET(msg->msg_flags, MSG_TRUNC))) {
                cmsg_close_all(msg);
                return FLAGS_SET(msg->msg_flags, MSG_CTRUNC) ? -ECHRNG : -EXFULL;
        }
 
        return n;
}
 
int socket_get_family(int fd) {
        int af;
        socklen_t sl = sizeof(af);
 
        if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &af, &sl) < 0)
                return -errno;
 
        if (sl != sizeof(af))
                return -EINVAL;
 
        return af;
}
 
int socket_set_recvpktinfo(int fd, int af, bool b) {
 
        if (af == AF_UNSPEC) {
                af = socket_get_family(fd);
                if (af < 0)
                        return af;
        }
 
        switch (af) {
 
        case AF_INET:
                return setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, b);
 
        case AF_INET6:
                return setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, b);
 
        case AF_NETLINK:
                return setsockopt_int(fd, SOL_NETLINK, NETLINK_PKTINFO, b);
 
        case AF_PACKET:
                return setsockopt_int(fd, SOL_PACKET, PACKET_AUXDATA, b);
 
        default:
                return -EAFNOSUPPORT;
        }
}
 
int socket_set_unicast_if(int fd, int af, int ifi) {
        be32_t ifindex_be = htobe32(ifi);
 
        if (af == AF_UNSPEC) {
                af = socket_get_family(fd);
                if (af < 0)
                        return af;
        }
 
        switch (af) {
 
        case AF_INET:
                return RET_NERRNO(setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
 
        case AF_INET6:
                return RET_NERRNO(setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be)));
 
        default:
                return -EAFNOSUPPORT;
        }
}
 
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val) {
        if (af == AF_UNSPEC) {
                af = socket_get_family(fd);
                if (af < 0)
                        return af;
        }
 
        switch (af) {
 
        case AF_INET:
                return setsockopt_int(fd, IPPROTO_IP, opt_ipv4, val);
 
        case AF_INET6:
                return setsockopt_int(fd, IPPROTO_IPV6, opt_ipv6, val);
 
        default:
                return -EAFNOSUPPORT;
        }
}
 
int socket_get_mtu(int fd, int af, size_t *ret) {
        int mtu, r;
 
        assert(ret);
 
        if (af == AF_UNSPEC) {
                af = socket_get_family(fd);
                if (af < 0)
                        return af;
        }
 
        switch (af) {
 
        case AF_INET:
                r = getsockopt_int(fd, IPPROTO_IP, IP_MTU, &mtu);
                break;
 
        case AF_INET6:
                r = getsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, &mtu);
                break;
 
        default:
                return -EAFNOSUPPORT;
        }
 
        if (r < 0)
                return r;
        if (mtu <= 0)
                return -EINVAL;
 
        *ret = (size_t) mtu;
        return 0;
}
 
static int connect_unix_path_simple(int fd, const char *path) {
        union sockaddr_union sa = {
                .un.sun_family = AF_UNIX,
        };
        size_t l;
 
        assert(fd >= 0);
        assert(path);
 
        l = strlen(path);
        assert(l > 0);
        assert(l < sizeof(sa.un.sun_path));
 
        memcpy(sa.un.sun_path, path, l + 1);
        return RET_NERRNO(connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + l + 1));
}
 
static int connect_unix_inode(int fd, int inode_fd) {
        assert(fd >= 0);
        assert(inode_fd >= 0);
 
        return connect_unix_path_simple(fd, FORMAT_PROC_FD_PATH(inode_fd));
}
 
int connect_unix_path(int fd, int dir_fd, const char *path) {
        _cleanup_close_ int inode_fd = -EBADF;
 
        assert(fd >= 0);
        assert(wildcard_fd_is_valid(dir_fd));
 
        /* Connects to the specified AF_UNIX socket in the file system. Works around the 108 byte size limit
         * in sockaddr_un, by going via O_PATH if needed. This hence works for any kind of path. */
 
        if (!path) {
                if (dir_fd < 0)
                        return -EISDIR;
 
                return connect_unix_inode(fd, dir_fd); /* If no path is specified, then dir_fd refers to the socket inode to connect to. */
        }
 
        /* Refuse zero length path early, to make sure AF_UNIX stack won't mistake this for an abstract
         * namespace path, since first char is NUL */
        if (isempty(path))
                return -EINVAL;
 
        /* Shortcut for the simple case */
        if (dir_fd == AT_FDCWD && strlen(path) < sizeof_field(struct sockaddr_un, sun_path))
                return connect_unix_path_simple(fd, path);
 
        /* If dir_fd is specified, then we need to go the indirect O_PATH route, because connectat() does not
         * exist. If the path is too long, we also need to take the indirect route, since we can't fit this
         * into a sockaddr_un directly. */
 
        if (dir_fd == XAT_FDROOT) {
                _cleanup_free_ char *j = strjoin("/", path);
                if (!j)
                        return -ENOMEM;
 
                inode_fd = open(j, O_PATH|O_CLOEXEC);
        } else
                inode_fd = openat(dir_fd, path, O_PATH|O_CLOEXEC);
        if (inode_fd < 0)
                return -errno;
 
        return connect_unix_inode(fd, inode_fd);
}
 
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
        struct sockaddr_un un;
        int r;
 
        assert(ret_address);
        assert(s);
 
        if (!IN_SET(*s, '/', '@'))
                return -EPROTO;
 
        r = sockaddr_un_set_path(&un, s);
        if (r < 0)
                return r;
 
        *ret_address = (SocketAddress) {
                .sockaddr.un = un,
                .size = r,
        };
 
        return 0;
}
 
int socket_address_equal_unix(const char *a, const char *b) {
        SocketAddress socket_a, socket_b;
        int r;
 
        assert(a);
        assert(b);
 
        r = socket_address_parse_unix(&socket_a, a);
        if (r < 0)
                return r;
 
        r = socket_address_parse_unix(&socket_b, b);
        if (r < 0)
                return r;
 
        return sockaddr_equal(&socket_a.sockaddr, &socket_b.sockaddr);
}
 
int vsock_parse_port(const char *s, unsigned *ret) {
        int r;
 
        assert(ret);
 
        if (!s)
                return -EINVAL;
 
        unsigned u;
        r = safe_atou(s, &u);
        if (r < 0)
                return r;
 
        /* Port 0 is apparently valid and not special in AF_VSOCK (unlike on IP). But VMADDR_PORT_ANY
         * (UINT32_MAX) is. Hence refuse that. */
 
        if (u == VMADDR_PORT_ANY)
                return -EINVAL;
 
        *ret = u;
        return 0;
}
 
int vsock_parse_cid(const char *s, unsigned *ret) {
        assert(ret);
 
        if (!s)
                return -EINVAL;
 
        /* Parsed an AF_VSOCK "CID". This is a 32bit entity, and the usual type is "unsigned". We recognize
         * the four special CIDs as strings, and otherwise parse the numeric CIDs. */
 
        if (streq(s, "hypervisor"))
                *ret = VMADDR_CID_HYPERVISOR;
        else if (streq(s, "local"))
                *ret = VMADDR_CID_LOCAL;
        else if (streq(s, "host"))
                *ret = VMADDR_CID_HOST;
        else if (STR_IN_SET(s, "any", "-1"))
                *ret = VMADDR_CID_ANY;
        else
                return safe_atou(s, ret);
 
        return 0;
}
 
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
        /* AF_VSOCK socket in vsock:cid:port notation */
        _cleanup_free_ char *n = NULL;
        const char *e, *cid_start;
        unsigned port, cid;
        int type, r;
 
        assert(ret_address);
        assert(s);
 
        if ((cid_start = startswith(s, "vsock:")))
                type = 0;
        else if ((cid_start = startswith(s, "vsock-dgram:")))
                type = SOCK_DGRAM;
        else if ((cid_start = startswith(s, "vsock-seqpacket:")))
                type = SOCK_SEQPACKET;
        else if ((cid_start = startswith(s, "vsock-stream:")))
                type = SOCK_STREAM;
        else
                return -EPROTO;
 
        e = strchr(cid_start, ':');
        if (!e)
                return -EINVAL;
 
        r = vsock_parse_port(e+1, &port);
        if (r < 0)
                return r;
 
        n = strndup(cid_start, e - cid_start);
        if (!n)
                return -ENOMEM;
 
        if (isempty(n))
                cid = VMADDR_CID_ANY;
        else {
                r = vsock_parse_cid(n, &cid);
                if (r < 0)
                        return r;
        }
 
        *ret_address = (SocketAddress) {
                .sockaddr.vm = {
                        .svm_family = AF_VSOCK,
                        .svm_cid = cid,
                        .svm_port = port,
                },
                .type = type,
                .size = sizeof(struct sockaddr_vm),
        };
 
        return 0;
}
 
int netlink_socket_get_multicast_groups(int fd, size_t *ret_len, uint32_t **ret_groups) {
        _cleanup_free_ uint32_t *groups = NULL;
        socklen_t len = 0, old_len;
 
        assert(fd >= 0);
 
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, NULL, &len) < 0)
                return -errno;
 
        if (len == 0)
                goto finalize;
 
        groups = new0(uint32_t, len);
        if (!groups)
                return -ENOMEM;
 
        old_len = len;
 
        if (getsockopt(fd, SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, groups, &len) < 0)
                return -errno;
 
        if (old_len != len)
                return -EIO;
 
finalize:
        if (ret_len)
                *ret_len = len;
        if (ret_groups)
                *ret_groups = TAKE_PTR(groups);
 
        return 0;
}
 
int socket_get_cookie(int fd, uint64_t *ret) {
        assert(fd >= 0);
 
        uint64_t cookie = 0;
        socklen_t cookie_len = sizeof(cookie);
        if (getsockopt(fd, SOL_SOCKET, SO_COOKIE, &cookie, &cookie_len) < 0)
                return -errno;
 
        assert(cookie_len == sizeof(cookie));
        if (ret)
                *ret = cookie;
 
        return 0;
}
 
void cmsg_close_all(struct msghdr *mh) {
        assert(mh);
 
        struct cmsghdr *cmsg;
        CMSG_FOREACH(cmsg, mh) {
                if (cmsg->cmsg_level != SOL_SOCKET)
                        continue;
 
                if (cmsg->cmsg_type == SCM_RIGHTS)
                        close_many(CMSG_TYPED_DATA(cmsg, int),
                                   (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
                else if (cmsg->cmsg_type == SCM_PIDFD) {
                        assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
                        safe_close(*CMSG_TYPED_DATA(cmsg, int));
                }
        }
}
 
int tos_to_priority(uint8_t tos) {
        /* Map the IP Precedence (top 3 bits of the TOS field) to Linux internal packet priorities
         * (TC_PRIO_*). This exactly mirrors the standard Linux kernel IP precedence-to-priority mapping
         * (rt_tos2priority) to ensure consistent behavior when explicitly setting SO_PRIORITY. */
        switch (IPTOS_PREC(tos)) {
        case IPTOS_PREC_NETCONTROL:      /* 0xc0 (CS7) - Network Control. Used for infrastructure control (e.g., STP, keepalives). */
        case IPTOS_PREC_INTERNETCONTROL: /* 0xe0 (CS6) - Internetwork Control. Used for routing protocols (e.g., OSPF, BGP) and DHCP. */
                return TC_PRIO_CONTROL;
 
        case IPTOS_PREC_CRITIC_ECP:      /* 0xa0 (CS5) - Critical. Used for delay-sensitive traffic like Voice over IP (VoIP). */
        case IPTOS_PREC_FLASHOVERRIDE:   /* 0x80 (CS4) - Flash Override. Used for interactive video and multimedia. */
                return TC_PRIO_INTERACTIVE;
 
        case IPTOS_PREC_FLASH:           /* 0x60 (CS3) - Flash. Used for broadcast video and call signaling (e.g., SIP). */
        case IPTOS_PREC_IMMEDIATE:       /* 0x40 (CS2) - Immediate. Used for OAM (Operations, Administration, and Management) and transactional data. */
                return TC_PRIO_INTERACTIVE_BULK;
 
        case IPTOS_PREC_PRIORITY:        /* 0x20 (CS1) - Priority. Used for background traffic and bulk data transfers. */
                return TC_PRIO_BULK;
 
        case IPTOS_PREC_ROUTINE:         /* 0x00 (CS0) - Routine. Best effort traffic. */
        default:
                return TC_PRIO_BESTEFFORT;
        }
}
 
int socket_xattr_supported(void) {
        int r;
 
        // FIXME: Drop this check once Linux 7.1 becomes our baseline
 
        static int cached = -1;
        if (cached >= 0)
                return cached;
 
        _cleanup_close_ int fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, /* protocol= */ 0);
        if (fd < 0)
                return -errno;
 
        /* Old kernels return EPERM. But let's also check for more appropriate error codes, to be friendly to
         * seccomp policies */
        r = xsetxattr(fd, /* path= */ NULL, AT_EMPTY_PATH, "user.testxxx", "1");
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || r == -EPERM)
                return (cached = false);
        if (r < 0)
                return log_debug_errno(r, "Failed to set test xattr on socket: %m");
 
        return (cached = true);
}