1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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 * ---------------------------------------------------
21 /* $ModDesc: Text (spam) filtering */
23 static std::string RegexEngine = "";
24 static Module* rxengine = NULL;
34 class FilterResult : public classbase
44 bool flag_part_message;
45 bool flag_quit_message;
49 FilterResult(const std::string free, const std::string &rea, const std::string &act, long gt, const std::string &fla) :
50 freeform(free), reason(rea), action(act), gline_time(gt), flags(fla)
55 int FillFlags(const std::string &fl)
58 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg = flag_notice = false;
61 for (std::string::const_iterator n = flags.begin(); n != flags.end(); ++n, ++x)
69 flag_part_message = true;
72 flag_quit_message = true;
81 flag_no_opers = flag_part_message = flag_quit_message =
82 flag_privmsg = flag_notice = true;
96 virtual ~FilterResult()
103 class FilterBase : public Module
105 CommandFilter* filtcommand;
108 std::vector<std::string> exemptfromfilter; // List of channel names excluded from filtering.
110 FilterBase(InspIRCd* Me, const std::string &source);
111 virtual ~FilterBase();
112 virtual int OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
113 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flags) = 0;
114 virtual bool DeleteFilter(const std::string &freeform) = 0;
115 virtual void SyncFilters(Module* proto, void* opaque) = 0;
116 virtual void SendFilter(Module* proto, void* opaque, FilterResult* iter);
117 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;
118 virtual int OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list);
119 virtual void OnRehash(User* user, const std::string ¶meter);
120 virtual Version GetVersion();
121 std::string EncodeFilter(FilterResult* filter);
122 FilterResult DecodeFilter(const std::string &data);
123 virtual void OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable = false);
124 virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata);
125 virtual int OnStats(char symbol, User* user, string_list &results) = 0;
126 virtual int OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line);
127 bool AppliesToMe(User* user, FilterResult* filter, int flags);
128 void OnLoadModule(Module* mod, const std::string& name);
129 virtual void ReadFilters(ConfigReader &MyConf) = 0;
132 class CommandFilter : public Command
136 CommandFilter(FilterBase* f, InspIRCd* Me, const std::string &ssource) : Command(Me, "FILTER", "o", 1), Base(f)
138 this->source = ssource;
139 this->syntax = "<filter-definition> <type> <flags> [<gline-duration>] :<reason>";
142 CmdResult Handle(const std::vector<std::string> ¶meters, User *user)
144 if (parameters.size() == 1)
146 /* Deleting a filter */
147 if (Base->DeleteFilter(parameters[0]))
149 user->WriteServ("NOTICE %s :*** Deleted filter '%s'", user->nick.c_str(), parameters[0].c_str());
154 user->WriteServ("NOTICE %s :*** Filter '%s' not found on list.", user->nick.c_str(), parameters[0].c_str());
160 /* Adding a filter */
161 if (parameters.size() >= 4)
163 std::string freeform = parameters[0];
164 std::string type = parameters[1];
165 std::string flags = parameters[2];
170 if ((type != "gline") && (type != "none") && (type != "block") && (type != "kill") && (type != "silent"))
172 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), freeform.c_str());
178 if (parameters.size() >= 5)
180 duration = ServerInstance->Duration(parameters[3]);
181 reason = parameters[4];
185 this->TooFewParams(user, " When setting a gline type filter, a gline duration must be specified as the third parameter.");
191 reason = parameters[3];
193 std::pair<bool, std::string> result = Base->AddFilter(freeform, type, reason, duration, flags);
196 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
197 type.c_str(), (duration ? " duration: " : ""), (duration ? parameters[3].c_str() : ""),
198 flags.c_str(), reason.c_str());
203 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
209 this->TooFewParams(user, ".");
216 void TooFewParams(User* user, const std::string &extra_text)
218 user->WriteServ("NOTICE %s :*** Not enough parameters%s", user->nick.c_str(), extra_text.c_str());
222 bool FilterBase::AppliesToMe(User* user, FilterResult* filter, int iflags)
224 if ((filter->flag_no_opers) && IS_OPER(user))
226 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
228 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
230 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
232 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
237 FilterBase::FilterBase(InspIRCd* Me, const std::string &source) : Module(Me)
239 Me->Modules->UseInterface("RegularExpression");
240 filtcommand = new CommandFilter(this, Me, source);
241 ServerInstance->AddCommand(filtcommand);
242 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncOtherMetaData, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_OnLoadModule };
243 ServerInstance->Modules->Attach(eventlist, this, 8);
246 FilterBase::~FilterBase()
248 ServerInstance->Modules->DoneWithInterface("RegularExpression");
251 int FilterBase::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
253 flags = FLAG_PRIVMSG;
254 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
257 int FilterBase::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
262 /* Leave ulines alone */
263 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
266 FilterResult* f = this->FilterMatch(user, text, flags);
269 std::string target = "";
270 if (target_type == TYPE_USER)
272 User* t = (User*)dest;
273 target = std::string(t->nick);
275 else if (target_type == TYPE_CHANNEL)
277 Channel* t = (Channel*)dest;
278 target = std::string(t->name);
279 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
280 if (i != exemptfromfilter.end()) return 0;
282 if (f->action == "block")
284 ServerInstance->SNO->WriteToSnoMask('A', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
285 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message has been filtered and opers notified: "+f->reason);
287 if (f->action == "silent")
289 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message has been filtered: "+f->reason);
291 if (f->action == "kill")
293 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
295 if (f->action == "gline")
297 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
298 if (ServerInstance->XLines->AddLine(gl,NULL))
300 ServerInstance->XLines->ApplyLines();
306 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
312 int FilterBase::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line)
315 if (validated && IS_LOCAL(user))
317 std::string checkline;
318 int replacepoint = 0;
319 bool parting = false;
321 if (command == "QUIT")
323 /* QUIT with no reason: nothing to do */
324 if (parameters.size() < 1)
327 checkline = parameters[0];
332 else if (command == "PART")
334 /* PART with no reason: nothing to do */
335 if (parameters.size() < 2)
338 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
339 if (i != exemptfromfilter.end()) return 0;
340 checkline = parameters[1];
346 /* We're only messing with PART and QUIT */
349 FilterResult* f = NULL;
352 f = this->FilterMatch(user, checkline, flags);
355 /* PART or QUIT reason doesnt match a filter */
358 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
359 Command* c = ServerInstance->Parser->GetHandler(command);
362 std::vector<std::string> params;
363 for (int item = 0; item < (int)parameters.size(); item++)
364 params.push_back(parameters[item]);
365 params[replacepoint] = "Reason filtered";
367 /* We're blocking, OR theyre quitting and its a KILL action
368 * (we cant kill someone whos already quitting, so filter them anyway)
370 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
372 c->Handle(params, user);
377 /* Are they parting, if so, kill is applicable */
378 if ((parting) && (f->action == "kill"))
380 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
381 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
383 if (f->action == "gline")
385 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
386 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
387 if (ServerInstance->XLines->AddLine(gl,NULL))
389 ServerInstance->XLines->ApplyLines();
402 void FilterBase::OnRehash(User* user, const std::string ¶meter)
404 ConfigReader* MyConf = new ConfigReader(ServerInstance);
405 std::vector<std::string>().swap(exemptfromfilter);
406 for (int index = 0; index < MyConf->Enumerate("exemptfromfilter"); ++index)
408 std::string chan = MyConf->ReadValue("exemptfromfilter", "channel", index);
410 exemptfromfilter.push_back(chan);
413 std::string newrxengine = MyConf->ReadValue("filteropts", "engine", 0);
414 if (!RegexEngine.empty())
416 if (RegexEngine == newrxengine)
419 ServerInstance->SNO->WriteToSnoMask('A', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.c_str(), newrxengine.c_str());
420 //ServerInstance->XLines->DelAll("R");
424 RegexEngine = newrxengine;
425 modulelist* ml = ServerInstance->Modules->FindInterface("RegularExpression");
428 for (modulelist::iterator i = ml->begin(); i != ml->end(); ++i)
430 if (RegexNameRequest(this, *i).Send() == newrxengine)
432 ServerInstance->SNO->WriteToSnoMask('A', "Filter now using engine '%s'", RegexEngine.c_str());
439 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", RegexEngine.c_str());
445 void FilterBase::OnLoadModule(Module* mod, const std::string& name)
447 if (ServerInstance->Modules->ModuleHasInterface(mod, "RegularExpression"))
449 std::string rxname = RegexNameRequest(this, mod).Send();
450 if (rxname == RegexEngine)
453 /* Force a rehash to make sure that any filters that couldnt be applied from the conf
454 * on startup or on load are applied right now.
456 ConfigReader Config(ServerInstance);
457 ServerInstance->SNO->WriteToSnoMask('A', "Found and activated regex module '%s' for m_filter.so.", RegexEngine.c_str());
464 Version FilterBase::GetVersion()
466 return Version("$Id$", VF_VENDOR | VF_COMMON, API_VERSION);
470 std::string FilterBase::EncodeFilter(FilterResult* filter)
472 std::ostringstream stream;
473 std::string x = filter->freeform;
475 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
476 for (std::string::iterator n = x.begin(); n != x.end(); n++)
480 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
484 FilterResult FilterBase::DecodeFilter(const std::string &data)
487 irc::tokenstream tokens(data);
488 tokens.GetToken(res.freeform);
489 tokens.GetToken(res.action);
490 tokens.GetToken(res.flags);
491 if (res.flags == "-")
493 res.FillFlags(res.flags);
494 tokens.GetToken(res.gline_time);
495 tokens.GetToken(res.reason);
497 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
498 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
505 void FilterBase::OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable)
507 this->SyncFilters(proto, opaque);
510 void FilterBase::SendFilter(Module* proto, void* opaque, FilterResult* iter)
512 proto->ProtoSendMetaData(opaque, TYPE_OTHER, NULL, "filter", EncodeFilter(iter));
515 void FilterBase::OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
517 if ((target_type == TYPE_OTHER) && (extname == "filter"))
519 FilterResult data = DecodeFilter(extdata);
520 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
524 class ImplFilter : public FilterResult
529 ImplFilter(Module* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
530 : FilterResult(pat, rea, act, glinetime, flgs)
533 throw ModuleException("Regex module implementing '"+RegexEngine+"' is not loaded!");
535 regex = RegexFactoryRequest(mymodule, rxengine, pat).Create();
543 class ModuleFilter : public FilterBase
545 std::vector<ImplFilter> filters;
551 ModuleFilter(InspIRCd* Me)
552 : FilterBase(Me, "m_filter.so")
557 virtual ~ModuleFilter()
561 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flgs)
563 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
565 /* Skip ones that dont apply to us */
567 if (!FilterBase::AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
570 if (index->regex->Matches(text))
573 if (index != filters.begin())
575 /* Move to head of list for efficiency */
576 filters.erase(index);
577 filters.insert(filters.begin(), fr);
585 virtual bool DeleteFilter(const std::string &freeform)
587 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
589 if (i->freeform == freeform)
599 virtual void SyncFilters(Module* proto, void* opaque)
601 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
603 this->SendFilter(proto, opaque, &(*i));
607 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)
609 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
611 if (i->freeform == freeform)
613 return std::make_pair(false, "Filter already exists");
619 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
621 catch (ModuleException &e)
623 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
624 return std::make_pair(false, e.GetReason());
626 return std::make_pair(true, "");
629 virtual void OnRehash(User* user, const std::string ¶meter)
631 ConfigReader MyConf(ServerInstance);
632 FilterBase::OnRehash(user, parameter);
636 void ReadFilters(ConfigReader &MyConf)
638 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
640 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
642 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
643 std::string reason = MyConf.ReadValue("keyword", "reason", index);
644 std::string action = MyConf.ReadValue("keyword", "action", index);
645 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
646 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
654 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
655 ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str());
657 catch (ModuleException &e)
659 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
664 virtual int OnStats(char symbol, User* user, string_list &results)
668 std::string sn = ServerInstance->Config->ServerName;
669 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
671 results.push_back(sn+" 223 "+user->nick+" :REGEXP:"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
673 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
675 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
682 MODULE_INIT(ModuleFilter)