2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
25 #include "modules/regex.h"
26 #include "modules/server.h"
27 #include "modules/shun.h"
28 #include "modules/stats.h"
29 #include "modules/account.h"
58 unsigned long duration;
62 bool flag_part_message;
63 bool flag_quit_message;
66 bool flag_strip_color;
67 bool flag_no_registered;
69 FilterResult(dynamic_reference<RegexFactory>& RegexEngine, const std::string& free, const std::string& rea, FilterAction act, unsigned long gt, const std::string& fla, bool cfg)
77 throw ModuleException("Regex module implementing '"+RegexEngine.GetProvider()+"' is not loaded!");
78 regex = RegexEngine->Create(free);
82 char FillFlags(const std::string &fl)
84 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
85 flag_notice = flag_strip_color = flag_no_registered = false;
87 for (std::string::const_iterator n = fl.begin(); n != fl.end(); ++n)
95 flag_part_message = true;
98 flag_quit_message = true;
107 flag_strip_color = true;
110 flag_no_registered = true;
113 flag_no_opers = flag_part_message = flag_quit_message =
114 flag_privmsg = flag_notice = flag_strip_color = true;
124 std::string GetFlags()
128 flags.push_back('o');
129 if (flag_part_message)
130 flags.push_back('P');
131 if (flag_quit_message)
132 flags.push_back('q');
134 flags.push_back('p');
136 flags.push_back('n');
138 /* Order is important here, as the logic in FillFlags() stops parsing when it encounters
139 * an unknown character. So the following characters must be last in the string.
140 * 'c' is unsupported on < 2.0.10
141 * 'r' is unsupported on < 3.2.0
143 if (flag_strip_color)
144 flags.push_back('c');
145 if (flag_no_registered)
146 flags.push_back('r');
149 flags.push_back('-');
159 class CommandFilter : public Command
162 CommandFilter(Module* f)
163 : Command(f, "FILTER", 1, 5)
166 this->syntax = "<pattern> [<action> <flags> [<duration>] :<reason>]";
168 CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
170 RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
172 return ROUTE_BROADCAST;
176 class ModuleFilter : public Module, public ServerEventListener, public Stats::EventListener
178 typedef insp::flat_set<std::string, irc::insensitive_swo> ExemptTargetSet;
183 RegexFactory* factory;
187 CommandFilter filtcommand;
188 dynamic_reference<RegexFactory> RegexEngine;
190 std::vector<FilterResult> filters;
193 // List of channel names excluded from filtering.
194 ExemptTargetSet exemptedchans;
196 // List of target nicknames excluded from filtering.
197 ExemptTargetSet exemptednicks;
200 void init() CXX11_OVERRIDE;
201 CullResult cull() CXX11_OVERRIDE;
202 ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE;
203 FilterResult* FilterMatch(User* user, const std::string &text, int flags);
204 bool DeleteFilter(const std::string& freeform, std::string& reason);
205 std::pair<bool, std::string> AddFilter(const std::string& freeform, FilterAction type, const std::string& reason, unsigned long duration, const std::string& flags, bool config = false);
206 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE;
207 Version GetVersion() CXX11_OVERRIDE;
208 std::string EncodeFilter(FilterResult* filter);
209 FilterResult DecodeFilter(const std::string &data);
210 void OnSyncNetwork(ProtocolInterface::Server& server) CXX11_OVERRIDE;
211 void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) CXX11_OVERRIDE;
212 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE;
213 ModResult OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated) CXX11_OVERRIDE;
214 void OnUnloadModule(Module* mod) CXX11_OVERRIDE;
215 bool AppliesToMe(User* user, FilterResult* filter, int flags);
217 static bool StringToFilterAction(const std::string& str, FilterAction& fa);
218 static std::string FilterActionToString(FilterAction fa);
221 CmdResult CommandFilter::Handle(User* user, const Params& parameters)
223 if (parameters.size() == 1)
225 /* Deleting a filter */
226 Module* me = creator;
229 if (static_cast<ModuleFilter*>(me)->DeleteFilter(parameters[0], reason))
231 user->WriteNotice("*** Removed filter '" + parameters[0] + "': " + reason);
232 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'f' : 'F', "%s removed filter '%s': %s",
233 user->nick.c_str(), parameters[0].c_str(), reason.c_str());
238 user->WriteNotice("*** Filter '" + parameters[0] + "' not found on the list.");
244 /* Adding a filter */
245 if (parameters.size() >= 4)
247 const std::string& freeform = parameters[0];
249 const std::string& flags = parameters[2];
250 unsigned int reasonindex;
251 unsigned long duration = 0;
253 if (!ModuleFilter::StringToFilterAction(parameters[1], type))
255 if (ServerInstance->XLines->GetFactory("SHUN"))
256 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'zline', 'none', 'warn', 'block', 'silent', 'kill', and 'shun'.");
258 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'zline', 'none', 'warn', 'block', 'silent', and 'kill'.");
262 if (type == FA_GLINE || type == FA_ZLINE || type == FA_SHUN)
264 if (parameters.size() >= 5)
266 if (!InspIRCd::Duration(parameters[3], duration))
268 user->WriteNotice("*** Invalid duration for filter");
275 user->WriteNotice("*** Not enough parameters: When setting a '" + parameters[1] + "' type filter, a duration must be specified as the third parameter.");
284 Module* me = creator;
285 std::pair<bool, std::string> result = static_cast<ModuleFilter*>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
288 const std::string message = InspIRCd::Format("'%s', type '%s'%s, flags '%s', reason: %s",
289 freeform.c_str(), parameters[1].c_str(),
290 (duration ? InspIRCd::Format(", duration '%s'",
291 InspIRCd::DurationString(duration).c_str()).c_str()
292 : ""), flags.c_str(), parameters[reasonindex].c_str());
294 user->WriteNotice("*** Added filter " + message);
295 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'f' : 'F',
296 "%s added filter %s", user->nick.c_str(), message.c_str());
302 user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second);
308 user->WriteNotice("*** Not enough parameters.");
315 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
317 const AccountExtItem* accountext = GetAccountExtItem();
319 if ((filter->flag_no_opers) && user->IsOper())
321 if ((filter->flag_no_registered) && accountext && accountext->get(user))
323 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
325 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
327 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
329 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
334 ModuleFilter::ModuleFilter()
335 : ServerEventListener(this)
336 , Stats::EventListener(this)
339 , RegexEngine(this, "regex")
343 void ModuleFilter::init()
345 ServerInstance->SNO->EnableSnomask('f', "FILTER");
348 CullResult ModuleFilter::cull()
351 return Module::cull();
354 void ModuleFilter::FreeFilters()
356 for (std::vector<FilterResult>::const_iterator i = filters.begin(); i != filters.end(); ++i)
362 ModResult ModuleFilter::OnUserPreMessage(User* user, const MessageTarget& msgtarget, MessageDetails& details)
364 // Leave remote users and servers alone
366 return MOD_RES_PASSTHRU;
368 flags = (details.type == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE;
370 FilterResult* f = this->FilterMatch(user, details.text, flags);
373 bool is_selfmsg = false;
375 switch (msgtarget.type)
377 case MessageTarget::TYPE_USER:
379 User* t = msgtarget.Get<User>();
380 // Check if the target nick is exempted, if yes, ignore this message
381 if (exemptednicks.count(t->nick))
382 return MOD_RES_PASSTHRU;
390 case MessageTarget::TYPE_CHANNEL:
392 Channel* t = msgtarget.Get<Channel>();
393 if (exemptedchans.count(t->name))
394 return MOD_RES_PASSTHRU;
399 case MessageTarget::TYPE_SERVER:
403 if (is_selfmsg && warnonselfmsg)
405 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("WARNING: %s's self message matched %s (%s)",
406 user->nick.c_str(), f->freeform.c_str(), f->reason.c_str()));
407 return MOD_RES_PASSTHRU;
409 else if (f->action == FA_WARN)
411 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("WARNING: %s's message to %s matched %s (%s)",
412 user->nick.c_str(), target.c_str(), f->freeform.c_str(), f->reason.c_str()));
413 return MOD_RES_PASSTHRU;
415 else if (f->action == FA_BLOCK)
417 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s had their message to %s filtered as it matched %s (%s)",
418 user->nick.c_str(), target.c_str(), f->freeform.c_str(), f->reason.c_str()));
421 if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
422 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked and opers notified (%s)", f->reason.c_str()));
424 user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason);
427 details.echo_original = true;
429 else if (f->action == FA_SILENT)
433 if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
434 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked (%s)", f->reason.c_str()));
436 user->WriteNotice("Your message to "+target+" was blocked: "+f->reason);
439 details.echo_original = true;
441 else if (f->action == FA_KILL)
443 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s was killed because their message to %s matched %s (%s)",
444 user->nick.c_str(), target.c_str(), f->freeform.c_str(), f->reason.c_str()));
445 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
447 else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
449 Shun* sh = new Shun(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
450 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was shunned for %s (expires on %s) because their message to %s matched %s (%s)",
451 user->nick.c_str(), sh->Displayable().c_str(), InspIRCd::DurationString(f->duration).c_str(),
452 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
453 target.c_str(), f->freeform.c_str(), f->reason.c_str()));
454 if (ServerInstance->XLines->AddLine(sh, NULL))
456 ServerInstance->XLines->ApplyLines();
461 else if (f->action == FA_GLINE)
463 GLine* gl = new GLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
464 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was G-lined for %s (expires on %s) because their message to %s matched %s (%s)",
465 user->nick.c_str(), gl->Displayable().c_str(), InspIRCd::DurationString(f->duration).c_str(),
466 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
467 target.c_str(), f->freeform.c_str(), f->reason.c_str()));
468 if (ServerInstance->XLines->AddLine(gl,NULL))
470 ServerInstance->XLines->ApplyLines();
475 else if (f->action == FA_ZLINE)
477 ZLine* zl = new ZLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
478 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was Z-lined for %s (expires on %s) because their message to %s matched %s (%s)",
479 user->nick.c_str(), zl->Displayable().c_str(), InspIRCd::DurationString(f->duration).c_str(),
480 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
481 target.c_str(), f->freeform.c_str(), f->reason.c_str()));
482 if (ServerInstance->XLines->AddLine(zl,NULL))
484 ServerInstance->XLines->ApplyLines();
490 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
493 return MOD_RES_PASSTHRU;
496 ModResult ModuleFilter::OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated)
503 if (command == "QUIT")
505 /* QUIT with no reason: nothing to do */
506 if (parameters.size() < 1)
507 return MOD_RES_PASSTHRU;
512 else if (command == "PART")
514 /* PART with no reason: nothing to do */
515 if (parameters.size() < 2)
516 return MOD_RES_PASSTHRU;
518 if (exemptedchans.count(parameters[0]))
519 return MOD_RES_PASSTHRU;
525 /* We're only messing with PART and QUIT */
526 return MOD_RES_PASSTHRU;
528 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
530 /* PART or QUIT reason doesnt match a filter */
531 return MOD_RES_PASSTHRU;
533 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
534 parameters[parting ? 1 : 0] = "Reason filtered";
536 /* We're warning or blocking, OR theyre quitting and its a KILL action
537 * (we cant kill someone whos already quitting, so filter them anyway)
539 if ((f->action == FA_WARN) || (f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
541 return MOD_RES_PASSTHRU;
545 /* Are they parting, if so, kill is applicable */
546 if ((parting) && (f->action == FA_KILL))
548 user->WriteNotice("*** Your PART message was filtered: " + f->reason);
549 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
551 if (f->action == FA_GLINE)
553 /* Note: We G-line *@IP so that if their host doesn't resolve the G-line still applies. */
554 GLine* gl = new GLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
555 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was G-lined for %s (expires on %s) because their %s message matched %s (%s)",
556 user->nick.c_str(), gl->Displayable().c_str(),
557 InspIRCd::DurationString(f->duration).c_str(),
558 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
559 command.c_str(), f->freeform.c_str(), f->reason.c_str()));
561 if (ServerInstance->XLines->AddLine(gl,NULL))
563 ServerInstance->XLines->ApplyLines();
568 if (f->action == FA_ZLINE)
570 ZLine* zl = new ZLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
571 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was Z-lined for %s (expires on %s) because their %s message matched %s (%s)",
572 user->nick.c_str(), zl->Displayable().c_str(),
573 InspIRCd::DurationString(f->duration).c_str(),
574 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
575 command.c_str(), f->freeform.c_str(), f->reason.c_str()));
577 if (ServerInstance->XLines->AddLine(zl,NULL))
579 ServerInstance->XLines->ApplyLines();
584 else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
586 /* Note: We shun *!*@IP so that if their host doesnt resolve the shun still applies. */
587 Shun* sh = new Shun(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
588 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was shunned for %s (expires on %s) because their %s message matched %s (%s)",
589 user->nick.c_str(), sh->Displayable().c_str(),
590 InspIRCd::DurationString(f->duration).c_str(),
591 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
592 command.c_str(), f->freeform.c_str(), f->reason.c_str()));
594 if (ServerInstance->XLines->AddLine(sh, NULL))
596 ServerInstance->XLines->ApplyLines();
604 return MOD_RES_PASSTHRU;
607 void ModuleFilter::ReadConfig(ConfigStatus& status)
609 ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
610 exemptedchans.clear();
611 exemptednicks.clear();
613 for (ConfigIter i = tags.first; i != tags.second; ++i)
615 ConfigTag* tag = i->second;
617 // If "target" is not found, try the old "channel" key to keep compatibility with 2.0 configs
618 const std::string target = tag->getString("target", tag->getString("channel"));
621 if (target[0] == '#')
622 exemptedchans.insert(target);
624 exemptednicks.insert(target);
628 ConfigTag* tag = ServerInstance->Config->ConfValue("filteropts");
629 std::string newrxengine = tag->getString("engine");
630 notifyuser = tag->getBool("notifyuser", true);
631 warnonselfmsg = tag->getBool("warnonselfmsg");
633 factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
635 if (newrxengine.empty())
636 RegexEngine.SetProvider("regex");
638 RegexEngine.SetProvider("regex/" + newrxengine);
642 if (newrxengine.empty())
643 ServerInstance->SNO->WriteGlobalSno('f', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
645 ServerInstance->SNO->WriteGlobalSno('f', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
652 if ((!initing) && (RegexEngine.operator->() != factory))
654 ServerInstance->SNO->WriteGlobalSno('f', "Dumping all filters due to regex engine change");
662 Version ModuleFilter::GetVersion()
664 return Version("Provides text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
667 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
669 std::ostringstream stream;
670 std::string x = filter->freeform;
672 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
673 for (std::string::iterator n = x.begin(); n != x.end(); n++)
677 stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->duration << " :" << filter->reason;
681 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
683 std::string filteraction;
685 irc::tokenstream tokens(data);
686 tokens.GetMiddle(res.freeform);
687 tokens.GetMiddle(filteraction);
688 if (!StringToFilterAction(filteraction, res.action))
689 throw ModuleException("Invalid action: " + filteraction);
691 std::string filterflags;
692 tokens.GetMiddle(filterflags);
693 char c = res.FillFlags(filterflags);
695 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
697 std::string duration;
698 tokens.GetMiddle(duration);
699 res.duration = ConvToNum<unsigned long>(duration);
701 tokens.GetTrailing(res.reason);
703 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
704 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
711 void ModuleFilter::OnSyncNetwork(ProtocolInterface::Server& server)
713 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
715 FilterResult& filter = *i;
716 if (filter.from_config)
719 server.SendMetaData("filter", EncodeFilter(&filter));
723 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
725 if ((target == NULL) && (extname == "filter"))
729 FilterResult data = DecodeFilter(extdata);
730 this->AddFilter(data.freeform, data.action, data.reason, data.duration, data.GetFlags());
732 catch (ModuleException& e)
734 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Error when unserializing filter: " + e.GetReason());
739 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
741 static std::string stripped_text;
742 stripped_text.clear();
744 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
746 FilterResult* filter = &*i;
748 /* Skip ones that dont apply to us */
749 if (!AppliesToMe(user, filter, flgs))
752 if ((filter->flag_strip_color) && (stripped_text.empty()))
754 stripped_text = text;
755 InspIRCd::StripColor(stripped_text);
758 if (filter->regex->Matches(filter->flag_strip_color ? stripped_text : text))
764 bool ModuleFilter::DeleteFilter(const std::string& freeform, std::string& reason)
766 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
768 if (i->freeform == freeform)
770 reason.assign(i->reason);
779 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string& freeform, FilterAction type, const std::string& reason, unsigned long duration, const std::string& flgs, bool config)
781 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
783 if (i->freeform == freeform)
785 return std::make_pair(false, "Filter already exists");
791 filters.push_back(FilterResult(RegexEngine, freeform, reason, type, duration, flgs, config));
793 catch (ModuleException &e)
795 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason().c_str());
796 return std::make_pair(false, e.GetReason());
798 return std::make_pair(true, "");
801 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
803 if (stdalgo::string::equalsci(str, "gline"))
805 else if (stdalgo::string::equalsci(str, "zline"))
807 else if (stdalgo::string::equalsci(str, "warn"))
809 else if (stdalgo::string::equalsci(str, "block"))
811 else if (stdalgo::string::equalsci(str, "silent"))
813 else if (stdalgo::string::equalsci(str, "kill"))
815 else if (stdalgo::string::equalsci(str, "shun") && (ServerInstance->XLines->GetFactory("SHUN")))
817 else if (stdalgo::string::equalsci(str, "none"))
825 std::string ModuleFilter::FilterActionToString(FilterAction fa)
829 case FA_GLINE: return "gline";
830 case FA_ZLINE: return "zline";
831 case FA_WARN: return "warn";
832 case FA_BLOCK: return "block";
833 case FA_SILENT: return "silent";
834 case FA_KILL: return "kill";
835 case FA_SHUN: return "shun";
836 default: return "none";
840 void ModuleFilter::ReadFilters()
842 insp::flat_set<std::string> removedfilters;
844 for (std::vector<FilterResult>::iterator filter = filters.begin(); filter != filters.end(); )
846 if (filter->from_config)
848 removedfilters.insert(filter->freeform);
849 delete filter->regex;
850 filter = filters.erase(filter);
854 // The filter is not from the config.
858 ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
859 for (ConfigIter i = tags.first; i != tags.second; ++i)
861 std::string pattern = i->second->getString("pattern");
862 std::string reason = i->second->getString("reason");
863 std::string action = i->second->getString("action");
864 std::string flgs = i->second->getString("flags");
865 unsigned long duration = i->second->getDuration("duration", 10*60, 1);
870 if (!StringToFilterAction(action, fa))
873 std::pair<bool, std::string> result = static_cast<ModuleFilter*>(this)->AddFilter(pattern, fa, reason, duration, flgs, true);
875 removedfilters.erase(pattern);
877 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Filter '%s' could not be added: %s", pattern.c_str(), result.second.c_str());
880 if (!removedfilters.empty())
882 for (insp::flat_set<std::string>::const_iterator it = removedfilters.begin(); it != removedfilters.end(); ++it)
883 ServerInstance->SNO->WriteGlobalSno('f', "Removing filter '" + *(it) + "' due to config rehash.");
887 ModResult ModuleFilter::OnStats(Stats::Context& stats)
889 if (stats.GetSymbol() == 's')
891 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
893 stats.AddRow(223, RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->duration)+" :"+i->reason);
895 for (ExemptTargetSet::const_iterator i = exemptedchans.begin(); i != exemptedchans.end(); ++i)
897 stats.AddRow(223, "EXEMPT "+(*i));
899 for (ExemptTargetSet::const_iterator i = exemptednicks.begin(); i != exemptednicks.end(); ++i)
901 stats.AddRow(223, "EXEMPT "+(*i));
904 return MOD_RES_PASSTHRU;
907 void ModuleFilter::OnUnloadModule(Module* mod)
909 // If the regex engine became unavailable or has changed, remove all filters
914 else if (RegexEngine.operator->() != factory)
916 factory = RegexEngine.operator->();
921 MODULE_INIT(ModuleFilter)