1/*	$NetBSD: inet_cidr_ntop.c,v 1.8 2012/03/13 21:13:38 christos Exp $	*/
2
3/*
4 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
5 * Copyright (c) 1998,1999 by Internet Software Consortium.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
17 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include <sys/cdefs.h>
21#if defined(LIBC_SCCS) && !defined(lint)
22#if 0
23static const char rcsid[] = "Id: inet_cidr_ntop.c,v 1.7 2006/10/11 02:18:18 marka Exp";
24#else
25__RCSID("$NetBSD: inet_cidr_ntop.c,v 1.8 2012/03/13 21:13:38 christos Exp $");
26#endif
27#endif
28
29#include "port_before.h"
30
31#include <sys/types.h>
32#include <sys/socket.h>
33#include <netinet/in.h>
34#include <arpa/nameser.h>
35#include <arpa/inet.h>
36
37#include <assert.h>
38#include <errno.h>
39#include <stdio.h>
40#include <string.h>
41#include <stdlib.h>
42
43#include "port_after.h"
44
45#ifdef __weak_alias
46__weak_alias(inet_cidr_ntop,_inet_cidr_ntop)
47#endif
48
49#ifdef SPRINTF_CHAR
50# define SPRINTF(x) strlen(sprintf/**/x)
51#else
52# define SPRINTF(x) ((size_t)sprintf x)
53#endif
54
55static char *
56inet_cidr_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size);
57static char *
58inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size);
59
60/*%
61 * char *
62 * inet_cidr_ntop(af, src, bits, dst, size)
63 *	convert network address from network to presentation format.
64 *	"src"'s size is determined from its "af".
65 * return:
66 *	pointer to dst, or NULL if an error occurred (check errno).
67 * note:
68 *	192.5.5.1/28 has a nonzero host part, which means it isn't a network
69 *	as called for by inet_net_ntop() but it can be a host address with
70 *	an included netmask.
71 * author:
72 *	Paul Vixie (ISC), October 1998
73 */
74char *
75inet_cidr_ntop(int af, const void *src, int bits, char *dst, size_t size) {
76	switch (af) {
77	case AF_INET:
78		return (inet_cidr_ntop_ipv4(src, bits, dst, size));
79	case AF_INET6:
80		return (inet_cidr_ntop_ipv6(src, bits, dst, size));
81	default:
82		errno = EAFNOSUPPORT;
83		return (NULL);
84	}
85}
86
87static int
88decoct(const u_char *src, size_t bytes, char *dst, size_t size) {
89	char *odst = dst;
90	char *t;
91	size_t b;
92
93	for (b = 1; b <= bytes; b++) {
94		if (size < sizeof "255.")
95			return (0);
96		t = dst;
97		dst += SPRINTF((dst, "%u", *src++));
98		if (b != bytes) {
99			*dst++ = '.';
100			*dst = '\0';
101		}
102		size -= (size_t)(dst - t);
103	}
104	assert(INT_MIN <= (dst - odst) && (dst - odst) <= INT_MAX);
105	return (int)(dst - odst);
106}
107
108/*%
109 * static char *
110 * inet_cidr_ntop_ipv4(src, bits, dst, size)
111 *	convert IPv4 network address from network to presentation format.
112 *	"src"'s size is determined from its "af".
113 * return:
114 *	pointer to dst, or NULL if an error occurred (check errno).
115 * note:
116 *	network byte order assumed.  this means 192.5.5.240/28 has
117 *	0b11110000 in its fourth octet.
118 * author:
119 *	Paul Vixie (ISC), October 1998
120 */
121static char *
122inet_cidr_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size) {
123	char *odst = dst;
124	size_t len = 4;
125	size_t b;
126	size_t bytes;
127
128	if ((bits < -1) || (bits > 32)) {
129		errno = EINVAL;
130		return (NULL);
131	}
132
133	/* Find number of significant bytes in address. */
134	if (bits == -1)
135		len = 4;
136	else
137		for (len = 1, b = 1 ; b < 4U; b++)
138			if (*(src + b))
139				len = b + 1;
140
141	/* Format whole octets plus nonzero trailing octets. */
142	bytes = (((bits <= 0) ? 1 : bits) + 7) / 8;
143	if (len > bytes)
144		bytes = len;
145	b = decoct(src, bytes, dst, size);
146	if (b == 0U)
147		goto emsgsize;
148	dst += b;
149	size -= b;
150
151	if (bits != -1) {
152		/* Format CIDR /width. */
153		if (size < sizeof "/32")
154			goto emsgsize;
155		dst += SPRINTF((dst, "/%u", bits));
156	}
157
158	return (odst);
159
160 emsgsize:
161	errno = EMSGSIZE;
162	return (NULL);
163}
164
165static char *
166inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) {
167	/*
168	 * Note that int32_t and int16_t need only be "at least" large enough
169	 * to contain a value of the specified size.  On some systems, like
170	 * Crays, there is no such thing as an integer variable with 16 bits.
171	 * Keep this in mind if you think this function should have been coded
172	 * to use pointer overlays.  All the world's not a VAX.
173	 */
174	char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255/128"];
175	char *tp;
176	struct { int base, len; } best, cur;
177	u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
178	int i;
179
180	if ((bits < -1) || (bits > 128)) {
181		errno = EINVAL;
182		return (NULL);
183	}
184
185	/*
186	 * Preprocess:
187	 *	Copy the input (bytewise) array into a wordwise array.
188	 *	Find the longest run of 0x00's in src[] for :: shorthanding.
189	 */
190	memset(words, '\0', sizeof words);
191	for (i = 0; i < NS_IN6ADDRSZ; i++)
192		words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
193	best.base = -1;
194	best.len = 0;
195	cur.base = -1;
196	cur.len = 0;
197	for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
198		if (words[i] == 0) {
199			if (cur.base == -1)
200				cur.base = i, cur.len = 1;
201			else
202				cur.len++;
203		} else {
204			if (cur.base != -1) {
205				if (best.base == -1 || cur.len > best.len)
206					best = cur;
207				cur.base = -1;
208			}
209		}
210	}
211	if (cur.base != -1) {
212		if (best.base == -1 || cur.len > best.len)
213			best = cur;
214	}
215	if (best.base != -1 && best.len < 2)
216		best.base = -1;
217
218	/*
219	 * Format the result.
220	 */
221	tp = tmp;
222	for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
223		/* Are we inside the best run of 0x00's? */
224		if (best.base != -1 && i >= best.base &&
225		    i < (best.base + best.len)) {
226			if (i == best.base)
227				*tp++ = ':';
228			continue;
229		}
230		/* Are we following an initial run of 0x00s or any real hex? */
231		if (i != 0)
232			*tp++ = ':';
233		/* Is this address an encapsulated IPv4? */
234		if (i == 6 && best.base == 0 && (best.len == 6 ||
235		    (best.len == 7 && words[7] != 0x0001) ||
236		    (best.len == 5 && words[5] == 0xffff))) {
237			size_t n;
238
239			if (src[15] || bits == -1 || bits > 120)
240				n = 4;
241			else if (src[14] || bits > 112)
242				n = 3;
243			else
244				n = 2;
245			n = decoct(src+12, n, tp, sizeof tmp - (tp - tmp));
246			if (n == 0) {
247				errno = EMSGSIZE;
248				return (NULL);
249			}
250			tp += strlen(tp);
251			break;
252		}
253		tp += SPRINTF((tp, "%x", words[i]));
254	}
255
256	/* Was it a trailing run of 0x00's? */
257	if (best.base != -1 && (best.base + best.len) ==
258	    (NS_IN6ADDRSZ / NS_INT16SZ))
259		*tp++ = ':';
260	*tp = '\0';
261
262	if (bits != -1)
263		tp += SPRINTF((tp, "/%u", bits));
264
265	/*
266	 * Check for overflow, copy, and we're done.
267	 */
268	if ((size_t)(tp - tmp) > size) {
269		errno = EMSGSIZE;
270		return (NULL);
271	}
272	strcpy(dst, tmp);
273	return (dst);
274}
275
276#undef inet_cidr_ntop
277#pragma weak inet_cidr_ntop = __inet_cidr_ntop
278