]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/net/res_query.c
make sure install scripts are executable
[FreeBSD/FreeBSD.git] / lib / libc / net / res_query.c
1 /*-
2  * Copyright (c) 1988, 1993
3  *    The Regents of the University of California.  All rights reserved.
4  * 
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
36  * 
37  * Permission to use, copy, modify, and distribute this software for any
38  * purpose with or without fee is hereby granted, provided that the above
39  * copyright notice and this permission notice appear in all copies, and that
40  * the name of Digital Equipment Corporation not be used in advertising or
41  * publicity pertaining to distribution of the document or software without
42  * specific, written prior permission.
43  * 
44  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
45  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
46  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
47  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
48  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
49  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
50  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
51  * SOFTWARE.
52  */
53
54 /*
55  * Portions Copyright (c) 1996 by Internet Software Consortium.
56  *
57  * Permission to use, copy, modify, and distribute this software for any
58  * purpose with or without fee is hereby granted, provided that the above
59  * copyright notice and this permission notice appear in all copies.
60  *
61  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
62  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
63  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
64  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
65  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
66  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
67  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
68  * SOFTWARE.
69  */
70
71 #if defined(LIBC_SCCS) && !defined(lint)
72 static char sccsid[] = "@(#)res_query.c 8.1 (Berkeley) 6/4/93";
73 static char rcsid[] = "$Id: res_query.c,v 8.14 1997/06/09 17:47:05 halley Exp $";
74 #endif /* LIBC_SCCS and not lint */
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
77
78 #include <sys/types.h>
79 #include <sys/param.h>
80 #include <netinet/in.h>
81 #include <arpa/inet.h>
82 #include <arpa/nameser.h>
83 #include <ctype.h>
84 #include <errno.h>
85 #include <netdb.h>
86 #include <resolv.h>
87 #include <stdio.h>
88 #include <stdlib.h>
89 #include <string.h>
90 #include <unistd.h>
91
92 #include "res_config.h"
93
94 #if PACKETSZ > 1024
95 #define MAXPACKET       PACKETSZ
96 #else
97 #define MAXPACKET       1024
98 #endif
99
100 const char *_res_hostalias(const char *, char *, size_t);
101
102 /*
103  * Formulate a normal query, send, and await answer.
104  * Returned answer is placed in supplied buffer "answer".
105  * Perform preliminary check of answer, returning success only
106  * if no error is indicated and the answer count is nonzero.
107  * Return the size of the response on success, -1 on error.
108  * Error number is left in h_errno.
109  *
110  * Caller must parse answer and determine whether it answers the question.
111  */
112 int
113 res_query(name, class, type, answer, anslen)
114         const char *name;       /* domain name */
115         int class, type;        /* class and type of query */
116         u_char *answer;         /* buffer to put answer */
117         int anslen;             /* size of answer buffer */
118 {
119         u_char buf[MAXPACKET];
120         HEADER *hp = (HEADER *) answer;
121         int n;
122
123         hp->rcode = NOERROR;    /* default */
124
125         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
126                 h_errno = NETDB_INTERNAL;
127                 return (-1);
128         }
129 #ifdef DEBUG
130         if (_res.options & RES_DEBUG)
131                 printf(";; res_query(%s, %d, %d)\n", name, class, type);
132 #endif
133
134         n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
135                         buf, sizeof(buf));
136         if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
137                 n = res_opt(n, buf, sizeof(buf), anslen);
138         if (n <= 0) {
139 #ifdef DEBUG
140                 if (_res.options & RES_DEBUG)
141                         printf(";; res_query: mkquery failed\n");
142 #endif
143                 h_errno = NO_RECOVERY;
144                 return (n);
145         }
146         n = res_send(buf, n, answer, anslen);
147         if (n < 0) {
148 #ifdef DEBUG
149                 if (_res.options & RES_DEBUG)
150                         printf(";; res_query: send error\n");
151 #endif
152                 h_errno = TRY_AGAIN;
153                 return (n);
154         }
155
156         if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
157 #ifdef DEBUG
158                 if (_res.options & RES_DEBUG)
159                         printf(";; rcode = %d, ancount=%d\n", hp->rcode,
160                             ntohs(hp->ancount));
161 #endif
162                 switch (hp->rcode) {
163                 case NXDOMAIN:
164                         h_errno = HOST_NOT_FOUND;
165                         break;
166                 case SERVFAIL:
167                         h_errno = TRY_AGAIN;
168                         break;
169                 case NOERROR:
170                         h_errno = NO_DATA;
171                         break;
172                 case FORMERR:
173                 case NOTIMP:
174                 case REFUSED:
175                 default:
176                         h_errno = NO_RECOVERY;
177                         break;
178                 }
179                 return (-1);
180         }
181         return (n);
182 }
183
184 /*
185  * Formulate a normal query, send, and retrieve answer in supplied buffer.
186  * Return the size of the response on success, -1 on error.
187  * If enabled, implement search rules until answer or unrecoverable failure
188  * is detected.  Error code, if any, is left in h_errno.
189  */
190 int
191 res_search(name, class, type, answer, anslen)
192         const char *name;       /* domain name */
193         int class, type;        /* class and type of query */
194         u_char *answer;         /* buffer to put answer */
195         int anslen;             /* size of answer */
196 {
197         const char *cp, * const *domain;
198         char tmp[MAXDNAME];
199         u_int dots;
200         int trailing_dot, ret, saved_herrno;
201         int got_nodata = 0, got_servfail = 0, root_on_list = 0;
202         int tried_as_is = 0;
203         int searched = 0;
204
205         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
206                 h_errno = NETDB_INTERNAL;
207                 return (-1);
208         }
209         errno = 0;
210         h_errno = HOST_NOT_FOUND;       /* default, if we never query */
211         dots = 0;
212         for (cp = name; *cp; cp++)
213                 dots += (*cp == '.');
214         trailing_dot = 0;
215         if (cp > name && *--cp == '.')
216                 trailing_dot++;
217
218         /* If there aren't any dots, it could be a user-level alias */
219         if (!dots && (cp = _res_hostalias(name, tmp, sizeof tmp)) != NULL)
220                 return (res_query(cp, class, type, answer, anslen));
221
222         /*
223          * If there are enough dots in the name, let's just give it a
224          * try 'as is'. The threshold can be set with the "ndots" option.
225          * Also, query 'as is', if there is a trailing dot in the name.
226          */
227         saved_herrno = -1;
228         if (dots >= _res.ndots || trailing_dot) {
229                 ret = res_querydomain(name, NULL, class, type, answer, anslen);
230                 if (ret > 0 || trailing_dot)
231                         return (ret);
232                 if (errno == ECONNREFUSED) {
233                         h_errno = TRY_AGAIN;
234                         return (-1);
235                 }
236                 switch (h_errno) {
237                 case NO_DATA:
238                 case HOST_NOT_FOUND:
239                         break;
240                 default:
241                         return (-1);
242                 }
243                 saved_herrno = h_errno;
244                 tried_as_is++;
245         }
246
247         /*
248          * We do at least one level of search if
249          *      - there is no dot and RES_DEFNAME is set, or
250          *      - there is at least one dot, there is no trailing dot,
251          *        and RES_DNSRCH is set.
252          */
253         if ((!dots && (_res.options & RES_DEFNAMES)) ||
254             (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
255                 int done = 0;
256
257                 for (domain = (const char * const *)_res.dnsrch;
258                      *domain && !done;
259                      domain++) {
260                         searched = 1;
261
262                         if (domain[0][0] == '\0' ||
263                             (domain[0][0] == '.' && domain[0][1] == '\0'))
264                                 root_on_list++;
265
266                         if (root_on_list && tried_as_is)
267                                 continue;
268
269                         ret = res_querydomain(name, *domain, class, type,
270                                               answer, anslen);
271                         if (ret > 0)
272                                 return (ret);
273
274                         /*
275                          * If no server present, give up.
276                          * If name isn't found in this domain,
277                          * keep trying higher domains in the search list
278                          * (if that's enabled).
279                          * On a NO_DATA error, keep trying, otherwise
280                          * a wildcard entry of another type could keep us
281                          * from finding this entry higher in the domain.
282                          * If we get some other error (negative answer or
283                          * server failure), then stop searching up,
284                          * but try the input name below in case it's
285                          * fully-qualified.
286                          */
287                         if (errno == ECONNREFUSED) {
288                                 h_errno = TRY_AGAIN;
289                                 return (-1);
290                         }
291
292                         switch (h_errno) {
293                         case NO_DATA:
294                                 got_nodata++;
295                                 /* FALLTHROUGH */
296                         case HOST_NOT_FOUND:
297                                 /* keep trying */
298                                 break;
299                         case TRY_AGAIN:
300                                 /*
301                                  * This can occur due to a server failure
302                                  * (that is, all listed servers have failed),
303                                  * or all listed servers have timed out.
304                                  * ((HEADER *)answer)->rcode may not be set
305                                  * to SERVFAIL in the case of a timeout.
306                                  *
307                                  * Either way we must terminate the search
308                                  * and return TRY_AGAIN in order to avoid
309                                  * non-deterministic return codes.  For
310                                  * example, loaded name servers or races
311                                  * against network startup/validation (dhcp,
312                                  * ppp, etc) can cause the search to timeout
313                                  * on one search element, e.g. 'fu.bar.com',
314                                  * and return a definitive failure on the
315                                  * next search element, e.g. 'fu.'.
316                                  */
317                                 ++got_servfail;
318                                 /* FALLTHROUGH */
319                         default:
320                                 /* anything else implies that we're done */
321                                 done++;
322                         }
323
324                         /* if we got here for some reason other than DNSRCH,
325                          * we only wanted one iteration of the loop, so stop.
326                          */
327                         if (!(_res.options & RES_DNSRCH))
328                                 done++;
329                 }
330         }
331
332         switch (h_errno) {
333         case NO_DATA:
334         case HOST_NOT_FOUND:
335                 break;
336         default:
337                 goto giveup;
338         }
339
340         /*
341          * If the query has not already been tried as is then try it
342          * unless RES_NOTLDQUERY is set and there were no dots.
343          */
344         if ((dots || !searched || !(_res.options & RES_NOTLDQUERY)) &&
345             !(tried_as_is || root_on_list)) {
346                 ret = res_querydomain(name, NULL, class, type, answer, anslen);
347                 if (ret > 0)
348                         return (ret);
349         }
350
351         /* if we got here, we didn't satisfy the search.
352          * if we did an initial full query, return that query's h_errno
353          * (note that we wouldn't be here if that query had succeeded).
354          * else if we ever got a nodata, send that back as the reason.
355          * else send back meaningless h_errno, that being the one from
356          * the last DNSRCH we did.
357          */
358 giveup:
359         if (saved_herrno != -1)
360                 h_errno = saved_herrno;
361         else if (got_nodata)
362                 h_errno = NO_DATA;
363         else if (got_servfail)
364                 h_errno = TRY_AGAIN;
365         return (-1);
366 }
367
368 /*
369  * Perform a call on res_query on the concatenation of name and domain,
370  * removing a trailing dot from name if domain is NULL.
371  */
372 int
373 res_querydomain(name, domain, class, type, answer, anslen)
374         const char *name, *domain;
375         int class, type;        /* class and type of query */
376         u_char *answer;         /* buffer to put answer */
377         int anslen;             /* size of answer */
378 {
379         char nbuf[MAXDNAME];
380         const char *longname = nbuf;
381         int n, d;
382
383         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
384                 h_errno = NETDB_INTERNAL;
385                 return (-1);
386         }
387 #ifdef DEBUG
388         if (_res.options & RES_DEBUG)
389                 printf(";; res_querydomain(%s, %s, %d, %d)\n",
390                        name, domain?domain:"<Nil>", class, type);
391 #endif
392         if (domain == NULL) {
393                 /*
394                  * Check for trailing '.';
395                  * copy without '.' if present.
396                  */
397                 n = strlen(name);
398                 if (n >= MAXDNAME) {
399                         h_errno = NO_RECOVERY;
400                         return (-1);
401                 }
402                 n--;
403                 if (n >= 0 && name[n] == '.') {
404                         strncpy(nbuf, name, n);
405                         nbuf[n] = '\0';
406                 } else
407                         longname = name;
408         } else {
409                 n = strlen(name);
410                 d = strlen(domain);
411                 if (n + d + 1 >= MAXDNAME) {
412                         h_errno = NO_RECOVERY;
413                         return (-1);
414                 }
415                 sprintf(nbuf, "%s.%s", name, domain);
416         }
417         return (res_query(longname, class, type, answer, anslen));
418 }
419
420 const char *
421 _res_hostalias(const char *name, char *dst, size_t siz)
422 {
423         char *file, *cp1, *cp2;
424         char buf[BUFSIZ];
425         FILE *fp;
426
427         if (_res.options & RES_NOALIASES)
428                 return (NULL);
429         if (issetugid())
430                 return (NULL);
431         file = getenv("HOSTALIASES");
432         if (file == NULL || (fp = fopen(file, "r")) == NULL)
433                 return (NULL);
434         setbuf(fp, NULL);
435         buf[sizeof(buf) - 1] = '\0';
436         while (fgets(buf, sizeof(buf), fp)) {
437                 for (cp1 = buf; *cp1 && !isspace((unsigned char)*cp1); ++cp1)
438                         ;
439                 if (!*cp1)
440                         break;
441                 *cp1 = '\0';
442                 if (!strcasecmp(buf, name)) {
443                         while (isspace((unsigned char)*++cp1))
444                                 ;
445                         if (!*cp1)
446                                 break;
447                         for (cp2 = cp1 + 1; *cp2 &&
448                              !isspace((unsigned char)*cp2); ++cp2)
449                                 ;
450                         *cp2 = '\0';
451                         strncpy(dst, cp1, siz - 1);
452                         dst[siz - 1] = '\0';
453                         fclose(fp);
454                         return (dst);
455                 }
456         }
457         fclose(fp);
458         return (NULL);
459 }
460
461 const char *
462 hostalias(const char *name)
463 {
464         static char abuf[MAXDNAME];
465
466         return (_res_hostalias(name, abuf, sizeof abuf));
467 }
468
469 /*
470  * Weak aliases for applications that use certain private entry points,
471  * and fail to include <resolv.h>.
472  */
473 #undef res_query
474 __weak_reference(__res_query, res_query);
475 #undef res_search
476 __weak_reference(__res_search, res_search);
477 #undef res_querydomain
478 __weak_reference(__res_querydomain, res_querydomain);