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