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