2 * Copyright © 2012 Collabora, Ltd.
4 * Permission to use, copy, modify, distribute, and sell this software and its
5 * documentation for any purpose is hereby granted without fee, provided that
6 * the above copyright notice appear in all copies and that both that copyright
7 * notice and this permission notice appear in supporting documentation, and
8 * that the name of the copyright holders not be used in advertising or
9 * publicity pertaining to distribution of the software without specific,
10 * written prior permission. The copyright holders make no representations
11 * about the suitability of this software for any purpose. It is provided "as
12 * is" without express or implied warranty.
14 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
25 #include <sys/types.h>
26 #include <sys/socket.h>
30 #include <sys/epoll.h>
32 #include "../config.h"
33 #include "wayland-os.h"
36 set_cloexec_or_close(int fd)
43 flags = fcntl(fd, F_GETFD);
47 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
58 wl_os_socket_cloexec(int domain, int type, int protocol)
62 fd = socket(domain, type | SOCK_CLOEXEC, protocol);
68 fd = socket(domain, type, protocol);
69 return set_cloexec_or_close(fd);
73 wl_os_dupfd_cloexec(int fd, long minfd)
77 newfd = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
83 newfd = fcntl(fd, F_DUPFD, minfd);
84 return set_cloexec_or_close(newfd);
88 recvmsg_cloexec_fallback(int sockfd, struct msghdr *msg, int flags)
96 len = recvmsg(sockfd, msg, flags);
100 if (!msg->msg_control || msg->msg_controllen == 0)
103 cmsg = CMSG_FIRSTHDR(msg);
104 for (; cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) {
105 if (cmsg->cmsg_level != SOL_SOCKET ||
106 cmsg->cmsg_type != SCM_RIGHTS)
109 data = CMSG_DATA(cmsg);
110 end = (int *)(data + cmsg->cmsg_len - CMSG_LEN(0));
111 for (fd = (int *)data; fd < end; ++fd)
112 *fd = set_cloexec_or_close(*fd);
119 wl_os_recvmsg_cloexec(int sockfd, struct msghdr *msg, int flags)
123 len = recvmsg(sockfd, msg, flags | MSG_CMSG_CLOEXEC);
129 return recvmsg_cloexec_fallback(sockfd, msg, flags);
133 wl_os_epoll_create_cloexec(void)
138 fd = epoll_create1(EPOLL_CLOEXEC);
145 fd = epoll_create(1);
146 return set_cloexec_or_close(fd);
150 wl_os_accept_cloexec(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
155 fd = accept4(sockfd, addr, addrlen, SOCK_CLOEXEC);
162 fd = accept(sockfd, addr, addrlen);
163 return set_cloexec_or_close(fd);