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"
54 bool flag_part_message;
55 bool flag_quit_message;
58 bool flag_strip_color;
60 FilterResult(dynamic_reference<RegexFactory>& RegexEngine, const std::string& free, const std::string& rea, FilterAction act, long gt, const std::string& fla)
61 : freeform(free), reason(rea), action(act), gline_time(gt)
64 throw ModuleException("Regex module implementing '"+RegexEngine.GetProvider()+"' is not loaded!");
65 regex = RegexEngine->Create(free);
69 char FillFlags(const std::string &fl)
71 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
72 flag_notice = flag_strip_color = false;
74 for (std::string::const_iterator n = fl.begin(); n != fl.end(); ++n)
82 flag_part_message = true;
85 flag_quit_message = true;
94 flag_strip_color = true;
97 flag_no_opers = flag_part_message = flag_quit_message =
98 flag_privmsg = flag_notice = flag_strip_color = true;
108 std::string GetFlags()
112 flags.push_back('o');
113 if (flag_part_message)
114 flags.push_back('P');
115 if (flag_quit_message)
116 flags.push_back('q');
118 flags.push_back('p');
120 flags.push_back('n');
122 /* Order is important here, 'c' must be the last char in the string as it is unsupported
123 * on < 2.0.10, and the logic in FillFlags() stops parsing when it ecounters an unknown
126 if (flag_strip_color)
127 flags.push_back('c');
130 flags.push_back('-');
140 class CommandFilter : public Command
143 CommandFilter(Module* f)
144 : Command(f, "FILTER", 1, 5)
147 this->syntax = "<filter-definition> <action> <flags> [<gline-duration>] :<reason>";
149 CmdResult Handle(const std::vector<std::string>&, User*);
151 RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
153 return ROUTE_BROADCAST;
157 class ModuleFilter : public Module
159 typedef std::set<std::string, irc::insensitive_swo> ExemptTargetSet;
162 RegexFactory* factory;
166 CommandFilter filtcommand;
167 dynamic_reference<RegexFactory> RegexEngine;
169 std::vector<FilterResult> filters;
172 // List of channel names excluded from filtering.
173 ExemptTargetSet exemptedchans;
177 ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE;
178 FilterResult* FilterMatch(User* user, const std::string &text, int flags);
179 bool DeleteFilter(const std::string &freeform);
180 std::pair<bool, std::string> AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flags);
181 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE;
182 Version GetVersion() CXX11_OVERRIDE;
183 std::string EncodeFilter(FilterResult* filter);
184 FilterResult DecodeFilter(const std::string &data);
185 void OnSyncNetwork(ProtocolInterface::Server& server) CXX11_OVERRIDE;
186 void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) CXX11_OVERRIDE;
187 ModResult OnStats(char symbol, User* user, string_list &results) CXX11_OVERRIDE;
188 ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE;
189 void OnUnloadModule(Module* mod) CXX11_OVERRIDE;
190 bool AppliesToMe(User* user, FilterResult* filter, int flags);
192 static bool StringToFilterAction(const std::string& str, FilterAction& fa);
193 static std::string FilterActionToString(FilterAction fa);
196 CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User *user)
198 if (parameters.size() == 1)
200 /* Deleting a filter */
201 Module *me = creator;
202 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
204 user->WriteNotice("*** Removed filter '" + parameters[0] + "'");
205 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
210 user->WriteNotice("*** Filter '" + parameters[0] + "' not found in list, try /stats s.");
216 /* Adding a filter */
217 if (parameters.size() >= 4)
219 const std::string& freeform = parameters[0];
221 const std::string& flags = parameters[2];
222 unsigned int reasonindex;
225 if (!ModuleFilter::StringToFilterAction(parameters[1], type))
227 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.");
231 if (type == FA_GLINE)
233 if (parameters.size() >= 5)
235 duration = InspIRCd::Duration(parameters[3]);
240 user->WriteNotice("*** Not enough parameters: When setting a gline type filter, a gline duration must be specified as the third parameter.");
249 Module *me = creator;
250 std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
253 user->WriteNotice("*** Added filter '" + freeform + "', type '" + parameters[1] + "'" +
254 (duration ? ", duration " + parameters[3] : "") + ", flags '" + flags + "', reason: '" +
255 parameters[reasonindex] + "'");
257 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]);
263 user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second);
269 user->WriteNotice("*** Not enough parameters.");
276 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
278 if ((filter->flag_no_opers) && user->IsOper())
280 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
282 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
284 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
286 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
291 ModuleFilter::ModuleFilter()
292 : initing(true), filtcommand(this), RegexEngine(this, "regex")
296 CullResult ModuleFilter::cull()
299 return Module::cull();
302 void ModuleFilter::FreeFilters()
304 for (std::vector<FilterResult>::const_iterator i = filters.begin(); i != filters.end(); ++i)
310 ModResult ModuleFilter::OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype)
312 // Leave remote users and servers alone
314 return MOD_RES_PASSTHRU;
316 flags = (msgtype == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE;
318 FilterResult* f = this->FilterMatch(user, text, flags);
322 if (target_type == TYPE_USER)
324 User* t = (User*)dest;
327 else if (target_type == TYPE_CHANNEL)
329 Channel* t = (Channel*)dest;
330 if (exemptedchans.count(t->name))
331 return MOD_RES_PASSTHRU;
335 if (f->action == FA_BLOCK)
337 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
338 if (target_type == TYPE_CHANNEL)
339 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Message to channel blocked and opers notified (%s)", target.c_str(), f->reason.c_str());
341 user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason);
343 else if (f->action == FA_SILENT)
345 if (target_type == TYPE_CHANNEL)
346 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Message to channel blocked (%s)", target.c_str(), f->reason.c_str());
348 user->WriteNotice("Your message to "+target+" was blocked: "+f->reason);
350 else if (f->action == FA_KILL)
352 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
354 else if (f->action == FA_GLINE)
356 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
357 if (ServerInstance->XLines->AddLine(gl,NULL))
359 ServerInstance->XLines->ApplyLines();
365 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
368 return MOD_RES_PASSTHRU;
371 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line)
373 if (validated && IS_LOCAL(user))
378 if (command == "QUIT")
380 /* QUIT with no reason: nothing to do */
381 if (parameters.size() < 1)
382 return MOD_RES_PASSTHRU;
387 else if (command == "PART")
389 /* PART with no reason: nothing to do */
390 if (parameters.size() < 2)
391 return MOD_RES_PASSTHRU;
393 if (exemptedchans.count(parameters[0]))
394 return MOD_RES_PASSTHRU;
400 /* We're only messing with PART and QUIT */
401 return MOD_RES_PASSTHRU;
403 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
405 /* PART or QUIT reason doesnt match a filter */
406 return MOD_RES_PASSTHRU;
408 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
409 parameters[parting ? 1 : 0] = "Reason filtered";
411 /* We're blocking, OR theyre quitting and its a KILL action
412 * (we cant kill someone whos already quitting, so filter them anyway)
414 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
416 return MOD_RES_PASSTHRU;
420 /* Are they parting, if so, kill is applicable */
421 if ((parting) && (f->action == FA_KILL))
423 user->WriteNotice("*** Your PART message was filtered: " + f->reason);
424 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
426 if (f->action == FA_GLINE)
428 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
429 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
430 if (ServerInstance->XLines->AddLine(gl,NULL))
432 ServerInstance->XLines->ApplyLines();
440 return MOD_RES_PASSTHRU;
443 void ModuleFilter::ReadConfig(ConfigStatus& status)
445 ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
446 exemptedchans.clear();
447 for (ConfigIter i = tags.first; i != tags.second; ++i)
449 ConfigTag* tag = i->second;
451 // If "target" is not found, try the old "channel" key to keep compatibility with 2.0 configs
452 const std::string target = tag->getString("target", tag->getString("channel"));
454 exemptedchans.insert(target);
457 std::string newrxengine = ServerInstance->Config->ConfValue("filteropts")->getString("engine");
459 factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
461 if (newrxengine.empty())
462 RegexEngine.SetProvider("regex");
464 RegexEngine.SetProvider("regex/" + newrxengine);
468 if (newrxengine.empty())
469 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
471 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
478 if ((!initing) && (RegexEngine.operator->() != factory))
480 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change");
488 Version ModuleFilter::GetVersion()
490 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
493 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
495 std::ostringstream stream;
496 std::string x = filter->freeform;
498 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
499 for (std::string::iterator n = x.begin(); n != x.end(); n++)
503 stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->gline_time << " :" << filter->reason;
507 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
509 std::string filteraction;
511 irc::tokenstream tokens(data);
512 tokens.GetToken(res.freeform);
513 tokens.GetToken(filteraction);
514 if (!StringToFilterAction(filteraction, res.action))
515 throw ModuleException("Invalid action: " + filteraction);
517 std::string filterflags;
518 tokens.GetToken(filterflags);
519 char c = res.FillFlags(filterflags);
521 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
523 tokens.GetToken(res.gline_time);
524 tokens.GetToken(res.reason);
526 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
527 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
534 void ModuleFilter::OnSyncNetwork(ProtocolInterface::Server& server)
536 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
538 server.SendMetaData("filter", EncodeFilter(&(*i)));
542 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
544 if ((target == NULL) && (extname == "filter"))
548 FilterResult data = DecodeFilter(extdata);
549 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.GetFlags());
551 catch (ModuleException& e)
553 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Error when unserializing filter: " + e.GetReason());
558 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
560 static std::string stripped_text;
561 stripped_text.clear();
563 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
565 FilterResult* filter = &*i;
567 /* Skip ones that dont apply to us */
568 if (!AppliesToMe(user, filter, flgs))
571 if ((filter->flag_strip_color) && (stripped_text.empty()))
573 stripped_text = text;
574 InspIRCd::StripColor(stripped_text);
577 if (filter->regex->Matches(filter->flag_strip_color ? stripped_text : text))
583 bool ModuleFilter::DeleteFilter(const std::string &freeform)
585 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
587 if (i->freeform == freeform)
597 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
599 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
601 if (i->freeform == freeform)
603 return std::make_pair(false, "Filter already exists");
609 filters.push_back(FilterResult(RegexEngine, freeform, reason, type, duration, flgs));
611 catch (ModuleException &e)
613 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason().c_str());
614 return std::make_pair(false, e.GetReason());
616 return std::make_pair(true, "");
619 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
621 irc::string s(str.c_str());
625 else if (s == "block")
627 else if (s == "silent")
629 else if (s == "kill")
631 else if (s == "none")
639 std::string ModuleFilter::FilterActionToString(FilterAction fa)
643 case FA_GLINE: return "gline";
644 case FA_BLOCK: return "block";
645 case FA_SILENT: return "silent";
646 case FA_KILL: return "kill";
647 default: return "none";
651 void ModuleFilter::ReadFilters()
653 ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
654 for (ConfigIter i = tags.first; i != tags.second; ++i)
656 std::string pattern = i->second->getString("pattern");
657 this->DeleteFilter(pattern);
659 std::string reason = i->second->getString("reason");
660 std::string action = i->second->getString("action");
661 std::string flgs = i->second->getString("flags");
662 unsigned long gline_time = i->second->getDuration("duration", 10*60, 1);
667 if (!StringToFilterAction(action, fa))
672 filters.push_back(FilterResult(RegexEngine, pattern, reason, fa, gline_time, flgs));
673 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Regular expression %s loaded.", pattern.c_str());
675 catch (ModuleException &e)
677 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason().c_str());
682 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
686 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
688 results.push_back("223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason);
690 for (ExemptTargetSet::const_iterator i = exemptedchans.begin(); i != exemptedchans.end(); ++i)
692 results.push_back("223 "+user->nick+" :EXEMPT "+(*i));
695 return MOD_RES_PASSTHRU;
698 void ModuleFilter::OnUnloadModule(Module* mod)
700 // If the regex engine became unavailable or has changed, remove all filters
705 else if (RegexEngine.operator->() != factory)
707 factory = RegexEngine.operator->();
712 MODULE_INIT(ModuleFilter)