]> jfr.im git - irc/quakenet/newserv.git/blob - newsearch/ns-cidr.c
LUA: port luadb to dbapi2 to drop postgres dependency
[irc/quakenet/newserv.git] / newsearch / ns-cidr.c
1 /*
2 * CIDR functionality
3 */
4
5 #include "newsearch.h"
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10
11 #include "../irc/irc_config.h"
12 #include "../lib/irc_string.h"
13 #include "../lib/irc_ipv6.h"
14
15 struct cidr_localdata {
16 struct irc_in_addr ip;
17 unsigned char bits;
18 };
19
20 void *cidr_exe(searchCtx *ctx, struct searchNode *thenode, void *theinput);
21 void cidr_free(searchCtx *ctx, struct searchNode *thenode);
22
23 struct searchNode *cidr_parse(searchCtx *ctx, int argc, char **argv) {
24 struct searchNode *thenode, *convsn;
25 struct cidr_localdata *c;
26 struct irc_in_addr ip;
27 unsigned char bits;
28 char *p;
29 int ret;
30
31 if(argc != 1) {
32 parseError = "usage: cidr ip/mask";
33 return NULL;
34 }
35
36 if (!(convsn=argtoconststr("cidr", ctx, argv[0], &p)))
37 return NULL;
38
39 ret = ipmask_parse(p, &ip, &bits);
40 convsn->free(ctx, convsn);
41
42 if(!ret) {
43 parseError = "usage: cidr ip/mask";
44 return NULL;
45 }
46
47 if (!(thenode=(struct searchNode *)malloc(sizeof (struct searchNode)))) {
48 parseError = "malloc: could not allocate memory for this search.";
49 return NULL;
50 }
51
52 thenode->returntype = RETURNTYPE_BOOL;
53 if (!(c = malloc(sizeof(struct cidr_localdata)))) {
54 /* couldn't malloc() memory for thenode->localdata, so free thenode to avoid leakage */
55 parseError = "malloc: could not allocate memory for this search.";
56 free(thenode);
57 return NULL;
58 }
59
60 memcpy(&c->ip, &ip, sizeof(struct irc_in_addr));
61 c->bits = bits;
62
63 thenode->localdata = (void *)c;
64 thenode->free = cidr_free;
65 thenode->exe = cidr_exe;
66
67 return thenode;
68 }
69
70 void *cidr_exe(searchCtx *ctx, struct searchNode *thenode, void *theinput) {
71 nick *np = (nick *)theinput;
72 struct cidr_localdata *c = thenode->localdata;
73
74 if(!ipmask_check(&np->ipaddress, &c->ip, c->bits))
75 return (void *)0;
76
77 return (void *)1;
78 }
79
80 void cidr_free(searchCtx *ctx, struct searchNode *thenode) {
81 free(thenode->localdata);
82 free(thenode);
83 }