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