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