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