implement result address sorting in the resolver (getaddrinfo, etc.)
[musl] / src / network / lookup_name.c
1 #include <sys/socket.h>
2 #include <netinet/in.h>
3 #include <netdb.h>
4 #include <net/if.h>
5 #include <arpa/inet.h>
6 #include <ctype.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <pthread.h>
12 #include "lookup.h"
13 #include "stdio_impl.h"
14 #include "syscall.h"
15
16 static int is_valid_hostname(const char *host)
17 {
18         const unsigned char *s;
19         if (strnlen(host, 255)-1 >= 254 || mbstowcs(0, host, 0) == -1) return 0;
20         for (s=(void *)host; *s>=0x80 || *s=='.' || *s=='-' || isalnum(*s); s++);
21         return !*s;
22 }
23
24 static int name_from_null(struct address buf[static 2], const char *name, int family, int flags)
25 {
26         int cnt = 0;
27         if (name) return 0;
28         if (flags & AI_PASSIVE) {
29                 if (family != AF_INET6)
30                         buf[cnt++] = (struct address){ .family = AF_INET };
31                 if (family != AF_INET)
32                         buf[cnt++] = (struct address){ .family = AF_INET6 };
33         } else {
34                 if (family != AF_INET6)
35                         buf[cnt++] = (struct address){ .family = AF_INET, .addr = { 127,0,0,1 } };
36                 if (family != AF_INET)
37                         buf[cnt++] = (struct address){ .family = AF_INET6, .addr = { [15] = 1 } };
38         }
39         return cnt;
40 }
41
42 static int name_from_numeric(struct address buf[static 1], const char *name, int family)
43 {
44         return __lookup_ipliteral(buf, name, family);
45 }
46
47 static int name_from_hosts(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
48 {
49         char line[512];
50         size_t l = strlen(name);
51         int cnt = 0;
52         unsigned char _buf[1032];
53         FILE _f, *f = __fopen_rb_ca("/etc/hosts", &_f, _buf, sizeof _buf);
54         if (!f) return 0;
55         while (fgets(line, sizeof line, f) && cnt < MAXADDRS) {
56                 char *p, *z;
57
58                 if ((p=strchr(line, '#'))) *p++='\n', *p=0;
59                 for(p=line+1; (p=strstr(p, name)) &&
60                         (!isspace(p[-1]) || !isspace(p[l])); p++);
61                 if (!p) continue;
62
63                 /* Isolate IP address to parse */
64                 for (p=line; *p && !isspace(*p); p++);
65                 *p++ = 0;
66                 if (name_from_numeric(buf+cnt, line, family))
67                         cnt++;
68
69                 /* Extract first name as canonical name */
70                 for (; *p && isspace(*p); p++);
71                 for (z=p; *z && !isspace(*z); z++);
72                 *z = 0;
73                 if (is_valid_hostname(p)) memcpy(canon, p, z-p+1);
74         }
75         __fclose_ca(f);
76         return cnt;
77 }
78
79 struct dpc_ctx {
80         struct address *addrs;
81         char *canon;
82         int cnt;
83 };
84
85 int __dns_parse(const unsigned char *, int, int (*)(void *, int, const void *, int, const void *), void *);
86 int __dn_expand(const unsigned char *, const unsigned char *, const unsigned char *, char *, int);
87 int __res_mkquery(int, const char *, int, int, const unsigned char *, int, const unsigned char*, unsigned char *, int);
88 int __res_msend(int, const unsigned char *const *, const int *, unsigned char *const *, int *, int);
89
90 #define RR_A 1
91 #define RR_CNAME 5
92 #define RR_AAAA 28
93
94 static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
95 {
96         char tmp[256];
97         struct dpc_ctx *ctx = c;
98         switch (rr) {
99         case RR_A:
100                 if (len != 4) return -1;
101                 ctx->addrs[ctx->cnt].family = AF_INET;
102                 ctx->addrs[ctx->cnt].scopeid = 0;
103                 memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
104                 break;
105         case RR_AAAA:
106                 if (len != 16) return -1;
107                 ctx->addrs[ctx->cnt].family = AF_INET6;
108                 ctx->addrs[ctx->cnt].scopeid = 0;
109                 memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
110                 break;
111         case RR_CNAME:
112                 if (__dn_expand(packet, (const unsigned char *)packet + 512,
113                     data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
114                         strcpy(ctx->canon, tmp);
115                 break;
116         }
117         return 0;
118 }
119
120 static int name_from_dns(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
121 {
122         unsigned char qbuf[2][280], abuf[2][512];
123         const unsigned char *qp[2] = { qbuf[0], qbuf[1] };
124         unsigned char *ap[2] = { abuf[0], abuf[1] };
125         int qlens[2], alens[2];
126         int i, nq = 0;
127         struct dpc_ctx ctx = { .addrs = buf, .canon = canon };
128
129         if (family != AF_INET6) {
130                 qlens[nq] = __res_mkquery(0, name, 1, RR_A, 0, 0, 0,
131                         qbuf[nq], sizeof *qbuf);
132                 nq++;
133         }
134         if (family != AF_INET) {
135                 qlens[nq] = __res_mkquery(0, name, 1, RR_AAAA, 0, 0, 0,
136                         qbuf[nq], sizeof *qbuf);
137                 nq++;
138         }
139
140         if (__res_msend(nq, qp, qlens, ap, alens, sizeof *abuf) < 0) return EAI_SYSTEM;
141
142         for (i=0; i<nq; i++)
143                 __dns_parse(abuf[i], alens[i], dns_parse_callback, &ctx);
144
145         if (ctx.cnt) return ctx.cnt;
146         if (alens[0] < 4 || (abuf[0][3] & 15) == 2) return EAI_AGAIN;
147         if ((abuf[0][3] & 15) == 3) return EAI_NONAME;
148         return EAI_FAIL;
149 }
150
151 static const struct policy {
152         unsigned char addr[16];
153         unsigned char len, mask;
154         unsigned char prec, label;
155 } defpolicy[] = {
156         { "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1", 15, 0xff, 50, 0 },
157         { "\0\0\0\0\0\0\0\0\0\0\xff\xff", 11, 0xff, 35, 4 },
158         { "\x20\2", 1, 0xff, 30, 2 },
159         { "\x20\1", 3, 0xff, 5, 5 },
160         { "\xfc", 0, 0xfe, 3, 13 },
161 #if 0
162         /* These are deprecated and/or returned to the address
163          * pool, so despite the RFC, treating them as special
164          * is probably wrong. */
165         { "", 11, 0xff, 1, 3 },
166         { "\xfe\xc0", 1, 0xc0, 1, 11 },
167         { "\x3f\xfe", 1, 0xff, 1, 12 },
168 #endif
169         /* Last rule must match all addresses to stop loop. */
170         { "", 0, 0, 40, 1 },
171 };
172
173 static const struct policy *policyof(const struct in6_addr *a)
174 {
175         int i;
176         for (i=0; ; i++) {
177                 if (memcmp(a->s6_addr, defpolicy[i].addr, defpolicy[i].len))
178                         continue;
179                 if ((a->s6_addr[defpolicy[i].len] & defpolicy[i].mask)
180                     != defpolicy[i].addr[defpolicy[i].len])
181                         continue;
182                 return defpolicy+i;
183         }
184 }
185
186 static int labelof(const struct in6_addr *a)
187 {
188         return policyof(a)->label;
189 }
190
191 static int scopeof(const struct in6_addr *a)
192 {
193         if (IN6_IS_ADDR_MULTICAST(a)) return a->s6_addr[1] & 15;
194         if (IN6_IS_ADDR_LINKLOCAL(a)) return 2;
195         if (IN6_IS_ADDR_LOOPBACK(a)) return 2;
196         if (IN6_IS_ADDR_SITELOCAL(a)) return 5;
197         return 14;
198 }
199
200 static int prefixmatch(const struct in6_addr *s, const struct in6_addr *d)
201 {
202         /* FIXME: The common prefix length should be limited to no greater
203          * than the nominal length of the prefix portion of the source
204          * address. However the definition of the source prefix length is
205          * not clear and thus this limiting is not yet implemented. */
206         unsigned i;
207         for (i=0; i<128 && !((s->s6_addr[i/8]^d->s6_addr[i/8])&(128>>(i%8))); i++);
208         return i;
209 }
210
211 #define DAS_USABLE              0x40000000
212 #define DAS_MATCHINGSCOPE       0x20000000
213 #define DAS_MATCHINGLABEL       0x10000000
214 #define DAS_PREC_SHIFT          20
215 #define DAS_SCOPE_SHIFT         16
216 #define DAS_PREFIX_SHIFT        8
217 #define DAS_ORDER_SHIFT         0
218
219 static int addrcmp(const void *_a, const void *_b)
220 {
221         const struct address *a = _a, *b = _b;
222         return b->sortkey - a->sortkey;
223 }
224
225 int __lookup_name(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family, int flags)
226 {
227         int cnt = 0, i, j;
228
229         *canon = 0;
230         if (name) {
231                 /* reject empty name and check len so it fits into temp bufs */
232                 size_t l = strnlen(name, 255);
233                 if (l-1 >= 254)
234                         return EAI_NONAME;
235                 memcpy(canon, name, l+1);
236         }
237
238         /* Procedurally, a request for v6 addresses with the v4-mapped
239          * flag set is like a request for unspecified family, followed
240          * by filtering of the results. */
241         if (flags & AI_V4MAPPED) {
242                 if (family == AF_INET6) family = AF_UNSPEC;
243                 else flags -= AI_V4MAPPED;
244         }
245
246         /* Try each backend until there's at least one result. */
247         cnt = name_from_null(buf, name, family, flags);
248         if (!cnt) cnt = name_from_numeric(buf, name, family);
249         if (!cnt && !(flags & AI_NUMERICHOST)) {
250                 cnt = name_from_hosts(buf, canon, name, family);
251                 if (!cnt) cnt = name_from_dns(buf, canon, name, family);
252         }
253         if (cnt<=0) return cnt ? cnt : EAI_NONAME;
254
255         /* Filter/transform results for v4-mapped lookup, if requested. */
256         if (flags & AI_V4MAPPED) {
257                 if (!(flags & AI_ALL)) {
258                         /* If any v6 results exist, remove v4 results. */
259                         for (i=0; i<cnt && buf[i].family != AF_INET6; i++);
260                         if (i<cnt) {
261                                 for (j=0; i<cnt; i++) {
262                                         if (buf[i].family == AF_INET6)
263                                                 buf[j++] = buf[i];
264                                 }
265                                 cnt = i = j;
266                         }
267                 }
268                 /* Translate any remaining v4 results to v6 */
269                 for (i=0; i<cnt; i++) {
270                         if (buf[i].family != AF_INET) continue;
271                         memcpy(buf[i].addr+12, buf[i].addr, 4);
272                         memcpy(buf[i].addr, "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
273                         buf[i].family = AF_INET6;
274                 }
275         }
276
277         /* No further processing is needed if there are fewer than 2
278          * results or if there are only IPv4 results. */
279         if (cnt<2 || family==AF_INET) return cnt;
280         for (i=0; buf[i].family == AF_INET; i++)
281                 if (i==cnt) return cnt;
282
283         int cs;
284         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
285
286         /* The following implements a subset of RFC 3484/6724 destination
287          * address selection by generating a single 31-bit sort key for
288          * each address. Rules 3, 4, and 7 are omitted for having
289          * excessive runtime and code size cost and dubious benefit.
290          * So far the label/precedence table cannot be customized. */
291         for (i=0; i<cnt; i++) {
292                 int key = 0;
293                 struct sockaddr_in6 sa, da = {
294                         .sin6_family = AF_INET6,
295                         .sin6_scope_id = buf[i].scopeid,
296                         .sin6_port = 65535
297                 };
298                 if (buf[i].family == AF_INET6) {
299                         memcpy(da.sin6_addr.s6_addr, buf[i].addr, 16);
300                 } else {
301                         memcpy(da.sin6_addr.s6_addr,
302                                 "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
303                         memcpy(da.sin6_addr.s6_addr+12, buf[i].addr, 4);
304                 }
305                 const struct policy *dpolicy = policyof(&da.sin6_addr);
306                 int dscope = scopeof(&da.sin6_addr);
307                 int dlabel = dpolicy->label;
308                 int dprec = dpolicy->prec;
309                 int prefixlen = 0;
310                 int fd = socket(AF_INET6, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_UDP);
311                 if (fd >= 0) {
312                         if (!connect(fd, (void *)&da, sizeof da)) {
313                                 key |= DAS_USABLE;
314                                 if (!getsockname(fd, (void *)&sa,
315                                     &(socklen_t){sizeof sa})) {
316                                         if (dscope == scopeof(&sa.sin6_addr))
317                                                 key |= DAS_MATCHINGSCOPE;
318                                         if (dlabel == labelof(&sa.sin6_addr))
319                                                 key |= DAS_MATCHINGLABEL;
320                                         prefixlen = prefixmatch(&sa.sin6_addr,
321                                                 &da.sin6_addr);
322                                 }
323                         }
324                         close(fd);
325                 }
326                 key |= dprec << DAS_PREC_SHIFT;
327                 key |= (15-dscope) << DAS_SCOPE_SHIFT;
328                 key |= prefixlen << DAS_PREFIX_SHIFT;
329                 key |= (MAXADDRS-i) << DAS_ORDER_SHIFT;
330                 buf[i].sortkey = key;
331         }
332         qsort(buf, cnt, sizeof *buf, addrcmp);
333
334         pthread_setcancelstate(cs, 0);
335
336         return cnt;
337 }