31#pragma clang diagnostic push
32#pragma clang diagnostic ignored "-Wreserved-id-macro"
38#pragma clang diagnostic pop
41#if defined(__FreeBSD__) || defined(__DragonFly__)
46#if !defined(O_TMPFILE) && !defined(__FreeBSD__)
47#define O_TMPFILE (020000000 | O_DIRECTORY)
51#include <sys/socket.h>
64#include <winpr/wtypes.h>
65#include <uwac/config.h>
68#include "uwac-utils.h"
70static int set_cloexec_or_close(
int fd)
77 flags = fcntl(fd, F_GETFD);
82 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
91int uwac_os_socket_cloexec(
int domain,
int type,
int protocol)
94 fd = socket(domain, type | SOCK_CLOEXEC, protocol);
102 fd = socket(domain, type, protocol);
103 return set_cloexec_or_close(fd);
106int uwac_os_dupfd_cloexec(
int fd,
long minfd)
109 newfd = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
117 newfd = fcntl(fd, F_DUPFD, minfd);
118 return set_cloexec_or_close(newfd);
121static ssize_t recvmsg_cloexec_fallback(
int sockfd,
struct msghdr* msg,
int flags)
124 struct cmsghdr* cmsg =
nullptr;
125 unsigned char* data =
nullptr;
127 len = recvmsg(sockfd, msg, flags);
132 if (!msg->msg_control || msg->msg_controllen == 0)
135 cmsg = CMSG_FIRSTHDR(msg);
137 for (; cmsg !=
nullptr; cmsg = CMSG_NXTHDR(msg, cmsg))
139 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
142 data = CMSG_DATA(cmsg);
143 end = (
int*)(data + cmsg->cmsg_len - CMSG_LEN(0));
145 for (
int* fd = (
int*)data; fd < end; ++fd)
146 *fd = set_cloexec_or_close(*fd);
152ssize_t uwac_os_recvmsg_cloexec(
int sockfd,
struct msghdr* msg,
int flags)
155 len = recvmsg(sockfd, msg, flags | MSG_CMSG_CLOEXEC);
163 return recvmsg_cloexec_fallback(sockfd, msg, flags);
166int uwac_os_epoll_create_cloexec(
void)
170 fd = epoll_create1(EPOLL_CLOEXEC);
179 fd = epoll_create(1);
180 return set_cloexec_or_close(fd);
183static int secure_mkstemp(
char* tmpname)
185 const mode_t mask = umask(S_IRWXU);
186 int fd = mkstemp(tmpname);
191static int create_tmpfile_cloexec(
char* tmpname)
195 fd = shm_open(SHM_ANON, O_CREAT | O_RDWR, 0600);
196#elif defined(UWAC_HAVE_MKOSTEMP)
197 fd = mkostemp(tmpname, O_CLOEXEC);
203 fd = secure_mkstemp(tmpname);
207 fd = set_cloexec_or_close(fd);
236int uwac_create_anonymous_file(off_t size)
238 static const char template[] =
"/weston-shared-XXXXXX";
240 char* name =
nullptr;
244 const char* path = getenv(
"XDG_RUNTIME_DIR");
253 fd = open(path, O_TMPFILE | O_RDWR | O_EXCL, 0600);
265 length = strlen(path) +
sizeof(
template);
266 name = xmalloc(length);
271 (void)snprintf(name, length,
"%s%s", path,
template);
272 fd = create_tmpfile_cloexec(name);
279#ifdef UWAC_HAVE_POSIX_FALLOCATE
280 ret = posix_fallocate(fd, 0, size);
290 ret = ftruncate(fd, size);