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