yp_dnslookup.c revision 143415
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
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/usr.sbin/ypserv/yp_dnslookup.c 143415 2005-03-11 14:17:12Z stefanf $");
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
67static char *
68parse(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
104extern struct hostent *__dns_getanswer(char *, int, char *, int);
105
106static TAILQ_HEAD(dns_qhead, circleq_dnsentry) qhead;
107
108struct 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	TAILQ_ENTRY(circleq_dnsentry) links;
121};
122
123static int pending = 0;
124
125int
126yp_init_resolver(void)
127{
128	TAILQ_INIT(&qhead);
129	if (!(_res.options & RES_INIT) && res_init() == -1) {
130		yp_error("res_init failed");
131		return(1);
132	}
133	if ((resfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
134		yp_error("couldn't create socket");
135		return(1);
136	}
137	if (fcntl(resfd, F_SETFL, O_NONBLOCK) == -1) {
138		yp_error("couldn't make resolver socket non-blocking");
139		return(1);
140	}
141	return(0);
142}
143
144static struct
145circleq_dnsentry *yp_malloc_dnsent(void)
146{
147	register struct circleq_dnsentry *q;
148
149	q = (struct circleq_dnsentry *)malloc(sizeof(struct circleq_dnsentry));
150
151	if (q == NULL) {
152		yp_error("failed to malloc() circleq dns entry");
153		return(NULL);
154	}
155
156	return(q);
157}
158
159/*
160 * Transmit a query.
161 */
162static unsigned long
163yp_send_dns_query(char *name, int type)
164{
165	char buf[MAXPACKET];
166	int n;
167	HEADER *hptr;
168	int ns;
169	int rval;
170	unsigned long id;
171
172	bzero(buf, sizeof(buf));
173
174	n = res_mkquery(QUERY,name,C_IN,type,NULL,0,NULL,buf,sizeof(buf));
175
176	if (n <= 0) {
177		yp_error("res_mkquery failed for %s type %d", name, type);
178		return(0);
179	}
180
181	hptr = (HEADER *)&buf;
182	id = ntohs(hptr->id);
183
184	for (ns = 0; ns < _res.nscount; ns++) {
185		rval = sendto(resfd, buf, n, 0,
186			(struct sockaddr *)&_res.nsaddr_list[ns],
187				sizeof(struct sockaddr));
188		if (rval == -1) {
189			yp_error("sendto failed");
190			return(0);
191		}
192	}
193
194	return(id);
195}
196
197static struct circleq_dnsentry *
198yp_find_dnsqent(unsigned long id, int type)
199{
200	register struct circleq_dnsentry *q;
201
202	TAILQ_FOREACH(q, &qhead, links) {
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
218static void
219yp_send_dns_reply(struct circleq_dnsentry *q, char *buf)
220{
221	ypresponse result_v1;
222	ypresp_val result_v2;
223	unsigned long xid;
224	struct sockaddr_in client_addr;
225	xdrproc_t xdrfunc;
226	char *result;
227
228	/*
229	 * Set up correct reply struct and
230	 * XDR filter depending on ypvers.
231	 */
232	switch (q->ypvers) {
233	case YPVERS:
234		bzero((char *)&result_v2, sizeof(result_v2));
235
236		if (buf == NULL)
237			result_v2.stat = YP_NOKEY;
238		else {
239			result_v2.val.valdat_len = strlen(buf);
240			result_v2.val.valdat_val = buf;
241			result_v2.stat = YP_TRUE;
242		}
243		result = (char *)&result_v2;
244		xdrfunc = (xdrproc_t)xdr_ypresp_val;
245		break;
246	case YPOLDVERS:
247		/*
248		 * The odds are we will _never_ execute this
249		 * particular code, but we include it anyway
250		 * for the sake of completeness.
251		 */
252		bzero((char *)&result_v1, sizeof(result_v1));
253		result_v1.yp_resptype = YPRESP_VAL;
254
255#define YPVAL ypresponse_u.yp_resp_valtype
256		if (buf == NULL)
257			result_v1.YPVAL.stat = YP_NOKEY;
258		else {
259			result_v1.YPVAL.val.valdat_len = strlen(buf);
260			result_v1.YPVAL.val.valdat_val = buf;
261			result_v1.YPVAL.stat = YP_TRUE;
262		}
263		result = (char *)&result_v1;
264		xdrfunc = (xdrproc_t)xdr_ypresponse;
265		break;
266	default:
267		yp_error("bad YP program version (%lu)!", q->ypvers);
268			return;
269		break;
270	}
271
272	if (debug)
273		yp_error("sending dns reply to %s (%lu)",
274			inet_ntoa(q->client_addr.sin_addr), q->id);
275	/*
276	 * XXX This is disgusting. There's basically one transport
277	 * handle for UDP, but we're holding off on replying to a
278	 * client until we're ready, by which time we may have received
279	 * several other queries from other clients with different
280	 * transaction IDs. So to make the delayed response thing work,
281	 * we have to save the transaction ID and client address of
282	 * each request, then jam them into the transport handle when
283	 * we're ready to send a reply. Then after we've send the reply,
284	 * we put the old transaction ID and remote address back the
285	 * way we found 'em. This is _INCREDIBLY_ non-portable; it's
286	 * not even supported by the RPC library.
287	 */
288	/*
289	 * XXX Don't frob the transaction ID for TCP handles.
290	 */
291	if (q->prot_type == SOCK_DGRAM)
292		xid = svcudp_set_xid(q->xprt, q->xid);
293	client_addr = q->xprt->xp_raddr;
294	q->xprt->xp_raddr = q->client_addr;
295
296	if (!svc_sendreply(q->xprt, xdrfunc, result))
297		yp_error("svc_sendreply failed");
298
299	/*
300	 * Now that we sent the reply,
301	 * put the handle back the way it was.
302	 */
303	if (q->prot_type == SOCK_DGRAM)
304		svcudp_set_xid(q->xprt, xid);
305	q->xprt->xp_raddr = client_addr;
306
307	return;
308}
309
310/*
311 * Decrement TTL on all queue entries, possibly nuking
312 * any that have been around too long without being serviced.
313 */
314void
315yp_prune_dnsq(void)
316{
317	register struct circleq_dnsentry *q, *n;
318
319	q = TAILQ_FIRST(&qhead);
320	while (q != NULL) {
321		q->ttl--;
322		n = TAILQ_NEXT(q, links);
323		if (!q->ttl) {
324			TAILQ_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 */
342void
343yp_run_dnsq(void)
344{
345	register struct circleq_dnsentry *q;
346	char buf[sizeof(HEADER) + MAXPACKET];
347	char retrybuf[MAXHOSTNAMELEN];
348	struct sockaddr_in sin;
349	socklen_t len;
350	int rval;
351	HEADER *hptr;
352	struct hostent *hent;
353
354	if (debug)
355		yp_error("running dns queue");
356
357	bzero(buf, sizeof(buf));
358
359	len = sizeof(struct sockaddr_in);
360	rval = recvfrom(resfd, buf, sizeof(buf), 0,
361			(struct sockaddr *)&sin, &len);
362
363	if (rval == -1) {
364		yp_error("recvfrom failed: %s", strerror(errno));
365		return;
366	}
367
368	/*
369	 * We may have data left in the socket that represents
370	 * replies to earlier queries that we don't care about
371	 * anymore. If there are no lookups pending or the packet
372	 * ID doesn't match any of the queue IDs, just drop it
373	 * on the floor.
374	 */
375	hptr = (HEADER *)&buf;
376	if (!pending ||
377		(q = yp_find_dnsqent(ntohs(hptr->id), BY_DNS_ID)) == NULL) {
378		/* ignore */
379		return;
380	}
381
382	if (debug)
383		yp_error("got dns reply from %s", inet_ntoa(sin.sin_addr));
384
385	hent = __dns_getanswer(buf, rval, q->name, q->type);
386
387	if (hent != NULL) {
388		if (q->type == T_PTR) {
389			hent->h_addr = (char *)&q->addr.s_addr;
390			hent->h_length = sizeof(struct in_addr);
391		}
392	}
393
394	/* Got an answer ready for a client -- send it off. */
395	yp_send_dns_reply(q, parse(hent));
396	pending--;
397	TAILQ_REMOVE(&qhead, q, links);
398	free(q->name);
399	free(q);
400
401	/* Decrement TTLs on other entries while we're here. */
402	yp_prune_dnsq();
403
404	return;
405}
406
407/*
408 * Queue and transmit an asynchronous DNS hostname lookup.
409 */
410ypstat
411yp_async_lookup_name(struct svc_req *rqstp, char *name)
412{
413	register struct circleq_dnsentry *q;
414	socklen_t len;
415	int type;
416
417	/* Check for SOCK_DGRAM or SOCK_STREAM -- we need to know later */
418	type = -1;
419	len = sizeof(type);
420	if (getsockopt(rqstp->rq_xprt->xp_fd, SOL_SOCKET,
421					SO_TYPE, &type, &len) == -1) {
422		yp_error("getsockopt failed: %s", strerror(errno));
423		return(YP_YPERR);
424	}
425
426	/* Avoid transmitting dupe requests. */
427	if (type == SOCK_DGRAM &&
428	    yp_find_dnsqent(svcudp_get_xid(rqstp->rq_xprt),BY_RPC_XID) != NULL)
429		return(YP_TRUE);
430
431	if ((q = yp_malloc_dnsent()) == NULL)
432		return(YP_YPERR);
433
434	q->type = T_A;
435	q->ttl = DEF_TTL;
436	q->xprt = rqstp->rq_xprt;
437	q->ypvers = rqstp->rq_vers;
438	q->prot_type = type;
439	if (q->prot_type == SOCK_DGRAM)
440		q->xid = svcudp_get_xid(q->xprt);
441	q->client_addr = q->xprt->xp_raddr;
442	q->domain = _res.dnsrch;
443	q->id = yp_send_dns_query(name, q->type);
444
445	if (q->id == 0) {
446		yp_error("DNS query failed");
447		free(q);
448		return(YP_YPERR);
449	}
450
451	q->name = strdup(name);
452	TAILQ_INSERT_HEAD(&qhead, q, links);
453	pending++;
454
455	if (debug)
456		yp_error("queueing async DNS name lookup (%d)", q->id);
457
458	yp_prune_dnsq();
459	return(YP_TRUE);
460}
461
462/*
463 * Queue and transmit an asynchronous DNS IP address lookup.
464 */
465ypstat
466yp_async_lookup_addr(struct svc_req *rqstp, char *addr)
467{
468	register struct circleq_dnsentry *q;
469	char buf[MAXHOSTNAMELEN];
470	socklen_t len;
471	int a, b, c, d;
472	int type;
473
474	/* Check for SOCK_DGRAM or SOCK_STREAM -- we need to know later */
475	type = -1;
476	len = sizeof(type);
477	if (getsockopt(rqstp->rq_xprt->xp_fd, SOL_SOCKET,
478					SO_TYPE, &type, &len) == -1) {
479		yp_error("getsockopt failed: %s", strerror(errno));
480		return(YP_YPERR);
481	}
482
483	/* Avoid transmitting dupe requests. */
484	if (type == SOCK_DGRAM &&
485	    yp_find_dnsqent(svcudp_get_xid(rqstp->rq_xprt),BY_RPC_XID) != NULL)
486		return(YP_TRUE);
487
488	if ((q = yp_malloc_dnsent()) == NULL)
489		return(YP_YPERR);
490
491	if (sscanf(addr, "%d.%d.%d.%d", &a, &b, &c, &d) != 4)
492		return(YP_NOKEY);
493
494	snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa", d, c, b, a);
495
496	if (debug)
497		yp_error("DNS address is: %s", buf);
498
499	q->type = T_PTR;
500	q->ttl = DEF_TTL;
501	q->xprt = rqstp->rq_xprt;
502	q->ypvers = rqstp->rq_vers;
503	q->domain = NULL;
504	q->prot_type = type;
505	if (q->prot_type == SOCK_DGRAM)
506		q->xid = svcudp_get_xid(q->xprt);
507	q->client_addr = q->xprt->xp_raddr;
508	q->id = yp_send_dns_query(buf, q->type);
509
510	if (q->id == 0) {
511		yp_error("DNS query failed");
512		free(q);
513		return(YP_YPERR);
514	}
515
516	inet_aton(addr, &q->addr);
517	q->name = strdup(buf);
518	TAILQ_INSERT_HEAD(&qhead, q, links);
519	pending++;
520
521	if (debug)
522		yp_error("queueing async DNS address lookup (%d)", q->id);
523
524	yp_prune_dnsq();
525	return(YP_TRUE);
526}
527