2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019-2020 Sadie Powell <sadie@witchery.services>
5 * Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
7 * This file is part of InspIRCd. InspIRCd is free software: you can
8 * redistribute it and/or modify it under the terms of the GNU General Public
9 * License as published by the Free Software Foundation, version 2.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /// $CompilerFlags: require_version("libmaxminddb" "0" "1.2.1") warning("The version of libmaxminddb you are using may cause a segmentation fault if given a corrupt database file!")
21 /// $CompilerFlags: find_compiler_flags("libmaxminddb" "")
23 /// $LinkerFlags: find_linker_flags("libmaxminddb" "-lmaxminddb")
25 /// $PackageInfo: require_system("arch") libmaxminddb pkgconf
26 /// $PackageInfo: require_system("darwin") libmaxminddb pkg-config
27 /// $PackageInfo: require_system("debian" "9.0") libmaxminddb-dev pkg-config
28 /// $PackageInfo: require_system("ubuntu" "16.04") libmaxminddb-dev pkg-config
31 # pragma comment(lib, "libmaxminddb.lib")
35 #include "modules/geolocation.h"
36 #include <maxminddb.h>
38 class GeolocationExtItem : public ExtensionItem
41 GeolocationExtItem(Module* parent)
42 : ExtensionItem("geolocation", ExtensionItem::EXT_USER, parent)
46 void free(Extensible* container, void* item) CXX11_OVERRIDE
48 Geolocation::Location* old = static_cast<Geolocation::Location*>(item);
53 Geolocation::Location* get(const Extensible* item) const
55 return static_cast<Geolocation::Location*>(get_raw(item));
58 void set(Extensible* item, Geolocation::Location* value)
60 value->refcount_inc();
61 free(item, set_raw(item, value));
64 void unset(Extensible* container)
66 free(container, unset_raw(container));
70 typedef insp::flat_map<std::string, Geolocation::Location*> LocationMap;
72 class GeolocationAPIImpl : public Geolocation::APIBase
75 GeolocationExtItem ext;
76 LocationMap locations;
79 GeolocationAPIImpl(Module* parent)
80 : Geolocation::APIBase(parent)
85 Geolocation::Location* GetLocation(User* user) CXX11_OVERRIDE
87 // If we have the location cached then use that instead.
88 Geolocation::Location* location = ext.get(user);
92 // Attempt to locate this user.
93 location = GetLocation(user->client_sa);
97 // We found the user. Cache their location for future use.
98 ext.set(user, location);
102 Geolocation::Location* GetLocation(irc::sockets::sockaddrs& sa) CXX11_OVERRIDE
104 // Skip trying to look up a UNIX socket.
105 if (sa.family() != AF_INET && sa.family() != AF_INET6)
108 // Attempt to look up the socket address.
110 MMDB_lookup_result_s lookup = MMDB_lookup_sockaddr(&mmdb, &sa.sa, &result);
111 if (result != MMDB_SUCCESS || !lookup.found_entry)
114 // Attempt to retrieve the country code.
115 MMDB_entry_data_s country_code;
116 result = MMDB_get_value(&lookup.entry, &country_code, "country", "iso_code", NULL);
117 if (result != MMDB_SUCCESS || !country_code.has_data || country_code.type != MMDB_DATA_TYPE_UTF8_STRING || country_code.data_size != 2)
120 // If the country has been seen before then use our cached Location object.
121 const std::string code(country_code.utf8_string, country_code.data_size);
122 LocationMap::iterator liter = locations.find(code);
123 if (liter != locations.end())
124 return liter->second;
126 // Attempt to retrieve the country name.
127 MMDB_entry_data_s country_name;
128 result = MMDB_get_value(&lookup.entry, &country_name, "country", "names", "en", NULL);
129 if (result != MMDB_SUCCESS || !country_name.has_data || country_name.type != MMDB_DATA_TYPE_UTF8_STRING)
132 // Create a Location object and cache it.
133 const std::string cname(country_name.utf8_string, country_name.data_size);
134 Geolocation::Location* location = new Geolocation::Location(code, cname);
135 locations[code] = location;
140 class ModuleGeoMaxMind : public Module
143 GeolocationAPIImpl geoapi;
149 memset(&geoapi.mmdb, 0, sizeof(geoapi.mmdb));
154 MMDB_close(&geoapi.mmdb);
157 Version GetVersion() CXX11_OVERRIDE
159 return Version("Allows the server to perform geolocation lookups on both IP addresses and users.", VF_VENDOR);
162 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
164 ConfigTag* tag = ServerInstance->Config->ConfValue("maxmind");
165 const std::string file = ServerInstance->Config->Paths.PrependConfig(tag->getString("file", "GeoLite2-Country.mmdb", 1));
167 // Try to read the new database.
169 int result = MMDB_open(file.c_str(), MMDB_MODE_MMAP, &mmdb);
170 if (result != MMDB_SUCCESS)
171 throw ModuleException(InspIRCd::Format("Unable to load the MaxMind database (%s): %s",
172 file.c_str(), MMDB_strerror(result)));
174 // Swap the new database with the old database.
175 std::swap(mmdb, geoapi.mmdb);
177 // Free the old database.
181 void OnGarbageCollect() CXX11_OVERRIDE
183 for (LocationMap::iterator iter = geoapi.locations.begin(); iter != geoapi.locations.end(); )
185 Geolocation::Location* location = iter->second;
186 if (location->GetUseCount())
188 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Preserving geolocation data for %s (%s) with use count %u... ",
189 location->GetName().c_str(), location->GetCode().c_str(), location->GetUseCount());
194 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Deleting unused geolocation data for %s (%s)",
195 location->GetName().c_str(), location->GetCode().c_str());
197 iter = geoapi.locations.erase(iter);
202 void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
204 // Unset the extension so that the location of this user is looked
205 // up again next time it is requested.
206 geoapi.ext.unset(user);
210 MODULE_INIT(ModuleGeoMaxMind)