2 * UCW Library -- IP address access lists
4 * (c) 1997--2006 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include "lib/clists.h"
13 #include "lib/getopt.h"
14 #include "lib/fastbuf.h"
15 #include "lib/ipaccess.h"
24 struct ipaccess_entry {
31 addrmask_parser(byte *c, void *ptr)
34 * This is tricky: addrmasks will be compared by memcmp(), so we must ensure
35 * that even the padding between structure members is zeroed out.
37 struct addrmask *am = ptr;
38 bzero(am, sizeof(*am));
40 byte *p = strchr(c, '/');
43 byte *err = cf_parse_ip(c, &am->addr);
49 if (!cf_parse_int(p, &len) && len <= 32)
50 am->mask = ~(len == 32 ? 0 : ~0U >> len);
51 else if (cf_parse_ip(p, &am->mask))
52 return "Invalid prefix length or netmask";
60 addrmask_dumper(struct fastbuf *fb, void *ptr)
62 struct addrmask *am = ptr;
63 bprintf(fb, "%08x/%08x ", am->addr, am->mask);
66 static struct cf_user_type addrmask_type = {
67 .size = sizeof(struct addrmask),
69 .parser = addrmask_parser,
70 .dumper = addrmask_dumper
73 struct cf_section ipaccess_cf = {
74 CF_TYPE(struct ipaccess_entry),
76 CF_LOOKUP("Mode", PTR_TO(struct ipaccess_entry, allow), ((byte*[]) { "deny", "allow", NULL })),
77 CF_USER("IP", PTR_TO(struct ipaccess_entry, addr), &addrmask_type),
83 ipaccess_check(clist *l, u32 ip)
85 CLIST_FOR_EACH(struct ipaccess_entry *, a, *l)
86 if (! ((ip ^ a->addr.addr) & a->addr.mask))
97 static struct cf_section test_cf = {
99 CF_LIST("A", &t, &ipaccess_cf),
104 int main(int argc, char **argv)
106 cf_declare_section("T", &test_cf, 0);
107 if (cf_getopt(argc, argv, CF_SHORT_OPTS, CF_NO_LONG_OPTS, NULL) != -1)
108 die("Invalid arguments");
111 while (fgets(buf, sizeof(buf), stdin))
113 byte *c = strchr(buf, '\n');
117 if (cf_parse_ip(buf, &ip))
118 puts("Invalid IP address");
119 else if (ipaccess_check(&t, ip))