]> mj.ucw.cz Git - libucw.git/blob - lib/ipaccess.c
Added generic functions for IP address access lists.
[libucw.git] / lib / ipaccess.c
1 /*
2  *      Sherlock Library -- IP address access lists
3  *
4  *      (c) 1997--2001 Martin Mares <mj@ucw.cz>
5  */
6
7 #include "lib/lib.h"
8 #include "lib/conf.h"
9 #include "lib/chartype.h"
10 #include "lib/ipaccess.h"
11
12 #include <string.h>
13
14 struct ipaccess_entry {
15   node n;
16   uns allow;
17   u32 addr, mask;
18 };
19
20 void
21 ipaccess_init(ipaccess_list *l)
22 {
23   init_list(l);
24 }
25
26 static byte *
27 parse_ip(byte *x, u32 *a)
28 {
29   uns i, q;
30   u32 z = 0;
31
32   for(i=0; i<4; i++)
33     {
34       q = 0;
35       while (Cdigit(*x))
36         {
37           q = q*10 + *x++ - '0';
38           if (q > 255)
39             return "Invalid IP address";
40         }
41       if (*x++ != ((i == 3) ? 0 : '.'))
42         return "Invalid IP address";
43       z = (z << 8) | q;
44     }
45   *a = z;
46   return NULL;
47 }
48
49 byte *
50 ipaccess_parse(ipaccess_list *l, byte *c, int is_allow)
51 {
52   byte *p = strchr(c, '/');
53   byte *q;
54   struct ipaccess_entry *a = cfg_malloc(sizeof(struct ipaccess_entry));
55
56   a->allow = is_allow;
57   if (p)
58     {
59       *p++ = 0;
60       if (q = parse_ip(p, &a->mask))
61         return q;
62     }
63   else
64     a->mask = ~0;
65   add_tail(l, &a->n);
66   return parse_ip(c, &a->addr);
67 }
68
69 int
70 ipaccess_check(ipaccess_list *l, u32 ip)
71 {
72   struct ipaccess_entry *a;
73
74   DO_FOR_ALL(a, *l)
75     if (! ((ip ^ a->addr) & a->mask))
76       return a->allow;
77   return 0;
78 }