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