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