xref: /openbsd-src/lib/libc/asr/getaddrinfo_async.c (revision 48756ee85dedd6f721ebcc181822375f06c4e19d)
1 /*	$OpenBSD: getaddrinfo_async.c,v 1.3 2012/07/10 09:20:51 eric Exp $	*/
2 /*
3  * Copyright (c) 2012 Eric Faurot <eric@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include <sys/types.h>
18 #include <sys/uio.h>
19 
20 #include <arpa/nameser.h>
21 
22 #include <err.h>
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 
28 #include "asr.h"
29 #include "asr_private.h"
30 
31 struct match {
32 	int family;
33 	int socktype;
34 	int protocol;
35 };
36 
37 static int getaddrinfo_async_run(struct async *, struct async_res *);
38 static int get_port(const char *, const char *, int);
39 static int iter_family(struct async *, int);
40 static int add_sockaddr(struct async *, struct sockaddr *, const char *);
41 
42 static const struct match matches[] = {
43 	{ PF_INET,	SOCK_DGRAM,	IPPROTO_UDP	},
44 	{ PF_INET,	SOCK_STREAM,	IPPROTO_TCP	},
45 	{ PF_INET,	SOCK_RAW,	0		},
46 	{ PF_INET6,	SOCK_DGRAM,	IPPROTO_UDP	},
47 	{ PF_INET6,	SOCK_STREAM,	IPPROTO_TCP	},
48 	{ PF_INET6,	SOCK_RAW,	0		},
49 	{ -1, 		0, 		0, 		},
50 };
51 
52 #define MATCH_FAMILY(a, b) ((a) == matches[(b)].family || (a) == PF_UNSPEC)
53 #define MATCH_PROTO(a, b) ((a) == matches[(b)].protocol || (a) == 0)
54 /* Do not match SOCK_RAW unless explicitely specified */
55 #define MATCH_SOCKTYPE(a, b) ((a) == matches[(b)].socktype || ((a) == 0 && \
56 				matches[(b)].socktype != SOCK_RAW))
57 
58 struct async *
59 getaddrinfo_async(const char *hostname, const char *servname,
60 	const struct addrinfo *hints, struct asr *asr)
61 {
62 	struct asr_ctx	*ac;
63 	struct async	*as;
64 
65 	ac = asr_use_resolver(asr);
66 	if ((as = async_new(ac, ASR_GETADDRINFO)) == NULL)
67 		goto abort; /* errno set */
68 	as->as_run = getaddrinfo_async_run;
69 
70 	if (hostname && (as->as.ai.hostname = strdup(hostname)) == NULL)
71 		goto abort; /* errno set */
72 	if (servname && (as->as.ai.servname = strdup(servname)) == NULL)
73 		goto abort; /* errno set */
74 	if (hints)
75 		memmove(&as->as.ai.hints, hints, sizeof *hints);
76 	else {
77 		memset(&as->as.ai.hints, 0, sizeof as->as.ai.hints);
78 		as->as.ai.hints.ai_family = PF_UNSPEC;
79 	}
80 
81 	asr_ctx_unref(ac);
82 	return (as);
83     abort:
84 	if (as)
85 		async_free(as);
86 	asr_ctx_unref(ac);
87 	return (NULL);
88 }
89 
90 static int
91 getaddrinfo_async_run(struct async *as, struct async_res *ar)
92 {
93 	const char	*str;
94 	struct addrinfo	*ai;
95 	int		 i, family, r;
96 	char		 fqdn[MAXDNAME];
97 	union {
98 		struct sockaddr		sa;
99 		struct sockaddr_in	sain;
100 		struct sockaddr_in6	sain6;
101 	} sa;
102 
103     next:
104 	switch(as->as_state) {
105 
106 	case ASR_STATE_INIT:
107 
108 		/*
109 		 * First, make sure the parameters are valid.
110 		 */
111 
112 		as->as_count = 0;
113 		async_set_state(as, ASR_STATE_HALT);
114 		ar->ar_errno = 0;
115 		ar->ar_h_errno = NETDB_SUCCESS;
116 		ar->ar_gai_errno = 0;
117 
118 		if (as->as.ai.hostname == NULL &&
119 		    as->as.ai.servname == NULL) {
120 			ar->ar_h_errno = NO_RECOVERY;
121 			ar->ar_gai_errno = EAI_NONAME;
122 			break;
123 		}
124 
125 		ai = &as->as.ai.hints;
126 
127 		if (ai->ai_addrlen ||
128 		    ai->ai_canonname ||
129 		    ai->ai_addr ||
130 		    ai->ai_next) {
131 			ar->ar_h_errno = NO_RECOVERY;
132 			ar->ar_gai_errno = EAI_BADHINTS;
133 			break;
134 		}
135 
136 		if (ai->ai_flags & ~AI_MASK ||
137 		    (ai->ai_flags & AI_CANONNAME && ai->ai_flags & AI_FQDN)) {
138 			ar->ar_h_errno = NO_RECOVERY;
139 			ar->ar_gai_errno = EAI_BADFLAGS;
140 			break;
141 		}
142 
143 		if (ai->ai_family != PF_UNSPEC &&
144 		    ai->ai_family != PF_INET &&
145 		    ai->ai_family != PF_INET6) {
146 			ar->ar_h_errno = NO_RECOVERY;
147 			ar->ar_gai_errno = EAI_FAMILY;
148 			break;
149 		}
150 
151 		if (ai->ai_socktype &&
152 		    ai->ai_socktype != SOCK_DGRAM  &&
153 		    ai->ai_socktype != SOCK_STREAM &&
154 		    ai->ai_socktype != SOCK_RAW) {
155 			ar->ar_h_errno = NO_RECOVERY;
156 			ar->ar_gai_errno = EAI_SOCKTYPE;
157 			break;
158 		}
159 
160 		if (ai->ai_protocol &&
161 		    ai->ai_protocol != IPPROTO_UDP  &&
162 		    ai->ai_protocol != IPPROTO_TCP) {
163 			ar->ar_h_errno = NO_RECOVERY;
164 			ar->ar_gai_errno = EAI_PROTOCOL;
165 			break;
166 		}
167 
168 		if (ai->ai_socktype == SOCK_RAW &&
169 		    as->as.ai.servname != NULL) {
170 			ar->ar_h_errno = NO_RECOVERY;
171 			ar->ar_gai_errno = EAI_SERVICE;
172 			break;
173 		}
174 
175 		/* Make sure there is at least a valid combination */
176 		for (i = 0; matches[i].family != -1; i++)
177 			if (MATCH_FAMILY(ai->ai_family, i) &&
178 			    MATCH_SOCKTYPE(ai->ai_socktype, i) &&
179 			    MATCH_PROTO(ai->ai_protocol, i))
180 				break;
181 		if (matches[i].family == -1) {
182 			ar->ar_h_errno = NO_RECOVERY;
183 			ar->ar_gai_errno = EAI_BADHINTS;
184 			break;
185 		}
186 
187 		if (ai->ai_protocol == 0 || ai->ai_protocol == IPPROTO_UDP)
188 			as->as.ai.port_udp = get_port(as->as.ai.servname, "udp",
189 			    as->as.ai.hints.ai_flags & AI_NUMERICSERV);
190 		if (ai->ai_protocol == 0 || ai->ai_protocol == IPPROTO_TCP)
191 			as->as.ai.port_tcp = get_port(as->as.ai.servname, "tcp",
192 			    as->as.ai.hints.ai_flags & AI_NUMERICSERV);
193 		if (as->as.ai.port_tcp == -2 || as->as.ai.port_udp == -2 ||
194 		    (as->as.ai.port_tcp == -1 && as->as.ai.port_udp == -1)) {
195 			ar->ar_h_errno = NO_RECOVERY;
196 			ar->ar_gai_errno = EAI_SERVICE;
197 			break;
198 		}
199 
200 		/* If hostname is NULL, use local address */
201 		if (as->as.ai.hostname == NULL) {
202 			for(family = iter_family(as, 1);
203 			    family != -1;
204 			    family = iter_family(as, 0)) {
205 				/*
206 				 * We could use statically built sockaddrs for
207 				 * those, rather than parsing over and over.
208 				 */
209 				if (family == PF_INET)
210 					str = (ai->ai_flags & AI_PASSIVE) ? \
211 						"0.0.0.0" : "127.0.0.1";
212 				else /* PF_INET6 */
213 					str = (ai->ai_flags & AI_PASSIVE) ? \
214 						"::" : "::1";
215 				 /* This can't fail */
216 				sockaddr_from_str(&sa.sa, family, str);
217 				if ((r = add_sockaddr(as, &sa.sa, NULL))) {
218 					ar->ar_errno = errno;
219 					ar->ar_h_errno = NETDB_INTERNAL;
220 					ar->ar_gai_errno = r;
221 					async_set_state(as, ASR_STATE_HALT);
222 					break;
223 				}
224 			}
225 			if (ar->ar_gai_errno == 0 && as->as_count == 0) {
226 				ar->ar_h_errno = NO_DATA;
227 				ar->ar_gai_errno = EAI_NODATA;
228 			}
229 			break;
230 		}
231 
232 		/* Try numeric addresses first */
233 		for(family = iter_family(as, 1);
234 		    family != -1;
235 		    family = iter_family(as, 0)) {
236 
237 			if (sockaddr_from_str(&sa.sa, family,
238 					      as->as.ai.hostname) == -1)
239 				continue;
240 
241 			if ((r = add_sockaddr(as, &sa.sa, NULL))) {
242 				ar->ar_errno = errno;
243 				ar->ar_h_errno = NETDB_INTERNAL;
244 				ar->ar_gai_errno = r;
245 				async_set_state(as, ASR_STATE_HALT);
246 				break;
247 			}
248 
249 			async_set_state(as, ASR_STATE_HALT);
250 			break;
251 		}
252 		if (ar->ar_gai_errno || as->as_count)
253 			break;
254 
255 		if (ai->ai_flags & AI_NUMERICHOST) {
256 			ar->ar_h_errno = NO_RECOVERY;
257 			ar->ar_gai_errno = EAI_FAIL;
258 			async_set_state(as, ASR_STATE_HALT);
259 			break;
260 		}
261 
262 		/* Starting domain lookup */
263 		async_set_state(as, ASR_STATE_SEARCH_DOMAIN);
264 		break;
265 
266 	case ASR_STATE_SEARCH_DOMAIN:
267 
268 		r = asr_iter_domain(as, as->as.ai.hostname, fqdn, sizeof(fqdn));
269 		if (r == -1) {
270 			async_set_state(as, ASR_STATE_NOT_FOUND);
271 			break;
272 		}
273 		if (r > (int)sizeof(fqdn)) {
274 			ar->ar_errno = EINVAL;
275 			ar->ar_h_errno = NO_RECOVERY;
276 			ar->ar_gai_errno = EAI_OVERFLOW;
277 			async_set_state(as, ASR_STATE_HALT);
278 			break;
279 		}
280 
281 		/*
282 		 * Create a subquery to lookup the host addresses.
283 		 * We use the special hostaddr_async() API, which has the
284 		 * nice property of honoring the "lookup" and "family" keyword
285 		 * in the configuration, thus returning the right address
286 		 * families in the right order, and thus fixing the current
287 		 * getaddrinfo() feature documented in the BUGS section of
288 		 * resolver.conf(5).
289 		 */
290 		as->as.ai.subq = hostaddr_async_ctx(fqdn,
291 		    as->as.ai.hints.ai_family, as->as.ai.hints.ai_flags,
292 		    as->as_ctx);
293 		if (as->as.ai.subq == NULL) {
294 			ar->ar_errno = errno;
295 			if (errno == EINVAL) {
296 				ar->ar_h_errno = NO_RECOVERY;
297 				ar->ar_gai_errno = EAI_FAIL;
298 			} else {
299 				ar->ar_h_errno = NETDB_INTERNAL;
300 				ar->ar_gai_errno = EAI_MEMORY;
301 			}
302 			async_set_state(as, ASR_STATE_HALT);
303 			break;
304 		}
305 		async_set_state(as, ASR_STATE_LOOKUP_DOMAIN);
306 		break;
307 
308 	case ASR_STATE_LOOKUP_DOMAIN:
309 
310 		/* Run the subquery */
311 		if ((r = async_run(as->as.ai.subq, ar)) == ASYNC_COND)
312 			return (ASYNC_COND);
313 
314 		/* Got one more address, use it to extend the result list. */
315 		if (r == ASYNC_YIELD) {
316 			if ((r = add_sockaddr(as, &ar->ar_sa.sa,
317 			    ar->ar_cname))) {
318 				ar->ar_errno = errno;
319 				ar->ar_h_errno = NETDB_INTERNAL;
320 				ar->ar_gai_errno = r;
321 				async_set_state(as, ASR_STATE_HALT);
322 			}
323 			if (ar->ar_cname)
324 				free(ar->ar_cname);
325 			break;
326 		}
327 
328 		/*
329 		 * The subquery is done. Stop there if we have at least one
330 		 * answer.
331 		 */
332 		as->as.ai.subq = NULL;
333 		if (ar->ar_count) {
334 			async_set_state(as, ASR_STATE_HALT);
335 			break;
336 		}
337 
338 		/*
339 		 * No anwser for this domain, but we might be suggested to
340 		 * try again later, so remember this. Then search the next
341 		 * domain.
342 		 */
343 		if (ar->ar_gai_errno == EAI_AGAIN)
344 			as->as.ai.flags |= ASYNC_AGAIN;
345 		async_set_state(as, ASR_STATE_SEARCH_DOMAIN);
346 		break;
347 
348 	case ASR_STATE_NOT_FOUND:
349 
350 		/*
351 		 * No result found. Maybe we can try again.
352 		 */
353 		ar->ar_errno = 0;
354 		if (as->as.ai.flags & ASYNC_AGAIN) {
355 			ar->ar_h_errno = TRY_AGAIN;
356 			ar->ar_gai_errno = EAI_AGAIN;
357 		} else {
358 			ar->ar_h_errno = NO_DATA;
359 			ar->ar_gai_errno = EAI_NODATA;
360 		}
361 		async_set_state(as, ASR_STATE_HALT);
362 		break;
363 
364 	case ASR_STATE_HALT:
365 
366 		/* Set the results. */
367 
368 		if (ar->ar_gai_errno == 0) {
369 			ar->ar_count = as->as_count;
370 			ar->ar_addrinfo = as->as.ai.aifirst;
371 			as->as.ai.aifirst = NULL;
372 		} else {
373 			ar->ar_count = 0;
374 			ar->ar_addrinfo = NULL;
375 		}
376 		return (ASYNC_DONE);
377 
378 	default:
379 		ar->ar_errno = EOPNOTSUPP;
380 		ar->ar_h_errno = NETDB_INTERNAL;
381 		ar->ar_gai_errno = EAI_SYSTEM;
382 		async_set_state(as, ASR_STATE_HALT);
383                 break;
384 	}
385 	goto next;
386 }
387 
388 /*
389  * Retreive the port number for the service name "servname" and
390  * the protocol "proto".
391  */
392 static int
393 get_port(const char *servname, const char *proto, int numonly)
394 {
395 	struct servent		se;
396 	struct servent_data	sed;
397 	int			port, r;
398 	const char*		e;
399 
400 	if (servname == NULL)
401 		return (0);
402 
403 	e = NULL;
404 	port = strtonum(servname, 0, USHRT_MAX, &e);
405 	if (e == NULL)
406 		return (port);
407 	if (errno == ERANGE)
408 		return (-2); /* invalid */
409 	if (numonly)
410 		return (-2);
411 
412 	memset(&sed, 0, sizeof(sed));
413 	r = getservbyname_r(servname, proto, &se, &sed);
414 	port = ntohs(se.s_port);
415 	endservent_r(&sed);
416 
417 	if (r == -1)
418 		return (-1); /* not found */
419 
420 	return (port);
421 }
422 
423 /*
424  * Iterate over the address families that are to be queried. Use the
425  * list on the async context, unless a specific family was given in hints.
426  */
427 static int
428 iter_family(struct async *as, int first)
429 {
430 	if (first) {
431 		as->as_family_idx = 0;
432 		if (as->as.ai.hints.ai_family != PF_UNSPEC)
433 			return as->as.ai.hints.ai_family;
434 		return AS_FAMILY(as);
435 	}
436 
437 	if (as->as.ai.hints.ai_family != PF_UNSPEC)
438 		return (-1);
439 
440 	as->as_family_idx++;
441 
442 	return AS_FAMILY(as);
443 }
444 
445 /*
446  * Use the sockaddr at "sa" to extend the result list on the "as" context,
447  * with the specified canonical name "cname". This function adds one
448  * entry per protocol/socktype match.
449  */
450 static int
451 add_sockaddr(struct async *as, struct sockaddr *sa, const char *cname)
452 {
453 	struct addrinfo		*ai;
454 	int			 i, port;
455 
456 	for(i = 0; matches[i].family != -1; i++) {
457 		if (matches[i].family != sa->sa_family ||
458 		    !MATCH_SOCKTYPE(as->as.ai.hints.ai_socktype, i) ||
459 		    !MATCH_PROTO(as->as.ai.hints.ai_protocol, i))
460 			continue;
461 
462 		if (matches[i].protocol == IPPROTO_TCP)
463 			port = as->as.ai.port_tcp;
464 		else if (matches[i].protocol == IPPROTO_UDP)
465 			port = as->as.ai.port_udp;
466 		else
467 			port = 0;
468 
469 		/* servname specified, but not defined for this protocol */
470 		if (port == -1)
471 			continue;
472 
473 		ai = calloc(1, sizeof(*ai) + sa->sa_len);
474 		if (ai == NULL)
475 			return (EAI_MEMORY);
476 		ai->ai_family = sa->sa_family;
477 		ai->ai_socktype = matches[i].socktype;
478 		ai->ai_protocol = matches[i].protocol;
479 		ai->ai_addrlen = sa->sa_len;
480 		ai->ai_addr = (void*)(ai + 1);
481 		if (cname &&
482 		    as->as.ai.hints.ai_flags & (AI_CANONNAME | AI_FQDN)) {
483 			if ((ai->ai_canonname = strdup(cname)) == NULL) {
484 				free(ai);
485 				return (EAI_MEMORY);
486 			}
487 		}
488 		memmove(ai->ai_addr, sa, sa->sa_len);
489 		if (sa->sa_family == PF_INET)
490 			((struct sockaddr_in *)ai->ai_addr)->sin_port =
491 			    htons(port);
492 		else if (sa->sa_family == PF_INET6)
493 			((struct sockaddr_in6 *)ai->ai_addr)->sin6_port =
494 			    htons(port);
495 
496 		if (as->as.ai.aifirst == NULL)
497 			as->as.ai.aifirst = ai;
498 		if (as->as.ai.ailast)
499 			as->as.ai.ailast->ai_next = ai;
500 		as->as.ai.ailast = ai;
501 		as->as_count += 1;
502 	}
503 
504 	return (0);
505 }
506