]> mj.ucw.cz Git - libucw.git/blob - lib/ipaccess.c
the init-hook of the main section inserts a few nodes into the link-list
[libucw.git] / lib / ipaccess.c
1 /*
2  *      UCW 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 #include <stdlib.h>
18
19 struct ipaccess_list {
20   list l;
21 };
22
23 struct ipaccess_entry {
24   node n;
25   uns allow;
26   u32 addr, mask;
27 };
28
29 struct ipaccess_list *
30 ipaccess_init(void)
31 {
32   /* Cannot use cfg_malloc() here as the pool can be uninitialized now */
33   struct ipaccess_list *l = xmalloc(sizeof(*l));
34
35   init_list(&l->l);
36   return l;
37 }
38
39 byte *
40 ipaccess_parse(struct ipaccess_list *l, byte *c, int is_allow)
41 {
42   byte *p = strchr(c, '/');
43   char *q;
44   struct ipaccess_entry *a = cfg_malloc(sizeof(struct ipaccess_entry));
45   unsigned long pxlen;
46
47   a->allow = is_allow;
48   a->mask = ~0U;
49   if (p)
50     {
51       *p++ = 0;
52       pxlen = strtoul(p, &q, 10);
53       if ((!q || !*q) && pxlen <= 32)
54         {
55           if (pxlen != 32)
56             a->mask = ~(~0U >> (uns) pxlen);
57         }
58       else if (q = cf_parse_ip(&p, &a->mask))
59         return q;
60     }
61   add_tail(&l->l, &a->n);
62   return cf_parse_ip(&c, &a->addr);
63 }
64
65 int
66 ipaccess_check(struct ipaccess_list *l, u32 ip)
67 {
68   struct ipaccess_entry *a;
69
70   DO_FOR_ALL(a, l->l)
71     if (! ((ip ^ a->addr) & a->mask))
72       return a->allow;
73   return 0;
74 }