1 /* $OpenBSD: res_query.c,v 1.4 2013/05/27 17:31:01 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 res_init(); 35 36 if (ans == NULL || anslen <= 0) { 37 h_errno = NO_RECOVERY; 38 errno = EINVAL; 39 return (-1); 40 } 41 42 as = res_query_async(name, class, type, NULL); 43 if (as == NULL) { 44 if (errno == EINVAL) 45 h_errno = NO_RECOVERY; 46 else 47 h_errno = NETDB_INTERNAL; 48 return (-1); /* errno set */ 49 } 50 51 async_run_sync(as, &ar); 52 53 if (ar.ar_errno) 54 errno = ar.ar_errno; 55 h_errno = ar.ar_h_errno; 56 57 if (ar.ar_h_errno != NETDB_SUCCESS) 58 return (-1); 59 60 len = anslen; 61 if (ar.ar_datalen < len) 62 len = ar.ar_datalen; 63 memmove(ans, ar.ar_data, len); 64 free(ar.ar_data); 65 66 return (ar.ar_datalen); 67 } 68 69 int 70 res_search(const char *name, int class, int type, u_char *ans, int anslen) 71 { 72 struct async *as; 73 struct async_res ar; 74 size_t len; 75 76 res_init(); 77 78 if (ans == NULL || anslen <= 0) { 79 h_errno = NO_RECOVERY; 80 errno = EINVAL; 81 return (-1); 82 } 83 84 as = res_search_async(name, class, type, NULL); 85 if (as == NULL) { 86 if (errno == EINVAL) 87 h_errno = NO_RECOVERY; 88 else 89 h_errno = NETDB_INTERNAL; 90 return (-1); /* errno set */ 91 } 92 93 async_run_sync(as, &ar); 94 95 if (ar.ar_errno) 96 errno = ar.ar_errno; 97 h_errno = ar.ar_h_errno; 98 99 if (ar.ar_h_errno != NETDB_SUCCESS) 100 return (-1); 101 102 len = anslen; 103 if (ar.ar_datalen < len) 104 len = ar.ar_datalen; 105 memmove(ans, ar.ar_data, len); 106 free(ar.ar_data); 107 108 return (ar.ar_datalen); 109 } 110