]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_filter.cpp
49553545ca747c7a662c7e774be1ca0ae540f02d
[user/henk/code/inspircd.git] / src / modules / m_filter.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2004, 2008 Craig Edwards <craigedwards@brainbox.cc>
6  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
7  *   Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22
23 #include "inspircd.h"
24 #include "xline.h"
25 #include "modules/regex.h"
26 #include "modules/server.h"
27 #include "modules/shun.h"
28 #include "modules/stats.h"
29
30 enum FilterFlags
31 {
32         FLAG_PART = 2,
33         FLAG_QUIT = 4,
34         FLAG_PRIVMSG = 8,
35         FLAG_NOTICE = 16
36 };
37
38 enum FilterAction
39 {
40         FA_GLINE,
41         FA_ZLINE,
42         FA_WARN,
43         FA_BLOCK,
44         FA_SILENT,
45         FA_KILL,
46         FA_SHUN,
47         FA_NONE
48 };
49
50 class FilterResult
51 {
52  public:
53         Regex* regex;
54         std::string freeform;
55         std::string reason;
56         FilterAction action;
57         unsigned long duration;
58         bool from_config;
59
60         bool flag_no_opers;
61         bool flag_part_message;
62         bool flag_quit_message;
63         bool flag_privmsg;
64         bool flag_notice;
65         bool flag_strip_color;
66
67         FilterResult(dynamic_reference<RegexFactory>& RegexEngine, const std::string& free, const std::string& rea, FilterAction act, unsigned long gt, const std::string& fla, bool cfg)
68                 : freeform(free)
69                 , reason(rea)
70                 , action(act)
71                 , duration(gt)
72                 , from_config(cfg)
73         {
74                 if (!RegexEngine)
75                         throw ModuleException("Regex module implementing '"+RegexEngine.GetProvider()+"' is not loaded!");
76                 regex = RegexEngine->Create(free);
77                 this->FillFlags(fla);
78         }
79
80         char FillFlags(const std::string &fl)
81         {
82                 flag_no_opers = flag_part_message = flag_quit_message = flag_privmsg =
83                         flag_notice = flag_strip_color = false;
84
85                 for (std::string::const_iterator n = fl.begin(); n != fl.end(); ++n)
86                 {
87                         switch (*n)
88                         {
89                                 case 'o':
90                                         flag_no_opers = true;
91                                 break;
92                                 case 'P':
93                                         flag_part_message = true;
94                                 break;
95                                 case 'q':
96                                         flag_quit_message = true;
97                                 break;
98                                 case 'p':
99                                         flag_privmsg = true;
100                                 break;
101                                 case 'n':
102                                         flag_notice = true;
103                                 break;
104                                 case 'c':
105                                         flag_strip_color = true;
106                                 break;
107                                 case '*':
108                                         flag_no_opers = flag_part_message = flag_quit_message =
109                                                 flag_privmsg = flag_notice = flag_strip_color = true;
110                                 break;
111                                 default:
112                                         return *n;
113                                 break;
114                         }
115                 }
116                 return 0;
117         }
118
119         std::string GetFlags()
120         {
121                 std::string flags;
122                 if (flag_no_opers)
123                         flags.push_back('o');
124                 if (flag_part_message)
125                         flags.push_back('P');
126                 if (flag_quit_message)
127                         flags.push_back('q');
128                 if (flag_privmsg)
129                         flags.push_back('p');
130                 if (flag_notice)
131                         flags.push_back('n');
132
133                 /* Order is important here, 'c' must be the last char in the string as it is unsupported
134                  * on < 2.0.10, and the logic in FillFlags() stops parsing when it ecounters an unknown
135                  * character.
136                  */
137                 if (flag_strip_color)
138                         flags.push_back('c');
139
140                 if (flags.empty())
141                         flags.push_back('-');
142
143                 return flags;
144         }
145
146         FilterResult()
147         {
148         }
149 };
150
151 class CommandFilter : public Command
152 {
153  public:
154         CommandFilter(Module* f)
155                 : Command(f, "FILTER", 1, 5)
156         {
157                 flags_needed = 'o';
158                 this->syntax = "<pattern> [<action> <flags> [<duration>] :<reason>]";
159         }
160         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
161
162         RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
163         {
164                 return ROUTE_BROADCAST;
165         }
166 };
167
168 class ModuleFilter : public Module, public ServerEventListener, public Stats::EventListener
169 {
170         typedef insp::flat_set<std::string, irc::insensitive_swo> ExemptTargetSet;
171
172         bool initing;
173         bool notifyuser;
174         RegexFactory* factory;
175         void FreeFilters();
176
177  public:
178         CommandFilter filtcommand;
179         dynamic_reference<RegexFactory> RegexEngine;
180
181         std::vector<FilterResult> filters;
182         int flags;
183
184         // List of channel names excluded from filtering.
185         ExemptTargetSet exemptedchans;
186
187         // List of target nicknames excluded from filtering.
188         ExemptTargetSet exemptednicks;
189
190         ModuleFilter();
191         void init() CXX11_OVERRIDE;
192         CullResult cull() CXX11_OVERRIDE;
193         ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE;
194         FilterResult* FilterMatch(User* user, const std::string &text, int flags);
195         bool DeleteFilter(const std::string& freeform, std::string& reason);
196         std::pair<bool, std::string> AddFilter(const std::string& freeform, FilterAction type, const std::string& reason, unsigned long duration, const std::string& flags, bool config = false);
197         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE;
198         Version GetVersion() CXX11_OVERRIDE;
199         std::string EncodeFilter(FilterResult* filter);
200         FilterResult DecodeFilter(const std::string &data);
201         void OnSyncNetwork(ProtocolInterface::Server& server) CXX11_OVERRIDE;
202         void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) CXX11_OVERRIDE;
203         ModResult OnStats(Stats::Context& stats) CXX11_OVERRIDE;
204         ModResult OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated) CXX11_OVERRIDE;
205         void OnUnloadModule(Module* mod) CXX11_OVERRIDE;
206         bool AppliesToMe(User* user, FilterResult* filter, int flags);
207         void ReadFilters();
208         static bool StringToFilterAction(const std::string& str, FilterAction& fa);
209         static std::string FilterActionToString(FilterAction fa);
210 };
211
212 CmdResult CommandFilter::Handle(User* user, const Params& parameters)
213 {
214         if (parameters.size() == 1)
215         {
216                 /* Deleting a filter */
217                 Module* me = creator;
218                 std::string reason;
219
220                 if (static_cast<ModuleFilter*>(me)->DeleteFilter(parameters[0], reason))
221                 {
222                         user->WriteNotice("*** Removed filter '" + parameters[0] + "': " + reason);
223                         ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'f' : 'F', "%s removed filter '%s': %s",
224                                 user->nick.c_str(), parameters[0].c_str(), reason.c_str());
225                         return CMD_SUCCESS;
226                 }
227                 else
228                 {
229                         user->WriteNotice("*** Filter '" + parameters[0] + "' not found on the list.");
230                         return CMD_FAILURE;
231                 }
232         }
233         else
234         {
235                 /* Adding a filter */
236                 if (parameters.size() >= 4)
237                 {
238                         const std::string& freeform = parameters[0];
239                         FilterAction type;
240                         const std::string& flags = parameters[2];
241                         unsigned int reasonindex;
242                         unsigned long duration = 0;
243
244                         if (!ModuleFilter::StringToFilterAction(parameters[1], type))
245                         {
246                                 if (ServerInstance->XLines->GetFactory("SHUN"))
247                                         user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'zline', 'none', 'warn', 'block', 'silent', 'kill', and 'shun'.");
248                                 else
249                                         user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'zline', 'none', 'warn', 'block', 'silent', and 'kill'.");
250                                 return CMD_FAILURE;
251                         }
252
253                         if (type == FA_GLINE || type == FA_ZLINE || type == FA_SHUN)
254                         {
255                                 if (parameters.size() >= 5)
256                                 {
257                                         if (!InspIRCd::Duration(parameters[3], duration))
258                                         {
259                                                 user->WriteNotice("*** Invalid duration for filter");
260                                                 return CMD_FAILURE;
261                                         }
262                                         reasonindex = 4;
263                                 }
264                                 else
265                                 {
266                                         user->WriteNotice("*** Not enough parameters: When setting a '" + parameters[1] + "' type filter, a duration must be specified as the third parameter.");
267                                         return CMD_FAILURE;
268                                 }
269                         }
270                         else
271                         {
272                                 reasonindex = 3;
273                         }
274
275                         Module* me = creator;
276                         std::pair<bool, std::string> result = static_cast<ModuleFilter*>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags);
277                         if (result.first)
278                         {
279                                 const std::string message = InspIRCd::Format("'%s', type '%s'%s, flags '%s', reason: %s",
280                                         freeform.c_str(), parameters[1].c_str(),
281                                         (duration ? InspIRCd::Format(", duration '%s'",
282                                                 InspIRCd::DurationString(duration).c_str()).c_str()
283                                         : ""), flags.c_str(), parameters[reasonindex].c_str());
284
285                                 user->WriteNotice("*** Added filter " + message);
286                                 ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'f' : 'F',
287                                         "%s added filter %s", user->nick.c_str(), message.c_str());
288
289                                 return CMD_SUCCESS;
290                         }
291                         else
292                         {
293                                 user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second);
294                                 return CMD_FAILURE;
295                         }
296                 }
297                 else
298                 {
299                         user->WriteNotice("*** Not enough parameters.");
300                         return CMD_FAILURE;
301                 }
302
303         }
304 }
305
306 bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags)
307 {
308         if ((filter->flag_no_opers) && user->IsOper())
309                 return false;
310         if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg))
311                 return false;
312         if ((iflags & FLAG_NOTICE) && (!filter->flag_notice))
313                 return false;
314         if ((iflags & FLAG_QUIT)   && (!filter->flag_quit_message))
315                 return false;
316         if ((iflags & FLAG_PART)   && (!filter->flag_part_message))
317                 return false;
318         return true;
319 }
320
321 ModuleFilter::ModuleFilter()
322         : ServerEventListener(this)
323         , Stats::EventListener(this)
324         , initing(true)
325         , filtcommand(this)
326         , RegexEngine(this, "regex")
327 {
328 }
329
330 void ModuleFilter::init()
331 {
332         ServerInstance->SNO->EnableSnomask('f', "FILTER");
333 }
334
335 CullResult ModuleFilter::cull()
336 {
337         FreeFilters();
338         return Module::cull();
339 }
340
341 void ModuleFilter::FreeFilters()
342 {
343         for (std::vector<FilterResult>::const_iterator i = filters.begin(); i != filters.end(); ++i)
344                 delete i->regex;
345
346         filters.clear();
347 }
348
349 ModResult ModuleFilter::OnUserPreMessage(User* user, const MessageTarget& msgtarget, MessageDetails& details)
350 {
351         // Leave remote users and servers alone
352         if (!IS_LOCAL(user))
353                 return MOD_RES_PASSTHRU;
354
355         flags = (details.type == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE;
356
357         FilterResult* f = this->FilterMatch(user, details.text, flags);
358         if (f)
359         {
360                 std::string target;
361                 if (msgtarget.type == MessageTarget::TYPE_USER)
362                 {
363                         User* t = msgtarget.Get<User>();
364                         // Check if the target nick is exempted, if yes, ignore this message
365                         if (exemptednicks.count(t->nick))
366                                 return MOD_RES_PASSTHRU;
367
368                         target = t->nick;
369                 }
370                 else if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
371                 {
372                         Channel* t = msgtarget.Get<Channel>();
373                         if (exemptedchans.count(t->name))
374                                 return MOD_RES_PASSTHRU;
375
376                         target = t->name;
377                 }
378                 if (f->action == FA_WARN)
379                 {
380                         ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("WARNING: %s's message to %s matched %s (%s)",
381                                 user->nick.c_str(), target.c_str(), f->freeform.c_str(), f->reason.c_str()));
382                         return MOD_RES_PASSTHRU;
383                 }
384                 if (f->action == FA_BLOCK)
385                 {
386                         ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s had their message to %s filtered as it matched %s (%s)",
387                                 user->nick.c_str(), target.c_str(), f->freeform.c_str(), f->reason.c_str()));
388                         if (notifyuser)
389                         {
390                                 if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
391                                         user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked and opers notified (%s)", f->reason.c_str()));
392                                 else
393                                         user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason);
394                         }
395                         else
396                                 details.echo_original = true;
397                 }
398                 else if (f->action == FA_SILENT)
399                 {
400                         if (notifyuser)
401                         {
402                                 if (msgtarget.type == MessageTarget::TYPE_CHANNEL)
403                                         user->WriteNumeric(ERR_CANNOTSENDTOCHAN, target, InspIRCd::Format("Message to channel blocked (%s)", f->reason.c_str()));
404                                 else
405                                         user->WriteNotice("Your message to "+target+" was blocked: "+f->reason);
406                         }
407                         else
408                                 details.echo_original = true;
409                 }
410                 else if (f->action == FA_KILL)
411                 {
412                         ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s was killed because their message to %s matched %s (%s)",
413                                 user->nick.c_str(), target.c_str(), f->freeform.c_str(), f->reason.c_str()));
414                         ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
415                 }
416                 else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
417                 {
418                         Shun* sh = new Shun(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
419                         ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was shunned for %s (expires on %s) because their message to %s matched %s (%s)",
420                                 user->nick.c_str(), sh->Displayable().c_str(), InspIRCd::DurationString(f->duration).c_str(),
421                                 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
422                                 target.c_str(), f->freeform.c_str(), f->reason.c_str()));
423                         if (ServerInstance->XLines->AddLine(sh, NULL))
424                         {
425                                 ServerInstance->XLines->ApplyLines();
426                         }
427                         else
428                                 delete sh;
429                 }
430                 else if (f->action == FA_GLINE)
431                 {
432                         GLine* gl = new GLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
433                         ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was G-lined for %s (expires on %s) because their message to %s matched %s (%s)",
434                                 user->nick.c_str(), gl->Displayable().c_str(), InspIRCd::DurationString(f->duration).c_str(),
435                                 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
436                                 target.c_str(), f->freeform.c_str(), f->reason.c_str()));
437                         if (ServerInstance->XLines->AddLine(gl,NULL))
438                         {
439                                 ServerInstance->XLines->ApplyLines();
440                         }
441                         else
442                                 delete gl;
443                 }
444                 else if (f->action == FA_ZLINE)
445                 {
446                         ZLine* zl = new ZLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
447                         ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was Z-lined for %s (expires on %s) because their message to %s matched %s (%s)",
448                                 user->nick.c_str(), zl->Displayable().c_str(), InspIRCd::DurationString(f->duration).c_str(),
449                                 InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
450                                 target.c_str(), f->freeform.c_str(), f->reason.c_str()));
451                         if (ServerInstance->XLines->AddLine(zl,NULL))
452                         {
453                                 ServerInstance->XLines->ApplyLines();
454                         }
455                         else
456                                 delete zl;
457                 }
458
459                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action));
460                 return MOD_RES_DENY;
461         }
462         return MOD_RES_PASSTHRU;
463 }
464
465 ModResult ModuleFilter::OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated)
466 {
467         if (validated)
468         {
469                 flags = 0;
470                 bool parting;
471
472                 if (command == "QUIT")
473                 {
474                         /* QUIT with no reason: nothing to do */
475                         if (parameters.size() < 1)
476                                 return MOD_RES_PASSTHRU;
477
478                         parting = false;
479                         flags = FLAG_QUIT;
480                 }
481                 else if (command == "PART")
482                 {
483                         /* PART with no reason: nothing to do */
484                         if (parameters.size() < 2)
485                                 return MOD_RES_PASSTHRU;
486
487                         if (exemptedchans.count(parameters[0]))
488                                 return MOD_RES_PASSTHRU;
489
490                         parting = true;
491                         flags = FLAG_PART;
492                 }
493                 else
494                         /* We're only messing with PART and QUIT */
495                         return MOD_RES_PASSTHRU;
496
497                 FilterResult* f = this->FilterMatch(user, parameters[parting ? 1 : 0], flags);
498                 if (!f)
499                         /* PART or QUIT reason doesnt match a filter */
500                         return MOD_RES_PASSTHRU;
501
502                 /* We cant block a part or quit, so instead we change the reason to 'Reason filtered' */
503                 parameters[parting ? 1 : 0] = "Reason filtered";
504
505                 /* We're warning or blocking, OR theyre quitting and its a KILL action
506                  * (we cant kill someone whos already quitting, so filter them anyway)
507                  */
508                 if ((f->action == FA_WARN) || (f->action == FA_BLOCK) || (((!parting) && (f->action == FA_KILL))) || (f->action == FA_SILENT))
509                 {
510                         return MOD_RES_PASSTHRU;
511                 }
512                 else
513                 {
514                         /* Are they parting, if so, kill is applicable */
515                         if ((parting) && (f->action == FA_KILL))
516                         {
517                                 user->WriteNotice("*** Your PART message was filtered: " + f->reason);
518                                 ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason);
519                         }
520                         if (f->action == FA_GLINE)
521                         {
522                                 /* Note: We G-line *@IP so that if their host doesn't resolve the G-line still applies. */
523                                 GLine* gl = new GLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), "*", user->GetIPString());
524                                 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was G-lined for %s (expires on %s) because their %s message matched %s (%s)",
525                                         user->nick.c_str(), gl->Displayable().c_str(),
526                                         InspIRCd::DurationString(f->duration).c_str(),
527                                         InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
528                                         command.c_str(), f->freeform.c_str(), f->reason.c_str()));
529
530                                 if (ServerInstance->XLines->AddLine(gl,NULL))
531                                 {
532                                         ServerInstance->XLines->ApplyLines();
533                                 }
534                                 else
535                                         delete gl;
536                         }
537                         if (f->action == FA_ZLINE)
538                         {
539                                 ZLine* zl = new ZLine(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
540                                 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was Z-lined for %s (expires on %s) because their %s message matched %s (%s)",
541                                         user->nick.c_str(), zl->Displayable().c_str(),
542                                         InspIRCd::DurationString(f->duration).c_str(),
543                                         InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
544                                         command.c_str(), f->freeform.c_str(), f->reason.c_str()));
545
546                                 if (ServerInstance->XLines->AddLine(zl,NULL))
547                                 {
548                                         ServerInstance->XLines->ApplyLines();
549                                 }
550                                 else
551                                         delete zl;
552                         }
553                         else if (f->action == FA_SHUN && (ServerInstance->XLines->GetFactory("SHUN")))
554                         {
555                                 /* Note: We shun *!*@IP so that if their host doesnt resolve the shun still applies. */
556                                 Shun* sh = new Shun(ServerInstance->Time(), f->duration, ServerInstance->Config->ServerName.c_str(), f->reason.c_str(), user->GetIPString());
557                                 ServerInstance->SNO->WriteGlobalSno('f', InspIRCd::Format("%s (%s) was shunned for %s (expires on %s) because their %s message matched %s (%s)",
558                                         user->nick.c_str(), sh->Displayable().c_str(),
559                                         InspIRCd::DurationString(f->duration).c_str(),
560                                         InspIRCd::TimeString(ServerInstance->Time() + f->duration).c_str(),
561                                         command.c_str(), f->freeform.c_str(), f->reason.c_str()));
562
563                                 if (ServerInstance->XLines->AddLine(sh, NULL))
564                                 {
565                                         ServerInstance->XLines->ApplyLines();
566                                 }
567                                 else
568                                         delete sh;
569                         }
570                         return MOD_RES_DENY;
571                 }
572         }
573         return MOD_RES_PASSTHRU;
574 }
575
576 void ModuleFilter::ReadConfig(ConfigStatus& status)
577 {
578         ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter");
579         exemptedchans.clear();
580         exemptednicks.clear();
581
582         for (ConfigIter i = tags.first; i != tags.second; ++i)
583         {
584                 ConfigTag* tag = i->second;
585
586                 // If "target" is not found, try the old "channel" key to keep compatibility with 2.0 configs
587                 const std::string target = tag->getString("target", tag->getString("channel"));
588                 if (!target.empty())
589                 {
590                         if (target[0] == '#')
591                                 exemptedchans.insert(target);
592                         else
593                                 exemptednicks.insert(target);
594                 }
595         }
596
597         ConfigTag* tag = ServerInstance->Config->ConfValue("filteropts");
598         std::string newrxengine = tag->getString("engine");
599         notifyuser = tag->getBool("notifyuser", true);
600
601         factory = RegexEngine ? (RegexEngine.operator->()) : NULL;
602
603         if (newrxengine.empty())
604                 RegexEngine.SetProvider("regex");
605         else
606                 RegexEngine.SetProvider("regex/" + newrxengine);
607
608         if (!RegexEngine)
609         {
610                 if (newrxengine.empty())
611                         ServerInstance->SNO->WriteGlobalSno('f', "WARNING: No regex engine loaded - Filter functionality disabled until this is corrected.");
612                 else
613                         ServerInstance->SNO->WriteGlobalSno('f', "WARNING: Regex engine '%s' is not loaded - Filter functionality disabled until this is corrected.", newrxengine.c_str());
614
615                 initing = false;
616                 FreeFilters();
617                 return;
618         }
619
620         if ((!initing) && (RegexEngine.operator->() != factory))
621         {
622                 ServerInstance->SNO->WriteGlobalSno('f', "Dumping all filters due to regex engine change");
623                 FreeFilters();
624         }
625
626         initing = false;
627         ReadFilters();
628 }
629
630 Version ModuleFilter::GetVersion()
631 {
632         return Version("Text (spam) filtering", VF_VENDOR | VF_COMMON, RegexEngine ? RegexEngine->name : "");
633 }
634
635 std::string ModuleFilter::EncodeFilter(FilterResult* filter)
636 {
637         std::ostringstream stream;
638         std::string x = filter->freeform;
639
640         /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
641         for (std::string::iterator n = x.begin(); n != x.end(); n++)
642                 if (*n == ' ')
643                         *n = '\7';
644
645         stream << x << " " << FilterActionToString(filter->action) << " " << filter->GetFlags() << " " << filter->duration << " :" << filter->reason;
646         return stream.str();
647 }
648
649 FilterResult ModuleFilter::DecodeFilter(const std::string &data)
650 {
651         std::string filteraction;
652         FilterResult res;
653         irc::tokenstream tokens(data);
654         tokens.GetMiddle(res.freeform);
655         tokens.GetMiddle(filteraction);
656         if (!StringToFilterAction(filteraction, res.action))
657                 throw ModuleException("Invalid action: " + filteraction);
658
659         std::string filterflags;
660         tokens.GetMiddle(filterflags);
661         char c = res.FillFlags(filterflags);
662         if (c != 0)
663                 throw ModuleException("Invalid flag: '" + std::string(1, c) + "'");
664
665         std::string duration;
666         tokens.GetMiddle(duration);
667         res.duration = ConvToNum<unsigned long>(duration);
668
669         tokens.GetTrailing(res.reason);
670
671         /* Hax to allow spaces in the freeform without changing the design of the irc protocol */
672         for (std::string::iterator n = res.freeform.begin(); n != res.freeform.end(); n++)
673                 if (*n == '\7')
674                         *n = ' ';
675
676         return res;
677 }
678
679 void ModuleFilter::OnSyncNetwork(ProtocolInterface::Server& server)
680 {
681         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
682         {
683                 FilterResult& filter = *i;
684                 if (filter.from_config)
685                         continue;
686
687                 server.SendMetaData("filter", EncodeFilter(&filter));
688         }
689 }
690
691 void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata)
692 {
693         if ((target == NULL) && (extname == "filter"))
694         {
695                 try
696                 {
697                         FilterResult data = DecodeFilter(extdata);
698                         this->AddFilter(data.freeform, data.action, data.reason, data.duration, data.GetFlags());
699                 }
700                 catch (ModuleException& e)
701                 {
702                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Error when unserializing filter: " + e.GetReason());
703                 }
704         }
705 }
706
707 FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs)
708 {
709         static std::string stripped_text;
710         stripped_text.clear();
711
712         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i)
713         {
714                 FilterResult* filter = &*i;
715
716                 /* Skip ones that dont apply to us */
717                 if (!AppliesToMe(user, filter, flgs))
718                         continue;
719
720                 if ((filter->flag_strip_color) && (stripped_text.empty()))
721                 {
722                         stripped_text = text;
723                         InspIRCd::StripColor(stripped_text);
724                 }
725
726                 if (filter->regex->Matches(filter->flag_strip_color ? stripped_text : text))
727                         return filter;
728         }
729         return NULL;
730 }
731
732 bool ModuleFilter::DeleteFilter(const std::string& freeform, std::string& reason)
733 {
734         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
735         {
736                 if (i->freeform == freeform)
737                 {
738                         reason.assign(i->reason);
739                         delete i->regex;
740                         filters.erase(i);
741                         return true;
742                 }
743         }
744         return false;
745 }
746
747 std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string& freeform, FilterAction type, const std::string& reason, unsigned long duration, const std::string& flgs, bool config)
748 {
749         for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
750         {
751                 if (i->freeform == freeform)
752                 {
753                         return std::make_pair(false, "Filter already exists");
754                 }
755         }
756
757         try
758         {
759                 filters.push_back(FilterResult(RegexEngine, freeform, reason, type, duration, flgs, config));
760         }
761         catch (ModuleException &e)
762         {
763                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason().c_str());
764                 return std::make_pair(false, e.GetReason());
765         }
766         return std::make_pair(true, "");
767 }
768
769 bool ModuleFilter::StringToFilterAction(const std::string& str, FilterAction& fa)
770 {
771         if (stdalgo::string::equalsci(str, "gline"))
772                 fa = FA_GLINE;
773         else if (stdalgo::string::equalsci(str, "zline"))
774                 fa = FA_ZLINE;
775         else if (stdalgo::string::equalsci(str, "warn"))
776                 fa = FA_WARN;
777         else if (stdalgo::string::equalsci(str, "block"))
778                 fa = FA_BLOCK;
779         else if (stdalgo::string::equalsci(str, "silent"))
780                 fa = FA_SILENT;
781         else if (stdalgo::string::equalsci(str, "kill"))
782                 fa = FA_KILL;
783         else if (stdalgo::string::equalsci(str, "shun") && (ServerInstance->XLines->GetFactory("SHUN")))
784                 fa = FA_SHUN;
785         else if (stdalgo::string::equalsci(str, "none"))
786                 fa = FA_NONE;
787         else
788                 return false;
789
790         return true;
791 }
792
793 std::string ModuleFilter::FilterActionToString(FilterAction fa)
794 {
795         switch (fa)
796         {
797                 case FA_GLINE:  return "gline";
798                 case FA_ZLINE:  return "zline";
799                 case FA_WARN:   return "warn";
800                 case FA_BLOCK:  return "block";
801                 case FA_SILENT: return "silent";
802                 case FA_KILL:   return "kill";
803                 case FA_SHUN:   return "shun";
804                 default:                return "none";
805         }
806 }
807
808 void ModuleFilter::ReadFilters()
809 {
810         insp::flat_set<std::string> removedfilters;
811
812         for (std::vector<FilterResult>::iterator filter = filters.begin(); filter != filters.end(); )
813         {
814                 if (filter->from_config)
815                 {
816                         removedfilters.insert(filter->freeform);
817                         delete filter->regex;
818                         filter = filters.erase(filter);
819                         continue;
820                 }
821
822                 // The filter is not from the config.
823                 filter++;
824         }
825
826         ConfigTagList tags = ServerInstance->Config->ConfTags("keyword");
827         for (ConfigIter i = tags.first; i != tags.second; ++i)
828         {
829                 std::string pattern = i->second->getString("pattern");
830                 std::string reason = i->second->getString("reason");
831                 std::string action = i->second->getString("action");
832                 std::string flgs = i->second->getString("flags");
833                 unsigned long duration = i->second->getDuration("duration", 10*60, 1);
834                 if (flgs.empty())
835                         flgs = "*";
836
837                 FilterAction fa;
838                 if (!StringToFilterAction(action, fa))
839                         fa = FA_NONE;
840
841                 std::pair<bool, std::string> result = static_cast<ModuleFilter*>(this)->AddFilter(pattern, fa, reason, duration, flgs, true);
842                 if (result.first)
843                         removedfilters.erase(pattern);
844                 else
845                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Filter '%s' could not be added: %s", pattern.c_str(), result.second.c_str());
846         }
847
848         if (!removedfilters.empty())
849         {
850                 for (insp::flat_set<std::string>::const_iterator it = removedfilters.begin(); it != removedfilters.end(); ++it)
851                         ServerInstance->SNO->WriteGlobalSno('f', "Removing filter '" + *(it) + "' due to config rehash.");
852         }
853 }
854
855 ModResult ModuleFilter::OnStats(Stats::Context& stats)
856 {
857         if (stats.GetSymbol() == 's')
858         {
859                 for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++)
860                 {
861                         stats.AddRow(223, RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->duration)+" :"+i->reason);
862                 }
863                 for (ExemptTargetSet::const_iterator i = exemptedchans.begin(); i != exemptedchans.end(); ++i)
864                 {
865                         stats.AddRow(223, "EXEMPT "+(*i));
866                 }
867                 for (ExemptTargetSet::const_iterator i = exemptednicks.begin(); i != exemptednicks.end(); ++i)
868                 {
869                         stats.AddRow(223, "EXEMPT "+(*i));
870                 }
871         }
872         return MOD_RES_PASSTHRU;
873 }
874
875 void ModuleFilter::OnUnloadModule(Module* mod)
876 {
877         // If the regex engine became unavailable or has changed, remove all filters
878         if (!RegexEngine)
879         {
880                 FreeFilters();
881         }
882         else if (RegexEngine.operator->() != factory)
883         {
884                 factory = RegexEngine.operator->();
885                 FreeFilters();
886         }
887 }
888
889 MODULE_INIT(ModuleFilter)