]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/xline.cpp
8d4c822aab715bc43e5c5c7ade70dde7bbe7863a
[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
27 /** An XLineFactory specialized to generate GLine* pointers
28  */
29 class GLineFactory : public XLineFactory
30 {
31  public:
32         GLineFactory() : XLineFactory("G") { }
33
34         /** Generate a GLine
35          */
36         XLine* Generate(time_t set_time, long duration, std::string source, std::string reason, std::string xline_specific_mask) CXX11_OVERRIDE
37         {
38                 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
39                 return new GLine(set_time, duration, source, reason, ih.first, ih.second);
40         }
41 };
42
43 /** An XLineFactory specialized to generate ELine* pointers
44  */
45 class ELineFactory : public XLineFactory
46 {
47  public:
48         ELineFactory() : XLineFactory("E") { }
49
50         /** Generate an ELine
51          */
52         XLine* Generate(time_t set_time, long duration, std::string source, std::string reason, std::string xline_specific_mask) CXX11_OVERRIDE
53         {
54                 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
55                 return new ELine(set_time, duration, source, reason, ih.first, ih.second);
56         }
57 };
58
59 /** An XLineFactory specialized to generate KLine* pointers
60  */
61 class KLineFactory : public XLineFactory
62 {
63  public:
64         KLineFactory() : XLineFactory("K") { }
65
66         /** Generate a KLine
67          */
68         XLine* Generate(time_t set_time, long duration, std::string source, std::string reason, std::string xline_specific_mask) CXX11_OVERRIDE
69         {
70                 IdentHostPair ih = ServerInstance->XLines->IdentSplit(xline_specific_mask);
71                 return new KLine(set_time, duration, source, reason, ih.first, ih.second);
72         }
73 };
74
75 /** An XLineFactory specialized to generate QLine* pointers
76  */
77 class QLineFactory : public XLineFactory
78 {
79  public:
80         QLineFactory() : XLineFactory("Q") { }
81
82         /** Generate a QLine
83          */
84         XLine* Generate(time_t set_time, long duration, std::string source, std::string reason, std::string xline_specific_mask) CXX11_OVERRIDE
85         {
86                 return new QLine(set_time, duration, source, reason, xline_specific_mask);
87         }
88 };
89
90 /** An XLineFactory specialized to generate ZLine* pointers
91  */
92 class ZLineFactory : public XLineFactory
93 {
94  public:
95         ZLineFactory() : XLineFactory("Z") { }
96
97         /** Generate a ZLine
98          */
99         XLine* Generate(time_t set_time, long duration, std::string source, std::string reason, std::string xline_specific_mask) CXX11_OVERRIDE
100         {
101                 return new ZLine(set_time, duration, source, reason, xline_specific_mask);
102         }
103 };
104
105
106 /*
107  * This is now version 3 of the XLine subsystem, let's see if we can get it as nice and
108  * efficient as we can this time so we can close this file and never ever touch it again ..
109  *
110  * Background:
111  *  Version 1 stored all line types in one list (one for g, one for z, etc). This was fine,
112  *  but both version 1 and 2 suck at applying lines efficiently. That is, every time a new line
113  *  was added, it iterated every existing line for every existing user. Ow. Expiry was also
114  *  expensive, as the lists were NOT sorted.
115  *
116  *  Version 2 moved permanent lines into a seperate list from non-permanent to help optimize
117  *  matching speed, but matched in the same way.
118  *  Expiry was also sped up by sorting the list by expiry (meaning just remove the items at the
119  *  head of the list that are outdated.)
120  *
121  * This was fine and good, but it looked less than ideal in code, and matching was still slower
122  * than it could have been, something which we address here.
123  *
124  * VERSION 3:
125  *  All lines are (as in v1) stored together -- no seperation of perm and non-perm. They are stored in
126  *  a map of maps (first map is line type, second map is for quick lookup on add/delete/etc).
127  *
128  *  Expiry is *no longer* performed on a timer, and no longer uses a sorted list of any variety. This
129  *  is now done by only checking for expiry when a line is accessed, meaning that expiry is no longer
130  *  a resource intensive problem.
131  *
132  *  Application no longer tries to apply every single line on every single user - instead, now only lines
133  *  added since the previous application are applied. This keeps S2S ADDLINE during burst nice and fast,
134  *  while at the same time not slowing things the fuck down when we try adding a ban with lots of preexisting
135  *  bans. :)
136  */
137
138 bool XLine::Matches(User *u)
139 {
140         return false;
141 }
142
143 /*
144  * Checks what users match a given vector of ELines and sets their ban exempt flag accordingly.
145  */
146 void XLineManager::CheckELines()
147 {
148         ContainerIter n = lookup_lines.find("E");
149
150         if (n == lookup_lines.end())
151                 return;
152
153         XLineLookup& ELines = n->second;
154
155         if (ELines.empty())
156                 return;
157
158         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
159         for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
160         {
161                 LocalUser* u = *u2;
162                 u->exempt = false;
163
164                 /* This uses safe iteration to ensure that if a line expires here, it doenst trash the iterator */
165                 LookupIter safei;
166
167                 for (LookupIter i = ELines.begin(); i != ELines.end(); )
168                 {
169                         safei = i;
170                         safei++;
171
172                         XLine *e = i->second;
173                         if ((!e->duration || ServerInstance->Time() < e->expiry) && e->Matches(u))
174                                 u->exempt = true;
175
176                         i = safei;
177                 }
178         }
179 }
180
181
182 XLineLookup* XLineManager::GetAll(const std::string &type)
183 {
184         ContainerIter n = lookup_lines.find(type);
185
186         if (n == lookup_lines.end())
187                 return NULL;
188
189         LookupIter safei;
190         const time_t current = ServerInstance->Time();
191
192         /* Expire any dead ones, before sending */
193         for (LookupIter x = n->second.begin(); x != n->second.end(); )
194         {
195                 safei = x;
196                 safei++;
197                 if (x->second->duration && current > x->second->expiry)
198                 {
199                         ExpireLine(n, x);
200                 }
201                 x = safei;
202         }
203
204         return &(n->second);
205 }
206
207 void XLineManager::DelAll(const std::string &type)
208 {
209         ContainerIter n = lookup_lines.find(type);
210
211         if (n == lookup_lines.end())
212                 return;
213
214         LookupIter x;
215
216         /* Delete all of a given type (this should probably use DelLine, but oh well) */
217         while ((x = n->second.begin()) != n->second.end())
218         {
219                 ExpireLine(n, x);
220         }
221 }
222
223 std::vector<std::string> XLineManager::GetAllTypes()
224 {
225         std::vector<std::string> items;
226         for (ContainerIter x = lookup_lines.begin(); x != lookup_lines.end(); ++x)
227                 items.push_back(x->first);
228         return items;
229 }
230
231 IdentHostPair XLineManager::IdentSplit(const std::string &ident_and_host)
232 {
233         IdentHostPair n = std::make_pair<std::string,std::string>("*","*");
234         std::string::size_type x = ident_and_host.find('@');
235         if (x != std::string::npos)
236         {
237                 n.second = ident_and_host.substr(x + 1,ident_and_host.length());
238                 n.first = ident_and_host.substr(0, x);
239                 if (!n.first.length())
240                         n.first.assign("*");
241                 if (!n.second.length())
242                         n.second.assign("*");
243         }
244         else
245         {
246                 n.first.clear();
247                 n.second = ident_and_host;
248         }
249
250         return n;
251 }
252
253 // adds a line
254
255 bool XLineManager::AddLine(XLine* line, User* user)
256 {
257         if (line->duration && ServerInstance->Time() > line->expiry)
258                 return false; // Don't apply expired XLines.
259
260         /* Don't apply duplicate xlines */
261         ContainerIter x = lookup_lines.find(line->type);
262         if (x != lookup_lines.end())
263         {
264                 LookupIter i = x->second.find(line->Displayable());
265                 if (i != x->second.end())
266                 {
267                         // XLine propagation bug was here, if the line to be added already exists and
268                         // it's expired then expire it and add the new one instead of returning false
269                         if ((!i->second->duration) || (ServerInstance->Time() < i->second->expiry))
270                                 return false;
271
272                         ExpireLine(x, i);
273                 }
274         }
275
276         /*ELine* item = new ELine(ServerInstance->Time(), duration, source, reason, ih.first.c_str(), ih.second.c_str());*/
277         XLineFactory* xlf = GetFactory(line->type);
278         if (!xlf)
279                 return false;
280
281         ServerInstance->BanCache.RemoveEntries(line->type, false); // XXX perhaps remove ELines here?
282
283         if (xlf->AutoApplyToUserList(line))
284                 pending_lines.push_back(line);
285
286         lookup_lines[line->type][line->Displayable()] = line;
287         line->OnAdd();
288
289         FOREACH_MOD(OnAddLine, (user, line));
290
291         return true;
292 }
293
294 // deletes a line, returns true if the line existed and was removed
295
296 bool XLineManager::DelLine(const char* hostmask, const std::string &type, User* user, bool simulate)
297 {
298         ContainerIter x = lookup_lines.find(type);
299
300         if (x == lookup_lines.end())
301                 return false;
302
303         LookupIter y = x->second.find(hostmask);
304
305         if (y == x->second.end())
306                 return false;
307
308         if (simulate)
309                 return true;
310
311         ServerInstance->BanCache.RemoveEntries(y->second->type, true);
312
313         FOREACH_MOD(OnDelLine, (user, y->second));
314
315         y->second->Unset();
316
317         stdalgo::erase(pending_lines, y->second);
318
319         delete y->second;
320         x->second.erase(y);
321
322         return true;
323 }
324
325
326 void ELine::Unset()
327 {
328         ServerInstance->XLines->CheckELines();
329 }
330
331 // returns a pointer to the reason if a nickname matches a qline, NULL if it didnt match
332
333 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
334 {
335         ContainerIter x = lookup_lines.find(type);
336
337         if (x == lookup_lines.end())
338                 return NULL;
339
340         const time_t current = ServerInstance->Time();
341
342         LookupIter safei;
343
344         for (LookupIter i = x->second.begin(); i != x->second.end(); )
345         {
346                 safei = i;
347                 safei++;
348
349                 if (i->second->duration && current > i->second->expiry)
350                 {
351                         /* Expire the line, proceed to next one */
352                         ExpireLine(x, i);
353                         i = safei;
354                         continue;
355                 }
356
357                 if (i->second->Matches(user))
358                 {
359                         return i->second;
360                 }
361
362                 i = safei;
363         }
364         return NULL;
365 }
366
367 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
368 {
369         ContainerIter x = lookup_lines.find(type);
370
371         if (x == lookup_lines.end())
372                 return NULL;
373
374         const time_t current = ServerInstance->Time();
375
376          LookupIter safei;
377
378         for (LookupIter i = x->second.begin(); i != x->second.end(); )
379         {
380                 safei = i;
381                 safei++;
382
383                 if (i->second->Matches(pattern))
384                 {
385                         if (i->second->duration && current > i->second->expiry)
386                         {
387                                 /* Expire the line, return nothing */
388                                 ExpireLine(x, i);
389                                 /* See above */
390                                 i = safei;
391                                 continue;
392                         }
393                         else
394                                 return i->second;
395                 }
396
397                 i = safei;
398         }
399         return NULL;
400 }
401
402 // removes lines that have expired
403 void XLineManager::ExpireLine(ContainerIter container, LookupIter item)
404 {
405         FOREACH_MOD(OnExpireLine, (item->second));
406
407         item->second->DisplayExpiry();
408         item->second->Unset();
409
410         /* TODO: Can we skip this loop by having a 'pending' field in the XLine class, which is set when a line
411          * is pending, cleared when it is no longer pending, so we skip over this loop if its not pending?
412          * -- Brain
413          */
414         stdalgo::erase(pending_lines, item->second);
415
416         delete item->second;
417         container->second.erase(item);
418 }
419
420
421 // applies lines, removing clients and changing nicks etc as applicable
422 void XLineManager::ApplyLines()
423 {
424         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
425         for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); ++j)
426         {
427                 LocalUser* u = *j;
428
429                 // Don't ban people who are exempt.
430                 if (u->exempt)
431                         continue;
432
433                 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
434                 {
435                         XLine *x = *i;
436                         if (x->Matches(u))
437                                 x->Apply(u);
438                 }
439         }
440
441         pending_lines.clear();
442 }
443
444 void XLineManager::InvokeStats(const std::string& type, unsigned int numeric, Stats::Context& stats)
445 {
446         ContainerIter n = lookup_lines.find(type);
447
448         time_t current = ServerInstance->Time();
449
450         LookupIter safei;
451
452         if (n != lookup_lines.end())
453         {
454                 XLineLookup& list = n->second;
455                 for (LookupIter i = list.begin(); i != list.end(); )
456                 {
457                         safei = i;
458                         safei++;
459
460                         if (i->second->duration && current > i->second->expiry)
461                         {
462                                 ExpireLine(n, i);
463                         }
464                         else
465                                 stats.AddRow(numeric, i->second->Displayable()+" "+
466                                         ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+i->second->source+" :"+i->second->reason);
467                         i = safei;
468                 }
469         }
470 }
471
472
473 XLineManager::XLineManager()
474 {
475         GLineFactory* GFact;
476         ELineFactory* EFact;
477         KLineFactory* KFact;
478         QLineFactory* QFact;
479         ZLineFactory* ZFact;
480
481
482         GFact = new GLineFactory;
483         EFact = new ELineFactory;
484         KFact = new KLineFactory;
485         QFact = new QLineFactory;
486         ZFact = new ZLineFactory;
487
488         RegisterFactory(GFact);
489         RegisterFactory(EFact);
490         RegisterFactory(KFact);
491         RegisterFactory(QFact);
492         RegisterFactory(ZFact);
493 }
494
495 XLineManager::~XLineManager()
496 {
497         const char gekqz[] = "GEKQZ";
498         for(unsigned int i=0; i < sizeof(gekqz); i++)
499         {
500                 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
501                 delete xlf;
502         }
503
504         // Delete all existing XLines
505         for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
506         {
507                 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
508                 {
509                         delete j->second;
510                 }
511         }
512 }
513
514 void XLine::Apply(User* u)
515 {
516 }
517
518 bool XLine::IsBurstable()
519 {
520         return true;
521 }
522
523 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
524 {
525         const std::string banReason = line + "-Lined: " + reason;
526
527         if (!ServerInstance->Config->XLineMessage.empty())
528                 u->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
529
530         if (ServerInstance->Config->HideBans)
531                 ServerInstance->Users->QuitUser(u, line + "-Lined", &banReason);
532         else
533                 ServerInstance->Users->QuitUser(u, banReason);
534
535
536         if (bancache)
537         {
538                 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
539                 ServerInstance->BanCache.AddHit(u->GetIPString(), this->type, banReason, this->duration);
540         }
541 }
542
543 bool KLine::Matches(User *u)
544 {
545         LocalUser* lu = IS_LOCAL(u);
546         if (lu && lu->exempt)
547                 return false;
548
549         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
550         {
551                 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
552                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
553                 {
554                         return true;
555                 }
556         }
557
558         return false;
559 }
560
561 void KLine::Apply(User* u)
562 {
563         DefaultApply(u, "K", (this->identmask ==  "*") ? true : false);
564 }
565
566 bool GLine::Matches(User *u)
567 {
568         LocalUser* lu = IS_LOCAL(u);
569         if (lu && lu->exempt)
570                 return false;
571
572         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
573         {
574                 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
575                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
576                 {
577                         return true;
578                 }
579         }
580
581         return false;
582 }
583
584 void GLine::Apply(User* u)
585 {
586         DefaultApply(u, "G", (this->identmask == "*") ? true : false);
587 }
588
589 bool ELine::Matches(User *u)
590 {
591         LocalUser* lu = IS_LOCAL(u);
592         if (lu && lu->exempt)
593                 return false;
594
595         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
596         {
597                 if (InspIRCd::MatchCIDR(u->GetRealHost(), this->hostmask, ascii_case_insensitive_map) ||
598                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
599                 {
600                         return true;
601                 }
602         }
603
604         return false;
605 }
606
607 bool ZLine::Matches(User *u)
608 {
609         LocalUser* lu = IS_LOCAL(u);
610         if (lu && lu->exempt)
611                 return false;
612
613         if (InspIRCd::MatchCIDR(u->GetIPString(), this->ipaddr))
614                 return true;
615         else
616                 return false;
617 }
618
619 void ZLine::Apply(User* u)
620 {
621         DefaultApply(u, "Z", true);
622 }
623
624
625 bool QLine::Matches(User *u)
626 {
627         if (InspIRCd::Match(u->nick, this->nick))
628                 return true;
629
630         return false;
631 }
632
633 void QLine::Apply(User* u)
634 {
635         /* Force to uuid on apply of qline, no need to disconnect any more :) */
636         u->ChangeNick(u->uuid);
637 }
638
639
640 bool ZLine::Matches(const std::string &str)
641 {
642         if (InspIRCd::MatchCIDR(str, this->ipaddr))
643                 return true;
644         else
645                 return false;
646 }
647
648 bool QLine::Matches(const std::string &str)
649 {
650         if (InspIRCd::Match(str, this->nick))
651                 return true;
652
653         return false;
654 }
655
656 bool ELine::Matches(const std::string &str)
657 {
658         return (InspIRCd::MatchCIDR(str, matchtext));
659 }
660
661 bool KLine::Matches(const std::string &str)
662 {
663         return (InspIRCd::MatchCIDR(str.c_str(), matchtext));
664 }
665
666 bool GLine::Matches(const std::string &str)
667 {
668         return (InspIRCd::MatchCIDR(str, matchtext));
669 }
670
671 void ELine::OnAdd()
672 {
673         /* When adding one eline, only check the one eline */
674         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
675         for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
676         {
677                 LocalUser* u = *u2;
678                 if (this->Matches(u))
679                         u->exempt = true;
680         }
681 }
682
683 void XLine::DisplayExpiry()
684 {
685         bool onechar = (type.length() == 1);
686         ServerInstance->SNO->WriteToSnoMask('x', "Removing expired %s%s %s (set by %s %ld seconds ago)",
687                 type.c_str(), (onechar ? "-Line" : ""), Displayable().c_str(), source.c_str(), (long)(ServerInstance->Time() - set_time));
688 }
689
690 const std::string& ELine::Displayable()
691 {
692         return matchtext;
693 }
694
695 const std::string& KLine::Displayable()
696 {
697         return matchtext;
698 }
699
700 const std::string& GLine::Displayable()
701 {
702         return matchtext;
703 }
704
705 const std::string& ZLine::Displayable()
706 {
707         return ipaddr;
708 }
709
710 const std::string& QLine::Displayable()
711 {
712         return nick;
713 }
714
715 bool KLine::IsBurstable()
716 {
717         return false;
718 }
719
720 bool XLineManager::RegisterFactory(XLineFactory* xlf)
721 {
722         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
723
724         if (n != line_factory.end())
725                 return false;
726
727         line_factory[xlf->GetType()] = xlf;
728
729         return true;
730 }
731
732 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
733 {
734         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
735
736         if (n == line_factory.end())
737                 return false;
738
739         line_factory.erase(n);
740
741         return true;
742 }
743
744 XLineFactory* XLineManager::GetFactory(const std::string &type)
745 {
746         XLineFactMap::iterator n = line_factory.find(type);
747
748         if (n == line_factory.end())
749                 return NULL;
750
751         return n->second;
752 }