1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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, User *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")
258 ServerInstance->AddCommand(&filtcommand);
259 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash };
260 ServerInstance->Modules->Attach(eventlist, this, 7);
264 ModuleFilter::~ModuleFilter()
268 ModResult ModuleFilter::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
271 return MOD_RES_PASSTHRU;
273 flags = FLAG_PRIVMSG;
274 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
277 ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
279 /* Leave ulines alone */
280 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
281 return MOD_RES_PASSTHRU;
286 FilterResult* f = this->FilterMatch(user, text, flags);
289 std::string target = "";
290 if (target_type == TYPE_USER)
292 User* t = (User*)dest;
293 target = std::string(t->nick);
295 else if (target_type == TYPE_CHANNEL)
297 Channel* t = (Channel*)dest;
298 target = std::string(t->name);
299 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
300 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
302 if (f->action == "block")
304 ServerInstance->SNO->WriteGlobalSno('a', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
305 if (target_type == TYPE_CHANNEL)
306 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
308 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
310 if (f->action == "silent")
312 if (target_type == TYPE_CHANNEL)
313 user->WriteNumeric(404, "%s %s :Message to channel blocked (%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: "+f->reason);
317 if (f->action == "kill")
319 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
321 if (f->action == "gline")
323 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
324 if (ServerInstance->XLines->AddLine(gl,NULL))
326 ServerInstance->XLines->ApplyLines();
332 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
335 return MOD_RES_PASSTHRU;
338 ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line)
341 if (validated && IS_LOCAL(user))
343 std::string checkline;
344 int replacepoint = 0;
345 bool parting = false;
347 if (command == "QUIT")
349 /* QUIT with no reason: nothing to do */
350 if (parameters.size() < 1)
351 return MOD_RES_PASSTHRU;
353 checkline = parameters[0];
358 else if (command == "PART")
360 /* PART with no reason: nothing to do */
361 if (parameters.size() < 2)
362 return MOD_RES_PASSTHRU;
364 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
365 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
366 checkline = parameters[1];
372 /* We're only messing with PART and QUIT */
373 return MOD_RES_PASSTHRU;
375 FilterResult* f = NULL;
378 f = this->FilterMatch(user, checkline, flags);
381 /* PART or QUIT reason doesnt match a filter */
382 return MOD_RES_PASSTHRU;
384 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
385 Command* c = ServerInstance->Parser->GetHandler(command);
388 std::vector<std::string> params;
389 for (int item = 0; item < (int)parameters.size(); item++)
390 params.push_back(parameters[item]);
391 params[replacepoint] = "Reason filtered";
393 /* We're blocking, OR theyre quitting and its a KILL action
394 * (we cant kill someone whos already quitting, so filter them anyway)
396 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
398 c->Handle(params, user);
403 /* Are they parting, if so, kill is applicable */
404 if ((parting) && (f->action == "kill"))
406 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
407 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
409 if (f->action == "gline")
411 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
412 GLine* gl = new GLine(ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
413 if (ServerInstance->XLines->AddLine(gl,NULL))
415 ServerInstance->XLines->ApplyLines();
423 return MOD_RES_PASSTHRU;
425 return MOD_RES_PASSTHRU;
428 void ModuleFilter::OnRehash(User* user)
431 std::vector<std::string>().swap(exemptfromfilter);
432 for (int index = 0; index < MyConf.Enumerate("exemptfromfilter"); ++index)
434 std::string chan = MyConf.ReadValue("exemptfromfilter", "channel", index);
436 exemptfromfilter.push_back(chan);
439 std::string newrxengine = "regex/" + MyConf.ReadValue("filteropts", "engine", 0);
440 if (RegexEngine.GetProvider() == newrxengine)
443 //ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.GetProvider().c_str(), newrxengine.c_str());
444 //ServerInstance->XLines->DelAll("R");
446 RegexEngine.SetProvider(newrxengine);
449 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", RegexEngine.GetProvider().c_str());
454 Version ModuleFilter::GetVersion()
456 return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON);
460 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
462 std::ostringstream stream;
463 std::string x = filter->freeform;
465 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
466 for (std::string::iterator n = x.begin(); n != x.end(); n++)
470 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
474 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
477 irc::tokenstream tokens(data);
478 tokens.GetToken(res.freeform);
479 tokens.GetToken(res.action);
480 tokens.GetToken(res.flags);
481 if (res.flags == "-")
483 res.FillFlags(res.flags);
484 tokens.GetToken(res.gline_time);
485 tokens.GetToken(res.reason);
487 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
488 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
495 void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque)
497 this->SyncFilters(proto, opaque);
500 void ModuleFilter::SendFilter(Module* proto, void* opaque, FilterResult* iter)
502 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(iter));
505 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
507 if ((target == NULL) && (extname == "filter"))
509 FilterResult data = DecodeFilter(extdata);
510 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
514 ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
515 : FilterResult(pat, rea, act, glinetime, flgs)
517 if (!mymodule->RegexEngine)
518 throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!");
519 regex = mymodule->RegexEngine->Create(pat);
522 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
524 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
526 /* Skip ones that dont apply to us */
527 if (!AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
530 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
531 if (index->regex->Matches(text))
533 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
534 ImplFilter fr = *index;
535 if (index != filters.begin())
537 /* Move to head of list for efficiency */
538 filters.erase(index);
539 filters.insert(filters.begin(), fr);
541 return &*filters.begin();
543 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
548 bool ModuleFilter::DeleteFilter(const std::string &freeform)
550 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
552 if (i->freeform == freeform)
562 void ModuleFilter::SyncFilters(Module* proto, void* opaque)
564 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
566 this->SendFilter(proto, opaque, &(*i));
570 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)
572 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
574 if (i->freeform == freeform)
576 return std::make_pair(false, "Filter already exists");
582 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
584 catch (ModuleException &e)
586 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
587 return std::make_pair(false, e.GetReason());
589 return std::make_pair(true, "");
592 void ModuleFilter::ReadFilters(ConfigReader &MyConf)
594 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
596 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
598 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
599 std::string reason = MyConf.ReadValue("keyword", "reason", index);
600 std::string action = MyConf.ReadValue("keyword", "action", index);
601 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
602 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
610 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
611 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
613 catch (ModuleException &e)
615 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
620 ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results)
624 std::string sn = ServerInstance->Config->ServerName;
625 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
627 results.push_back(sn+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
629 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
631 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
634 return MOD_RES_PASSTHRU;
637 MODULE_INIT(ModuleFilter)