1/*	$NetBSD: getnameinfo.c,v 1.60 2023/09/08 18:17:41 christos Exp $	*/
2/*	$KAME: getnameinfo.c,v 1.45 2000/09/25 22:43:56 itojun Exp $	*/
3
4/*
5 * Copyright (c) 2000 Ben Harris.
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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
34/*
35 * Issues to be discussed:
36 * - Thread safe-ness must be checked
37 * - RFC2553 says that we should raise error on short buffer.  X/Open says
38 *   we need to truncate the result.  We obey RFC2553 (and X/Open should be
39 *   modified).  ipngwg rough consensus seems to follow RFC2553.
40 * - What is "local" in NI_FQDN?
41 * - NI_NAMEREQD and NI_NUMERICHOST conflict with each other.
42 * - (KAME extension) always attach textual scopeid (fe80::1%lo0), if
43 *   sin6_scope_id is filled - standardization status?
44 *   XXX breaks backward compat for code that expects no scopeid.
45 *   beware on merge.
46 */
47
48#include <sys/cdefs.h>
49#if defined(LIBC_SCCS) && !defined(lint)
50__RCSID("$NetBSD: getnameinfo.c,v 1.60 2023/09/08 18:17:41 christos Exp $");
51#endif /* LIBC_SCCS and not lint */
52
53#ifndef RUMP_ACTION
54#include "namespace.h"
55#endif
56#include <sys/types.h>
57#include <sys/socket.h>
58#include <sys/un.h>
59#include <net/if.h>
60#include <net/if_dl.h>
61#include <net/if_ieee1394.h>
62#include <net/if_types.h>
63#include <netatalk/at.h>
64#include <netinet/in.h>
65#include <arpa/inet.h>
66#include <arpa/nameser.h>
67#include <assert.h>
68#include <limits.h>
69#include <netdb.h>
70#include <resolv.h>
71#include <stddef.h>
72#include <string.h>
73
74#include "servent.h"
75#include "hostent.h"
76
77#ifndef RUMP_ACTION
78#ifdef __weak_alias
79__weak_alias(getnameinfo,_getnameinfo)
80#endif
81#endif
82
83static const struct afd {
84	int		a_af;
85	socklen_t	a_addrlen;
86	socklen_t	a_socklen;
87	int		a_off;
88} afdl [] = {
89#ifdef INET6
90	{PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
91		offsetof(struct sockaddr_in6, sin6_addr)},
92#endif
93	{PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
94		offsetof(struct sockaddr_in, sin_addr)},
95	{0, 0, 0, 0},
96};
97
98struct sockinet {
99	u_char	si_len;
100	u_char	si_family;
101	u_short	si_port;
102};
103
104static int getnameinfo_inet(const struct sockaddr *, socklen_t, char *,
105    socklen_t, char *, socklen_t, int);
106#ifdef INET6
107static int ip6_parsenumeric(const struct sockaddr *, const char *, char *,
108				 socklen_t, int);
109static int ip6_sa2str(const struct sockaddr_in6 *, char *, size_t, int);
110#endif
111static int getnameinfo_atalk(const struct sockaddr *, socklen_t, char *,
112    socklen_t, char *, socklen_t, int);
113static int getnameinfo_local(const struct sockaddr *, socklen_t, char *,
114    socklen_t, char *, socklen_t, int);
115
116static int getnameinfo_link(const struct sockaddr *, socklen_t, char *,
117    socklen_t, char *, socklen_t, int);
118static int hexname(const uint8_t *, size_t, char *, socklen_t);
119
120/*
121 * Top-level getnameinfo() code.  Look at the address family, and pick an
122 * appropriate function to call.
123 */
124int
125getnameinfo(const struct sockaddr *sa, socklen_t salen,
126	char *host, socklen_t hostlen,
127	char *serv, socklen_t servlen,
128	int flags)
129{
130
131	/*
132	 * getnameinfo() accepts an salen of sizeof(struct sockaddr_storage)
133	 * at maximum as shown in RFC 4038 Sec.6.2.3.
134	 */
135	if (salen > sizeof(struct sockaddr_storage))
136		return EAI_FAMILY;
137
138	switch (sa->sa_family) {
139	case AF_APPLETALK:
140		return getnameinfo_atalk(sa, salen, host, hostlen,
141		    serv, servlen, flags);
142	case AF_INET:
143	case AF_INET6:
144		return getnameinfo_inet(sa, salen, host, hostlen,
145		    serv, servlen, flags);
146	case AF_LINK:
147		return getnameinfo_link(sa, salen, host, hostlen,
148		    serv, servlen, flags);
149	case AF_LOCAL:
150		return getnameinfo_local(sa, salen, host, hostlen,
151		    serv, servlen, flags);
152	default:
153		return EAI_FAMILY;
154	}
155}
156
157/*
158 * getnameinfo_atalk():
159 * Format an AppleTalk address into a printable format.
160 */
161/* ARGSUSED */
162static int
163getnameinfo_atalk(const struct sockaddr *sa, socklen_t salen,
164    char *host, socklen_t hostlen, char *serv, socklen_t servlen,
165    int flags)
166{
167	char numserv[8];
168	int n, m=0;
169
170	const struct sockaddr_at *sat =
171	    (const struct sockaddr_at *)(const void *)sa;
172
173	if (serv != NULL && servlen > 0) {
174		snprintf(numserv, sizeof(numserv), "%u", sat->sat_port);
175		if (strlen(numserv) + 1 > servlen)
176			return EAI_MEMORY;
177		strlcpy(serv, numserv, servlen);
178	}
179
180        n = snprintf(host, hostlen, "%u.%u",
181	    ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node);
182
183	if (n < 0 || (socklen_t)(m+n) >= hostlen)
184		goto errout;
185
186	m += n;
187
188	if (sat->sat_range.r_netrange.nr_phase) {
189        	n = snprintf(host+m, hostlen-m, " phase %u",
190			sat->sat_range.r_netrange.nr_phase);
191
192		if (n < 0 || (socklen_t)(m+n) >= hostlen)
193			goto errout;
194
195		m += n;
196	}
197	if (sat->sat_range.r_netrange.nr_firstnet) {
198        	n = snprintf(host+m, hostlen-m, " range %u - %u",
199			ntohs(sat->sat_range.r_netrange.nr_firstnet),
200			ntohs(sat->sat_range.r_netrange.nr_lastnet ));
201
202		if (n < 0 || (socklen_t)(m+n) >= hostlen)
203			goto errout;
204
205		m += n;
206	}
207
208	return 0;
209
210errout:
211	if (host && hostlen>0)
212		host[m] = '\0';	/* XXX ??? */
213
214	return EAI_MEMORY;
215}
216
217/*
218 * getnameinfo_local():
219 * Format an local address into a printable format.
220 */
221/* ARGSUSED */
222static int
223getnameinfo_local(const struct sockaddr *sa, socklen_t salen,
224    char *host, socklen_t hostlen, char *serv, socklen_t servlen,
225    int flags)
226{
227	const struct sockaddr_un *sun =
228	    (const struct sockaddr_un *)(const void *)sa;
229
230        if (salen <= sizeof(*sun) - sizeof(sun->sun_path))
231		return EAI_FAMILY;
232
233	if (serv != NULL && servlen > 0)
234		serv[0] = '\0';
235
236	if (host && hostlen > 0)
237		strlcpy(host, sun->sun_path,
238		    MIN(sizeof(sun->sun_path) + 1, hostlen));
239
240	return 0;
241}
242
243/*
244 * getnameinfo_inet():
245 * Format an IPv4 or IPv6 sockaddr into a printable string.
246 */
247static int
248getnameinfo_inet(const struct sockaddr *sa, socklen_t salen,
249	char *host, socklen_t hostlen,
250	char *serv, socklen_t servlen,
251	int flags)
252{
253	const struct afd *afd;
254	struct servent *sp;
255	struct hostent *hp;
256	u_short port;
257	int family, i;
258	const char *addr;
259	uint32_t v4a;
260	char numserv[512];
261	char numaddr[512];
262
263	/* sa is checked below */
264	/* host may be NULL */
265	/* serv may be NULL */
266
267	if (sa == NULL)
268		return EAI_FAIL;
269
270	family = sa->sa_family;
271	for (i = 0; afdl[i].a_af; i++)
272		if (afdl[i].a_af == family) {
273			afd = &afdl[i];
274			goto found;
275		}
276	return EAI_FAMILY;
277
278 found:
279	if (salen < afd->a_socklen)
280		return EAI_FAMILY;
281
282	/* network byte order */
283	port = ((const struct sockinet *)(const void *)sa)->si_port;
284	addr = (const char *)(const void *)sa + afd->a_off;
285
286	if (serv == NULL || servlen == 0) {
287		/*
288		 * do nothing in this case.
289		 * in case you are wondering if "&&" is more correct than
290		 * "||" here: rfc2553bis-03 says that serv == NULL OR
291		 * servlen == 0 means that the caller does not want the result.
292		 */
293	} else {
294		struct servent_data svd;
295		struct servent sv;
296
297		if (flags & NI_NUMERICSERV)
298			sp = NULL;
299		else {
300			(void)memset(&svd, 0, sizeof(svd));
301			sp = getservbyport_r(port,
302				(flags & NI_DGRAM) ? "udp" : "tcp", &sv, &svd);
303		}
304		if (sp) {
305			if (strlen(sp->s_name) + 1 > servlen) {
306				endservent_r(&svd);
307				return EAI_MEMORY;
308			}
309			strlcpy(serv, sp->s_name, servlen);
310			endservent_r(&svd);
311		} else {
312			snprintf(numserv, sizeof(numserv), "%u", ntohs(port));
313			if (strlen(numserv) + 1 > servlen)
314				return EAI_MEMORY;
315			strlcpy(serv, numserv, servlen);
316		}
317	}
318
319	switch (sa->sa_family) {
320	case AF_INET:
321		v4a = (uint32_t)
322		    ntohl(((const struct sockaddr_in *)
323		    (const void *)sa)->sin_addr.s_addr);
324		if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
325			flags |= NI_NUMERICHOST;
326		v4a >>= IN_CLASSA_NSHIFT;
327		if (v4a == 0)
328			flags |= NI_NUMERICHOST;
329		break;
330#ifdef INET6
331	case AF_INET6:
332	    {
333		const struct sockaddr_in6 *sin6;
334		sin6 = (const struct sockaddr_in6 *)(const void *)sa;
335		switch (sin6->sin6_addr.s6_addr[0]) {
336		case 0x00:
337			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
338				;
339			else if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
340				;
341			else
342				flags |= NI_NUMERICHOST;
343			break;
344		default:
345			if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
346				flags |= NI_NUMERICHOST;
347			}
348			else if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
349				flags |= NI_NUMERICHOST;
350			break;
351		}
352	    }
353		break;
354#endif
355	}
356	if (host == NULL || hostlen == 0) {
357		/*
358		 * do nothing in this case.
359		 * in case you are wondering if "&&" is more correct than
360		 * "||" here: rfc2553bis-03 says that host == NULL or
361		 * hostlen == 0 means that the caller does not want the result.
362		 */
363	} else if (flags & NI_NUMERICHOST) {
364		size_t numaddrlen;
365
366		/* NUMERICHOST and NAMEREQD conflicts with each other */
367		if (flags & NI_NAMEREQD)
368			return EAI_NONAME;
369
370		switch(afd->a_af) {
371#ifdef INET6
372		case AF_INET6:
373		{
374			int error;
375
376			if ((error = ip6_parsenumeric(sa, addr, host,
377						      hostlen, flags)) != 0)
378				return(error);
379			break;
380		}
381#endif
382		default:
383			if (inet_ntop(afd->a_af, addr, numaddr,
384			    (socklen_t)sizeof(numaddr)) == NULL)
385				return EAI_SYSTEM;
386			numaddrlen = strlen(numaddr);
387			if (numaddrlen + 1 > hostlen) /* don't forget terminator */
388				return EAI_MEMORY;
389			strlcpy(host, numaddr, hostlen);
390			break;
391		}
392	} else {
393		struct hostent hent;
394		char hbuf[4096];
395		int he;
396		hp = gethostbyaddr_r(addr, afd->a_addrlen, afd->a_af, &hent,
397		    hbuf, sizeof(hbuf), &he);
398
399		if (hp) {
400#if 0
401			/*
402			 * commented out, since "for local host" is not
403			 * implemented here - see RFC2553 p30
404			 */
405			if (flags & NI_NOFQDN) {
406				char *p;
407				p = strchr(hp->h_name, '.');
408				if (p)
409					*p = '\0';
410			}
411#endif
412			if (strlen(hp->h_name) + 1 > hostlen) {
413				return EAI_MEMORY;
414			}
415			strlcpy(host, hp->h_name, hostlen);
416		} else {
417			switch (he) {
418			case NO_DATA:
419			case HOST_NOT_FOUND:
420				if (flags & NI_NAMEREQD)
421					return EAI_NONAME;
422				break;
423			case TRY_AGAIN:
424				return EAI_AGAIN;
425			case NETDB_SUCCESS:
426			case NETDB_INTERNAL:
427			case NO_RECOVERY:
428				/*FALLTHROUGH*/
429			default:
430				return EAI_SYSTEM;
431			}
432			switch(afd->a_af) {
433#ifdef INET6
434			case AF_INET6:
435			{
436				int error;
437
438				if ((error = ip6_parsenumeric(sa, addr, host,
439							      hostlen,
440							      flags)) != 0)
441					return(error);
442				break;
443			}
444#endif
445			default:
446				if (inet_ntop(afd->a_af, addr, host,
447				    hostlen) == NULL)
448					return EAI_SYSTEM;
449				break;
450			}
451		}
452	}
453	return(0);
454}
455
456#ifdef INET6
457static int
458ip6_parsenumeric(const struct sockaddr *sa, const char *addr, char *host,
459	socklen_t hostlen, int flags)
460{
461	size_t numaddrlen;
462	char numaddr[512];
463
464	_DIAGASSERT(sa != NULL);
465	_DIAGASSERT(addr != NULL);
466	_DIAGASSERT(host != NULL);
467
468	if (inet_ntop(AF_INET6, addr, numaddr, (socklen_t)sizeof(numaddr))
469	    == NULL)
470		return EAI_SYSTEM;
471
472	numaddrlen = strlen(numaddr);
473	if (numaddrlen + 1 > hostlen) /* don't forget terminator */
474		return EAI_OVERFLOW;
475	strlcpy(host, numaddr, hostlen);
476
477	if (((const struct sockaddr_in6 *)(const void *)sa)->sin6_scope_id) {
478		char zonebuf[MAXHOSTNAMELEN];
479		int zonelen;
480
481		zonelen = ip6_sa2str(
482		    (const struct sockaddr_in6 *)(const void *)sa,
483		    zonebuf, sizeof(zonebuf), flags);
484		if (zonelen < 0)
485			return EAI_OVERFLOW;
486		if ((size_t) zonelen + 1 + numaddrlen + 1 > hostlen)
487			return EAI_OVERFLOW;
488		/* construct <numeric-addr><delim><zoneid> */
489		memcpy(host + numaddrlen + 1, zonebuf,
490		    (size_t)zonelen);
491		host[numaddrlen] = SCOPE_DELIMITER;
492		host[numaddrlen + 1 + zonelen] = '\0';
493	}
494
495	return 0;
496}
497
498/* ARGSUSED */
499static int
500ip6_sa2str(const struct sockaddr_in6 *sa6, char *buf, size_t bufsiz, int flags)
501{
502	unsigned int ifindex;
503	const struct in6_addr *a6;
504	int n;
505
506	_DIAGASSERT(sa6 != NULL);
507	_DIAGASSERT(buf != NULL);
508
509	ifindex = (unsigned int)sa6->sin6_scope_id;
510	a6 = &sa6->sin6_addr;
511
512#ifdef NI_NUMERICSCOPE
513	if ((flags & NI_NUMERICSCOPE) != 0) {
514		n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id);
515		if (n < 0 || (size_t)n >= bufsiz)
516			return -1;
517		else
518			return n;
519	}
520#endif
521
522	/* if_indextoname() does not take buffer size.  not a good api... */
523	if ((IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) &&
524	    bufsiz >= IF_NAMESIZE) {
525		char *p = if_indextoname(ifindex, buf);
526		if (p) {
527			return (int)strlen(p);
528		}
529	}
530
531	/* last resort */
532	n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id);
533	if (n < 0 || (size_t) n >= bufsiz)
534		return -1;
535	else
536		return n;
537}
538#endif /* INET6 */
539
540
541/*
542 * getnameinfo_link():
543 * Format a link-layer address into a printable format, paying attention to
544 * the interface type.
545 */
546/* ARGSUSED */
547static int
548getnameinfo_link(const struct sockaddr *sa, socklen_t salen,
549    char *host, socklen_t hostlen, char *serv, socklen_t servlen,
550    int flags)
551{
552	const struct sockaddr_dl *sdl =
553	    (const struct sockaddr_dl *)(const void *)sa;
554	const struct ieee1394_hwaddr *iha;
555	int n;
556
557        if (salen <= sizeof(*sdl) - sizeof(sdl->sdl_data))
558		return EAI_FAMILY;
559
560	if (serv != NULL && servlen > 0)
561		*serv = '\0';
562
563	if (sdl->sdl_nlen == 0 && sdl->sdl_alen == 0 && sdl->sdl_slen == 0) {
564		n = snprintf(host, hostlen, "link#%u", sdl->sdl_index);
565		goto out;
566	}
567
568	switch (sdl->sdl_type) {
569#ifdef IFT_ECONET
570	case IFT_ECONET:
571		if (sdl->sdl_alen < 2)
572			return EAI_FAMILY;
573		if (CLLADDR(sdl)[1] == 0)
574			n = snprintf(host, hostlen, "%u", CLLADDR(sdl)[0]);
575		else
576			n = snprintf(host, hostlen, "%u.%u",
577			    CLLADDR(sdl)[1], CLLADDR(sdl)[0]);
578		goto out;
579#endif
580	case IFT_IEEE1394:
581		if (sdl->sdl_alen < sizeof(iha->iha_uid))
582			return EAI_FAMILY;
583		iha =
584		    (const struct ieee1394_hwaddr *)(const void *)CLLADDR(sdl);
585		return hexname(iha->iha_uid, sizeof(iha->iha_uid),
586		    host, hostlen);
587	/*
588	 * The following have zero-length addresses.
589	 * IFT_ATM	(net/if_atmsubr.c)
590	 * IFT_FAITH	(net/if_faith.c)
591	 * IFT_GIF	(net/if_gif.c)
592	 * IFT_LOOP	(net/if_loop.c)
593	 * IFT_PPP	(net/if_ppp.c, net/if_spppsubr.c)
594	 * IFT_SLIP	(net/if_sl.c, net/if_strip.c)
595	 * IFT_STF	(net/if_stf.c)
596	 * IFT_L2VLAN	(net/if_vlan.c)
597	 * IFT_PROPVIRTUAL (net/if_bridge.h>
598	 */
599	/*
600	 * The following use IPv4 addresses as link-layer addresses:
601	 * IFT_OTHER	(net/if_gre.c)
602	 */
603	case IFT_ARCNET: /* default below is believed correct for all these. */
604	case IFT_ETHER:
605	case IFT_FDDI:
606	case IFT_HIPPI:
607	case IFT_ISO88025:
608	default:
609		return hexname((const uint8_t *)CLLADDR(sdl),
610		    (size_t)sdl->sdl_alen, host, hostlen);
611	}
612out:
613	if (n < 0 || (socklen_t) n >= hostlen) {
614		*host = '\0';
615		return EAI_MEMORY;
616	}
617	return 0;
618}
619
620static int
621hexname(const uint8_t *cp, size_t len, char *host, socklen_t hostlen)
622{
623	int n;
624	size_t i;
625	char *outp = host;
626
627	*outp = '\0';
628	for (i = 0; i < len; i++) {
629		n = snprintf(outp, hostlen, "%s%02x",
630		    i ? ":" : "", cp[i]);
631		if (n < 0 || (socklen_t) n >= hostlen) {
632			*host = '\0';
633			return EAI_MEMORY;
634		}
635		outp += n;
636		hostlen -= n;
637	}
638	return 0;
639}
640