1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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, const std::string ¶meter);
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> <type> <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 :*** Deleted filter '%s'", user->nick.c_str(), parameters[0].c_str());
151 user->WriteServ("NOTICE %s :*** Filter '%s' not found on list.", user->nick.c_str(), parameters[0].c_str());
157 /* Adding a filter */
158 if (parameters.size() >= 4)
160 std::string freeform = parameters[0];
161 std::string type = parameters[1];
162 std::string flags = parameters[2];
167 if ((type != "gline") && (type != "none") && (type != "block") && (type != "kill") && (type != "silent"))
169 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), freeform.c_str());
175 if (parameters.size() >= 5)
177 duration = ServerInstance->Duration(parameters[3]);
178 reason = parameters[4];
182 this->TooFewParams(user, " When setting a gline type filter, a gline duration must be specified as the third parameter.");
188 reason = parameters[3];
190 std::pair<bool, std::string> result = Base->AddFilter(freeform, type, reason, duration, flags);
193 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
194 type.c_str(), (duration ? " duration: " : ""), (duration ? parameters[3].c_str() : ""),
195 flags.c_str(), reason.c_str());
200 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
206 this->TooFewParams(user, ".");
213 void TooFewParams(User* user, const std::string &extra_text)
215 user->WriteServ("NOTICE %s :*** Not enough parameters%s", user->nick.c_str(), extra_text.c_str());
219 bool FilterBase::AppliesToMe(User* user, FilterResult* filter, int iflags)
221 if ((filter->flag_no_opers) && IS_OPER(user))
223 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
225 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
227 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
229 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
234 FilterBase::FilterBase(InspIRCd* Me, const std::string &source) : Module(Me)
236 Me->Modules->UseInterface("RegularExpression");
237 filtcommand = new CommandFilter(this, Me, source);
238 ServerInstance->AddCommand(filtcommand);
239 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncOtherMetaData, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_OnLoadModule };
240 ServerInstance->Modules->Attach(eventlist, this, 8);
243 FilterBase::~FilterBase()
245 ServerInstance->Modules->DoneWithInterface("RegularExpression");
248 int FilterBase::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
250 flags = FLAG_PRIVMSG;
251 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
254 int FilterBase::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
259 /* Leave ulines alone */
260 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
263 FilterResult* f = this->FilterMatch(user, text, flags);
266 std::string target = "";
267 if (target_type == TYPE_USER)
269 User* t = (User*)dest;
270 target = std::string(t->nick);
272 else if (target_type == TYPE_CHANNEL)
274 Channel* t = (Channel*)dest;
275 target = std::string(t->name);
276 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
277 if (i != exemptfromfilter.end()) return 0;
279 if (f->action == "block")
281 ServerInstance->SNO->WriteToSnoMask('A', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
282 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message has been filtered and opers notified: "+f->reason);
284 if (f->action == "silent")
286 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message has been filtered: "+f->reason);
288 if (f->action == "kill")
290 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
292 if (f->action == "gline")
294 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
295 if (ServerInstance->XLines->AddLine(gl,NULL))
297 ServerInstance->XLines->ApplyLines();
303 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
309 int FilterBase::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line)
312 if (validated && IS_LOCAL(user))
314 std::string checkline;
315 int replacepoint = 0;
316 bool parting = false;
318 if (command == "QUIT")
320 /* QUIT with no reason: nothing to do */
321 if (parameters.size() < 1)
324 checkline = parameters[0];
329 else if (command == "PART")
331 /* PART with no reason: nothing to do */
332 if (parameters.size() < 2)
335 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
336 if (i != exemptfromfilter.end()) return 0;
337 checkline = parameters[1];
343 /* We're only messing with PART and QUIT */
346 FilterResult* f = NULL;
349 f = this->FilterMatch(user, checkline, flags);
352 /* PART or QUIT reason doesnt match a filter */
355 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
356 Command* c = ServerInstance->Parser->GetHandler(command);
359 std::vector<std::string> params;
360 for (int item = 0; item < (int)parameters.size(); item++)
361 params.push_back(parameters[item]);
362 params[replacepoint] = "Reason filtered";
364 /* We're blocking, OR theyre quitting and its a KILL action
365 * (we cant kill someone whos already quitting, so filter them anyway)
367 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
369 c->Handle(params, user);
374 /* Are they parting, if so, kill is applicable */
375 if ((parting) && (f->action == "kill"))
377 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
378 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
380 if (f->action == "gline")
382 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
383 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
384 if (ServerInstance->XLines->AddLine(gl,NULL))
386 ServerInstance->XLines->ApplyLines();
399 void FilterBase::OnRehash(User* user, const std::string ¶meter)
401 ConfigReader* MyConf = new ConfigReader(ServerInstance);
402 std::vector<std::string>().swap(exemptfromfilter);
403 for (int index = 0; index < MyConf->Enumerate("exemptfromfilter"); ++index)
405 std::string chan = MyConf->ReadValue("exemptfromfilter", "channel", index);
407 exemptfromfilter.push_back(chan);
410 std::string newrxengine = MyConf->ReadValue("filteropts", "engine", 0);
411 if (!RegexEngine.empty())
413 if (RegexEngine == newrxengine)
416 ServerInstance->SNO->WriteToSnoMask('A', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.c_str(), newrxengine.c_str());
417 //ServerInstance->XLines->DelAll("R");
421 RegexEngine = newrxengine;
422 modulelist* ml = ServerInstance->Modules->FindInterface("RegularExpression");
425 for (modulelist::iterator i = ml->begin(); i != ml->end(); ++i)
427 if (RegexNameRequest(this, *i).Send() == newrxengine)
429 ServerInstance->SNO->WriteToSnoMask('A', "Filter now using engine '%s'", RegexEngine.c_str());
436 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", RegexEngine.c_str());
442 void FilterBase::OnLoadModule(Module* mod, const std::string& name)
444 if (ServerInstance->Modules->ModuleHasInterface(mod, "RegularExpression"))
446 std::string rxname = RegexNameRequest(this, mod).Send();
447 if (rxname == RegexEngine)
450 /* Force a rehash to make sure that any filters that couldnt be applied from the conf
451 * on startup or on load are applied right now.
453 ConfigReader Config(ServerInstance);
454 ServerInstance->SNO->WriteToSnoMask('A', "Found and activated regex module '%s' for m_filter.so.", RegexEngine.c_str());
461 Version FilterBase::GetVersion()
463 return Version("$Id$", VF_VENDOR | VF_COMMON, API_VERSION);
467 std::string FilterBase::EncodeFilter(FilterResult* filter)
469 std::ostringstream stream;
470 std::string x = filter->freeform;
472 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
473 for (std::string::iterator n = x.begin(); n != x.end(); n++)
477 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
481 FilterResult FilterBase::DecodeFilter(const std::string &data)
484 irc::tokenstream tokens(data);
485 tokens.GetToken(res.freeform);
486 tokens.GetToken(res.action);
487 tokens.GetToken(res.flags);
488 if (res.flags == "-")
490 res.FillFlags(res.flags);
491 tokens.GetToken(res.gline_time);
492 tokens.GetToken(res.reason);
494 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
495 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
502 void FilterBase::OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable)
504 this->SyncFilters(proto, opaque);
507 void FilterBase::SendFilter(Module* proto, void* opaque, FilterResult* iter)
509 proto->ProtoSendMetaData(opaque, TYPE_OTHER, NULL, "filter", EncodeFilter(iter));
512 void FilterBase::OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
514 if ((target_type == TYPE_OTHER) && (extname == "filter"))
516 FilterResult data = DecodeFilter(extdata);
517 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
521 class ImplFilter : public FilterResult
526 ImplFilter(Module* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
527 : FilterResult(pat, rea, act, glinetime, flgs)
530 throw ModuleException("Regex module implementing '"+RegexEngine+"' is not loaded!");
532 regex = RegexFactoryRequest(mymodule, rxengine, pat).Create();
540 class ModuleFilter : public FilterBase
542 std::vector<ImplFilter> filters;
548 ModuleFilter(InspIRCd* Me)
549 : FilterBase(Me, "m_filter.so")
554 virtual ~ModuleFilter()
558 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flgs)
560 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
562 /* Skip ones that dont apply to us */
563 if (!FilterBase::AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
566 //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str());
567 if (index->regex->Matches(text))
569 //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH");
571 if (index != filters.begin())
573 /* Move to head of list for efficiency */
574 filters.erase(index);
575 filters.insert(filters.begin(), fr);
579 //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH");
584 virtual bool DeleteFilter(const std::string &freeform)
586 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
588 if (i->freeform == freeform)
598 virtual void SyncFilters(Module* proto, void* opaque)
600 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
602 this->SendFilter(proto, opaque, &(*i));
606 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)
608 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
610 if (i->freeform == freeform)
612 return std::make_pair(false, "Filter already exists");
618 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
620 catch (ModuleException &e)
622 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
623 return std::make_pair(false, e.GetReason());
625 return std::make_pair(true, "");
628 virtual void OnRehash(User* user, const std::string ¶meter)
630 ConfigReader MyConf(ServerInstance);
631 FilterBase::OnRehash(user, parameter);
635 void ReadFilters(ConfigReader &MyConf)
637 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
639 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
641 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
642 std::string reason = MyConf.ReadValue("keyword", "reason", index);
643 std::string action = MyConf.ReadValue("keyword", "action", index);
644 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
645 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
653 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
654 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
656 catch (ModuleException &e)
658 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
663 virtual int OnStats(char symbol, User* user, string_list &results)
667 std::string sn = ServerInstance->Config->ServerName;
668 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
670 results.push_back(sn+" 223 "+user->nick+" :"+RegexEngine+":"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
672 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
674 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
681 MODULE_INIT(ModuleFilter)