1 /* IPNode.c - NeonServ v5.5
2 * Copyright (C) 2011-2012 Philipp Kreil (pk910)
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #define hex2dec(x) (isxdigit(x) ? (isdigit(x) ? x - '0' : (isupper(x) ? x - 'A' : x - 'a') + 10) : 0)
21 static struct IPNode *parseIP(struct IPNode *ip, const char *org_ipstr);
23 struct IPNode *createIPNode(const char *ipstr) {
24 struct IPNode *ip = malloc(sizeof(*ip));
27 if(!parseIP(ip, ipstr)) {
34 static struct IPNode *parseIP(struct IPNode *ip, const char *org_ipstr) {
35 char ipstr[strlen(org_ipstr)+1];
36 strcpy(ipstr, org_ipstr);
37 if(strchr(ipstr, ':')) {
38 ip->flags |= IPNODE_IS_IPV6;
43 if(p1[0] == ':' && p1[1] == ':') {
55 if(blocks > 8) return 0;
58 for(i = 0; i < 32; i++)
64 if(p1[0] == ':' && p1[1] == ':') {
70 while(*p2 && *p2 != ':') {
81 while(*p2 && *p2 != ':') {
87 if(p >= 4 || i >= 8) return NULL;
88 hexa[i*4 + ((4-len) + (p++))] = *p1;
91 for(i = 0, p = 0; i < 32; i+=2, p++) {
92 ip->ipdata[p] = hex2dec(hexa[i]) << 4;
93 ip->ipdata[p] |= hex2dec(hexa[i+1]);
95 } else if(strchr(ipstr, '.')) {
97 char *next = strchr(ipstr, '/');
104 next = strchr(ippart, '.');
105 if(next) *next = '\0';
106 if(i >= 4) return NULL;
107 ip->ipdata[12+(i++)] = (unsigned char) atoi(ippart);
114 if(i != 3) return NULL;
120 int ipmatch(struct IPNode *ip1, struct IPNode *ip2, int bits) {
122 bits = (ip2->flags & IPNODE_IS_IPV6 ? bits : bits + (12*8));
123 if(bits > 128) return 1;
124 int sbit = (bits % 8);
125 int check = (bits / 8) + (sbit ? 1 : 0);
127 for(i = 0; i < check; i++) {
128 if(i == check-1 && sbit) {
131 for(;j < sbit; j++) {
139 if((ip1->ipdata[i] & bitmask) != (ip2->ipdata[i] & bitmask))
141 } else if(ip1->ipdata[i] != ip2->ipdata[i])
147 void freeIPNode(struct IPNode *ip) {