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