xref: /freebsd/lib/libc/inet/inet_cidr_ntop.c (revision 069ac18495ad8fde2748bc94b0f80a50250bb01d)
1 /*-
2  * SPDX-License-Identifier: ISC
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 "port_before.h"
21 
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/nameser.h>
26 #include <arpa/inet.h>
27 
28 #include <errno.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 
33 #include "port_after.h"
34 
35 #ifdef SPRINTF_CHAR
36 # define SPRINTF(x) strlen(sprintf/**/x)
37 #else
38 # define SPRINTF(x) ((size_t)sprintf x)
39 #endif
40 
41 static char *
42 inet_cidr_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size);
43 static char *
44 inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size);
45 
46 /*%
47  * char *
48  * inet_cidr_ntop(af, src, bits, dst, size)
49  *	convert network address from network to presentation format.
50  *	"src"'s size is determined from its "af".
51  * return:
52  *	pointer to dst, or NULL if an error occurred (check errno).
53  * note:
54  *	192.5.5.1/28 has a nonzero host part, which means it isn't a network
55  *	as called for by inet_net_ntop() but it can be a host address with
56  *	an included netmask.
57  * author:
58  *	Paul Vixie (ISC), October 1998
59  */
60 char *
61 inet_cidr_ntop(int af, const void *src, int bits, char *dst, size_t size) {
62 	switch (af) {
63 	case AF_INET:
64 		return (inet_cidr_ntop_ipv4(src, bits, dst, size));
65 	case AF_INET6:
66 		return (inet_cidr_ntop_ipv6(src, bits, dst, size));
67 	default:
68 		errno = EAFNOSUPPORT;
69 		return (NULL);
70 	}
71 }
72 
73 static int
74 decoct(const u_char *src, int bytes, char *dst, size_t size) {
75 	char *odst = dst;
76 	char *t;
77 	int b;
78 
79 	for (b = 1; b <= bytes; b++) {
80 		if (size < sizeof "255.")
81 			return (0);
82 		t = dst;
83 		dst += SPRINTF((dst, "%u", *src++));
84 		if (b != bytes) {
85 			*dst++ = '.';
86 			*dst = '\0';
87 		}
88 		size -= (size_t)(dst - t);
89 	}
90 	return (dst - odst);
91 }
92 
93 /*%
94  * static char *
95  * inet_cidr_ntop_ipv4(src, bits, dst, size)
96  *	convert IPv4 network address from network to presentation format.
97  *	"src"'s size is determined from its "af".
98  * return:
99  *	pointer to dst, or NULL if an error occurred (check errno).
100  * note:
101  *	network byte order assumed.  this means 192.5.5.240/28 has
102  *	0b11110000 in its fourth octet.
103  * author:
104  *	Paul Vixie (ISC), October 1998
105  */
106 static char *
107 inet_cidr_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size) {
108 	char *odst = dst;
109 	size_t len = 4;
110 	size_t b;
111 	size_t bytes;
112 
113 	if ((bits < -1) || (bits > 32)) {
114 		errno = EINVAL;
115 		return (NULL);
116 	}
117 
118 	/* Find number of significant bytes in address. */
119 	if (bits == -1)
120 		len = 4;
121 	else
122 		for (len = 1, b = 1 ; b < 4U; b++)
123 			if (*(src + b))
124 				len = b + 1;
125 
126 	/* Format whole octets plus nonzero trailing octets. */
127 	bytes = (((bits <= 0) ? 1 : bits) + 7) / 8;
128 	if (len > bytes)
129 		bytes = len;
130 	b = decoct(src, bytes, dst, size);
131 	if (b == 0U)
132 		goto emsgsize;
133 	dst += b;
134 	size -= b;
135 
136 	if (bits != -1) {
137 		/* Format CIDR /width. */
138 		if (size < sizeof "/32")
139 			goto emsgsize;
140 		dst += SPRINTF((dst, "/%u", bits));
141 	}
142 
143 	return (odst);
144 
145  emsgsize:
146 	errno = EMSGSIZE;
147 	return (NULL);
148 }
149 
150 static char *
151 inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) {
152 	/*
153 	 * Note that int32_t and int16_t need only be "at least" large enough
154 	 * to contain a value of the specified size.  On some systems, like
155 	 * Crays, there is no such thing as an integer variable with 16 bits.
156 	 * Keep this in mind if you think this function should have been coded
157 	 * to use pointer overlays.  All the world's not a VAX.
158 	 */
159 	char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255/128"];
160 	char *tp;
161 	struct { int base, len; } best, cur;
162 	u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
163 	int i;
164 
165 	if ((bits < -1) || (bits > 128)) {
166 		errno = EINVAL;
167 		return (NULL);
168 	}
169 
170 	/*
171 	 * Preprocess:
172 	 *	Copy the input (bytewise) array into a wordwise array.
173 	 *	Find the longest run of 0x00's in src[] for :: shorthanding.
174 	 */
175 	memset(words, '\0', sizeof words);
176 	for (i = 0; i < NS_IN6ADDRSZ; i++)
177 		words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
178 	best.base = -1;
179 	best.len = 0;
180 	cur.base = -1;
181 	cur.len = 0;
182 	for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
183 		if (words[i] == 0) {
184 			if (cur.base == -1)
185 				cur.base = i, cur.len = 1;
186 			else
187 				cur.len++;
188 		} else {
189 			if (cur.base != -1) {
190 				if (best.base == -1 || cur.len > best.len)
191 					best = cur;
192 				cur.base = -1;
193 			}
194 		}
195 	}
196 	if (cur.base != -1) {
197 		if (best.base == -1 || cur.len > best.len)
198 			best = cur;
199 	}
200 	if (best.base != -1 && best.len < 2)
201 		best.base = -1;
202 
203 	/*
204 	 * Format the result.
205 	 */
206 	tp = tmp;
207 	for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
208 		/* Are we inside the best run of 0x00's? */
209 		if (best.base != -1 && i >= best.base &&
210 		    i < (best.base + best.len)) {
211 			if (i == best.base)
212 				*tp++ = ':';
213 			continue;
214 		}
215 		/* Are we following an initial run of 0x00s or any real hex? */
216 		if (i != 0)
217 			*tp++ = ':';
218 		/* Is this address an encapsulated IPv4? */
219 		if (i == 6 && best.base == 0 && (best.len == 6 ||
220 		    (best.len == 7 && words[7] != 0x0001) ||
221 		    (best.len == 5 && words[5] == 0xffff))) {
222 			int n;
223 
224 			if (src[15] || bits == -1 || bits > 120)
225 				n = 4;
226 			else if (src[14] || bits > 112)
227 				n = 3;
228 			else
229 				n = 2;
230 			n = decoct(src+12, n, tp, sizeof tmp - (tp - tmp));
231 			if (n == 0) {
232 				errno = EMSGSIZE;
233 				return (NULL);
234 			}
235 			tp += strlen(tp);
236 			break;
237 		}
238 		tp += SPRINTF((tp, "%x", words[i]));
239 	}
240 
241 	/* Was it a trailing run of 0x00's? */
242 	if (best.base != -1 && (best.base + best.len) ==
243 	    (NS_IN6ADDRSZ / NS_INT16SZ))
244 		*tp++ = ':';
245 	*tp = '\0';
246 
247 	if (bits != -1)
248 		tp += SPRINTF((tp, "/%u", bits));
249 
250 	/*
251 	 * Check for overflow, copy, and we're done.
252 	 */
253 	if ((size_t)(tp - tmp) > size) {
254 		errno = EMSGSIZE;
255 		return (NULL);
256 	}
257 	strcpy(dst, tmp);
258 	return (dst);
259 }
260 
261 /*! \file */
262