]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_repeat.cpp
Call Channel::SetModeParam() from the mode parser when needed instead of requiring...
[user/henk/code/inspircd.git] / src / modules / m_repeat.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
5  *
6  * This file is part of InspIRCd.  InspIRCd is free software: you can
7  * redistribute it and/or modify it under the terms of the GNU General Public
8  * License as published by the Free Software Foundation, version 2.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
13  * details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19
20 #include "inspircd.h"
21
22 #ifdef _WIN32
23 // windows.h defines this
24 #undef min
25 #endif
26
27 class RepeatMode : public ModeHandler
28 {
29  private:
30         struct RepeatItem
31         {
32                 time_t ts;
33                 std::string line;
34                 RepeatItem(time_t TS, const std::string& Line) : ts(TS), line(Line) { }
35         };
36
37         typedef std::deque<RepeatItem> RepeatItemList;
38
39         struct MemberInfo
40         {
41                 RepeatItemList ItemList;
42                 unsigned int Counter;
43                 MemberInfo() : Counter(0) {}
44         };
45
46         struct ModuleSettings
47         {
48                 unsigned int MaxLines;
49                 unsigned int MaxSecs;
50                 unsigned int MaxBacklog;
51                 unsigned int MaxDiff;
52                 ModuleSettings() : MaxLines(0), MaxSecs(0), MaxBacklog(0), MaxDiff() { }
53         };
54
55         std::vector<std::vector<unsigned int> > mx;
56         ModuleSettings ms;
57
58         bool CompareLines(const std::string& message, const std::string& historyline, unsigned int trigger)
59         {
60                 if (trigger)
61                         return (Levenshtein(message, historyline) <= trigger);
62                 else
63                         return (message == historyline);
64         }
65
66         unsigned int Levenshtein(const std::string& s1, const std::string& s2)
67         {
68                 unsigned int l1 = s1.size();
69                 unsigned int l2 = s2.size();
70
71                 for (unsigned int i = 0; i <= l1; i++)
72                         mx[i][0] = i;
73                 for (unsigned int i = 0; i <= l2; i++)
74                         mx[0][i] = i;
75                 for (unsigned int i = 1; i <= l1; i++)
76                         for (unsigned int j = 1; j <= l2; j++)
77                                 mx[i][j] = std::min(std::min(mx[i - 1][j] + 1, mx[i][j - 1] + 1), mx[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1));
78                 return (mx[l1][l2]);
79         }
80
81  public:
82         enum RepeatAction
83         {
84                 ACT_KICK,
85                 ACT_BLOCK,
86                 ACT_BAN
87         };
88
89         class ChannelSettings
90         {
91          public:
92                 RepeatAction Action;
93                 unsigned int Backlog;
94                 unsigned int Lines;
95                 unsigned int Diff;
96                 unsigned int Seconds;
97
98                 std::string serialize()
99                 {
100                         std::string ret = ((Action == ACT_BAN) ? "*" : (Action == ACT_BLOCK ? "~" : "")) + ConvToStr(Lines) + ":" + ConvToStr(Seconds);
101                         if (Diff)
102                         {
103                                 ret += ":" + ConvToStr(Diff);
104                                 if (Backlog)
105                                         ret += ":" + ConvToStr(Backlog);
106                         }
107                         return ret;
108                 }
109         };
110
111         SimpleExtItem<MemberInfo> MemberInfoExt;
112         SimpleExtItem<ChannelSettings> ChanSet;
113
114         RepeatMode(Module* Creator)
115                 : ModeHandler(Creator, "repeat", 'E', PARAM_SETONLY, MODETYPE_CHANNEL)
116                 , MemberInfoExt("repeat_memb", Creator)
117                 , ChanSet("repeat", Creator)
118         {
119         }
120
121         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding)
122         {
123                 if (!adding)
124                 {
125                         if (!channel->IsModeSet(this))
126                                 return MODEACTION_DENY;
127
128                         // Unset the per-membership extension when the mode is removed
129                         const UserMembList* users = channel->GetUsers();
130                         for (UserMembCIter i = users->begin(); i != users->end(); ++i)
131                                 MemberInfoExt.unset(i->second);
132
133                         ChanSet.unset(channel);
134                         return MODEACTION_ALLOW;
135                 }
136
137                 if (channel->GetModeParameter(this) == parameter)
138                         return MODEACTION_DENY;
139
140                 ChannelSettings settings;
141                 if (!ParseSettings(source, parameter, settings))
142                 {
143                         source->WriteNotice("*** Invalid syntax. Syntax is {[~*]}[lines]:[time]{:[difference]}{:[backlog]}");
144                         return MODEACTION_DENY;
145                 }
146
147                 if ((settings.Backlog > 0) && (settings.Lines > settings.Backlog))
148                 {
149                         source->WriteNotice("*** You can't set needed lines higher than backlog");
150                         return MODEACTION_DENY;
151                 }
152
153                 LocalUser* localsource = IS_LOCAL(source);
154                 if ((localsource) && (!ValidateSettings(localsource, settings)))
155                         return MODEACTION_DENY;
156
157                 ChanSet.set(channel, settings);
158
159                 return MODEACTION_ALLOW;
160         }
161
162         bool MatchLine(Membership* memb, ChannelSettings* rs, std::string message)
163         {
164                 // If the message is larger than whatever size it's set to,
165                 // let's pretend it isn't. If the first 512 (def. setting) match, it's probably spam.
166                 if (message.size() > mx.size())
167                         message.erase(mx.size());
168
169                 MemberInfo* rp = MemberInfoExt.get(memb);
170                 if (!rp)
171                 {
172                         rp = new MemberInfo;
173                         MemberInfoExt.set(memb, rp);
174                 }
175
176                 unsigned int matches = 0;
177                 if (!rs->Backlog)
178                         matches = rp->Counter;
179
180                 RepeatItemList& items = rp->ItemList;
181                 const unsigned int trigger = (message.size() * rs->Diff / 100);
182                 const time_t now = ServerInstance->Time();
183
184                 std::transform(message.begin(), message.end(), message.begin(), ::tolower);
185
186                 for (std::deque<RepeatItem>::iterator it = items.begin(); it != items.end(); ++it)
187                 {
188                         if (it->ts < now)
189                         {
190                                 items.erase(it, items.end());
191                                 matches = 0;
192                                 break;
193                         }
194
195                         if (CompareLines(message, it->line, trigger))
196                         {
197                                 if (++matches >= rs->Lines)
198                                 {
199                                         if (rs->Action != ACT_BLOCK)
200                                                 rp->Counter = 0;
201                                         return true;
202                                 }
203                         }
204                         else if ((ms.MaxBacklog == 0) || (rs->Backlog == 0))
205                         {
206                                 matches = 0;
207                                 items.clear();
208                                 break;
209                         }
210                 }
211
212                 unsigned int max_items = (rs->Backlog ? rs->Backlog : 1);
213                 if (items.size() >= max_items)
214                         items.pop_back();
215
216                 items.push_front(RepeatItem(now + rs->Seconds, message));
217                 rp->Counter = matches;
218                 return false;
219         }
220
221         void Resize(size_t size)
222         {
223                 if (size == mx.size())
224                         return;
225                 mx.resize(size);
226
227                 if (mx.size() > size)
228                 {
229                         mx.resize(size);
230                         for (unsigned int i = 0; i < mx.size(); i++)
231                                 mx[i].resize(size);
232                 }
233                 else
234                 {
235                         for (unsigned int i = 0; i < mx.size(); i++)
236                         {
237                                 mx[i].resize(size);
238                                 std::vector<unsigned int>(mx[i]).swap(mx[i]);
239                         }
240                         std::vector<std::vector<unsigned int> >(mx).swap(mx);
241                 }
242         }
243
244         void ReadConfig()
245         {
246                 ConfigTag* conf = ServerInstance->Config->ConfValue("repeat");
247                 ms.MaxLines = conf->getInt("maxlines", 20);
248                 ms.MaxBacklog = conf->getInt("maxbacklog", 20);
249                 ms.MaxSecs = conf->getInt("maxsecs", 0);
250
251                 ms.MaxDiff = conf->getInt("maxdistance", 50);
252                 if (ms.MaxDiff > 100)
253                         ms.MaxDiff = 100;
254
255                 unsigned int newsize = conf->getInt("size", 512);
256                 if (newsize > ServerInstance->Config->Limits.MaxLine)
257                         newsize = ServerInstance->Config->Limits.MaxLine;
258                 Resize(newsize);
259         }
260
261         std::string GetModuleSettings() const
262         {
263                 return ConvToStr(ms.MaxLines) + ":" + ConvToStr(ms.MaxSecs) + ":" + ConvToStr(ms.MaxDiff) + ":" + ConvToStr(ms.MaxBacklog);
264         }
265
266  private:
267         bool ParseSettings(User* source, std::string& parameter, ChannelSettings& settings)
268         {
269                 irc::sepstream stream(parameter, ':');
270                 std::string     item;
271                 if (!stream.GetToken(item))
272                         // Required parameter missing
273                         return false;
274
275                 if ((item[0] == '*') || (item[0] == '~'))
276                 {
277                         settings.Action = ((item[0] == '*') ? ACT_BAN : ACT_BLOCK);
278                         item.erase(item.begin());
279                 }
280                 else
281                         settings.Action = ACT_KICK;
282
283                 if ((settings.Lines = ConvToInt(item)) == 0)
284                         return false;
285
286                 if ((!stream.GetToken(item)) || ((settings.Seconds = InspIRCd::Duration(item)) == 0))
287                         // Required parameter missing
288                         return false;
289
290                 // The diff and backlog parameters are optional
291                 settings.Diff = settings.Backlog = 0;
292                 if (stream.GetToken(item))
293                 {
294                         // There is a diff parameter, see if it's valid (> 0)
295                         if ((settings.Diff = ConvToInt(item)) == 0)
296                                 return false;
297
298                         if (stream.GetToken(item))
299                         {
300                                 // There is a backlog parameter, see if it's valid
301                                 if ((settings.Backlog = ConvToInt(item)) == 0)
302                                         return false;
303
304                                 // If there are still tokens, then it's invalid because we allow only 4
305                                 if (stream.GetToken(item))
306                                         return false;
307                         }
308                 }
309
310                 parameter = settings.serialize();
311                 return true;
312         }
313
314         bool ValidateSettings(LocalUser* source, const ChannelSettings& settings)
315         {
316                 if (settings.Backlog && !ms.MaxBacklog)
317                 {
318                         source->WriteNotice("*** The server administrator has disabled backlog matching");
319                         return false;
320                 }
321
322                 if (settings.Diff)
323                 {
324                         if (settings.Diff > ms.MaxDiff)
325                         {
326                                 if (ms.MaxDiff == 0)
327                                         source->WriteNotice("*** The server administrator has disabled matching on edit distance");
328                                 else
329                                         source->WriteNotice("*** The distance you specified is too great. Maximum allowed is " + ConvToStr(ms.MaxDiff));
330                                 return false;
331                         }
332
333                         if (ms.MaxLines && settings.Lines > ms.MaxLines)
334                         {
335                                 source->WriteNotice("*** The line number you specified is too great. Maximum allowed is " + ConvToStr(ms.MaxLines));
336                                 return false;
337                         }
338
339                         if (ms.MaxSecs && settings.Seconds > ms.MaxSecs)
340                         {
341                                 source->WriteNotice("*** The seconds you specified is too great. Maximum allowed is " + ConvToStr(ms.MaxSecs));
342                                 return false;
343                         }
344                 }
345
346                 return true;
347         }
348 };
349
350 class RepeatModule : public Module
351 {
352         RepeatMode rm;
353
354  public:
355         RepeatModule() : rm(this) {}
356
357         void init() CXX11_OVERRIDE
358         {
359                 ServerInstance->Modules->AddService(rm);
360                 ServerInstance->Modules->AddService(rm.ChanSet);
361                 ServerInstance->Modules->AddService(rm.MemberInfoExt);
362                 Implementation eventlist[] = { I_OnUserPreMessage, I_OnRehash };
363                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
364                 rm.ReadConfig();
365         }
366
367         void OnRehash(User* user) CXX11_OVERRIDE
368         {
369                 rm.ReadConfig();
370         }
371
372         ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE
373         {
374                 if (target_type != TYPE_CHANNEL || !IS_LOCAL(user))
375                         return MOD_RES_PASSTHRU;
376
377                 Membership* memb = ((Channel*)dest)->GetUser(user);
378                 if (!memb || !memb->chan->IsModeSet(&rm))
379                         return MOD_RES_PASSTHRU;
380
381                 if (ServerInstance->OnCheckExemption(user, memb->chan, "repeat") == MOD_RES_ALLOW)
382                         return MOD_RES_PASSTHRU;
383
384                 RepeatMode::ChannelSettings* settings = rm.ChanSet.get(memb->chan);
385                 if (!settings)
386                         return MOD_RES_PASSTHRU;
387
388                 if (rm.MatchLine(memb, settings, text))
389                 {
390                         if (settings->Action == RepeatMode::ACT_BLOCK)
391                         {
392                                 user->WriteNotice("*** This line is too similiar to one of your last lines.");
393                                 return MOD_RES_DENY;
394                         }
395
396                         if (settings->Action == RepeatMode::ACT_BAN)
397                         {
398                                 std::vector<std::string> parameters;
399                                 parameters.push_back(memb->chan->name);
400                                 parameters.push_back("+b");
401                                 parameters.push_back("*!*@" + user->dhost);
402                                 ServerInstance->Modes->Process(parameters, ServerInstance->FakeClient);
403                         }
404
405                         memb->chan->KickUser(ServerInstance->FakeClient, user, "Repeat flood");
406                         return MOD_RES_DENY;
407                 }
408                 return MOD_RES_PASSTHRU;
409         }
410
411         void Prioritize() CXX11_OVERRIDE
412         {
413                 ServerInstance->Modules->SetPriority(this, I_OnUserPreMessage, PRIORITY_LAST);
414         }
415
416         Version GetVersion() CXX11_OVERRIDE
417         {
418                 return Version("Provides the +E channel mode - for blocking of similiar messages", VF_COMMON|VF_VENDOR, rm.GetModuleSettings());
419         }
420 };
421
422 MODULE_INIT(RepeatModule)