1 /**
2  * @file
3  * This is the IPv4 address tools implementation.
4  *
5  */
6 
7 /*
8  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation
18  *    and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
23  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
27  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
31  * OF SUCH DAMAGE.
32  *
33  * This file is part of the lwIP TCP/IP stack.
34  *
35  * Author: Adam Dunkels <adam@sics.se>
36  *
37  */
38 
39 #include "lwip/opt.h"
40 
41 #if LWIP_IPV4
42 
43 #include "lwip/ip_addr.h"
44 #include "lwip/netif.h"
45 
46 /* used by IP4_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */
47 const ip_addr_t ip_addr_any = IPADDR4_INIT(IPADDR_ANY);
48 const ip_addr_t ip_addr_broadcast = IPADDR4_INIT(IPADDR_BROADCAST);
49 
50 /**
51  * Determine if an address is a broadcast address on a network interface
52  *
53  * @param addr address to be checked
54  * @param netif the network interface against which the address is checked
55  * @return returns non-zero if the address is a broadcast address
56  */
57 u8_t
ip4_addr_isbroadcast_u32(u32_t addr,const struct netif * netif)58 ip4_addr_isbroadcast_u32(u32_t addr, const struct netif *netif)
59 {
60   ip4_addr_t ipaddr;
61   ip4_addr_set_u32(&ipaddr, addr);
62 
63   /* all ones (broadcast) or all zeroes (old skool broadcast) */
64   if ((~addr == IPADDR_ANY) ||
65       (addr == IPADDR_ANY)) {
66     return 1;
67   /* no broadcast support on this network interface? */
68   } else if ((netif->flags & NETIF_FLAG_BROADCAST) == 0) {
69     /* the given address cannot be a broadcast address
70      * nor can we check against any broadcast addresses */
71     return 0;
72   /* address matches network interface address exactly? => no broadcast */
73   } else if (addr == ip4_addr_get_u32(netif_ip4_addr(netif))) {
74     return 0;
75   /*  on the same (sub) network... */
76   } else if (ip4_addr_netcmp(&ipaddr, netif_ip4_addr(netif), netif_ip4_netmask(netif))
77          /* ...and host identifier bits are all ones? =>... */
78           && ((addr & ~ip4_addr_get_u32(netif_ip4_netmask(netif))) ==
79            (IPADDR_BROADCAST & ~ip4_addr_get_u32(netif_ip4_netmask(netif))))) {
80     /* => network broadcast address */
81     return 1;
82   } else {
83     return 0;
84   }
85 }
86 
87 /** Checks if a netmask is valid (starting with ones, then only zeros)
88  *
89  * @param netmask the IPv4 netmask to check (in network byte order!)
90  * @return 1 if the netmask is valid, 0 if it is not
91  */
92 u8_t
ip4_addr_netmask_valid(u32_t netmask)93 ip4_addr_netmask_valid(u32_t netmask)
94 {
95   u32_t mask;
96   u32_t nm_hostorder = lwip_htonl(netmask);
97 
98   /* first, check for the first zero */
99   for (mask = 1UL << 31 ; mask != 0; mask >>= 1) {
100     if ((nm_hostorder & mask) == 0) {
101       break;
102     }
103   }
104   /* then check that there is no one */
105   for (; mask != 0; mask >>= 1) {
106     if ((nm_hostorder & mask) != 0) {
107       /* there is a one after the first zero -> invalid */
108       return 0;
109     }
110   }
111   /* no one after the first zero -> valid */
112   return 1;
113 }
114 
115 /* Here for now until needed in other places in lwIP */
116 #ifndef isprint
117 #define in_range(c, lo, up)  ((u8_t)c >= lo && (u8_t)c <= up)
118 #define isprint(c)           in_range(c, 0x20, 0x7f)
119 #define isdigit(c)           in_range(c, '0', '9')
120 #define isxdigit(c)          (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F'))
121 #define islower(c)           in_range(c, 'a', 'z')
122 #define isspace(c)           (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v')
123 #endif
124 
125 /**
126  * Ascii internet address interpretation routine.
127  * The value returned is in network order.
128  *
129  * @param cp IP address in ascii representation (e.g. "127.0.0.1")
130  * @return ip address in network order
131  */
132 u32_t
ipaddr_addr(const char * cp)133 ipaddr_addr(const char *cp)
134 {
135   ip4_addr_t val;
136 
137   if (ip4addr_aton(cp, &val)) {
138     return ip4_addr_get_u32(&val);
139   }
140   return (IPADDR_NONE);
141 }
142 
143 /**
144  * Check whether "cp" is a valid ascii representation
145  * of an Internet address and convert to a binary address.
146  * Returns 1 if the address is valid, 0 if not.
147  * This replaces inet_addr, the return value from which
148  * cannot distinguish between failure and a local broadcast address.
149  *
150  * @param cp IP address in ascii representation (e.g. "127.0.0.1")
151  * @param addr pointer to which to save the ip address in network order
152  * @return 1 if cp could be converted to addr, 0 on failure
153  */
154 int
ip4addr_aton(const char * cp,ip4_addr_t * addr)155 ip4addr_aton(const char *cp, ip4_addr_t *addr)
156 {
157   u32_t val;
158   u8_t base;
159   char c;
160   u32_t parts[4];
161   u32_t *pp = parts;
162 
163   c = *cp;
164   for (;;) {
165     /*
166      * Collect number up to ``.''.
167      * Values are specified as for C:
168      * 0x=hex, 0=octal, 1-9=decimal.
169      */
170     if (!isdigit(c)) {
171       return 0;
172     }
173     val = 0;
174     base = 10;
175     if (c == '0') {
176       c = *++cp;
177       if (c == 'x' || c == 'X') {
178         base = 16;
179         c = *++cp;
180       } else {
181         base = 8;
182       }
183     }
184     for (;;) {
185       if (isdigit(c)) {
186         val = (val * base) + (int)(c - '0');
187         c = *++cp;
188       } else if (base == 16 && isxdigit(c)) {
189         val = (val << 4) | (int)(c + 10 - (islower(c) ? 'a' : 'A'));
190         c = *++cp;
191       } else {
192         break;
193       }
194     }
195     if (c == '.') {
196       /*
197        * Internet format:
198        *  a.b.c.d
199        *  a.b.c   (with c treated as 16 bits)
200        *  a.b (with b treated as 24 bits)
201        */
202       if (pp >= parts + 3) {
203         return 0;
204       }
205       *pp++ = val;
206       c = *++cp;
207     } else {
208       break;
209     }
210   }
211   /*
212    * Check for trailing characters.
213    */
214   if (c != '\0' && !isspace(c)) {
215     return 0;
216   }
217   /*
218    * Concoct the address according to
219    * the number of parts specified.
220    */
221   switch (pp - parts + 1) {
222 
223   case 0:
224     return 0;       /* initial nondigit */
225 
226   case 1:             /* a -- 32 bits */
227     break;
228 
229   case 2:             /* a.b -- 8.24 bits */
230     if (val > 0xffffffUL) {
231       return 0;
232     }
233     if (parts[0] > 0xff) {
234       return 0;
235     }
236     val |= parts[0] << 24;
237     break;
238 
239   case 3:             /* a.b.c -- 8.8.16 bits */
240     if (val > 0xffff) {
241       return 0;
242     }
243     if ((parts[0] > 0xff) || (parts[1] > 0xff)) {
244       return 0;
245     }
246     val |= (parts[0] << 24) | (parts[1] << 16);
247     break;
248 
249   case 4:             /* a.b.c.d -- 8.8.8.8 bits */
250     if (val > 0xff) {
251       return 0;
252     }
253     if ((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff)) {
254       return 0;
255     }
256     val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
257     break;
258   default:
259     LWIP_ASSERT("unhandled", 0);
260     break;
261   }
262   if (addr) {
263     ip4_addr_set_u32(addr, lwip_htonl(val));
264   }
265   return 1;
266 }
267 
268 /**
269  * Convert numeric IP address into decimal dotted ASCII representation.
270  * returns ptr to static buffer; not reentrant!
271  *
272  * @param addr ip address in network order to convert
273  * @return pointer to a global static (!) buffer that holds the ASCII
274  *         representation of addr
275  */
276 char*
ip4addr_ntoa(const ip4_addr_t * addr)277 ip4addr_ntoa(const ip4_addr_t *addr)
278 {
279   static char str[IP4ADDR_STRLEN_MAX];
280   return ip4addr_ntoa_r(addr, str, IP4ADDR_STRLEN_MAX);
281 }
282 
283 /**
284  * Same as ipaddr_ntoa, but reentrant since a user-supplied buffer is used.
285  *
286  * @param addr ip address in network order to convert
287  * @param buf target buffer where the string is stored
288  * @param buflen length of buf
289  * @return either pointer to buf which now holds the ASCII
290  *         representation of addr or NULL if buf was too small
291  */
292 char*
ip4addr_ntoa_r(const ip4_addr_t * addr,char * buf,int buflen)293 ip4addr_ntoa_r(const ip4_addr_t *addr, char *buf, int buflen)
294 {
295   u32_t s_addr;
296   char inv[3];
297   char *rp;
298   u8_t *ap;
299   u8_t rem;
300   u8_t n;
301   u8_t i;
302   int len = 0;
303 
304   s_addr = ip4_addr_get_u32(addr);
305 
306   rp = buf;
307   ap = (u8_t *)&s_addr;
308   for (n = 0; n < 4; n++) {
309     i = 0;
310     do {
311       rem = *ap % (u8_t)10;
312       *ap /= (u8_t)10;
313       inv[i++] = '0' + rem;
314     } while (*ap);
315     while (i--) {
316       if (len++ >= buflen) {
317         return NULL;
318       }
319       *rp++ = inv[i];
320     }
321     if (len++ >= buflen) {
322       return NULL;
323     }
324     *rp++ = '.';
325     ap++;
326   }
327   *--rp = 0;
328   return buf;
329 }
330 
331 #endif /* LWIP_IPV4 */
332