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