summaryrefslogtreecommitdiff
path: root/src/modules/extra/m_geo_maxmind.cpp
blob: 0cf082775b911a7283bd5fee4a6c86e622540946 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/*
 * InspIRCd -- Internet Relay Chat Daemon
 *
 *   Copyright (C) 2019 Sadie Powell <sadie@witchery.services>
 *   Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
 *
 * This file is part of InspIRCd.  InspIRCd is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, version 2.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/// $CompilerFlags: find_compiler_flags("libmaxminddb" "")
/// $LinkerFlags: find_linker_flags("libmaxminddb" "-lmaxminddb")

/// $PackageInfo: require_system("arch") libmaxminddb pkgconf
/// $PackageInfo: require_system("darwin") libmaxminddb pkg-config
/// $PackageInfo: require_system("debian" "9.0") libmaxminddb-dev pkg-config
/// $PackageInfo: require_system("ubuntu" "16.04") libmaxminddb-dev pkg-config

#ifdef _WIN32
# pragma comment(lib, "libmaxminddb.lib")
#endif

#include "inspircd.h"
#include "modules/geolocation.h"
#include <maxminddb.h>

class GeolocationExtItem : public ExtensionItem
{
 public:
	GeolocationExtItem(Module* parent)
		: ExtensionItem("geolocation", ExtensionItem::EXT_USER, parent)
	{
	}

	void free(Extensible* container, void* item) CXX11_OVERRIDE
	{
		Geolocation::Location* old = static_cast<Geolocation::Location*>(item);
		if (old)
			old->refcount_dec();
	}

	Geolocation::Location* get(const Extensible* item) const
	{
		return static_cast<Geolocation::Location*>(get_raw(item));
	}

	void set(Extensible* item, Geolocation::Location* value)
	{
		value->refcount_inc();
		free(item, set_raw(item, value));
	}

	void unset(Extensible* container)
	{
		free(container, unset_raw(container));
	}
};

typedef insp::flat_map<std::string, Geolocation::Location*> LocationMap;

class GeolocationAPIImpl : public Geolocation::APIBase
{
 public:
	GeolocationExtItem ext;
	LocationMap locations;
	MMDB_s mmdb;

	GeolocationAPIImpl(Module* parent)
		: Geolocation::APIBase(parent)
		, ext(parent)
	{
	}

	Geolocation::Location* GetLocation(User* user) CXX11_OVERRIDE
	{
		// If we have the location cached then use that instead.
		Geolocation::Location* location = ext.get(user);
		if (location)
			return location;

		// Attempt to locate this user.
		location = GetLocation(user->client_sa);
		if (!location)
			return NULL;

		// We found the user. Cache their location for future use.
		ext.set(user, location);
		return location;
	}

	Geolocation::Location* GetLocation(irc::sockets::sockaddrs& sa) CXX11_OVERRIDE
	{
		// Skip trying to look up a UNIX socket.
		if (sa.family() != AF_INET && sa.family() != AF_INET6)
			return NULL;

		// Attempt to look up the socket address.
		int result;
		MMDB_lookup_result_s lookup = MMDB_lookup_sockaddr(&mmdb, &sa.sa, &result);
		if (result != MMDB_SUCCESS || !lookup.found_entry)
			return NULL;

		// Attempt to retrieve the country code.
		MMDB_entry_data_s country_code;
		result = MMDB_get_value(&lookup.entry, &country_code, "country", "iso_code", NULL);
		if (result != MMDB_SUCCESS || !country_code.has_data || country_code.type != MMDB_DATA_TYPE_UTF8_STRING || country_code.data_size != 2)
			return NULL;

		// If the country has been seen before then use our cached Location object.
		const std::string code(country_code.utf8_string, country_code.data_size);
		LocationMap::iterator liter = locations.find(code);
		if (liter != locations.end())
			return liter->second;

		// Attempt to retrieve the country name.
		MMDB_entry_data_s country_name;
		result = MMDB_get_value(&lookup.entry, &country_name, "country", "names", "en", NULL);
		if (result != MMDB_SUCCESS || !country_name.has_data || country_name.type != MMDB_DATA_TYPE_UTF8_STRING)
			return NULL;

		// Create a Location object and cache it.
		const std::string cname(country_name.utf8_string, country_name.data_size);
		Geolocation::Location* location = new Geolocation::Location(code, cname);
		locations[code] = location;
		return location;
	}
};

class ModuleGeoMaxMind : public Module
{
 private:
	GeolocationAPIImpl geoapi;

 public:
	ModuleGeoMaxMind()
		: geoapi(this)
	{
		memset(&geoapi.mmdb, 0, sizeof(geoapi.mmdb));
	}

	~ModuleGeoMaxMind()
	{
		MMDB_close(&geoapi.mmdb);
	}

	Version GetVersion() CXX11_OVERRIDE
	{
		return Version("Provides Geolocation lookups using the libMaxMindDB library", VF_VENDOR);
	}

	void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
	{
		ConfigTag* tag = ServerInstance->Config->ConfValue("maxmind");
		const std::string file = ServerInstance->Config->Paths.PrependConfig(tag->getString("file", "GeoLite2-Country.mmdb"));

		// Try to read the new database.
		MMDB_s mmdb;
		int result = MMDB_open(file.c_str(), MMDB_MODE_MMAP, &mmdb);
		if (result != MMDB_SUCCESS)
			throw ModuleException(InspIRCd::Format("Unable to load the MaxMind database (%s): %s",
				file.c_str(), MMDB_strerror(result)));

		// Swap the new database with the old database.
		std::swap(mmdb, geoapi.mmdb);

		// Free the old database.
		MMDB_close(&mmdb);
	}

	void OnGarbageCollect() CXX11_OVERRIDE
	{
		for (LocationMap::iterator iter = geoapi.locations.begin(); iter != geoapi.locations.end(); )
		{
			Geolocation::Location* location = iter->second;
			if (location->GetUseCount())
			{
				ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Preserving geolocation data for %s (%s) with use count %u... ",
					location->GetName().c_str(), location->GetCode().c_str(), location->GetUseCount());
				iter++;
			}
			else
			{
				ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Deleting unused geolocation data for %s (%s)",
					location->GetName().c_str(), location->GetCode().c_str());
				delete location;
				iter = geoapi.locations.erase(iter);
			}
		}
	}

	void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
	{
		// Unset the extension so that the location of this user is looked
		// up again next time it is requested.
		geoapi.ext.unset(user);
	}
};

MODULE_INIT(ModuleGeoMaxMind)