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