initial check-in, version 0.5.0
[musl] / src / network / __dns.c
1 #include <stdint.h>
2 #include <netdb.h>
3 #include <stdio.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <string.h>
7 #include <sys/socket.h>
8 #include <sys/select.h>
9 #include <sys/time.h>
10 #include <netinet/in.h>
11 #include <time.h>
12 #include <ctype.h>
13 #include <unistd.h>
14 #include "__dns.h"
15 #include "stdio_impl.h"
16
17 #define TIMEOUT 5
18 #define RETRY 1
19 #define PACKET_MAX 512
20 #define PTR_MAX (64 + sizeof ".in-addr.arpa")
21
22 int __dns_doqueries(unsigned char *dest, const char *name, int *rr, int rrcnt)
23 {
24         time_t t0 = time(0);
25         int fd;
26         FILE *f, _f;
27         unsigned char _buf[64];
28         char line[64], *s, *z;
29         union {
30                 struct sockaddr_in sin;
31                 struct sockaddr_in6 sin6;
32         } sa = {0}, ns[3] = {{0}};
33         socklen_t sl;
34         int nns;
35         int family;
36         unsigned char q[280] = "", *r = dest;
37         int ql;
38         int rlen;
39         int got = 0, failed = 0;
40         int errcode = EAI_AGAIN;
41         int i, j;
42         struct timeval tv;
43         fd_set fds;
44         int id;
45
46         /* Construct query template - RR and ID will be filled later */
47         if (strlen(name)-1 >= 254U) return -1;
48         q[2] = q[5] = 1;
49         strcpy(q+13, name);
50         for (i=13; q[i]; i=j+1) {
51                 for (j=i; q[j] && q[j] != '.'; j++);
52                 if (j-i-1u > 62u) return -1;
53                 q[i-1] = j-i;
54         }
55         q[i+3] = 1;
56         ql = i+4;
57
58         /* Make a reasonably unpredictable id */
59         gettimeofday(&tv, 0);
60         id = tv.tv_usec + tv.tv_usec/256 & 0xffff;
61
62         /* Get nameservers from resolv.conf, fallback to localhost */
63         f = __fopen_rb_ca("/etc/resolv.conf", &_f, _buf, sizeof _buf);
64         if (f) for (nns=0; nns<3 && fgets(line, sizeof line, f); ) {
65                 if (strncmp(line, "nameserver", 10) || !isspace(line[10]))
66                         continue;
67                 for (s=line+11; isspace(*s); s++);
68                 for (z=s; *z && !isspace(*z); z++);
69                 *z=0;
70                 if (__ipparse(ns+nns, family, s) < 0) continue;
71                 ns[nns].sin.sin_port = htons(53);
72                 family = ns[nns++].sin.sin_family;
73                 sl = family==AF_INET6 ? sizeof sa.sin6 : sizeof sa.sin;
74         }
75         if (f) __fclose_ca(f);
76         if (!nns) {
77                 ns[0].sin.sin_family = AF_INET;
78                 ns[0].sin.sin_port = htons(53);
79                 nns=1;
80                 sl = sizeof sa.sin;
81         }
82
83         /* Get local address and open/bind a socket */
84         sa.sin.sin_family = family;
85         fd = socket(family, SOCK_DGRAM, 0);
86         if (bind(fd, (void *)&sa, sl) < 0) {
87                 close(fd);
88                 return -1;
89         }
90         /* Nonblocking to work around Linux UDP select bug */
91         fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
92
93         /* Loop until we timeout; break early on success */
94         for (; time(0)-t0 < TIMEOUT; ) {
95
96                 /* Query all configured namservers in parallel */
97                 for (i=0; i<rrcnt; i++) if (rr[i]) for (j=0; j<nns; j++) {
98                         q[0] = id+i >> 8;
99                         q[1] = id+i;
100                         q[ql-3] = rr[i];
101                         sendto(fd, q, ql, MSG_NOSIGNAL, (void *)&ns[j], sl);
102                 }
103
104                 /* Wait for a response, or until time to retry */
105                 FD_ZERO(&fds);
106                 FD_SET(fd, &fds);
107                 tv.tv_sec = RETRY;
108                 tv.tv_usec = 0;
109                 if (select(fd+1, &fds, 0, 0, &tv) <= 0) continue;
110
111                 /* Process any and all replies */
112                 while (got+failed < rrcnt && (rlen = recvfrom(fd, r, 512, 0,
113                         (void *)&sa, (socklen_t[1]){sl})) >= 2)
114                 {
115                         /* Ignore replies from addresses we didn't send to */
116                         for (i=0; i<nns; i++) if (!memcmp(ns+i, &sa, sl)) break;
117                         if (i==nns) continue;
118
119                         /* Compute index of the query from id */
120                         i = r[0]*256+r[1] - id & 0xffff;
121                         if ((unsigned)i >= rrcnt || !rr[i]) continue;
122
123                         /* Interpret the result code */
124                         switch (r[3] & 15) {
125                         case 0:
126                                 got++;
127                                 break;
128                         case 3:
129                                 if (1) errcode = EAI_NONAME; else
130                         default:
131                                 errcode = EAI_FAIL;
132                                 failed++;
133                         }
134
135                         /* Mark this record as answered */
136                         rr[i] = 0;
137                         r += 512;
138                 }
139
140                 /* Check to see if we have answers to all queries */
141                 if (got+failed == rrcnt) break;
142         }
143         close(fd);
144
145         /* Return the number of results, or an error code if none */
146         if (got) return got;
147         return errcode;
148 }
149
150 static void mkptr4(char *s, const unsigned char *ip)
151 {
152         sprintf(s, "%d.%d.%d.%d.in-addr.arpa",
153                 ip[3], ip[2], ip[1], ip[0]);
154 }
155
156 static void mkptr6(char *s, const unsigned char *ip)
157 {
158         static const char xdigits[] = "0123456789abcdef";
159         int i;
160         for (i=15; i>=0; i--) {
161                 *s++ = xdigits[ip[i]&15]; *s++ = '.';
162                 *s++ = xdigits[ip[i]>>4]; *s++ = '.';
163         }
164         strcpy(s, "ip6.arpa");
165 }
166
167 int __dns_query(unsigned char *r, const void *a, int family, int ptr)
168 {
169         char buf[PTR_MAX];
170         int rr[2], rrcnt = 1;
171
172         if (ptr) {
173                 if (family == AF_INET6) mkptr6(buf, a);
174                 else mkptr4(buf, a);
175                 rr[0] = RR_PTR;
176                 a = buf;
177         } else if (family == AF_INET6) {
178                 rr[0] = RR_AAAA;
179         } else {
180                 rr[0] = RR_A;
181                 if (family != AF_INET) rr[rrcnt++] = RR_AAAA;
182         }
183
184         return __dns_doqueries(r, a, rr, rrcnt);
185 }
186
187
188 #define BITOP(a,b,op) \
189  ((a)[(size_t)(b)/(8*sizeof *(a))] op (size_t)1<<((size_t)(b)%(8*sizeof *(a))))
190
191 static int decname(char *s, const unsigned char *b, const unsigned char *p)
192 {
193         /* Remember jump destinations to detect loops and abort */
194         size_t seen[PACKET_MAX/8/sizeof(size_t)] = { 0 };
195         char *sz = s + HOST_NAME_MAX;
196         const unsigned char *pz = b+512;
197         for (;;) {
198                 if (p>=pz) return -1;
199                 else if (*p&0xc0) {
200                         int j = (p[0]&1) | p[1];
201                         if (BITOP(seen, j, &)) return -1;
202                         BITOP(seen, j, |=);
203                         p = b + j;
204                 } else if (*p) {
205                         if (p+*p+1>=pz || s+*p>=sz) return -1;
206                         memcpy(s, p+1, *p);
207                         s += *p+1;
208                         p += *p+1;
209                         s[-1] = *p ? '.' : 0;
210                 } else return 0;
211         }
212 }
213
214 int __dns_get_rr(void *dest, size_t stride, size_t maxlen, size_t limit, const unsigned char *r, int rr, int dec)
215 {
216         int qdcount, ancount;
217         const unsigned char *p;
218         char tmp[256];
219         int found = 0;
220         int len;
221
222         if ((r[3]&15)) return 0;
223         p = r+12;
224         qdcount = r[4]*256 + r[5];
225         ancount = r[6]*256 + r[7];
226         if (qdcount+ancount > 64) return -1;
227         while (qdcount--) {
228                 while (p-r < 512 && *p-1U < 127) p++;
229                 if (*p>193 || (*p==193 && p[1]>254) || p>r+506)
230                         return -1;
231                 p += 5 + !!*p;
232         }
233         while (ancount--) {
234                 while (p-r < 512 && *p-1U < 127) p++;
235                 if (*p>193 || (*p==193 && p[1]>254) || p>r+506)
236                         return -1;
237                 p += 1 + !!*p;
238                 len = p[8]*256 + p[9];
239                 if (p+len > r+512) return -1;
240                 if (p[1]==rr && len <= maxlen) {
241                         if (dec && decname(tmp, r, p+10)<0) return -1;
242                         if (dest && limit) {
243                                 if (dec) strcpy(dest, tmp);
244                                 else memcpy(dest, p+10, len);
245                                 dest = (char *)dest + stride;
246                                 limit--;
247                         }
248                         found++;
249                 }
250                 p += 10 + len;
251         }
252         return found;
253 }
254
255 int __dns_count_addrs(const unsigned char *r, int cnt)
256 {
257         int found=0, res, i;
258         static const int p[2][2] = { { 4, RR_A }, { 16, RR_AAAA } };
259
260         while (cnt--) for (i=0; i<2; i++) {
261                 res = __dns_get_rr(0, 0, p[i][0], -1, r, p[i][1], 0);
262                 if (res < 0) return res;
263                 found += res;
264                 r += 512;
265         }
266         return found;
267 }