summaryrefslogtreecommitdiff
path: root/src/modules/m_monitor.cpp
blob: 823a6fe5dc9a0560330ec1abe8a12c0308ad6771 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
 * InspIRCd -- Internet Relay Chat Daemon
 *
 *   Copyright (C) 2019 Robby <robby@chatbelgie.be>
 *   Copyright (C) 2018-2019 Sadie Powell <sadie@witchery.services>
 *   Copyright (C) 2016 Attila Molnar <attilamolnar@hush.com>
 *
 * This file is part of InspIRCd.  InspIRCd is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, version 2.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#include "inspircd.h"

namespace IRCv3
{
	namespace Monitor
	{
		class ExtItem;
		struct Entry;
		class Manager;
		class ManagerInternal;

		typedef std::vector<Entry*> WatchedList;
		typedef std::vector<LocalUser*> WatcherList;
	}
}

struct IRCv3::Monitor::Entry
{
	WatcherList watchers;
	std::string nick;

	void SetNick(const std::string& Nick)
	{
		nick.clear();
		// We may show this string to other users so do not leak the casing
		std::transform(Nick.begin(), Nick.end(), std::back_inserter(nick), ::tolower);
	}

	const std::string& GetNick() const { return nick; }
};

class IRCv3::Monitor::Manager
{
	struct ExtData
	{
		WatchedList list;
	};

	class ExtItem : public ExtensionItem
	{
		Manager& manager;

	 public:
		ExtItem(Module* mod, const std::string& extname, Manager& managerref)
			: ExtensionItem(extname, ExtensionItem::EXT_USER, mod)
			, manager(managerref)
		{
		}

		ExtData* get(Extensible* container, bool create = false)
		{
			ExtData* extdata = static_cast<ExtData*>(get_raw(container));
			if ((!extdata) && (create))
			{
				extdata = new ExtData;
				set_raw(container, extdata);
			}
			return extdata;
		}

		void unset(Extensible* container)
		{
			free(container, unset_raw(container));
		}

		std::string ToInternal(const Extensible* container, void* item) const CXX11_OVERRIDE
		{
			std::string ret;
			const ExtData* extdata = static_cast<ExtData*>(item);
			for (WatchedList::const_iterator i = extdata->list.begin(); i != extdata->list.end(); ++i)
			{
				const Entry* entry = *i;
				ret.append(entry->GetNick()).push_back(' ');
			}
			if (!ret.empty())
				ret.erase(ret.size()-1);
			return ret;
		}

		void FromInternal(Extensible* container, const std::string& value) CXX11_OVERRIDE;

		void free(Extensible* container, void* item) CXX11_OVERRIDE
		{
			delete static_cast<ExtData*>(item);
		}
	};

 public:
	Manager(Module* mod, const std::string& extname)
		: ext(mod, extname, *this)
	{
	}

	enum WatchResult
	{
		WR_OK,
		WR_TOOMANY,
		WR_ALREADYWATCHING,
		WR_INVALIDNICK
	};

	WatchResult Watch(LocalUser* user, const std::string& nick, unsigned int maxwatch)
	{
		if (!ServerInstance->IsNick(nick))
			return WR_INVALIDNICK;

		WatchedList* watched = GetWatchedPriv(user, true);
		if (watched->size() >= maxwatch)
			return WR_TOOMANY;

		Entry* entry = AddWatcher(nick, user);
		if (stdalgo::isin(*watched, entry))
			return WR_ALREADYWATCHING;

		entry->watchers.push_back(user);
		watched->push_back(entry);
		return WR_OK;
	}

	bool Unwatch(LocalUser* user, const std::string& nick)
	{
		WatchedList* list = GetWatchedPriv(user);
		if (!list)
			return false;

		bool ret = RemoveWatcher(nick, user, *list);
		// If no longer watching any nick unset ext
		if (list->empty())
			ext.unset(user);
		return ret;
	}

	const WatchedList& GetWatched(LocalUser* user)
	{
		WatchedList* list = GetWatchedPriv(user);
		if (list)
			return *list;
		return emptywatchedlist;
	}

	void UnwatchAll(LocalUser* user)
	{
		WatchedList* list = GetWatchedPriv(user);
		if (!list)
			return;

		while (!list->empty())
		{
			Entry* entry = list->front();
			RemoveWatcher(entry->GetNick(), user, *list);
		}
		ext.unset(user);
	}

