xref: /openbsd-src/lib/libc/asr/res_query.c (revision 35d50e37c6a86fa2a0d7df2bf7fb22b25ce1eba9)
1 /*	$OpenBSD: res_query.c,v 1.6 2013/11/12 06:09:50 deraadt 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 
18 #include <sys/types.h>
19 #include <netinet/in.h>
20 
21 #include <errno.h>
22 #include <resolv.h>
23 #include <string.h>
24 #include <stdlib.h>
25 
26 #include "asr.h"
27 
28 int
29 res_query(const char *name, int class, int type, u_char *ans, int anslen)
30 {
31 	struct async	*as;
32 	struct async_res ar;
33 	size_t		 len;
34 
35 	res_init();
36 
37 	if (ans == NULL || anslen <= 0) {
38 		h_errno = NO_RECOVERY;
39 		errno = EINVAL;
40 		return (-1);
41 	}
42 
43 	as = res_query_async(name, class, type, NULL);
44 	if (as == NULL) {
45 		if (errno == EINVAL)
46 			h_errno = NO_RECOVERY;
47 		else
48 			h_errno = NETDB_INTERNAL;
49 		return (-1); /* errno set */
50 	}
51 
52 	asr_async_run_sync(as, &ar);
53 
54 	if (ar.ar_errno)
55 		errno = ar.ar_errno;
56 	h_errno = ar.ar_h_errno;
57 
58 	if (ar.ar_h_errno != NETDB_SUCCESS)
59 		return (-1);
60 
61 	len = anslen;
62 	if (ar.ar_datalen < len)
63 		len = ar.ar_datalen;
64 	memmove(ans, ar.ar_data, len);
65 	free(ar.ar_data);
66 
67 	return (ar.ar_datalen);
68 }
69 
70 int
71 res_search(const char *name, int class, int type, u_char *ans, int anslen)
72 {
73 	struct async	*as;
74 	struct async_res ar;
75 	size_t		 len;
76 
77 	res_init();
78 
79 	if (ans == NULL || anslen <= 0) {
80 		h_errno = NO_RECOVERY;
81 		errno = EINVAL;
82 		return (-1);
83 	}
84 
85 	as = res_search_async(name, class, type, NULL);
86 	if (as == NULL) {
87 		if (errno == EINVAL)
88 			h_errno = NO_RECOVERY;
89 		else
90 			h_errno = NETDB_INTERNAL;
91 		return (-1); /* errno set */
92 	}
93 
94 	asr_async_run_sync(as, &ar);
95 
96 	if (ar.ar_errno)
97 		errno = ar.ar_errno;
98 	h_errno = ar.ar_h_errno;
99 
100 	if (ar.ar_h_errno != NETDB_SUCCESS)
101 		return (-1);
102 
103 	len = anslen;
104 	if (ar.ar_datalen < len)
105 		len = ar.ar_datalen;
106 	memmove(ans, ar.ar_data, len);
107 	free(ar.ar_data);
108 
109 	return (ar.ar_datalen);
110 }
111