aboutsummaryrefslogtreecommitdiff
path: root/src/modules/m_serverbots.cpp
blob: b50403da388193c44063c3c64cb84f81bd0c1732 (about) (plain) (blame)
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
/*       +------------------------------------+
 *       | Inspire Internet Relay Chat Daemon |
 *       +------------------------------------+
 *
 *  InspIRCd: (C) 2002-2011 InspIRCd Development Team
 * See: http://wiki.inspircd.org/Credits
 *
 * This program is free but copyrighted software; see
 *            the file COPYING for details.
 *
 * ---------------------------------------------------
 */

#include "inspircd.h"
#include "command_parse.h"
#include "cull_list.h"

/* $ModDesc: Provides fake clients that respond to messages. */

namespace m_serverbots
{

/** Command definition
 */
class Alias
{
 public:
	/** The text of the alias command */
	irc::string AliasedCommand;

	/** Text to replace with */
	std::string ReplaceFormat;

	/** Nickname required to perform alias */
	std::string RequiredNick;

	/** RequiredNick must be on a ulined server */
	bool ULineOnly;

	/** Requires oper? */
	bool OperOnly;

	/** Format that must be matched for use */
	std::string format;
};

typedef std::multimap<irc::string, Alias>::iterator AliasIter;

class AliasFormatSubst : public FormatSubstitute
{
 public:
	SubstMap info;
	const std::string &line;
	AliasFormatSubst(const std::string &Line) : line(Line) {}
	std::string lookup(const std::string& key)
	{
		if (isdigit(key[0]))
		{
			int index = atoi(key.c_str());
			irc::spacesepstream ss(line);
			bool everything_after = (key.find('-') != std::string::npos);
			bool good = true;
			std::string word;

			for (int j = 0; j < index && good; j++)
				good = ss.GetToken(word);

			if (everything_after)
			{
				std::string more;
				while (ss.GetToken(more))
				{
					word.append(" ");
					word.append(more);
				}
			}

			return word;
		}
		SubstMap::iterator i = info.find(key);
		if (i != info.end())
			return i->second;
		return "";
	}
};

class ServerBot : public FakeUser
{
 public:
	ServerBot(const std::string& uid) : FakeUser(uid, ServerInstance->Config->ServerName) {}
	virtual const std::string& GetFullHost()
	{
		return this->User::GetFullHost();
	}
};

class BotData
{
 public:
	std::multimap<irc::string, Alias> Aliases;
	ServerBot* const bot;
	BotData(ServerBot* Bot) : bot(Bot) {}

	void HandleMessage(LocalUser* user, const std::string& text)
	{
		if(!user)
			return;
		irc::spacesepstream ss(text);
		std::string command, params;
		ss.GetToken(command);
		params = ss.GetRemaining();

		std::pair<AliasIter, AliasIter> range = Aliases.equal_range(command);

		for(AliasIter i = range.first; i != range.second; ++i)
			if(DoAlias(user, &i->second, params, text))
				return;

		// also support no-command aliases (presumably they have format checks)
		range = Aliases.equal_range("");
		for(AliasIter i = range.first; i != range.second; ++i)
			if(DoAlias(user, &i->second, text, text))
				return;
	}

	bool DoAlias(LocalUser *user, Alias *a, const std::string& params, const std::string& text)
	{
		/* Does it match the pattern? */
		if (!a->format.empty())
		{
			if (!InspIRCd::Match(params, a->format))
				return false;
		}

		if ((a->OperOnly) && (!IS_OPER(user)))
			return 0;

		if (!a->RequiredNick.empty())
		{
			User* u = ServerInstance->FindNick(a->RequiredNick);
			if (!u)
			{
				user->WriteFrom(bot, "NOTICE %s :%s is currently unavailable. Please try again later.",
					user->nick.c_str(), a->RequiredNick.c_str());
				return true;
			}
			if (a->ULineOnly && !ServerInstance->ULine(u->server))
			{
				ServerInstance->SNO->WriteToSnoMask('a', "NOTICE -- Service "+a->RequiredNick+" required by alias "+std::string(a->AliasedCommand.c_str())+" is not on a u-lined server, possibly underhanded antics detected!");
				user->WriteFrom(bot, "NOTICE %s :%s is an imposter! Please inform an IRC operator as soon as possible.",
					user->nick.c_str(), a->RequiredNick.c_str());
				return true;
			}
		}

		/* Now, search and replace in a copy of the original_line, replacing $1 through $9 and $1- etc */

		irc::sepstream commands(a->ReplaceFormat, '\n');
		std::string scommand;
		while (commands.GetToken(scommand))
		{
			DoCommand(scommand, user, text);
		}
		return true;
	}

