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 */
20 static std::string RegexEngine = "";
21 static Module* rxengine = NULL;
31 class FilterResult : public classbase
41 bool flag_part_message;
42 bool flag_quit_message;
46 FilterResult(const std::string free, const std::string &rea, const std::string &act, long gt, const std::string &fla) :
47 freeform(free), reason(rea), action(act), gline_time(gt), flags(fla)
52 int FillFlags(const std::string &fl)
55 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg = flag_notice = false;
58 for (std::string::const_iterator n = flags.begin(); n != flags.end(); ++n, ++x)
66 flag_part_message = true;
69 flag_quit_message = true;
78 flag_no_opers = flag_part_message = flag_quit_message =
79 flag_privmsg = flag_notice = true;
93 virtual ~FilterResult()
100 class CommandFilter : public Command
104 CommandFilter(FilterBase* f, const std::string &ssource)
105 : Command(reinterpret_cast<Module*>(f), "FILTER", 1, 5), Base(f)
108 this->syntax = "<filter-definition> <action> <flags> [<gline-duration>] :<reason>";
110 CmdResult Handle(const std::vector<std::string>&, User*);
112 void TooFewParams(User* user, const std::string &extra_text)
114 user->WriteServ("NOTICE %s :*** Not enough parameters%s", user->nick.c_str(), extra_text.c_str());
117 RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
119 return ROUTE_BROADCAST;
123 class FilterBase : public Module
125 CommandFilter filtcommand;
128 std::vector<std::string> exemptfromfilter; // List of channel names excluded from filtering.
130 FilterBase(InspIRCd* Me, const std::string &source);
131 virtual ~FilterBase();
132 virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
133 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flags) = 0;
134 virtual bool DeleteFilter(const std::string &freeform) = 0;
135 virtual void SyncFilters(Module* proto, void* opaque) = 0;
136 virtual void SendFilter(Module* proto, void* opaque, FilterResult* iter);
137 virtual std::pair<bool, std::string> AddFilter(const std::string &freeform, const std::string &type, const std::string &reason, long duration, const std::string &flags) = 0;
138 virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
139 virtual void OnRehash(User* user);
140 virtual Version GetVersion();
141 std::string EncodeFilter(FilterResult* filter);
142 FilterResult DecodeFilter(const std::string &data);
143 virtual void OnSyncNetwork(Module* proto, void* opaque);
144 virtual void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata);
145 virtual ModResult OnStats(char symbol, User* user, string_list &results) = 0;
146 virtual ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line);
147 bool AppliesToMe(User* user, FilterResult* filter, int flags);
148 void OnLoadModule(Module* mod, const std::string& name);
149 virtual void ReadFilters(ConfigReader &MyConf) = 0;
152 CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User *user)
154 if (parameters.size() == 1)
156 /* Deleting a filter */
157 if (Base->DeleteFilter(parameters[0]))
159 user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str());
160 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', std::string("FILTER: ")+user->nick+" removed filter '"+parameters[0]+"'");
165 user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str());
171 /* Adding a filter */
172 if (parameters.size() >= 4)
174 std::string freeform = parameters[0];
175 std::string type = parameters[1];
176 std::string flags = parameters[2];
181 if ((type != "gline") && (type != "none") && (type != "block") && (type != "kill") && (type != "silent"))
183 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), type.c_str());
189 if (parameters.size() >= 5)
191 duration = ServerInstance->Duration(parameters[3]);
192 reason = parameters[4];
196 this->TooFewParams(user, ": When setting a gline type filter, a gline duration must be specified as the third parameter.");
202 reason = parameters[3];
204 std::pair<bool, std::string> result = Base->AddFilter(freeform, type, reason, duration, flags);
207 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
208 type.c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""),
209 flags.c_str(), reason.c_str());
211 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);
217 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
223 this->TooFewParams(user, ".");
230 bool FilterBase::AppliesToMe(User* user, FilterResult* filter, int iflags)
232 if ((filter->flag_no_opers) && IS_OPER(user))
234 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
236 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
238 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
240 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
245 FilterBase::FilterBase(InspIRCd* Me, const std::string &source) : Module(Me), filtcommand(this, source)
247 Me->Modules->UseInterface("RegularExpression");
248 ServerInstance->AddCommand(&filtcommand);
249 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_OnLoadModule };
250 ServerInstance->Modules->Attach(eventlist, this, 8);
253 FilterBase::~FilterBase()
255 ServerInstance->Modules->DoneWithInterface("RegularExpression");
258 ModResult FilterBase::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
261 return MOD_RES_PASSTHRU;
263 flags = FLAG_PRIVMSG;
264 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
267 ModResult FilterBase::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
269 /* Leave ulines alone */
270 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
271 return MOD_RES_PASSTHRU;
276 FilterResult* f = this->FilterMatch(user, text, flags);
279 std::string target = "";
280 if (target_type == TYPE_USER)
282 User* t = (User*)dest;
283 target = std::string(t->nick);
285 else if (target_type == TYPE_CHANNEL)
287 Channel* t = (Channel*)dest;
288 target = std::string(t->name);
289 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
290 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
292 if (f->action == "block")
294 ServerInstance->SNO->WriteGlobalSno('a', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
295 if (target_type == TYPE_CHANNEL)
296 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
298 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
300 if (f->action == "silent")
302 if (target_type == TYPE_CHANNEL)
303 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
305 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked: "+f->reason);
307 if (f->action == "kill")
309 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
311 if (f->action == "gline")
313 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
314 if (ServerInstance->XLines->AddLine(gl,NULL))
316 ServerInstance->XLines->ApplyLines();
322 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
325 return MOD_RES_PASSTHRU;
328 ModResult FilterBase::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line)
331 if (validated && IS_LOCAL(user))
333 std::string checkline;
334 int replacepoint = 0;
335 bool parting = false;
337 if (command == "QUIT")
339 /* QUIT with no reason: nothing to do */
340 if (parameters.size() < 1)
341 return MOD_RES_PASSTHRU;
343 checkline = parameters[0];
348 else if (command == "PART")
350 /* PART with no reason: nothing to do */
351 if (parameters.size() < 2)
352 return MOD_RES_PASSTHRU;
354 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
355 if (i != exemptfromfilter.end()) return MOD_RES_PASSTHRU;
356 checkline = parameters[1];
362 /* We're only messing with PART and QUIT */
363 return MOD_RES_PASSTHRU;
365 FilterResult* f = NULL;
368 f = this->FilterMatch(user, checkline, flags);
371 /* PART or QUIT reason doesnt match a filter */
372 return MOD_RES_PASSTHRU;
374 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
375 Command* c = ServerInstance->Parser->GetHandler(command);
378 std::vector<std::string> params;
379 for (int item = 0; item < (int)parameters.size(); item++)
380 params.push_back(parameters[item]);
381 params[replacepoint] = "Reason filtered";
383 /* We're blocking, OR theyre quitting and its a KILL action
384 * (we cant kill someone whos already quitting, so filter them anyway)
386 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
388 c->Handle(params, user);
393 /* Are they parting, if so, kill is applicable */
394 if ((parting) && (f->action == "kill"))
396 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
397 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
399 if (f->action == "gline")
401 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
402 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
403 if (ServerInstance->XLines->AddLine(gl,NULL))
405 ServerInstance->XLines->ApplyLines();
413 return MOD_RES_PASSTHRU;
415 return MOD_RES_PASSTHRU;
418 void FilterBase::OnRehash(User* user)
420 ConfigReader MyConf(ServerInstance);
421 std::vector<std::string>().swap(exemptfromfilter);
422 for (int index = 0; index < MyConf.Enumerate("exemptfromfilter"); ++index)
424 std::string chan = MyConf.ReadValue("exemptfromfilter", "channel", index);
426 exemptfromfilter.push_back(chan);
429 std::string newrxengine = MyConf.ReadValue("filteropts", "engine", 0);
430 if (!RegexEngine.empty())
432 if (RegexEngine == newrxengine)
435 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.c_str(), newrxengine.c_str());
436 //ServerInstance->XLines->DelAll("R");
440 RegexEngine = newrxengine;
441 modulelist* ml = ServerInstance->Modules->FindInterface("RegularExpression");
444 for (modulelist::iterator i = ml->begin(); i != ml->end(); ++i)
446 if (RegexNameRequest(this, *i).Send() == newrxengine)
448 ServerInstance->SNO->WriteGlobalSno('a', "Filter now using engine '%s'", RegexEngine.c_str());
455 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", RegexEngine.c_str());
459 void FilterBase::OnLoadModule(Module* mod, const std::string& name)
461 if (ServerInstance->Modules->ModuleHasInterface(mod, "RegularExpression"))
463 std::string rxname = RegexNameRequest(this, mod).Send();
464 if (rxname == RegexEngine)
467 /* Force a rehash to make sure that any filters that couldnt be applied from the conf
468 * on startup or on load are applied right now.
470 ConfigReader Config(ServerInstance);
471 ServerInstance->SNO->WriteGlobalSno('a', "Found and activated regex module '%s' for m_filter.so.", RegexEngine.c_str());
478 Version FilterBase::GetVersion()
480 return Version("$Id$", VF_VENDOR | VF_COMMON, API_VERSION);
484 std::string FilterBase::EncodeFilter(FilterResult* filter)
486 std::ostringstream stream;
487 std::string x = filter->freeform;
489 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
490 for (std::string::iterator n = x.begin(); n != x.end(); n++)
494 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
498 FilterResult FilterBase::DecodeFilter(const std::string &data)
501 irc::tokenstream tokens(data);
502 tokens.GetToken(res.freeform);
503 tokens.GetToken(res.action);
504 tokens.GetToken(res.flags);
505 if (res.flags == "-")
507 res.FillFlags(res.flags);
508 tokens.GetToken(res.gline_time);
509 tokens.GetToken(res.reason);
511 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
512 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
519 void FilterBase::OnSyncNetwork(Module* proto, void* opaque)
521 this->SyncFilters(proto, opaque);
524 void FilterBase::SendFilter(Module* proto, void* opaque, FilterResult* iter)
526 proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(iter));
529 void FilterBase::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
531 if ((target == NULL) && (extname == "filter"))
533 FilterResult data = DecodeFilter(extdata);
534 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
538 class ImplFilter : public FilterResult
543 ImplFilter(Module* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
544 : FilterResult(pat, rea, act, glinetime, flgs)
547 throw ModuleException("Regex module implementing '"+RegexEngine+"' is not loaded!");
549 regex = RegexFactoryRequest(mymodule, rxengine, pat).Create();
557 class ModuleFilter : public FilterBase
559 std::vector<ImplFilter> filters;
565 ModuleFilter(InspIRCd* Me)
566 : FilterBase(Me, "m_filter.so")
571 virtual ~ModuleFilter()
575 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flgs)
577 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
579 /* Skip ones that dont apply to us */
580 if (!FilterBase::AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
583 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
584 if (index->regex->Matches(text))
586 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
588 if (index != filters.begin())
590 /* Move to head of list for efficiency */
591 filters.erase(index);
592 filters.insert(filters.begin(), fr);
596 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
601 virtual bool DeleteFilter(const std::string &freeform)
603 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
605 if (i->freeform == freeform)
615 virtual void SyncFilters(Module* proto, void* opaque)
617 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
619 this->SendFilter(proto, opaque, &(*i));
623 virtual std::pair<bool, std::string> AddFilter(const std::string &freeform, const std::string &type, const std::string &reason, long duration, const std::string &flgs)
625 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
627 if (i->freeform == freeform)
629 return std::make_pair(false, "Filter already exists");
635 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
637 catch (ModuleException &e)
639 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
640 return std::make_pair(false, e.GetReason());
642 return std::make_pair(true, "");
645 virtual void OnRehash(User* user)
647 ConfigReader MyConf(ServerInstance);
648 FilterBase::OnRehash(user);
652 void 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));
670 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
671 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
673 catch (ModuleException &e)
675 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
680 virtual ModResult OnStats(char symbol, User* user, string_list &results)
684 std::string sn = ServerInstance->Config->ServerName;
685 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
687 results.push_back(sn+" 223 "+user->nick+" :"+RegexEngine+":"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
689 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
691 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
694 return MOD_RES_PASSTHRU;
698 MODULE_INIT(ModuleFilter)