]> jfr.im git - irc/quakenet/newserv.git/blob - geoip/geoip.c
Sigh
[irc/quakenet/newserv.git] / geoip / geoip.c
1 /*
2 Geoip module
3 Copyright (C) 2004-2006 Chris Porter.
4 */
5
6 #include "../nick/nick.h"
7 #include "../core/error.h"
8 #include "../core/config.h"
9 #include "../core/hooks.h"
10 #include "../control/control.h"
11 #include "../lib/version.h"
12
13 #include "libGeoIP/GeoIP.h"
14 #include "geoip.h"
15
16 MODULE_VERSION("$Id: geoip.c 663 2006-05-16 17:27:36Z newserv $")
17
18 int geoip_totals[COUNTRY_MAX + 1];
19 int geoip_nickext = -1;
20 GeoIP *gi = NULL;
21
22 void geoip_setupuser(nick *np);
23
24 void geoip_new_nick(int hook, void *args);
25 void geoip_quit(int hook, void *args);
26 void geoip_whois_handler(int hooknum, void *arg);
27
28 void _init(void) {
29 int i;
30 nick *np;
31 sstring *filename;
32
33 filename = getcopyconfigitem("geoip", "db", "GeoIP.dat", 256);
34 gi = GeoIP_new(GEOIP_MEMORY_CACHE, filename->content);
35 freesstring(filename);
36
37 if(!gi)
38 return;
39
40 geoip_nickext = registernickext("geoip");
41 if(geoip_nickext == -1)
42 return; /* PPA: registerchanext produces an error, however the module should stop loading */
43
44 memset(geoip_totals, 0, sizeof(geoip_totals));
45
46 for(i=0;i<NICKHASHSIZE;i++)
47 for(np=nicktable[i];np;np=np->next)
48 geoip_setupuser(np);
49
50 registerhook(HOOK_NICK_LOSTNICK, &geoip_quit);
51 registerhook(HOOK_NICK_NEWNICK, &geoip_new_nick);
52 registerhook(HOOK_CONTROL_WHOISREQUEST, &geoip_whois_handler);
53 }
54
55 void _fini(void) {
56 if(gi)
57 GeoIP_delete(gi);
58
59 if(geoip_nickext == -1)
60 return;
61
62 releasenickext(geoip_nickext);
63
64 deregisterhook(HOOK_NICK_NEWNICK, &geoip_new_nick);
65 deregisterhook(HOOK_NICK_LOSTNICK, &geoip_quit);
66 deregisterhook(HOOK_CONTROL_WHOISREQUEST, &geoip_whois_handler);
67 }
68
69 void geoip_setupuser(nick *np) {
70 int country = GeoIP_id_by_ipnum(gi, np->ipaddress);
71 if((country < COUNTRY_MIN) || (country > COUNTRY_MAX))
72 return;
73
74 geoip_totals[country]++;
75 np->exts[geoip_nickext] = (void *)(long)country;
76 }
77
78 void geoip_new_nick(int hook, void *args) {
79 geoip_setupuser((nick *)args);
80 }
81
82 void geoip_quit(int hook, void *args) {
83 int item;
84 nick *np = (nick *)args;
85
86 item = (int)((long)np->exts[geoip_nickext]);
87
88 if((item < COUNTRY_MIN) || (item > COUNTRY_MAX))
89 return;
90
91 geoip_totals[item]--;
92 }
93
94 void geoip_whois_handler(int hooknum, void *arg) {
95 int item;
96 char message[512], *longcountry, *shortcountry, *shortcountry3;
97 nick *np = (nick *)arg;
98
99 if(!np)
100 return;
101
102 item = (int)((long)np->exts[geoip_nickext]);
103 if((item < COUNTRY_MIN) || (item > COUNTRY_MAX))
104 return;
105
106 if(GeoIP_country_info_by_id(item, &shortcountry, &shortcountry3, &longcountry)) {
107 snprintf(message, sizeof(message), "Country : %s (%s)", shortcountry, longcountry);
108 triggerhook(HOOK_CONTROL_WHOISREPLY, message);
109 }
110 }
111