]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/xline.cpp
Fix mistakenly using Clang instead of GCC on older FreeBSD versions.
[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
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.clear();
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         if (line->duration && ServerInstance->Time() > line->expiry)
256                 return false; // Don't apply expired XLines.
257
258         /* Don't apply duplicate xlines */
259         ContainerIter x = lookup_lines.find(line->type);
260         if (x != lookup_lines.end())
261         {
262                 LookupIter i = x->second.find(line->Displayable());
263                 if (i != x->second.end())
264                 {
265                         // XLine propagation bug was here, if the line to be added already exists and
266                         // it's expired then expire it and add the new one instead of returning false
267                         if ((!i->second->duration) || (ServerInstance->Time() < i->second->expiry))
268                                 return false;
269
270                         ExpireLine(x, i);
271                 }
272         }
273
274         /*ELine* item = new ELine(ServerInstance->Time(), duration, source, reason, ih.first.c_str(), ih.second.c_str());*/
275         XLineFactory* xlf = GetFactory(line->type);
276         if (!xlf)
277                 return false;
278
279         ServerInstance->BanCache->RemoveEntries(line->type, false); // XXX perhaps remove ELines here?
280
281         if (xlf->AutoApplyToUserList(line))
282                 pending_lines.push_back(line);
283
284         lookup_lines[line->type][line->Displayable()] = line;
285         line->OnAdd();
286
287         FOREACH_MOD(I_OnAddLine,OnAddLine(user, line));
288
289         return true;
290 }
291
292 // deletes a line, returns true if the line existed and was removed
293
294 bool XLineManager::DelLine(const char* hostmask, const std::string &type, User* user, bool simulate)
295 {
296         ContainerIter x = lookup_lines.find(type);
297
298         if (x == lookup_lines.end())
299                 return false;
300
301         LookupIter y = x->second.find(hostmask);
302
303         if (y == x->second.end())
304                 return false;
305
306         if (simulate)
307                 return true;
308
309         ServerInstance->BanCache->RemoveEntries(y->second->type, true);
310
311         FOREACH_MOD(I_OnDelLine,OnDelLine(user, y->second));
312
313         y->second->Unset();
314
315         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), y->second);
316         if (pptr != pending_lines.end())
317                 pending_lines.erase(pptr);
318
319         delete y->second;
320         x->second.erase(y);
321
322         return true;
323 }
324
325
326 void ELine::Unset()
327 {
328         /* remove exempt from everyone and force recheck after deleting eline */
329         for (LocalUserList::const_iterator u2 = ServerInstance->Users->local_users.begin(); u2 != ServerInstance->Users->local_users.end(); u2++)
330         {
331                 User* u = (User*)(*u2);
332                 u->exempt = false;
333         }
334
335         ServerInstance->XLines->CheckELines();
336 }
337
338 // returns a pointer to the reason if a nickname matches a qline, NULL if it didnt match
339
340 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
341 {
342         ContainerIter x = lookup_lines.find(type);
343
344         if (x == lookup_lines.end())
345                 return NULL;
346
347         const time_t current = ServerInstance->Time();
348
349         LookupIter safei;
350
351         for (LookupIter i = x->second.begin(); i != x->second.end(); )
352         {
353                 safei = i;
354                 safei++;
355
356                 if (i->second->duration && current > i->second->expiry)
357                 {
358                         /* Expire the line, proceed to next one */
359                         ExpireLine(x, i);
360                         i = safei;
361                         continue;
362                 }
363
364                 if (i->second->Matches(user))
365                 {
366                         return i->second;
367                 }
368
369                 i = safei;
370         }
371         return NULL;
372 }
373
374 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
375 {
376         ContainerIter x = lookup_lines.find(type);
377
378         if (x == lookup_lines.end())
379                 return NULL;
380
381         const time_t current = ServerInstance->Time();
382
383          LookupIter safei;
384
385         for (LookupIter i = x->second.begin(); i != x->second.end(); )
386         {
387                 safei = i;
388                 safei++;
389
390                 if (i->second->Matches(pattern))
391                 {
392                         if (i->second->duration && current > i->second->expiry)
393                         {
394                                 /* Expire the line, return nothing */
395                                 ExpireLine(x, i);
396                                 /* See above */
397                                 i = safei;
398                                 continue;
399                         }
400                         else
401                                 return i->second;
402                 }
403
404                 i = safei;
405         }
406         return NULL;
407 }
408
409 // removes lines that have expired
410 void XLineManager::ExpireLine(ContainerIter container, LookupIter item)
411 {
412         FOREACH_MOD(I_OnExpireLine, OnExpireLine(item->second));
413
414         item->second->DisplayExpiry();
415         item->second->Unset();
416
417         /* TODO: Can we skip this loop by having a 'pending' field in the XLine class, which is set when a line
418          * is pending, cleared when it is no longer pending, so we skip over this loop if its not pending?
419          * -- Brain
420          */
421         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), item->second);
422         if (pptr != pending_lines.end())
423                 pending_lines.erase(pptr);
424
425         delete item->second;
426         container->second.erase(item);
427 }
428
429
430 // applies lines, removing clients and changing nicks etc as applicable
431 void XLineManager::ApplyLines()
432 {
433         LocalUserList::reverse_iterator u2 = ServerInstance->Users->local_users.rbegin();
434         while (u2 != ServerInstance->Users->local_users.rend())
435         {
436                 User* u = *u2++;
437
438                 // Don't ban people who are exempt.
439                 if (u->exempt)
440                         continue;
441
442                 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
443                 {
444                         XLine *x = *i;
445                         if (x->Matches(u))
446                                 x->Apply(u);
447                 }
448         }
449
450         pending_lines.clear();
451 }
452
453 void XLineManager::InvokeStats(const std::string &type, int numeric, User* user, string_list &results)
454 {
455         ContainerIter n = lookup_lines.find(type);
456
457         time_t current = ServerInstance->Time();
458
459         LookupIter safei;
460
461         if (n != lookup_lines.end())
462         {
463                 XLineLookup& list = n->second;
464                 for (LookupIter i = list.begin(); i != list.end(); )
465                 {
466                         safei = i;
467                         safei++;
468
469                         if (i->second->duration && current > i->second->expiry)
470                         {
471                                 ExpireLine(n, i);
472                         }
473                         else
474                                 results.push_back(ServerInstance->Config->ServerName+" "+ConvToStr(numeric)+" "+user->nick+" :"+i->second->Displayable()+" "+
475                                         ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+i->second->source+" :"+i->second->reason);
476                         i = safei;
477                 }
478         }
479 }
480
481
482 XLineManager::XLineManager()
483 {
484         GLineFactory* GFact;
485         ELineFactory* EFact;
486         KLineFactory* KFact;
487         QLineFactory* QFact;
488         ZLineFactory* ZFact;
489
490
491         GFact = new GLineFactory;
492         EFact = new ELineFactory;
493         KFact = new KLineFactory;
494         QFact = new QLineFactory;
495         ZFact = new ZLineFactory;
496
497         RegisterFactory(GFact);
498         RegisterFactory(EFact);
499         RegisterFactory(KFact);
500         RegisterFactory(QFact);
501         RegisterFactory(ZFact);
502 }
503
504 XLineManager::~XLineManager()
505 {
506         const char gekqz[] = "GEKQZ";
507         for(unsigned int i=0; i < sizeof(gekqz); i++)
508         {
509                 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
510                 delete xlf;
511         }
512
513         // Delete all existing XLines
514         for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
515         {
516                 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
517                 {
518                         delete j->second;
519                 }
520         }
521 }
522
523 void XLine::Apply(User* u)
524 {
525 }
526
527 bool XLine::IsBurstable()
528 {
529         return true;
530 }
531
532 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
533 {
534         char sreason[MAXBUF];
535         snprintf(sreason, MAXBUF, "%s-Lined: %s", line.c_str(), this->reason.c_str());
536         if (!ServerInstance->Config->MoronBanner.empty())
537                 u->WriteServ("NOTICE %s :*** %s", u->nick.c_str(), ServerInstance->Config->MoronBanner.c_str());
538
539         if (ServerInstance->Config->HideBans)
540                 ServerInstance->Users->QuitUser(u, line + "-Lined", sreason);
541         else
542                 ServerInstance->Users->QuitUser(u, sreason);
543
544
545         if (bancache)
546         {
547                 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
548                 if (this->duration > 0)
549                         ServerInstance->BanCache->AddHit(u->GetIPString(), this->type, line + "-Lined: " + this->reason, this->duration);
550                 else
551                         ServerInstance->BanCache->AddHit(u->GetIPString(), this->type, line + "-Lined: " + this->reason);
552         }
553 }
554
555 bool KLine::Matches(User *u)
556 {
557         if (u->exempt)
558                 return false;
559
560         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
561         {
562                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
563                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
564                 {
565                         return true;
566                 }
567         }
568
569         return false;
570 }
571
572 void KLine::Apply(User* u)
573 {
574         DefaultApply(u, "K", (this->identmask ==  "*") ? true : false);
575 }
576
577 bool GLine::Matches(User *u)
578 {
579         if (u->exempt)
580                 return false;
581
582         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
583         {
584                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
585                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
586                 {
587                         return true;
588                 }
589         }
590
591         return false;
592 }
593
594 void GLine::Apply(User* u)
595 {
596         DefaultApply(u, "G", (this->identmask == "*") ? true : false);
597 }
598
599 bool ELine::Matches(User *u)
600 {
601         if (u->exempt)
602                 return false;
603
604         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
605         {
606                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
607                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
608                 {
609                         return true;
610                 }
611         }
612
613         return false;
614 }
615
616 bool ZLine::Matches(User *u)
617 {
618         if (u->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.c_str());
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                 User* u = (User*)(*u2);
685                 if (this->Matches(u))
686                         u->exempt = true;
687         }
688 }
689
690 void ELine::DisplayExpiry()
691 {
692         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired E-Line %s@%s (set by %s %ld seconds ago)",
693                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
694 }
695
696 void QLine::DisplayExpiry()
697 {
698         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired Q-Line %s (set by %s %ld seconds ago)",
699                 nick.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
700 }
701
702 void ZLine::DisplayExpiry()
703 {
704         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired Z-Line %s (set by %s %ld seconds ago)",
705                 ipaddr.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
706 }
707
708 void KLine::DisplayExpiry()
709 {
710         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired K-Line %s@%s (set by %s %ld seconds ago)",
711                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
712 }
713
714 void GLine::DisplayExpiry()
715 {
716         ServerInstance->SNO->WriteToSnoMask('x',"Removing expired G-Line %s@%s (set by %s %ld seconds ago)",
717                 identmask.c_str(),hostmask.c_str(),source.c_str(),(long)(ServerInstance->Time() - this->set_time));
718 }
719
720 const char* ELine::Displayable()
721 {
722         return matchtext.c_str();
723 }
724
725 const char* KLine::Displayable()
726 {
727         return matchtext.c_str();
728 }
729
730 const char* GLine::Displayable()
731 {
732         return matchtext.c_str();
733 }
734
735 const char* ZLine::Displayable()
736 {
737         return ipaddr.c_str();
738 }
739
740 const char* QLine::Displayable()
741 {
742         return nick.c_str();
743 }
744
745 bool KLine::IsBurstable()
746 {
747         return false;
748 }
749
750 bool XLineManager::RegisterFactory(XLineFactory* xlf)
751 {
752         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
753
754         if (n != line_factory.end())
755                 return false;
756
757         line_factory[xlf->GetType()] = xlf;
758
759         return true;
760 }
761
762 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
763 {
764         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
765
766         if (n == line_factory.end())
767                 return false;
768
769         line_factory.erase(n);
770
771         return true;
772 }
773
774 XLineFactory* XLineManager::GetFactory(const std::string &type)
775 {
776         XLineFactMap::iterator n = line_factory.find(type);
777
778         if (n == line_factory.end())
779                 return NULL;
780
781         return n->second;
782 }