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/>.
27 /* $ModDesc: Text (spam) filtering */
57 bool flag_part_message;
58 bool flag_quit_message;
61 bool flag_strip_color;
63 FilterResult(const std::string free, const std::string &rea, FilterAction act, long gt, const std::string &fla) :
64 freeform(free), reason(rea), action(act), gline_time(gt)
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 ImplFilter : public FilterResult
162 ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs);
166 class ModuleFilter : public Module
169 CommandFilter filtcommand;
170 dynamic_reference<RegexFactory> RegexEngine;
172 std::vector<ImplFilter> filters;
177 std::set<std::string> exemptfromfilter; // List of channel names excluded from filtering.
181 ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
182 FilterResult* FilterMatch(User* user, const std::string &text, int flags);
183 bool DeleteFilter(const std::string &freeform);
184 std::pair<bool, std::string> AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flags);
185 ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
186 void OnRehash(User* user);
187 Version GetVersion();
188 std::string EncodeFilter(FilterResult* filter);
189 FilterResult DecodeFilter(const std::string &data);
190 void OnSyncNetwork(Module* proto, void* opaque);
191 void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata);
192 ModResult OnStats(char symbol, User* user, string_list &results);
193 ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line);
194 bool AppliesToMe(User* user, FilterResult* filter, int flags);
196 static bool StringToFilterAction(const std::string& str, FilterAction& fa);
197 static std::string FilterActionToString(FilterAction fa);
200 CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User *user)
202 if (parameters.size() == 1)
204 /* Deleting a filter */
205 Module *me = creator;
206 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
208 user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str());
209 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
214 user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str());
220 /* Adding a filter */
221 if (parameters.size() >= 4)
223 const std::string& freeform = parameters[0];
225 const std::string& flags = parameters[2];
226 unsigned int reasonindex;
229 if (!ModuleFilter::StringToFilterAction(parameters[1], type))
231 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), parameters[1].c_str());
235 if (type == FA_GLINE)
237 if (parameters.size() >= 5)
239 duration = InspIRCd::Duration(parameters[3]);
244 user->WriteServ("NOTICE %s :*** Not enough parameters: When setting a gline type filter, a gline duration must be specified as the third parameter.", user->nick.c_str());
253 Module *me = creator;
254 std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
257 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
258 parameters[1].c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""),
259 flags.c_str(), parameters[reasonindex].c_str());
261 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]);
267 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
273 user->WriteServ("NOTICE %s :*** Not enough parameters.", user->nick.c_str());
280 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
282 if ((filter->flag_no_opers) && IS_OPER(user))
284 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
286 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
288 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
290 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
295 ModuleFilter::ModuleFilter() : filtcommand(this), RegexEngine(this, "regex")
299 void ModuleFilter::init()
301 ServerInstance->Modules->AddService(filtcommand);
302 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash };
303 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
307 ModResult ModuleFilter::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
310 return MOD_RES_PASSTHRU;
312 flags = FLAG_PRIVMSG;
313 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
316 ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
318 /* Leave ulines alone */
319 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
320 return MOD_RES_PASSTHRU;
325 FilterResult* f = this->FilterMatch(user, text, flags);
329 if (target_type == TYPE_USER)
331 User* t = (User*)dest;
334 else if (target_type == TYPE_CHANNEL)
336 Channel* t = (Channel*)dest;
337 if (exemptfromfilter.find(t->name) != exemptfromfilter.end())
338 return MOD_RES_PASSTHRU;
342 if (f->action == FA_BLOCK)
344 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
345 if (target_type == TYPE_CHANNEL)
346 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
348 user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
350 else if (f->action == FA_SILENT)
352 if (target_type == TYPE_CHANNEL)
353 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
355 user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked: "+f->reason);
357 else if (f->action == FA_KILL)
359 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
361 else if (f->action == FA_GLINE)
363 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
364 if (ServerInstance->XLines->AddLine(gl,NULL))
366 ServerInstance->XLines->ApplyLines();
372 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
375 return MOD_RES_PASSTHRU;
378 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line)
380 if (validated && IS_LOCAL(user))
385 if (command == "QUIT")
387 /* QUIT with no reason: nothing to do */
388 if (parameters.size() < 1)
389 return MOD_RES_PASSTHRU;
394 else if (command == "PART")
396 /* PART with no reason: nothing to do */
397 if (parameters.size() < 2)
398 return MOD_RES_PASSTHRU;
400 if (exemptfromfilter.find(parameters[0]) != exemptfromfilter.end())
401 return MOD_RES_PASSTHRU;
407 /* We're only messing with PART and QUIT */
408 return MOD_RES_PASSTHRU;
410 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
412 /* PART or QUIT reason doesnt match a filter */
413 return MOD_RES_PASSTHRU;
415 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
416 parameters[parting ? 1 : 0] = "Reason filtered";
418 /* We're blocking, OR theyre quitting and its a KILL action
419 * (we cant kill someone whos already quitting, so filter them anyway)
421 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
423 return MOD_RES_PASSTHRU;
427 /* Are they parting, if so, kill is applicable */
428 if ((parting) && (f->action == FA_KILL))
430 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
431 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
433 if (f->action == FA_GLINE)
435 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
436 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
437 if (ServerInstance->XLines->AddLine(gl,NULL))
439 ServerInstance->XLines->ApplyLines();
447 return MOD_RES_PASSTHRU;
450 void ModuleFilter::OnRehash(User* user)
452 ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
453 exemptfromfilter.clear();
454 for (ConfigIter i = tags.first; i != tags.second; ++i)
456 std::string chan = i->second->getString("channel");
458 exemptfromfilter.insert(chan);
460 std::string newrxengine = "regex/" + ServerInstance->Config->ConfValue("filteropts")->getString("engine");
461 if (newrxengine == "regex/")
462 newrxengine = "regex";
463 if (RegexEngine.GetProvider() == newrxengine)
466 //ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.GetProvider().c_str(), newrxengine.c_str());
467 //ServerInstance->XLines->DelAll("R");
469 RegexEngine.SetProvider(newrxengine);
472 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
477 Version ModuleFilter::GetVersion()
479 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
482 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
484 std::ostringstream stream;
485 std::string x = filter->freeform;
487 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
488 for (std::string::iterator n = x.begin(); n != x.end(); n++)
492 stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->gline_time << " :" << filter->reason;
496 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
498 std::string filteraction;
500 irc::tokenstream tokens(data);
501 tokens.GetToken(res.freeform);
502 tokens.GetToken(filteraction);
503 if (!StringToFilterAction(filteraction, res.action))
504 throw ModuleException("Invalid action: " + filteraction);
506 std::string filterflags;
507 tokens.GetToken(filterflags);
508 char c = res.FillFlags(filterflags);
510 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
512 tokens.GetToken(res.gline_time);
513 tokens.GetToken(res.reason);
515 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
516 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
523 void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque)
525 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); ++i)
527 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(&(*i)));
531 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
533 if ((target == NULL) && (extname == "filter"))
537 FilterResult data = DecodeFilter(extdata);
538 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.GetFlags());
540 catch (ModuleException& e)
542 ServerInstance->Logs->Log("m_filter", DEBUG, "Error when unserializing filter: " + std::string(e.GetReason()));
547 ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs)
548 : FilterResult(pat, rea, act, glinetime, flgs)
550 if (!mymodule->RegexEngine)
551 throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!");
552 regex = mymodule->RegexEngine->Create(pat);
555 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
557 static std::string stripped_text;
558 stripped_text.clear();
560 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
562 FilterResult* filter = dynamic_cast<FilterResult*>(&(*index));
564 /* Skip ones that dont apply to us */
565 if (!AppliesToMe(user, filter, flgs))
568 if ((filter->flag_strip_color) && (stripped_text.empty()))
570 stripped_text = text;
571 InspIRCd::StripColor(stripped_text);
574 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
575 if (index->regex->Matches(filter->flag_strip_color ? stripped_text : text))
577 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
580 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
585 bool ModuleFilter::DeleteFilter(const std::string &freeform)
587 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
589 if (i->freeform == freeform)
599 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
601 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
603 if (i->freeform == freeform)
605 return std::make_pair(false, "Filter already exists");
611 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
613 catch (ModuleException &e)
615 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
616 return std::make_pair(false, e.GetReason());
618 return std::make_pair(true, "");
621 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
623 irc::string s(str.c_str());
627 else if (s == "block")
629 else if (s == "silent")
631 else if (s == "kill")
633 else if (s == "none")
641 std::string ModuleFilter::FilterActionToString(FilterAction fa)
645 case FA_GLINE: return "gline";
646 case FA_BLOCK: return "block";
647 case FA_SILENT: return "silent";
648 case FA_KILL: return "kill";
649 default: return "none";
653 void ModuleFilter::ReadFilters()
655 ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
656 for (ConfigIter i = tags.first; i != tags.second; ++i)
658 std::string pattern = i->second->getString("pattern");
659 this->DeleteFilter(pattern);
661 std::string reason = i->second->getString("reason");
662 std::string action = i->second->getString("action");
663 std::string flgs = i->second->getString("flags");
664 unsigned long gline_time = InspIRCd::Duration(i->second->getString("duration"));
669 if (!StringToFilterAction(action, fa))
674 filters.push_back(ImplFilter(this, reason, fa, gline_time, pattern, flgs));
675 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
677 catch (ModuleException &e)
679 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
684 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
688 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
690 results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason);
692 for (std::set<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
694 results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :EXEMPT "+(*i));
697 return MOD_RES_PASSTHRU;
700 MODULE_INIT(ModuleFilter)