31#pragma clang diagnostic push
32#pragma clang diagnostic ignored "-Wreserved-id-macro"
38#pragma clang diagnostic pop
46#include <sys/socket.h>
59#include <winpr/wtypes.h>
60#include <uwac/config.h>
63#include "uwac-utils.h"
65static int set_cloexec_or_close(
int fd)
72 flags = fcntl(fd, F_GETFD);
77 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
86int uwac_os_socket_cloexec(
int domain,
int type,
int protocol)
89 fd = socket(domain, type | SOCK_CLOEXEC, protocol);
97 fd = socket(domain, type, protocol);
98 return set_cloexec_or_close(fd);
101int uwac_os_dupfd_cloexec(
int fd,
long minfd)
104 newfd = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
112 newfd = fcntl(fd, F_DUPFD, minfd);
113 return set_cloexec_or_close(newfd);
116static ssize_t recvmsg_cloexec_fallback(
int sockfd,
struct msghdr* msg,
int flags)
119 struct cmsghdr* cmsg =
nullptr;
120 unsigned char* data =
nullptr;
122 len = recvmsg(sockfd, msg, flags);
127 if (!msg->msg_control || msg->msg_controllen == 0)
130 cmsg = CMSG_FIRSTHDR(msg);
132 for (; cmsg !=
nullptr; cmsg = CMSG_NXTHDR(msg, cmsg))
134 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
137 data = CMSG_DATA(cmsg);
138 end = (
int*)(data + cmsg->cmsg_len - CMSG_LEN(0));
140 for (
int* fd = (
int*)data; fd < end; ++fd)
141 *fd = set_cloexec_or_close(*fd);
147ssize_t uwac_os_recvmsg_cloexec(
int sockfd,
struct msghdr* msg,
int flags)
150 len = recvmsg(sockfd, msg, flags | MSG_CMSG_CLOEXEC);
158 return recvmsg_cloexec_fallback(sockfd, msg, flags);
161int uwac_os_epoll_create_cloexec(
void)
165 fd = epoll_create1(EPOLL_CLOEXEC);
174 fd = epoll_create(1);
175 return set_cloexec_or_close(fd);
178static int secure_mkstemp(
char* tmpname)
180 const mode_t mask = umask(S_IRWXU);
181 int fd = mkstemp(tmpname);
186static int create_tmpfile_cloexec(
char* tmpname)
190 fd = shm_open(SHM_ANON, O_CREAT | O_RDWR, 0600);
191#elif defined(UWAC_HAVE_MKOSTEMP)
192 fd = mkostemp(tmpname, O_CLOEXEC);
198 fd = secure_mkstemp(tmpname);
202 fd = set_cloexec_or_close(fd);
231int uwac_create_anonymous_file(off_t size)
233 static const char template[] =
"/weston-shared-XXXXXX";
235 char* name =
nullptr;
239 const char* path = getenv(
"XDG_RUNTIME_DIR");
248 fd = open(path, O_TMPFILE | O_RDWR | O_EXCL, 0600);
260 length = strlen(path) +
sizeof(
template);
261 name = xmalloc(length);
266 (void)snprintf(name, length,
"%s%s", path,
template);
267 fd = create_tmpfile_cloexec(name);
274#ifdef UWAC_HAVE_POSIX_FALLOCATE
275 ret = posix_fallocate(fd, 0, size);
285 ret = ftruncate(fd, size);