2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2005-2009 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2004-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8 * Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "modules/stats.h"
28 /** An XLineFactory specialized to generate GLine* pointers
30 class GLineFactory : public XLineFactory
33 GLineFactory() : XLineFactory("G") { }
37 XLine* Generate(time_t set_time, unsigned long duration, const std::string& source, const std::string& reason, const std::string& xline_specific_mask) CXX11_OVERRIDE
39 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
40 return new GLine(set_time, duration, source, reason, ih.first, ih.second);
44 /** An XLineFactory specialized to generate ELine* pointers
46 class ELineFactory : public XLineFactory
49 ELineFactory() : XLineFactory("E") { }
53 XLine* Generate(time_t set_time, unsigned long duration, const std::string& source, const std::string& reason, const std::string& xline_specific_mask) CXX11_OVERRIDE
55 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
56 return new ELine(set_time, duration, source, reason, ih.first, ih.second);
60 /** An XLineFactory specialized to generate KLine* pointers
62 class KLineFactory : public XLineFactory
65 KLineFactory() : XLineFactory("K") { }
69 XLine* Generate(time_t set_time, unsigned long duration, const std::string& source, const std::string& reason, const std::string& xline_specific_mask) CXX11_OVERRIDE
71 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
72 return new KLine(set_time, duration, source, reason, ih.first, ih.second);
76 /** An XLineFactory specialized to generate QLine* pointers
78 class QLineFactory : public XLineFactory
81 QLineFactory() : XLineFactory("Q") { }
85 XLine* Generate(time_t set_time, unsigned long duration, const std::string& source, const std::string& reason, const std::string& xline_specific_mask) CXX11_OVERRIDE
87 return new QLine(set_time, duration, source, reason, xline_specific_mask);
91 /** An XLineFactory specialized to generate ZLine* pointers
93 class ZLineFactory : public XLineFactory
96 ZLineFactory() : XLineFactory("Z") { }
100 XLine* Generate(time_t set_time, unsigned long duration, const std::string& source, const std::string& reason, const std::string& xline_specific_mask) CXX11_OVERRIDE
102 return new ZLine(set_time, duration, source, reason, xline_specific_mask);
108 * This is now version 3 of the XLine subsystem, let's see if we can get it as nice and
109 * efficient as we can this time so we can close this file and never ever touch it again ..
112 * Version 1 stored all line types in one list (one for g, one for z, etc). This was fine,
113 * but both version 1 and 2 suck at applying lines efficiently. That is, every time a new line
114 * was added, it iterated every existing line for every existing user. Ow. Expiry was also
115 * expensive, as the lists were NOT sorted.
117 * Version 2 moved permanent lines into a seperate list from non-permanent to help optimize
118 * matching speed, but matched in the same way.
119 * Expiry was also sped up by sorting the list by expiry (meaning just remove the items at the
120 * head of the list that are outdated.)
122 * This was fine and good, but it looked less than ideal in code, and matching was still slower
123 * than it could have been, something which we address here.
126 * All lines are (as in v1) stored together -- no seperation of perm and non-perm. They are stored in
127 * a map of maps (first map is line type, second map is for quick lookup on add/delete/etc).
129 * Expiry is *no longer* performed on a timer, and no longer uses a sorted list of any variety. This
130 * is now done by only checking for expiry when a line is accessed, meaning that expiry is no longer
131 * a resource intensive problem.
133 * Application no longer tries to apply every single line on every single user - instead, now only lines
134 * added since the previous application are applied. This keeps S2S ADDLINE during burst nice and fast,
135 * while at the same time not slowing things the fuck down when we try adding a ban with lots of preexisting
139 bool XLine::Matches(User *u)
145 * Checks what users match a given vector of ELines and sets their ban exempt flag accordingly.
147 void XLineManager::CheckELines()
149 ContainerIter n = lookup_lines.find("E");
151 if (n == lookup_lines.end())
154 XLineLookup& ELines = n->second;
159 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
160 for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
165 /* This uses safe iteration to ensure that if a line expires here, it doenst trash the iterator */
168 for (LookupIter i = ELines.begin(); i != ELines.end(); )
173 XLine *e = i->second;
174 if ((!e->duration || ServerInstance->Time() < e->expiry) && e->Matches(u))
183 XLineLookup* XLineManager::GetAll(const std::string &type)
185 ContainerIter n = lookup_lines.find(type);
187 if (n == lookup_lines.end())
191 const time_t current = ServerInstance->Time();
193 /* Expire any dead ones, before sending */
194 for (LookupIter x = n->second.begin(); x != n->second.end(); )
198 if (x->second->duration && current > x->second->expiry)
208 void XLineManager::DelAll(const std::string &type)
210 ContainerIter n = lookup_lines.find(type);
212 if (n == lookup_lines.end())
217 /* Delete all of a given type (this should probably use DelLine, but oh well) */
218 while ((x = n->second.begin()) != n->second.end())
224 std::vector<std::string> XLineManager::GetAllTypes()
226 std::vector<std::string> items;
227 for (ContainerIter x = lookup_lines.begin(); x != lookup_lines.end(); ++x)
228 items.push_back(x->first);
232 IdentHostPair XLineManager::IdentSplit(const std::string &ident_and_host)
234 IdentHostPair n = std::make_pair<std::string,std::string>("*","*");
235 std::string::size_type x = ident_and_host.find('@');
236 if (x != std::string::npos)
238 n.second = ident_and_host.substr(x + 1,ident_and_host.length());
239 n.first = ident_and_host.substr(0, x);
240 if (!n.first.length())
242 if (!n.second.length())
243 n.second.assign("*");
248 n.second = ident_and_host;
256 bool XLineManager::AddLine(XLine* line, User* user)
258 if (line->duration && ServerInstance->Time() > line->expiry)
259 return false; // Don't apply expired XLines.
261 /* Don't apply duplicate xlines */
262 ContainerIter x = lookup_lines.find(line->type);
263 if (x != lookup_lines.end())
265 LookupIter i = x->second.find(line->Displayable());
266 if (i != x->second.end())
270 // Allow replacing a config line for an updated config line.
271 if (i->second->from_config && line->from_config)
273 // Nothing changed, skip adding this one.
274 if (i->second->reason == line->reason)
279 // Allow replacing a non-config line for a new config line.
280 else if (!line->from_config)
282 // X-line propagation bug was here, if the line to be added already exists and
283 // it's expired then expire it and add the new one instead of returning false
284 if ((!i->second->duration) || (ServerInstance->Time() < i->second->expiry))
292 ExpireLine(x, i, silent);
296 /*ELine* item = new ELine(ServerInstance->Time(), duration, source, reason, ih.first.c_str(), ih.second.c_str());*/
297 XLineFactory* xlf = GetFactory(line->type);
301 ServerInstance->BanCache.RemoveEntries(line->type, false); // XXX perhaps remove ELines here?
303 if (xlf->AutoApplyToUserList(line))
304 pending_lines.push_back(line);
306 lookup_lines[line->type][line->Displayable()] = line;
309 FOREACH_MOD(OnAddLine, (user, line));
314 // deletes a line, returns true if the line existed and was removed
316 bool XLineManager::DelLine(const char* hostmask, const std::string& type, std::string& reason, User* user, bool simulate)
318 ContainerIter x = lookup_lines.find(type);
320 if (x == lookup_lines.end())
323 LookupIter y = x->second.find(hostmask);
325 if (y == x->second.end())
328 reason.assign(y->second->reason);
333 ServerInstance->BanCache.RemoveEntries(y->second->type, true);
335 FOREACH_MOD(OnDelLine, (user, y->second));
339 stdalgo::erase(pending_lines, y->second);
350 ServerInstance->XLines->CheckELines();
353 // returns a pointer to the reason if a nickname matches a Q-line, NULL if it didn't match
355 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
357 ContainerIter x = lookup_lines.find(type);
359 if (x == lookup_lines.end())
362 const time_t current = ServerInstance->Time();
366 for (LookupIter i = x->second.begin(); i != x->second.end(); )
371 if (i->second->duration && current > i->second->expiry)
373 /* Expire the line, proceed to next one */
379 if (i->second->Matches(user))
389 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
391 ContainerIter x = lookup_lines.find(type);
393 if (x == lookup_lines.end())
396 const time_t current = ServerInstance->Time();
400 for (LookupIter i = x->second.begin(); i != x->second.end(); )
405 if (i->second->Matches(pattern))
407 if (i->second->duration && current > i->second->expiry)
409 /* Expire the line, return nothing */
424 // removes lines that have expired
425 void XLineManager::ExpireLine(ContainerIter container, LookupIter item, bool silent)
427 FOREACH_MOD(OnExpireLine, (item->second));
430 item->second->DisplayExpiry();
432 item->second->Unset();
434 /* TODO: Can we skip this loop by having a 'pending' field in the XLine class, which is set when a line
435 * is pending, cleared when it is no longer pending, so we skip over this loop if its not pending?
438 stdalgo::erase(pending_lines, item->second);
441 container->second.erase(item);
445 // applies lines, removing clients and changing nicks etc as applicable
446 void XLineManager::ApplyLines()
448 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
449 for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); ++j)
453 // Don't ban people who are exempt.
457 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
465 pending_lines.clear();
468 void XLineManager::InvokeStats(const std::string& type, unsigned int numeric, Stats::Context& stats)
470 ContainerIter n = lookup_lines.find(type);
472 time_t current = ServerInstance->Time();
476 if (n != lookup_lines.end())
478 XLineLookup& list = n->second;
479 for (LookupIter i = list.begin(); i != list.end(); )
484 if (i->second->duration && current > i->second->expiry)
489 stats.AddRow(numeric, i->second->Displayable()+" "+
490 ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+i->second->source+" :"+i->second->reason);
497 XLineManager::XLineManager()
506 GFact = new GLineFactory;
507 EFact = new ELineFactory;
508 KFact = new KLineFactory;
509 QFact = new QLineFactory;
510 ZFact = new ZLineFactory;
512 RegisterFactory(GFact);
513 RegisterFactory(EFact);
514 RegisterFactory(KFact);
515 RegisterFactory(QFact);
516 RegisterFactory(ZFact);
519 XLineManager::~XLineManager()
521 const char gekqz[] = "GEKQZ";
522 for(unsigned int i=0; i < sizeof(gekqz); i++)
524 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
528 // Delete all existing XLines
529 for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
531 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
538 void XLine::Apply(User* u)
542 bool XLine::IsBurstable()
547 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
549 const std::string banReason = line + "-lined: " + reason;
551 if (!ServerInstance->Config->XLineMessage.empty())
552 u->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
554 if (ServerInstance->Config->HideBans)
555 ServerInstance->Users->QuitUser(u, line + "-lined", &banReason);
557 ServerInstance->Users->QuitUser(u, banReason);
562 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
563 ServerInstance->BanCache.AddHit(u->GetIPString(), this->type, banReason, (this->duration > 0 ? (this->expiry - ServerInstance->Time()) : 0));
567 bool KLine::Matches(User *u)
569 LocalUser* lu = IS_LOCAL(u);
570 if (lu && lu->exempt)
573 if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
575 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
576 InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
585 void KLine::Apply(User* u)
587 DefaultApply(u, "K", (this->identmask == "*") ? true : false);
590 bool GLine::Matches(User *u)
592 LocalUser* lu = IS_LOCAL(u);
593 if (lu && lu->exempt)
596 if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
598 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
599 InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
608 void GLine::Apply(User* u)
610 DefaultApply(u, "G", (this->identmask == "*") ? true : false);
613 bool ELine::Matches(User *u)
615 if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
617 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
618 InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
627 bool ZLine::Matches(User *u)
629 LocalUser* lu = IS_LOCAL(u);
630 if (lu && lu->exempt)
633 if (InspIRCd::MatchCIDR(u->GetIPString(), this->ipaddr))
639 void ZLine::Apply(User* u)
641 DefaultApply(u, "Z", true);
645 bool QLine::Matches(User *u)
647 if (InspIRCd::Match(u->nick, this->nick))
653 void QLine::Apply(User* u)
655 /* Force to uuid on apply of Q-line, no need to disconnect anymore :) */
656 u->ChangeNick(u->uuid);
660 bool ZLine::Matches(const std::string &str)
662 if (InspIRCd::MatchCIDR(str, this->ipaddr))
668 bool QLine::Matches(const std::string &str)
670 if (InspIRCd::Match(str, this->nick))
676 bool ELine::Matches(const std::string &str)
678 return (InspIRCd::MatchCIDR(str, matchtext));
681 bool KLine::Matches(const std::string &str)
683 return (InspIRCd::MatchCIDR(str.c_str(), matchtext));
686 bool GLine::Matches(const std::string &str)
688 return (InspIRCd::MatchCIDR(str, matchtext));
693 /* When adding one E-line, only check the one E-line */
694 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
695 for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
698 if (this->Matches(u))
703 void XLine::DisplayExpiry()
705 bool onechar = (type.length() == 1);
706 ServerInstance->SNO->WriteToSnoMask('x', "Removing expired %s%s %s (set by %s %s ago): %s",
707 type.c_str(), (onechar ? "-line" : ""), Displayable().c_str(), source.c_str(), InspIRCd::DurationString(ServerInstance->Time() - set_time).c_str(), reason.c_str());
710 const std::string& ELine::Displayable()
715 const std::string& KLine::Displayable()
720 const std::string& GLine::Displayable()
725 const std::string& ZLine::Displayable()
730 const std::string& QLine::Displayable()
735 bool KLine::IsBurstable()
740 bool XLineManager::RegisterFactory(XLineFactory* xlf)
742 XLineFactMap::iterator n = line_factory.find(xlf->GetType());
744 if (n != line_factory.end())
747 line_factory[xlf->GetType()] = xlf;
752 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
754 XLineFactMap::iterator n = line_factory.find(xlf->GetType());
756 if (n == line_factory.end())
759 line_factory.erase(n);
764 XLineFactory* XLineManager::GetFactory(const std::string &type)
766 XLineFactMap::iterator n = line_factory.find(type);
768 if (n == line_factory.end())
774 void XLineManager::ExpireRemovedConfigLines(const std::string& type, const insp::flat_set<std::string>& configlines)
777 if (lookup_lines.empty())
780 ContainerIter xlines = lookup_lines.find(type);
781 if (xlines == lookup_lines.end())
784 for (LookupIter xline = xlines->second.begin(); xline != xlines->second.end(); )
786 LookupIter cachedxline = xline++;
787 if (!cachedxline->second->from_config)
790 if (!configlines.count(cachedxline->second->Displayable()))
791 ExpireLine(xlines, cachedxline);