]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/xline.cpp
Merge pull request #96 from Justasic/insp20
[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 (std::vector<LocalUser*>::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
160         {
161                 User* u = (User*)(*u2);
162
163                 /* This uses safe iteration to ensure that if a line expires here, it doenst trash the iterator */
164                 LookupIter safei;
165
166                 for (LookupIter i = ELines.begin(); i != ELines.end(); )
167                 {
168                         safei = i;
169                         safei++;
170
171                         XLine *e = i->second;
172                         u->exempt = e->Matches(u);
173
174                         i = safei;
175                 }
176         }
177 }
178
179
180 XLineLookup* XLineManager::GetAll(const std::string &type)
181 {
182         ContainerIter n = lookup_lines.find(type);
183
184         if (n == lookup_lines.end())
185                 return NULL;
186
187         LookupIter safei;
188         const time_t current = ServerInstance->Time();
189
190         /* Expire any dead ones, before sending */
191         for (LookupIter x = n->second.begin(); x != n->second.end(); )
192         {
193                 safei = x;
194                 safei++;
195                 if (x->second->duration && current > x->second->expiry)
196                 {
197                         ExpireLine(n, x);
198                 }
199                 x = safei;
200         }
201
202         return &(n->second);
203 }
204
205 void XLineManager::DelAll(const std::string &type)
206 {
207         ContainerIter n = lookup_lines.find(type);
208
209         if (n == lookup_lines.end())
210                 return;
211
212         LookupIter x;
213
214         /* Delete all of a given type (this should probably use DelLine, but oh well) */
215         while ((x = n->second.begin()) != n->second.end())
216         {
217                 ExpireLine(n, x);
218         }
219 }
220
221 std::vector<std::string> XLineManager::GetAllTypes()
222 {
223         std::vector<std::string> items;
224         for (ContainerIter x = lookup_lines.begin(); x != lookup_lines.end(); ++x)
225                 items.push_back(x->first);
226         return items;
227 }
228
229 IdentHostPair XLineManager::IdentSplit(const std::string &ident_and_host)
230 {
231         IdentHostPair n = std::make_pair<std::string,std::string>("*","*");
232         std::string::size_type x = ident_and_host.find('@');
233         if (x != std::string::npos)
234         {
235                 n.second = ident_and_host.substr(x + 1,ident_and_host.length());
236                 n.first = ident_and_host.substr(0, x);
237                 if (!n.first.length())
238                         n.first.assign("*");
239                 if (!n.second.length())
240                         n.second.assign("*");
241         }
242         else
243         {
244                 n.first = "";
245                 n.second = ident_and_host;
246         }
247
248         return n;
249 }
250
251 // adds a line
252
253 bool XLineManager::AddLine(XLine* line, User* user)
254 {
255         ServerInstance->BanCache->RemoveEntries(line->type, false); // XXX perhaps remove ELines here?
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                         return false;
268                 }
269         }
270
271         /*ELine* item = new ELine(ServerInstance->Time(), duration, source, reason, ih.first.c_str(), ih.second.c_str());*/
272         XLineFactory* xlf = GetFactory(line->type);
273         if (!xlf)
274                 return false;
275
276         if (xlf->AutoApplyToUserList(line))
277                 pending_lines.push_back(line);
278
279         lookup_lines[line->type][line->Displayable()] = line;
280         line->OnAdd();
281
282         FOREACH_MOD(I_OnAddLine,OnAddLine(user, line));
283
284         return true;
285 }
286
287 // deletes a line, returns true if the line existed and was removed
288
289 bool XLineManager::DelLine(const char* hostmask, const std::string &type, User* user, bool simulate)
290 {
291         ContainerIter x = lookup_lines.find(type);
292
293         if (x == lookup_lines.end())
294                 return false;
295
296         LookupIter y = x->second.find(hostmask);
297
298         if (y == x->second.end())
299                 return false;
300
301         if (simulate)
302                 return true;
303
304         ServerInstance->BanCache->RemoveEntries(y->second->type, true);
305
306         FOREACH_MOD(I_OnDelLine,OnDelLine(user, y->second));
307
308         y->second->Unset();
309
310         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), y->second);
311         if (pptr != pending_lines.end())
312                 pending_lines.erase(pptr);
313
314         delete y->second;
315         x->second.erase(y);
316
317         return true;
318 }
319
320
321 void ELine::Unset()
322 {
323         /* remove exempt from everyone and force recheck after deleting eline */
324         for (std::vector<LocalUser*>::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
325         {
326                 User* u = (User*)(*u2);
327                 u->exempt = false;
328         }
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         std::vector<LocalUser*>::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         std::string sn = ServerInstance->Config->ServerName;
451
452         ContainerIter n = lookup_lines.find(type);
453
454         time_t current = ServerInstance->Time();
455
456         LookupIter safei;
457
458         if (n != lookup_lines.end())
459         {
460                 XLineLookup& list = n->second;
461                 for (LookupIter i = list.begin(); i != list.end(); )
462                 {
463                         safei = i;
464                         safei++;
465
466                         if (i->second->duration && current > i->second->expiry)
467                         {
468                                 ExpireLine(n, i);
469                         }
470                         else
471                                 results.push_back(sn+" "+ConvToStr(numeric)+" "+user->nick+" :"+i->second->Displayable()+" "+
472                                         ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+std::string(i->second->source)+" :"+(i->second->reason));
473                         i = safei;
474                 }
475         }
476 }
477
478
479 XLineManager::XLineManager()
480 {
481         GLineFactory* GFact;
482         ELineFactory* EFact;
483         KLineFactory* KFact;
484         QLineFactory* QFact;
485         ZLineFactory* ZFact;
486
487
488         GFact = new GLineFactory;
489         EFact = new ELineFactory;
490         KFact = new KLineFactory;
491         QFact = new QLineFactory;
492         ZFact = new ZLineFactory;
493
494         RegisterFactory(GFact);
495         RegisterFactory(EFact);
496         RegisterFactory(KFact);
497         RegisterFactory(QFact);
498         RegisterFactory(ZFact);
499 }
500
501 XLineManager::~XLineManager()
502 {
503         const char gekqz[] = "GEKQZ";
504         for(unsigned int i=0; i < sizeof(gekqz); i++)
505         {
506                 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
507                 if (xlf)
508                         UnregisterFactory(xlf);
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                 i->second.clear();
520         }
521         lookup_lines.clear();
522
523 }
524
525 void XLine::Apply(User* u)
526 {
527 }
528
529 bool XLine::IsBurstable()
530 {
531         return true;
532 }
533
534 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
535 {
536         char sreason[MAXBUF];
537         snprintf(sreason, MAXBUF, "%s-Lined: %s", line.c_str(), this->reason.c_str());
538         if (!ServerInstance->Config->MoronBanner.empty())
539                 u->WriteServ("NOTICE %s :*** %s", u->nick.c_str(), ServerInstance->Config->MoronBanner.c_str());
540
541         if (ServerInstance->Config->HideBans)
542                 ServerInstance->Users->QuitUser(u, line + "-Lined", sreason);
543         else
544                 ServerInstance->Users->QuitUser(u, sreason);
545
546
547         if (bancache)
548         {
549                 ServerInstance->Logs->Log("BANCACHE", DEBUG, std::string("BanCache: Adding positive hit (") + line + ") for " + u->GetIPString());
550                 if (this->duration > 0)
551                         ServerInstance->BanCache->AddHit(u->GetIPString(), this->type, line + "-Lined: " + this->reason, this->duration);
552                 else
553                         ServerInstance->BanCache->AddHit(u->GetIPString(), this->type, line + "-Lined: " + this->reason);
554         }
555 }
556
557 bool KLine::Matches(User *u)
558 {
559         if (u->exempt)
560                 return false;
561
562         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
563         {
564                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
565                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
566                 {
567                         return true;
568                 }
569         }
570
571         return false;
572 }
573
574 void KLine::Apply(User* u)
575 {
576         DefaultApply(u, "K", (this->identmask ==  "*") ? true : false);
577 }
578
579 bool GLine::Matches(User *u)
580 {
581         if (u->exempt)
582                 return false;
583
584         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
585         {
586                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
587                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
588                 {
589                         return true;
590                 }
591         }
592
593         return false;
594 }
595
596 void GLine::Apply(User* u)
597 {
598         DefaultApply(u, "G", (this->identmask == "*") ? true : false);
599 }
600
601 bool ELine::Matches(User *u)
602 {
603         if (u->exempt)
604                 return false;
605
606         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
607         {
608                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
609                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
610                 {
611                         return true;
612                 }
613         }
614
615         return false;
616 }
617
618 bool ZLine::Matches(User *u)
619 {
620         if (u->exempt)
621                 return false;
622
623         if (InspIRCd::MatchCIDR(u->GetIPString(), this->ipaddr))
624                 return true;
625         else
626                 return false;
627 }
628
629 void ZLine::Apply(User* u)
630 {
631         DefaultApply(u, "Z", true);
632 }
633
634
635 bool QLine::Matches(User *u)
636 {
637         if (InspIRCd::Match(u->nick, this->nick))
638                 return true;
639
640         return false;
641 }
642
643 void QLine::Apply(User* u)
644 {
645         /* Force to uuid on apply of qline, no need to disconnect any more :) */
646         u->ForceNickChange(u->uuid.c_str());
647 }
648
649
650 bool ZLine::Matches(const std::string &str)
651 {
652         if (InspIRCd::MatchCIDR(str, this->ipaddr))
653                 return true;
654         else
655                 return false;
656 }
657
658 bool QLine::Matches(const std::string &str)
659 {
660         if (InspIRCd::Match(str, this->nick))
661                 return true;
662
663         return false;
664 }
665
666 bool ELine::Matches(const std::string &str)
667 {
668         return (InspIRCd::MatchCIDR(str, matchtext));
669 }
670
671 bool KLine::Matches(const std::string &str)
672 {
673         return (InspIRCd::MatchCIDR(str.c_str(), matchtext));
674 }
675
676 bool GLine::Matches(const std::string &str)
677 {
678         return (InspIRCd::MatchCIDR(str, matchtext));
679 }
680
681 void ELine::OnAdd()
682 {
683         /* When adding one eline, only check the one eline */
684         for (std::vector<LocalUser*>::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
685         {
686                 User* u = (User*)(*u2);
687                 if (this->Matches(u))
688                         u->exempt = true;
689         }
690 }
691
692 void ELine::DisplayExpiry()
693 {
694         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired E-Line %s@%s (set by %s %ld seconds ago)",
695                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
696 }
697
698 void QLine::DisplayExpiry()
699 {
700         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired Q-Line %s (set by %s %ld seconds ago)",
701                 nick.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
702 }
703
704 void ZLine::DisplayExpiry()
705 {
706         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired Z-Line %s (set by %s %ld seconds ago)",
707                 ipaddr.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
708 }
709
710 void KLine::DisplayExpiry()
711 {
712         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired K-Line %s@%s (set by %s %ld seconds ago)",
713                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
714 }
715
716 void GLine::DisplayExpiry()
717 {
718         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired G-Line %s@%s (set by %s %ld seconds ago)",
719                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
720 }
721
722 const char* ELine::Displayable()
723 {
724         return matchtext.c_str();
725 }
726
727 const char* KLine::Displayable()
728 {
729         return matchtext.c_str();
730 }
731
732 const char* GLine::Displayable()
733 {
734         return matchtext.c_str();
735 }
736
737 const char* ZLine::Displayable()
738 {
739         return ipaddr.c_str();
740 }
741
742 const char* QLine::Displayable()
743 {
744         return nick.c_str();
745 }
746
747 bool KLine::IsBurstable()
748 {
749         return false;
750 }
751
752 bool XLineManager::RegisterFactory(XLineFactory* xlf)
753 {
754         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
755
756         if (n != line_factory.end())
757                 return false;
758
759         line_factory[xlf->GetType()] = xlf;
760
761         return true;
762 }
763
764 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
765 {
766         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
767
768         if (n == line_factory.end())
769                 return false;
770
771         line_factory.erase(n);
772
773         return true;
774 }
775
776 XLineFactory* XLineManager::GetFactory(const std::string &type)
777 {
778         XLineFactMap::iterator n = line_factory.find(type);
779
780         if (n == line_factory.end())
781                 return NULL;
782
783         return n->second;
784 }