1 /*
2  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
7  *
8  * See the COPYRIGHT file distributed with this work for additional
9  * information regarding copyright ownership.
10  */
11 
12 /*! \file */
13 
14 /*
15  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. Neither the name of the project nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  */
42 
43 /**
44  *    getnameinfo() returns the hostname for the struct sockaddr sa which is
45  *    salen bytes long. The hostname is of length hostlen and is returned via
46  *    *host. The maximum length of the hostname is 1025 bytes: #NI_MAXHOST.
47  *
48  *    The name of the service associated with the port number in sa is
49  *    returned in *serv. It is servlen bytes long. The maximum length of the
50  *    service name is #NI_MAXSERV - 32 bytes.
51  *
52  *    The flags argument sets the following bits:
53  *
54  * \li   #NI_NOFQDN:
55  *           A fully qualified domain name is not required for local hosts.
56  *           The local part of the fully qualified domain name is returned
57  *           instead.
58  *
59  * \li   #NI_NUMERICHOST
60  *           Return the address in numeric form, as if calling inet_ntop(),
61  *           instead of a host name.
62  *
63  * \li   #NI_NAMEREQD
64  *           A name is required. If the hostname cannot be found in the DNS
65  *           and this flag is set, a non-zero error code is returned. If the
66  *           hostname is not found and the flag is not set, the address is
67  *           returned in numeric form.
68  *
69  * \li   #NI_NUMERICSERV
70  *           The service name is returned as a digit string representing the
71  *           port number.
72  *
73  * \li   #NI_DGRAM
74  *           Specifies that the service being looked up is a datagram
75  *           service, and causes getservbyport() to be called with a second
76  *           argument of "udp" instead of its default of "tcp". This is
77  *           required for the few ports (512-514) that have different
78  *           services for UDP and TCP.
79  *
80  * \section getnameinfo_return Return Values
81  *
82  *    getnameinfo() returns 0 on success or a non-zero error code if
83  *    an error occurs.
84  *
85  * \section getname_see See Also
86  *
87  *    RFC3493, getservbyport(),
88  *    getnamebyaddr(). inet_ntop().
89  */
90 
91 #include <config.h>
92 
93 #include <stdbool.h>
94 #include <stdio.h>
95 #include <string.h>
96 
97 #include <isc/netaddr.h>
98 #include <isc/print.h>
99 #include <isc/sockaddr.h>
100 #include <isc/string.h>
101 #include <isc/util.h>
102 
103 #include <dns/byaddr.h>
104 #include <dns/client.h>
105 #include <dns/fixedname.h>
106 #include <dns/name.h>
107 #include <dns/rdata.h>
108 #include <dns/rdataset.h>
109 #include <dns/rdatastruct.h>
110 #include <dns/result.h>
111 
112 #include <irs/context.h>
113 #include <irs/netdb.h>
114 
115 #define SUCCESS 0
116 
117 /*% afd structure definition */
118 static struct afd {
119 	int a_af;
120 	size_t a_addrlen;
121 	size_t a_socklen;
122 } afdl [] = {
123 	/*!
124 	 * First entry is linked last...
125 	 */
126 	{ AF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in) },
127 	{ AF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6) },
128 	{0, 0, 0},
129 };
130 
131 /*!
132  * The test against 0 is there to keep the Solaris compiler
133  * from complaining about "end-of-loop code not reached".
134  */
135 #define ERR(code) \
136 	do { result = (code);			\
137 		if (result != 0) goto cleanup;	\
138 	} while (0)
139 
140 int
getnameinfo(const struct sockaddr * sa,IRS_GETNAMEINFO_SOCKLEN_T salen,char * host,IRS_GETNAMEINFO_BUFLEN_T hostlen,char * serv,IRS_GETNAMEINFO_BUFLEN_T servlen,IRS_GETNAMEINFO_FLAGS_T flags)141 getnameinfo(const struct sockaddr *sa, IRS_GETNAMEINFO_SOCKLEN_T salen,
142 	    char *host, IRS_GETNAMEINFO_BUFLEN_T hostlen,
143 	    char *serv, IRS_GETNAMEINFO_BUFLEN_T servlen,
144 	    IRS_GETNAMEINFO_FLAGS_T flags)
145 {
146 	struct afd *afd = NULL;
147 	struct servent *sp;
148 	unsigned short port = 0;
149 #ifdef IRS_PLATFORM_HAVESALEN
150 	size_t len;
151 #endif
152 	int family, i;
153 	const void *addr = NULL;
154 	char *p;
155 #if 0
156 	unsigned long v4a;
157 	unsigned char pfx;
158 #endif
159 	char numserv[sizeof("65000")];
160 	char numaddr[sizeof("abcd:abcd:abcd:abcd:abcd:abcd:255.255.255.255")
161 		    + 1 + sizeof("4294967295")];
162 	const char *proto;
163 	int result = SUCCESS;
164 
165 	if (sa == NULL)
166 		ERR(EAI_FAIL);
167 
168 #ifdef IRS_PLATFORM_HAVESALEN
169 	len = sa->sa_len;
170 	if (len != salen)
171 		ERR(EAI_FAIL);
172 #endif
173 
174 	family = sa->sa_family;
175 	for (i = 0; afdl[i].a_af; i++)
176 		if (afdl[i].a_af == family) {
177 			afd = &afdl[i];
178 			goto found;
179 		}
180 	ERR(EAI_FAMILY);
181 
182  found:
183 	if (salen != afd->a_socklen)
184 		ERR(EAI_FAIL);
185 
186 	switch (family) {
187 	case AF_INET:
188 		port = ((const struct sockaddr_in *)sa)->sin_port;
189 		addr = &((const struct sockaddr_in *)sa)->sin_addr.s_addr;
190 		break;
191 
192 	case AF_INET6:
193 		port = ((const struct sockaddr_in6 *)sa)->sin6_port;
194 		addr = ((const struct sockaddr_in6 *)sa)->sin6_addr.s6_addr;
195 		break;
196 
197 	default:
198 		INSIST(0);
199 		ISC_UNREACHABLE();
200 	}
201 	proto = ((flags & NI_DGRAM) != 0) ? "udp" : "tcp";
202 
203 	if (serv == NULL || servlen == 0U) {
204 		/*
205 		 * Caller does not want service.
206 		 */
207 	} else if ((flags & NI_NUMERICSERV) != 0 ||
208 		   (sp = getservbyport(port, proto)) == NULL) {
209 		snprintf(numserv, sizeof(numserv), "%d", ntohs(port));
210 		if ((strlen(numserv) + 1) > servlen)
211 			ERR(EAI_OVERFLOW);
212 		strlcpy(serv, numserv, servlen);
213 	} else {
214 		if ((strlen(sp->s_name) + 1) > servlen)
215 			ERR(EAI_OVERFLOW);
216 		strlcpy(serv, sp->s_name, servlen);
217 	}
218 
219 #if 0
220 	switch (sa->sa_family) {
221 	case AF_INET:
222 		v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
223 		if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
224 			flags |= NI_NUMERICHOST;
225 		v4a >>= IN_CLASSA_NSHIFT;
226 		if (v4a == 0 || v4a == IN_LOOPBACKNET)
227 			flags |= NI_NUMERICHOST;
228 		break;
229 
230 	case AF_INET6:
231 		pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[0];
232 		if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
233 			flags |= NI_NUMERICHOST;
234 		break;
235 	}
236 #endif
237 
238 	if (host == NULL || hostlen == 0U) {
239 		/*
240 		 * do nothing in this case.
241 		 * in case you are wondering if "&&" is more correct than
242 		 * "||" here: RFC3493 says that host == NULL or hostlen == 0
243 		 * means that the caller does not want the result.
244 		 */
245 	} else if ((flags & NI_NUMERICHOST) != 0) {
246 		if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr))
247 		    == NULL)
248 			ERR(EAI_SYSTEM);
249 #if defined(IRS_HAVE_SIN6_SCOPE_ID)
250 		if (afd->a_af == AF_INET6 &&
251 		    ((const struct sockaddr_in6 *)sa)->sin6_scope_id) {
252 			char *p = numaddr + strlen(numaddr);
253 			const char *stringscope = NULL;
254 #ifdef VENDOR_SPECIFIC
255 			/*
256 			 * Vendors may want to add support for
257 			 * non-numeric scope identifier.
258 			 */
259 			stringscope = foo;
260 #endif
261 			if (stringscope == NULL) {
262 				snprintf(p, sizeof(numaddr) - (p - numaddr),
263 				    "%%%u",
264 				    ((const struct sockaddr_in6 *)sa)->sin6_scope_id);
265 			} else {
266 				snprintf(p, sizeof(numaddr) - (p - numaddr),
267 				    "%%%s", stringscope);
268 			}
269 		}
270 #endif
271 		if (strlen(numaddr) + 1 > hostlen)
272 			ERR(EAI_OVERFLOW);
273 		strlcpy(host, numaddr, hostlen);
274 	} else {
275 		isc_netaddr_t netaddr;
276 		dns_fixedname_t ptrfname;
277 		dns_name_t *ptrname;
278 		irs_context_t *irsctx = NULL;
279 		dns_client_t *client;
280 		bool found = false;
281 		dns_namelist_t answerlist;
282 		dns_rdataset_t *rdataset;
283 		isc_region_t hostregion;
284 		char hoststr[1024]; /* is this enough? */
285 		isc_result_t iresult;
286 
287 		/* Get IRS context and the associated DNS client object */
288 		iresult = irs_context_get(&irsctx);
289 		if (iresult != ISC_R_SUCCESS)
290 			ERR(EAI_FAIL);
291 		client = irs_context_getdnsclient(irsctx);
292 
293 		/* Make query name */
294 		isc_netaddr_fromsockaddr(&netaddr, (const isc_sockaddr_t *)sa);
295 		ptrname = dns_fixedname_initname(&ptrfname);
296 		iresult = dns_byaddr_createptrname2(&netaddr, 0, ptrname);
297 		if (iresult != ISC_R_SUCCESS)
298 			ERR(EAI_FAIL);
299 
300 		/* Get the PTR RRset */
301 		ISC_LIST_INIT(answerlist);
302 		iresult = dns_client_resolve(client, ptrname,
303 					     dns_rdataclass_in,
304 					     dns_rdatatype_ptr,
305 					     DNS_CLIENTRESOPT_ALLOWRUN,
306 					     &answerlist);
307 		switch (iresult) {
308 		case ISC_R_SUCCESS:
309 		/*
310 		 * a 'non-existent' error is not necessarily fatal for
311 		 * getnameinfo().
312 		 */
313 		case DNS_R_NCACHENXDOMAIN:
314 		case DNS_R_NCACHENXRRSET:
315 			break;
316 		case DNS_R_SIGINVALID:
317 		case DNS_R_SIGEXPIRED:
318 		case DNS_R_SIGFUTURE:
319 		case DNS_R_KEYUNAUTHORIZED:
320 		case DNS_R_MUSTBESECURE:
321 		case DNS_R_COVERINGNSEC:
322 		case DNS_R_NOTAUTHORITATIVE:
323 		case DNS_R_NOVALIDKEY:
324 		case DNS_R_NOVALIDDS:
325 		case DNS_R_NOVALIDSIG:
326 			/*
327 			 * Don't use ERR as GCC 7 wants to raise a
328 			 * warning with ERR about possible falling
329 			 * through which is impossible.
330 			 */
331 			result = EAI_INSECUREDATA;
332 			goto cleanup;
333 		default:
334 			ERR(EAI_FAIL);
335 		}
336 
337 		/* Parse the answer for the hostname */
338 		for (ptrname = ISC_LIST_HEAD(answerlist); ptrname != NULL;
339 		     ptrname = ISC_LIST_NEXT(ptrname, link)) {
340 			for (rdataset = ISC_LIST_HEAD(ptrname->list);
341 			     rdataset != NULL;
342 			     rdataset = ISC_LIST_NEXT(rdataset, link)) {
343 				if (!dns_rdataset_isassociated(rdataset))
344 					continue;
345 				if (rdataset->type != dns_rdatatype_ptr)
346 					continue;
347 
348 				for (iresult = dns_rdataset_first(rdataset);
349 				     iresult == ISC_R_SUCCESS;
350 				     iresult = dns_rdataset_next(rdataset)) {
351 					dns_rdata_t rdata;
352 					dns_rdata_ptr_t rdata_ptr;
353 					isc_buffer_t b;
354 
355 					dns_rdata_init(&rdata);
356 					dns_rdataset_current(rdataset, &rdata);
357 					dns_rdata_tostruct(&rdata, &rdata_ptr,
358 							   NULL);
359 
360 					isc_buffer_init(&b, hoststr,
361 							sizeof(hoststr));
362 					iresult =
363 						dns_name_totext(&rdata_ptr.ptr,
364 								true, &b);
365 					dns_rdata_freestruct(&rdata_ptr);
366 					if (iresult == ISC_R_SUCCESS) {
367 						/*
368 						 * We ignore the rest of the
369 						 * answer.  After all,
370 						 * getnameinfo() can return
371 						 * at most one hostname.
372 						 */
373 						found = true;
374 						isc_buffer_usedregion(
375 							&b, &hostregion);
376 						goto ptrfound;
377 					}
378 
379 				}
380 			}
381 		}
382 	ptrfound:
383 		dns_client_freeresanswer(client, &answerlist);
384 		if (found) {
385 			if ((flags & NI_NOFQDN) != 0) {
386 				p = strchr(hoststr, '.');
387 				if (p)
388 					*p = '\0';
389 			}
390 			if (hostregion.length + 1 > hostlen)
391 				ERR(EAI_OVERFLOW);
392 			snprintf(host, hostlen, "%.*s",
393 				 (int)hostregion.length,
394 				 (char *)hostregion.base);
395 		} else {
396 			if ((flags & NI_NAMEREQD) != 0)
397 				ERR(EAI_NONAME);
398 			if (inet_ntop(afd->a_af, addr, numaddr,
399 				      sizeof(numaddr)) == NULL)
400 				ERR(EAI_SYSTEM);
401 			if ((strlen(numaddr) + 1) > hostlen)
402 				ERR(EAI_OVERFLOW);
403 			strlcpy(host, numaddr, hostlen);
404 		}
405 	}
406 	result = SUCCESS;
407 
408  cleanup:
409 	return (result);
410 }
411