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