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"
58 bool flag_part_message;
59 bool flag_quit_message;
62 bool flag_strip_color;
64 FilterResult(dynamic_reference<RegexFactory>& RegexEngine, const std::string& free, const std::string& rea, FilterAction act, long gt, const std::string& fla)
71 throw ModuleException("Regex module implementing '"+RegexEngine.GetProvider()+"' is not loaded!");
72 regex = RegexEngine->Create(free);
76 char FillFlags(const std::string &fl)
78 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
79 flag_notice = flag_strip_color = false;
81 for (std::string::const_iterator n = fl.begin(); n != fl.end(); ++n)
89 flag_part_message = true;
92 flag_quit_message = true;
101 flag_strip_color = true;
104 flag_no_opers = flag_part_message = flag_quit_message =
105 flag_privmsg = flag_notice = flag_strip_color = true;
115 std::string GetFlags()
119 flags.push_back('o');
120 if (flag_part_message)
121 flags.push_back('P');
122 if (flag_quit_message)
123 flags.push_back('q');
125 flags.push_back('p');
127 flags.push_back('n');
129 /* Order is important here, 'c' must be the last char in the string as it is unsupported
130 * on < 2.0.10, and the logic in FillFlags() stops parsing when it ecounters an unknown
133 if (flag_strip_color)
134 flags.push_back('c');
137 flags.push_back('-');
147 class CommandFilter : public Command
150 CommandFilter(Module* f)
151 : Command(f, "FILTER", 1, 5)
154 this->syntax = "<filter-definition> <action> <flags> [<duration>] :<reason>";
156 CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
158 RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
160 return ROUTE_BROADCAST;
164 class ModuleFilter : public Module, public ServerEventListener, public Stats::EventListener
166 typedef insp::flat_set<std::string, irc::insensitive_swo> ExemptTargetSet;
170 RegexFactory* factory;
174 CommandFilter filtcommand;
175 dynamic_reference<RegexFactory> RegexEngine;
177 std::vector<FilterResult> filters;
180 // List of channel names excluded from filtering.
181 ExemptTargetSet exemptedchans;
183 // List of target nicknames excluded from filtering.
184 ExemptTargetSet exemptednicks;
187 CullResult cull() CXX11_OVERRIDE;
188 ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE;
189 FilterResult* FilterMatch(User* user, const std::string &text, int flags);
190 bool DeleteFilter(const std::string &freeform);
191 std::pair<bool, std::string> AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flags);
192 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE;
193 Version GetVersion() CXX11_OVERRIDE;
194 std::string EncodeFilter(FilterResult* filter);
195 FilterResult DecodeFilter(const std::string &data);
196 void OnSyncNetwork(ProtocolInterface::Server& server) CXX11_OVERRIDE;
197 void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) CXX11_OVERRIDE;
198 ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE;
199 ModResult OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated) CXX11_OVERRIDE;
200 void OnUnloadModule(Module* mod) CXX11_OVERRIDE;
201 bool AppliesToMe(User* user, FilterResult* filter, int flags);
203 static bool StringToFilterAction(const std::string& str, FilterAction& fa);
204 static std::string FilterActionToString(FilterAction fa);
207 CmdResult CommandFilter::Handle(User* user, const Params& parameters)
209 if (parameters.size() == 1)
211 /* Deleting a filter */
212 Module *me = creator;
213 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
215 user->WriteNotice("*** Removed filter '" + parameters[0] + "'");
216 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
221 user->WriteNotice("*** Filter '" + parameters[0] + "' not found in list, try /stats s.");
227 /* Adding a filter */
228 if (parameters.size() >= 4)
230 const std::string& freeform = parameters[0];
232 const std::string& flags = parameters[2];
233 unsigned int reasonindex;
236 if (!ModuleFilter::StringToFilterAction(parameters[1], type))
238 if (ServerInstance->XLines->GetFactory("SHUN"))
239 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent', 'kill', and 'shun'.");
241 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent', and 'kill'.");
245 if (type == FA_GLINE || type == FA_SHUN)
247 if (parameters.size() >= 5)
249 duration = InspIRCd::Duration(parameters[3]);
254 user->WriteNotice("*** Not enough parameters: When setting a gline or shun type filter, a duration must be specified as the third parameter.");
263 Module *me = creator;
264 std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
267 user->WriteNotice("*** Added filter '" + freeform + "', type '" + parameters[1] + "'" +
268 (duration ? ", duration " + parameters[3] : "") + ", flags '" + flags + "', reason: '" +
269 parameters[reasonindex] + "'");
271 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]);
277 user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second);
283 user->WriteNotice("*** Not enough parameters.");
290 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
292 if ((filter->flag_no_opers) && user->IsOper())
294 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
296 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
298 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
300 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
305 ModuleFilter::ModuleFilter()
306 : ServerEventListener(this)
307 , Stats::EventListener(this)
310 , RegexEngine(this, "regex")
314 CullResult ModuleFilter::cull()
317 return Module::cull();
320 void ModuleFilter::FreeFilters()
322 for (std::vector<FilterResult>::const_iterator i = filters.begin(); i != filters.end(); ++i)
328 ModResult ModuleFilter::OnUserPreMessage(User* user, const MessageTarget& msgtarget, MessageDetails& details)
330 // Leave remote users and servers alone
332 return MOD_RES_PASSTHRU;
334 flags = (details.type == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE;
336 FilterResult* f = this->FilterMatch(user, details.text, flags);
340 if (msgtarget.type == MessageTarget::TYPE_USER)
342 User* t = msgtarget.Get<User>();
343 // Check if the target nick is exempted, if yes, ignore this message
344 if (exemptednicks.count(t->nick))
345 return MOD_RES_PASSTHRU;
349 else if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
351 Channel* t = msgtarget.Get<Channel>();
352 if (exemptedchans.count(t->name))
353 return MOD_RES_PASSTHRU;
357 if (f->action == FA_BLOCK)
359 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
362 if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
363 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked and opers notified (%s)", f->reason.c_str()));
365 user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason);
368 details.echooriginal = true;
370 else if (f->action == FA_SILENT)
374 if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
375 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked (%s)", f->reason.c_str()));
377 user->WriteNotice("Your message to "+target+" was blocked: "+f->reason);
380 details.echooriginal = true;
382 else if (f->action == FA_KILL)
384 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: " + user->nick + " had their message filtered and was killed, target was " + target + ": " + f->reason);
385 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
387 else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
389 Shun* sh = new Shun(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
390 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: " + user->nick + " had their message filtered and was shunned, target was " + target + ": " + f->reason);
391 if (ServerInstance->XLines->AddLine(sh, NULL))
393 ServerInstance->XLines->ApplyLines();
398 else if (f->action == FA_GLINE)
400 GLine* gl = new GLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
401 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: " + user->nick + " had their message filtered and was G-Lined, target was " + target + ": " + f->reason);
402 if (ServerInstance->XLines->AddLine(gl,NULL))
404 ServerInstance->XLines->ApplyLines();
410 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
413 return MOD_RES_PASSTHRU;
416 ModResult ModuleFilter::OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated)
423 if (command == "QUIT")
425 /* QUIT with no reason: nothing to do */
426 if (parameters.size() < 1)
427 return MOD_RES_PASSTHRU;
432 else if (command == "PART")
434 /* PART with no reason: nothing to do */
435 if (parameters.size() < 2)
436 return MOD_RES_PASSTHRU;
438 if (exemptedchans.count(parameters[0]))
439 return MOD_RES_PASSTHRU;
445 /* We're only messing with PART and QUIT */
446 return MOD_RES_PASSTHRU;
448 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
450 /* PART or QUIT reason doesnt match a filter */
451 return MOD_RES_PASSTHRU;
453 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
454 parameters[parting ? 1 : 0] = "Reason filtered";
456 /* We're blocking, OR theyre quitting and its a KILL action
457 * (we cant kill someone whos already quitting, so filter them anyway)
459 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
461 return MOD_RES_PASSTHRU;
465 /* Are they parting, if so, kill is applicable */
466 if ((parting) && (f->action == FA_KILL))
468 user->WriteNotice("*** Your PART message was filtered: " + f->reason);
469 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
471 if (f->action == FA_GLINE)
473 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
474 GLine* gl = new GLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
475 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: " + user->nick + " had their " + command + " message filtered and was G-Lined: " + f->reason);
476 if (ServerInstance->XLines->AddLine(gl,NULL))
478 ServerInstance->XLines->ApplyLines();
483 else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
485 /* Note: We shun *!*@IP so that if their host doesnt resolve the shun still applies. */
486 Shun* sh = new Shun(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
487 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: " + user->nick + " had their " + command + " message filtered and was shunned: " + f->reason);
488 if (ServerInstance->XLines->AddLine(sh, NULL))
490 ServerInstance->XLines->ApplyLines();
498 return MOD_RES_PASSTHRU;
501 void ModuleFilter::ReadConfig(ConfigStatus& status)
503 ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
504 exemptedchans.clear();
505 exemptednicks.clear();
507 for (ConfigIter i = tags.first; i != tags.second; ++i)
509 ConfigTag* tag = i->second;
511 // If "target" is not found, try the old "channel" key to keep compatibility with 2.0 configs
512 const std::string target = tag->getString("target", tag->getString("channel"));
515 if (target[0] == '#')
516 exemptedchans.insert(target);
518 exemptednicks.insert(target);
522 ConfigTag* tag = ServerInstance->Config->ConfValue("filteropts");
523 std::string newrxengine = tag->getString("engine");
524 notifyuser = tag->getBool("notifyuser", true);
526 factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
528 if (newrxengine.empty())
529 RegexEngine.SetProvider("regex");
531 RegexEngine.SetProvider("regex/" + newrxengine);
535 if (newrxengine.empty())
536 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
538 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
545 if ((!initing) && (RegexEngine.operator->() != factory))
547 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change");
555 Version ModuleFilter::GetVersion()
557 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
560 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
562 std::ostringstream stream;
563 std::string x = filter->freeform;
565 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
566 for (std::string::iterator n = x.begin(); n != x.end(); n++)
570 stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->duration << " :" << filter->reason;
574 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
576 std::string filteraction;
578 irc::tokenstream tokens(data);
579 tokens.GetMiddle(res.freeform);
580 tokens.GetMiddle(filteraction);
581 if (!StringToFilterAction(filteraction, res.action))
582 throw ModuleException("Invalid action: " + filteraction);
584 std::string filterflags;
585 tokens.GetMiddle(filterflags);
586 char c = res.FillFlags(filterflags);
588 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
590 std::string duration;
591 tokens.GetMiddle(duration);
592 res.duration = ConvToInt(duration);
594 tokens.GetTrailing(res.reason);
596 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
597 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
604 void ModuleFilter::OnSyncNetwork(ProtocolInterface::Server& server)
606 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
608 server.SendMetaData("filter", EncodeFilter(&(*i)));
612 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
614 if ((target == NULL) && (extname == "filter"))
618 FilterResult data = DecodeFilter(extdata);
619 this->AddFilter(data.freeform, data.action, data.reason, data.duration, data.GetFlags());
621 catch (ModuleException& e)
623 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Error when unserializing filter: " + e.GetReason());
628 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
630 static std::string stripped_text;
631 stripped_text.clear();
633 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
635 FilterResult* filter = &*i;
637 /* Skip ones that dont apply to us */
638 if (!AppliesToMe(user, filter, flgs))
641 if ((filter->flag_strip_color) && (stripped_text.empty()))
643 stripped_text = text;
644 InspIRCd::StripColor(stripped_text);
647 if (filter->regex->Matches(filter->flag_strip_color ? stripped_text : text))
653 bool ModuleFilter::DeleteFilter(const std::string &freeform)
655 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
657 if (i->freeform == freeform)
667 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
669 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
671 if (i->freeform == freeform)
673 return std::make_pair(false, "Filter already exists");
679 filters.push_back(FilterResult(RegexEngine, freeform, reason, type, duration, flgs));
681 catch (ModuleException &e)
683 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason().c_str());
684 return std::make_pair(false, e.GetReason());
686 return std::make_pair(true, "");
689 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
691 if (stdalgo::string::equalsci(str, "gline"))
693 else if (stdalgo::string::equalsci(str, "block"))
695 else if (stdalgo::string::equalsci(str, "silent"))
697 else if (stdalgo::string::equalsci(str, "kill"))
699 else if (stdalgo::string::equalsci(str, "shun") && (ServerInstance->XLines->GetFactory("SHUN")))
701 else if (stdalgo::string::equalsci(str, "none"))
709 std::string ModuleFilter::FilterActionToString(FilterAction fa)
713 case FA_GLINE: return "gline";
714 case FA_BLOCK: return "block";
715 case FA_SILENT: return "silent";
716 case FA_KILL: return "kill";
717 case FA_SHUN: return "shun";
718 default: return "none";
722 void ModuleFilter::ReadFilters()
724 ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
725 for (ConfigIter i = tags.first; i != tags.second; ++i)
727 std::string pattern = i->second->getString("pattern");
728 this->DeleteFilter(pattern);
730 std::string reason = i->second->getString("reason");
731 std::string action = i->second->getString("action");
732 std::string flgs = i->second->getString("flags");
733 unsigned long duration = i->second->getDuration("duration", 10*60, 1);
738 if (!StringToFilterAction(action, fa))
743 filters.push_back(FilterResult(RegexEngine, pattern, reason, fa, duration, flgs));
744 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Regular expression %s loaded.", pattern.c_str());
746 catch (ModuleException &e)
748 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason().c_str());
753 ModResult ModuleFilter::OnStats(Stats::Context& stats)
755 if (stats.GetSymbol() == 's')
757 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
759 stats.AddRow(223, RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->duration)+" :"+i->reason);
761 for (ExemptTargetSet::const_iterator i = exemptedchans.begin(); i != exemptedchans.end(); ++i)
763 stats.AddRow(223, "EXEMPT "+(*i));
765 for (ExemptTargetSet::const_iterator i = exemptednicks.begin(); i != exemptednicks.end(); ++i)
767 stats.AddRow(223, "EXEMPT "+(*i));
770 return MOD_RES_PASSTHRU;
773 void ModuleFilter::OnUnloadModule(Module* mod)
775 // If the regex engine became unavailable or has changed, remove all filters
780 else if (RegexEngine.operator->() != factory)
782 factory = RegexEngine.operator->();
787 MODULE_INIT(ModuleFilter)