	WatcherList* GetWatcherList(const std::string& nick)
	{
		Entry* entry = Find(nick);
		if (entry)
			return &entry->watchers;
		return NULL;
	}

	static User* FindNick(const std::string& nick)
	{
		User* user = ServerInstance->FindNickOnly(nick);
		if ((user) && (user->registered == REG_ALL))
			return user;
		return NULL;
	}

 private:
	typedef TR1NS::unordered_map<std::string, Entry, irc::insensitive, irc::StrHashComp> NickHash;

	Entry* Find(const std::string& nick)
	{
		NickHash::iterator it = nicks.find(nick);
		if (it != nicks.end())
			return &it->second;
		return NULL;
	}

	Entry* AddWatcher(const std::string& nick, LocalUser* user)
	{
		std::pair<NickHash::iterator, bool> ret = nicks.insert(std::make_pair(nick, Entry()));
		Entry& entry = ret.first->second;
		if (ret.second)
			entry.SetNick(nick);
		return &entry;
	}

	bool RemoveWatcher(const std::string& nick, LocalUser* user, WatchedList& watchedlist)
	{
		NickHash::iterator it = nicks.find(nick);
		// If nobody is watching this nick the user trying to remove it isn't watching it for sure
		if (it == nicks.end())
			return false;

		Entry& entry = it->second;
		// Erase from the user's list of watched nicks
		if (!stdalgo::vector::swaperase(watchedlist, &entry))
			return false; // User is not watching this nick

		// Erase from the nick's list of watching users
		stdalgo::vector::swaperase(entry.watchers, user);

		// If nobody else is watching the nick remove map entry
		if (entry.watchers.empty())
			nicks.erase(it);

		return true;
	}

	WatchedList* GetWatchedPriv(LocalUser* user, bool create = false)
	{
		ExtData* extdata = ext.get(user, create);
		if (!extdata)
			return NULL;
		return &extdata->list;
	}

	NickHash nicks;
	ExtItem ext;
	WatchedList emptywatchedlist;
};

void IRCv3::Monitor::Manager::ExtItem::FromInternal(Extensible* container, const std::string& value)
{
	irc::spacesepstream ss(value);
	for (std::string nick; ss.GetToken(nick); )
		manager.Watch(static_cast<LocalUser*>(container), nick, UINT_MAX);
}

#ifndef INSPIRCD_MONITOR_MANAGER_ONLY

enum
{
	RPL_MONONLINE = 730,
	RPL_MONOFFLINE = 731,
	RPL_MONLIST = 732,
	RPL_ENDOFMONLIST = 733,
	ERR_MONLISTFULL = 734
};

class CommandMonitor : public SplitCommand
{
	typedef Numeric::Builder<> ReplyBuilder;
	// Additional penalty for the /MONITOR L and /MONITOR S commands that request a list from the server
	static const unsigned int ListPenalty = 3000;

	IRCv3::Monitor::Manager& manager;

	void HandlePlus(LocalUser* user, const std::string& input)
	{
		ReplyBuilder online(user, RPL_MONONLINE);
		ReplyBuilder offline(user, RPL_MONOFFLINE);
		irc::commasepstream ss(input);
		for (std::string nick; ss.GetToken(nick); )
		{
			IRCv3::Monitor::Manager::WatchResult result = manager.Watch(user, nick, maxmonitor);
			if (result == IRCv3::Monitor::Manager::WR_TOOMANY)
			{
				// List is full, send error which includes the remaining nicks that were not processed
				user->WriteNumeric(ERR_MONLISTFULL, maxmonitor, InspIRCd::Format("%s%s%s", nick.c_str(), (ss.StreamEnd() ? "" : ","), ss.GetRemaining().c_str()), "Monitor list is full");
				break;
			}
			else if (result != IRCv3::Monitor::Manager::WR_OK)
				continue; // Already added or invalid nick

			ReplyBuilder& out = (IRCv3::Monitor::Manager::FindNick(nick) ? online : offline);
			out.Add(nick);
		}

		online.Flush();
		offline.Flush();
	}

	void HandleMinus(LocalUser* user, const std::string& input)
	{
		irc::commasepstream ss(input);
		for (std::string nick; ss.GetToken(nick); )
			manager.Unwatch(user, nick);
	}

