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 FilterBase : public Module
102 CommandFilter* filtcommand;
105 std::vector<std::string> exemptfromfilter; // List of channel names excluded from filtering.
107 FilterBase(InspIRCd* Me, const std::string &source);
108 virtual ~FilterBase();
109 virtual int OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
110 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flags) = 0;
111 virtual bool DeleteFilter(const std::string &freeform) = 0;
112 virtual void SyncFilters(Module* proto, void* opaque) = 0;
113 virtual void SendFilter(Module* proto, void* opaque, FilterResult* iter);
114 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;
115 virtual int OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
116 virtual void OnRehash(User* user);
117 virtual Version GetVersion();
118 std::string EncodeFilter(FilterResult* filter);
119 FilterResult DecodeFilter(const std::string &data);
120 virtual void OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable = false);
121 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata);
122 virtual int OnStats(char symbol, User* user, string_list &results) = 0;
123 virtual int OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line);
124 bool AppliesToMe(User* user, FilterResult* filter, int flags);
125 void OnLoadModule(Module* mod, const std::string& name);
126 virtual void ReadFilters(ConfigReader &MyConf) = 0;
129 class CommandFilter : public Command
133 CommandFilter(FilterBase* f, InspIRCd* Me, const std::string &ssource) : Command(Me, "FILTER", "o", 1, 5), Base(f)
135 this->source = ssource;
136 this->syntax = "<filter-definition> <action> <flags> [<gline-duration>] :<reason>";
139 CmdResult Handle(const std::vector<std::string> ¶meters, User *user)
141 if (parameters.size() == 1)
143 /* Deleting a filter */
144 if (Base->DeleteFilter(parameters[0]))
146 user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str());
147 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', std::string("FILTER: ")+user->nick+" removed filter '"+parameters[0]+"'");
152 user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str());
158 /* Adding a filter */
159 if (parameters.size() >= 4)
161 std::string freeform = parameters[0];
162 std::string type = parameters[1];
163 std::string flags = parameters[2];
168 if ((type != "gline") && (type != "none") && (type != "block") && (type != "kill") && (type != "silent"))
170 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), type.c_str());
176 if (parameters.size() >= 5)
178 duration = ServerInstance->Duration(parameters[3]);
179 reason = parameters[4];
183 this->TooFewParams(user, ": When setting a gline type filter, a gline duration must be specified as the third parameter.");
189 reason = parameters[3];
191 std::pair<bool, std::string> result = Base->AddFilter(freeform, type, reason, duration, flags);
194 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
195 type.c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""),
196 flags.c_str(), reason.c_str());
198 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);
204 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
210 this->TooFewParams(user, ".");
217 void TooFewParams(User* user, const std::string &extra_text)
219 user->WriteServ("NOTICE %s :*** Not enough parameters%s", user->nick.c_str(), extra_text.c_str());
223 bool FilterBase::AppliesToMe(User* user, FilterResult* filter, int iflags)
225 if ((filter->flag_no_opers) && IS_OPER(user))
227 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
229 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
231 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
233 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
238 FilterBase::FilterBase(InspIRCd* Me, const std::string &source) : Module(Me)
240 Me->Modules->UseInterface("RegularExpression");
241 filtcommand = new CommandFilter(this, Me, source);
242 ServerInstance->AddCommand(filtcommand);
243 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncOtherMetaData, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_OnLoadModule };
244 ServerInstance->Modules->Attach(eventlist, this, 8);
247 FilterBase::~FilterBase()
249 ServerInstance->Modules->DoneWithInterface("RegularExpression");
252 int FilterBase::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
257 flags = FLAG_PRIVMSG;
258 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
261 int FilterBase::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
263 /* Leave ulines alone */
264 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
270 FilterResult* f = this->FilterMatch(user, text, flags);
273 std::string target = "";
274 if (target_type == TYPE_USER)
276 User* t = (User*)dest;
277 target = std::string(t->nick);
279 else if (target_type == TYPE_CHANNEL)
281 Channel* t = (Channel*)dest;
282 target = std::string(t->name);
283 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
284 if (i != exemptfromfilter.end()) return 0;
286 if (f->action == "block")
288 ServerInstance->SNO->WriteGlobalSno('a', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
289 if (target_type == TYPE_CHANNEL)
290 user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
292 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked and opers notified: "+f->reason);
294 if (f->action == "silent")
296 if (target_type == TYPE_CHANNEL)
297 user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str());
299 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message to "+target+" was blocked: "+f->reason);
301 if (f->action == "kill")
303 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
305 if (f->action == "gline")
307 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
308 if (ServerInstance->XLines->AddLine(gl,NULL))
310 ServerInstance->XLines->ApplyLines();
316 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
322 int FilterBase::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line)
325 if (validated && IS_LOCAL(user))
327 std::string checkline;
328 int replacepoint = 0;
329 bool parting = false;
331 if (command == "QUIT")
333 /* QUIT with no reason: nothing to do */
334 if (parameters.size() < 1)
337 checkline = parameters[0];
342 else if (command == "PART")
344 /* PART with no reason: nothing to do */
345 if (parameters.size() < 2)
348 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
349 if (i != exemptfromfilter.end()) return 0;
350 checkline = parameters[1];
356 /* We're only messing with PART and QUIT */
359 FilterResult* f = NULL;
362 f = this->FilterMatch(user, checkline, flags);
365 /* PART or QUIT reason doesnt match a filter */
368 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
369 Command* c = ServerInstance->Parser->GetHandler(command);
372 std::vector<std::string> params;
373 for (int item = 0; item < (int)parameters.size(); item++)
374 params.push_back(parameters[item]);
375 params[replacepoint] = "Reason filtered";
377 /* We're blocking, OR theyre quitting and its a KILL action
378 * (we cant kill someone whos already quitting, so filter them anyway)
380 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
382 c->Handle(params, user);
387 /* Are they parting, if so, kill is applicable */
388 if ((parting) && (f->action == "kill"))
390 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
391 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
393 if (f->action == "gline")
395 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
396 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
397 if (ServerInstance->XLines->AddLine(gl,NULL))
399 ServerInstance->XLines->ApplyLines();
412 void FilterBase::OnRehash(User* user)
414 ConfigReader MyConf(ServerInstance);
415 std::vector<std::string>().swap(exemptfromfilter);
416 for (int index = 0; index < MyConf.Enumerate("exemptfromfilter"); ++index)
418 std::string chan = MyConf.ReadValue("exemptfromfilter", "channel", index);
420 exemptfromfilter.push_back(chan);
423 std::string newrxengine = MyConf.ReadValue("filteropts", "engine", 0);
424 if (!RegexEngine.empty())
426 if (RegexEngine == newrxengine)
429 ServerInstance->SNO->WriteGlobalSno('a', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.c_str(), newrxengine.c_str());
430 //ServerInstance->XLines->DelAll("R");
434 RegexEngine = newrxengine;
435 modulelist* ml = ServerInstance->Modules->FindInterface("RegularExpression");
438 for (modulelist::iterator i = ml->begin(); i != ml->end(); ++i)
440 if (RegexNameRequest(this, *i).Send() == newrxengine)
442 ServerInstance->SNO->WriteGlobalSno('a', "Filter now using engine '%s'", RegexEngine.c_str());
449 ServerInstance->SNO->WriteGlobalSno('a', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", RegexEngine.c_str());
453 void FilterBase::OnLoadModule(Module* mod, const std::string& name)
455 if (ServerInstance->Modules->ModuleHasInterface(mod, "RegularExpression"))
457 std::string rxname = RegexNameRequest(this, mod).Send();
458 if (rxname == RegexEngine)
461 /* Force a rehash to make sure that any filters that couldnt be applied from the conf
462 * on startup or on load are applied right now.
464 ConfigReader Config(ServerInstance);
465 ServerInstance->SNO->WriteGlobalSno('a', "Found and activated regex module '%s' for m_filter.so.", RegexEngine.c_str());
472 Version FilterBase::GetVersion()
474 return Version("$Id$", VF_VENDOR | VF_COMMON, API_VERSION);
478 std::string FilterBase::EncodeFilter(FilterResult* filter)
480 std::ostringstream stream;
481 std::string x = filter->freeform;
483 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
484 for (std::string::iterator n = x.begin(); n != x.end(); n++)
488 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
492 FilterResult FilterBase::DecodeFilter(const std::string &data)
495 irc::tokenstream tokens(data);
496 tokens.GetToken(res.freeform);
497 tokens.GetToken(res.action);
498 tokens.GetToken(res.flags);
499 if (res.flags == "-")
501 res.FillFlags(res.flags);
502 tokens.GetToken(res.gline_time);
503 tokens.GetToken(res.reason);
505 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
506 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
513 void FilterBase::OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable)
515 this->SyncFilters(proto, opaque);
518 void FilterBase::SendFilter(Module* proto, void* opaque, FilterResult* iter)
520 proto->ProtoSendMetaData(opaque, TYPE_OTHER, NULL, "filter", EncodeFilter(iter));
523 void FilterBase::OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
525 if ((target_type == TYPE_OTHER) && (extname == "filter"))
527 FilterResult data = DecodeFilter(extdata);
528 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
532 class ImplFilter : public FilterResult
537 ImplFilter(Module* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
538 : FilterResult(pat, rea, act, glinetime, flgs)
541 throw ModuleException("Regex module implementing '"+RegexEngine+"' is not loaded!");
543 regex = RegexFactoryRequest(mymodule, rxengine, pat).Create();
551 class ModuleFilter : public FilterBase
553 std::vector<ImplFilter> filters;
559 ModuleFilter(InspIRCd* Me)
560 : FilterBase(Me, "m_filter.so")
565 virtual ~ModuleFilter()
569 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flgs)
571 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
573 /* Skip ones that dont apply to us */
574 if (!FilterBase::AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
577 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
578 if (index->regex->Matches(text))
580 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
582 if (index != filters.begin())
584 /* Move to head of list for efficiency */
585 filters.erase(index);
586 filters.insert(filters.begin(), fr);
590 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
595 virtual bool DeleteFilter(const std::string &freeform)
597 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
599 if (i->freeform == freeform)
609 virtual void SyncFilters(Module* proto, void* opaque)
611 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
613 this->SendFilter(proto, opaque, &(*i));
617 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)
619 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
621 if (i->freeform == freeform)
623 return std::make_pair(false, "Filter already exists");
629 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
631 catch (ModuleException &e)
633 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
634 return std::make_pair(false, e.GetReason());
636 return std::make_pair(true, "");
639 virtual void OnRehash(User* user)
641 ConfigReader MyConf(ServerInstance);
642 FilterBase::OnRehash(user);
646 void ReadFilters(ConfigReader &MyConf)
648 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
650 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
652 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
653 std::string reason = MyConf.ReadValue("keyword", "reason", index);
654 std::string action = MyConf.ReadValue("keyword", "action", index);
655 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
656 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
664 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
665 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
667 catch (ModuleException &e)
669 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
674 virtual int OnStats(char symbol, User* user, string_list &results)
678 std::string sn = ServerInstance->Config->ServerName;
679 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
681 results.push_back(sn+" 223 "+user->nick+" :"+RegexEngine+":"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
683 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
685 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
692 MODULE_INIT(ModuleFilter)