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);
131 class CommandFilter : public Command
135 CommandFilter(FilterBase* f, InspIRCd* Me, const std::string &ssource) : Command(Me, "FILTER", "o", 1), Base(f)
137 this->source = ssource;
138 this->syntax = "<filter-definition> <type> <flags> [<gline-duration>] :<reason>";
141 CmdResult Handle(const std::vector<std::string> ¶meters, User *user)
143 if (parameters.size() == 1)
145 /* Deleting a filter */
146 if (Base->DeleteFilter(parameters[0]))
148 user->WriteServ("NOTICE %s :*** Deleted filter '%s'", user->nick.c_str(), parameters[0].c_str());
153 user->WriteServ("NOTICE %s :*** Filter '%s' not found on list.", user->nick.c_str(), parameters[0].c_str());
159 /* Adding a filter */
160 if (parameters.size() >= 4)
162 std::string freeform = parameters[0];
163 std::string type = parameters[1];
164 std::string flags = parameters[2];
169 if ((type != "gline") && (type != "none") && (type != "block") && (type != "kill") && (type != "silent"))
171 user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), freeform.c_str());
177 if (parameters.size() >= 5)
179 duration = ServerInstance->Duration(parameters[3]);
180 reason = parameters[4];
184 this->TooFewParams(user, " When setting a gline type filter, a gline duration must be specified as the third parameter.");
190 reason = parameters[3];
192 std::pair<bool, std::string> result = Base->AddFilter(freeform, type, reason, duration, flags);
195 user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(),
196 type.c_str(), (duration ? " duration: " : ""), (duration ? parameters[3].c_str() : ""),
197 flags.c_str(), reason.c_str());
202 user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str());
208 this->TooFewParams(user, ".");
215 void TooFewParams(User* user, const std::string &extra_text)
217 user->WriteServ("NOTICE %s :*** Not enough parameters%s", user->nick.c_str(), extra_text.c_str());
221 bool FilterBase::AppliesToMe(User* user, FilterResult* filter, int iflags)
223 if ((filter->flag_no_opers) && IS_OPER(user))
225 if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
227 if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
229 if ((iflags & FLAG_QUIT) && (!filter->flag_quit_message))
231 if ((iflags & FLAG_PART) && (!filter->flag_part_message))
236 FilterBase::FilterBase(InspIRCd* Me, const std::string &source) : Module(Me)
238 Me->Modules->UseInterface("RegularExpression");
239 filtcommand = new CommandFilter(this, Me, source);
240 ServerInstance->AddCommand(filtcommand);
241 Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncOtherMetaData, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_OnLoadModule };
242 ServerInstance->Modules->Attach(eventlist, this, 8);
245 FilterBase::~FilterBase()
247 ServerInstance->Modules->DoneWithInterface("RegularExpression");
250 int FilterBase::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
252 flags = FLAG_PRIVMSG;
253 return OnUserPreNotice(user,dest,target_type,text,status,exempt_list);
256 int FilterBase::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list)
261 /* Leave ulines alone */
262 if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user)))
265 FilterResult* f = this->FilterMatch(user, text, flags);
268 std::string target = "";
269 if (target_type == TYPE_USER)
271 User* t = (User*)dest;
272 target = std::string(t->nick);
274 else if (target_type == TYPE_CHANNEL)
276 Channel* t = (Channel*)dest;
277 target = std::string(t->name);
278 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), target);
279 if (i != exemptfromfilter.end()) return 0;
281 if (f->action == "block")
283 ServerInstance->SNO->WriteToSnoMask('A', std::string("FILTER: ")+user->nick+" had their message filtered, target was "+target+": "+f->reason);
284 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message has been filtered and opers notified: "+f->reason);
286 if (f->action == "silent")
288 user->WriteServ("NOTICE "+std::string(user->nick)+" :Your message has been filtered: "+f->reason);
290 if (f->action == "kill")
292 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
294 if (f->action == "gline")
296 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
297 if (ServerInstance->XLines->AddLine(gl,NULL))
299 ServerInstance->XLines->ApplyLines();
305 ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + f->action);
311 int FilterBase::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, User *user, bool validated, const std::string &original_line)
314 if (validated && IS_LOCAL(user))
316 std::string checkline;
317 int replacepoint = 0;
318 bool parting = false;
320 if (command == "QUIT")
322 /* QUIT with no reason: nothing to do */
323 if (parameters.size() < 1)
326 checkline = parameters[0];
331 else if (command == "PART")
333 /* PART with no reason: nothing to do */
334 if (parameters.size() < 2)
337 std::vector<std::string>::iterator i = find(exemptfromfilter.begin(), exemptfromfilter.end(), parameters[0]);
338 if (i != exemptfromfilter.end()) return 0;
339 checkline = parameters[1];
345 /* We're only messing with PART and QUIT */
348 FilterResult* f = NULL;
351 f = this->FilterMatch(user, checkline, flags);
354 /* PART or QUIT reason doesnt match a filter */
357 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
358 Command* c = ServerInstance->Parser->GetHandler(command);
361 std::vector<std::string> params;
362 for (int item = 0; item < (int)parameters.size(); item++)
363 params.push_back(parameters[item]);
364 params[replacepoint] = "Reason filtered";
366 /* We're blocking, OR theyre quitting and its a KILL action
367 * (we cant kill someone whos already quitting, so filter them anyway)
369 if ((f->action == "block") || (((!parting) && (f->action == "kill"))) || (f->action == "silent"))
371 c->Handle(params, user);
376 /* Are they parting, if so, kill is applicable */
377 if ((parting) && (f->action == "kill"))
379 user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str());
380 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
382 if (f->action == "gline")
384 /* Note: We gline *@IP so that if their host doesnt resolve the gline still applies. */
385 GLine* gl = new GLine(ServerInstance, ServerInstance->Time(), f->gline_time, ServerInstance->Config->ServerName, f->reason.c_str(), "*", user->GetIPString());
386 if (ServerInstance->XLines->AddLine(gl,NULL))
388 ServerInstance->XLines->ApplyLines();
401 void FilterBase::OnRehash(User* user, const std::string ¶meter)
403 ConfigReader* MyConf = new ConfigReader(ServerInstance);
404 std::vector<std::string>().swap(exemptfromfilter);
405 for (int index = 0; index < MyConf->Enumerate("exemptfromfilter"); ++index)
407 std::string chan = MyConf->ReadValue("exemptfromfilter", "channel", index);
409 exemptfromfilter.push_back(chan);
412 std::string newrxengine = MyConf->ReadValue("filteropts", "engine", 0);
413 if (!RegexEngine.empty())
415 if (RegexEngine == newrxengine)
418 ServerInstance->SNO->WriteToSnoMask('A', "Dumping all filters due to regex engine change (was '%s', now '%s')", RegexEngine.c_str(), newrxengine.c_str());
419 //ServerInstance->XLines->DelAll("R");
423 printf("In Rehash\n");
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)
452 ServerInstance->SNO->WriteToSnoMask('A', "Filter now using engine '%s'", RegexEngine.c_str());
459 Version FilterBase::GetVersion()
461 return Version("$Id$", VF_VENDOR | VF_COMMON, API_VERSION);
465 std::string FilterBase::EncodeFilter(FilterResult* filter)
467 std::ostringstream stream;
468 std::string x = filter->freeform;
470 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
471 for (std::string::iterator n = x.begin(); n != x.end(); n++)
475 stream << x << " " << filter->action << " " << (filter->flags.empty() ? "-" : filter->flags) << " " << filter->gline_time << " :" << filter->reason;
479 FilterResult FilterBase::DecodeFilter(const std::string &data)
482 irc::tokenstream tokens(data);
483 tokens.GetToken(res.freeform);
484 tokens.GetToken(res.action);
485 tokens.GetToken(res.flags);
486 if (res.flags == "-")
488 res.FillFlags(res.flags);
489 tokens.GetToken(res.gline_time);
490 tokens.GetToken(res.reason);
492 /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
493 for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
500 void FilterBase::OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable)
502 this->SyncFilters(proto, opaque);
505 void FilterBase::SendFilter(Module* proto, void* opaque, FilterResult* iter)
507 proto->ProtoSendMetaData(opaque, TYPE_OTHER, NULL, "filter", EncodeFilter(iter));
510 void FilterBase::OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
512 if ((target_type == TYPE_OTHER) && (extname == "filter"))
514 FilterResult data = DecodeFilter(extdata);
515 this->AddFilter(data.freeform, data.action, data.reason, data.gline_time, data.flags);
519 class ImplFilter : public FilterResult
524 ImplFilter(Module* mymodule, const std::string &rea, const std::string &act, long glinetime, const std::string &pat, const std::string &flgs)
525 : FilterResult(pat, rea, act, glinetime, flgs)
528 throw ModuleException("Regex module implementing '"+RegexEngine+"' is not loaded!");
530 regex = RegexFactoryRequest(mymodule, rxengine, pat).Create();
539 class ModuleFilter : public FilterBase
541 std::vector<ImplFilter> filters;
547 ModuleFilter(InspIRCd* Me)
548 : FilterBase(Me, "m_filter.so")
553 virtual ~ModuleFilter()
557 virtual FilterResult* FilterMatch(User* user, const std::string &text, int flgs)
559 for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++)
561 /* Skip ones that dont apply to us */
563 if (!FilterBase::AppliesToMe(user, dynamic_cast<FilterResult*>(&(*index)), flgs))
566 if (index->regex->Matches(text))
569 if (index != filters.begin())
571 /* Move to head of list for efficiency */
572 filters.erase(index);
573 filters.insert(filters.begin(), fr);
581 virtual bool DeleteFilter(const std::string &freeform)
583 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
585 if (i->freeform == freeform)
594 virtual void SyncFilters(Module* proto, void* opaque)
596 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
598 this->SendFilter(proto, opaque, &(*i));
602 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)
604 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
606 if (i->freeform == freeform)
608 return std::make_pair(false, "Filter already exists");
614 filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs));
616 catch (ModuleException &e)
618 ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason());
619 return std::make_pair(false, e.GetReason());
621 return std::make_pair(true, "");
624 virtual void OnRehash(User* user, const std::string ¶meter)
626 ConfigReader MyConf(ServerInstance);
628 FilterBase::OnRehash(user, parameter);
630 for (int index = 0; index < MyConf.Enumerate("keyword"); index++)
632 this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index));
634 std::string pattern = MyConf.ReadValue("keyword", "pattern", index);
635 std::string reason = MyConf.ReadValue("keyword", "reason", index);
636 std::string action = MyConf.ReadValue("keyword", "action", index);
637 std::string flgs = MyConf.ReadValue("keyword", "flags", index);
638 long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index));
646 filters.push_back(ImplFilter(this, reason, action, gline_time, pattern, flgs));
647 ServerInstance->Logs->Log("m_filter",DEFAULT,"Regular expression %s loaded.", pattern.c_str());
649 catch (ModuleException &e)
651 ServerInstance->Logs->Log("m_filter",DEFAULT,"Error in regular expression '%s': %s", pattern.c_str(), e.GetReason());
656 virtual int OnStats(char symbol, User* user, string_list &results)
660 std::string sn = ServerInstance->Config->ServerName;
661 for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++)
663 results.push_back(sn+" 223 "+user->nick+" :REGEXP:"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason);
665 for (std::vector<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i)
667 results.push_back(sn+" 223 "+user->nick+" :EXEMPT "+(*i));
674 MODULE_INIT(ModuleFilter)