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 */
58 bool flag_part_message;
59 bool flag_quit_message;
62 bool flag_strip_color;
64 FilterResult(const std::string free, const std::string &rea, FilterAction act, long gt, const std::string &fla) :
65 freeform(free), reason(rea), action(act), gline_time(gt), flags(fla)
70 int FillFlags(const std::string &fl)
73 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
74 flag_notice = flag_strip_color = false;
77 for (std::string::const_iterator n = flags.begin(); n != flags.end(); ++n, ++x)
85 flag_part_message = true;
88 flag_quit_message = true;
97 flag_strip_color = true;
100 flag_no_opers = flag_part_message = flag_quit_message =
101 flag_privmsg = flag_notice = flag_strip_color = true;
116 class CommandFilter : public Command
119 CommandFilter(Module* f)
120 : Command(f, "FILTER", 1, 5)
123 this->syntax = "<filter-definition> <action> <flags> [<gline-duration>] :<reason>";
125 CmdResult Handle(const std::vector<std::string>&, User*);
127 RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
129 return ROUTE_BROADCAST;
133 class ImplFilter : public FilterResult
138 ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs);
142 class ModuleFilter : public Module
145 CommandFilter filtcommand;
146 dynamic_reference<RegexFactory> RegexEngine;
148 std::vector<ImplFilter> filters;
153 std::vector<std::string> exemptfromfilter; // List of channel names excluded from filtering.
157 ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
158 FilterResult* FilterMatch(User* user, const std::string &text, int flags);
159 bool DeleteFilter(const std::string &freeform);
160 std::pair<bool, std::string> AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flags);
161 ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
162 void OnRehash(User* user);
163 Version GetVersion();
164 std::string EncodeFilter(FilterResult* filter);
165 FilterResult DecodeFilter(const std::string &data);
166 void OnSyncNetwork(Module* proto, void* opaque);
167 void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata);
168 ModResult OnStats(char symbol, User* user, string_list &results);
169 ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line);
170 bool AppliesToMe(User* user, FilterResult* filter, int flags);
171 void ReadFilters(ConfigReader &MyConf);
172 static bool StringToFilterAction(const std::string& str, FilterAction& fa);
173 static std::string FilterActionToString(FilterAction fa);
176 CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User *user)
178 if (parameters.size() == 1)
180 /* Deleting a filter */
181 Module *me = creator;
182 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
184 user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str());
185 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'");
190 user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str());
196 /* Adding a filter */
197 if (parameters.size() >= 4)
199 std::string freeform = parameters[0];
201 std::string flags = parameters[2];
205 if (!ModuleFilter::StringToFilterAction(parameters[1], type))
207 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());
211 if (type == FA_GLINE)
213 if (parameters.size() >= 5)
215 duration = ServerInstance->Duration(parameters[3]);
216 reason = parameters[4];
220 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());
226 reason = parameters[3];
229 Module *me = creator;
230 std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, reason, duration, flags);
233 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
234 parameters[1].c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""),
235 flags.c_str(), reason.c_str());
237 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" added filter '"+freeform+"', type '"+parameters[1]+"', "+(duration ? "duration "+parameters[3]+", " : "")+"flags '"+flags+"', reason: "+reason);
243 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
249 user->WriteServ("NOTICE %s :*** Not enough parameters.", user->nick.c_str());
256 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
258 if ((filter->flag_no_opers) && IS_OPER(user))
260 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
262 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
264 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
266 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
271 ModuleFilter::ModuleFilter() : filtcommand(this), RegexEngine(this, "regex")
275 void ModuleFilter::init()
277 ServerInstance->AddCommand(&filtcommand);
278 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash };
279 ServerInstance->Modules->Attach(eventlist, this, 7);
283 ModResult ModuleFilter::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
286 return MOD_RES_PASSTHRU;
288 flags = FLAG_PRIVMSG;
289 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
292 ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
294 /* Leave ulines alone */
295 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
296 return MOD_RES_PASSTHRU;
301 FilterResult* f = this->FilterMatch(user, text, flags);
304 std::string target = "";
305 if (target_type == TYPE_USER)
307 User* t = (User*)dest;
310 else if (target_type == TYPE_CHANNEL)
312 Channel* t = (Channel*)dest;
313 target = std::string(t->name);
314 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
315 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
317 if (f->action == FA_BLOCK)
319 ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason);
320 if (target_type == TYPE_CHANNEL)
321 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
323 user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
325 else if (f->action == FA_SILENT)
327 if (target_type == TYPE_CHANNEL)
328 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
330 user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked: "+f->reason);
332 else if (f->action == FA_KILL)
334 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
336 else if (f->action == FA_GLINE)
338 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
339 if (ServerInstance->XLines->AddLine(gl,NULL))
341 ServerInstance->XLines->ApplyLines();
347 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
350 return MOD_RES_PASSTHRU;
353 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line)
356 if (validated && IS_LOCAL(user))
358 std::string checkline;
359 int replacepoint = 0;
360 bool parting = false;
362 if (command == "QUIT")
364 /* QUIT with no reason: nothing to do */
365 if (parameters.size() < 1)
366 return MOD_RES_PASSTHRU;
368 checkline = parameters[0];
373 else if (command == "PART")
375 /* PART with no reason: nothing to do */
376 if (parameters.size() < 2)
377 return MOD_RES_PASSTHRU;
379 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
380 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
381 checkline = parameters[1];
387 /* We're only messing with PART and QUIT */
388 return MOD_RES_PASSTHRU;
390 FilterResult* f = NULL;
393 f = this->FilterMatch(user, checkline, flags);
396 /* PART or QUIT reason doesnt match a filter */
397 return MOD_RES_PASSTHRU;
399 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
400 Command* c = ServerInstance->Parser->GetHandler(command);
403 std::vector<std::string> params;
404 for (int item = 0; item < (int)parameters.size(); item++)
405 params.push_back(parameters[item]);
406 params[replacepoint] = "Reason filtered";
408 /* We're blocking, OR theyre quitting and its a KILL action
409 * (we cant kill someone whos already quitting, so filter them anyway)
411 if ((f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
413 c->Handle(params, user);
418 /* Are they parting, if so, kill is applicable */
419 if ((parting) && (f->action == FA_KILL))
421 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
422 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
424 if (f->action == FA_GLINE)
426 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
427 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
428 if (ServerInstance->XLines->AddLine(gl,NULL))
430 ServerInstance->XLines->ApplyLines();
438 return MOD_RES_PASSTHRU;
440 return MOD_RES_PASSTHRU;
443 void ModuleFilter::OnRehash(User* user)
446 std::vector<std::string>().swap(exemptfromfilter);
447 for (int index = 0; index < MyConf.Enumerate("exemptfromfilter"); ++index)
449 std::string chan = MyConf.ReadValue("exemptfromfilter", "channel", index);
451 exemptfromfilter.push_back(chan);
454 std::string newrxengine = "regex/" + MyConf.ReadValue("filteropts", "engine", 0);
455 if (newrxengine == "regex/")
456 newrxengine = "regex";
457 if (RegexEngine.GetProvider() == newrxengine)
460 //ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.GetProvider().c_str(), newrxengine.c_str());
461 //ServerInstance->XLines->DelAll("R");
463 RegexEngine.SetProvider(newrxengine);
466 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
471 Version ModuleFilter::GetVersion()
473 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
476 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
478 std::ostringstream stream;
479 std::string x = filter->freeform;
481 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
482 for (std::string::iterator n = x.begin(); n != x.end(); n++)
486 stream << x << " " << FilterActionToString(filter->action) << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
490 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
492 std::string filteraction;
494 irc::tokenstream tokens(data);
495 tokens.GetToken(res.freeform);
496 tokens.GetToken(filteraction);
497 if (!StringToFilterAction(filteraction, res.action))
498 throw ModuleException("Invalid action: " + filteraction);
500 tokens.GetToken(res.flags);
501 if (res.flags == "-")
503 res.FillFlags(res.flags);
504 tokens.GetToken(res.gline_time);
505 tokens.GetToken(res.reason);
507 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
508 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
515 void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque)
517 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); ++i)
519 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(&(*i)));
523 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
525 if ((target == NULL) && (extname == "filter"))
529 FilterResult data = DecodeFilter(extdata);
530 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
532 catch (ModuleException& e)
534 ServerInstance->Logs->Log("m_filter", DEBUG, "Error when unserializing filter: " + std::string(e.GetReason()));
539 ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs)
540 : FilterResult(pat, rea, act, glinetime, flgs)
542 if (!mymodule->RegexEngine)
543 throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!");
544 regex = mymodule->RegexEngine->Create(pat);
547 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
549 static std::string stripped_text;
550 stripped_text.clear();
552 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
554 FilterResult* filter = dynamic_cast<FilterResult*>(&(*index));
556 /* Skip ones that dont apply to us */
557 if (!AppliesToMe(user, filter, flgs))
560 if ((filter->flag_strip_color) && (stripped_text.empty()))
562 stripped_text = text;
563 InspIRCd::StripColor(stripped_text);
566 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
567 if (index->regex->Matches(filter->flag_strip_color ? stripped_text : text))
569 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
570 ImplFilter fr = *index;
571 if (index != filters.begin())
573 /* Move to head of list for efficiency */
574 filters.erase(index);
575 filters.insert(filters.begin(), fr);
577 return &*filters.begin();
579 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
584 bool ModuleFilter::DeleteFilter(const std::string &freeform)
586 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
588 if (i->freeform == freeform)
598 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs)
600 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
602 if (i->freeform == freeform)
604 return std::make_pair(false, "Filter already exists");
610 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
612 catch (ModuleException &e)
614 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
615 return std::make_pair(false, e.GetReason());
617 return std::make_pair(true, "");
620 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
622 irc::string s(str.c_str());
626 else if (s == "block")
628 else if (s == "silent")
630 else if (s == "kill")
632 else if (s == "none")
640 std::string ModuleFilter::FilterActionToString(FilterAction fa)
644 case FA_GLINE: return "gline";
645 case FA_BLOCK: return "block";
646 case FA_SILENT: return "silent";
647 case FA_KILL: return "kill";
648 default: return "none";
652 void ModuleFilter::ReadFilters(ConfigReader &MyConf)
654 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
656 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
658 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
659 std::string reason = MyConf.ReadValue("keyword", "reason", index);
660 std::string action = MyConf.ReadValue("keyword", "action", index);
661 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
662 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
667 if (!StringToFilterAction(action, fa))
672 filters.push_back(ImplFilter(this, reason, fa, gline_time, pattern, flgs));
673 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
675 catch (ModuleException &e)
677 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
682 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
686 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
688 results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->flags+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason);
690 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
692 results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :EXEMPT "+(*i));
695 return MOD_RES_PASSTHRU;
698 MODULE_INIT(ModuleFilter)