cidr.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /* $Id: cidr.c 1543 2006-07-29 06:20:25Z aturner $ */
  2. /*
  3. * Copyright (c) 2001-2004 Aaron Turner.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the names of the copyright owners nor the names of its
  16. * contributors may be used to endorse or promote products derived from
  17. * this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  20. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  21. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  23. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  25. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  27. * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  28. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  29. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #include "config.h"
  32. #include "defines.h"
  33. #include "common.h"
  34. #include "lib/strlcpy.h"
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. /* required for inet_aton() */
  39. #include <sys/socket.h>
  40. #include <netinet/in.h>
  41. #include <arpa/inet.h>
  42. #ifdef DEBUG
  43. extern int debug;
  44. #endif
  45. static tcpr_cidr_t *cidr2cidr(char *);
  46. /*
  47. * prints to the given fd all the entries in mycidr
  48. */
  49. void
  50. print_cidr(tcpr_cidr_t * mycidr)
  51. {
  52. tcpr_cidr_t *cidr_ptr;
  53. fprintf(stderr, "Cidr List: ");
  54. cidr_ptr = mycidr;
  55. while (cidr_ptr != NULL) {
  56. /* print it */
  57. fprintf(stderr, "%s/%d, ",
  58. get_addr2name4(cidr_ptr->network, RESOLVE),
  59. cidr_ptr->masklen);
  60. /* go to the next */
  61. if (cidr_ptr->next != NULL) {
  62. cidr_ptr = cidr_ptr->next;
  63. }
  64. else {
  65. break;
  66. }
  67. }
  68. fprintf(stderr, "\n");
  69. }
  70. /*
  71. * deletes all entries in a cidr and destroys the datastructure
  72. */
  73. void
  74. destroy_cidr(tcpr_cidr_t * cidr)
  75. {
  76. if (cidr != NULL)
  77. if (cidr->next != NULL)
  78. destroy_cidr(cidr->next);
  79. free(cidr);
  80. return;
  81. }
  82. /*
  83. * adds a new tcpr_cidr_t entry to cidrdata
  84. */
  85. void
  86. add_cidr(tcpr_cidr_t ** cidrdata, tcpr_cidr_t ** newcidr)
  87. {
  88. tcpr_cidr_t *cidr_ptr;
  89. dbg(1, "Running new_cidr()");
  90. if (*cidrdata == NULL) {
  91. *cidrdata = *newcidr;
  92. }
  93. else {
  94. cidr_ptr = *cidrdata;
  95. while (cidr_ptr->next != NULL) {
  96. cidr_ptr = cidr_ptr->next;
  97. }
  98. cidr_ptr->next = *newcidr;
  99. }
  100. }
  101. /*
  102. * takes in an IP and masklen, and returns a string in
  103. * cidr format: x.x.x.x/y. This malloc's memory.
  104. */
  105. u_char *
  106. ip2cidr(const unsigned long ip, const int masklen)
  107. {
  108. u_char *network;
  109. char mask[3];
  110. network = (u_char *)safe_malloc(20);
  111. strlcpy((char *)network, (char *)get_addr2name4(ip, RESOLVE),
  112. sizeof(network));
  113. strcat((char *)network, "/");
  114. if (masklen < 10) {
  115. snprintf(mask, 1, "%d", masklen);
  116. strncat((char *)network, mask, 1);
  117. }
  118. else {
  119. snprintf(mask, 2, "%d", masklen);
  120. strncat((char *)network, mask, 2);
  121. }
  122. return (network);
  123. }
  124. /*
  125. * Mallocs and sets to sane defaults a tcpr_cidr_t structure
  126. */
  127. tcpr_cidr_t *
  128. new_cidr(void)
  129. {
  130. tcpr_cidr_t *newcidr;
  131. newcidr = (tcpr_cidr_t *)safe_malloc(sizeof(tcpr_cidr_t));
  132. memset(newcidr, '\0', sizeof(tcpr_cidr_t));
  133. newcidr->masklen = 99;
  134. newcidr->next = NULL;
  135. return (newcidr);
  136. }
  137. tcpr_cidrmap_t *
  138. new_cidr_map(void)
  139. {
  140. tcpr_cidrmap_t *new;
  141. new = (tcpr_cidrmap_t *)safe_malloc(sizeof(tcpr_cidrmap_t));
  142. memset(new, '\0', sizeof(tcpr_cidrmap_t));
  143. new->next = NULL;
  144. return (new);
  145. }
  146. /*
  147. * Converts a single cidr (string) in the form of x.x.x.x/y into a
  148. * tcpr_cidr_t structure. Will malloc the tcpr_cidr_t structure.
  149. */
  150. static tcpr_cidr_t *
  151. cidr2cidr(char *cidr)
  152. {
  153. int count = 0;
  154. unsigned int octets[4]; /* used in sscanf */
  155. tcpr_cidr_t *newcidr;
  156. char networkip[16], tempoctet[4], ebuf[EBUF_SIZE];
  157. assert(cidr);
  158. assert(strlen(cidr) <= EBUF_SIZE);
  159. newcidr = new_cidr();
  160. /*
  161. * scan it, and make sure it scanned correctly, also copy over the
  162. * masklen
  163. */
  164. count = sscanf(cidr, "%u.%u.%u.%u/%d", &octets[0], &octets[1],
  165. &octets[2], &octets[3], &newcidr->masklen);
  166. if (count == 4) {
  167. newcidr->masklen = 32;
  168. } else if (count != 5) {
  169. goto error;
  170. }
  171. /* masklen better be 0 =< masklen <= 32 */
  172. if (newcidr->masklen > 32)
  173. goto error;
  174. /* copy in the ip address */
  175. memset(networkip, '\0', 16);
  176. for (count = 0; count < 4; count++) {
  177. if (octets[count] > 255)
  178. goto error;
  179. snprintf(tempoctet, sizeof(octets[count]), "%d", octets[count]);
  180. strcat(networkip, tempoctet);
  181. /* we don't want a '.' at the end of the last octet */
  182. if (count < 3)
  183. strcat(networkip, ".");
  184. }
  185. /* copy over the network address and return */
  186. #ifdef HAVE_INET_ATON
  187. inet_aton(networkip, (struct in_addr *)&newcidr->network);
  188. #elif HAVE_INET_ADDR
  189. newcidr->network = inet_addr(networkip);
  190. #endif
  191. return (newcidr);
  192. /* we only get here on error parsing input */
  193. error:
  194. memset(ebuf, '\0', EBUF_SIZE);
  195. strcpy(ebuf, "Unable to parse as a vaild CIDR: ");
  196. strlcat(ebuf, cidr, EBUF_SIZE);
  197. errx(1, "%s", ebuf);
  198. return NULL;
  199. }
  200. /*
  201. * parses a list of tcpr_cidr_t's input from the user which should be in the form
  202. * of x.x.x.x/y,x.x.x.x/y...
  203. * returns 1 for success, or fails to return on failure (exit 1)
  204. * since we use strtok to process cidr, it gets zeroed out.
  205. */
  206. int
  207. parse_cidr(tcpr_cidr_t ** cidrdata, char *cidrin, char *delim)
  208. {
  209. tcpr_cidr_t *cidr_ptr; /* ptr to current cidr record */
  210. char *network = NULL;
  211. char *token = NULL;
  212. /* first itteration of input using strtok */
  213. network = strtok_r(cidrin, delim, &token);
  214. *cidrdata = cidr2cidr(network);
  215. cidr_ptr = *cidrdata;
  216. /* do the same with the rest of the input */
  217. while (1) {
  218. network = strtok_r(NULL, delim, &token);
  219. /* if that was the last CIDR, then kickout */
  220. if (network == NULL)
  221. break;
  222. /* next record */
  223. cidr_ptr->next = cidr2cidr(network);
  224. cidr_ptr = cidr_ptr->next;
  225. }
  226. return 1;
  227. }
  228. /*
  229. * parses a pair of IP addresses: <IP1>:<IP2> and processes it like:
  230. * -N 0.0.0.0/0:<IP1> -N 0.0.0.0/0:<IP2>
  231. * returns 1 for success or returns 0 on failure
  232. * since we use strtok to process optarg, it gets zeroed out
  233. */
  234. int
  235. parse_endpoints(tcpr_cidrmap_t ** cidrmap1, tcpr_cidrmap_t ** cidrmap2, const char *optarg)
  236. {
  237. #define NEWMAP_LEN 32
  238. char *map = NULL, newmap[NEWMAP_LEN];
  239. char *token = NULL;
  240. char *string;
  241. string = safe_strdup(optarg);
  242. memset(newmap, '\0', NEWMAP_LEN);
  243. map = strtok_r(string, ":", &token);
  244. strlcpy(newmap, "0.0.0.0/0:", NEWMAP_LEN);
  245. strlcat(newmap, map, NEWMAP_LEN);
  246. if (! parse_cidr_map(cidrmap1, newmap))
  247. return 0;
  248. /* do again with the second IP */
  249. memset(newmap, '\0', NEWMAP_LEN);
  250. map = strtok_r(NULL, ":", &token);
  251. strlcpy(newmap, "0.0.0.0/0:", NEWMAP_LEN);
  252. strlcat(newmap, map, NEWMAP_LEN);
  253. if (! parse_cidr_map(cidrmap2, newmap))
  254. return 0;
  255. free(string);
  256. return 1; /* success */
  257. }
  258. /*
  259. * parses a list of tcpr_cidrmap_t's input from the user which should be in the form
  260. * of x.x.x.x/y:x.x.x.x/y,...
  261. * returns 1 for success, or returns 0 on failure
  262. * since we use strtok to process optarg, it gets zeroed out.
  263. */
  264. int
  265. parse_cidr_map(tcpr_cidrmap_t **cidrmap, const char *optarg)
  266. {
  267. tcpr_cidr_t *cidr = NULL;
  268. char *map = NULL;
  269. char *token = NULL, *string = NULL;
  270. tcpr_cidrmap_t *ptr;
  271. string = safe_strdup(optarg);
  272. /* first iteration */
  273. map = strtok_r(string, ",", &token);
  274. if (! parse_cidr(&cidr, map, ":"))
  275. return 0;
  276. /* must return a linked list of two */
  277. if (cidr->next == NULL)
  278. return 0;
  279. /* copy over */
  280. *cidrmap = new_cidr_map();
  281. ptr = *cidrmap;
  282. ptr->from = cidr;
  283. ptr->to = cidr->next;
  284. ptr->from->next = NULL;
  285. /* do the same with the reset of the input */
  286. while(1) {
  287. map = strtok_r(NULL, ",", &token);
  288. if (map == NULL)
  289. break;
  290. if (! parse_cidr(&cidr, map, ":"))
  291. return 0;
  292. /* must return a linked list of two */
  293. if (cidr->next == NULL)
  294. return 0;
  295. /* copy over */
  296. ptr->next = new_cidr_map();
  297. ptr = ptr->next;
  298. ptr->from = cidr;
  299. ptr->to = cidr->next;
  300. ptr->from->next = NULL;
  301. }
  302. free(string);
  303. return 1; /* success */
  304. }
  305. /*
  306. * checks to see if the ip address is in the cidr
  307. * returns CACHE_PRIMARY for true, CACHE_SECONDARY for false
  308. */
  309. int
  310. ip_in_cidr(const tcpr_cidr_t * mycidr, const unsigned long ip)
  311. {
  312. unsigned long ipaddr = 0, network = 0, mask = 0;
  313. int ret;
  314. /* always return 1 if 0.0.0.0/0 */
  315. if (mycidr->masklen == 0 && mycidr->network == 0)
  316. return CACHE_PRIMARY;
  317. mask = ~0; /* turn on all the bits */
  318. /* shift over by the correct number of bits */
  319. mask = mask << (32 - mycidr->masklen);
  320. /* apply the mask to the network and ip */
  321. ipaddr = ntohl(ip) & mask;
  322. network = htonl(mycidr->network) & mask;
  323. /* if they're the same, then ip is in network */
  324. if (network == ipaddr) {
  325. dbgx(1, "The ip %s is inside of %s/%d",
  326. get_addr2name4(ip, RESOLVE),
  327. get_addr2name4(htonl(network), RESOLVE), mycidr->masklen);
  328. ret = CACHE_PRIMARY;
  329. }
  330. else {
  331. dbgx(1, "The ip %s is not inside of %s/%d",
  332. get_addr2name4(ip, RESOLVE),
  333. get_addr2name4(htonl(network), RESOLVE), mycidr->masklen);
  334. ret = CACHE_SECONDARY;
  335. }
  336. return ret;
  337. }
  338. /*
  339. * iterates over cidrdata to find if a given ip matches
  340. * returns CACHE_PRIMARY for true, CACHE_SECONDARY for false
  341. */
  342. int
  343. check_ip_cidr(tcpr_cidr_t * cidrdata, const unsigned long ip)
  344. {
  345. tcpr_cidr_t *mycidr;
  346. /* if we have no cidrdata, of course it isn't in there
  347. * this actually should happen occasionally, so don't put an assert here
  348. */
  349. if (cidrdata == NULL) {
  350. return CACHE_SECONDARY;
  351. }
  352. mycidr = cidrdata;
  353. /* loop through cidr */
  354. while (1) {
  355. /* if match, return 1 */
  356. if (ip_in_cidr(mycidr, ip) == CACHE_PRIMARY) {
  357. dbgx(3, "Found %s in cidr", get_addr2name4(ip, RESOLVE));
  358. return CACHE_PRIMARY;
  359. }
  360. /* check for next record */
  361. if (mycidr->next != NULL) {
  362. mycidr = mycidr->next;
  363. }
  364. else {
  365. break;
  366. }
  367. }
  368. /* if we get here, no match */
  369. dbgx(3, "Didn't find %s in cidr", get_addr2name4(ip, RESOLVE));
  370. return CACHE_SECONDARY;
  371. }
  372. /*
  373. * cidr2ip takes a tcpr_cidr_t and a delimiter
  374. * and returns a string which lists all the IP addresses in the cidr
  375. * deliminated by the given char
  376. */
  377. char *
  378. cidr2iplist(tcpr_cidr_t * cidr, char delim)
  379. {
  380. char *list = NULL;
  381. char ipaddr[16];
  382. u_int32_t size, addr, first, last, numips;
  383. struct in_addr in;
  384. /*
  385. * 16 bytes per IP + delim
  386. * # of IP's = 2^(32-masklen)
  387. */
  388. numips = 2;
  389. for (int i = 2; i <= (32 - cidr->masklen); i++) {
  390. numips *= 2;
  391. }
  392. size = 16 * numips;
  393. list = (char *)safe_malloc(size);
  394. memset(list, 0, size);
  395. /* first and last should not include network or broadcast */
  396. first = ntohl(cidr->network) + 1;
  397. last = first + numips - 3;
  398. dbgx(1, "First: %u\t\tLast: %u", first, last);
  399. /* loop through all but the last one */
  400. for (addr = first; addr < last; addr++) {
  401. in.s_addr = htonl(addr);
  402. snprintf(ipaddr, 17, "%s%c", inet_ntoa(in), delim);
  403. dbgx(2, "%s", ipaddr);
  404. strlcat(list, ipaddr, size);
  405. }
  406. /* last is a special case, end in \0 */
  407. in.s_addr = htonl(addr);
  408. snprintf(ipaddr, 16, "%s", inet_ntoa(in));
  409. strlcat(list, ipaddr, size);
  410. return list;
  411. }
  412. /*
  413. Local Variables:
  414. mode:c
  415. indent-tabs-mode:nil
  416. c-basic-offset:4
  417. End:
  418. */