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"
55 bool flag_part_message;
56 bool flag_quit_message;
59 bool flag_strip_color;
61 FilterResult(const std::string& free, const std::string& rea, FilterAction act, long gt, const std::string& fla) :
62 freeform(free), reason(rea), action(act), gline_time(gt)
67 char FillFlags(const std::string &fl)
69 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
70 flag_notice = flag_strip_color = false;
72 for (std::string::const_iterator n = fl.begin(); n != fl.end(); ++n)
80 flag_part_message = true;
83 flag_quit_message = true;
92 flag_strip_color = true;
95 flag_no_opers = flag_part_message = flag_quit_message =
96 flag_privmsg = flag_notice = flag_strip_color = true;
106 std::string GetFlags()
110 flags.push_back('o');
111 if (flag_part_message)
112 flags.push_back('P');
113 if (flag_quit_message)
114 flags.push_back('q');
116 flags.push_back('p');
118 flags.push_back('n');
120 /* Order is important here, 'c' must be the last char in the string as it is unsupported
121 * on < 2.0.10, and the logic in FillFlags() stops parsing when it ecounters an unknown
124 if (flag_strip_color)
125 flags.push_back('c');
128 flags.push_back('-');
138 class CommandFilter : public Command
141 CommandFilter(Module* f)
142 : Command(f, "FILTER", 1, 5)
145 this->syntax = "<filter-definition> <action> <flags> [<gline-duration>] :<reason>";
147 CmdResult Handle(const std::vector<std::string>&, User*);
149 RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
151 return ROUTE_BROADCAST;
155 class ImplFilter : public FilterResult
160 ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs);
164 class ModuleFilter : public Module
167 RegexFactory* factory;
171 CommandFilter filtcommand;
172 dynamic_reference<RegexFactory> RegexEngine;
174 std::vector<ImplFilter> filters;
177 std::set<std::string> exemptfromfilter; // List of channel names excluded from filtering.
180 void init() CXX11_OVERRIDE;
182 ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE;
183 FilterResult* FilterMatch(User* user, const std::string &text, int flags);
184 bool DeleteFilter(const std::string &freeform);
185 std::pair<bool, std::string> AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flags);
186 void OnRehash(User* user) CXX11_OVERRIDE;
187 Version GetVersion() CXX11_OVERRIDE;
188 std::string EncodeFilter(FilterResult* filter);
189 FilterResult DecodeFilter(const std::string &data);
190 void OnSyncNetwork(Module* proto, void* opaque) CXX11_OVERRIDE;
191 void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) CXX11_OVERRIDE;
192 ModResult OnStats(char symbol, User* user, string_list &results) CXX11_OVERRIDE;
193 ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE;
194 void OnUnloadModule(Module* mod) CXX11_OVERRIDE;
195 bool AppliesToMe(User* user, FilterResult* filter, int flags);
197 static bool StringToFilterAction(const std::string& str, FilterAction& fa);
198 static std::string FilterActionToString(FilterAction fa);
201 CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User *user)
203 if (parameters.size() == 1)
205 /* Deleting a filter */
206 Module *me = creator;
207 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
209 user->WriteNotice("*** Removed filter '" + parameters[0] + "'");
210 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
215 user->WriteNotice("*** Filter '" + parameters[0] + "' not found in list, try /stats s.");
221 /* Adding a filter */
222 if (parameters.size() >= 4)
224 const std::string& freeform = parameters[0];
226 const std::string& flags = parameters[2];
227 unsigned int reasonindex;
230 if (!ModuleFilter::StringToFilterAction(parameters[1], type))
232 user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.");
236 if (type == FA_GLINE)
238 if (parameters.size() >= 5)
240 duration = InspIRCd::Duration(parameters[3]);
245 user->WriteNotice("*** Not enough parameters: When setting a gline type filter, a gline duration must be specified as the third parameter.");
254 Module *me = creator;
255 std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
258 user->WriteNotice("*** Added filter '" + freeform + "', type '" + parameters[1] + "'" +
259 (duration ? ", duration " + parameters[3] : "") + ", flags '" + flags + "', reason: '" +
260 parameters[reasonindex] + "'");
262 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]);
268 user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second);
274 user->WriteNotice("*** Not enough parameters.");
281 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
283 if ((filter->flag_no_opers) && user->IsOper())
285 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
287 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
289 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
291 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
296 ModuleFilter::ModuleFilter()
297 : initing(true), filtcommand(this), RegexEngine(this, "regex")
301 void ModuleFilter::init()
303 ServerInstance->Modules->AddService(filtcommand);
304 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnRehash, I_OnUnloadModule };
305 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
309 CullResult ModuleFilter::cull()
312 return Module::cull();
315 void ModuleFilter::FreeFilters()
317 for (std::vector<ImplFilter>::const_iterator i = filters.begin(); i != filters.end(); ++i)
323 ModResult ModuleFilter::OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype)
325 /* Leave ulines alone */
326 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
327 return MOD_RES_PASSTHRU;
329 flags = (msgtype == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE;
331 FilterResult* f = this->FilterMatch(user, text, flags);
335 if (target_type == TYPE_USER)
337 User* t = (User*)dest;
340 else if (target_type == TYPE_CHANNEL)
342 Channel* t = (Channel*)dest;
343 if (exemptfromfilter.find(t->name) != exemptfromfilter.end())
344 return MOD_RES_PASSTHRU;
348 if (f->action == FA_BLOCK)
350 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
351 if (target_type == TYPE_CHANNEL)
352 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
354 user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason);
356 else if (f->action == FA_SILENT)
358 if (target_type == TYPE_CHANNEL)
359 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
361 user->WriteNotice("Your message to "+target+" was blocked: "+f->reason);
363 else if (f->action == FA_KILL)
365 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
367 else if (f->action == FA_GLINE)
369 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
370 if (ServerInstance->XLines->AddLine(gl,NULL))
372 ServerInstance->XLines->ApplyLines();
378 ServerInstance->Logs->Log("FILTER", LOG_DEFAULT, "FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
381 return MOD_RES_PASSTHRU;
384 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line)
386 if (validated && IS_LOCAL(user))
391 if (command == "QUIT")
393 /* QUIT with no reason: nothing to do */
394 if (parameters.size() < 1)
395 return MOD_RES_PASSTHRU;
400 else if (command == "PART")
402 /* PART with no reason: nothing to do */
403 if (parameters.size() < 2)
404 return MOD_RES_PASSTHRU;
406 if (exemptfromfilter.find(parameters[0]) != exemptfromfilter.end())
407 return MOD_RES_PASSTHRU;
413 /* We're only messing with PART and QUIT */
414 return MOD_RES_PASSTHRU;
416 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
418 /* PART or QUIT reason doesnt match a filter */
419 return MOD_RES_PASSTHRU;
421 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
422 parameters[parting ? 1 : 0] = "Reason filtered";
424 /* We're blocking, OR theyre quitting and its a KILL action
425 * (we cant kill someone whos already quitting, so filter them anyway)
427 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
429 return MOD_RES_PASSTHRU;
433 /* Are they parting, if so, kill is applicable */
434 if ((parting) && (f->action == FA_KILL))
436 user->WriteNotice("*** Your PART message was filtered: " + f->reason);
437 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
439 if (f->action == FA_GLINE)
441 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
442 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
443 if (ServerInstance->XLines->AddLine(gl,NULL))
445 ServerInstance->XLines->ApplyLines();
453 return MOD_RES_PASSTHRU;
456 void ModuleFilter::OnRehash(User* user)
458 ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
459 exemptfromfilter.clear();
460 for (ConfigIter i = tags.first; i != tags.second; ++i)
462 std::string chan = i->second->getString("channel");
464 exemptfromfilter.insert(chan);
467 std::string newrxengine = ServerInstance->Config->ConfValue("filteropts")->getString("engine");
469 factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
471 if (newrxengine.empty())
472 RegexEngine.SetProvider("regex");
474 RegexEngine.SetProvider("regex/" + newrxengine);
478 if (newrxengine.empty())
479 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
481 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
488 if ((!initing) && (RegexEngine.operator->() != factory))
490 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change");
498 Version ModuleFilter::GetVersion()
500 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
503 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
505 std::ostringstream stream;
506 std::string x = filter->freeform;
508 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
509 for (std::string::iterator n = x.begin(); n != x.end(); n++)
513 stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->gline_time << " :" << filter->reason;
517 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
519 std::string filteraction;
521 irc::tokenstream tokens(data);
522 tokens.GetToken(res.freeform);
523 tokens.GetToken(filteraction);
524 if (!StringToFilterAction(filteraction, res.action))
525 throw ModuleException("Invalid action: " + filteraction);
527 std::string filterflags;
528 tokens.GetToken(filterflags);
529 char c = res.FillFlags(filterflags);
531 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
533 tokens.GetToken(res.gline_time);
534 tokens.GetToken(res.reason);
536 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
537 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
544 void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque)
546 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); ++i)
548 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(&(*i)));
552 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
554 if ((target == NULL) && (extname == "filter"))
558 FilterResult data = DecodeFilter(extdata);
559 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.GetFlags());
561 catch (ModuleException& e)
563 ServerInstance->Logs->Log("m_filter", LOG_DEBUG, "Error when unserializing filter: " + std::string(e.GetReason()));
568 ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs)
569 : FilterResult(pat, rea, act, glinetime, flgs)
571 if (!mymodule->RegexEngine)
572 throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!");
573 regex = mymodule->RegexEngine->Create(pat);
576 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
578 static std::string stripped_text;
579 stripped_text.clear();
581 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
583 FilterResult* filter = dynamic_cast<FilterResult*>(&(*index));
585 /* Skip ones that dont apply to us */
586 if (!AppliesToMe(user, filter, flgs))
589 if ((filter->flag_strip_color) && (stripped_text.empty()))
591 stripped_text = text;
592 InspIRCd::StripColor(stripped_text);
595 if (index->regex->Matches(filter->flag_strip_color ? stripped_text : text))
601 bool ModuleFilter::DeleteFilter(const std::string &freeform)
603 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
605 if (i->freeform == freeform)
615 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
617 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
619 if (i->freeform == freeform)
621 return std::make_pair(false, "Filter already exists");
627 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
629 catch (ModuleException &e)
631 ServerInstance->Logs->Log("m_filter", LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
632 return std::make_pair(false, e.GetReason());
634 return std::make_pair(true, "");
637 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
639 irc::string s(str.c_str());
643 else if (s == "block")
645 else if (s == "silent")
647 else if (s == "kill")
649 else if (s == "none")
657 std::string ModuleFilter::FilterActionToString(FilterAction fa)
661 case FA_GLINE: return "gline";
662 case FA_BLOCK: return "block";
663 case FA_SILENT: return "silent";
664 case FA_KILL: return "kill";
665 default: return "none";
669 void ModuleFilter::ReadFilters()
671 ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
672 for (ConfigIter i = tags.first; i != tags.second; ++i)
674 std::string pattern = i->second->getString("pattern");
675 this->DeleteFilter(pattern);
677 std::string reason = i->second->getString("reason");
678 std::string action = i->second->getString("action");
679 std::string flgs = i->second->getString("flags");
680 unsigned long gline_time = InspIRCd::Duration(i->second->getString("duration"));
685 if (!StringToFilterAction(action, fa))
690 filters.push_back(ImplFilter(this, reason, fa, gline_time, pattern, flgs));
691 ServerInstance->Logs->Log("m_filter", LOG_DEFAULT, "Regular expression %s loaded.", pattern.c_str());
693 catch (ModuleException &e)
695 ServerInstance->Logs->Log("m_filter", LOG_DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
700 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
704 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
706 results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason);
708 for (std::set<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
710 results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :EXEMPT "+(*i));
713 return MOD_RES_PASSTHRU;
716 void ModuleFilter::OnUnloadModule(Module* mod)
718 // If the regex engine became unavailable or has changed, remove all filters
723 else if (RegexEngine.operator->() != factory)
725 factory = RegexEngine.operator->();
730 MODULE_INIT(ModuleFilter)