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 if (static_cast<ModuleFilter&>(*creator).DeleteFilter(parameters[0]))
170 user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str());
171 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', std::string("FILTER: ")+user->nick+" removed filter '"+parameters[0]+"'");
176 user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str());
182 /* Adding a filter */
183 if (parameters.size() >= 4)
185 std::string freeform = parameters[0];
186 std::string type = parameters[1];
187 std::string flags = parameters[2];
192 if ((type != "gline") && (type != "none") && (type != "block") && (type != "kill") && (type != "silent"))
194 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), type.c_str());
200 if (parameters.size() >= 5)
202 duration = ServerInstance->Duration(parameters[3]);
203 reason = parameters[4];
207 this->TooFewParams(user, ": When setting a gline type filter, a gline duration must be specified as the third parameter.");
213 reason = parameters[3];
215 std::pair<bool, std::string> result = static_cast<ModuleFilter&>(*creator).AddFilter(freeform, type, reason, duration, flags);
218 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
219 type.c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""),
220 flags.c_str(), reason.c_str());
222 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);
228 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
234 this->TooFewParams(user, ".");
241 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
243 if ((filter->flag_no_opers) && IS_OPER(user))
245 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
247 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
249 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
251 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
256 ModuleFilter::ModuleFilter() : filtcommand(this), RegexEngine(this, "regex")
260 void ModuleFilter::init()
262 ServerInstance->AddCommand(&filtcommand);
263 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash };
264 ServerInstance->Modules->Attach(eventlist, this, 7);
268 ModuleFilter::~ModuleFilter()
272 ModResult ModuleFilter::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
275 return MOD_RES_PASSTHRU;
277 flags = FLAG_PRIVMSG;
278 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
281 ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
283 /* Leave ulines alone */
284 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
285 return MOD_RES_PASSTHRU;
290 FilterResult* f = this->FilterMatch(user, text, flags);
293 std::string target = "";
294 if (target_type == TYPE_USER)
296 User* t = (User*)dest;
297 target = std::string(t->nick);
299 else if (target_type == TYPE_CHANNEL)
301 Channel* t = (Channel*)dest;
302 target = std::string(t->name);
303 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
304 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
306 if (f->action == "block")
308 ServerInstance->SNO->WriteGlobalSno('a', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
309 if (target_type == TYPE_CHANNEL)
310 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
312 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
314 if (f->action == "silent")
316 if (target_type == TYPE_CHANNEL)
317 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
319 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked: "+f->reason);
321 if (f->action == "kill")
323 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
325 if (f->action == "gline")
327 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
328 if (ServerInstance->XLines->AddLine(gl,NULL))
330 ServerInstance->XLines->ApplyLines();
336 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
339 return MOD_RES_PASSTHRU;
342 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line)
345 if (validated && IS_LOCAL(user))
347 std::string checkline;
348 int replacepoint = 0;
349 bool parting = false;
351 if (command == "QUIT")
353 /* QUIT with no reason: nothing to do */
354 if (parameters.size() < 1)
355 return MOD_RES_PASSTHRU;
357 checkline = parameters[0];
362 else if (command == "PART")
364 /* PART with no reason: nothing to do */
365 if (parameters.size() < 2)
366 return MOD_RES_PASSTHRU;
368 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
369 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
370 checkline = parameters[1];
376 /* We're only messing with PART and QUIT */
377 return MOD_RES_PASSTHRU;
379 FilterResult* f = NULL;
382 f = this->FilterMatch(user, checkline, flags);
385 /* PART or QUIT reason doesnt match a filter */
386 return MOD_RES_PASSTHRU;
388 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
389 Command* c = ServerInstance->Parser->GetHandler(command);
392 std::vector<std::string> params;
393 for (int item = 0; item < (int)parameters.size(); item++)
394 params.push_back(parameters[item]);
395 params[replacepoint] = "Reason filtered";
397 /* We're blocking, OR theyre quitting and its a KILL action
398 * (we cant kill someone whos already quitting, so filter them anyway)
400 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
402 c->Handle(params, user);
407 /* Are they parting, if so, kill is applicable */
408 if ((parting) && (f->action == "kill"))
410 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
411 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
413 if (f->action == "gline")
415 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
416 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
417 if (ServerInstance->XLines->AddLine(gl,NULL))
419 ServerInstance->XLines->ApplyLines();
427 return MOD_RES_PASSTHRU;
429 return MOD_RES_PASSTHRU;
432 void ModuleFilter::OnRehash(User* user)
435 std::vector<std::string>().swap(exemptfromfilter);
436 for (int index = 0; index < MyConf.Enumerate("exemptfromfilter"); ++index)
438 std::string chan = MyConf.ReadValue("exemptfromfilter", "channel", index);
440 exemptfromfilter.push_back(chan);
443 std::string newrxengine = "regex/" + MyConf.ReadValue("filteropts", "engine", 0);
444 if (newrxengine == "regex/")
445 newrxengine = "regex";
446 if (RegexEngine.GetProvider() == newrxengine)
449 //ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.GetProvider().c_str(), newrxengine.c_str());
450 //ServerInstance->XLines->DelAll("R");
452 RegexEngine.SetProvider(newrxengine);
455 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
460 Version ModuleFilter::GetVersion()
462 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
466 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
468 std::ostringstream stream;
469 std::string x = filter->freeform;
471 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
472 for (std::string::iterator n = x.begin(); n != x.end(); n++)
476 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
480 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
483 irc::tokenstream tokens(data);
484 tokens.GetToken(res.freeform);
485 tokens.GetToken(res.action);
486 tokens.GetToken(res.flags);
487 if (res.flags == "-")
489 res.FillFlags(res.flags);
490 tokens.GetToken(res.gline_time);
491 tokens.GetToken(res.reason);
493 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
494 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
501 void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque)
503 this->SyncFilters(proto, opaque);
506 void ModuleFilter::SendFilter(Module* proto, void* opaque, FilterResult* iter)
508 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(iter));
511 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
513 if ((target == NULL) && (extname == "filter"))
515 FilterResult data = DecodeFilter(extdata);
516 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
520 ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
521 : FilterResult(pat, rea, act, glinetime, flgs)
523 if (!mymodule->RegexEngine)
524 throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!");
525 regex = mymodule->RegexEngine->Create(pat);
528 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
530 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
532 /* Skip ones that dont apply to us */
533 if (!AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
536 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
537 if (index->regex->Matches(text))
539 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
540 ImplFilter fr = *index;
541 if (index != filters.begin())
543 /* Move to head of list for efficiency */
544 filters.erase(index);
545 filters.insert(filters.begin(), fr);
547 return &*filters.begin();
549 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
554 bool ModuleFilter::DeleteFilter(const std::string &freeform)
556 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
558 if (i->freeform == freeform)
568 void ModuleFilter::SyncFilters(Module* proto, void* opaque)
570 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
572 this->SendFilter(proto, opaque, &(*i));
576 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)
578 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
580 if (i->freeform == freeform)
582 return std::make_pair(false, "Filter already exists");
588 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
590 catch (ModuleException &e)
592 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
593 return std::make_pair(false, e.GetReason());
595 return std::make_pair(true, "");
598 void ModuleFilter::ReadFilters(ConfigReader &MyConf)
600 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
602 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
604 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
605 std::string reason = MyConf.ReadValue("keyword", "reason", index);
606 std::string action = MyConf.ReadValue("keyword", "action", index);
607 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
608 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
616 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
617 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
619 catch (ModuleException &e)
621 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
626 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
630 std::string sn = ServerInstance->Config->ServerName;
631 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
633 results.push_back(sn+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
635 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
637 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
640 return MOD_RES_PASSTHRU;
643 MODULE_INIT(ModuleFilter)