1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
18 /* $ModDesc: Text (spam) filtering */
40 bool flag_part_message;
41 bool flag_quit_message;
45 FilterResult(const std::string free, const std::string &rea, const std::string &act, long gt, const std::string &fla) :
46 freeform(free), reason(rea), action(act), gline_time(gt), flags(fla)
51 int FillFlags(const std::string &fl)
54 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg = flag_notice = false;
57 for (std::string::const_iterator n = flags.begin(); n != flags.end(); ++n, ++x)
65 flag_part_message = true;
68 flag_quit_message = true;
77 flag_no_opers = flag_part_message = flag_quit_message =
78 flag_privmsg = flag_notice = true;
97 class CommandFilter : public Command
100 CommandFilter(Module* f)
101 : Command(f, "FILTER", 1, 5)
104 this->syntax = "<filter-definition> <action> <flags> [<gline-duration>] :<reason>";
106 CmdResult Handle(const std::vector<std::string>&, User*);
108 void TooFewParams(User* user, const std::string &extra_text)
110 user->WriteServ("NOTICE %s :*** Not enough parameters%s", user->nick.c_str(), extra_text.c_str());
113 RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
115 return ROUTE_BROADCAST;
119 class ImplFilter : public FilterResult
124 ImplFilter(ModuleFilter* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs);
128 class ModuleFilter : public Module
131 CommandFilter filtcommand;
132 dynamic_reference<RegexFactory> RegexEngine;
134 std::vector<ImplFilter> filters;
139 std::vector<std::string> exemptfromfilter; // List of channel names excluded from filtering.
144 ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
145 FilterResult* FilterMatch(User* user, const std::string &text, int flags);
146 bool DeleteFilter(const std::string &freeform);
147 void SyncFilters(Module* proto, void* opaque);
148 void SendFilter(Module* proto, void* opaque, FilterResult* iter);
149 std::pair<bool, std::string> AddFilter(const std::string &freeform, const std::string &type, const std::string &reason, long duration, const std::string &flags);
150 ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
151 void OnRehash(User* user);
152 Version GetVersion();
153 std::string EncodeFilter(FilterResult* filter);
154 FilterResult DecodeFilter(const std::string &data);
155 void OnSyncNetwork(Module* proto, void* opaque);
156 void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata);
157 ModResult OnStats(char symbol, User* user, string_list &results);
158 ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line);
159 bool AppliesToMe(User* user, FilterResult* filter, int flags);
160 void ReadFilters(ConfigReader &MyConf);
163 CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User *user)
165 if (parameters.size() == 1)
167 /* Deleting a filter */
168 Module *me = creator;
169 if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0]))
171 user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str());
172 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', std::string("FILTER: ")+user->nick+" removed filter '"+parameters[0]+"'");
177 user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str());
183 /* Adding a filter */
184 if (parameters.size() >= 4)
186 std::string freeform = parameters[0];
187 std::string type = parameters[1];
188 std::string flags = parameters[2];
193 if ((type != "gline") && (type != "none") && (type != "block") && (type != "kill") && (type != "silent"))
195 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), type.c_str());
201 if (parameters.size() >= 5)
203 duration = ServerInstance->Duration(parameters[3]);
204 reason = parameters[4];
208 this->TooFewParams(user, ": When setting a gline type filter, a gline duration must be specified as the third parameter.");
214 reason = parameters[3];
217 Module *me = creator;
218 std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, reason, duration, flags);
221 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
222 type.c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""),
223 flags.c_str(), reason.c_str());
225 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', std::string("FILTER: ")+user->nick+" added filter '"+freeform+"', type '"+type+"', "+(duration ? "duration "+parameters[3]+", " : "")+"flags '"+flags+"', reason: "+reason);
231 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
237 this->TooFewParams(user, ".");
244 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
246 if ((filter->flag_no_opers) && IS_OPER(user))
248 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
250 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
252 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
254 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
259 ModuleFilter::ModuleFilter() : filtcommand(this), RegexEngine(this, "regex")
263 void ModuleFilter::init()
265 ServerInstance->AddCommand(&filtcommand);
266 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash };
267 ServerInstance->Modules->Attach(eventlist, this, 7);
271 ModuleFilter::~ModuleFilter()
275 ModResult ModuleFilter::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
278 return MOD_RES_PASSTHRU;
280 flags = FLAG_PRIVMSG;
281 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
284 ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
286 /* Leave ulines alone */
287 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
288 return MOD_RES_PASSTHRU;
293 FilterResult* f = this->FilterMatch(user, text, flags);
296 std::string target = "";
297 if (target_type == TYPE_USER)
299 User* t = (User*)dest;
300 target = std::string(t->nick);
302 else if (target_type == TYPE_CHANNEL)
304 Channel* t = (Channel*)dest;
305 target = std::string(t->name);
306 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
307 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
309 if (f->action == "block")
311 ServerInstance->SNO->WriteGlobalSno('a', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
312 if (target_type == TYPE_CHANNEL)
313 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
315 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
317 if (f->action == "silent")
319 if (target_type == TYPE_CHANNEL)
320 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
322 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked: "+f->reason);
324 if (f->action == "kill")
326 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
328 if (f->action == "gline")
330 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
331 if (ServerInstance->XLines->AddLine(gl,NULL))
333 ServerInstance->XLines->ApplyLines();
339 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
342 return MOD_RES_PASSTHRU;
345 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line)
348 if (validated && IS_LOCAL(user))
350 std::string checkline;
351 int replacepoint = 0;
352 bool parting = false;
354 if (command == "QUIT")
356 /* QUIT with no reason: nothing to do */
357 if (parameters.size() < 1)
358 return MOD_RES_PASSTHRU;
360 checkline = parameters[0];
365 else if (command == "PART")
367 /* PART with no reason: nothing to do */
368 if (parameters.size() < 2)
369 return MOD_RES_PASSTHRU;
371 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
372 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
373 checkline = parameters[1];
379 /* We're only messing with PART and QUIT */
380 return MOD_RES_PASSTHRU;
382 FilterResult* f = NULL;
385 f = this->FilterMatch(user, checkline, flags);
388 /* PART or QUIT reason doesnt match a filter */
389 return MOD_RES_PASSTHRU;
391 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
392 Command* c = ServerInstance->Parser->GetHandler(command);
395 std::vector<std::string> params;
396 for (int item = 0; item < (int)parameters.size(); item++)
397 params.push_back(parameters[item]);
398 params[replacepoint] = "Reason filtered";
400 /* We're blocking, OR theyre quitting and its a KILL action
401 * (we cant kill someone whos already quitting, so filter them anyway)
403 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
405 c->Handle(params, user);
410 /* Are they parting, if so, kill is applicable */
411 if ((parting) && (f->action == "kill"))
413 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
414 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
416 if (f->action == "gline")
418 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
419 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
420 if (ServerInstance->XLines->AddLine(gl,NULL))
422 ServerInstance->XLines->ApplyLines();
430 return MOD_RES_PASSTHRU;
432 return MOD_RES_PASSTHRU;
435 void ModuleFilter::OnRehash(User* user)
438 std::vector<std::string>().swap(exemptfromfilter);
439 for (int index = 0; index < MyConf.Enumerate("exemptfromfilter"); ++index)
441 std::string chan = MyConf.ReadValue("exemptfromfilter", "channel", index);
443 exemptfromfilter.push_back(chan);
446 std::string newrxengine = "regex/" + MyConf.ReadValue("filteropts", "engine", 0);
447 if (newrxengine == "regex/")
448 newrxengine = "regex";
449 if (RegexEngine.GetProvider() == newrxengine)
452 //ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.GetProvider().c_str(), newrxengine.c_str());
453 //ServerInstance->XLines->DelAll("R");
455 RegexEngine.SetProvider(newrxengine);
458 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
463 Version ModuleFilter::GetVersion()
465 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
469 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
471 std::ostringstream stream;
472 std::string x = filter->freeform;
474 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
475 for (std::string::iterator n = x.begin(); n != x.end(); n++)
479 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
483 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
486 irc::tokenstream tokens(data);
487 tokens.GetToken(res.freeform);
488 tokens.GetToken(res.action);
489 tokens.GetToken(res.flags);
490 if (res.flags == "-")
492 res.FillFlags(res.flags);
493 tokens.GetToken(res.gline_time);
494 tokens.GetToken(res.reason);
496 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
497 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
504 void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque)
506 this->SyncFilters(proto, opaque);
509 void ModuleFilter::SendFilter(Module* proto, void* opaque, FilterResult* iter)
511 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(iter));
514 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
516 if ((target == NULL) && (extname == "filter"))
518 FilterResult data = DecodeFilter(extdata);
519 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
523 ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
524 : FilterResult(pat, rea, act, glinetime, flgs)
526 if (!mymodule->RegexEngine)
527 throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!");
528 regex = mymodule->RegexEngine->Create(pat);
531 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
533 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
535 /* Skip ones that dont apply to us */
536 if (!AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
539 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
540 if (index->regex->Matches(text))
542 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
543 ImplFilter fr = *index;
544 if (index != filters.begin())
546 /* Move to head of list for efficiency */
547 filters.erase(index);
548 filters.insert(filters.begin(), fr);
550 return &*filters.begin();
552 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
557 bool ModuleFilter::DeleteFilter(const std::string &freeform)
559 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
561 if (i->freeform == freeform)
571 void ModuleFilter::SyncFilters(Module* proto, void* opaque)
573 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
575 this->SendFilter(proto, opaque, &(*i));
579 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, const std::string &type, const std::string &reason, long duration, const std::string &flgs)
581 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
583 if (i->freeform == freeform)
585 return std::make_pair(false, "Filter already exists");
591 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
593 catch (ModuleException &e)
595 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
596 return std::make_pair(false, e.GetReason());
598 return std::make_pair(true, "");
601 void ModuleFilter::ReadFilters(ConfigReader &MyConf)
603 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
605 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
607 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
608 std::string reason = MyConf.ReadValue("keyword", "reason", index);
609 std::string action = MyConf.ReadValue("keyword", "action", index);
610 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
611 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
619 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
620 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
622 catch (ModuleException &e)
624 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
629 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
633 std::string sn = ServerInstance->Config->ServerName;
634 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
636 results.push_back(sn+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
638 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
640 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
643 return MOD_RES_PASSTHRU;
646 MODULE_INIT(ModuleFilter)