safely handle failure to open hosts, services, resolv.conf files
[musl] / src / network / res_msend.c
1 #include <sys/socket.h>
2 #include <netinet/in.h>
3 #include <netdb.h>
4 #include <arpa/inet.h>
5 #include <stdint.h>
6 #include <string.h>
7 #include <poll.h>
8 #include <time.h>
9 #include <ctype.h>
10 #include <unistd.h>
11 #include <errno.h>
12 #include <pthread.h>
13 #include "stdio_impl.h"
14 #include "syscall.h"
15 #include "lookup.h"
16
17 static void cleanup(void *p)
18 {
19         __syscall(SYS_close, (intptr_t)p);
20 }
21
22 static unsigned long mtime()
23 {
24         struct timespec ts;
25         clock_gettime(CLOCK_REALTIME, &ts);
26         return (unsigned long)ts.tv_sec * 1000
27                 + ts.tv_nsec / 1000000;
28 }
29
30 int __res_msend(int nqueries, const unsigned char *const *queries,
31         const int *qlens, unsigned char *const *answers, int *alens, int asize)
32 {
33         int fd;
34         FILE *f, _f;
35         unsigned char _buf[256];
36         char line[64], *s, *z;
37         int timeout = 5000, attempts = 2, retry_interval, servfail_retry;
38         union {
39                 struct sockaddr_in sin;
40                 struct sockaddr_in6 sin6;
41         } sa = {0}, ns[3] = {{0}};
42         socklen_t sl = sizeof sa.sin;
43         int nns = 0;
44         int family = AF_INET;
45         int rlen;
46         int next;
47         int i, j;
48         int cs;
49         struct pollfd pfd;
50         unsigned long t0, t1, t2;
51         struct address iplit;
52
53         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
54
55         /* Get nameservers from resolv.conf, fallback to localhost */
56         f = __fopen_rb_ca("/etc/resolv.conf", &_f, _buf, sizeof _buf);
57         if (!f) switch (errno) {
58         case ENOENT:
59         case ENOTDIR:
60         case EACCES:
61                 goto no_resolv_conf;
62         default:
63                 return -1;
64         }
65         for (nns=0; nns<3 && fgets(line, sizeof line, f); ) {
66                 if (!strncmp(line, "options", 7) && isspace(line[7])) {
67                         unsigned long x;
68                         char *p, *z;
69                         p = strstr(line, "timeout:");
70                         if (p && isdigit(p[8])) {
71                                 p += 8;
72                                 x = strtoul(p, &z, 10);
73                                 if (z != p) timeout = x < 30 ? x*1000 : 30000;
74                         }
75                         p = strstr(line, "attempts:");
76                         if (p && isdigit(p[9])) {
77                                 p += 9;
78                                 x = strtoul(p, &z, 10);
79                                 if (z != p) attempts = x < 10 ? x : 10;
80                                 if (!attempts) attempts = 1;
81                         }
82                 }
83                 if (strncmp(line, "nameserver", 10) || !isspace(line[10]))
84                         continue;
85                 for (s=line+11; isspace(*s); s++);
86                 for (z=s; *z && !isspace(*z); z++);
87                 *z=0;
88
89                 if (__lookup_ipliteral(&iplit, s, AF_UNSPEC)>0) {
90                         if (iplit.family == AF_INET) {
91                                 memcpy(&ns[nns].sin.sin_addr, iplit.addr, 4);
92                                 ns[nns].sin.sin_port = htons(53);
93                                 ns[nns++].sin.sin_family = AF_INET;
94                         } else {
95                                 sl = sizeof sa.sin6;
96                                 memcpy(&ns[nns].sin6.sin6_addr, iplit.addr, 16);
97                                 ns[nns].sin6.sin6_port = htons(53);
98                                 ns[nns].sin6.sin6_scope_id = iplit.scopeid;
99                                 ns[nns++].sin6.sin6_family = family = AF_INET6;
100                         }
101                 }
102         }
103         __fclose_ca(f);
104 no_resolv_conf:
105         if (!nns) {
106                 ns[0].sin.sin_family = AF_INET;
107                 ns[0].sin.sin_port = htons(53);
108                 ns[0].sin.sin_addr.s_addr = htonl(0x7f000001);
109                 nns=1;
110         }
111
112         /* Get local address and open/bind a socket */
113         sa.sin.sin_family = family;
114         fd = socket(family, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
115
116         /* Handle case where system lacks IPv6 support */
117         if (fd < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
118                 fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
119                 family = AF_INET;
120         }
121         if (fd < 0 || bind(fd, (void *)&sa, sl) < 0) return -1;
122
123         /* Past this point, there are no errors. Each individual query will
124          * yield either no reply (indicated by zero length) or an answer
125          * packet which is up to the caller to interpret. */
126
127         pthread_cleanup_push(cleanup, (void *)(intptr_t)fd);
128         pthread_setcancelstate(cs, 0);
129
130         /* Convert any IPv4 addresses in a mixed environment to v4-mapped */
131         if (family == AF_INET6) {
132                 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &(int){0}, sizeof 0);
133                 for (i=0; i<nns; i++) {
134                         if (ns[i].sin.sin_family != AF_INET) continue;
135                         memcpy(ns[i].sin6.sin6_addr.s6_addr+12,
136                                 &ns[i].sin.sin_addr, 4);
137                         memcpy(ns[i].sin6.sin6_addr.s6_addr,
138                                 "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
139                         ns[i].sin6.sin6_family = AF_INET6;
140                         ns[i].sin6.sin6_flowinfo = 0;
141                         ns[i].sin6.sin6_scope_id = 0;
142                 }
143         }
144
145         memset(alens, 0, sizeof *alens * nqueries);
146
147         pfd.fd = fd;
148         pfd.events = POLLIN;
149         retry_interval = timeout / attempts;
150         next = 0;
151         t0 = t2 = mtime();
152         t1 = t2 - retry_interval;
153
154         for (; t2-t0 < timeout; t2=mtime()) {
155                 if (t2-t1 >= retry_interval) {
156                         /* Query all configured namservers in parallel */
157                         for (i=0; i<nqueries; i++)
158                                 if (!alens[i])
159                                         for (j=0; j<nns; j++)
160                                                 sendto(fd, queries[i],
161                                                         qlens[i], MSG_NOSIGNAL,
162                                                         (void *)&ns[j], sl);
163                         t1 = t2;
164                         servfail_retry = 2 * nqueries;
165                 }
166
167                 /* Wait for a response, or until time to retry */
168                 if (poll(&pfd, 1, t1+retry_interval-t2) <= 0) continue;
169
170                 while ((rlen = recvfrom(fd, answers[next], asize, 0,
171                   (void *)&sa, (socklen_t[1]){sl})) >= 0) {
172
173                         /* Ignore non-identifiable packets */
174                         if (rlen < 4) continue;
175
176                         /* Ignore replies from addresses we didn't send to */
177                         for (j=0; j<nns && memcmp(ns+j, &sa, sl); j++);
178                         if (j==nns) continue;
179
180                         /* Find which query this answer goes with, if any */
181                         for (i=next; i<nqueries && (
182                                 answers[next][0] != queries[i][0] ||
183                                 answers[next][1] != queries[i][1] ); i++);
184                         if (i==nqueries) continue;
185                         if (alens[i]) continue;
186
187                         /* Only accept positive or negative responses;
188                          * retry immediately on server failure, and ignore
189                          * all other codes such as refusal. */
190                         switch (answers[next][3] & 15) {
191                         case 0:
192                         case 3:
193                                 break;
194                         case 2:
195                                 if (servfail_retry && servfail_retry--)
196                                         sendto(fd, queries[i],
197                                                 qlens[i], MSG_NOSIGNAL,
198                                                 (void *)&ns[j], sl);
199                         default:
200                                 continue;
201                         }
202
203                         /* Store answer in the right slot, or update next
204                          * available temp slot if it's already in place. */
205                         alens[i] = rlen;
206                         if (i == next)
207                                 for (; next<nqueries && alens[next]; next++);
208                         else
209                                 memcpy(answers[i], answers[next], rlen);
210
211                         if (next == nqueries) goto out;
212                 }
213         }
214 out:
215         pthread_cleanup_pop(1);
216
217         return 0;
218 }