1/*	$NetBSD: getnameinfo.c,v 1.53 2012/09/26 23:13:00 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.53 2012/09/26 23:13:00 christos Exp $");
51#endif /* LIBC_SCCS and not lint */
52
53#include <sys/types.h>
54#include <sys/socket.h>
55#include <sys/un.h>
56#include <net/if.h>
57#include <net/if_ieee1394.h>
58#include <net/if_types.h>
59#include <netinet/in.h>
60#include <arpa/inet.h>
61#include <assert.h>
62#include <limits.h>
63#include <netdb.h>
64#include "arpa_nameser.h"
65#include "resolv_private.h"
66#include <sys/system_properties.h>
67#include <stdlib.h>
68#include <unistd.h>
69#include <errno.h>
70#define MIN(x,y) ((x) < (y) ? (x) : (y))
71#include <stddef.h>
72#include <string.h>
73
74static const struct afd {
75	int		a_af;
76	socklen_t	a_addrlen;
77	socklen_t	a_socklen;
78	int		a_off;
79} afdl [] = {
80#ifdef INET6
81	{PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
82		offsetof(struct sockaddr_in6, sin6_addr)},
83#endif
84	{PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
85		offsetof(struct sockaddr_in, sin_addr)},
86	{0, 0, 0, 0},
87};
88
89struct sockinet {
90	u_char	si_len;
91	u_char	si_family;
92	u_short	si_port;
93};
94
95static int getnameinfo_inet(const struct sockaddr *, socklen_t, char *,
96    socklen_t, char *, socklen_t, int, const char*, int);
97#ifdef INET6
98static int ip6_parsenumeric(const struct sockaddr *, const char *, char *,
99				 socklen_t, int);
100static int ip6_sa2str(const struct sockaddr_in6 *, char *, size_t, int);
101#endif
102static int getnameinfo_local(const struct sockaddr *, socklen_t, char *,
103    socklen_t, char *, socklen_t, int);
104
105/*
106 * Top-level getnameinfo() code.  Look at the address family, and pick an
107 * appropriate function to call.
108 */
109int getnameinfo(const struct sockaddr* sa, socklen_t salen, char* host, size_t hostlen, char* serv, size_t servlen, int flags)
110{
111	return android_getnameinfoforiface(sa, salen, host, hostlen, serv, servlen, flags, NULL, 0);
112}
113
114int android_getnameinfoforiface(const struct sockaddr* sa, socklen_t salen, char* host, size_t hostlen, char* serv, size_t servlen, int flags, const char* iface, int mark)
115{
116	switch (sa->sa_family) {
117	case AF_INET:
118	case AF_INET6:
119		return getnameinfo_inet(sa, salen, host, hostlen,
120				serv, servlen, flags, iface, mark);
121	case AF_LOCAL:
122		return getnameinfo_local(sa, salen, host, hostlen,
123		    serv, servlen, flags);
124	default:
125		return EAI_FAMILY;
126	}
127}
128
129/*
130 * getnameinfo_local():
131 * Format an local address into a printable format.
132 */
133/* ARGSUSED */
134static int
135getnameinfo_local(const struct sockaddr *sa, socklen_t salen,
136    char *host, socklen_t hostlen, char *serv, socklen_t servlen,
137    int flags __attribute__((unused)))
138{
139       const struct sockaddr_un *sun =
140           (const struct sockaddr_un *)(const void *)sa;
141
142       if (salen < (socklen_t) offsetof(struct sockaddr_un, sun_path)) {
143           return EAI_FAMILY;
144       }
145
146       if (serv != NULL && servlen > 0)
147               serv[0] = '\0';
148
149       if (host && hostlen > 0)
150               strlcpy(host, sun->sun_path,
151                   MIN((socklen_t) sizeof(sun->sun_path) + 1, hostlen));
152
153       return 0;
154}
155
156/* On success length of the host name is returned. A return
157 * value of 0 means there's no host name associated with
158 * the address. On failure -1 is returned in which case
159 * normal execution flow shall continue. */
160static int
161android_gethostbyaddr_proxy(char* nameBuf, size_t nameBufLen, const void *addr, socklen_t addrLen, int addrFamily, const char* iface, int mark)
162{
163	struct hostent *hostResult =
164			android_gethostbyaddrforiface_proxy(addr, addrLen, addrFamily, iface, mark);
165
166	if (hostResult == NULL) return 0;
167
168	int lengthResult = strlen(hostResult->h_name);
169
170	if (nameBuf) strncpy(nameBuf, hostResult->h_name, nameBufLen);
171	return lengthResult;
172}
173
174/*
175 * getnameinfo_inet():
176 * Format an IPv4 or IPv6 sockaddr into a printable string.
177 */
178static int
179getnameinfo_inet(const struct sockaddr* sa, socklen_t salen,
180       char *host, socklen_t hostlen,
181       char *serv, socklen_t servlen,
182       int flags, const char* iface, int mark)
183{
184	const struct afd *afd;
185	struct servent *sp;
186	struct hostent *hp;
187	u_short port;
188	int family, i;
189	const char *addr;
190	uint32_t v4a;
191	char numserv[512];
192	char numaddr[512];
193
194	/* sa is checked below */
195	/* host may be NULL */
196	/* serv may be NULL */
197
198	if (sa == NULL)
199		return EAI_FAIL;
200
201	family = sa->sa_family;
202	for (i = 0; afdl[i].a_af; i++)
203		if (afdl[i].a_af == family) {
204			afd = &afdl[i];
205			goto found;
206		}
207	return EAI_FAMILY;
208
209 found:
210	// http://b/1889275: callers should be allowed to provide too much
211	// space, but not too little.
212	if (salen < afd->a_socklen) {
213		return EAI_FAMILY;
214	}
215
216	/* network byte order */
217	port = ((const struct sockinet *)(const void *)sa)->si_port;
218	addr = (const char *)(const void *)sa + afd->a_off;
219
220	if (serv == NULL || servlen == 0) {
221		/*
222		 * do nothing in this case.
223		 * in case you are wondering if "&&" is more correct than
224		 * "||" here: rfc2553bis-03 says that serv == NULL OR
225		 * servlen == 0 means that the caller does not want the result.
226		 */
227	} else {
228		if (flags & NI_NUMERICSERV)
229			sp = NULL;
230		else {
231			sp = getservbyport(port,
232				(flags & NI_DGRAM) ? "udp" : "tcp");
233		}
234		if (sp) {
235			if (strlen(sp->s_name) + 1 > (size_t)servlen)
236				return EAI_MEMORY;
237			strlcpy(serv, sp->s_name, servlen);
238		} else {
239			snprintf(numserv, sizeof(numserv), "%u", ntohs(port));
240			if (strlen(numserv) + 1 > (size_t)servlen)
241				return EAI_MEMORY;
242			strlcpy(serv, numserv, servlen);
243		}
244	}
245
246	switch (sa->sa_family) {
247	case AF_INET:
248		v4a = (uint32_t)
249		    ntohl(((const struct sockaddr_in *)
250		    (const void *)sa)->sin_addr.s_addr);
251		if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
252			flags |= NI_NUMERICHOST;
253		v4a >>= IN_CLASSA_NSHIFT;
254		if (v4a == 0)
255			flags |= NI_NUMERICHOST;
256		break;
257#ifdef INET6
258	case AF_INET6:
259	    {
260		const struct sockaddr_in6 *sin6;
261		sin6 = (const struct sockaddr_in6 *)(const void *)sa;
262		switch (sin6->sin6_addr.s6_addr[0]) {
263		case 0x00:
264			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
265				;
266			else if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
267				;
268			else
269				flags |= NI_NUMERICHOST;
270			break;
271		default:
272			if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
273				flags |= NI_NUMERICHOST;
274			}
275			else if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
276				flags |= NI_NUMERICHOST;
277			break;
278		}
279	    }
280		break;
281#endif
282	}
283	if (host == NULL || hostlen == 0) {
284		/*
285		 * do nothing in this case.
286		 * in case you are wondering if "&&" is more correct than
287		 * "||" here: rfc2553bis-03 says that host == NULL or
288		 * hostlen == 0 means that the caller does not want the result.
289		 */
290	} else if (flags & NI_NUMERICHOST) {
291		size_t numaddrlen;
292
293		/* NUMERICHOST and NAMEREQD conflicts with each other */
294		if (flags & NI_NAMEREQD)
295			return EAI_NONAME;
296
297		switch(afd->a_af) {
298#ifdef INET6
299		case AF_INET6:
300		{
301			int error;
302
303			if ((error = ip6_parsenumeric(sa, addr, host,
304						      hostlen, flags)) != 0)
305				return(error);
306			break;
307		}
308#endif
309		default:
310			if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr))
311			    == NULL)
312				return EAI_SYSTEM;
313			numaddrlen = strlen(numaddr);
314			if (numaddrlen + 1 > (size_t)hostlen) /* don't forget terminator */
315				return EAI_MEMORY;
316			strlcpy(host, numaddr, hostlen);
317			break;
318		}
319	} else {
320		struct hostent android_proxy_hostent;
321		char android_proxy_buf[MAXDNAME];
322
323		int hostnamelen = android_gethostbyaddr_proxy(android_proxy_buf,
324				MAXDNAME, addr, afd->a_addrlen, afd->a_af, iface, mark);
325		if (hostnamelen > 0) {
326			hp = &android_proxy_hostent;
327			hp->h_name = android_proxy_buf;
328		} else if (!hostnamelen) {
329			hp = NULL;
330		} else {
331			hp = android_gethostbyaddrforiface(addr, afd->a_addrlen, afd->a_af,
332					iface, mark);
333		}
334
335		if (hp) {
336#if 0
337			/*
338			 * commented out, since "for local host" is not
339			 * implemented here - see RFC2553 p30
340			 */
341			if (flags & NI_NOFQDN) {
342				char *p;
343				p = strchr(hp->h_name, '.');
344				if (p)
345					*p = '\0';
346			}
347#endif
348			if (strlen(hp->h_name) + 1 > (size_t)hostlen) {
349				return EAI_MEMORY;
350			}
351			strlcpy(host, hp->h_name, hostlen);
352		} else {
353			if (flags & NI_NAMEREQD)
354				return EAI_NONAME;
355			switch(afd->a_af) {
356#ifdef INET6
357			case AF_INET6:
358			{
359				int error;
360
361				if ((error = ip6_parsenumeric(sa, addr, host,
362							      hostlen,
363							      flags)) != 0)
364					return(error);
365				break;
366			}
367#endif
368			default:
369				if (inet_ntop(afd->a_af, addr, host,
370				    hostlen) == NULL)
371					return EAI_SYSTEM;
372				break;
373			}
374		}
375	}
376	return(0);
377}
378
379#ifdef INET6
380static int
381ip6_parsenumeric(const struct sockaddr *sa, const char *addr, char *host,
382       socklen_t hostlen, int flags)
383{
384	size_t numaddrlen;
385	char numaddr[512];
386
387	assert(sa != NULL);
388	assert(addr != NULL);
389	assert(host != NULL);
390
391	if (inet_ntop(AF_INET6, addr, numaddr, sizeof(numaddr)) == NULL)
392		return EAI_SYSTEM;
393
394	numaddrlen = strlen(numaddr);
395	if (numaddrlen + 1 > (size_t)hostlen) /* don't forget terminator */
396		return EAI_OVERFLOW;
397	strlcpy(host, numaddr, hostlen);
398
399	if (((const struct sockaddr_in6 *)(const void *)sa)->sin6_scope_id) {
400		char zonebuf[MAXHOSTNAMELEN];
401		int zonelen;
402
403		zonelen = ip6_sa2str(
404		    (const struct sockaddr_in6 *)(const void *)sa,
405		    zonebuf, sizeof(zonebuf), flags);
406		if (zonelen < 0)
407			return EAI_OVERFLOW;
408		if ((size_t) zonelen + 1 + numaddrlen + 1 > (size_t)hostlen)
409			return EAI_OVERFLOW;
410		/* construct <numeric-addr><delim><zoneid> */
411		memcpy(host + numaddrlen + 1, zonebuf,
412		    (size_t)zonelen);
413		host[numaddrlen] = SCOPE_DELIMITER;
414		host[numaddrlen + 1 + zonelen] = '\0';
415	}
416
417	return 0;
418}
419
420/* ARGSUSED */
421static int
422ip6_sa2str(const struct sockaddr_in6 *sa6, char *buf, size_t bufsiz, int flags)
423{
424	unsigned int ifindex;
425	const struct in6_addr *a6;
426	int n;
427
428	assert(sa6 != NULL);
429	assert(buf != NULL);
430
431	ifindex = (unsigned int)sa6->sin6_scope_id;
432	a6 = &sa6->sin6_addr;
433
434#ifdef NI_NUMERICSCOPE
435	if ((flags & NI_NUMERICSCOPE) != 0) {
436		n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id);
437		if (n < 0 || n >= bufsiz)
438			return -1;
439		else
440			return n;
441	}
442#endif
443
444	/* if_indextoname() does not take buffer size.  not a good api... */
445	if ((IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) &&
446	    bufsiz >= IF_NAMESIZE) {
447		char *p = if_indextoname(ifindex, buf);
448		if (p) {
449			return(strlen(p));
450		}
451	}
452
453	/* last resort */
454	n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id);
455	if (n < 0 || (size_t) n >= bufsiz)
456		return -1;
457	else
458		return n;
459}
460#endif /* INET6 */
461