2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2013, 2017-2018, 2020 Sadie Powell <sadie@witchery.services>
5 * Copyright (C) 2012-2016 Attila Molnar <attilamolnar@hush.com>
6 * Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
7 * Copyright (C) 2010 Craig Edwards <brain@inspircd.org>
8 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
9 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
10 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
11 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13 * This file is part of InspIRCd. InspIRCd is free software: you can
14 * redistribute it and/or modify it under the terms of the GNU General Public
15 * License as published by the Free Software Foundation, version 2.
17 * This program is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include "modules/stats.h"
34 RPL_ENDOFWHOWAS = 369,
42 /** One entry for a nick. There may be multiple entries for a nick. */
46 const std::string host;
49 const std::string dhost;
52 const std::string ident;
55 const std::string server;
58 const std::string real;
63 /** Initialize this Entry with a user */
67 /** Everything known about one nick */
68 struct Nick : public insp::intrusive_list_node<Nick>
70 /** A group of users related by nickname */
71 typedef std::deque<Entry*> List;
73 /** Container where each element has information about one occurrence of this nick */
76 /** Time this nick was added to the database */
79 /** Nickname whose information is stored in this class */
80 const std::string nick;
82 /** Constructor to initialize fields */
83 Nick(const std::string& nickname);
85 /** Destructor, deallocates all elements in the entries container */
94 /** Number of currently existing WhoWas::Entry objects */
98 /** Add a user to the whowas database. Called when a user quits.
99 * @param user The user to add to the database
101 void Add(User* user);
103 /** Retrieves statistics about the whowas database
104 * @return Whowas statistics as a WhoWas::Manager::Stats struct
106 Stats GetStats() const;
108 /** Expires old entries */
111 /** Updates the current configuration which may result in the database being pruned if the
112 * new values are lower than the current ones.
113 * @param NewGroupSize Maximum number of nicks allowed in the database. In case there are this many nicks
114 * in the database and one more is added, the oldest one is removed (FIFO).
115 * @param NewMaxGroups Maximum number of entries per nick
116 * @param NewMaxKeep Seconds how long each nick should be kept
118 void UpdateConfig(unsigned int NewGroupSize, unsigned int NewMaxGroups, unsigned int NewMaxKeep);
120 /** Retrieves all data known about a given nick
121 * @param nick Nickname to find, case insensitive (IRC casemapping)
122 * @return A pointer to a WhoWas::Nick if the nick was found, NULL otherwise
124 const Nick* FindNick(const std::string& nick) const;
126 /** Returns true if WHOWAS is enabled according to the current configuration
127 * @return True if WHOWAS is enabled according to the configuration, false if WHOWAS is disabled
129 bool IsEnabled() const;
138 /** Order in which the users were added into the map, used to remove oldest nick */
139 typedef insp::intrusive_list_tail<Nick> FIFO;
141 /** Sets of users in the whowas system */
142 typedef TR1NS::unordered_map<std::string, WhoWas::Nick*, irc::insensitive, irc::StrHashComp> whowas_users;
144 /** Primary container, links nicknames tracked by WHOWAS to a list of records */
147 /** List of nicknames in the order they were inserted into the map */
150 /** Max number of WhoWas entries per user. */
151 unsigned int GroupSize;
153 /** Max number of cumulative user-entries in WhoWas.
154 * When max reached and added to, push out oldest entry FIFO style.
156 unsigned int MaxGroups;
158 /** Max seconds a user is kept in WhoWas before being pruned. */
159 unsigned int MaxKeep;
161 /** Shrink all data structures to honor the current settings */
164 /** Remove a nick (and all entries belonging to it) from the database
165 * @param it Iterator to the nick to purge
167 void PurgeNick(whowas_users::iterator it);
169 /** Remove a nick (and all entries belonging to it) from the database
170 * @param nick Nick to purge
172 void PurgeNick(WhoWas::Nick* nick);
176 class CommandWhowas : public Command
179 // Manager handling all whowas database related tasks
180 WhoWas::Manager manager;
182 CommandWhowas(Module* parent);
183 CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
186 CommandWhowas::CommandWhowas( Module* parent)
187 : Command(parent, "WHOWAS", 1)
193 CmdResult CommandWhowas::Handle(User* user, const Params& parameters)
195 /* if whowas disabled in config */
196 if (!manager.IsEnabled())
198 user->WriteNumeric(ERR_UNKNOWNCOMMAND, name, "This command has been disabled.");
202 const WhoWas::Nick* const nick = manager.FindNick(parameters[0]);
205 user->WriteNumeric(ERR_WASNOSUCHNICK, parameters[0], "There was no such nickname");
209 const WhoWas::Nick::List& list = nick->entries;
210 for (WhoWas::Nick::List::const_iterator i = list.begin(); i != list.end(); ++i)
212 WhoWas::Entry* u = *i;
214 user->WriteNumeric(RPL_WHOWASUSER, parameters[0], u->ident, u->dhost, '*', u->real);
216 if (user->HasPrivPermission("users/auspex"))
217 user->WriteNumeric(RPL_WHOWASIP, parameters[0], InspIRCd::Format("was connecting from *@%s", u->host.c_str()));
219 std::string signon = InspIRCd::TimeString(u->signon);
220 bool hide_server = (!ServerInstance->Config->HideServer.empty() && !user->HasPrivPermission("servers/auspex"));
221 user->WriteNumeric(RPL_WHOISSERVER, parameters[0], (hide_server ? ServerInstance->Config->HideServer : u->server), signon);
225 user->WriteNumeric(RPL_ENDOFWHOWAS, parameters[0], "End of WHOWAS");
229 WhoWas::Manager::Manager()
230 : GroupSize(0), MaxGroups(0), MaxKeep(0)
234 const WhoWas::Nick* WhoWas::Manager::FindNick(const std::string& nickname) const
236 whowas_users::const_iterator it = whowas.find(nickname);
237 if (it == whowas.end())
242 WhoWas::Manager::Stats WhoWas::Manager::GetStats() const
244 size_t entrycount = 0;
245 for (whowas_users::const_iterator i = whowas.begin(); i != whowas.end(); ++i)
247 WhoWas::Nick::List& list = i->second->entries;
248 entrycount += list.size();
252 stats.entrycount = entrycount;
256 void WhoWas::Manager::Add(User* user)
261 // Insert nick if it doesn't exist
262 // 'first' will point to the newly inserted element or to the existing element with an equivalent key
263 std::pair<whowas_users::iterator, bool> ret = whowas.insert(std::make_pair(user->nick, static_cast<WhoWas::Nick*>(NULL)));
265 if (ret.second) // If inserted
267 // This nick is new, create a list for it and add the first record to it
268 WhoWas::Nick* nick = new WhoWas::Nick(ret.first->first);
269 nick->entries.push_back(new Entry(user));
270 ret.first->second = nick;
272 // Add this nick to the fifo too
273 whowas_fifo.push_back(nick);
275 if (whowas.size() > this->MaxGroups)
277 // Too many nicks, remove the nick which was inserted the longest time ago from both the map and the fifo
278 PurgeNick(whowas_fifo.front());
283 // We've met this nick before, add a new record to the list
284 WhoWas::Nick::List& list = ret.first->second->entries;
285 list.push_back(new Entry(user));
287 // If there are too many records for this nick, remove the oldest (front)
288 if (list.size() > this->GroupSize)
296 /* on rehash, refactor maps according to new conf values */
297 void WhoWas::Manager::Prune()
299 time_t min = ServerInstance->Time() - this->MaxKeep;
301 /* first cut the list to new size (maxgroups) and also prune entries that are timed out. */
302 while (!whowas_fifo.empty())
304 WhoWas::Nick* nick = whowas_fifo.front();
305 if ((whowas_fifo.size() > this->MaxGroups) || (nick->addtime < min))
311 /* Then cut the whowas sets to new size (groupsize) */
312 for (whowas_users::iterator i = whowas.begin(); i != whowas.end(); )
314 WhoWas::Nick::List& list = i->second->entries;
315 while (list.size() > this->GroupSize)
328 /* call maintain once an hour to remove expired nicks */
329 void WhoWas::Manager::Maintain()
331 time_t min = ServerInstance->Time() - this->MaxKeep;
332 for (whowas_users::iterator i = whowas.begin(); i != whowas.end(); )
334 WhoWas::Nick::List& list = i->second->entries;
335 while (!list.empty() && list.front()->signon < min)
348 WhoWas::Manager::~Manager()
350 for (whowas_users::iterator i = whowas.begin(); i != whowas.end(); ++i)
352 WhoWas::Nick* nick = i->second;
357 bool WhoWas::Manager::IsEnabled() const
359 return ((GroupSize != 0) && (MaxGroups != 0));
362 void WhoWas::Manager::UpdateConfig(unsigned int NewGroupSize, unsigned int NewMaxGroups, unsigned int NewMaxKeep)
364 if ((NewGroupSize == GroupSize) && (NewMaxGroups == MaxGroups) && (NewMaxKeep == MaxKeep))
367 GroupSize = NewGroupSize;
368 MaxGroups = NewMaxGroups;
369 MaxKeep = NewMaxKeep;
373 void WhoWas::Manager::PurgeNick(whowas_users::iterator it)
375 WhoWas::Nick* nick = it->second;
376 whowas_fifo.erase(nick);
381 void WhoWas::Manager::PurgeNick(WhoWas::Nick* nick)
383 whowas_users::iterator it = whowas.find(nick->nick);
384 if (it == whowas.end())
386 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in whowas database, please report");
392 WhoWas::Entry::Entry(User* user)
393 : host(user->GetRealHost())
394 , dhost(user->GetDisplayedHost())
396 , server(user->server->GetName())
397 , real(user->GetRealName())
398 , signon(user->signon)
402 WhoWas::Nick::Nick(const std::string& nickname)
403 : addtime(ServerInstance->Time())
408 WhoWas::Nick::~Nick()
410 stdalgo::delete_all(entries);
413 class ModuleWhoWas : public Module, public Stats::EventListener
419 : Stats::EventListener(this)
424 void OnGarbageCollect() CXX11_OVERRIDE
426 // Remove all entries older than MaxKeep
427 cmd.manager.Maintain();
430 void OnUserQuit(User* user, const std::string& message, const std::string& oper_message) CXX11_OVERRIDE
432 cmd.manager.Add(user);
435 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE
437 if (stats.GetSymbol() == 'z')
438 stats.AddRow(249, "Whowas entries: "+ConvToStr(cmd.manager.GetStats().entrycount));
440 return MOD_RES_PASSTHRU;
443 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
445 ConfigTag* tag = ServerInstance->Config->ConfValue("whowas");
446 unsigned int NewGroupSize = tag->getUInt("groupsize", 10, 0, 10000);
447 unsigned int NewMaxGroups = tag->getUInt("maxgroups", 10240, 0, 1000000);
448 unsigned int NewMaxKeep = tag->getDuration("maxkeep", 3600, 3600);
450 cmd.manager.UpdateConfig(NewGroupSize, NewMaxGroups, NewMaxKeep);
453 Version GetVersion() CXX11_OVERRIDE
455 return Version("Provides the WHOWAS command", VF_CORE | VF_VENDOR);
459 MODULE_INIT(ModuleWhoWas)