]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/xline.cpp
Merge pull request #1359 from genius3000/insp20+sasl_no_server
[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 "bancache.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, long duration, std::string source, std::string reason, std::string xline_specific_mask)
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, long duration, std::string source, std::string reason, std::string xline_specific_mask)
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, long duration, std::string source, std::string reason, std::string xline_specific_mask)
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, long duration, std::string source, std::string reason, std::string xline_specific_mask)
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, long duration, std::string source, std::string reason, std::string xline_specific_mask)
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         for (LocalUserList::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
160         {
161                 User* u = (User*)(*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(I_OnAddLine,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(I_OnDelLine,OnDelLine(user, y->second));
314
315         y->second->Unset();
316
317         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), y->second);
318         if (pptr != pending_lines.end())
319                 pending_lines.erase(pptr);
320
321         delete y->second;
322         x->second.erase(y);
323
324         return true;
325 }
326
327
328 void ELine::Unset()
329 {
330         ServerInstance->XLines->CheckELines();
331 }
332
333 // returns a pointer to the reason if a nickname matches a qline, NULL if it didnt match
334
335 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
336 {
337         ContainerIter x = lookup_lines.find(type);
338
339         if (x == lookup_lines.end())
340                 return NULL;
341
342         const time_t current = ServerInstance->Time();
343
344         LookupIter safei;
345
346         for (LookupIter i = x->second.begin(); i != x->second.end(); )
347         {
348                 safei = i;
349                 safei++;
350
351                 if (i->second->duration && current > i->second->expiry)
352                 {
353                         /* Expire the line, proceed to next one */
354                         ExpireLine(x, i);
355                         i = safei;
356                         continue;
357                 }
358
359                 if (i->second->Matches(user))
360                 {
361                         return i->second;
362                 }
363
364                 i = safei;
365         }
366         return NULL;
367 }
368
369 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
370 {
371         ContainerIter x = lookup_lines.find(type);
372
373         if (x == lookup_lines.end())
374                 return NULL;
375
376         const time_t current = ServerInstance->Time();
377
378          LookupIter safei;
379
380         for (LookupIter i = x->second.begin(); i != x->second.end(); )
381         {
382                 safei = i;
383                 safei++;
384
385                 if (i->second->Matches(pattern))
386                 {
387                         if (i->second->duration && current > i->second->expiry)
388                         {
389                                 /* Expire the line, return nothing */
390                                 ExpireLine(x, i);
391                                 /* See above */
392                                 i = safei;
393                                 continue;
394                         }
395                         else
396                                 return i->second;
397                 }
398
399                 i = safei;
400         }
401         return NULL;
402 }
403
404 // removes lines that have expired
405 void XLineManager::ExpireLine(ContainerIter container, LookupIter item)
406 {
407         FOREACH_MOD(I_OnExpireLine, OnExpireLine(item->second));
408
409         item->second->DisplayExpiry();
410         item->second->Unset();
411
412         /* TODO: Can we skip this loop by having a 'pending' field in the XLine class, which is set when a line
413          * is pending, cleared when it is no longer pending, so we skip over this loop if its not pending?
414          * -- Brain
415          */
416         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), item->second);
417         if (pptr != pending_lines.end())
418                 pending_lines.erase(pptr);
419
420         delete item->second;
421         container->second.erase(item);
422 }
423
424
425 // applies lines, removing clients and changing nicks etc as applicable
426 void XLineManager::ApplyLines()
427 {
428         LocalUserList::reverse_iterator u2 = ServerInstance->Users->local_users.rbegin();
429         while (u2 != ServerInstance->Users->local_users.rend())
430         {
431                 User* u = *u2++;
432
433                 // Don't ban people who are exempt.
434                 if (u->exempt)
435                         continue;
436
437                 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
438                 {
439                         XLine *x = *i;
440                         if (x->Matches(u))
441                                 x->Apply(u);
442                 }
443         }
444
445         pending_lines.clear();
446 }
447
448 void XLineManager::InvokeStats(const std::string &type, int numeric, User* user, string_list &results)
449 {
450         ContainerIter n = lookup_lines.find(type);
451
452         time_t current = ServerInstance->Time();
453
454         LookupIter safei;
455
456         if (n != lookup_lines.end())
457         {
458                 XLineLookup& list = n->second;
459                 for (LookupIter i = list.begin(); i != list.end(); )
460                 {
461                         safei = i;
462                         safei++;
463
464                         if (i->second->duration && current > i->second->expiry)
465                         {
466                                 ExpireLine(n, i);
467                         }
468                         else
469                                 results.push_back(ServerInstance->Config->ServerName+" "+ConvToStr(numeric)+" "+user->nick+" :"+i->second->Displayable()+" "+
470                                         ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+i->second->source+" :"+i->second->reason);
471                         i = safei;
472                 }
473         }
474 }
475
476
477 XLineManager::XLineManager()
478 {
479         GLineFactory* GFact;
480         ELineFactory* EFact;
481         KLineFactory* KFact;
482         QLineFactory* QFact;
483         ZLineFactory* ZFact;
484
485
486         GFact = new GLineFactory;
487         EFact = new ELineFactory;
488         KFact = new KLineFactory;
489         QFact = new QLineFactory;
490         ZFact = new ZLineFactory;
491
492         RegisterFactory(GFact);
493         RegisterFactory(EFact);
494         RegisterFactory(KFact);
495         RegisterFactory(QFact);
496         RegisterFactory(ZFact);
497 }
498
499 XLineManager::~XLineManager()
500 {
501         const char gekqz[] = "GEKQZ";
502         for(unsigned int i=0; i < sizeof(gekqz); i++)
503         {
504                 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
505                 delete xlf;
506         }
507
508         // Delete all existing XLines
509         for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
510         {
511                 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
512                 {
513                         delete j->second;
514                 }
515         }
516 }
517
518 void XLine::Apply(User* u)
519 {
520 }
521
522 bool XLine::IsBurstable()
523 {
524         return true;
525 }
526
527 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
528 {
529         char sreason[MAXBUF];
530         snprintf(sreason, MAXBUF, "%s-Lined: %s", line.c_str(), this->reason.c_str());
531         if (!ServerInstance->Config->MoronBanner.empty())
532                 u->WriteServ("NOTICE %s :*** %s", u->nick.c_str(), ServerInstance->Config->MoronBanner.c_str());
533
534         if (ServerInstance->Config->HideBans)
535                 ServerInstance->Users->QuitUser(u, line + "-Lined", sreason);
536         else
537                 ServerInstance->Users->QuitUser(u, sreason);
538
539
540         if (bancache)
541         {
542                 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
543                 if (this->duration > 0)
544                         ServerInstance->BanCache->AddHit(u->GetIPString(), this->type, line + "-Lined: " + this->reason, this->duration);
545                 else
546                         ServerInstance->BanCache->AddHit(u->GetIPString(), this->type, line + "-Lined: " + this->reason);
547         }
548 }
549
550 bool KLine::Matches(User *u)
551 {
552         if (u->exempt)
553                 return false;
554
555         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
556         {
557                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
558                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
559                 {
560                         return true;
561                 }
562         }
563
564         return false;
565 }
566
567 void KLine::Apply(User* u)
568 {
569         DefaultApply(u, "K", (this->identmask ==  "*") ? true : false);
570 }
571
572 bool GLine::Matches(User *u)
573 {
574         if (u->exempt)
575                 return false;
576
577         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
578         {
579                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
580                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
581                 {
582                         return true;
583                 }
584         }
585
586         return false;
587 }
588
589 void GLine::Apply(User* u)
590 {
591         DefaultApply(u, "G", (this->identmask == "*") ? true : false);
592 }
593
594 bool ELine::Matches(User *u)
595 {
596         if (u->exempt)
597                 return false;
598
599         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
600         {
601                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
602                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
603                 {
604                         return true;
605                 }
606         }
607
608         return false;
609 }
610
611 bool ZLine::Matches(User *u)
612 {
613         if (u->exempt)
614                 return false;
615
616         if (InspIRCd::MatchCIDR(u->GetIPString(), this->ipaddr))
617                 return true;
618         else
619                 return false;
620 }
621
622 void ZLine::Apply(User* u)
623 {
624         DefaultApply(u, "Z", true);
625 }
626
627
628 bool QLine::Matches(User *u)
629 {
630         if (InspIRCd::Match(u->nick, this->nick))
631                 return true;
632
633         return false;
634 }
635
636 void QLine::Apply(User* u)
637 {
638         /* Force to uuid on apply of qline, no need to disconnect any more :) */
639         u->ForceNickChange(u->uuid.c_str());
640 }
641
642
643 bool ZLine::Matches(const std::string &str)
644 {
645         if (InspIRCd::MatchCIDR(str, this->ipaddr))
646                 return true;
647         else
648                 return false;
649 }
650
651 bool QLine::Matches(const std::string &str)
652 {
653         if (InspIRCd::Match(str, this->nick))
654                 return true;
655
656         return false;
657 }
658
659 bool ELine::Matches(const std::string &str)
660 {
661         return (InspIRCd::MatchCIDR(str, matchtext));
662 }
663
664 bool KLine::Matches(const std::string &str)
665 {
666         return (InspIRCd::MatchCIDR(str.c_str(), matchtext));
667 }
668
669 bool GLine::Matches(const std::string &str)
670 {
671         return (InspIRCd::MatchCIDR(str, matchtext));
672 }
673
674 void ELine::OnAdd()
675 {
676         /* When adding one eline, only check the one eline */
677         for (LocalUserList::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
678         {
679                 User* u = (User*)(*u2);
680                 if (this->Matches(u))
681                         u->exempt = true;
682         }
683 }
684
685 void ELine::DisplayExpiry()
686 {
687         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired E-Line %s@%s (set by %s %ld seconds ago)",
688                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
689 }
690
691 void QLine::DisplayExpiry()
692 {
693         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired Q-Line %s (set by %s %ld seconds ago)",
694                 nick.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
695 }
696
697 void ZLine::DisplayExpiry()
698 {
699         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired Z-Line %s (set by %s %ld seconds ago)",
700                 ipaddr.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
701 }
702
703 void KLine::DisplayExpiry()
704 {
705         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired K-Line %s@%s (set by %s %ld seconds ago)",
706                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
707 }
708
709 void GLine::DisplayExpiry()
710 {
711         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired G-Line %s@%s (set by %s %ld seconds ago)",
712                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
713 }
714
715 const char* ELine::Displayable()
716 {
717         return matchtext.c_str();
718 }
719
720 const char* KLine::Displayable()
721 {
722         return matchtext.c_str();
723 }
724
725 const char* GLine::Displayable()
726 {
727         return matchtext.c_str();
728 }
729
730 const char* ZLine::Displayable()
731 {
732         return ipaddr.c_str();
733 }
734
735 const char* QLine::Displayable()
736 {
737         return nick.c_str();
738 }
739
740 bool KLine::IsBurstable()
741 {
742         return false;
743 }
744
745 bool XLineManager::RegisterFactory(XLineFactory* xlf)
746 {
747         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
748
749         if (n != line_factory.end())
750                 return false;
751
752         line_factory[xlf->GetType()] = xlf;
753
754         return true;
755 }
756
757 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
758 {
759         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
760
761         if (n == line_factory.end())
762                 return false;
763
764         line_factory.erase(n);
765
766         return true;
767 }
768
769 XLineFactory* XLineManager::GetFactory(const std::string &type)
770 {
771         XLineFactMap::iterator n = line_factory.find(type);
772
773         if (n == line_factory.end())
774                 return NULL;
775
776         return n->second;
777 }