]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_repeat.cpp
Skip module tags which don't have a module specified.
[user/henk/code/inspircd.git] / src / modules / m_repeat.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Robby <robby@chatbelgie.be>
5  *   Copyright (C) 2018-2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6  *   Copyright (C) 2018 Matt Schatz <genius3000@g3k.solutions>
7  *   Copyright (C) 2017-2019 Sadie Powell <sadie@witchery.services>
8  *   Copyright (C) 2015 James Lu <GLolol@overdrivenetworks.com>
9  *   Copyright (C) 2013-2015 Attila Molnar <attilamolnar@hush.com>
10  *   Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
11  *
12  * This file is part of InspIRCd.  InspIRCd is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU General Public
14  * License as published by the Free Software Foundation, version 2.
15  *
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25
26 #include "inspircd.h"
27 #include "modules/exemption.h"
28
29 class ChannelSettings
30 {
31  public:
32         enum RepeatAction
33         {
34                 ACT_KICK,
35                 ACT_BLOCK,
36                 ACT_BAN
37         };
38
39         RepeatAction Action;
40         unsigned int Backlog;
41         unsigned int Lines;
42         unsigned int Diff;
43         unsigned long Seconds;
44
45         void serialize(std::string& out) const
46         {
47                 if (Action == ACT_BAN)
48                         out.push_back('*');
49                 else if (Action == ACT_BLOCK)
50                         out.push_back('~');
51
52                 out.append(ConvToStr(Lines)).push_back(':');
53                 out.append(ConvToStr(Seconds));
54                 if (Diff)
55                 {
56                         out.push_back(':');
57                         out.append(ConvToStr(Diff));
58                         if (Backlog)
59                         {
60                                 out.push_back(':');
61                                 out.append(ConvToStr(Backlog));
62                         }
63                 }
64         }
65 };
66
67 class RepeatMode : public ParamMode<RepeatMode, SimpleExtItem<ChannelSettings> >
68 {
69  private:
70         struct RepeatItem
71         {
72                 time_t ts;
73                 std::string line;
74                 RepeatItem(time_t TS, const std::string& Line) : ts(TS), line(Line) { }
75         };
76
77         typedef std::deque<RepeatItem> RepeatItemList;
78
79         struct MemberInfo
80         {
81                 RepeatItemList ItemList;
82                 unsigned int Counter;
83                 MemberInfo() : Counter(0) {}
84         };
85
86         struct ModuleSettings
87         {
88                 unsigned int MaxLines;
89                 unsigned int MaxSecs;
90                 unsigned int MaxBacklog;
91                 unsigned int MaxDiff;
92                 unsigned int MaxMessageSize;
93                 ModuleSettings() : MaxLines(0), MaxSecs(0), MaxBacklog(0), MaxDiff() { }
94         };
95
96         std::vector<unsigned int> mx[2];
97         ModuleSettings ms;
98
99         bool CompareLines(const std::string& message, const std::string& historyline, unsigned int trigger)
100         {
101                 if (message == historyline)
102                         return true;
103                 else if (trigger)
104                         return (Levenshtein(message, historyline) <= trigger);
105
106                 return false;
107         }
108
109         unsigned int Levenshtein(const std::string& s1, const std::string& s2)
110         {
111                 unsigned int l1 = s1.size();
112                 unsigned int l2 = s2.size();
113
114                 for (unsigned int i = 0; i < l2; i++)
115                         mx[0][i] = i;
116                 for (unsigned int i = 0; i < l1; i++)
117                 {
118                         mx[1][0] = i + 1;
119                         for (unsigned int j = 0; j < l2; j++)
120                                 mx[1][j + 1] = std::min(std::min(mx[1][j] + 1, mx[0][j + 1] + 1), mx[0][j] + ((s1[i] == s2[j]) ? 0 : 1));
121
122                         mx[0].swap(mx[1]);
123                 }
124                 return mx[0][l2];
125         }
126
127  public:
128         SimpleExtItem<MemberInfo> MemberInfoExt;
129
130         RepeatMode(Module* Creator)
131                 : ParamMode<RepeatMode, SimpleExtItem<ChannelSettings> >(Creator, "repeat", 'E')
132                 , MemberInfoExt("repeat_memb", ExtensionItem::EXT_MEMBERSHIP, Creator)
133         {
134                 syntax = "[~|*]<lines>:<sec>[:<difference>][:<backlog>]";
135         }
136
137         void OnUnset(User* source, Channel* chan) CXX11_OVERRIDE
138         {
139                 // Unset the per-membership extension when the mode is removed
140                 const Channel::MemberMap& users = chan->GetUsers();
141                 for (Channel::MemberMap::const_iterator i = users.begin(); i != users.end(); ++i)
142                         MemberInfoExt.unset(i->second);
143         }
144
145         ModeAction OnSet(User* source, Channel* channel, std::string& parameter) CXX11_OVERRIDE
146         {
147                 ChannelSettings settings;
148                 if (!ParseSettings(source, parameter, settings))
149                 {
150                         source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter));
151                         return MODEACTION_DENY;
152                 }
153
154                 if ((settings.Backlog > 0) && (settings.Lines > settings.Backlog))
155                 {
156                         source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter,
157                                 "You can't set lines higher than backlog."));
158                         return MODEACTION_DENY;
159                 }
160
161                 LocalUser* localsource = IS_LOCAL(source);
162                 if ((localsource) && (!ValidateSettings(localsource, channel, parameter, settings)))
163                         return MODEACTION_DENY;
164
165                 ext.set(channel, settings);
166
167                 return MODEACTION_ALLOW;
168         }
169
170         bool MatchLine(Membership* memb, ChannelSettings* rs, std::string message)
171         {
172                 // If the message is larger than whatever size it's set to,
173                 // let's pretend it isn't. If the first 512 (def. setting) match, it's probably spam.
174                 if (message.size() > ms.MaxMessageSize)
175                         message.erase(ms.MaxMessageSize);
176
177                 MemberInfo* rp = MemberInfoExt.get(memb);
178                 if (!rp)
179                 {
180                         rp = new MemberInfo;
181                         MemberInfoExt.set(memb, rp);
182                 }
183
184                 unsigned int matches = 0;
185                 if (!rs->Backlog)
186                         matches = rp->Counter;
187
188                 RepeatItemList& items = rp->ItemList;
189                 const unsigned int trigger = (message.size() * rs->Diff / 100);
190                 const time_t now = ServerInstance->Time();
191
192                 std::transform(message.begin(), message.end(), message.begin(), ::tolower);
193
194                 for (std::deque<RepeatItem>::iterator it = items.begin(); it != items.end(); ++it)
195                 {
196                         if (it->ts < now)
197                         {
198                                 items.erase(it, items.end());
199                                 matches = 0;
200                                 break;
201                         }
202
203                         if (CompareLines(message, it->line, trigger))
204                         {
205                                 if (++matches >= rs->Lines)
206                                 {
207                                         if (rs->Action != ChannelSettings::ACT_BLOCK)
208                                                 rp->Counter = 0;
209                                         return true;
210                                 }
211                         }
212                         else if ((ms.MaxBacklog == 0) || (rs->Backlog == 0))
213                         {
214                                 matches = 0;
215                                 items.clear();
216                                 break;
217                         }
218                 }
219
220                 unsigned int max_items = (rs->Backlog ? rs->Backlog : 1);
221                 if (items.size() >= max_items)
222                         items.pop_back();
223
224                 items.push_front(RepeatItem(now + rs->Seconds, message));
225                 rp->Counter = matches;
226                 return false;
227         }
228
229         void Resize(size_t size)
230         {
231                 size_t newsize = size+1;
232                 if (newsize <= mx[0].size())
233                         return;
234                 ms.MaxMessageSize = size;
235                 mx[0].resize(newsize);
236                 mx[1].resize(newsize);
237         }
238
239         void ReadConfig()
240         {
241                 ConfigTag* conf = ServerInstance->Config->ConfValue("repeat");
242                 ms.MaxLines = conf->getUInt("maxlines", 20);
243                 ms.MaxBacklog = conf->getUInt("maxbacklog", 20);
244                 ms.MaxSecs = conf->getDuration("maxtime", conf->getDuration("maxsecs", 0));
245
246                 ms.MaxDiff = conf->getUInt("maxdistance", 50);
247                 if (ms.MaxDiff > 100)
248                         ms.MaxDiff = 100;
249
250                 unsigned int newsize = conf->getUInt("size", 512);
251                 if (newsize > ServerInstance->Config->Limits.MaxLine)
252                         newsize = ServerInstance->Config->Limits.MaxLine;
253                 Resize(newsize);
254         }
255
256         std::string GetModuleSettings() const
257         {
258                 return ConvToStr(ms.MaxLines) + ":" + ConvToStr(ms.MaxSecs) + ":" + ConvToStr(ms.MaxDiff) + ":" + ConvToStr(ms.MaxBacklog);
259         }
260
261         void SerializeParam(Channel* chan, const ChannelSettings* chset, std::string& out)
262         {
263                 chset->serialize(out);
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] == '*') ? ChannelSettings::ACT_BAN : ChannelSettings::ACT_BLOCK);
278                         item.erase(item.begin());
279                 }
280                 else
281                         settings.Action = ChannelSettings::ACT_KICK;
282
283                 if ((settings.Lines = ConvToNum<unsigned int>(item)) == 0)
284                         return false;
285
286                 if ((!stream.GetToken(item)) || !InspIRCd::Duration(item, settings.Seconds) || (settings.Seconds == 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 = ConvToNum<unsigned int>(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 = ConvToNum<unsigned int>(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                 return true;
311         }
312
313         bool ValidateSettings(LocalUser* source, Channel* channel, const std::string& parameter, const ChannelSettings& settings)
314         {
315                 if (ms.MaxLines && settings.Lines > ms.MaxLines)
316                 {
317                         source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter, InspIRCd::Format(
318                                 "The line number you specified is too big. Maximum allowed is %u.", ms.MaxLines)));
319                         return false;
320                 }
321
322                 if (ms.MaxSecs && settings.Seconds > ms.MaxSecs)
323                 {
324                         source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter, InspIRCd::Format(
325                                 "The seconds you specified are too big. Maximum allowed is %u.", ms.MaxSecs)));
326                         return false;
327                 }
328
329                 if (settings.Diff && settings.Diff > ms.MaxDiff)
330                 {
331                         if (ms.MaxDiff == 0)
332                                 source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter,
333                                         "The server administrator has disabled matching on edit distance."));
334                         else
335                                 source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter, InspIRCd::Format(
336                                         "The distance you specified is too big. Maximum allowed is %u.", ms.MaxDiff)));
337                         return false;
338                 }
339
340                 if (settings.Backlog && settings.Backlog > ms.MaxBacklog)
341                 {
342                         if (ms.MaxBacklog == 0)
343                                 source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter,
344                                         "The server administrator has disabled backlog matching."));
345                         else
346                                 source->WriteNumeric(Numerics::InvalidModeParameter(channel, this, parameter, InspIRCd::Format(
347                                         "The backlog you specified is too big. Maximum allowed is %u.", ms.MaxBacklog)));
348                         return false;
349                 }
350
351                 return true;
352         }
353 };
354
355 class RepeatModule : public Module
356 {
357         CheckExemption::EventProvider exemptionprov;
358         RepeatMode rm;
359
360  public:
361         RepeatModule()
362                 : exemptionprov(this)
363                 , rm(this)
364         {
365         }
366
367         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
368         {
369                 rm.ReadConfig();
370         }
371
372         ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE
373         {
374                 if (target.type != MessageTarget::TYPE_CHANNEL || !IS_LOCAL(user))
375                         return MOD_RES_PASSTHRU;
376
377                 Channel* chan = target.Get<Channel>();
378                 ChannelSettings* settings = rm.ext.get(chan);
379                 if (!settings)
380                         return MOD_RES_PASSTHRU;
381
382                 Membership* memb = chan->GetUser(user);
383                 if (!memb)
384                         return MOD_RES_PASSTHRU;
385
386                 ModResult res = CheckExemption::Call(exemptionprov, user, chan, "repeat");
387                 if (res == MOD_RES_ALLOW)
388                         return MOD_RES_PASSTHRU;
389
390                 if (rm.MatchLine(memb, settings, details.text))
391                 {
392                         if (settings->Action == ChannelSettings::ACT_BLOCK)
393                         {
394                                 user->WriteNotice("*** This line is too similar to one of your last lines.");
395                                 return MOD_RES_DENY;
396                         }
397
398                         if (settings->Action == ChannelSettings::ACT_BAN)
399                         {
400                                 Modes::ChangeList changelist;
401                                 changelist.push_add(ServerInstance->Modes->FindMode('b', MODETYPE_CHANNEL), "*!*@" + user->GetDisplayedHost());
402                                 ServerInstance->Modes->Process(ServerInstance->FakeClient, chan, NULL, changelist);
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("Adds channel mode E (repeat) which helps protect against spammers which spam the same message repeatedly.", VF_COMMON|VF_VENDOR, rm.GetModuleSettings());
419         }
420 };
421
422 MODULE_INIT(RepeatModule)