]> mj.ucw.cz Git - libucw.git/blob - lib/ipaccess.c
conf2: bugfixes in journaling
[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 #include <errno.h>
19
20 struct ipaccess_list {
21   list l;
22 };
23
24 struct ipaccess_entry {
25   node n;
26   uns allow;
27   u32 addr, mask;
28 };
29
30 struct ipaccess_list *
31 ipaccess_init(void)
32 {
33   /* Cannot use cfg_malloc() here as the pool can be uninitialized now */
34   struct ipaccess_list *l = xmalloc(sizeof(*l));
35
36   init_list(&l->l);
37   return l;
38 }
39
40 static byte *
41 parse_ip(byte **p, u32 *varp)
42 {
43   while (Cspace(**p))
44     (*p)++;
45   if (!**p)
46     return "Missing IP address";
47   uns x = 0;
48   if (**p == '0' && *(*p + 1) | 32 == 'X')
49     {
50       errno = 0;
51       x = strtoul(*p + 2, (char **)p, 16);
52       if (errno == ERANGE || x > 0xffffffff)
53         goto error;
54     }
55   else
56     for (uns i = 0; i < 4; i++)
57       {
58         if (i)
59           {
60             while (Cspace(**p))
61               (*p)++;
62             if (*(*p)++ != '.')
63               goto error;
64           }
65         while (Cspace(**p))
66           (*p)++;
67         errno = 0;
68         uns y = strtoul(*p, (char **)p, 10);
69         if (errno == ERANGE || y > 255)
70           goto error;
71         x = (x << 8) + y;
72       }
73   *varp = x;
74   return NULL;
75 error:
76   return "Invalid IP address";
77 }
78
79 byte *
80 ipaccess_parse(struct ipaccess_list *l, byte *c, int is_allow)
81 {
82   byte *p = strchr(c, '/');
83   char *q;
84   struct ipaccess_entry *a = cfg_malloc(sizeof(struct ipaccess_entry));
85   unsigned long pxlen;
86
87   a->allow = is_allow;
88   a->mask = ~0U;
89   if (p)
90     {
91       *p++ = 0;
92       pxlen = strtoul(p, &q, 10);
93       if ((!q || !*q) && pxlen <= 32)
94         {
95           if (pxlen != 32)
96             a->mask = ~(~0U >> (uns) pxlen);
97         }
98       else if (q = parse_ip(&p, &a->mask))
99         return q;
100     }
101   add_tail(&l->l, &a->n);
102   return parse_ip(&c, &a->addr);
103 }
104
105 int
106 ipaccess_check(struct ipaccess_list *l, u32 ip)
107 {
108   struct ipaccess_entry *a;
109
110   DO_FOR_ALL(a, l->l)
111     if (! ((ip ^ a->addr) & a->mask))
112       return a->allow;
113   return 0;
114 }