]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_filter.cpp
Merge branch 'insp20' into master.
[user/henk/code/inspircd.git] / src / modules / m_filter.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2004, 2008 Craig Edwards <craigedwards@brainbox.cc>
6  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
7  *   Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22
23 #include "inspircd.h"
24 #include "xline.h"
25 #include "modules/regex.h"
26 #include "modules/server.h"
27
28 enum FilterFlags
29 {
30         FLAG_PART = 2,
31         FLAG_QUIT = 4,
32         FLAG_PRIVMSG = 8,
33         FLAG_NOTICE = 16
34 };
35
36 enum FilterAction
37 {
38         FA_GLINE,
39         FA_BLOCK,
40         FA_SILENT,
41         FA_KILL,
42         FA_NONE
43 };
44
45 class FilterResult
46 {
47  public:
48         Regex* regex;
49         std::string freeform;
50         std::string reason;
51         FilterAction action;
52         long gline_time;
53
54         bool flag_no_opers;
55         bool flag_part_message;
56         bool flag_quit_message;
57         bool flag_privmsg;
58         bool flag_notice;
59         bool flag_strip_color;
60
61         FilterResult(dynamic_reference<RegexFactory>& RegexEngine, const std::string& free, const std::string& rea, FilterAction act, long gt, const std::string& fla)
62                 : freeform(free), reason(rea), action(act), gline_time(gt)
63         {
64                 if (!RegexEngine)
65                         throw ModuleException("Regex module implementing '"+RegexEngine.GetProvider()+"' is not loaded!");
66                 regex = RegexEngine->Create(free);
67                 this->FillFlags(fla);
68         }
69
70         char FillFlags(const std::string &fl)
71         {
72                 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
73                         flag_notice = flag_strip_color = false;
74
75                 for (std::string::const_iterator n = fl.begin(); n != fl.end(); ++n)
76                 {
77                         switch (*n)
78                         {
79                                 case 'o':
80                                         flag_no_opers = true;
81                                 break;
82                                 case 'P':
83                                         flag_part_message = true;
84                                 break;
85                                 case 'q':
86                                         flag_quit_message = true;
87                                 break;
88                                 case 'p':
89                                         flag_privmsg = true;
90                                 break;
91                                 case 'n':
92                                         flag_notice = true;
93                                 break;
94                                 case 'c':
95                                         flag_strip_color = true;
96                                 break;
97                                 case '*':
98                                         flag_no_opers = flag_part_message = flag_quit_message =
99                                                 flag_privmsg = flag_notice = flag_strip_color = true;
100                                 break;
101                                 default:
102                                         return *n;
103                                 break;
104                         }
105                 }
106                 return 0;
107         }
108
109         std::string GetFlags()
110         {
111                 std::string flags;
112                 if (flag_no_opers)
113                         flags.push_back('o');
114                 if (flag_part_message)
115                         flags.push_back('P');
116                 if (flag_quit_message)
117                         flags.push_back('q');
118                 if (flag_privmsg)
119                         flags.push_back('p');
120                 if (flag_notice)
121                         flags.push_back('n');
122
123                 /* Order is important here, 'c' must be the last char in the string as it is unsupported
124                  * on < 2.0.10, and the logic in FillFlags() stops parsing when it ecounters an unknown
125                  * character.
126                  */
127                 if (flag_strip_color)
128                         flags.push_back('c');
129
130                 if (flags.empty())
131                         flags.push_back('-');
132
133                 return flags;
134         }
135
136         FilterResult()
137         {
138         }
139 };
140
141 class CommandFilter : public Command
142 {
143  public:
144         CommandFilter(Module* f)
145                 : Command(f, "FILTER", 1, 5)
146         {
147                 flags_needed = 'o';
148                 this->syntax = "<filter-definition> <action> <flags> [<gline-duration>] :<reason>";
149         }
150         CmdResult Handle(const std::vector<std::string>& , User* ) CXX11_OVERRIDE;
151
152         RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) CXX11_OVERRIDE
153         {
154                 return ROUTE_BROADCAST;
155         }
156 };
157
158 class ModuleFilter : public Module, public ServerEventListener
159 {
160         typedef insp::flat_set<std::string, irc::insensitive_swo> ExemptTargetSet;
161
162         bool initing;
163         RegexFactory* factory;
164         void FreeFilters();
165
166  public:
167         CommandFilter filtcommand;
168         dynamic_reference<RegexFactory> RegexEngine;
169
170         std::vector<FilterResult> filters;
171         int flags;
172
173         // List of channel names excluded from filtering.
174         ExemptTargetSet exemptedchans;
175
176         // List of target nicknames excluded from filtering.
177         ExemptTargetSet exemptednicks;
178
179         ModuleFilter();
180         CullResult cull() CXX11_OVERRIDE;
181         ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE;
182         FilterResult* FilterMatch(User* user, const std::string &text, int flags);
183         bool DeleteFilter(const std::string &freeform);
184         std::pair<bool, std::string> AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flags);
185         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE;
186         Version GetVersion() CXX11_OVERRIDE;
187         std::string EncodeFilter(FilterResult* filter);
188         FilterResult DecodeFilter(const std::string &data);
189         void OnSyncNetwork(ProtocolInterface::Server& server) CXX11_OVERRIDE;
190         void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) CXX11_OVERRIDE;
191         ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE;
192         ModResult OnPreCommand(std::string &command, std::vector<std::string> &parameters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE;
193         void OnUnloadModule(Module* mod) CXX11_OVERRIDE;
194         bool AppliesToMe(User* user, FilterResult* filter, int flags);
195         void ReadFilters();
196         static bool StringToFilterAction(const std::string& str, FilterAction& fa);
197         static std::string FilterActionToString(FilterAction fa);
198 };
199
200 CmdResult CommandFilter::Handle(const std::vector<std::string> &parameters, User *user)
201 {
202         if (parameters.size() == 1)
203         {
204                 /* Deleting a filter */
205                 Module *me = creator;
206                 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
207                 {
208                         user->WriteNotice("*** Removed filter '" + parameters[0] + "'");
209                         ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
210                         return CMD_SUCCESS;
211                 }
212                 else
213                 {
214                         user->WriteNotice("*** Filter '" + parameters[0] + "' not found in list, try /stats s.");
215                         return CMD_FAILURE;
216                 }
217         }
218         else
219         {
220                 /* Adding a filter */
221                 if (parameters.size() >= 4)
222                 {
223                         const std::string& freeform = parameters[0];
224                         FilterAction type;
225                         const std::string& flags = parameters[2];
226                         unsigned int reasonindex;
227                         long duration = 0;
228
229                         if (!ModuleFilter::StringToFilterAction(parameters[1], type))
230                         {
231                                 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.");
232                                 return CMD_FAILURE;
233                         }
234
235                         if (type == FA_GLINE)
236                         {
237                                 if (parameters.size() >= 5)
238                                 {
239                                         duration = InspIRCd::Duration(parameters[3]);
240                                         reasonindex = 4;
241                                 }
242                                 else
243                                 {
244                                         user->WriteNotice("*** Not enough parameters: When setting a gline type filter, a gline duration must be specified as the third parameter.");
245                                         return CMD_FAILURE;
246                                 }
247                         }
248                         else
249                         {
250                                 reasonindex = 3;
251                         }
252
253                         Module *me = creator;
254                         std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
255                         if (result.first)
256                         {
257                                 user->WriteNotice("*** Added filter '" + freeform + "', type '" + parameters[1] + "'" +
258                                         (duration ? ", duration " +  parameters[3] : "") + ", flags '" + flags + "', reason: '" +
259                                         parameters[reasonindex] + "'");
260
261                                 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" added filter '"+freeform+"', type '"+parameters[1]+"', "+(duration ? "duration "+parameters[3]+", " : "")+"flags '"+flags+"', reason: "+parameters[reasonindex]);
262
263                                 return CMD_SUCCESS;
264                         }
265                         else
266                         {
267                                 user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second);
268                                 return CMD_FAILURE;
269                         }
270                 }
271                 else
272                 {
273                         user->WriteNotice("*** Not enough parameters.");
274                         return CMD_FAILURE;
275                 }
276
277         }
278 }
279
280 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
281 {
282         if ((filter->flag_no_opers) && user->IsOper())
283                 return false;
284         if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
285                 return false;
286         if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
287                 return false;
288         if ((iflags & FLAG_QUIT)   && (!filter->flag_quit_message))
289                 return false;
290         if ((iflags & FLAG_PART)   && (!filter->flag_part_message))
291                 return false;
292         return true;
293 }
294
295 ModuleFilter::ModuleFilter()
296         : ServerEventListener(this)
297         , initing(true)
298         , filtcommand(this)
299         , RegexEngine(this, "regex")
300 {
301 }
302
303 CullResult ModuleFilter::cull()
304 {
305         FreeFilters();
306         return Module::cull();
307 }
308
309 void ModuleFilter::FreeFilters()
310 {
311         for (std::vector<FilterResult>::const_iterator i = filters.begin(); i != filters.end(); ++i)
312                 delete i->regex;
313
314         filters.clear();
315 }
316
317 ModResult ModuleFilter::OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype)
318 {
319         // Leave remote users and servers alone
320         if (!IS_LOCAL(user))
321                 return MOD_RES_PASSTHRU;
322
323         flags = (msgtype == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE;
324
325         FilterResult* f = this->FilterMatch(user, text, flags);
326         if (f)
327         {
328                 std::string target;
329                 if (target_type == TYPE_USER)
330                 {
331                         User* t = (User*)dest;
332                         // Check if the target nick is exempted, if yes, ignore this message
333                         if (exemptednicks.count(t->nick))
334                                 return MOD_RES_PASSTHRU;
335
336                         target = t->nick;
337                 }
338                 else if (target_type == TYPE_CHANNEL)
339                 {
340                         Channel* t = (Channel*)dest;
341                         if (exemptedchans.count(t->name))
342                                 return MOD_RES_PASSTHRU;
343
344                         target = t->name;
345                 }
346                 if (f->action == FA_BLOCK)
347                 {
348                         ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
349                         if (target_type == TYPE_CHANNEL)
350                                 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked and opers notified (%s)", f->reason.c_str()));
351                         else
352                                 user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason);
353                 }
354                 else if (f->action == FA_SILENT)
355                 {
356                         if (target_type == TYPE_CHANNEL)
357                                 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked (%s)", f->reason.c_str()));
358                         else
359                                 user->WriteNotice("Your message to "+target+" was blocked: "+f->reason);
360                 }
361                 else if (f->action == FA_KILL)
362                 {
363                         ServerInstance->SNO->WriteGlobalSno('a', "FILTER: " + user->nick + " had their message filtered and was killed, target was " + target + ": " + f->reason);
364                         ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
365                 }
366                 else if (f->action == FA_GLINE)
367                 {
368                         GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
369                         ServerInstance->SNO->WriteGlobalSno('a', "FILTER: " + user->nick + " had their message filtered and was G-Lined, target was " + target + ": " + f->reason);
370                         if (ServerInstance->XLines->AddLine(gl,NULL))
371                         {
372                                 ServerInstance->XLines->ApplyLines();
373                         }
374                         else
375                                 delete gl;
376                 }
377
378                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
379                 return MOD_RES_DENY;
380         }
381         return MOD_RES_PASSTHRU;
382 }
383
384 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> &parameters, LocalUser *user, bool validated, const std::string &original_line)
385 {
386         if (validated)
387         {
388                 flags = 0;
389                 bool parting;
390
391                 if (command == "QUIT")
392                 {
393                         /* QUIT with no reason: nothing to do */
394                         if (parameters.size() < 1)
395                                 return MOD_RES_PASSTHRU;
396
397                         parting = false;
398                         flags = FLAG_QUIT;
399                 }
400                 else if (command == "PART")
401                 {
402                         /* PART with no reason: nothing to do */
403                         if (parameters.size() < 2)
404                                 return MOD_RES_PASSTHRU;
405
406                         if (exemptedchans.count(parameters[0]))
407                                 return MOD_RES_PASSTHRU;
408
409                         parting = true;
410                         flags = FLAG_PART;
411                 }
412                 else
413                         /* We're only messing with PART and QUIT */
414                         return MOD_RES_PASSTHRU;
415
416                 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
417                 if (!f)
418                         /* PART or QUIT reason doesnt match a filter */
419                         return MOD_RES_PASSTHRU;
420
421                 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
422                 parameters[parting ? 1 : 0] = "Reason filtered";
423
424                 /* We're blocking, OR theyre quitting and its a KILL action
425                  * (we cant kill someone whos already quitting, so filter them anyway)
426                  */
427                 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
428                 {
429                         return MOD_RES_PASSTHRU;
430                 }
431                 else
432                 {
433                         /* Are they parting, if so, kill is applicable */
434                         if ((parting) && (f->action == FA_KILL))
435                         {
436                                 user->WriteNotice("*** Your PART message was filtered: " + f->reason);
437                                 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
438                         }
439                         if (f->action == FA_GLINE)
440                         {
441                                 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
442                                 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
443                                 if (ServerInstance->XLines->AddLine(gl,NULL))
444                                 {
445                                         ServerInstance->XLines->ApplyLines();
446                                 }
447                                 else
448                                         delete gl;
449                         }
450                         return MOD_RES_DENY;
451                 }
452         }
453         return MOD_RES_PASSTHRU;
454 }
455
456 void ModuleFilter::ReadConfig(ConfigStatus& status)
457 {
458         ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
459         exemptedchans.clear();
460         exemptednicks.clear();
461
462         for (ConfigIter i = tags.first; i != tags.second; ++i)
463         {
464                 ConfigTag* tag = i->second;
465
466                 // If "target" is not found, try the old "channel" key to keep compatibility with 2.0 configs
467                 const std::string target = tag->getString("target", tag->getString("channel"));
468                 if (!target.empty())
469                 {
470                         if (target[0] == '#')
471                                 exemptedchans.insert(target);
472                         else
473                                 exemptednicks.insert(target);
474                 }
475         }
476
477         std::string newrxengine = ServerInstance->Config->ConfValue("filteropts")->getString("engine");
478
479         factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
480
481         if (newrxengine.empty())
482                 RegexEngine.SetProvider("regex");
483         else
484                 RegexEngine.SetProvider("regex/" + newrxengine);
485
486         if (!RegexEngine)
487         {
488                 if (newrxengine.empty())
489                         ServerInstance->SNO->WriteGlobalSno('a', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
490                 else
491                         ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
492
493                 initing = false;
494                 FreeFilters();
495                 return;
496         }
497
498         if ((!initing) && (RegexEngine.operator->() != factory))
499         {
500                 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change");
501                 FreeFilters();
502         }
503
504         initing = false;
505         ReadFilters();
506 }
507
508 Version ModuleFilter::GetVersion()
509 {
510         return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
511 }
512
513 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
514 {
515         std::ostringstream stream;
516         std::string x = filter->freeform;
517
518         /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
519         for (std::string::iterator n = x.begin(); n != x.end(); n++)
520                 if (*n == ' ')
521                         *n = '\7';
522
523         stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->gline_time << " :" << filter->reason;
524         return stream.str();
525 }
526
527 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
528 {
529         std::string filteraction;
530         FilterResult res;
531         irc::tokenstream tokens(data);
532         tokens.GetToken(res.freeform);
533         tokens.GetToken(filteraction);
534         if (!StringToFilterAction(filteraction, res.action))
535                 throw ModuleException("Invalid action: " + filteraction);
536
537         std::string filterflags;
538         tokens.GetToken(filterflags);
539         char c = res.FillFlags(filterflags);
540         if (c != 0)
541                 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
542
543         tokens.GetToken(res.gline_time);
544         tokens.GetToken(res.reason);
545
546         /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
547         for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
548                 if (*n == '\7')
549                         *n = ' ';
550
551         return res;
552 }
553
554 void ModuleFilter::OnSyncNetwork(ProtocolInterface::Server& server)
555 {
556         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
557         {
558                 server.SendMetaData("filter", EncodeFilter(&(*i)));
559         }
560 }
561
562 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
563 {
564         if ((target == NULL) && (extname == "filter"))
565         {
566                 try
567                 {
568                         FilterResult data = DecodeFilter(extdata);
569                         this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.GetFlags());
570                 }
571                 catch (ModuleException& e)
572                 {
573                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Error when unserializing filter: " + e.GetReason());
574                 }
575         }
576 }
577
578 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
579 {
580         static std::string stripped_text;
581         stripped_text.clear();
582
583         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
584         {
585                 FilterResult* filter = &*i;
586
587                 /* Skip ones that dont apply to us */
588                 if (!AppliesToMe(user, filter, flgs))
589                         continue;
590
591                 if ((filter->flag_strip_color) && (stripped_text.empty()))
592                 {
593                         stripped_text = text;
594                         InspIRCd::StripColor(stripped_text);
595                 }
596
597                 if (filter->regex->Matches(filter->flag_strip_color ? stripped_text : text))
598                         return filter;
599         }
600         return NULL;
601 }
602
603 bool ModuleFilter::DeleteFilter(const std::string &freeform)
604 {
605         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
606         {
607                 if (i->freeform == freeform)
608                 {
609                         delete i->regex;
610                         filters.erase(i);
611                         return true;
612                 }
613         }
614         return false;
615 }
616
617 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
618 {
619         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
620         {
621                 if (i->freeform == freeform)
622                 {
623                         return std::make_pair(false, "Filter already exists");
624                 }
625         }
626
627         try
628         {
629                 filters.push_back(FilterResult(RegexEngine, freeform, reason, type, duration, flgs));
630         }
631         catch (ModuleException &e)
632         {
633                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason().c_str());
634                 return std::make_pair(false, e.GetReason());
635         }
636         return std::make_pair(true, "");
637 }
638
639 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
640 {
641         if (stdalgo::string::equalsci(str, "gline"))
642                 fa = FA_GLINE;
643         else if (stdalgo::string::equalsci(str, "block"))
644                 fa = FA_BLOCK;
645         else if (stdalgo::string::equalsci(str, "silent"))
646                 fa = FA_SILENT;
647         else if (stdalgo::string::equalsci(str, "kill"))
648                 fa = FA_KILL;
649         else if (stdalgo::string::equalsci(str, "none"))
650                 fa = FA_NONE;
651         else
652                 return false;
653
654         return true;
655 }
656
657 std::string ModuleFilter::FilterActionToString(FilterAction fa)
658 {
659         switch (fa)
660         {
661                 case FA_GLINE:  return "gline";
662                 case FA_BLOCK:  return "block";
663                 case FA_SILENT: return "silent";
664                 case FA_KILL:   return "kill";
665                 default:                return "none";
666         }
667 }
668
669 void ModuleFilter::ReadFilters()
670 {
671         ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
672         for (ConfigIter i = tags.first; i != tags.second; ++i)
673         {
674                 std::string pattern = i->second->getString("pattern");
675                 this->DeleteFilter(pattern);
676
677                 std::string reason = i->second->getString("reason");
678                 std::string action = i->second->getString("action");
679                 std::string flgs = i->second->getString("flags");
680                 unsigned long gline_time = i->second->getDuration("duration", 10*60, 1);
681                 if (flgs.empty())
682                         flgs = "*";
683
684                 FilterAction fa;
685                 if (!StringToFilterAction(action, fa))
686                         fa = FA_NONE;
687
688                 try
689                 {
690                         filters.push_back(FilterResult(RegexEngine, pattern, reason, fa, gline_time, flgs));
691                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Regular expression %s loaded.", pattern.c_str());
692                 }
693                 catch (ModuleException &e)
694                 {
695                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason().c_str());
696                 }
697         }
698 }
699
700 ModResult ModuleFilter::OnStats(Stats::Context& stats)
701 {
702         if (stats.GetSymbol() == 's')
703         {
704                 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
705                 {
706                         stats.AddRow(223, RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason);
707                 }
708                 for (ExemptTargetSet::const_iterator i = exemptedchans.begin(); i != exemptedchans.end(); ++i)
709                 {
710                         stats.AddRow(223, "EXEMPT "+(*i));
711                 }
712                 for (ExemptTargetSet::const_iterator i = exemptednicks.begin(); i != exemptednicks.end(); ++i)
713                 {
714                         stats.AddRow(223, "EXEMPT "+(*i));
715                 }
716         }
717         return MOD_RES_PASSTHRU;
718 }
719
720 void ModuleFilter::OnUnloadModule(Module* mod)
721 {
722         // If the regex engine became unavailable or has changed, remove all filters
723         if (!RegexEngine)
724         {
725                 FreeFilters();
726         }
727         else if (RegexEngine.operator->() != factory)
728         {
729                 factory = RegexEngine.operator->();
730                 FreeFilters();
731         }
732 }
733
734 MODULE_INIT(ModuleFilter)