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