]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/xline.cpp
Ignore clients on ulined servers when reporting stats in LUSERS.
[user/henk/code/inspircd.git] / src / xline.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
9  *
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.
13  *
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
17  * details.
18  *
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/>.
21  */
22
23
24 #include "inspircd.h"
25 #include "xline.h"
26 #include "modules/stats.h"
27
28 /** An XLineFactory specialized to generate GLine* pointers
29  */
30 class GLineFactory : public XLineFactory
31 {
32  public:
33         GLineFactory() : XLineFactory("G") { }
34
35         /** Generate a GLine
36          */
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
38         {
39                 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
40                 return new GLine(set_time, duration, source, reason, ih.first, ih.second);
41         }
42 };
43
44 /** An XLineFactory specialized to generate ELine* pointers
45  */
46 class ELineFactory : public XLineFactory
47 {
48  public:
49         ELineFactory() : XLineFactory("E") { }
50
51         /** Generate an ELine
52          */
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
54         {
55                 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
56                 return new ELine(set_time, duration, source, reason, ih.first, ih.second);
57         }
58 };
59
60 /** An XLineFactory specialized to generate KLine* pointers
61  */
62 class KLineFactory : public XLineFactory
63 {
64  public:
65         KLineFactory() : XLineFactory("K") { }
66
67         /** Generate a KLine
68          */
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
70         {
71                 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
72                 return new KLine(set_time, duration, source, reason, ih.first, ih.second);
73         }
74 };
75
76 /** An XLineFactory specialized to generate QLine* pointers
77  */
78 class QLineFactory : public XLineFactory
79 {
80  public:
81         QLineFactory() : XLineFactory("Q") { }
82
83         /** Generate a QLine
84          */
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
86         {
87                 return new QLine(set_time, duration, source, reason, xline_specific_mask);
88         }
89 };
90
91 /** An XLineFactory specialized to generate ZLine* pointers
92  */
93 class ZLineFactory : public XLineFactory
94 {
95  public:
96         ZLineFactory() : XLineFactory("Z") { }
97
98         /** Generate a ZLine
99          */
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
101         {
102                 return new ZLine(set_time, duration, source, reason, xline_specific_mask);
103         }
104 };
105
106
107 /*
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 ..
110  *
111  * Background:
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.
116  *
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.)
121  *
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.
124  *
125  * VERSION 3:
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).
128  *
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.
132  *
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
136  *  bans. :)
137  */
138
139 bool XLine::Matches(User *u)
140 {
141         return false;
142 }
143
144 /*
145  * Checks what users match a given vector of ELines and sets their ban exempt flag accordingly.
146  */
147 void XLineManager::CheckELines()
148 {
149         ContainerIter n = lookup_lines.find("E");
150
151         if (n == lookup_lines.end())
152                 return;
153
154         XLineLookup& ELines = n->second;
155
156         if (ELines.empty())
157                 return;
158
159         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
160         for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
161         {
162                 LocalUser* u = *u2;
163                 u->exempt = false;
164
165                 /* This uses safe iteration to ensure that if a line expires here, it doenst trash the iterator */
166                 LookupIter safei;
167
168                 for (LookupIter i = ELines.begin(); i != ELines.end(); )
169                 {
170                         safei = i;
171                         safei++;
172
173                         XLine *e = i->second;
174                         if ((!e->duration || ServerInstance->Time() < e->expiry) && e->Matches(u))
175                                 u->exempt = true;
176
177                         i = safei;
178                 }
179         }
180 }
181
182
183 XLineLookup* XLineManager::GetAll(const std::string &type)
184 {
185         ContainerIter n = lookup_lines.find(type);
186
187         if (n == lookup_lines.end())
188                 return NULL;
189
190         LookupIter safei;
191         const time_t current = ServerInstance->Time();
192
193         /* Expire any dead ones, before sending */
194         for (LookupIter x = n->second.begin(); x != n->second.end(); )
195         {
196                 safei = x;
197                 safei++;
198                 if (x->second->duration && current > x->second->expiry)
199                 {
200                         ExpireLine(n, x);
201                 }
202                 x = safei;
203         }
204
205         return &(n->second);
206 }
207
208 void XLineManager::DelAll(const std::string &type)
209 {
210         ContainerIter n = lookup_lines.find(type);
211
212         if (n == lookup_lines.end())
213                 return;
214
215         LookupIter x;
216
217         /* Delete all of a given type (this should probably use DelLine, but oh well) */
218         while ((x = n->second.begin()) != n->second.end())
219         {
220                 ExpireLine(n, x);
221         }
222 }
223
224 std::vector<std::string> XLineManager::GetAllTypes()
225 {
226         std::vector<std::string> items;
227         for (ContainerIter x = lookup_lines.begin(); x != lookup_lines.end(); ++x)
228                 items.push_back(x->first);
229         return items;
230 }
231
232 IdentHostPair XLineManager::IdentSplit(const std::string &ident_and_host)
233 {
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)
237         {
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())
241                         n.first.assign("*");
242                 if (!n.second.length())
243                         n.second.assign("*");
244         }
245         else
246         {
247                 n.first.clear();
248                 n.second = ident_and_host;
249         }
250
251         return n;
252 }
253
254 // adds a line
255
256 bool XLineManager::AddLine(XLine* line, User* user)
257 {
258         if (line->duration && ServerInstance->Time() > line->expiry)
259                 return false; // Don't apply expired XLines.
260
261         /* Don't apply duplicate xlines */
262         ContainerIter x = lookup_lines.find(line->type);
263         if (x != lookup_lines.end())
264         {
265                 LookupIter i = x->second.find(line->Displayable());
266                 if (i != x->second.end())
267                 {
268                         bool silent = false;
269
270                         // Allow replacing a config line for an updated config line.
271                         if (i->second->from_config && line->from_config)
272                         {
273                                 // Nothing changed, skip adding this one.
274                                 if (i->second->reason == line->reason)
275                                         return false;
276
277                                 silent = true;
278                         }
279                         // Allow replacing a non-config line for a new config line.
280                         else if (!line->from_config)
281                         {
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))
285                                         return false;
286                         }
287                         else
288                         {
289                                 silent = true;
290                         }
291
292                         ExpireLine(x, i, silent);
293                 }
294         }
295
296         /*ELine* item = new ELine(ServerInstance->Time(), duration, source, reason, ih.first.c_str(), ih.second.c_str());*/
297         XLineFactory* xlf = GetFactory(line->type);
298         if (!xlf)
299                 return false;
300
301         ServerInstance->BanCache.RemoveEntries(line->type, false); // XXX perhaps remove ELines here?
302
303         if (xlf->AutoApplyToUserList(line))
304                 pending_lines.push_back(line);
305
306         lookup_lines[line->type][line->Displayable()] = line;
307         line->OnAdd();
308
309         FOREACH_MOD(OnAddLine, (user, line));
310
311         return true;
312 }
313
314 // deletes a line, returns true if the line existed and was removed
315
316 bool XLineManager::DelLine(const char* hostmask, const std::string& type, std::string& reason, User* user, bool simulate)
317 {
318         ContainerIter x = lookup_lines.find(type);
319
320         if (x == lookup_lines.end())
321                 return false;
322
323         LookupIter y = x->second.find(hostmask);
324
325         if (y == x->second.end())
326                 return false;
327
328         reason.assign(y->second->reason);
329
330         if (simulate)
331                 return true;
332
333         ServerInstance->BanCache.RemoveEntries(y->second->type, true);
334
335         FOREACH_MOD(OnDelLine, (user, y->second));
336
337         y->second->Unset();
338
339         stdalgo::erase(pending_lines, y->second);
340
341         delete y->second;
342         x->second.erase(y);
343
344         return true;
345 }
346
347
348 void ELine::Unset()
349 {
350         ServerInstance->XLines->CheckELines();
351 }
352
353 // returns a pointer to the reason if a nickname matches a Q-line, NULL if it didn't match
354
355 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
356 {
357         ContainerIter x = lookup_lines.find(type);
358
359         if (x == lookup_lines.end())
360                 return NULL;
361
362         const time_t current = ServerInstance->Time();
363
364         LookupIter safei;
365
366         for (LookupIter i = x->second.begin(); i != x->second.end(); )
367         {
368                 safei = i;
369                 safei++;
370
371                 if (i->second->duration && current > i->second->expiry)
372                 {
373                         /* Expire the line, proceed to next one */
374                         ExpireLine(x, i);
375                         i = safei;
376                         continue;
377                 }
378
379                 if (i->second->Matches(user))
380                 {
381                         return i->second;
382                 }
383
384                 i = safei;
385         }
386         return NULL;
387 }
388
389 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
390 {
391         ContainerIter x = lookup_lines.find(type);
392
393         if (x == lookup_lines.end())
394                 return NULL;
395
396         const time_t current = ServerInstance->Time();
397
398          LookupIter safei;
399
400         for (LookupIter i = x->second.begin(); i != x->second.end(); )
401         {
402                 safei = i;
403                 safei++;
404
405                 if (i->second->Matches(pattern))
406                 {
407                         if (i->second->duration && current > i->second->expiry)
408                         {
409                                 /* Expire the line, return nothing */
410                                 ExpireLine(x, i);
411                                 /* See above */
412                                 i = safei;
413                                 continue;
414                         }
415                         else
416                                 return i->second;
417                 }
418
419                 i = safei;
420         }
421         return NULL;
422 }
423
424 // removes lines that have expired
425 void XLineManager::ExpireLine(ContainerIter container, LookupIter item, bool silent)
426 {
427         FOREACH_MOD(OnExpireLine, (item->second));
428
429         if (!silent)
430                 item->second->DisplayExpiry();
431
432         item->second->Unset();
433
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?
436          * -- Brain
437          */
438         stdalgo::erase(pending_lines, item->second);
439
440         delete item->second;
441         container->second.erase(item);
442 }
443
444
445 // applies lines, removing clients and changing nicks etc as applicable
446 void XLineManager::ApplyLines()
447 {
448         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
449         for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); )
450         {
451                 LocalUser* u = *j++;
452
453                 // Don't ban people who are exempt.
454                 if (u->exempt)
455                         continue;
456
457                 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
458                 {
459                         XLine *x = *i;
460                         if (x->Matches(u))
461                         {
462                                 x->Apply(u);
463
464                                 // If applying the X-line has killed the user then don't
465                                 // apply any more lines to them.
466                                 if (u->quitting)
467                                         break;
468                         }
469                 }
470         }
471
472         pending_lines.clear();
473 }
474
475 void XLineManager::InvokeStats(const std::string& type, unsigned int numeric, Stats::Context& stats)
476 {
477         ContainerIter n = lookup_lines.find(type);
478
479         time_t current = ServerInstance->Time();
480
481         LookupIter safei;
482
483         if (n != lookup_lines.end())
484         {
485                 XLineLookup& list = n->second;
486                 for (LookupIter i = list.begin(); i != list.end(); )
487                 {
488                         safei = i;
489                         safei++;
490
491                         if (i->second->duration && current > i->second->expiry)
492                         {
493                                 ExpireLine(n, i);
494                         }
495                         else
496                                 stats.AddRow(numeric, i->second->Displayable()+" "+
497                                         ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+i->second->source+" :"+i->second->reason);
498                         i = safei;
499                 }
500         }
501 }
502
503
504 XLineManager::XLineManager()
505 {
506         GLineFactory* GFact;
507         ELineFactory* EFact;
508         KLineFactory* KFact;
509         QLineFactory* QFact;
510         ZLineFactory* ZFact;
511
512
513         GFact = new GLineFactory;
514         EFact = new ELineFactory;
515         KFact = new KLineFactory;
516         QFact = new QLineFactory;
517         ZFact = new ZLineFactory;
518
519         RegisterFactory(GFact);
520         RegisterFactory(EFact);
521         RegisterFactory(KFact);
522         RegisterFactory(QFact);
523         RegisterFactory(ZFact);
524 }
525
526 XLineManager::~XLineManager()
527 {
528         const char gekqz[] = "GEKQZ";
529         for(unsigned int i=0; i < sizeof(gekqz); i++)
530         {
531                 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
532                 delete xlf;
533         }
534
535         // Delete all existing XLines
536         for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
537         {
538                 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
539                 {
540                         delete j->second;
541                 }
542         }
543 }
544
545 void XLine::Apply(User* u)
546 {
547 }
548
549 bool XLine::IsBurstable()
550 {
551         return !from_config;
552 }
553
554 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
555 {
556         const std::string banReason = line + "-lined: " + reason;
557
558         if (!ServerInstance->Config->XLineMessage.empty())
559                 u->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
560
561         if (ServerInstance->Config->HideBans)
562                 ServerInstance->Users->QuitUser(u, line + "-lined", &banReason);
563         else
564                 ServerInstance->Users->QuitUser(u, banReason);
565
566
567         if (bancache)
568         {
569                 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
570                 ServerInstance->BanCache.AddHit(u->GetIPString(), this->type, banReason, (this->duration > 0 ? (this->expiry - ServerInstance->Time()) : 0));
571         }
572 }
573
574 bool KLine::Matches(User *u)
575 {
576         LocalUser* lu = IS_LOCAL(u);
577         if (lu && lu->exempt)
578                 return false;
579
580         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
581         {
582                 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
583                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
584                 {
585                         return true;
586                 }
587         }
588
589         return false;
590 }
591
592 void KLine::Apply(User* u)
593 {
594         DefaultApply(u, "K", (this->identmask ==  "*") ? true : false);
595 }
596
597 bool GLine::Matches(User *u)
598 {
599         LocalUser* lu = IS_LOCAL(u);
600         if (lu && lu->exempt)
601                 return false;
602
603         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
604         {
605                 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
606                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
607                 {
608                         return true;
609                 }
610         }
611
612         return false;
613 }
614
615 void GLine::Apply(User* u)
616 {
617         DefaultApply(u, "G", (this->identmask == "*") ? true : false);
618 }
619
620 bool ELine::Matches(User *u)
621 {
622         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
623         {
624                 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
625                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
626                 {
627                         return true;
628                 }
629         }
630
631         return false;
632 }
633
634 bool ZLine::Matches(User *u)
635 {
636         LocalUser* lu = IS_LOCAL(u);
637         if (lu && lu->exempt)
638                 return false;
639
640         if (InspIRCd::MatchCIDR(u->GetIPString(), this->ipaddr))
641                 return true;
642         else
643                 return false;
644 }
645
646 void ZLine::Apply(User* u)
647 {
648         DefaultApply(u, "Z", true);
649 }
650
651
652 bool QLine::Matches(User *u)
653 {
654         if (InspIRCd::Match(u->nick, this->nick))
655                 return true;
656
657         return false;
658 }
659
660 void QLine::Apply(User* u)
661 {
662         /* Force to uuid on apply of Q-line, no need to disconnect anymore :) */
663         u->ChangeNick(u->uuid);
664 }
665
666
667 bool ZLine::Matches(const std::string &str)
668 {
669         if (InspIRCd::MatchCIDR(str, this->ipaddr))
670                 return true;
671         else
672                 return false;
673 }
674
675 bool QLine::Matches(const std::string &str)
676 {
677         if (InspIRCd::Match(str, this->nick))
678                 return true;
679
680         return false;
681 }
682
683 bool ELine::Matches(const std::string &str)
684 {
685         return (InspIRCd::MatchCIDR(str, matchtext));
686 }
687
688 bool KLine::Matches(const std::string &str)
689 {
690         return (InspIRCd::MatchCIDR(str.c_str(), matchtext));
691 }
692
693 bool GLine::Matches(const std::string &str)
694 {
695         return (InspIRCd::MatchCIDR(str, matchtext));
696 }
697
698 void ELine::OnAdd()
699 {
700         /* When adding one E-line, only check the one E-line */
701         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
702         for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
703         {
704                 LocalUser* u = *u2;
705                 if (this->Matches(u))
706                         u->exempt = true;
707         }
708 }
709
710 void XLine::DisplayExpiry()
711 {
712         bool onechar = (type.length() == 1);
713         ServerInstance->SNO->WriteToSnoMask('x', "Removing expired %s%s %s (set by %s %s ago): %s",
714                 type.c_str(), (onechar ? "-line" : ""), Displayable().c_str(), source.c_str(), InspIRCd::DurationString(ServerInstance->Time() - set_time).c_str(), reason.c_str());
715 }
716
717 const std::string& ELine::Displayable()
718 {
719         return matchtext;
720 }
721
722 const std::string& KLine::Displayable()
723 {
724         return matchtext;
725 }
726
727 const std::string& GLine::Displayable()
728 {
729         return matchtext;
730 }
731
732 const std::string& ZLine::Displayable()
733 {
734         return ipaddr;
735 }
736
737 const std::string& QLine::Displayable()
738 {
739         return nick;
740 }
741
742 bool KLine::IsBurstable()
743 {
744         return false;
745 }
746
747 bool XLineManager::RegisterFactory(XLineFactory* xlf)
748 {
749         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
750
751         if (n != line_factory.end())
752                 return false;
753
754         line_factory[xlf->GetType()] = xlf;
755
756         return true;
757 }
758
759 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
760 {
761         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
762
763         if (n == line_factory.end())
764                 return false;
765
766         line_factory.erase(n);
767
768         return true;
769 }
770
771 XLineFactory* XLineManager::GetFactory(const std::string &type)
772 {
773         XLineFactMap::iterator n = line_factory.find(type);
774
775         if (n == line_factory.end())
776                 return NULL;
777
778         return n->second;
779 }
780
781 void XLineManager::ExpireRemovedConfigLines(const std::string& type, const insp::flat_set<std::string>& configlines)
782 {
783         // Nothing to do.
784         if (lookup_lines.empty())
785                 return;
786
787         ContainerIter xlines = lookup_lines.find(type);
788         if (xlines == lookup_lines.end())
789                 return;
790
791         for (LookupIter xline = xlines->second.begin(); xline != xlines->second.end(); )
792         {
793                 LookupIter cachedxline = xline++;
794                 if (!cachedxline->second->from_config)
795                         continue;
796
797                 if (!configlines.count(cachedxline->second->Displayable()))
798                         ExpireLine(xlines, cachedxline);
799         }
800 }