xref: /freebsd/lib/libc/net/getnetbydns.c (revision 6b3455a7665208c366849f0b2b3bc916fb97516e)
1 /*-
2  * Copyright (c) 1985, 1988, 1993
3  *	The Regents of the University of California.  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 the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  * -
33  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
34  *
35  * Permission to use, copy, modify, and distribute this software for any
36  * purpose with or without fee is hereby granted, provided that the above
37  * copyright notice and this permission notice appear in all copies, and that
38  * the name of Digital Equipment Corporation not be used in advertising or
39  * publicity pertaining to distribution of the document or software without
40  * specific, written prior permission.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
43  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
44  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
45  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
46  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
47  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
48  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
49  * SOFTWARE.
50  * -
51  * --Copyright--
52  */
53 /* Portions Copyright (c) 1993 Carlos Leandro and Rui Salgueiro
54  *	Dep. Matematica Universidade de Coimbra, Portugal, Europe
55  *
56  * Permission to use, copy, modify, and distribute this software for any
57  * purpose with or without fee is hereby granted, provided that the above
58  * copyright notice and this permission notice appear in all copies.
59  */
60 
61 #if defined(LIBC_SCCS) && !defined(lint)
62 static char sccsid[] = "@(#)gethostnamadr.c	8.1 (Berkeley) 6/4/93";
63 #endif /* LIBC_SCCS and not lint */
64 #include <sys/cdefs.h>
65 __FBSDID("$FreeBSD$");
66 
67 #include <sys/param.h>
68 #include <sys/socket.h>
69 #include <netinet/in.h>
70 #include <arpa/inet.h>
71 #include <arpa/nameser.h>
72 
73 #include <errno.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <netdb.h>
77 #include <resolv.h>
78 #include <ctype.h>
79 #include <string.h>
80 #include <unistd.h>
81 #include <syslog.h>
82 #include <stdarg.h>
83 #include <nsswitch.h>
84 
85 #include "res_config.h"
86 
87 extern int h_errno;
88 
89 #define BYADDR 0
90 #define BYNAME 1
91 #define	MAXALIASES	35
92 
93 #define MAXPACKET	(64*1024)
94 
95 typedef union {
96 	HEADER	hdr;
97 	u_char	buf[MAXPACKET];
98 } querybuf;
99 
100 typedef union {
101 	long	al;
102 	char	ac;
103 } align;
104 
105 /*
106  * Reverse the order of first four dotted entries of in.
107  * Out must contain space for at least strlen(in) characters.
108  * The result does not include any leading 0s of in.
109  */
110 static void
111 ipreverse(char *in, char *out)
112 {
113 	char *pos[4];
114 	int len[4];
115 	char *p, *start;
116 	int i = 0;
117 	int leading = 1;
118 
119 	/* Fill-in element positions and lengths: pos[], len[]. */
120 	start = p = in;
121 	for (;;) {
122 		if (*p == '.' || *p == '\0') {
123 			/* Leading 0? */
124 			if (leading && p - start == 1 && *start == '0')
125 				len[i] = 0;
126 			else {
127 				len[i] = p - start;
128 				leading = 0;
129 			}
130 			pos[i] = start;
131 			start = p + 1;
132 			i++;
133 		}
134 		if (i == 4)
135 			break;
136 		if (*p == 0) {
137 			for (; i < 4; i++) {
138 				pos[i] = p;
139 				len[i] = 0;
140 			}
141 			break;
142 		}
143 		p++;
144 	}
145 
146 	/* Copy the entries in reverse order */
147 	p = out;
148 	leading = 1;
149 	for (i = 3; i >= 0; i--) {
150 		memcpy(p, pos[i], len[i]);
151 		if (len[i])
152 			leading = 0;
153 		p += len[i];
154 		/* Need a . separator? */
155 		if (!leading && i > 0 && len[i - 1])
156 			*p++ = '.';
157 	}
158 	*p = '\0';
159 }
160 
161 static struct netent *
162 getnetanswer(answer, anslen, net_i)
163 	querybuf *answer;
164 	int anslen;
165 	int net_i;
166 {
167 
168 	HEADER *hp;
169 	u_char *cp;
170 	int n;
171 	u_char *eom;
172 	int type, class, ancount, qdcount, haveanswer;
173 	char aux[MAXHOSTNAMELEN];
174 	char *in, *bp, *ep, **ap;
175 static	struct netent net_entry;
176 static	char *net_aliases[MAXALIASES], netbuf[PACKETSZ];
177 static	char ans[MAXHOSTNAMELEN];
178 
179 	/*
180 	 * find first satisfactory answer
181 	 *
182 	 *      answer --> +------------+  ( MESSAGE )
183 	 *		   |   Header   |
184 	 *		   +------------+
185 	 *		   |  Question  | the question for the name server
186 	 *		   +------------+
187 	 *		   |   Answer   | RRs answering the question
188 	 *		   +------------+
189 	 *		   | Authority  | RRs pointing toward an authority
190 	 *		   | Additional | RRs holding additional information
191 	 *		   +------------+
192 	 */
193 	eom = answer->buf + anslen;
194 	hp = &answer->hdr;
195 	ancount = ntohs(hp->ancount); /* #/records in the answer section */
196 	qdcount = ntohs(hp->qdcount); /* #/entries in the question section */
197 	bp = netbuf;
198 	ep = netbuf + sizeof(netbuf);
199 	cp = answer->buf + HFIXEDSZ;
200 	if (!qdcount) {
201 		if (hp->aa)
202 			h_errno = HOST_NOT_FOUND;
203 		else
204 			h_errno = TRY_AGAIN;
205 		return (NULL);
206 	}
207 	while (qdcount-- > 0)
208 		cp += __dn_skipname(cp, eom) + QFIXEDSZ;
209 	ap = net_aliases;
210 	*ap = NULL;
211 	net_entry.n_aliases = net_aliases;
212 	haveanswer = 0;
213 	while (--ancount >= 0 && cp < eom) {
214 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
215 		if ((n < 0) || !res_dnok(bp))
216 			break;
217 		cp += n;
218 		ans[0] = '\0';
219 		(void)strncpy(&ans[0], bp, sizeof(ans) - 1);
220 		ans[sizeof(ans) - 1] = '\0';
221 		GETSHORT(type, cp);
222 		GETSHORT(class, cp);
223 		cp += INT32SZ;		/* TTL */
224 		GETSHORT(n, cp);
225 		if (class == C_IN && type == T_PTR) {
226 			n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
227 			if ((n < 0) || !res_hnok(bp)) {
228 				cp += n;
229 				return (NULL);
230 			}
231 			cp += n;
232 			*ap++ = bp;
233 			n = strlen(bp) + 1;
234 			bp += n;
235 			net_entry.n_addrtype =
236 				(class == C_IN) ? AF_INET : AF_UNSPEC;
237 			haveanswer++;
238 		}
239 	}
240 	if (haveanswer) {
241 		*ap = NULL;
242 		switch (net_i) {
243 		case BYADDR:
244 			net_entry.n_name = *net_entry.n_aliases;
245 			net_entry.n_net = 0L;
246 			break;
247 		case BYNAME:
248 			in = *net_entry.n_aliases;
249 			net_entry.n_name = &ans[0];
250 			if (strlen(in) + 1 > sizeof(aux)) {
251 				h_errno = NETDB_INTERNAL;
252 				errno = ENOBUFS;
253 				return (NULL);
254 			}
255 			ipreverse(in, aux);
256 			net_entry.n_net = inet_network(aux);
257 			break;
258 		}
259 		net_entry.n_aliases++;
260 		return (&net_entry);
261 	}
262 	h_errno = TRY_AGAIN;
263 	return (NULL);
264 }
265 
266 int
267 _dns_getnetbyaddr(void *rval, void *cb_data, va_list ap)
268 {
269 	unsigned long net;
270 	int net_type;
271 	unsigned int netbr[4];
272 	int nn, anslen;
273 	querybuf *buf;
274 	char qbuf[MAXDNAME];
275 	unsigned long net2;
276 	struct netent *net_entry;
277 
278 	net = va_arg(ap, unsigned long);
279 	net_type = va_arg(ap, int);
280 
281 	*(struct netent **)rval = NULL;
282 
283 	if (net_type != AF_INET)
284 		return NS_UNAVAIL;
285 
286 	for (nn = 4, net2 = net; net2; net2 >>= 8)
287 		netbr[--nn] = net2 & 0xff;
288 	switch (nn) {
289 	case 3: 	/* Class A */
290 		sprintf(qbuf, "0.0.0.%u.in-addr.arpa", netbr[3]);
291 		break;
292 	case 2: 	/* Class B */
293 		sprintf(qbuf, "0.0.%u.%u.in-addr.arpa", netbr[3], netbr[2]);
294 		break;
295 	case 1: 	/* Class C */
296 		sprintf(qbuf, "0.%u.%u.%u.in-addr.arpa", netbr[3], netbr[2],
297 		    netbr[1]);
298 		break;
299 	case 0: 	/* Class D - E */
300 		sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa", netbr[3], netbr[2],
301 		    netbr[1], netbr[0]);
302 		break;
303 	}
304 	if ((buf = malloc(sizeof(*buf))) == NULL) {
305 		h_errno = NETDB_INTERNAL;
306 		return NS_NOTFOUND;
307 	}
308 	anslen = res_query(qbuf, C_IN, T_PTR, (u_char *)buf, sizeof(*buf));
309 	if (anslen < 0) {
310 		free(buf);
311 #ifdef DEBUG
312 		if (_res.options & RES_DEBUG)
313 			printf("res_search failed\n");
314 #endif
315 		return NS_UNAVAIL;
316 	} else if (anslen > sizeof(*buf)) {
317 		free(buf);
318 #ifdef DEBUG
319 		if (_res.options & RES_DEBUG)
320 			printf("res_search static buffer too small\n");
321 #endif
322 		return NS_UNAVAIL;
323 	}
324 	net_entry = getnetanswer(buf, anslen, BYADDR);
325 	free(buf);
326 	if (net_entry) {
327 		unsigned u_net = net;	/* maybe net should be unsigned ? */
328 
329 		/* Strip trailing zeros */
330 		while ((u_net & 0xff) == 0 && u_net != 0)
331 			u_net >>= 8;
332 		net_entry->n_net = u_net;
333 		*(struct netent **)rval = net_entry;
334 		return NS_SUCCESS;
335 	}
336 	return NS_NOTFOUND;
337 }
338 
339 int
340 _dns_getnetbyname(void *rval, void *cb_data, va_list ap)
341 {
342 	const char *net;
343 	int anslen;
344 	querybuf *buf;
345 	char qbuf[MAXDNAME];
346 
347 	net = va_arg(ap, const char *);
348 
349 	*(struct netent**)rval = NULL;
350 
351 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
352 		h_errno = NETDB_INTERNAL;
353 		return NS_UNAVAIL;
354 	}
355 	if ((buf = malloc(sizeof(*buf))) == NULL) {
356 		h_errno = NETDB_INTERNAL;
357 		return NS_NOTFOUND;
358 	}
359 	strncpy(qbuf, net, sizeof(qbuf) - 1);
360 	qbuf[sizeof(qbuf) - 1] = '\0';
361 	anslen = res_search(qbuf, C_IN, T_PTR, (u_char *)buf, sizeof(*buf));
362 	if (anslen < 0) {
363 		free(buf);
364 #ifdef DEBUG
365 		if (_res.options & RES_DEBUG)
366 			printf("res_search failed\n");
367 #endif
368 		return NS_UNAVAIL;
369 	} else if (anslen > sizeof(*buf)) {
370 		free(buf);
371 #ifdef DEBUG
372 		if (_res.options & RES_DEBUG)
373 			printf("res_search static buffer too small\n");
374 #endif
375 		return NS_UNAVAIL;
376 	}
377 	*(struct netent**)rval = getnetanswer(buf, anslen, BYNAME);
378 	free(buf);
379 	return (*(struct netent**)rval != NULL) ? NS_SUCCESS : NS_NOTFOUND;
380 }
381 
382 void
383 _setnetdnsent(stayopen)
384 	int stayopen;
385 {
386 	if (stayopen)
387 		_res.options |= RES_STAYOPEN | RES_USEVC;
388 }
389 
390 void
391 _endnetdnsent()
392 {
393 	_res.options &= ~(RES_STAYOPEN | RES_USEVC);
394 	res_close();
395 }
396