2 This file is part of GNUnet
3 (C) 2012, 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file src/tun/regex.c
22 * @brief functions to convert IP networks to regexes
23 * @author Maximilian Szengel
26 #include "gnunet_util_lib.h"
27 #include "gnunet_tun_lib.h"
31 * Create a string with binary IP notation for the given 'addr' in 'str'.
33 * @param af address family of the given 'addr'.
34 * @param addr address that should be converted to a string.
35 * struct in_addr * for IPv4 and struct in6_addr * for IPv6.
36 * @param str string that will contain binary notation of 'addr'. Expected
37 * to be at least 33 bytes long for IPv4 and 129 bytes long for IPv6.
40 iptobinstr (const int af, const void *addr, char *str)
48 uint32_t b = htonl (((struct in_addr *) addr)->s_addr);
52 for (i = 31; i >= 0; i--)
62 struct in6_addr b = *(const struct in6_addr *) addr;
66 for (i = 127; i >= 0; i--)
68 *str = (b.s6_addr[i / 8] & 1) + '0';
70 b.s6_addr[i / 8] >>= 1;
79 * Get the ipv4 network prefix from the given 'netmask'.
81 * @param netmask netmask for which to get the prefix len.
83 * @return length of ipv4 prefix for 'netmask'.
86 ipv4netmasktoprefixlen (const char *netmask)
92 if (1 != inet_pton (AF_INET, netmask, &a))
95 for (t = htonl (~a.s_addr); 0 != t; t >>= 1)
102 * Create a regex in 'rxstr' from the given 'ip' and 'netmask'.
104 * @param ip IPv4 representation.
105 * @param netmask netmask for the ip.
106 * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV4_REGEXLEN
110 GNUNET_TUN_ipv4toregex (const struct in_addr *ip, const char *netmask,
115 pfxlen = ipv4netmasktoprefixlen (netmask);
116 iptobinstr (AF_INET, ip, rxstr);
117 rxstr[pfxlen] = '\0';
119 strcat (rxstr, "(0|1)+");
124 * Create a regex in 'rxstr' from the given 'ipv6' and 'prefixlen'.
126 * @param ipv6 IPv6 representation.
127 * @param prefixlen length of the ipv6 prefix.
128 * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV6_REGEXLEN
132 GNUNET_TUN_ipv6toregex (const struct in6_addr *ipv6, unsigned int prefixlen,
135 iptobinstr (AF_INET6, ipv6, rxstr);
136 rxstr[prefixlen] = '\0';
138 strcat (rxstr, "(0|1)+");