]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_geo_maxmind.cpp
Merge branch 'insp20' into insp3.
[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 <maxminddb.h>
31 #include "inspircd.h"
32 #include "modules/geolocation.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                 // Attempt to look up the socket address.
101                 int result;
102                 MMDB_lookup_result_s lookup = MMDB_lookup_sockaddr(&mmdb, &sa.sa, &result);
103                 if (result != MMDB_SUCCESS || !lookup.found_entry)
104                         return NULL;
105
106                 // Attempt to retrieve the country code.
107                 MMDB_entry_data_s country_code;
108                 result = MMDB_get_value(&lookup.entry, &country_code, "country", "iso_code", NULL);
109                 if (result != MMDB_SUCCESS || !country_code.has_data || country_code.type != MMDB_DATA_TYPE_UTF8_STRING || country_code.data_size != 2)
110                         return NULL;
111
112                 // If the country has been seen before then use our cached Location object.
113                 const std::string code(country_code.utf8_string, country_code.data_size);
114                 LocationMap::iterator liter = locations.find(code);
115                 if (liter != locations.end())
116                         return liter->second;
117
118                 // Attempt to retrieve the country name.
119                 MMDB_entry_data_s country_name;
120                 result = MMDB_get_value(&lookup.entry, &country_name, "country", "names", "en", NULL);
121                 if (result != MMDB_SUCCESS || !country_name.has_data || country_name.type != MMDB_DATA_TYPE_UTF8_STRING)
122                         return NULL;
123
124                 // Create a Location object and cache it.
125                 const std::string cname(country_name.utf8_string, country_name.data_size);
126                 Geolocation::Location* location = new Geolocation::Location(code, cname);
127                 locations[code] = location;
128                 return location;
129         }
130 };
131
132 class ModuleGeoMaxMind : public Module
133 {
134  private:
135         GeolocationAPIImpl geoapi;
136
137  public:
138         ModuleGeoMaxMind()
139                 : geoapi(this)
140         {
141                 memset(&geoapi.mmdb, 0, sizeof(geoapi.mmdb));
142         }
143
144         ~ModuleGeoMaxMind()
145         {
146                 MMDB_close(&geoapi.mmdb);
147         }
148
149         Version GetVersion() CXX11_OVERRIDE
150         {
151                 return Version("Provides Geolocation lookups using the libMaxMindDB library", VF_VENDOR);
152         }
153
154         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
155         {
156                 ConfigTag* tag = ServerInstance->Config->ConfValue("maxmind");
157                 const std::string file = ServerInstance->Config->Paths.PrependConfig(tag->getString("file", "GeoLite2-Country.mmdb"));
158
159                 // Try to read the new database.
160                 MMDB_s mmdb;
161                 int result = MMDB_open(file.c_str(), MMDB_MODE_MMAP, &mmdb);
162                 if (result != MMDB_SUCCESS)
163                         throw ModuleException(InspIRCd::Format("Unable to load the MaxMind database (%s): %s",
164                                 file.c_str(), MMDB_strerror(result)));
165
166                 // Swap the new database with the old database.
167                 std::swap(mmdb, geoapi.mmdb);
168
169                 // Free the old database.
170                 MMDB_close(&mmdb);
171         }
172
173         void OnGarbageCollect() CXX11_OVERRIDE
174         {
175                 for (LocationMap::iterator iter = geoapi.locations.begin(); iter != geoapi.locations.end(); )
176                 {       
177                         Geolocation::Location* location = iter->second;
178                         if (location->GetUseCount())
179                         {
180                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Preserving geolocation data for %s (%s) with use count %u... ",
181                                         location->GetName().c_str(), location->GetCode().c_str(), location->GetUseCount());
182                                 iter++;
183                         }
184                         else
185                         {
186                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Deleting unused geolocation data for %s (%s)",
187                                         location->GetName().c_str(), location->GetCode().c_str());
188                                 delete location;
189                                 iter = geoapi.locations.erase(iter);
190                         }
191                 }
192         }
193
194         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
195         {
196                 // Unset the extension so that the location of this user is looked
197                 // up again next time it is requested.
198                 geoapi.ext.unset(user);
199         }
200 };
201
202 MODULE_INIT(ModuleGeoMaxMind)