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