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 <uwac/config.h>
67#include "uwac-utils.h"
69static int set_cloexec_or_close(
int fd)
76 flags = fcntl(fd, F_GETFD);
81 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
90int uwac_os_socket_cloexec(
int domain,
int type,
int protocol)
93 fd = socket(domain, type | SOCK_CLOEXEC, protocol);
101 fd = socket(domain, type, protocol);
102 return set_cloexec_or_close(fd);
105int uwac_os_dupfd_cloexec(
int fd,
long minfd)
108 newfd = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
116 newfd = fcntl(fd, F_DUPFD, minfd);
117 return set_cloexec_or_close(newfd);
120static ssize_t recvmsg_cloexec_fallback(
int sockfd,
struct msghdr* msg,
int flags)
123 struct cmsghdr* cmsg = NULL;
124 unsigned char* data = NULL;
126 len = recvmsg(sockfd, msg, flags);
131 if (!msg->msg_control || msg->msg_controllen == 0)
134 cmsg = CMSG_FIRSTHDR(msg);
136 for (; cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
138 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
141 data = CMSG_DATA(cmsg);
142 end = (
int*)(data + cmsg->cmsg_len - CMSG_LEN(0));
144 for (
int* fd = (
int*)data; fd < end; ++fd)
145 *fd = set_cloexec_or_close(*fd);
151ssize_t uwac_os_recvmsg_cloexec(
int sockfd,
struct msghdr* msg,
int flags)
154 len = recvmsg(sockfd, msg, flags | MSG_CMSG_CLOEXEC);
162 return recvmsg_cloexec_fallback(sockfd, msg, flags);
165int uwac_os_epoll_create_cloexec(
void)
169 fd = epoll_create1(EPOLL_CLOEXEC);
178 fd = epoll_create(1);
179 return set_cloexec_or_close(fd);
182static int secure_mkstemp(
char* tmpname)
184 const mode_t mask = umask(S_IRWXU);
185 int fd = mkstemp(tmpname);
190static int create_tmpfile_cloexec(
char* tmpname)
194 fd = shm_open(SHM_ANON, O_CREAT | O_RDWR, 0600);
195#elif defined(UWAC_HAVE_MKOSTEMP)
196 fd = mkostemp(tmpname, O_CLOEXEC);
202 fd = secure_mkstemp(tmpname);
206 fd = set_cloexec_or_close(fd);
235int uwac_create_anonymous_file(off_t size)
237 static const char template[] =
"/weston-shared-XXXXXX";
243 const char* path = getenv(
"XDG_RUNTIME_DIR");
252 fd = open(path, O_TMPFILE | O_RDWR | O_EXCL, 0600);
264 length = strlen(path) +
sizeof(
template);
265 name = xmalloc(length);
270 (void)snprintf(name, length,
"%s%s", path,
template);
271 fd = create_tmpfile_cloexec(name);
278#ifdef UWAC_HAVE_POSIX_FALLOCATE
279 ret = posix_fallocate(fd, 0, size);
289 ret = ftruncate(fd, size);