 public:
	unsigned int maxmonitor;

	CommandMonitor(Module* mod, IRCv3::Monitor::Manager& managerref)
		: SplitCommand(mod, "MONITOR", 1)
		, manager(managerref)
	{
		Penalty = 2;
		allow_empty_last_param = false;
		syntax = "C|L|S|(+|-) <nick>[,<nick>]+";
	}

	CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
	{
		char subcmd = toupper(parameters[0][0]);
		if (subcmd == '+')
		{
			if (parameters.size() > 1)
				HandlePlus(user, parameters[1]);
		}
		else if (subcmd == '-')
		{
			if (parameters.size() > 1)
				HandleMinus(user, parameters[1]);
		}
		else if (subcmd == 'C')
		{
			manager.UnwatchAll(user);
		}
		else if (subcmd == 'L')
		{
			user->CommandFloodPenalty += ListPenalty;
			const IRCv3::Monitor::WatchedList& list = manager.GetWatched(user);
			ReplyBuilder out(user, RPL_MONLIST);
			for (IRCv3::Monitor::WatchedList::const_iterator i = list.begin(); i != list.end(); ++i)
			{
				IRCv3::Monitor::Entry* entry = *i;
				out.Add(entry->GetNick());
			}
			out.Flush();
			user->WriteNumeric(RPL_ENDOFMONLIST, "End of MONITOR list");
		}
		else if (subcmd == 'S')
		{
			user->CommandFloodPenalty += ListPenalty;

			ReplyBuilder online(user, RPL_MONONLINE);
			ReplyBuilder offline(user, RPL_MONOFFLINE);

			const IRCv3::Monitor::WatchedList& list = manager.GetWatched(user);
			for (IRCv3::Monitor::WatchedList::const_iterator i = list.begin(); i != list.end(); ++i)
			{
				IRCv3::Monitor::Entry* entry = *i;
				ReplyBuilder& out = (IRCv3::Monitor::Manager::FindNick(entry->GetNick()) ? online : offline);
				out.Add(entry->GetNick());
			}

			online.Flush();
			offline.Flush();
		}
		else
			return CMD_FAILURE;

		return CMD_SUCCESS;
	}
};

class ModuleMonitor : public Module
{
	IRCv3::Monitor::Manager manager;
	CommandMonitor cmd;

	void SendAlert(unsigned int numeric, const std::string& nick)
	{
		const IRCv3::Monitor::WatcherList* list = manager.GetWatcherList(nick);
		if (!list)
			return;

		for (IRCv3::Monitor::WatcherList::const_iterator i = list->begin(); i != list->end(); ++i)
		{
			LocalUser* curr = *i;
			curr->WriteNumeric(numeric, nick);
		}
	}

 public:
	ModuleMonitor()
		: manager(this, "monitor")
		, cmd(this, manager)
	{
	}

	void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
	{
		ConfigTag* tag = ServerInstance->Config->ConfValue("monitor");
		cmd.maxmonitor = tag->getUInt("maxentries", 30, 1);
	}

	void OnPostConnect(User* user) CXX11_OVERRIDE
	{
		SendAlert(RPL_MONONLINE, user->nick);
	}

	void OnUserPostNick(User* user, const std::string& oldnick) CXX11_OVERRIDE
	{
		// Detect and ignore nickname case change
		if (ServerInstance->FindNickOnly(oldnick) == user)
			return;

		SendAlert(RPL_MONOFFLINE, oldnick);
		SendAlert(RPL_MONONLINE, user->nick);
	}

	void OnUserQuit(User* user, const std::string& message, const std::string& oper_message) CXX11_OVERRIDE
	{
		LocalUser* localuser = IS_LOCAL(user);
		if (localuser)
			manager.UnwatchAll(localuser);
		SendAlert(RPL_MONOFFLINE, user->nick);
	}

	void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
	{
		tokens["MONITOR"] = ConvToStr(cmd.maxmonitor);
	}

	Version GetVersion() CXX11_OVERRIDE
	{
		return Version("Adds the /MONITOR command which allows users to find out when their friends are connected to the server.", VF_VENDOR);
	}
};

MODULE_INIT(ModuleMonitor)

#endif