	void DoCommand(const std::string& format, LocalUser* user, const std::string &text)
	{
		AliasFormatSubst subst(text);
		user->PopulateInfoMap(subst.info);
		std::string bothost = bot->GetFullHost();
		subst.info["bot"] = bot->nick;
		subst.info["fullbot"] = bothost;
		std::string result = subst.format(format);

		irc::tokenstream ss(result);
		std::vector<std::string> pars;
		std::string command, token;

		ss.GetToken(command);
		if (irc::string(command) == "BOTNOTICE")
		{
			ss.GetToken(token);
			user->Write(":%s NOTICE %s :%s", bothost.c_str(), user->nick.c_str(), token.c_str());
			return;
		}

		while (ss.GetToken(token) && (pars.size() <= MAXPARAMETERS))
		{
			pars.push_back(token);
		}
		CmdResult res = ServerInstance->Parser->CallHandler(command, pars, user);
		FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, pars, user, res,text));
	}

	std::string GetVar(std::string varname, const std::string &original_line)
	{
		irc::spacesepstream ss(original_line);
		int index = varname[1] - '0';
		bool everything_after = (varname.length() == 3);
		std::string word;

		for (int j = 0; j < index; j++)
			ss.GetToken(word);

		if (everything_after)
			return ss.GetRemaining();

		ss.GetToken(word);
		return word;
	}
};

class BotTracker : public SimpleExtItem<BotData>
{
 public:
	std::map<std::string, BotData*> bots;
	BotTracker(Module* Creator) : SimpleExtItem<BotData>(EXTENSIBLE_USER, "serverbot", Creator) {}

	void free(void* item)
	{
		BotData* ext = static_cast<BotData*>(item);
		if (!ext)
			return;
		bots.erase(ext->bot->nick);
		ServerInstance->GlobalCulls->AddItem(ext->bot);
		delete ext;
	}
};

class ModuleServerBots : public Module
{
	BotTracker dataExt;
	bool recursing;
	int botID;
 public:
	ModuleServerBots() : dataExt(this), recursing(false), botID(0) {}

	void early_init()
	{
		ServerInstance->Modules->AddService(dataExt);
	}

	void init()
	{
		ServerInstance->Modules->Attach(I_OnUserMessage, this);
	}

	Version GetVersion()
	{
		return Version("Provides fake clients for handling IRCd commands.", VF_VENDOR);
	}

	void OnUserMessage(User *user, void *dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
	{
		if (target_type != TYPE_USER)
			return;
		User* b = (User*)dest;
		BotData* bot = dataExt.get(b);
		if (!bot)
			return;

		if (recursing)
		{
			user->WriteFrom(bot->bot, "NOTICE %s :Your command caused a recursive bot message which was not processed.", user->nick.c_str());
			return;
		}

		recursing = true;
		bot->HandleMessage(IS_LOCAL(user), text);
		recursing = false;
	}

	void ReadConfig(ConfigReadStatus&)
	{
		std::map<std::string, BotData*> oldbots;
		oldbots.swap(dataExt.bots);

		ConfigTagList tags = ServerInstance->Config->GetTags("bot");
		for(ConfigIter i = tags.first; i != tags.second; i++)
		{
			ConfigTag* tag = i->second;
			// UID is of the form "12!BOT"
			std::string nick = tag->getString("nick");
			if (nick.empty())
				continue;
			std::map<std::string, BotData*>::iterator found = oldbots.find(nick);
			ServerBot* bot;
			if (found != oldbots.end())
			{
				dataExt.bots.insert(*found);
				bot = found->second->bot;
				found->second->Aliases.clear();
				oldbots.erase(found);
			}
			else
			{
				User* bump = ServerInstance->FindNick(nick);
				if (bump)
					bump->ChangeNick(bump->uuid, true);
				std::string uid = ConvToStr(++botID) + "!BOT";
				bot = new ServerBot(uid);
				BotData* bd = new BotData(bot);
				dataExt.set(bot, bd);
				dataExt.bots.insert(std::make_pair(nick, bd));

				bot->ChangeNick(nick, true);
			}
			bot->ident = tag->getString("ident", "bot");
			bot->host = tag->getString("host", ServerInstance->Config->ServerName);
			bot->dhost = bot->host;
			bot->fullname = tag->getString("name", "Server-side Bot");
			bot->InvalidateCache();
			std::string oper = tag->getString("oper", "Server_Bot");
			if (!oper.empty())
			{
				OperIndex::iterator iter = ServerInstance->Config->oper_blocks.find(" " + oper);
				if (iter != ServerInstance->Config->oper_blocks.end())
					bot->oper = iter->second;
				else
					bot->oper = new OperInfo(oper);
			}
		}
		for(std::map<std::string, BotData*>::iterator i = oldbots.begin(); i != oldbots.end(); i++)
		{
			ServerInstance->GlobalCulls->AddItem(i->second->bot);
		}

		tags = ServerInstance->Config->GetTags("botcmd");
		for(ConfigIter i = tags.first; i != tags.second; i++)
		{
			ConfigTag* tag = i->second;
			std::string botnick = tag->getString("bot");
			std::map<std::string, BotData*>::iterator found = dataExt.bots.find(botnick);
			if (found == dataExt.bots.end())
				continue;
			BotData* bot = found->second;
			Alias a;
			a.AliasedCommand = tag->getString("text").c_str();
			tag->readString("replace", a.ReplaceFormat, true);
			a.RequiredNick = tag->getString("requires");
			a.ULineOnly = tag->getBool("uline");
			a.OperOnly = tag->getBool("operonly");
			a.format = tag->getString("format");

			bot->Aliases.insert(std::make_pair(a.AliasedCommand, a));
		}
 	}
};

}

using m_serverbots::ModuleServerBots;

MODULE_INIT(ModuleServerBots)