]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/xline.cpp
Change allocation of InspIRCd::BanCache to be physically part of the object containing it
[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)
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)
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)
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)
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)
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         for (LocalUserList::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
159         {
160                 LocalUser* u = *u2;
161
162                 /* This uses safe iteration to ensure that if a line expires here, it doenst trash the iterator */
163                 LookupIter safei;
164
165                 for (LookupIter i = ELines.begin(); i != ELines.end(); )
166                 {
167                         safei = i;
168                         safei++;
169
170                         XLine *e = i->second;
171                         u->exempt = e->Matches(u);
172
173                         i = safei;
174                 }
175         }
176 }
177
178
179 XLineLookup* XLineManager::GetAll(const std::string &type)
180 {
181         ContainerIter n = lookup_lines.find(type);
182
183         if (n == lookup_lines.end())
184                 return NULL;
185
186         LookupIter safei;
187         const time_t current = ServerInstance->Time();
188
189         /* Expire any dead ones, before sending */
190         for (LookupIter x = n->second.begin(); x != n->second.end(); )
191         {
192                 safei = x;
193                 safei++;
194                 if (x->second->duration && current > x->second->expiry)
195                 {
196                         ExpireLine(n, x);
197                 }
198                 x = safei;
199         }
200
201         return &(n->second);
202 }
203
204 void XLineManager::DelAll(const std::string &type)
205 {
206         ContainerIter n = lookup_lines.find(type);
207
208         if (n == lookup_lines.end())
209                 return;
210
211         LookupIter x;
212
213         /* Delete all of a given type (this should probably use DelLine, but oh well) */
214         while ((x = n->second.begin()) != n->second.end())
215         {
216                 ExpireLine(n, x);
217         }
218 }
219
220 std::vector<std::string> XLineManager::GetAllTypes()
221 {
222         std::vector<std::string> items;
223         for (ContainerIter x = lookup_lines.begin(); x != lookup_lines.end(); ++x)
224                 items.push_back(x->first);
225         return items;
226 }
227
228 IdentHostPair XLineManager::IdentSplit(const std::string &ident_and_host)
229 {
230         IdentHostPair n = std::make_pair<std::string,std::string>("*","*");
231         std::string::size_type x = ident_and_host.find('@');
232         if (x != std::string::npos)
233         {
234                 n.second = ident_and_host.substr(x + 1,ident_and_host.length());
235                 n.first = ident_and_host.substr(0, x);
236                 if (!n.first.length())
237                         n.first.assign("*");
238                 if (!n.second.length())
239                         n.second.assign("*");
240         }
241         else
242         {
243                 n.first.clear();
244                 n.second = ident_and_host;
245         }
246
247         return n;
248 }
249
250 // adds a line
251
252 bool XLineManager::AddLine(XLine* line, User* user)
253 {
254         if (line->duration && ServerInstance->Time() > line->expiry)
255                 return false; // Don't apply expired XLines.
256
257         /* Don't apply duplicate xlines */
258         ContainerIter x = lookup_lines.find(line->type);
259         if (x != lookup_lines.end())
260         {
261                 LookupIter i = x->second.find(line->Displayable().c_str());
262                 if (i != x->second.end())
263                 {
264                         // XLine propagation bug was here, if the line to be added already exists and
265                         // it's expired then expire it and add the new one instead of returning false
266                         if ((!i->second->duration) || (ServerInstance->Time() < i->second->expiry))
267                                 return false;
268
269                         ExpireLine(x, i);
270                 }
271         }
272
273         /*ELine* item = new ELine(ServerInstance->Time(), duration, source, reason, ih.first.c_str(), ih.second.c_str());*/
274         XLineFactory* xlf = GetFactory(line->type);
275         if (!xlf)
276                 return false;
277
278         ServerInstance->BanCache.RemoveEntries(line->type, false); // XXX perhaps remove ELines here?
279
280         if (xlf->AutoApplyToUserList(line))
281                 pending_lines.push_back(line);
282
283         lookup_lines[line->type][line->Displayable().c_str()] = line;
284         line->OnAdd();
285
286         FOREACH_MOD(OnAddLine, (user, line));
287
288         return true;
289 }
290
291 // deletes a line, returns true if the line existed and was removed
292
293 bool XLineManager::DelLine(const char* hostmask, const std::string &type, User* user, bool simulate)
294 {
295         ContainerIter x = lookup_lines.find(type);
296
297         if (x == lookup_lines.end())
298                 return false;
299
300         LookupIter y = x->second.find(hostmask);
301
302         if (y == x->second.end())
303                 return false;
304
305         if (simulate)
306                 return true;
307
308         ServerInstance->BanCache.RemoveEntries(y->second->type, true);
309
310         FOREACH_MOD(OnDelLine, (user, y->second));
311
312         y->second->Unset();
313
314         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), y->second);
315         if (pptr != pending_lines.end())
316                 pending_lines.erase(pptr);
317
318         delete y->second;
319         x->second.erase(y);
320
321         return true;
322 }
323
324
325 void ELine::Unset()
326 {
327         /* remove exempt from everyone and force recheck after deleting eline */
328         for (LocalUserList::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
329         {
330                 LocalUser* u = *u2;
331                 u->exempt = false;
332         }
333
334         ServerInstance->XLines->CheckELines();
335 }
336
337 // returns a pointer to the reason if a nickname matches a qline, NULL if it didnt match
338
339 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
340 {
341         ContainerIter x = lookup_lines.find(type);
342
343         if (x == lookup_lines.end())
344                 return NULL;
345
346         const time_t current = ServerInstance->Time();
347
348         LookupIter safei;
349
350         for (LookupIter i = x->second.begin(); i != x->second.end(); )
351         {
352                 safei = i;
353                 safei++;
354
355                 if (i->second->duration && current > i->second->expiry)
356                 {
357                         /* Expire the line, proceed to next one */
358                         ExpireLine(x, i);
359                         i = safei;
360                         continue;
361                 }
362
363                 if (i->second->Matches(user))
364                 {
365                         return i->second;
366                 }
367
368                 i = safei;
369         }
370         return NULL;
371 }
372
373 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
374 {
375         ContainerIter x = lookup_lines.find(type);
376
377         if (x == lookup_lines.end())
378                 return NULL;
379
380         const time_t current = ServerInstance->Time();
381
382          LookupIter safei;
383
384         for (LookupIter i = x->second.begin(); i != x->second.end(); )
385         {
386                 safei = i;
387                 safei++;
388
389                 if (i->second->Matches(pattern))
390                 {
391                         if (i->second->duration && current > i->second->expiry)
392                         {
393                                 /* Expire the line, return nothing */
394                                 ExpireLine(x, i);
395                                 /* See above */
396                                 i = safei;
397                                 continue;
398                         }
399                         else
400                                 return i->second;
401                 }
402
403                 i = safei;
404         }
405         return NULL;
406 }
407
408 // removes lines that have expired
409 void XLineManager::ExpireLine(ContainerIter container, LookupIter item)
410 {
411         FOREACH_MOD(OnExpireLine, (item->second));
412
413         item->second->DisplayExpiry();
414         item->second->Unset();
415
416         /* TODO: Can we skip this loop by having a 'pending' field in the XLine class, which is set when a line
417          * is pending, cleared when it is no longer pending, so we skip over this loop if its not pending?
418          * -- Brain
419          */
420         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), item->second);
421         if (pptr != pending_lines.end())
422                 pending_lines.erase(pptr);
423
424         delete item->second;
425         container->second.erase(item);
426 }
427
428
429 // applies lines, removing clients and changing nicks etc as applicable
430 void XLineManager::ApplyLines()
431 {
432         LocalUserList& list = ServerInstance->Users->local_users;
433         for (LocalUserList::iterator j = list.begin(); j != list.end(); ++j)
434         {
435                 LocalUser* u = *j;
436
437                 // Don't ban people who are exempt.
438                 if (u->exempt)
439                         continue;
440
441                 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
442                 {
443                         XLine *x = *i;
444                         if (x->Matches(u))
445                                 x->Apply(u);
446                 }
447         }
448
449         pending_lines.clear();
450 }
451
452 void XLineManager::InvokeStats(const std::string &type, int numeric, User* user, string_list &results)
453 {
454         ContainerIter n = lookup_lines.find(type);
455
456         time_t current = ServerInstance->Time();
457
458         LookupIter safei;
459
460         if (n != lookup_lines.end())
461         {
462                 XLineLookup& list = n->second;
463                 for (LookupIter i = list.begin(); i != list.end(); )
464                 {
465                         safei = i;
466                         safei++;
467
468                         if (i->second->duration && current > i->second->expiry)
469                         {
470                                 ExpireLine(n, i);
471                         }
472                         else
473                                 results.push_back(ConvToStr(numeric)+" "+user->nick+" :"+i->second->Displayable()+" "+
474                                         ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+i->second->source+" :"+i->second->reason);
475                         i = safei;
476                 }
477         }
478 }
479
480
481 XLineManager::XLineManager()
482 {
483         GLineFactory* GFact;
484         ELineFactory* EFact;
485         KLineFactory* KFact;
486         QLineFactory* QFact;
487         ZLineFactory* ZFact;
488
489
490         GFact = new GLineFactory;
491         EFact = new ELineFactory;
492         KFact = new KLineFactory;
493         QFact = new QLineFactory;
494         ZFact = new ZLineFactory;
495
496         RegisterFactory(GFact);
497         RegisterFactory(EFact);
498         RegisterFactory(KFact);
499         RegisterFactory(QFact);
500         RegisterFactory(ZFact);
501 }
502
503 XLineManager::~XLineManager()
504 {
505         const char gekqz[] = "GEKQZ";
506         for(unsigned int i=0; i < sizeof(gekqz); i++)
507         {
508                 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
509                 delete xlf;
510         }
511
512         // Delete all existing XLines
513         for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
514         {
515                 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
516                 {
517                         delete j->second;
518                 }
519         }
520 }
521
522 void XLine::Apply(User* u)
523 {
524 }
525
526 bool XLine::IsBurstable()
527 {
528         return true;
529 }
530
531 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
532 {
533         const std::string banReason = line + "-Lined: " + reason;
534
535         if (!ServerInstance->Config->XLineMessage.empty())
536                 u->WriteNotice("*** " + ServerInstance->Config->XLineMessage);
537
538         if (ServerInstance->Config->HideBans)
539                 ServerInstance->Users->QuitUser(u, line + "-Lined", &banReason);
540         else
541                 ServerInstance->Users->QuitUser(u, banReason);
542
543
544         if (bancache)
545         {
546                 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
547                 ServerInstance->BanCache.AddHit(u->GetIPString(), this->type, banReason, this->duration);
548         }
549 }
550
551 bool KLine::Matches(User *u)
552 {
553         LocalUser* lu = IS_LOCAL(u);
554         if (lu && lu->exempt)
555                 return false;
556
557         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
558         {
559                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
560                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
561                 {
562                         return true;
563                 }
564         }
565
566         return false;
567 }
568
569 void KLine::Apply(User* u)
570 {
571         DefaultApply(u, "K", (this->identmask ==  "*") ? true : false);
572 }
573
574 bool GLine::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->host, 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 GLine::Apply(User* u)
593 {
594         DefaultApply(u, "G", (this->identmask == "*") ? true : false);
595 }
596
597 bool ELine::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->host, 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 bool ZLine::Matches(User *u)
616 {
617         LocalUser* lu = IS_LOCAL(u);
618         if (lu && lu->exempt)
619                 return false;
620
621         if (InspIRCd::MatchCIDR(u->GetIPString(), this->ipaddr))
622                 return true;
623         else
624                 return false;
625 }
626
627 void ZLine::Apply(User* u)
628 {
629         DefaultApply(u, "Z", true);
630 }
631
632
633 bool QLine::Matches(User *u)
634 {
635         if (InspIRCd::Match(u->nick, this->nick))
636                 return true;
637
638         return false;
639 }
640
641 void QLine::Apply(User* u)
642 {
643         /* Force to uuid on apply of qline, no need to disconnect any more :) */
644         u->ForceNickChange(u->uuid);
645 }
646
647
648 bool ZLine::Matches(const std::string &str)
649 {
650         if (InspIRCd::MatchCIDR(str, this->ipaddr))
651                 return true;
652         else
653                 return false;
654 }
655
656 bool QLine::Matches(const std::string &str)
657 {
658         if (InspIRCd::Match(str, this->nick))
659                 return true;
660
661         return false;
662 }
663
664 bool ELine::Matches(const std::string &str)
665 {
666         return (InspIRCd::MatchCIDR(str, matchtext));
667 }
668
669 bool KLine::Matches(const std::string &str)
670 {
671         return (InspIRCd::MatchCIDR(str.c_str(), matchtext));
672 }
673
674 bool GLine::Matches(const std::string &str)
675 {
676         return (InspIRCd::MatchCIDR(str, matchtext));
677 }
678
679 void ELine::OnAdd()
680 {
681         /* When adding one eline, only check the one eline */
682         for (LocalUserList::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
683         {
684                 LocalUser* u = *u2;
685                 if (this->Matches(u))
686                         u->exempt = true;
687         }
688 }
689
690 void XLine::DisplayExpiry()
691 {
692         bool onechar = (type.length() == 1);
693         ServerInstance->SNO->WriteToSnoMask('x', "Removing expired %s%s %s (set by %s %ld seconds ago)",
694                 type.c_str(), (onechar ? "-Line" : ""), Displayable().c_str(), source.c_str(), (long)(ServerInstance->Time() - set_time));
695 }
696
697 const std::string& ELine::Displayable()
698 {
699         return matchtext;
700 }
701
702 const std::string& KLine::Displayable()
703 {
704         return matchtext;
705 }
706
707 const std::string& GLine::Displayable()
708 {
709         return matchtext;
710 }
711
712 const std::string& ZLine::Displayable()
713 {
714         return ipaddr;
715 }
716
717 const std::string& QLine::Displayable()
718 {
719         return nick;
720 }
721
722 bool KLine::IsBurstable()
723 {
724         return false;
725 }
726
727 bool XLineManager::RegisterFactory(XLineFactory* xlf)
728 {
729         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
730
731         if (n != line_factory.end())
732                 return false;
733
734         line_factory[xlf->GetType()] = xlf;
735
736         return true;
737 }
738
739 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
740 {
741         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
742
743         if (n == line_factory.end())
744                 return false;
745
746         line_factory.erase(n);
747
748         return true;
749 }
750
751 XLineFactory* XLineManager::GetFactory(const std::string &type)
752 {
753         XLineFactMap::iterator n = line_factory.find(type);
754
755         if (n == line_factory.end())
756                 return NULL;
757
758         return n->second;
759 }