uloop: ensure SIGCHLD is properly received on mac os x
[project/libubox.git] / usock.c
1 #include <sys/types.h>
2 #include <sys/socket.h>
3 #include <sys/un.h>
4 #include <netdb.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <fcntl.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <stdbool.h>
11
12 #include "usock.h"
13
14 static void usock_set_flags(int sock, unsigned int type)
15 {
16 if (!(type & USOCK_NOCLOEXEC))
17 fcntl(sock, F_SETFD, fcntl(sock, F_GETFD) | FD_CLOEXEC);
18
19 if (type & USOCK_NONBLOCK)
20 fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK);
21 }
22
23 static int usock_connect(struct sockaddr *sa, int sa_len, int family, int socktype, bool server)
24 {
25 int sock;
26
27 sock = socket(family, socktype, 0);
28 if (sock < 0)
29 return -1;
30
31 if (server) {
32 const int one = 1;
33 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
34
35 if (!bind(sock, sa, sa_len) &&
36 (socktype != SOCK_STREAM || !listen(sock, SOMAXCONN)))
37 return sock;
38 } else {
39 if (!connect(sock, sa, sa_len) || errno == EINPROGRESS)
40 return sock;
41 }
42
43 close(sock);
44 return -1;
45 }
46
47 static int usock_unix(const char *host, int socktype, bool server)
48 {
49 struct sockaddr_un sun = {.sun_family = AF_UNIX};
50
51 if (strlen(host) >= sizeof(sun.sun_path)) {
52 errno = EINVAL;
53 return -1;
54 }
55 strcpy(sun.sun_path, host);
56
57 return usock_connect((struct sockaddr*)&sun, sizeof(sun), AF_UNIX, socktype, server);
58 }
59
60 static int usock_inet(int type, const char *host, const char *service, int socktype, bool server)
61 {
62 struct addrinfo *result, *rp;
63 struct addrinfo hints = {
64 .ai_family = (type & USOCK_IPV6ONLY) ? AF_INET6 :
65 (type & USOCK_IPV4ONLY) ? AF_INET : AF_UNSPEC,
66 .ai_socktype = socktype,
67 .ai_flags = AI_ADDRCONFIG
68 | ((type & USOCK_SERVER) ? AI_PASSIVE : 0)
69 | ((type & USOCK_NUMERIC) ? AI_NUMERICHOST : 0),
70 };
71 int sock = -1;
72
73 if (getaddrinfo(host, service, &hints, &result))
74 return -1;
75
76 for (rp = result; rp != NULL; rp = rp->ai_next) {
77 sock = usock_connect(rp->ai_addr, rp->ai_addrlen, rp->ai_family, socktype, server);
78 if (sock >= 0)
79 break;
80 }
81
82 freeaddrinfo(result);
83 return sock;
84 }
85
86 int usock(int type, const char *host, const char *service) {
87 int socktype = ((type & 0xff) == USOCK_TCP) ? SOCK_STREAM : SOCK_DGRAM;
88 bool server = !!(type & USOCK_SERVER);
89 int sock;
90
91 if (type & USOCK_UNIX)
92 sock = usock_unix(host, socktype, server);
93 else
94 sock = usock_inet(type, host, service, socktype, server);
95
96 if (sock < 0)
97 return -1;
98
99 usock_set_flags(sock, type);
100 return sock;
101 }