Simplify dependency checking logic.
[oweals/dinit.git] / src / dinit-socket.h
1 #ifndef _DINIT_SOCKET_H_INCLUDED
2 #define _DINIT_SOCKET_H_INCLUDED
3
4 #include <sys/socket.h>
5 #include <fcntl.h>
6
7 namespace {
8 #if !defined(SOCK_NONBLOCK) && !defined(SOCK_CLOEXEC)
9     // make our own accept4 on systems that don't have it:
10     constexpr int SOCK_NONBLOCK = 1;
11     constexpr int SOCK_CLOEXEC = 2;
12     inline int dinit_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
13     {
14         int fd = accept(sockfd, addr, addrlen);
15         if (fd == -1) {
16             return -1;
17         }
18
19         if (flags & SOCK_CLOEXEC)  fcntl(fd, F_SETFD, FD_CLOEXEC);
20         if (flags & SOCK_NONBLOCK) fcntl(fd, F_SETFL, O_NONBLOCK);
21         return fd;
22     }
23
24     inline int dinit_socket(int domain, int type, int protocol, int flags)
25     {
26         int fd = socket(domain, type, protocol);
27         if (fd == -1) {
28             return -1;
29         }
30
31         if (flags & SOCK_CLOEXEC)  fcntl(fd, F_SETFD, FD_CLOEXEC);
32         if (flags & SOCK_NONBLOCK) fcntl(fd, F_SETFL, O_NONBLOCK);
33         return fd;
34     }
35
36     inline int dinit_socketpair(int domain, int type, int protocol, int socket_vector[2], int flags)
37     {
38         int r = socketpair(domain, type, protocol, socket_vector);
39         if (r == -1) {
40             return -1;
41         }
42
43         if (flags & SOCK_CLOEXEC) {
44             fcntl(socket_vector[0], F_SETFD, FD_CLOEXEC);
45             fcntl(socket_vector[1], F_SETFD, FD_CLOEXEC);
46         }
47         if (flags & SOCK_NONBLOCK) {
48             fcntl(socket_vector[0], F_SETFL, O_NONBLOCK);
49             fcntl(socket_vector[1], F_SETFL, O_NONBLOCK);
50         }
51         return 0;
52     }
53
54 #else
55     inline int dinit_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
56     {
57         return accept4(sockfd, addr, addrlen, flags);
58     }
59
60     inline int dinit_socket(int domain, int type, int protocol, int flags)
61     {
62         return socket(domain, type | flags, protocol);
63     }
64
65     inline int dinit_socketpair(int domain, int type, int protocol, int socket_vector[2], int flags)
66     {
67         return socketpair(domain, type | flags, protocol, socket_vector);
68     }
69 #endif
70 }
71
72 #endif