]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_filter.cpp
Merge insp20
[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();
183         CullResult cull();
184         ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
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         ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
189         void OnRehash(User* user);
190         Version GetVersion();
191         std::string EncodeFilter(FilterResult* filter);
192         FilterResult DecodeFilter(const std::string &data);
193         void OnSyncNetwork(Module* proto, void* opaque);
194         void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata);
195         ModResult OnStats(char symbol, User* user, string_list &results);
196         ModResult OnPreCommand(std::string &command, std::vector<std::string> &parameters, LocalUser *user, bool validated, const std::string &original_line);
197         void OnUnloadModule(Module* mod);
198         bool AppliesToMe(User* user, FilterResult* filter, int flags);
199         void ReadFilters();
200         static bool StringToFilterAction(const std::string& str, FilterAction& fa);
201         static std::string FilterActionToString(FilterAction fa);
202 };
203
204 CmdResult CommandFilter::Handle(const std::vector<std::string> &parameters, User *user)
205 {
206         if (parameters.size() == 1)
207         {
208                 /* Deleting a filter */
209                 Module *me = creator;
210                 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
211                 {
212                         user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str());
213                         ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
214                         return CMD_SUCCESS;
215                 }
216                 else
217                 {
218                         user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str());
219                         return CMD_FAILURE;
220                 }
221         }
222         else
223         {
224                 /* Adding a filter */
225                 if (parameters.size() >= 4)
226                 {
227                         const std::string& freeform = parameters[0];
228                         FilterAction type;
229                         const std::string& flags = parameters[2];
230                         unsigned int reasonindex;
231                         long duration = 0;
232
233                         if (!ModuleFilter::StringToFilterAction(parameters[1], type))
234                         {
235                                 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), parameters[1].c_str());
236                                 return CMD_FAILURE;
237                         }
238
239                         if (type == FA_GLINE)
240                         {
241                                 if (parameters.size() >= 5)
242                                 {
243                                         duration = InspIRCd::Duration(parameters[3]);
244                                         reasonindex = 4;
245                                 }
246                                 else
247                                 {
248                                         user->WriteServ("NOTICE %s :*** Not enough parameters: When setting a gline type filter, a gline duration must be specified as the third parameter.", user->nick.c_str());
249                                         return CMD_FAILURE;
250                                 }
251                         }
252                         else
253                         {
254                                 reasonindex = 3;
255                         }
256
257                         Module *me = creator;
258                         std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
259                         if (result.first)
260                         {
261                                 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
262                                                 parameters[1].c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""),
263                                                 flags.c_str(), parameters[reasonindex].c_str());
264
265                                 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]);
266
267                                 return CMD_SUCCESS;
268                         }
269                         else
270                         {
271                                 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
272                                 return CMD_FAILURE;
273                         }
274                 }
275                 else
276                 {
277                         user->WriteServ("NOTICE %s :*** Not enough parameters.", user->nick.c_str());
278                         return CMD_FAILURE;
279                 }
280
281         }
282 }
283
284 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
285 {
286         if ((filter->flag_no_opers) && user->IsOper())
287                 return false;
288         if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
289                 return false;
290         if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
291                 return false;
292         if ((iflags & FLAG_QUIT)   && (!filter->flag_quit_message))
293                 return false;
294         if ((iflags & FLAG_PART)   && (!filter->flag_part_message))
295                 return false;
296         return true;
297 }
298
299 ModuleFilter::ModuleFilter()
300         : initing(true), filtcommand(this), RegexEngine(this, "regex")
301 {
302 }
303
304 void ModuleFilter::init()
305 {
306         ServerInstance->Modules->AddService(filtcommand);
307         Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_OnUnloadModule };
308         ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
309         OnRehash(NULL);
310 }
311
312 CullResult ModuleFilter::cull()
313 {
314         FreeFilters();
315         return Module::cull();
316 }
317
318 void ModuleFilter::FreeFilters()
319 {
320         for (std::vector<ImplFilter>::const_iterator i = filters.begin(); i != filters.end(); ++i)
321                 delete i->regex;
322
323         filters.clear();
324 }
325
326 ModResult ModuleFilter::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
327 {
328         if (!IS_LOCAL(user))
329                 return MOD_RES_PASSTHRU;
330
331         flags = FLAG_PRIVMSG;
332         return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
333 }
334
335 ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
336 {
337         /* Leave ulines alone */
338         if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
339                 return MOD_RES_PASSTHRU;
340
341         if (!flags)
342                 flags = FLAG_NOTICE;
343
344         FilterResult* f = this->FilterMatch(user, text, flags);
345         if (f)
346         {
347                 std::string target;
348                 if (target_type == TYPE_USER)
349                 {
350                         User* t = (User*)dest;
351                         target = t->nick;
352                 }
353                 else if (target_type == TYPE_CHANNEL)
354                 {
355                         Channel* t = (Channel*)dest;
356                         if (exemptfromfilter.find(t->name) != exemptfromfilter.end())
357                                 return MOD_RES_PASSTHRU;
358
359                         target = t->name;
360                 }
361                 if (f->action == FA_BLOCK)
362                 {
363                         ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
364                         if (target_type == TYPE_CHANNEL)
365                                 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
366                         else
367                                 user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
368                 }
369                 else if (f->action == FA_SILENT)
370                 {
371                         if (target_type == TYPE_CHANNEL)
372                                 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
373                         else
374                                 user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked: "+f->reason);
375                 }
376                 else if (f->action == FA_KILL)
377                 {
378                         ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
379                 }
380                 else if (f->action == FA_GLINE)
381                 {
382                         GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
383                         if (ServerInstance->XLines->AddLine(gl,NULL))
384                         {
385                                 ServerInstance->XLines->ApplyLines();
386                         }
387                         else
388                                 delete gl;
389                 }
390
391                 ServerInstance->Logs->Log("FILTER",LOG_DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
392                 return MOD_RES_DENY;
393         }
394         return MOD_RES_PASSTHRU;
395 }
396
397 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> &parameters, LocalUser *user, bool validated, const std::string &original_line)
398 {
399         if (validated && IS_LOCAL(user))
400         {
401                 flags = 0;
402                 bool parting;
403
404                 if (command == "QUIT")
405                 {
406                         /* QUIT with no reason: nothing to do */
407                         if (parameters.size() < 1)
408                                 return MOD_RES_PASSTHRU;
409
410                         parting = false;
411                         flags = FLAG_QUIT;
412                 }
413                 else if (command == "PART")
414                 {
415                         /* PART with no reason: nothing to do */
416                         if (parameters.size() < 2)
417                                 return MOD_RES_PASSTHRU;
418
419                         if (exemptfromfilter.find(parameters[0]) != exemptfromfilter.end())
420                                 return MOD_RES_PASSTHRU;
421
422                         parting = true;
423                         flags = FLAG_PART;
424                 }
425                 else
426                         /* We're only messing with PART and QUIT */
427                         return MOD_RES_PASSTHRU;
428
429                 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
430                 if (!f)
431                         /* PART or QUIT reason doesnt match a filter */
432                         return MOD_RES_PASSTHRU;
433
434                 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
435                 parameters[parting ? 1 : 0] = "Reason filtered";
436
437                 /* We're blocking, OR theyre quitting and its a KILL action
438                  * (we cant kill someone whos already quitting, so filter them anyway)
439                  */
440                 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
441                 {
442                         return MOD_RES_PASSTHRU;
443                 }
444                 else
445                 {
446                         /* Are they parting, if so, kill is applicable */
447                         if ((parting) && (f->action == FA_KILL))
448                         {
449                                 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
450                                 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
451                         }
452                         if (f->action == FA_GLINE)
453                         {
454                                 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
455                                 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
456                                 if (ServerInstance->XLines->AddLine(gl,NULL))
457                                 {
458                                         ServerInstance->XLines->ApplyLines();
459                                 }
460                                 else
461                                         delete gl;
462                         }
463                         return MOD_RES_DENY;
464                 }
465         }
466         return MOD_RES_PASSTHRU;
467 }
468
469 void ModuleFilter::OnRehash(User* user)
470 {
471         ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
472         exemptfromfilter.clear();
473         for (ConfigIter i = tags.first; i != tags.second; ++i)
474         {
475                 std::string chan = i->second->getString("channel");
476                 if (!chan.empty())
477                         exemptfromfilter.insert(chan);
478         }
479
480         std::string newrxengine = ServerInstance->Config->ConfValue("filteropts")->getString("engine");
481
482         factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
483
484         if (newrxengine.empty())
485                 RegexEngine.SetProvider("regex");
486         else
487                 RegexEngine.SetProvider("regex/" + newrxengine);
488
489         if (!RegexEngine)
490         {
491                 if (newrxengine.empty())
492                         ServerInstance->SNO->WriteGlobalSno('a', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
493                 else
494                         ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
495
496                 initing = false;
497                 FreeFilters();
498                 return;
499         }
500
501         if ((!initing) && (RegexEngine.operator->() != factory))
502         {
503                 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change");
504                 FreeFilters();
505         }
506
507         initing = false;
508         ReadFilters();
509 }
510
511 Version ModuleFilter::GetVersion()
512 {
513         return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
514 }
515
516 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
517 {
518         std::ostringstream stream;
519         std::string x = filter->freeform;
520
521         /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
522         for (std::string::iterator n = x.begin(); n != x.end(); n++)
523                 if (*n == ' ')
524                         *n = '\7';
525
526         stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->gline_time << " :" << filter->reason;
527         return stream.str();
528 }
529
530 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
531 {
532         std::string filteraction;
533         FilterResult res;
534         irc::tokenstream tokens(data);
535         tokens.GetToken(res.freeform);
536         tokens.GetToken(filteraction);
537         if (!StringToFilterAction(filteraction, res.action))
538                 throw ModuleException("Invalid action: " + filteraction);
539
540         std::string filterflags;
541         tokens.GetToken(filterflags);
542         char c = res.FillFlags(filterflags);
543         if (c != 0)
544                 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
545
546         tokens.GetToken(res.gline_time);
547         tokens.GetToken(res.reason);
548
549         /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
550         for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
551                 if (*n == '\7')
552                         *n = ' ';
553
554         return res;
555 }
556
557 void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque)
558 {
559         for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); ++i)
560         {
561                 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(&(*i)));
562         }
563 }
564
565 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
566 {
567         if ((target == NULL) && (extname == "filter"))
568         {
569                 try
570                 {
571                         FilterResult data = DecodeFilter(extdata);
572                         this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.GetFlags());
573                 }
574                 catch (ModuleException& e)
575                 {
576                         ServerInstance->Logs->Log("m_filter", LOG_DEBUG, "Error when unserializing filter: " + std::string(e.GetReason()));
577                 }
578         }
579 }
580
581 ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs)
582                 : FilterResult(pat, rea, act, glinetime, flgs)
583 {
584         if (!mymodule->RegexEngine)
585                 throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!");
586         regex = mymodule->RegexEngine->Create(pat);
587 }
588
589 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
590 {
591         static std::string stripped_text;
592         stripped_text.clear();
593
594         for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
595         {
596                 FilterResult* filter = dynamic_cast<FilterResult*>(&(*index));
597
598                 /* Skip ones that dont apply to us */
599                 if (!AppliesToMe(user, filter, flgs))
600                         continue;
601
602                 if ((filter->flag_strip_color) && (stripped_text.empty()))
603                 {
604                         stripped_text = text;
605                         InspIRCd::StripColor(stripped_text);
606                 }
607
608                 //ServerInstance->Logs->Log("m_filter", LOG_DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
609                 if (index->regex->Matches(filter->flag_strip_color ? stripped_text : text))
610                 {
611                         //ServerInstance->Logs->Log("m_filter", LOG_DEBUG, "MATCH");
612                         return &*index;
613                 }
614                 //ServerInstance->Logs->Log("m_filter", LOG_DEBUG, "NO MATCH");
615         }
616         return NULL;
617 }
618
619 bool ModuleFilter::DeleteFilter(const std::string &freeform)
620 {
621         for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
622         {
623                 if (i->freeform == freeform)
624                 {
625                         delete i->regex;
626                         filters.erase(i);
627                         return true;
628                 }
629         }
630         return false;
631 }
632
633 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
634 {
635         for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
636         {
637                 if (i->freeform == freeform)
638                 {
639                         return std::make_pair(false, "Filter already exists");
640                 }
641         }
642
643         try
644         {
645                 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
646         }
647         catch (ModuleException &e)
648         {
649                 ServerInstance->Logs->Log("m_filter", LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
650                 return std::make_pair(false, e.GetReason());
651         }
652         return std::make_pair(true, "");
653 }
654
655 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
656 {
657         irc::string s(str.c_str());
658
659         if (s == "gline")
660                 fa = FA_GLINE;
661         else if (s == "block")
662                 fa = FA_BLOCK;
663         else if (s == "silent")
664                 fa = FA_SILENT;
665         else if (s == "kill")
666                 fa = FA_KILL;
667         else if (s == "none")
668                 fa = FA_NONE;
669         else
670                 return false;
671
672         return true;
673 }
674
675 std::string ModuleFilter::FilterActionToString(FilterAction fa)
676 {
677         switch (fa)
678         {
679                 case FA_GLINE:  return "gline";
680                 case FA_BLOCK:  return "block";
681                 case FA_SILENT: return "silent";
682                 case FA_KILL:   return "kill";
683                 default:                return "none";
684         }
685 }
686
687 void ModuleFilter::ReadFilters()
688 {
689         ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
690         for (ConfigIter i = tags.first; i != tags.second; ++i)
691         {
692                 std::string pattern = i->second->getString("pattern");
693                 this->DeleteFilter(pattern);
694
695                 std::string reason = i->second->getString("reason");
696                 std::string action = i->second->getString("action");
697                 std::string flgs = i->second->getString("flags");
698                 unsigned long gline_time = InspIRCd::Duration(i->second->getString("duration"));
699                 if (flgs.empty())
700                         flgs = "*";
701
702                 FilterAction fa;
703                 if (!StringToFilterAction(action, fa))
704                         fa = FA_NONE;
705
706                 try
707                 {
708                         filters.push_back(ImplFilter(this, reason, fa, gline_time, pattern, flgs));
709                         ServerInstance->Logs->Log("m_filter", LOG_DEFAULT, "Regular expression %s loaded.", pattern.c_str());
710                 }
711                 catch (ModuleException &e)
712                 {
713                         ServerInstance->Logs->Log("m_filter", LOG_DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
714                 }
715         }
716 }
717
718 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
719 {
720         if (symbol == 's')
721         {
722                 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
723                 {
724                         results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason);
725                 }
726                 for (std::set<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
727                 {
728                         results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :EXEMPT "+(*i));
729                 }
730         }
731         return MOD_RES_PASSTHRU;
732 }
733
734 void ModuleFilter::OnUnloadModule(Module* mod)
735 {
736         // If the regex engine became unavailable or has changed, remove all filters
737         if (!RegexEngine)
738         {
739                 FreeFilters();
740         }
741         else if (RegexEngine.operator->() != factory)
742         {
743                 factory = RegexEngine.operator->();
744                 FreeFilters();
745         }
746 }
747
748 MODULE_INIT(ModuleFilter)