1 #include <sys/socket.h>
2 #include <netinet/in.h>
15 #include "stdio_impl.h"
18 static int is_valid_hostname(const char *host)
20 const unsigned char *s;
21 if (strnlen(host, 255)-1 >= 254 || mbstowcs(0, host, 0) == -1) return 0;
22 for (s=(void *)host; *s>=0x80 || *s=='.' || *s=='-' || isalnum(*s); s++);
26 static int name_from_null(struct address buf[static 2], const char *name, int family, int flags)
30 if (flags & AI_PASSIVE) {
31 if (family != AF_INET6)
32 buf[cnt++] = (struct address){ .family = AF_INET };
33 if (family != AF_INET)
34 buf[cnt++] = (struct address){ .family = AF_INET6 };
36 if (family != AF_INET6)
37 buf[cnt++] = (struct address){ .family = AF_INET, .addr = { 127,0,0,1 } };
38 if (family != AF_INET)
39 buf[cnt++] = (struct address){ .family = AF_INET6, .addr = { [15] = 1 } };
44 static int name_from_numeric(struct address buf[static 1], const char *name, int family)
46 return __lookup_ipliteral(buf, name, family);
49 static int name_from_hosts(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
52 size_t l = strlen(name);
53 int cnt = 0, badfam = 0, have_canon = 0;
54 unsigned char _buf[1032];
55 FILE _f, *f = __fopen_rb_ca("/etc/hosts", &_f, _buf, sizeof _buf);
56 if (!f) switch (errno) {
64 while (fgets(line, sizeof line, f) && cnt < MAXADDRS) {
67 if ((p=strchr(line, '#'))) *p++='\n', *p=0;
68 for(p=line+1; (p=strstr(p, name)) &&
69 (!isspace(p[-1]) || !isspace(p[l])); p++);
72 /* Isolate IP address to parse */
73 for (p=line; *p && !isspace(*p); p++);
75 switch (name_from_numeric(buf+cnt, line, family)) {
86 if (have_canon) continue;
88 /* Extract first name as canonical name */
89 for (; *p && isspace(*p); p++);
90 for (z=p; *z && !isspace(*z); z++);
92 if (is_valid_hostname(p)) {
94 memcpy(canon, p, z-p+1);
98 return cnt ? cnt : badfam;
102 struct address *addrs;
111 #define ABUF_SIZE 768
113 static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
116 struct dpc_ctx *ctx = c;
117 if (ctx->cnt >= MAXADDRS) return -1;
120 if (len != 4) return -1;
121 ctx->addrs[ctx->cnt].family = AF_INET;
122 ctx->addrs[ctx->cnt].scopeid = 0;
123 memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
126 if (len != 16) return -1;
127 ctx->addrs[ctx->cnt].family = AF_INET6;
128 ctx->addrs[ctx->cnt].scopeid = 0;
129 memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
132 if (__dn_expand(packet, (const unsigned char *)packet + ABUF_SIZE,
133 data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
134 strcpy(ctx->canon, tmp);
140 static int name_from_dns(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family, const struct resolvconf *conf)
142 unsigned char qbuf[2][280], abuf[2][ABUF_SIZE];
143 const unsigned char *qp[2] = { qbuf[0], qbuf[1] };
144 unsigned char *ap[2] = { abuf[0], abuf[1] };
145 int qlens[2], alens[2];
147 struct dpc_ctx ctx = { .addrs = buf, .canon = canon };
148 static const struct { int af; int rr; } afrr[2] = {
149 { .af = AF_INET6, .rr = RR_A },
150 { .af = AF_INET, .rr = RR_AAAA },
153 for (i=0; i<2; i++) {
154 if (family != afrr[i].af) {
155 qlens[nq] = __res_mkquery(0, name, 1, afrr[i].rr,
156 0, 0, 0, qbuf[nq], sizeof *qbuf);
159 qbuf[nq][3] = 0; /* don't need AD flag */
160 /* Ensure query IDs are distinct. */
161 if (nq && qbuf[nq][0] == qbuf[0][0])
167 if (__res_msend_rc(nq, qp, qlens, ap, alens, sizeof *abuf, conf) < 0)
170 for (i=0; i<nq; i++) {
171 if (alens[i] < 4 || (abuf[i][3] & 15) == 2) return EAI_AGAIN;
172 if ((abuf[i][3] & 15) == 3) return 0;
173 if ((abuf[i][3] & 15) != 0) return EAI_FAIL;
176 for (i=nq-1; i>=0; i--)
177 __dns_parse(abuf[i], alens[i], dns_parse_callback, &ctx);
179 if (ctx.cnt) return ctx.cnt;
183 static int name_from_dns_search(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
186 struct resolvconf conf;
190 if (__get_resolv_conf(&conf, search, sizeof search) < 0) return -1;
192 /* Count dots, suppress search when >=ndots or name ends in
193 * a dot, which is an explicit request for global scope. */
194 for (dots=l=0; name[l]; l++) if (name[l]=='.') dots++;
195 if (dots >= conf.ndots || name[l-1]=='.') *search = 0;
197 /* Strip final dot for canon, fail if multiple trailing dots. */
198 if (name[l-1]=='.') l--;
199 if (!l || name[l-1]=='.') return EAI_NONAME;
201 /* This can never happen; the caller already checked length. */
202 if (l >= 256) return EAI_NONAME;
204 /* Name with search domain appended is setup in canon[]. This both
205 * provides the desired default canonical name (if the requested
206 * name is not a CNAME record) and serves as a buffer for passing
207 * the full requested name to name_from_dns. */
208 memcpy(canon, name, l);
211 for (p=search; *p; p=z) {
212 for (; isspace(*p); p++);
213 for (z=p; *z && !isspace(*z); z++);
215 if (z-p < 256 - l - 1) {
216 memcpy(canon+l+1, p, z-p);
218 int cnt = name_from_dns(buf, canon, canon, family, &conf);
224 return name_from_dns(buf, canon, name, family, &conf);
227 static const struct policy {
228 unsigned char addr[16];
229 unsigned char len, mask;
230 unsigned char prec, label;
232 { "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1", 15, 0xff, 50, 0 },
233 { "\0\0\0\0\0\0\0\0\0\0\xff\xff", 11, 0xff, 35, 4 },
234 { "\x20\2", 1, 0xff, 30, 2 },
235 { "\x20\1", 3, 0xff, 5, 5 },
236 { "\xfc", 0, 0xfe, 3, 13 },
238 /* These are deprecated and/or returned to the address
239 * pool, so despite the RFC, treating them as special
240 * is probably wrong. */
241 { "", 11, 0xff, 1, 3 },
242 { "\xfe\xc0", 1, 0xc0, 1, 11 },
243 { "\x3f\xfe", 1, 0xff, 1, 12 },
245 /* Last rule must match all addresses to stop loop. */
249 static const struct policy *policyof(const struct in6_addr *a)
253 if (memcmp(a->s6_addr, defpolicy[i].addr, defpolicy[i].len))
255 if ((a->s6_addr[defpolicy[i].len] & defpolicy[i].mask)
256 != defpolicy[i].addr[defpolicy[i].len])
262 static int labelof(const struct in6_addr *a)
264 return policyof(a)->label;
267 static int scopeof(const struct in6_addr *a)
269 if (IN6_IS_ADDR_MULTICAST(a)) return a->s6_addr[1] & 15;
270 if (IN6_IS_ADDR_LINKLOCAL(a)) return 2;
271 if (IN6_IS_ADDR_LOOPBACK(a)) return 2;
272 if (IN6_IS_ADDR_SITELOCAL(a)) return 5;
276 static int prefixmatch(const struct in6_addr *s, const struct in6_addr *d)
278 /* FIXME: The common prefix length should be limited to no greater
279 * than the nominal length of the prefix portion of the source
280 * address. However the definition of the source prefix length is
281 * not clear and thus this limiting is not yet implemented. */
283 for (i=0; i<128 && !((s->s6_addr[i/8]^d->s6_addr[i/8])&(128>>(i%8))); i++);
287 #define DAS_USABLE 0x40000000
288 #define DAS_MATCHINGSCOPE 0x20000000
289 #define DAS_MATCHINGLABEL 0x10000000
290 #define DAS_PREC_SHIFT 20
291 #define DAS_SCOPE_SHIFT 16
292 #define DAS_PREFIX_SHIFT 8
293 #define DAS_ORDER_SHIFT 0
295 static int addrcmp(const void *_a, const void *_b)
297 const struct address *a = _a, *b = _b;
298 return b->sortkey - a->sortkey;
301 int __lookup_name(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family, int flags)
307 /* reject empty name and check len so it fits into temp bufs */
308 size_t l = strnlen(name, 255);
311 memcpy(canon, name, l+1);
314 /* Procedurally, a request for v6 addresses with the v4-mapped
315 * flag set is like a request for unspecified family, followed
316 * by filtering of the results. */
317 if (flags & AI_V4MAPPED) {
318 if (family == AF_INET6) family = AF_UNSPEC;
319 else flags -= AI_V4MAPPED;
322 /* Try each backend until there's at least one result. */
323 cnt = name_from_null(buf, name, family, flags);
324 if (!cnt) cnt = name_from_numeric(buf, name, family);
325 if (!cnt && !(flags & AI_NUMERICHOST)) {
326 cnt = name_from_hosts(buf, canon, name, family);
327 if (!cnt) cnt = name_from_dns_search(buf, canon, name, family);
329 if (cnt<=0) return cnt ? cnt : EAI_NONAME;
331 /* Filter/transform results for v4-mapped lookup, if requested. */
332 if (flags & AI_V4MAPPED) {
333 if (!(flags & AI_ALL)) {
334 /* If any v6 results exist, remove v4 results. */
335 for (i=0; i<cnt && buf[i].family != AF_INET6; i++);
337 for (j=0; i<cnt; i++) {
338 if (buf[i].family == AF_INET6)
344 /* Translate any remaining v4 results to v6 */
345 for (i=0; i<cnt; i++) {
346 if (buf[i].family != AF_INET) continue;
347 memcpy(buf[i].addr+12, buf[i].addr, 4);
348 memcpy(buf[i].addr, "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
349 buf[i].family = AF_INET6;
353 /* No further processing is needed if there are fewer than 2
354 * results or if there are only IPv4 results. */
355 if (cnt<2 || family==AF_INET) return cnt;
356 for (i=0; i<cnt; i++) if (buf[i].family != AF_INET) break;
357 if (i==cnt) return cnt;
360 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
362 /* The following implements a subset of RFC 3484/6724 destination
363 * address selection by generating a single 31-bit sort key for
364 * each address. Rules 3, 4, and 7 are omitted for having
365 * excessive runtime and code size cost and dubious benefit.
366 * So far the label/precedence table cannot be customized. */
367 for (i=0; i<cnt; i++) {
368 int family = buf[i].family;
370 struct sockaddr_in6 sa6 = { 0 }, da6 = {
371 .sin6_family = AF_INET6,
372 .sin6_scope_id = buf[i].scopeid,
375 struct sockaddr_in sa4 = { 0 }, da4 = {
376 .sin_family = AF_INET,
380 socklen_t salen, dalen;
381 if (family == AF_INET6) {
382 memcpy(da6.sin6_addr.s6_addr, buf[i].addr, 16);
383 da = &da6; dalen = sizeof da6;
384 sa = &sa6; salen = sizeof sa6;
386 memcpy(sa6.sin6_addr.s6_addr,
387 "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
388 memcpy(da6.sin6_addr.s6_addr+12, buf[i].addr, 4);
389 memcpy(da6.sin6_addr.s6_addr,
390 "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
391 memcpy(da6.sin6_addr.s6_addr+12, buf[i].addr, 4);
392 memcpy(&da4.sin_addr, buf[i].addr, 4);
393 da = &da4; dalen = sizeof da4;
394 sa = &sa4; salen = sizeof sa4;
396 const struct policy *dpolicy = policyof(&da6.sin6_addr);
397 int dscope = scopeof(&da6.sin6_addr);
398 int dlabel = dpolicy->label;
399 int dprec = dpolicy->prec;
401 int fd = socket(family, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_UDP);
403 if (!connect(fd, da, dalen)) {
405 if (!getsockname(fd, sa, &salen)) {
406 if (family == AF_INET) memcpy(
407 sa6.sin6_addr.s6_addr+12,
409 if (dscope == scopeof(&sa6.sin6_addr))
410 key |= DAS_MATCHINGSCOPE;
411 if (dlabel == labelof(&sa6.sin6_addr))
412 key |= DAS_MATCHINGLABEL;
413 prefixlen = prefixmatch(&sa6.sin6_addr,
419 key |= dprec << DAS_PREC_SHIFT;
420 key |= (15-dscope) << DAS_SCOPE_SHIFT;
421 key |= prefixlen << DAS_PREFIX_SHIFT;
422 key |= (MAXADDRS-i) << DAS_ORDER_SHIFT;
423 buf[i].sortkey = key;
425 qsort(buf, cnt, sizeof *buf, addrcmp);
427 pthread_setcancelstate(cs, 0);