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