kernel - Reduce lwp_signotify() latency
[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.27 2005/05/20 13:04:10 charnier Exp $
33  */
34
35 /*
36  * Do standard and reverse DNS lookups using the resolver library.
37  * Take care of all the dirty work here so the main program only has to
38  * pass us a pointer to an array of characters.
39  *
40  * We have to use direct resolver calls here otherwise the YP server
41  * could end up looping by calling itself over and over again until
42  * it disappeared up its own belly button.
43  */
44
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #include <sys/time.h>
48 #include <sys/fcntl.h>
49 #include <sys/queue.h>
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
52 #include <arpa/nameser.h>
53
54 #include <ctype.h>
55 #include <errno.h>
56 #include <netdb.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <resolv.h>
61 #include <unistd.h>
62
63 #include <rpcsvc/yp.h>
64 #include "yp_extern.h"
65
66 static char *
67 parse(struct hostent *hp)
68 {
69         static char result[MAXHOSTNAMELEN * 2];
70         int i;
71         size_t len;
72         char addr[46];
73
74         if (hp == NULL)
75                 return(NULL);
76
77         if (inet_ntop(hp->h_addrtype, hp->h_addr, addr, sizeof(addr)) == NULL)
78                 return(NULL);
79
80         len = strlen(addr) + 1 + strlen(hp->h_name);
81         for (i = 0; hp->h_aliases[i]; i++)
82                 len += strlen(hp->h_aliases[i]) + 1;
83         len++;
84
85         if (len > sizeof(result))
86                 return(NULL);
87
88         bzero(result, sizeof(result));
89         snprintf(result, sizeof(result), "%s %s", addr, hp->h_name);
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 (64*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 TAILQ_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         int addrtype;
120         int addrlen;
121         uint32_t addr[4];       /* IPv4 or IPv6 */
122         TAILQ_ENTRY(circleq_dnsentry) links;
123 };
124
125 static int pending = 0;
126
127 int
128 yp_init_resolver(void)
129 {
130         TAILQ_INIT(&qhead);
131         if (!(_res.options & RES_INIT) && res_init() == -1) {
132                 yp_error("res_init failed");
133                 return(1);
134         }
135         if ((resfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
136                 yp_error("couldn't create socket");
137                 return(1);
138         }
139         if (fcntl(resfd, F_SETFL, O_NONBLOCK) == -1) {
140                 yp_error("couldn't make resolver socket non-blocking");
141                 return(1);
142         }
143         return(0);
144 }
145
146 static struct circleq_dnsentry *
147 yp_malloc_dnsent(void)
148 {
149         struct circleq_dnsentry *q;
150
151         q = (struct circleq_dnsentry *)malloc(sizeof(struct circleq_dnsentry));
152
153         if (q == NULL) {
154                 yp_error("failed to malloc() circleq dns entry");
155                 return(NULL);
156         }
157
158         return(q);
159 }
160
161 /*
162  * Transmit a query.
163  */
164 static unsigned long
165 yp_send_dns_query(char *name, int type)
166 {
167         char buf[MAXPACKET];
168         int n;
169         HEADER *hptr;
170         int ns;
171         int rval;
172         unsigned long id;
173
174         bzero(buf, sizeof(buf));
175
176         n = res_mkquery(QUERY,name,C_IN,type,NULL,0,NULL,buf,sizeof(buf));
177
178         if (n <= 0) {
179                 yp_error("res_mkquery failed for %s type %d", name, type);
180                 return(0);
181         }
182
183         hptr = (HEADER *)&buf;
184         id = ntohs(hptr->id);
185
186         for (ns = 0; ns < _res.nscount; ns++) {
187                 rval = sendto(resfd, buf, n, 0,
188                         (struct sockaddr *)&_res.nsaddr_list[ns],
189                                 sizeof(struct sockaddr));
190                 if (rval == -1) {
191                         yp_error("sendto failed");
192                         return(0);
193                 }
194         }
195
196         return(id);
197 }
198
199 static struct circleq_dnsentry *
200 yp_find_dnsqent(unsigned long id, int type)
201 {
202         struct circleq_dnsentry *q;
203
204         TAILQ_FOREACH(q, &qhead, links) {
205                 switch (type) {
206                 case BY_RPC_XID:
207                         if (id == q->xid)
208                                 return(q);
209                         break;
210                 case BY_DNS_ID:
211                 default:
212                         if (id == q->id)
213                                 return(q);
214                         break;
215                 }
216         }
217         return (NULL);
218 }
219
220 static void
221 yp_send_dns_reply(struct circleq_dnsentry *q, char *buf)
222 {
223         ypresponse result_v1;
224         ypresp_val result_v2;
225         unsigned long xid;
226         struct sockaddr_in client_addr;
227         xdrproc_t xdrfunc;
228         char *result;
229
230         /*
231          * Set up correct reply struct and
232          * XDR filter depending on ypvers.
233          */
234         switch (q->ypvers) {
235         case YPVERS:
236                 bzero((char *)&result_v2, sizeof(result_v2));
237
238                 if (buf == NULL)
239                         result_v2.stat = YP_NOKEY;
240                 else {
241                         result_v2.val.valdat_len = strlen(buf);
242                         result_v2.val.valdat_val = buf;
243                         result_v2.stat = YP_TRUE;
244                 }
245                 result = (char *)&result_v2;
246                 xdrfunc = (xdrproc_t)xdr_ypresp_val;
247                 break;
248         case YPOLDVERS:
249                 /*
250                  * The odds are we will _never_ execute this
251                  * particular code, but we include it anyway
252                  * for the sake of completeness.
253                  */
254                 bzero((char *)&result_v1, sizeof(result_v1));
255                 result_v1.yp_resptype = YPRESP_VAL;
256
257 #define YPVAL ypresponse_u.yp_resp_valtype
258                 if (buf == NULL)
259                         result_v1.YPVAL.stat = YP_NOKEY;
260                 else {
261                         result_v1.YPVAL.val.valdat_len = strlen(buf);
262                         result_v1.YPVAL.val.valdat_val = buf;
263                         result_v1.YPVAL.stat = YP_TRUE;
264                 }
265                 result = (char *)&result_v1;
266                 xdrfunc = (xdrproc_t)xdr_ypresponse;
267                 break;
268         default:
269                 yp_error("bad YP program version (%lu)!", q->ypvers);
270                         return;
271                 break;
272         }
273
274         if (debug)
275                 yp_error("sending dns reply to %s (%lu)",
276                         inet_ntoa(q->client_addr.sin_addr), q->id);
277         /*
278          * XXX This is disgusting. There's basically one transport
279          * handle for UDP, but we're holding off on replying to a
280          * client until we're ready, by which time we may have received
281          * several other queries from other clients with different
282          * transaction IDs. So to make the delayed response thing work,
283          * we have to save the transaction ID and client address of
284          * each request, then jam them into the transport handle when
285          * we're ready to send a reply. Then after we've send the reply,
286          * we put the old transaction ID and remote address back the
287          * way we found 'em. This is _INCREDIBLY_ non-portable; it's
288          * not even supported by the RPC library.
289          */
290         /*
291          * XXX Don't frob the transaction ID for TCP handles.
292          */
293         if (q->prot_type == SOCK_DGRAM)
294                 xid = svcudp_set_xid(q->xprt, q->xid);
295         client_addr = q->xprt->xp_raddr;
296         q->xprt->xp_raddr = q->client_addr;
297
298         if (!svc_sendreply(q->xprt, xdrfunc, result))
299                 yp_error("svc_sendreply failed");
300
301         /*
302          * Now that we sent the reply,
303          * put the handle back the way it was.
304          */
305         if (q->prot_type == SOCK_DGRAM)
306                 svcudp_set_xid(q->xprt, xid);
307         q->xprt->xp_raddr = client_addr;
308
309         return;
310 }
311
312 /*
313  * Decrement TTL on all queue entries, possibly nuking
314  * any that have been around too long without being serviced.
315  */
316 void
317 yp_prune_dnsq(void)
318 {
319         struct circleq_dnsentry *q, *n;
320
321         q = TAILQ_FIRST(&qhead);
322         while (q != NULL) {
323                 q->ttl--;
324                 n = TAILQ_NEXT(q, links);
325                 if (!q->ttl) {
326                         TAILQ_REMOVE(&qhead, q, links);
327                         free(q->name);
328                         free(q);
329                         pending--;
330                 }
331                 q = n;
332         }
333
334         if (pending < 0)
335                 pending = 0;
336
337         return;
338 }
339
340 /*
341  * Data is pending on the DNS socket; check for valid replies
342  * to our queries and dispatch them to waiting clients.
343  */
344 void
345 yp_run_dnsq(void)
346 {
347         struct circleq_dnsentry *q;
348         char buf[sizeof(HEADER) + MAXPACKET];
349         struct sockaddr_in sin;
350         socklen_t len;
351         int rval;
352         HEADER *hptr;
353         struct hostent *hent;
354
355         if (debug)
356                 yp_error("running dns queue");
357
358         bzero(buf, sizeof(buf));
359
360         len = sizeof(struct sockaddr_in);
361         rval = recvfrom(resfd, buf, sizeof(buf), 0,
362                         (struct sockaddr *)&sin, &len);
363
364         if (rval == -1) {
365                 yp_error("recvfrom failed: %s", strerror(errno));
366                 return;
367         }
368
369         /*
370          * We may have data left in the socket that represents
371          * replies to earlier queries that we don't care about
372          * anymore. If there are no lookups pending or the packet
373          * ID doesn't match any of the queue IDs, just drop it
374          * on the floor.
375          */
376         hptr = (HEADER *)&buf;
377         if (!pending ||
378                 (q = yp_find_dnsqent(ntohs(hptr->id), BY_DNS_ID)) == NULL) {
379                 /* ignore */
380                 return;
381         }
382
383         if (debug)
384                 yp_error("got dns reply from %s", inet_ntoa(sin.sin_addr));
385
386         hent = __dns_getanswer(buf, rval, q->name, q->type);
387
388         if (hent != NULL) {
389                 if (q->type == T_PTR) {
390                         hent->h_addr = (char *)q->addr;
391                         hent->h_addrtype = q->addrtype;
392                         hent->h_length = q->addrlen;
393                 }
394         }
395
396         /* Got an answer ready for a client -- send it off. */
397         yp_send_dns_reply(q, parse(hent));
398         pending--;
399         TAILQ_REMOVE(&qhead, q, links);
400         free(q->name);
401         free(q);
402
403         /* Decrement TTLs on other entries while we're here. */
404         yp_prune_dnsq();
405
406         return;
407 }
408
409 /*
410  * Queue and transmit an asynchronous DNS hostname lookup.
411  */
412 ypstat
413 yp_async_lookup_name(struct svc_req *rqstp, char *name, int af)
414 {
415         struct circleq_dnsentry *q;
416         socklen_t len;
417         int type;
418
419         /* Check for SOCK_DGRAM or SOCK_STREAM -- we need to know later */
420         type = -1;
421         len = sizeof(type);
422         if (getsockopt(rqstp->rq_xprt->xp_fd, SOL_SOCKET,
423                                         SO_TYPE, &type, &len) == -1) {
424                 yp_error("getsockopt failed: %s", strerror(errno));
425                 return(YP_YPERR);
426         }
427
428         /* Avoid transmitting dupe requests. */
429         if (type == SOCK_DGRAM &&
430             yp_find_dnsqent(svcudp_get_xid(rqstp->rq_xprt),BY_RPC_XID) != NULL)
431                 return(YP_TRUE);
432
433         if ((q = yp_malloc_dnsent()) == NULL)
434                 return(YP_YPERR);
435
436         q->type = (af == AF_INET) ? T_A : T_AAAA;
437         q->ttl = DEF_TTL;
438         q->xprt = rqstp->rq_xprt;
439         q->ypvers = rqstp->rq_vers;
440         q->prot_type = type;
441         if (q->prot_type == SOCK_DGRAM)
442                 q->xid = svcudp_get_xid(q->xprt);
443         q->client_addr = q->xprt->xp_raddr;
444         q->domain = _res.dnsrch;
445         q->id = yp_send_dns_query(name, q->type);
446
447         if (q->id == 0) {
448                 yp_error("DNS query failed");
449                 free(q);
450                 return(YP_YPERR);
451         }
452
453         q->name = strdup(name);
454         TAILQ_INSERT_HEAD(&qhead, q, links);
455         pending++;
456
457         if (debug)
458                 yp_error("queueing async DNS name lookup (%lu)", q->id);
459
460         yp_prune_dnsq();
461         return(YP_TRUE);
462 }
463
464 /*
465  * Queue and transmit an asynchronous DNS IP address lookup.
466  */
467 ypstat
468 yp_async_lookup_addr(struct svc_req *rqstp, char *addr, int af)
469 {
470         struct circleq_dnsentry *q;
471         char buf[MAXHOSTNAMELEN], *qp;
472         uint32_t abuf[4];       /* IPv4 or IPv6 */
473         u_char *uaddr = (u_char *)abuf;
474         socklen_t len;
475         int type, n;
476
477         /* Check for SOCK_DGRAM or SOCK_STREAM -- we need to know later */
478         type = -1;
479         len = sizeof(type);
480         if (getsockopt(rqstp->rq_xprt->xp_fd, SOL_SOCKET,
481                                         SO_TYPE, &type, &len) == -1) {
482                 yp_error("getsockopt failed: %s", strerror(errno));
483                 return(YP_YPERR);
484         }
485
486         /* Avoid transmitting dupe requests. */
487         if (type == SOCK_DGRAM &&
488             yp_find_dnsqent(svcudp_get_xid(rqstp->rq_xprt),BY_RPC_XID) != NULL)
489                 return(YP_TRUE);
490
491         if ((q = yp_malloc_dnsent()) == NULL)
492                 return(YP_YPERR);
493
494         switch (af) {
495         case AF_INET:
496                 if (inet_aton(addr, (struct in_addr *)uaddr) != 1)
497                         return(YP_NOKEY);
498                 snprintf(buf, sizeof(buf), "%u.%u.%u.%u.in-addr.arpa",
499                     (uaddr[3] & 0xff), (uaddr[2] & 0xff),
500                     (uaddr[1] & 0xff), (uaddr[0] & 0xff));
501                 len = INADDRSZ;
502                 break;
503         case AF_INET6:
504                 if (inet_pton(af, addr, uaddr) != 1)
505                         return(YP_NOKEY);
506                 qp = buf;
507                 for (n = IN6ADDRSZ - 1; n >= 0; n--) {
508                         qp += (size_t)sprintf(qp, "%x.%x.", uaddr[n] & 0xf,
509                             (uaddr[n] >> 4) & 0xf);
510                 }
511                 strlcat(buf, "ip6.arpa", sizeof(buf));
512                 len = IN6ADDRSZ;
513                 break;
514         default:
515                 return(YP_YPERR);
516         }
517
518         if (debug)
519                 yp_error("DNS address is: %s", buf);
520
521         q->type = T_PTR;
522         q->ttl = DEF_TTL;
523         q->xprt = rqstp->rq_xprt;
524         q->ypvers = rqstp->rq_vers;
525         q->domain = NULL;
526         q->prot_type = type;
527         if (q->prot_type == SOCK_DGRAM)
528                 q->xid = svcudp_get_xid(q->xprt);
529         q->client_addr = q->xprt->xp_raddr;
530         q->id = yp_send_dns_query(buf, q->type);
531
532         if (q->id == 0) {
533                 yp_error("DNS query failed");
534                 free(q);
535                 return(YP_YPERR);
536         }
537
538         memcpy(q->addr, uaddr, len);
539         q->addrlen = len;
540         q->addrtype = af;
541         q->name = strdup(buf);
542         TAILQ_INSERT_HEAD(&qhead, q, links);
543         pending++;
544
545         if (debug)
546                 yp_error("queueing async DNS address lookup (%lu)", q->id);
547
548         yp_prune_dnsq();
549         return(YP_TRUE);
550 }