]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_monitor.cpp
139c70e7646697016ac9faaadc08eda376fd73f5
[user/henk/code/inspircd.git] / src / modules / m_monitor.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2016 Attila Molnar <attilamolnar@hush.com>
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 namespace IRCv3
23 {
24         namespace Monitor
25         {
26                 class ExtItem;
27                 struct Entry;
28                 class Manager;
29                 class ManagerInternal;
30
31                 typedef std::vector<Entry*> WatchedList;
32                 typedef std::vector<LocalUser*> WatcherList;
33         }
34 }
35
36 struct IRCv3::Monitor::Entry
37 {
38         WatcherList watchers;
39         std::string nick;
40
41         void SetNick(const std::string& Nick)
42         {
43                 nick.clear();
44                 // We may show this string to other users so do not leak the casing
45                 std::transform(Nick.begin(), Nick.end(), std::back_inserter(nick), ::tolower);
46         }
47
48         const std::string& GetNick() const { return nick; }
49 };
50
51 class IRCv3::Monitor::Manager
52 {
53         struct ExtData
54         {
55                 WatchedList list;
56         };
57
58         class ExtItem : public ExtensionItem
59         {
60                 Manager& manager;
61
62          public:
63                 ExtItem(Module* mod, const std::string& extname, Manager& managerref)
64                         : ExtensionItem(extname, ExtensionItem::EXT_USER, mod)
65                         , manager(managerref)
66                 {
67                 }
68
69                 ExtData* get(Extensible* container, bool create = false)
70                 {
71                         ExtData* extdata = static_cast<ExtData*>(get_raw(container));
72                         if ((!extdata) && (create))
73                         {
74                                 extdata = new ExtData;
75                                 set_raw(container, extdata);
76                         }
77                         return extdata;
78                 }
79
80                 void unset(Extensible* container)
81                 {
82                         free(unset_raw(container));
83                 }
84
85                 std::string serialize(SerializeFormat format, const Extensible* container, void* item) const
86                 {
87                         std::string ret;
88                         if (format == FORMAT_NETWORK)
89                                 return ret;
90
91                         const ExtData* extdata = static_cast<ExtData*>(item);
92                         for (WatchedList::const_iterator i = extdata->list.begin(); i != extdata->list.end(); ++i)
93                         {
94                                 const Entry* entry = *i;
95                                 ret.append(entry->GetNick()).push_back(' ');
96                         }
97                         if (!ret.empty())
98                                 ret.erase(ret.size()-1);
99                         return ret;
100                 }
101
102                 void unserialize(SerializeFormat format, Extensible* container, const std::string& value);
103
104                 void free(void* item)
105                 {
106                         delete static_cast<ExtData*>(item);
107                 }
108         };
109
110  public:
111         Manager(Module* mod, const std::string& extname)
112                 : ext(mod, extname, *this)
113         {
114         }
115
116         enum WatchResult
117         {
118                 WR_OK,
119                 WR_TOOMANY,
120                 WR_ALREADYWATCHING,
121                 WR_INVALIDNICK
122         };
123
124         WatchResult Watch(LocalUser* user, const std::string& nick, unsigned int maxwatch)
125         {
126                 if (!ServerInstance->IsNick(nick))
127                         return WR_INVALIDNICK;
128
129                 WatchedList* watched = GetWatchedPriv(user, true);
130                 if (watched->size() >= maxwatch)
131                         return WR_TOOMANY;
132
133                 Entry* entry = AddWatcher(nick, user);
134                 if (stdalgo::isin(*watched, entry))
135                         return WR_ALREADYWATCHING;
136
137                 entry->watchers.push_back(user);
138                 watched->push_back(entry);
139                 return WR_OK;
140         }
141
142         bool Unwatch(LocalUser* user, const std::string& nick)
143         {
144                 WatchedList* list = GetWatchedPriv(user);
145                 if (!list)
146                         return false;
147
148                 bool ret = RemoveWatcher(nick, user, *list);
149                 // If no longer watching any nick unset ext
150                 if (list->empty())
151                         ext.unset(user);
152                 return ret;
153         }
154
155         const WatchedList& GetWatched(LocalUser* user)
156         {
157                 WatchedList* list = GetWatchedPriv(user);
158                 if (list)
159                         return *list;
160                 return emptywatchedlist;
161         }
162
163         void UnwatchAll(LocalUser* user)
164         {
165                 WatchedList* list = GetWatchedPriv(user);
166                 if (!list)
167                         return;
168
169                 while (!list->empty())
170                 {
171                         Entry* entry = list->front();
172                         RemoveWatcher(entry->GetNick(), user, *list);
173                 }
174                 ext.unset(user);
175         }
176
177         WatcherList* GetWatcherList(const std::string& nick)
178         {
179                 Entry* entry = Find(nick);
180                 if (entry)
181                         return &entry->watchers;
182                 return NULL;
183         }
184
185         static User* FindNick(const std::string& nick)
186         {
187                 User* user = ServerInstance->FindNickOnly(nick);
188                 if ((user) && (user->registered == REG_ALL))
189                         return user;
190                 return NULL;
191         }
192
193  private:
194         typedef TR1NS::unordered_map<std::string, Entry, irc::insensitive, irc::StrHashComp> NickHash;
195
196         Entry* Find(const std::string& nick)
197         {
198                 NickHash::iterator it = nicks.find(nick);
199                 if (it != nicks.end())
200                         return &it->second;
201                 return NULL;
202         }
203
204         Entry* AddWatcher(const std::string& nick, LocalUser* user)
205         {
206                 std::pair<NickHash::iterator, bool> ret = nicks.insert(std::make_pair(nick, Entry()));
207                 Entry& entry = ret.first->second;
208                 if (ret.second)
209                         entry.SetNick(nick);
210                 return &entry;
211         }
212
213         bool RemoveWatcher(const std::string& nick, LocalUser* user, WatchedList& watchedlist)
214         {
215                 NickHash::iterator it = nicks.find(nick);
216                 // If nobody is watching this nick the user trying to remove it isn't watching it for sure
217                 if (it == nicks.end())
218                         return false;
219
220                 Entry& entry = it->second;
221                 // Erase from the user's list of watched nicks
222                 if (!stdalgo::vector::swaperase(watchedlist, &entry))
223                         return false; // User is not watching this nick
224
225                 // Erase from the nick's list of watching users
226                 stdalgo::vector::swaperase(entry.watchers, user);
227
228                 // If nobody else is watching the nick remove map entry
229                 if (entry.watchers.empty())
230                         nicks.erase(it);
231
232                 return true;
233         }
234
235         WatchedList* GetWatchedPriv(LocalUser* user, bool create = false)
236         {
237                 ExtData* extdata = ext.get(user, create);
238                 if (!extdata)
239                         return NULL;
240                 return &extdata->list;
241         }
242
243         NickHash nicks;
244         ExtItem ext;
245         WatchedList emptywatchedlist;
246 };
247
248 void IRCv3::Monitor::Manager::ExtItem::unserialize(SerializeFormat format, Extensible* container, const std::string& value)
249 {
250         if (format == FORMAT_NETWORK)
251                 return;
252
253         irc::spacesepstream ss(value);
254         for (std::string nick; ss.GetToken(nick); )
255                 manager.Watch(static_cast<LocalUser*>(container), nick, UINT_MAX);
256 }
257
258 #ifndef INSPIRCD_MONITOR_MANAGER_ONLY
259
260 enum
261 {
262         RPL_MONONLINE = 730,
263         RPL_MONOFFLINE = 731,
264         RPL_MONLIST = 732,
265         RPL_ENDOFMONLIST = 733,
266         ERR_MONLISTFULL = 734
267 };
268
269 class CommandMonitor : public SplitCommand
270 {
271         typedef Numeric::Builder<> ReplyBuilder;
272         // Additional penalty for the /MONITOR L and /MONITOR S commands that request a list from the server
273         static const unsigned int ListPenalty = 3000;
274
275         IRCv3::Monitor::Manager& manager;
276
277         void HandlePlus(LocalUser* user, const std::string& input)
278         {
279                 ReplyBuilder online(user, RPL_MONONLINE);
280                 ReplyBuilder offline(user, RPL_MONOFFLINE);
281                 irc::commasepstream ss(input);
282                 for (std::string nick; ss.GetToken(nick); )
283                 {
284                         IRCv3::Monitor::Manager::WatchResult result = manager.Watch(user, nick, maxmonitor);
285                         if (result == IRCv3::Monitor::Manager::WR_TOOMANY)
286                         {
287                                 // List is full, send error which includes the remaining nicks that were not processed
288                                 user->WriteNumeric(ERR_MONLISTFULL, "%u %s%s%s :Monitor list is full", maxmonitor, nick.c_str(), (ss.StreamEnd() ? "" : ","), ss.GetRemaining().c_str());
289                                 break;
290                         }
291                         else if (result != IRCv3::Monitor::Manager::WR_OK)
292                                 continue; // Already added or invalid nick
293
294                         ReplyBuilder& out = (IRCv3::Monitor::Manager::FindNick(nick) ? online : offline);
295                         out.Add(nick);
296                 }
297
298                 online.Flush();
299                 offline.Flush();
300         }
301
302         void HandleMinus(LocalUser* user, const std::string& input)
303         {
304                 irc::commasepstream ss(input);
305                 for (std::string nick; ss.GetToken(nick); )
306                         manager.Unwatch(user, nick);
307         }
308
309  public:
310         unsigned int maxmonitor;
311
312         CommandMonitor(Module* mod, IRCv3::Monitor::Manager& managerref)
313                 : SplitCommand(mod, "MONITOR", 1)
314                 , manager(managerref)
315         {
316                 Penalty = 2;
317                 allow_empty_last_param = false;
318                 syntax = "[C|L|S|+ <nick1>[,<nick2>]|- <nick1>[,<nick2>]";
319         }
320
321         CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user)
322         {
323                 char subcmd = toupper(parameters[0][0]);
324                 if (subcmd == '+')
325                 {
326                         if (parameters.size() > 1)
327                                 HandlePlus(user, parameters[1]);
328                 }
329                 else if (subcmd == '-')
330                 {
331                         if (parameters.size() > 1)
332                                 HandleMinus(user, parameters[1]);
333                 }
334                 else if (subcmd == 'C')
335                 {
336                         manager.UnwatchAll(user);
337                 }
338                 else if (subcmd == 'L')
339                 {
340                         user->CommandFloodPenalty += ListPenalty;
341                         const IRCv3::Monitor::WatchedList& list = manager.GetWatched(user);
342                         ReplyBuilder out(user, RPL_MONLIST);
343                         for (IRCv3::Monitor::WatchedList::const_iterator i = list.begin(); i != list.end(); ++i)
344                         {
345                                 IRCv3::Monitor::Entry* entry = *i;
346                                 out.Add(entry->GetNick());
347                         }
348                         out.Flush();
349                         user->WriteNumeric(RPL_ENDOFMONLIST, ":End of MONITOR list");
350                 }
351                 else if (subcmd == 'S')
352                 {
353                         user->CommandFloodPenalty += ListPenalty;
354
355                         ReplyBuilder online(user, RPL_MONONLINE);
356                         ReplyBuilder offline(user, RPL_MONOFFLINE);
357
358                         const IRCv3::Monitor::WatchedList& list = manager.GetWatched(user);
359                         for (IRCv3::Monitor::WatchedList::const_iterator i = list.begin(); i != list.end(); ++i)
360                         {
361                                 IRCv3::Monitor::Entry* entry = *i;
362                                 ReplyBuilder& out = (IRCv3::Monitor::Manager::FindNick(entry->GetNick()) ? online : offline);
363                                 out.Add(entry->GetNick());
364                         }
365
366                         online.Flush();
367                         offline.Flush();
368                 }
369                 else
370                         return CMD_FAILURE;
371
372                 return CMD_SUCCESS;
373         }
374 };
375
376 class ModuleMonitor : public Module
377 {
378         IRCv3::Monitor::Manager manager;
379         CommandMonitor cmd;
380
381         void SendAlert(unsigned int numeric, const std::string& nick)
382         {
383                 const IRCv3::Monitor::WatcherList* list = manager.GetWatcherList(nick);
384                 if (!list)
385                         return;
386
387                 for (IRCv3::Monitor::WatcherList::const_iterator i = list->begin(); i != list->end(); ++i)
388                 {
389                         LocalUser* curr = *i;
390                         curr->WriteNumeric(numeric, nick);
391                 }
392         }
393
394  public:
395         ModuleMonitor()
396                 : manager(this, "monitor")
397                 , cmd(this, manager)
398         {
399         }
400
401         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
402         {
403                 ConfigTag* tag = ServerInstance->Config->ConfValue("monitor");
404                 cmd.maxmonitor = tag->getInt("maxentries", 30, 1);
405         }
406
407         void OnPostConnect(User* user) CXX11_OVERRIDE
408         {
409                 SendAlert(RPL_MONONLINE, user->nick);
410         }
411
412         void OnUserPostNick(User* user, const std::string& oldnick) CXX11_OVERRIDE
413         {
414                 // Detect and ignore nickname case change
415                 if (ServerInstance->FindNickOnly(oldnick) == user)
416                         return;
417
418                 SendAlert(RPL_MONOFFLINE, oldnick);
419                 SendAlert(RPL_MONONLINE, user->nick);
420         }
421
422         void OnUserQuit(User* user, const std::string& message, const std::string& oper_message) CXX11_OVERRIDE
423         {
424                 LocalUser* localuser = IS_LOCAL(user);
425                 if (localuser)
426                         manager.UnwatchAll(localuser);
427                 SendAlert(RPL_MONOFFLINE, user->nick);
428         }
429
430         void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
431         {
432                 tokens["MONITOR"] = ConvToStr(cmd.maxmonitor);
433         }
434
435         Version GetVersion() CXX11_OVERRIDE
436         {
437                 return Version("Provides MONITOR support", VF_VENDOR);
438         }
439 };
440
441 MODULE_INIT(ModuleMonitor)
442
443 #endif