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