]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/xline.cpp
Fix off by one in ping timeout.
[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         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
159         for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
160         {
161                 LocalUser* u = *u2;
162
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().c_str());
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().c_str()] = line;
285         line->OnAdd();
286
287         FOREACH_MOD(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(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         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
330         for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
331         {
332                 LocalUser* u = *u2;
333                 u->exempt = false;
334         }
335
336         ServerInstance->XLines->CheckELines();
337 }
338
339 // returns a pointer to the reason if a nickname matches a qline, NULL if it didnt match
340
341 XLine* XLineManager::MatchesLine(const std::string &type, User* user)
342 {
343         ContainerIter x = lookup_lines.find(type);
344
345         if (x == lookup_lines.end())
346                 return NULL;
347
348         const time_t current = ServerInstance->Time();
349
350         LookupIter safei;
351
352         for (LookupIter i = x->second.begin(); i != x->second.end(); )
353         {
354                 safei = i;
355                 safei++;
356
357                 if (i->second->duration && current > i->second->expiry)
358                 {
359                         /* Expire the line, proceed to next one */
360                         ExpireLine(x, i);
361                         i = safei;
362                         continue;
363                 }
364
365                 if (i->second->Matches(user))
366                 {
367                         return i->second;
368                 }
369
370                 i = safei;
371         }
372         return NULL;
373 }
374
375 XLine* XLineManager::MatchesLine(const std::string &type, const std::string &pattern)
376 {
377         ContainerIter x = lookup_lines.find(type);
378
379         if (x == lookup_lines.end())
380                 return NULL;
381
382         const time_t current = ServerInstance->Time();
383
384          LookupIter safei;
385
386         for (LookupIter i = x->second.begin(); i != x->second.end(); )
387         {
388                 safei = i;
389                 safei++;
390
391                 if (i->second->Matches(pattern))
392                 {
393                         if (i->second->duration && current > i->second->expiry)
394                         {
395                                 /* Expire the line, return nothing */
396                                 ExpireLine(x, i);
397                                 /* See above */
398                                 i = safei;
399                                 continue;
400                         }
401                         else
402                                 return i->second;
403                 }
404
405                 i = safei;
406         }
407         return NULL;
408 }
409
410 // removes lines that have expired
411 void XLineManager::ExpireLine(ContainerIter container, LookupIter item)
412 {
413         FOREACH_MOD(OnExpireLine, (item->second));
414
415         item->second->DisplayExpiry();
416         item->second->Unset();
417
418         /* TODO: Can we skip this loop by having a 'pending' field in the XLine class, which is set when a line
419          * is pending, cleared when it is no longer pending, so we skip over this loop if its not pending?
420          * -- Brain
421          */
422         std::vector<XLine*>::iterator pptr = std::find(pending_lines.begin(), pending_lines.end(), item->second);
423         if (pptr != pending_lines.end())
424                 pending_lines.erase(pptr);
425
426         delete item->second;
427         container->second.erase(item);
428 }
429
430
431 // applies lines, removing clients and changing nicks etc as applicable
432 void XLineManager::ApplyLines()
433 {
434         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
435         for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); ++j)
436         {
437                 LocalUser* u = *j;
438
439                 // Don't ban people who are exempt.
440                 if (u->exempt)
441                         continue;
442
443                 for (std::vector<XLine *>::iterator i = pending_lines.begin(); i != pending_lines.end(); i++)
444                 {
445                         XLine *x = *i;
446                         if (x->Matches(u))
447                                 x->Apply(u);
448                 }
449         }
450
451         pending_lines.clear();
452 }
453
454 void XLineManager::InvokeStats(const std::string &type, int numeric, User* user, string_list &results)
455 {
456         ContainerIter n = lookup_lines.find(type);
457
458         time_t current = ServerInstance->Time();
459
460         LookupIter safei;
461
462         if (n != lookup_lines.end())
463         {
464                 XLineLookup& list = n->second;
465                 for (LookupIter i = list.begin(); i != list.end(); )
466                 {
467                         safei = i;
468                         safei++;
469
470                         if (i->second->duration && current > i->second->expiry)
471                         {
472                                 ExpireLine(n, i);
473                         }
474                         else
475                                 results.push_back(ConvToStr(numeric)+" "+user->nick+" :"+i->second->Displayable()+" "+
476                                         ConvToStr(i->second->set_time)+" "+ConvToStr(i->second->duration)+" "+i->second->source+" :"+i->second->reason);
477                         i = safei;
478                 }
479         }
480 }
481
482
483 XLineManager::XLineManager()
484 {
485         GLineFactory* GFact;
486         ELineFactory* EFact;
487         KLineFactory* KFact;
488         QLineFactory* QFact;
489         ZLineFactory* ZFact;
490
491
492         GFact = new GLineFactory;
493         EFact = new ELineFactory;
494         KFact = new KLineFactory;
495         QFact = new QLineFactory;
496         ZFact = new ZLineFactory;
497
498         RegisterFactory(GFact);
499         RegisterFactory(EFact);
500         RegisterFactory(KFact);
501         RegisterFactory(QFact);
502         RegisterFactory(ZFact);
503 }
504
505 XLineManager::~XLineManager()
506 {
507         const char gekqz[] = "GEKQZ";
508         for(unsigned int i=0; i < sizeof(gekqz); i++)
509         {
510                 XLineFactory* xlf = GetFactory(std::string(1, gekqz[i]));
511                 delete xlf;
512         }
513
514         // Delete all existing XLines
515         for (XLineContainer::iterator i = lookup_lines.begin(); i != lookup_lines.end(); i++)
516         {
517                 for (XLineLookup::iterator j = i->second.begin(); j != i->second.end(); j++)
518                 {
519                         delete j->second;
520                 }
521         }
522 }
523
524 void XLine::Apply(User* u)
525 {
526 }
527
528 bool XLine::IsBurstable()
529 {
530         return true;
531 }
532
533 void XLine::DefaultApply(User* u, const std::string &line, bool bancache)
534 {
535         const std::string banReason = line + "-Lined: " + reason;
536
537         if (!ServerInstance->Config->XLineMessage.empty())
538                 u->WriteNotice("*** " + ServerInstance->Config->XLineMessage);
539
540         if (ServerInstance->Config->HideBans)
541                 ServerInstance->Users->QuitUser(u, line + "-Lined", &banReason);
542         else
543                 ServerInstance->Users->QuitUser(u, banReason);
544
545
546         if (bancache)
547         {
548                 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding positive hit (" + line + ") for " + u->GetIPString());
549                 ServerInstance->BanCache.AddHit(u->GetIPString(), this->type, banReason, this->duration);
550         }
551 }
552
553 bool KLine::Matches(User *u)
554 {
555         LocalUser* lu = IS_LOCAL(u);
556         if (lu && lu->exempt)
557                 return false;
558
559         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
560         {
561                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
562                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
563                 {
564                         return true;
565                 }
566         }
567
568         return false;
569 }
570
571 void KLine::Apply(User* u)
572 {
573         DefaultApply(u, "K", (this->identmask ==  "*") ? true : false);
574 }
575
576 bool GLine::Matches(User *u)
577 {
578         LocalUser* lu = IS_LOCAL(u);
579         if (lu && lu->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         LocalUser* lu = IS_LOCAL(u);
602         if (lu && lu->exempt)
603                 return false;
604
605         if (InspIRCd::Match(u->ident, this->identmask, ascii_case_insensitive_map))
606         {
607                 if (InspIRCd::MatchCIDR(u->host, this->hostmask, ascii_case_insensitive_map) ||
608                     InspIRCd::MatchCIDR(u->GetIPString(), this->hostmask, ascii_case_insensitive_map))
609                 {
610                         return true;
611                 }
612         }
613
614         return false;
615 }
616
617 bool ZLine::Matches(User *u)
618 {
619         LocalUser* lu = IS_LOCAL(u);
620         if (lu && lu->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->ChangeNick(u->uuid);
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         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
685         for (UserManager::LocalList::const_iterator u2 = list.begin(); u2 != list.end(); u2++)
686         {
687                 LocalUser* u = *u2;
688                 if (this->Matches(u))
689                         u->exempt = true;
690         }
691 }
692
693 void XLine::DisplayExpiry()
694 {
695         bool onechar = (type.length() == 1);
696         ServerInstance->SNO->WriteToSnoMask('x', "Removing expired %s%s %s (set by %s %ld seconds ago)",
697                 type.c_str(), (onechar ? "-Line" : ""), Displayable().c_str(), source.c_str(), (long)(ServerInstance->Time() - set_time));
698 }
699
700 const std::string& ELine::Displayable()
701 {
702         return matchtext;
703 }
704
705 const std::string& KLine::Displayable()
706 {
707         return matchtext;
708 }
709
710 const std::string& GLine::Displayable()
711 {
712         return matchtext;
713 }
714
715 const std::string& ZLine::Displayable()
716 {
717         return ipaddr;
718 }
719
720 const std::string& QLine::Displayable()
721 {
722         return nick;
723 }
724
725 bool KLine::IsBurstable()
726 {
727         return false;
728 }
729
730 bool XLineManager::RegisterFactory(XLineFactory* xlf)
731 {
732         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
733
734         if (n != line_factory.end())
735                 return false;
736
737         line_factory[xlf->GetType()] = xlf;
738
739         return true;
740 }
741
742 bool XLineManager::UnregisterFactory(XLineFactory* xlf)
743 {
744         XLineFactMap::iterator n = line_factory.find(xlf->GetType());
745
746         if (n == line_factory.end())
747                 return false;
748
749         line_factory.erase(n);
750
751         return true;
752 }
753
754 XLineFactory* XLineManager::GetFactory(const std::string &type)
755 {
756         XLineFactMap::iterator n = line_factory.find(type);
757
758         if (n == line_factory.end())
759                 return NULL;
760
761         return n->second;
762 }