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"
57 bool flag_part_message;
58 bool flag_quit_message;
61 bool flag_strip_color;
63 FilterResult(dynamic_reference<RegexFactory>& RegexEngine, const std::string& free, const std::string& rea, FilterAction act, long gt, const std::string& fla)
70 throw ModuleException("Regex module implementing '"+RegexEngine.GetProvider()+"' is not loaded!");
71 regex = RegexEngine->Create(free);
75 char FillFlags(const std::string &fl)
77 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
78 flag_notice = flag_strip_color = false;
80 for (std::string::const_iterator n = fl.begin(); n != fl.end(); ++n)
88 flag_part_message = true;
91 flag_quit_message = true;
100 flag_strip_color = true;
103 flag_no_opers = flag_part_message = flag_quit_message =
104 flag_privmsg = flag_notice = flag_strip_color = true;
114 std::string GetFlags()
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');
124 flags.push_back('p');
126 flags.push_back('n');
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
132 if (flag_strip_color)
133 flags.push_back('c');
136 flags.push_back('-');
146 class CommandFilter : public Command
149 CommandFilter(Module* f)
150 : Command(f, "FILTER", 1, 5)
153 this->syntax = "<filter-definition> <action> <flags> [<duration>] :<reason>";
155 CmdResult Handle(const std::vector<std::string>& , User* ) CXX11_OVERRIDE;
157 RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) CXX11_OVERRIDE
159 return ROUTE_BROADCAST;
163 class ModuleFilter : public Module, public ServerEventListener
165 typedef insp::flat_set<std::string, irc::insensitive_swo> ExemptTargetSet;
168 RegexFactory* factory;
172 CommandFilter filtcommand;
173 dynamic_reference<RegexFactory> RegexEngine;
175 std::vector<FilterResult> filters;
178 // List of channel names excluded from filtering.
179 ExemptTargetSet exemptedchans;
181 // List of target nicknames excluded from filtering.
182 ExemptTargetSet exemptednicks;
185 CullResult cull() CXX11_OVERRIDE;
186 ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) 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> ¶meters, 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);
201 static bool StringToFilterAction(const std::string& str, FilterAction& fa);
202 static std::string FilterActionToString(FilterAction fa);
205 CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User *user)
207 if (parameters.size() == 1)
209 /* Deleting a filter */
210 Module *me = creator;
211 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
213 user->WriteNotice("*** Removed filter '" + parameters[0] + "'");
214 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
219 user->WriteNotice("*** Filter '" + parameters[0] + "' not found in list, try /stats s.");
225 /* Adding a filter */
226 if (parameters.size() >= 4)
228 const std::string& freeform = parameters[0];
230 const std::string& flags = parameters[2];
231 unsigned int reasonindex;
234 if (!ModuleFilter::StringToFilterAction(parameters[1], type))
236 if (ServerInstance->XLines->GetFactory("SHUN"))
237 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent', 'kill', and 'shun'.");
239 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent', and 'kill'.");
243 if (type == FA_GLINE || type == FA_SHUN)
245 if (parameters.size() >= 5)
247 duration = InspIRCd::Duration(parameters[3]);
252 user->WriteNotice("*** Not enough parameters: When setting a gline or shun type filter, a duration must be specified as the third parameter.");
261 Module *me = creator;
262 std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
265 user->WriteNotice("*** Added filter '" + freeform + "', type '" + parameters[1] + "'" +
266 (duration ? ", duration " + parameters[3] : "") + ", flags '" + flags + "', reason: '" +
267 parameters[reasonindex] + "'");
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]);
275 user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second);
281 user->WriteNotice("*** Not enough parameters.");
288 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
290 if ((filter->flag_no_opers) && user->IsOper())
292 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
294 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
296 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
298 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
303 ModuleFilter::ModuleFilter()
304 : ServerEventListener(this)
307 , RegexEngine(this, "regex")
311 CullResult ModuleFilter::cull()
314 return Module::cull();
317 void ModuleFilter::FreeFilters()
319 for (std::vector<FilterResult>::const_iterator i = filters.begin(); i != filters.end(); ++i)
325 ModResult ModuleFilter::OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype)
327 // Leave remote users and servers alone
329 return MOD_RES_PASSTHRU;
331 flags = (msgtype == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE;
333 FilterResult* f = this->FilterMatch(user, text, flags);
337 if (target_type == TYPE_USER)
339 User* t = (User*)dest;
340 // Check if the target nick is exempted, if yes, ignore this message
341 if (exemptednicks.count(t->nick))
342 return MOD_RES_PASSTHRU;
346 else if (target_type == TYPE_CHANNEL)
348 Channel* t = (Channel*)dest;
349 if (exemptedchans.count(t->name))
350 return MOD_RES_PASSTHRU;
354 if (f->action == FA_BLOCK)
356 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
357 if (target_type == TYPE_CHANNEL)
358 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked and opers notified (%s)", f->reason.c_str()));
360 user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason);
362 else if (f->action == FA_SILENT)
364 if (target_type == TYPE_CHANNEL)
365 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked (%s)", f->reason.c_str()));
367 user->WriteNotice("Your message to "+target+" was blocked: "+f->reason);
369 else if (f->action == FA_KILL)
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);
374 else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
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))
380 ServerInstance->XLines->ApplyLines();
385 else if (f->action == FA_GLINE)
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))
391 ServerInstance->XLines->ApplyLines();
397 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
400 return MOD_RES_PASSTHRU;
403 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line)
410 if (command == "QUIT")
412 /* QUIT with no reason: nothing to do */
413 if (parameters.size() < 1)
414 return MOD_RES_PASSTHRU;
419 else if (command == "PART")
421 /* PART with no reason: nothing to do */
422 if (parameters.size() < 2)
423 return MOD_RES_PASSTHRU;
425 if (exemptedchans.count(parameters[0]))
426 return MOD_RES_PASSTHRU;
432 /* We're only messing with PART and QUIT */
433 return MOD_RES_PASSTHRU;
435 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
437 /* PART or QUIT reason doesnt match a filter */
438 return MOD_RES_PASSTHRU;
440 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
441 parameters[parting ? 1 : 0] = "Reason filtered";
443 /* We're blocking, OR theyre quitting and its a KILL action
444 * (we cant kill someone whos already quitting, so filter them anyway)
446 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
448 return MOD_RES_PASSTHRU;
452 /* Are they parting, if so, kill is applicable */
453 if ((parting) && (f->action == FA_KILL))
455 user->WriteNotice("*** Your PART message was filtered: " + f->reason);
456 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
458 if (f->action == FA_GLINE)
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))
465 ServerInstance->XLines->ApplyLines();
470 else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
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))
477 ServerInstance->XLines->ApplyLines();
485 return MOD_RES_PASSTHRU;
488 void ModuleFilter::ReadConfig(ConfigStatus& status)
490 ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
491 exemptedchans.clear();
492 exemptednicks.clear();
494 for (ConfigIter i = tags.first; i != tags.second; ++i)
496 ConfigTag* tag = i->second;
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"));
502 if (target[0] == '#')
503 exemptedchans.insert(target);
505 exemptednicks.insert(target);
509 std::string newrxengine = ServerInstance->Config->ConfValue("filteropts")->getString("engine");
511 factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
513 if (newrxengine.empty())
514 RegexEngine.SetProvider("regex");
516 RegexEngine.SetProvider("regex/" + newrxengine);
520 if (newrxengine.empty())
521 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
523 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
530 if ((!initing) && (RegexEngine.operator->() != factory))
532 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change");
540 Version ModuleFilter::GetVersion()
542 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
545 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
547 std::ostringstream stream;
548 std::string x = filter->freeform;
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++)
555 stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->duration << " :" << filter->reason;
559 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
561 std::string filteraction;
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);
569 std::string filterflags;
570 tokens.GetToken(filterflags);
571 char c = res.FillFlags(filterflags);
573 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
575 tokens.GetToken(res.duration);
576 tokens.GetToken(res.reason);
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++)
586 void ModuleFilter::OnSyncNetwork(ProtocolInterface::Server& server)
588 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
590 server.SendMetaData("filter", EncodeFilter(&(*i)));
594 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
596 if ((target == NULL) && (extname == "filter"))
600 FilterResult data = DecodeFilter(extdata);
601 this->AddFilter(data.freeform, data.action, data.reason, data.duration, data.GetFlags());
603 catch (ModuleException& e)
605 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Error when unserializing filter: " + e.GetReason());
610 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
612 static std::string stripped_text;
613 stripped_text.clear();
615 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
617 FilterResult* filter = &*i;
619 /* Skip ones that dont apply to us */
620 if (!AppliesToMe(user, filter, flgs))
623 if ((filter->flag_strip_color) && (stripped_text.empty()))
625 stripped_text = text;
626 InspIRCd::StripColor(stripped_text);
629 if (filter->regex->Matches(filter->flag_strip_color ? stripped_text : text))
635 bool ModuleFilter::DeleteFilter(const std::string &freeform)
637 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
639 if (i->freeform == freeform)
649 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
651 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
653 if (i->freeform == freeform)
655 return std::make_pair(false, "Filter already exists");
661 filters.push_back(FilterResult(RegexEngine, freeform, reason, type, duration, flgs));
663 catch (ModuleException &e)
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());
668 return std::make_pair(true, "");
671 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
673 if (stdalgo::string::equalsci(str, "gline"))
675 else if (stdalgo::string::equalsci(str, "block"))
677 else if (stdalgo::string::equalsci(str, "silent"))
679 else if (stdalgo::string::equalsci(str, "kill"))
681 else if (stdalgo::string::equalsci(str, "shun") && (ServerInstance->XLines->GetFactory("SHUN")))
683 else if (stdalgo::string::equalsci(str, "none"))
691 std::string ModuleFilter::FilterActionToString(FilterAction fa)
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";
704 void ModuleFilter::ReadFilters()
706 ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
707 for (ConfigIter i = tags.first; i != tags.second; ++i)
709 std::string pattern = i->second->getString("pattern");
710 this->DeleteFilter(pattern);
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);
720 if (!StringToFilterAction(action, fa))
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());
728 catch (ModuleException &e)
730 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason().c_str());
735 ModResult ModuleFilter::OnStats(Stats::Context& stats)
737 if (stats.GetSymbol() == 's')
739 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
741 stats.AddRow(223, RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->duration)+" :"+i->reason);
743 for (ExemptTargetSet::const_iterator i = exemptedchans.begin(); i != exemptedchans.end(); ++i)
745 stats.AddRow(223, "EXEMPT "+(*i));
747 for (ExemptTargetSet::const_iterator i = exemptednicks.begin(); i != exemptednicks.end(); ++i)
749 stats.AddRow(223, "EXEMPT "+(*i));
752 return MOD_RES_PASSTHRU;
755 void ModuleFilter::OnUnloadModule(Module* mod)
757 // If the regex engine became unavailable or has changed, remove all filters
762 else if (RegexEngine.operator->() != factory)
764 factory = RegexEngine.operator->();
769 MODULE_INIT(ModuleFilter)