style(9) cleanup:
[dragonfly.git] / usr.sbin / ypserv / yp_dnslookup.c
1 /*
2  * Copyright (c) 1995, 1996
3  *      Bill Paul <wpaul@ctr.columbia.edu>. 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 Bill Paul.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $FreeBSD: src/usr.sbin/ypserv/yp_dnslookup.c,v 1.16.2.1 2002/02/15 00:47:00 des Exp $
33  * $DragonFly: src/usr.sbin/ypserv/yp_dnslookup.c,v 1.2 2003/06/17 04:30:04 dillon Exp $
34  */
35
36 /*
37  * Do standard and reverse DNS lookups using the resolver library.
38  * Take care of all the dirty work here so the main program only has to
39  * pass us a pointer to an array of characters.
40  *
41  * We have to use direct resolver calls here otherwise the YP server
42  * could end up looping by calling itself over and over again until
43  * it disappeared up its own belly button.
44  */
45
46 #include <sys/param.h>
47 #include <sys/socket.h>
48 #include <sys/time.h>
49 #include <sys/fcntl.h>
50 #include <sys/queue.h>
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
53 #include <arpa/nameser.h>
54
55 #include <ctype.h>
56 #include <errno.h>
57 #include <netdb.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <resolv.h>
62 #include <unistd.h>
63
64 #include <rpcsvc/yp.h>
65 #include "yp_extern.h"
66
67 static char *parse(hp)
68         struct hostent *hp;
69 {
70         static char result[MAXHOSTNAMELEN * 2];
71         int len,i;
72         struct in_addr addr;
73
74         if (hp == NULL)
75                 return(NULL);
76
77         len = 16 + strlen(hp->h_name);
78         for (i = 0; hp->h_aliases[i]; i++)
79                 len += strlen(hp->h_aliases[i]) + 1;
80         len++;
81
82         if (len > sizeof(result))
83                 return(NULL);
84
85         bzero(result, sizeof(result));
86
87         bcopy(hp->h_addr, &addr, sizeof(struct in_addr));
88         snprintf(result, sizeof(result), "%s %s", inet_ntoa(addr), hp->h_name);
89
90         for (i = 0; hp->h_aliases[i]; i++) {
91                 strcat(result, " ");
92                 strcat(result, hp->h_aliases[i]);
93         }
94
95         return ((char *)&result);
96 }
97
98 #define MAXPACKET 1024
99 #define DEF_TTL 50
100
101 #define BY_DNS_ID 1
102 #define BY_RPC_XID 2
103
104 extern struct hostent *__dns_getanswer(char *, int, char *, int);
105
106 static CIRCLEQ_HEAD(dns_qhead, circleq_dnsentry) qhead;
107
108 struct circleq_dnsentry {
109         SVCXPRT *xprt;
110         unsigned long xid;
111         struct sockaddr_in client_addr;
112         unsigned long ypvers;
113         unsigned long id;
114         unsigned long ttl;
115         unsigned long type;
116         unsigned short prot_type;
117         char **domain;
118         char *name;
119         struct in_addr addr;
120         CIRCLEQ_ENTRY(circleq_dnsentry) links;
121 };
122
123 static int pending = 0;
124
125 int yp_init_resolver()
126 {
127         CIRCLEQ_INIT(&qhead);
128         if (!(_res.options & RES_INIT) && res_init() == -1) {
129                 yp_error("res_init failed");
130                 return(1);
131         }
132         if ((resfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
133                 yp_error("couldn't create socket");
134                 return(1);
135         }
136         if (fcntl(resfd, F_SETFL, O_NONBLOCK) == -1) {
137                 yp_error("couldn't make resolver socket non-blocking");
138                 return(1);
139         }
140         return(0);
141 }
142
143 static struct circleq_dnsentry *yp_malloc_dnsent()
144 {
145         register struct circleq_dnsentry *q;
146
147         q = (struct circleq_dnsentry *)malloc(sizeof(struct circleq_dnsentry));
148
149         if (q == NULL) {
150                 yp_error("failed to malloc() circleq dns entry");
151                 return(NULL);
152         }
153
154         return(q);
155 }
156
157 /*
158  * Transmit a query.
159  */
160 static unsigned long yp_send_dns_query(name, type)
161         char *name;
162         int type;
163 {
164         char buf[MAXPACKET];
165         int n;
166         HEADER *hptr;
167         int ns;
168         int rval;
169         unsigned long id;
170
171         bzero(buf, sizeof(buf));
172
173         n = res_mkquery(QUERY,name,C_IN,type,NULL,0,NULL,buf,sizeof(buf));
174
175         if (n <= 0) {
176                 yp_error("res_mkquery failed");
177                 return(0);
178         }
179
180         hptr = (HEADER *)&buf;
181         id = ntohs(hptr->id);
182
183         for (ns = 0; ns < _res.nscount; ns++) {
184                 rval = sendto(resfd, buf, n, 0,
185                         (struct sockaddr *)&_res.nsaddr_list[ns],
186                                 sizeof(struct sockaddr));
187                 if (rval == -1) {
188                         yp_error("sendto failed");
189                         return(0);
190                 }
191         }
192
193         return(id);
194 }
195
196 static struct circleq_dnsentry *yp_find_dnsqent(id, type)
197         unsigned long id;
198         int type;
199 {
200         register struct circleq_dnsentry *q;
201
202         for (q = qhead.cqh_first; q != (void *)&qhead; q = q->links.cqe_next) {
203                 switch (type) {
204                 case BY_RPC_XID:
205                         if (id == q->xid)
206                                 return(q);
207                         break;
208                 case BY_DNS_ID:
209                 default:
210                         if (id == q->id)
211                                 return(q);
212                         break;
213                 }
214         }
215         return (NULL);
216 }
217
218 static void yp_send_dns_reply(q, buf)
219         struct circleq_dnsentry *q;
220         char *buf;
221 {
222         ypresponse result_v1;
223         ypresp_val result_v2;
224         unsigned long xid;
225         struct sockaddr_in client_addr;
226         xdrproc_t xdrfunc;
227         char *result;
228
229         /*
230          * Set up correct reply struct and
231          * XDR filter depending on ypvers.
232          */
233         switch (q->ypvers) {
234         case YPVERS:
235                 bzero((char *)&result_v2, sizeof(result_v2));
236
237                 if (buf == NULL)
238                         result_v2.stat = YP_NOKEY;
239                 else {
240                         result_v2.val.valdat_len = strlen(buf);
241                         result_v2.val.valdat_val = buf;
242                         result_v2.stat = YP_TRUE;
243                 }
244                 result = (char *)&result_v2;
245                 xdrfunc = (xdrproc_t)xdr_ypresp_val;
246                 break;
247         case YPOLDVERS:
248                 /*
249                  * The odds are we will _never_ execute this
250                  * particular code, but we include it anyway
251                  * for the sake of completeness.
252                  */
253                 bzero((char *)&result_v1, sizeof(result_v1));
254                 result_v1.yp_resptype = YPRESP_VAL;
255 #               define YPVAL ypresponse_u.yp_resp_valtype
256
257                 if (buf == NULL)
258                         result_v1.YPVAL.stat = YP_NOKEY;
259                 else {
260                         result_v1.YPVAL.val.valdat_len = strlen(buf);
261                         result_v1.YPVAL.val.valdat_val = buf;
262                         result_v1.YPVAL.stat = YP_TRUE;
263                 }
264                 result = (char *)&result_v1;
265                 xdrfunc = (xdrproc_t)xdr_ypresponse;
266                 break;
267         default:
268                 yp_error("bad YP program version (%lu)!", q->ypvers);
269                         return;
270                 break;
271         }
272
273         if (debug)
274                 yp_error("sending dns reply to %s (%lu)",
275                         inet_ntoa(q->client_addr.sin_addr), q->id);
276         /*
277          * XXX This is disgusting. There's basically one transport
278          * handle for UDP, but we're holding off on replying to a
279          * client until we're ready, by which time we may have received
280          * several other queries from other clients with different
281          * transaction IDs. So to make the delayed response thing work,
282          * we have to save the transaction ID and client address of
283          * each request, then jam them into the transport handle when
284          * we're ready to send a reply. Then after we've send the reply,
285          * we put the old transaction ID and remote address back the
286          * way we found 'em. This is _INCREDIBLY_ non-portable; it's
287          * not even supported by the RPC library.
288          */
289         /*
290          * XXX Don't frob the transaction ID for TCP handles.
291          */
292         if (q->prot_type == SOCK_DGRAM)
293                 xid = svcudp_set_xid(q->xprt, q->xid);
294         client_addr = q->xprt->xp_raddr;
295         q->xprt->xp_raddr = q->client_addr;
296
297         if (!svc_sendreply(q->xprt, xdrfunc, result))
298                 yp_error("svc_sendreply failed");
299
300         /*
301          * Now that we sent the reply,
302          * put the handle back the way it was.
303          */
304         if (q->prot_type == SOCK_DGRAM)
305                 svcudp_set_xid(q->xprt, xid);
306         q->xprt->xp_raddr = client_addr;
307
308         return;
309 }
310
311 /*
312  * Decrement TTL on all queue entries, possibly nuking
313  * any that have been around too long without being serviced.
314  */
315 void yp_prune_dnsq()
316 {
317         register struct circleq_dnsentry *q, *n;
318
319         q = qhead.cqh_first;
320         while (q != (void *)&qhead) {
321                 q->ttl--;
322                 n = q->links.cqe_next;
323                 if (!q->ttl) {
324                         CIRCLEQ_REMOVE(&qhead, q, links);
325                         free(q->name);
326                         free(q);
327                         pending--;
328                 }
329                 q = n;
330         }
331
332         if (pending < 0)
333                 pending = 0;
334
335         return;
336 }
337
338 /*
339  * Data is pending on the DNS socket; check for valid replies
340  * to our queries and dispatch them to waiting clients.
341  */
342 void yp_run_dnsq()
343 {
344         register struct circleq_dnsentry *q;
345         char buf[sizeof(HEADER) + MAXPACKET];
346         char retrybuf[MAXHOSTNAMELEN];
347         struct sockaddr_in sin;
348         int rval;
349         int len;
350         HEADER *hptr;
351         struct hostent *hent;
352
353         if (debug)
354                 yp_error("running dns queue");
355
356         bzero(buf, sizeof(buf));
357
358         len = sizeof(struct sockaddr_in);
359         rval = recvfrom(resfd, buf, sizeof(buf), 0,
360                         (struct sockaddr *)&sin, &len);
361
362         if (rval == -1) {
363                 yp_error("recvfrom failed: %s", strerror(errno));
364                 return;
365         }
366
367         /*
368          * We may have data left in the socket that represents
369          * replies to earlier queries that we don't care about
370          * anymore. If there are no lookups pending or the packet
371          * ID doesn't match any of the queue IDs, just drop it
372          * on the floor.
373          */
374         hptr = (HEADER *)&buf;
375         if (!pending ||
376                 (q = yp_find_dnsqent(ntohs(hptr->id), BY_DNS_ID)) == NULL) {
377                 /* ignore */
378                 return;
379         }
380
381         if (debug)
382                 yp_error("got dns reply from %s", inet_ntoa(sin.sin_addr));
383
384         hent = __dns_getanswer(buf, rval, q->name, q->type);
385
386         /*
387          * If the lookup failed, try appending one of the domains
388          * from resolv.conf. If we have no domains to test, the
389          * query has failed.
390          */
391         if (hent == NULL) {
392                 if ((h_errno == TRY_AGAIN || h_errno == NO_RECOVERY)
393                                         && q->domain && *q->domain) {
394                         snprintf(retrybuf, sizeof(retrybuf), "%s.%s",
395                                                 q->name, *q->domain);
396                         if (debug)
397                                 yp_error("retrying with: %s", retrybuf);
398                         q->id = yp_send_dns_query(retrybuf, q->type);
399                         q->ttl = DEF_TTL;
400                         q->domain++;
401                         return;
402                 }
403         } else {
404                 if (q->type == T_PTR) {
405                         hent->h_addr = (char *)&q->addr.s_addr;
406                         hent->h_length = sizeof(struct in_addr);
407                 }
408         }
409
410         /* Got an answer ready for a client -- send it off. */
411         yp_send_dns_reply(q, parse(hent));
412         pending--;
413         CIRCLEQ_REMOVE(&qhead, q, links);
414         free(q->name);
415         free(q);
416
417         /* Decrement TTLs on other entries while we're here. */
418         yp_prune_dnsq();
419
420         return;
421 }
422
423 /*
424  * Queue and transmit an asynchronous DNS hostname lookup.
425  */
426 ypstat yp_async_lookup_name(rqstp, name)
427         struct svc_req *rqstp;
428         char *name;
429 {
430         register struct circleq_dnsentry *q;
431         int type, len;
432
433         /* Check for SOCK_DGRAM or SOCK_STREAM -- we need to know later */
434         type = -1; len = sizeof(type);
435         if (getsockopt(rqstp->rq_xprt->xp_sock, SOL_SOCKET,
436                                         SO_TYPE, &type, &len) == -1) {
437                 yp_error("getsockopt failed: %s", strerror(errno));
438                 return(YP_YPERR);
439         }
440
441         /* Avoid transmitting dupe requests. */
442         if (type == SOCK_DGRAM &&
443             yp_find_dnsqent(svcudp_get_xid(rqstp->rq_xprt),BY_RPC_XID) != NULL)
444                 return(YP_TRUE);
445
446         if ((q = yp_malloc_dnsent()) == NULL)
447                 return(YP_YPERR);
448
449         q->type = T_A;
450         q->ttl = DEF_TTL;
451         q->xprt = rqstp->rq_xprt;
452         q->ypvers = rqstp->rq_vers;
453         q->prot_type = type;
454         if (q->prot_type == SOCK_DGRAM)
455                 q->xid = svcudp_get_xid(q->xprt);
456         q->client_addr = q->xprt->xp_raddr;
457         q->domain = _res.dnsrch;
458         q->id = yp_send_dns_query(name, q->type);
459
460         if (q->id == 0) {
461                 yp_error("DNS query failed");
462                 free(q);
463                 return(YP_YPERR);
464         }
465
466         q->name = strdup(name);
467         CIRCLEQ_INSERT_HEAD(&qhead, q, links);
468         pending++;
469
470         if (debug)
471                 yp_error("queueing async DNS name lookup (%d)", q->id);
472
473         yp_prune_dnsq();
474         return(YP_TRUE);
475 }
476
477 /*
478  * Queue and transmit an asynchronous DNS IP address lookup.
479  */
480 ypstat yp_async_lookup_addr(rqstp, addr)
481         struct svc_req *rqstp;
482         char *addr;
483 {
484         register struct circleq_dnsentry *q;
485         char buf[MAXHOSTNAMELEN];
486         int a, b, c, d;
487         int type, len;
488
489         /* Check for SOCK_DGRAM or SOCK_STREAM -- we need to know later */
490         type = -1; len = sizeof(type);
491         if (getsockopt(rqstp->rq_xprt->xp_sock, SOL_SOCKET,
492                                         SO_TYPE, &type, &len) == -1) {
493                 yp_error("getsockopt failed: %s", strerror(errno));
494                 return(YP_YPERR);
495         }
496
497         /* Avoid transmitting dupe requests. */
498         if (type == SOCK_DGRAM &&
499             yp_find_dnsqent(svcudp_get_xid(rqstp->rq_xprt),BY_RPC_XID) != NULL)
500                 return(YP_TRUE);
501
502         if ((q = yp_malloc_dnsent()) == NULL)
503                 return(YP_YPERR);
504
505         if (sscanf(addr, "%d.%d.%d.%d", &a, &b, &c, &d) != 4)
506                 return(YP_NOKEY);
507
508         snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa", d, c, b, a);
509
510         if (debug)
511                 yp_error("DNS address is: %s", buf);
512
513         q->type = T_PTR;
514         q->ttl = DEF_TTL;
515         q->xprt = rqstp->rq_xprt;
516         q->ypvers = rqstp->rq_vers;
517         q->domain = NULL;
518         q->prot_type = type;
519         if (q->prot_type == SOCK_DGRAM)
520                 q->xid = svcudp_get_xid(q->xprt);
521         q->client_addr = q->xprt->xp_raddr;
522         q->id = yp_send_dns_query(buf, q->type);
523
524         if (q->id == 0) {
525                 yp_error("DNS query failed");
526                 free(q);
527                 return(YP_YPERR);
528         }
529
530         inet_aton(addr, &q->addr);
531         q->name = strdup(buf);
532         CIRCLEQ_INSERT_HEAD(&qhead, q, links);
533         pending++;
534
535         if (debug)
536                 yp_error("queueing async DNS address lookup (%d)", q->id);
537
538         yp_prune_dnsq();
539         return(YP_TRUE);
540 }