]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_geo_maxmind.cpp
6f84f31a3ffc95fe2d82f164f238352a1041092f
[user/henk/code/inspircd.git] / src / modules / extra / m_geo_maxmind.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Peter Powell <petpow@saberuk.com>
5  *
6  * This file is part of InspIRCd.  InspIRCd is free software: you can
7  * redistribute it and/or modify it under the terms of the GNU General Public
8  * License as published by the Free Software Foundation, version 2.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
13  * details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /// $CompilerFlags: find_compiler_flags("libmaxminddb" "")
20 /// $LinkerFlags: find_linker_flags("libmaxminddb" "-lmaxminddb")
21
22 /// $PackageInfo: require_system("darwin") libmaxminddb pkg-config
23 /// $PackageInfo: require_system("debian" "9.0") libmaxminddb-dev pkg-config
24 /// $PackageInfo: require_system("ubuntu" "16.04") libmaxminddb-dev pkg-config
25
26 #ifdef _WIN32
27 # pragma comment(lib, "libmaxminddb.lib")
28 #endif
29
30 #include "inspircd.h"
31 #include "modules/geolocation.h"
32 #include <maxminddb.h>
33
34 class GeolocationExtItem : public LocalExtItem
35 {
36  public:
37         GeolocationExtItem(Module* parent)
38                 : LocalExtItem("geolocation", ExtensionItem::EXT_USER, parent)
39         {
40         }
41
42         void free(Extensible* container, void* item) CXX11_OVERRIDE
43         {
44                 Geolocation::Location* old = static_cast<Geolocation::Location*>(item);
45                 if (old)
46                         old->refcount_dec();
47         }
48
49         Geolocation::Location* get(const Extensible* item) const
50         {
51                 return static_cast<Geolocation::Location*>(get_raw(item));
52         }
53
54         void set(Extensible* item, Geolocation::Location* value)
55         {
56                 value->refcount_inc();
57                 free(item, set_raw(item, value));
58         }
59
60         void unset(Extensible* container)
61         {
62                 free(container, unset_raw(container));
63         }
64 };
65
66 typedef insp::flat_map<std::string, Geolocation::Location*> LocationMap;
67
68 class GeolocationAPIImpl : public Geolocation::APIBase
69 {
70  public:
71         GeolocationExtItem ext;
72         LocationMap locations;
73         MMDB_s mmdb;
74
75         GeolocationAPIImpl(Module* parent)
76                 : Geolocation::APIBase(parent)
77                 , ext(parent)
78         {
79         }
80
81         Geolocation::Location* GetLocation(User* user) CXX11_OVERRIDE
82         {
83                 // If we have the location cached then use that instead.
84                 Geolocation::Location* location = ext.get(user);
85                 if (location)
86                         return location;
87
88                 // Attempt to locate this user.
89                 location = GetLocation(user->client_sa);
90                 if (!location)
91                         return NULL;
92
93                 // We found the user. Cache their location for future use.
94                 ext.set(user, location);
95                 return location;
96         }
97
98         Geolocation::Location* GetLocation(irc::sockets::sockaddrs& sa) CXX11_OVERRIDE
99         {
100                 // Skip trying to look up a UNIX socket.
101                 if (sa.family() != AF_INET && sa.family() != AF_INET6)
102                         return NULL;
103
104                 // Attempt to look up the socket address.
105                 int result;
106                 MMDB_lookup_result_s lookup = MMDB_lookup_sockaddr(&mmdb, &sa.sa, &result);
107                 if (result != MMDB_SUCCESS || !lookup.found_entry)
108                         return NULL;
109
110                 // Attempt to retrieve the country code.
111                 MMDB_entry_data_s country_code;
112                 result = MMDB_get_value(&lookup.entry, &country_code, "country", "iso_code", NULL);
113                 if (result != MMDB_SUCCESS || !country_code.has_data || country_code.type != MMDB_DATA_TYPE_UTF8_STRING || country_code.data_size != 2)
114                         return NULL;
115
116                 // If the country has been seen before then use our cached Location object.
117                 const std::string code(country_code.utf8_string, country_code.data_size);
118                 LocationMap::iterator liter = locations.find(code);
119                 if (liter != locations.end())
120                         return liter->second;
121
122                 // Attempt to retrieve the country name.
123                 MMDB_entry_data_s country_name;
124                 result = MMDB_get_value(&lookup.entry, &country_name, "country", "names", "en", NULL);
125                 if (result != MMDB_SUCCESS || !country_name.has_data || country_name.type != MMDB_DATA_TYPE_UTF8_STRING)
126                         return NULL;
127
128                 // Create a Location object and cache it.
129                 const std::string cname(country_name.utf8_string, country_name.data_size);
130                 Geolocation::Location* location = new Geolocation::Location(code, cname);
131                 locations[code] = location;
132                 return location;
133         }
134 };
135
136 class ModuleGeoMaxMind : public Module
137 {
138  private:
139         GeolocationAPIImpl geoapi;
140
141  public:
142         ModuleGeoMaxMind()
143                 : geoapi(this)
144         {
145                 memset(&geoapi.mmdb, 0, sizeof(geoapi.mmdb));
146         }
147
148         ~ModuleGeoMaxMind()
149         {
150                 MMDB_close(&geoapi.mmdb);
151         }
152
153         Version GetVersion() CXX11_OVERRIDE
154         {
155                 return Version("Provides Geolocation lookups using the libMaxMindDB library", VF_VENDOR);
156         }
157
158         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
159         {
160                 ConfigTag* tag = ServerInstance->Config->ConfValue("maxmind");
161                 const std::string file = ServerInstance->Config->Paths.PrependConfig(tag->getString("file", "GeoLite2-Country.mmdb"));
162
163                 // Try to read the new database.
164                 MMDB_s mmdb;
165                 int result = MMDB_open(file.c_str(), MMDB_MODE_MMAP, &mmdb);
166                 if (result != MMDB_SUCCESS)
167                         throw ModuleException(InspIRCd::Format("Unable to load the MaxMind database (%s): %s",
168                                 file.c_str(), MMDB_strerror(result)));
169
170                 // Swap the new database with the old database.
171                 std::swap(mmdb, geoapi.mmdb);
172
173                 // Free the old database.
174                 MMDB_close(&mmdb);
175         }
176
177         void OnGarbageCollect() CXX11_OVERRIDE
178         {
179                 for (LocationMap::iterator iter = geoapi.locations.begin(); iter != geoapi.locations.end(); )
180                 {       
181                         Geolocation::Location* location = iter->second;
182                         if (location->GetUseCount())
183                         {
184                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Preserving geolocation data for %s (%s) with use count %u... ",
185                                         location->GetName().c_str(), location->GetCode().c_str(), location->GetUseCount());
186                                 iter++;
187                         }
188                         else
189                         {
190                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Deleting unused geolocation data for %s (%s)",
191                                         location->GetName().c_str(), location->GetCode().c_str());
192                                 delete location;
193                                 iter = geoapi.locations.erase(iter);
194                         }
195                 }
196         }
197
198         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
199         {
200                 // Unset the extension so that the location of this user is looked
201                 // up again next time it is requested.
202                 geoapi.ext.unset(user);
203         }
204 };
205
206 MODULE_INIT(ModuleGeoMaxMind)