2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
5 * Copyright (C) 2013, 2017-2020 Sadie Powell <sadie@witchery.services>
6 * Copyright (C) 2013 Adam <Adam@anope.org>
7 * Copyright (C) 2012-2014, 2016 Attila Molnar <attilamolnar@hush.com>
8 * Copyright (C) 2012, 2018-2019 Robby <robby@chatbelgie.be>
9 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
10 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
11 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
12 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13 * Copyright (C) 2006-2008, 2010 Craig Edwards <brain@inspircd.org>
15 * This file is part of InspIRCd. InspIRCd is free software: you can
16 * redistribute it and/or modify it under the terms of the GNU General Public
17 * License as published by the Free Software Foundation, version 2.
19 * This program is distributed in the hope that it will be useful, but WITHOUT
20 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 #include "modules/stats.h"
33 /** An XLineFactory specialized to generate GLine* pointers
35 class GLineFactory : public XLineFactory
38 GLineFactory() : XLineFactory("G") { }
42 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
44 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
45 return new GLine(set_time, duration, source, reason, ih.first, ih.second);
49 /** An XLineFactory specialized to generate ELine* pointers
51 class ELineFactory : public XLineFactory
54 ELineFactory() : XLineFactory("E") { }
58 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
60 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
61 return new ELine(set_time, duration, source, reason, ih.first, ih.second);
65 /** An XLineFactory specialized to generate KLine* pointers
67 class KLineFactory : public XLineFactory
70 KLineFactory() : XLineFactory("K") { }
74 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
76 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
77 return new KLine(set_time, duration, source, reason, ih.first, ih.second);
81 /** An XLineFactory specialized to generate QLine* pointers
83 class QLineFactory : public XLineFactory
86 QLineFactory() : XLineFactory("Q") { }
90 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
92 return new QLine(set_time, duration, source, reason, xline_specific_mask);
96 /** An XLineFactory specialized to generate ZLine* pointers
98 class ZLineFactory : public XLineFactory
101 ZLineFactory() : XLineFactory("Z") { }
105 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
107 return new ZLine(set_time, duration, source, reason, xline_specific_mask);
113 * This is now version 3 of the XLine subsystem, let's see if we can get it as nice and
114 * efficient as we can this time so we can close this file and never ever touch it again ..
117 * Version 1 stored all line types in one list (one for g, one for z, etc). This was fine,
118 * but both version 1 and 2 suck at applying lines efficiently. That is, every time a new line
119 * was added, it iterated every existing line for every existing user. Ow. Expiry was also
120 * expensive, as the lists were NOT sorted.
122 * Version 2 moved permanent lines into a separate list from non-permanent to help optimize
123 * matching speed, but matched in the same way.
124 * Expiry was also sped up by sorting the list by expiry (meaning just remove the items at the
125 * head of the list that are outdated.)
127 * This was fine and good, but it looked less than ideal in code, and matching was still slower
128 * than it could have been, something which we address here.
131 * All lines are (as in v1) stored together -- no separation of perm and non-perm. They are stored in
132 * a map of maps (first map is line type, second map is for quick lookup on add/delete/etc).
134 * Expiry is *no longer* performed on a timer, and no longer uses a sorted list of any variety. This
135 * is now done by only checking for expiry when a line is accessed, meaning that expiry is no longer
136 * a resource intensive problem.
138 * Application no longer tries to apply every single line on every single user - instead, now only lines
139 * added since the previous application are applied. This keeps S2S ADDLINE during burst nice and fast,
140 * while at the same time not slowing things the fuck down when we try adding a ban with lots of preexisting
144 bool XLine::Matches(User *u)
150 * Checks what users match a given vector of ELines and sets their ban exempt flag accordingly.
152 void XLineManager::CheckELines()
154 ContainerIter n = lookup_lines.find("E");
156 if (n == lookup_lines.end())
159 XLineLookup& ELines = n->second;
164 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
165 for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
170 /* This uses safe iteration to ensure that if a line expires here, it doenst trash the iterator */
173 for (LookupIter i = ELines.begin(); i != ELines.end(); )
178 XLine *e = i->second;
179 if ((!e->duration || ServerInstance->Time() < e->expiry) && e->Matches(u))
188 XLineLookup* XLineManager::GetAll(const std::string &type)
190 ContainerIter n = lookup_lines.find(type);
192 if (n == lookup_lines.end())
196 const time_t current = ServerInstance->Time();
198 /* Expire any dead ones, before sending */
199 for (LookupIter x = n->second.begin(); x != n->second.end(); )
203 if (x->second->duration && current > x->second->expiry)
213 void XLineManager::DelAll(const std::string &type)
215 ContainerIter n = lookup_lines.find(type);
217 if (n == lookup_lines.end())
222 /* Delete all of a given type (this should probably use DelLine, but oh well) */
223 while ((x = n->second.begin()) != n->second.end())
229 std::vector<std::string> XLineManager::GetAllTypes()
231 std::vector<std::string> items;
232 for (ContainerIter x = lookup_lines.begin(); x != lookup_lines.end(); ++x)
233 items.push_back(x->first);
237 IdentHostPair XLineManager::IdentSplit(const std::string &ident_and_host)
239 IdentHostPair n = std::make_pair<std::string,std::string>("*","*");
240 std::string::size_type x = ident_and_host.find('@');
241 if (x != std::string::npos)
243 n.second = ident_and_host.substr(x + 1,ident_and_host.length());
244 n.first = ident_and_host.substr(0, x);
245 if (!n.first.length())
247 if (!n.second.length())
248 n.second.assign("*");
253 n.second = ident_and_host;
261 bool XLineManager::AddLine(XLine* line, User* user)
263 if (line->duration && ServerInstance->Time() > line->expiry)
264 return false; // Don't apply expired XLines.
266 /* Don't apply duplicate xlines */
267 ContainerIter x = lookup_lines.find(line->type);
268 if (x != lookup_lines.end())
270 LookupIter i = x->second.find(line->Displayable());
271 if (i != x->second.end())
275 // Allow replacing a config line for an updated config line.
276 if (i->second->from_config && line->from_config)
278 // Nothing changed, skip adding this one.
279 if (i->second->reason == line->reason)
284 // Allow replacing a non-config line for a new config line.
285 else if (!line->from_config)
287 // X-line propagation bug was here, if the line to be added already exists and
288 // it's expired then expire it and add the new one instead of returning false
289 if ((!i->second->duration) || (ServerInstance->Time() < i->second->expiry))
297 ExpireLine(x, i, silent);
301 /*ELine* item = new ELine(ServerInstance->Time(), duration, source, reason, ih.first.c_str(), ih.second.c_str());*/
302 XLineFactory* xlf = GetFactory(line->type);
306 ServerInstance->BanCache.RemoveEntries(line->type, false); // XXX perhaps remove ELines here?
308 if (xlf->AutoApplyToUserList(line))
309 pending_lines.push_back(line);
311 lookup_lines[line->type][line->Displayable()] = line;
314 FOREACH_MOD(OnAddLine, (user, line));
319 // deletes a line, returns true if the line existed and was removed
321 bool XLineManager::DelLine(const char* hostmask, const std::string& type, std::string& reason, User* user, bool simulate)
323 ContainerIter x = lookup_lines.find(type);
325 if (x == lookup_lines.end())
328 LookupIter y = x->second.find(hostmask);
330 if (y == x->second.end())
333 reason.assign(y->second->reason);
338 ServerInstance->BanCache.RemoveEntries(y->second->type, true);
340 FOREACH_MOD(OnDelLine, (user, y->second));
344 stdalgo::erase(pending_lines, y->second);
355 ServerInstance->XLines->CheckELines();
358 // returns a pointer to the reason if a nickname matches a Q-line, NULL if it didn't match
360 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
362 ContainerIter x = lookup_lines.find(type);
364 if (x == lookup_lines.end())
367 const time_t current = ServerInstance->Time();
371 for (LookupIter i = x->second.begin(); i != x->second.end(); )
376 if (i->second->duration && current > i->second->expiry)
378 /* Expire the line, proceed to next one */
384 if (i->second->Matches(user))
394 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
396 ContainerIter x = lookup_lines.find(type);
398 if (x == lookup_lines.end())
401 const time_t current = ServerInstance->Time();
405 for (LookupIter i = x->second.begin(); i != x->second.end(); )
410 if (i->second->Matches(pattern))
412 if (i->second->duration && current > i->second->expiry)
414 /* Expire the line, return nothing */
429 // removes lines that have expired
430 void XLineManager::ExpireLine(ContainerIter container, LookupIter item, bool silent)
432 FOREACH_MOD(OnExpireLine, (item->second));
435 item->second->DisplayExpiry();
437 item->second->Unset();
439 /* TODO: Can we skip this loop by having a 'pending' field in the XLine class, which is set when a line
440 * is pending, cleared when it is no longer pending, so we skip over this loop if its not pending?
443 stdalgo::erase(pending_lines, item->second);
446 container->second.erase(item);
450 // applies lines, removing clients and changing nicks etc as applicable
451 void XLineManager::ApplyLines()
453 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
454 for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); )
458 // Don't ban people who are exempt.
462 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
469 // If applying the X-line has killed the user then don't
470 // apply any more lines to them.
477 pending_lines.clear();
480 void XLineManager::InvokeStats(const std::string& type, unsigned int numeric, Stats::Context& stats)
482 ContainerIter n = lookup_lines.find(type);
484 time_t current = ServerInstance->Time();
488 if (n != lookup_lines.end())
490 XLineLookup& list = n->second;
491 for (LookupIter i = list.begin(); i != list.end(); )
496 if (i->second->duration && current > i->second->expiry)
501 stats.AddRow(numeric, i->second->Displayable(), i->second->set_time, i->second->duration, i->second->source, i->second->reason);
507 bool XLineManager::InvokeStats(const std::string& type, Stats::Context& context)
509 ContainerIter citer = lookup_lines.find(type);
510 if (citer == lookup_lines.end())
513 for (LookupIter liter = citer->second.begin(); liter != citer->second.end(); )
515 // We might be about to expire the XLine so we have to increment the
516 // iterator early to avoid doing that causing iterator invalidation.
517 LookupIter current = liter++;
519 XLine* xline = current->second;
520 if (xline->duration && xline->expiry <= ServerInstance->Time())
522 // This XLine has expired so remove and skip it.
523 ExpireLine(citer, current);
527 context.AddRow(RPL_STATS, context.GetSymbol(), xline->Displayable(), xline->set_time, xline->duration, xline->source, xline->reason);
532 XLineManager::XLineManager()
541 GFact = new GLineFactory;
542 EFact = new ELineFactory;
543 KFact = new KLineFactory;
544 QFact = new QLineFactory;
545 ZFact = new ZLineFactory;
547 RegisterFactory(GFact);
548 RegisterFactory(EFact);
549 RegisterFactory(KFact);
550 RegisterFactory(QFact);
551 RegisterFactory(ZFact);
554 XLineManager::~XLineManager()
556 const char gekqz[] = "GEKQZ";
557 for(unsigned int i=0; i < sizeof(gekqz); i++)
559 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
563 // Delete all existing XLines
564 for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
566 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
573 void XLine::Apply(User* u)
577 bool XLine::IsBurstable()
582 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
584 const std::string banReason = line + "-lined: " + reason;
586 if (!ServerInstance->Config->XLineMessage.empty())
587 u->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
589 if (ServerInstance->Config->HideBans)
590 ServerInstance->Users->QuitUser(u, line + "-lined", &banReason);
592 ServerInstance->Users->QuitUser(u, banReason);
597 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
598 ServerInstance->BanCache.AddHit(u->GetIPString(), this->type, banReason, (this->duration > 0 ? (this->expiry - ServerInstance->Time()) : 0));
602 bool KLine::Matches(User *u)
604 LocalUser* lu = IS_LOCAL(u);
605 if (lu && lu->exempt)
608 if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
610 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
611 InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
620 void KLine::Apply(User* u)
622 DefaultApply(u, "K", (this->identmask == "*") ? true : false);
625 bool GLine::Matches(User *u)
627 LocalUser* lu = IS_LOCAL(u);
628 if (lu && lu->exempt)
631 if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
633 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
634 InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
643 void GLine::Apply(User* u)
645 DefaultApply(u, "G", (this->identmask == "*") ? true : false);
648 bool ELine::Matches(User *u)
650 if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
652 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
653 InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
662 bool ZLine::Matches(User *u)
664 LocalUser* lu = IS_LOCAL(u);
665 if (lu && lu->exempt)
668 if (InspIRCd::MatchCIDR(u->GetIPString(), this->ipaddr))
674 void ZLine::Apply(User* u)
676 DefaultApply(u, "Z", true);
680 bool QLine::Matches(User *u)
682 if (InspIRCd::Match(u->nick, this->nick))
688 void QLine::Apply(User* u)
690 /* Force to uuid on apply of Q-line, no need to disconnect anymore :) */
691 u->WriteNumeric(RPL_SAVENICK, u->uuid, "Your nickname has been Q-lined.");
692 u->ChangeNick(u->uuid);
696 bool ZLine::Matches(const std::string &str)
698 if (InspIRCd::MatchCIDR(str, this->ipaddr))
704 bool QLine::Matches(const std::string &str)
706 if (InspIRCd::Match(str, this->nick))
712 bool ELine::Matches(const std::string &str)
714 return (InspIRCd::MatchCIDR(str, matchtext));
717 bool KLine::Matches(const std::string &str)
719 return (InspIRCd::MatchCIDR(str.c_str(), matchtext));
722 bool GLine::Matches(const std::string &str)
724 return (InspIRCd::MatchCIDR(str, matchtext));
729 /* When adding one E-line, only check the one E-line */
730 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
731 for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
734 if (this->Matches(u))
739 void XLine::DisplayExpiry()
741 bool onechar = (type.length() == 1);
742 ServerInstance->SNO->WriteToSnoMask('x', "Removing expired %s%s %s (set by %s %s ago): %s",
743 type.c_str(), (onechar ? "-line" : ""), Displayable().c_str(), source.c_str(), InspIRCd::DurationString(ServerInstance->Time() - set_time).c_str(), reason.c_str());
746 const std::string& ELine::Displayable()
751 const std::string& KLine::Displayable()
756 const std::string& GLine::Displayable()
761 const std::string& ZLine::Displayable()
766 const std::string& QLine::Displayable()
771 bool KLine::IsBurstable()
776 bool XLineManager::RegisterFactory(XLineFactory* xlf)
778 XLineFactMap::iterator n = line_factory.find(xlf->GetType());
780 if (n != line_factory.end())
783 line_factory[xlf->GetType()] = xlf;
788 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
790 XLineFactMap::iterator n = line_factory.find(xlf->GetType());
792 if (n == line_factory.end())
795 line_factory.erase(n);
800 XLineFactory* XLineManager::GetFactory(const std::string &type)
802 XLineFactMap::iterator n = line_factory.find(type);
804 if (n == line_factory.end())
810 void XLineManager::ExpireRemovedConfigLines(const std::string& type, const insp::flat_set<std::string>& configlines)
813 if (lookup_lines.empty())
816 ContainerIter xlines = lookup_lines.find(type);
817 if (xlines == lookup_lines.end())
820 for (LookupIter xline = xlines->second.begin(); xline != xlines->second.end(); )
822 LookupIter cachedxline = xline++;
823 if (!cachedxline->second->from_config)
826 if (!configlines.count(cachedxline->second->Displayable()))
827 ExpireLine(xlines, cachedxline);