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