summaryrefslogtreecommitdiff
path: root/src/botserv.cpp
blob: c1b7fde562fadbbbda5a1587525c582e27efeee1 (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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/* BotServ functions
 *
 * (C) 2003-2011 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 *
 * Based on the original code of Epona by Lara.
 * Based on the original code of Services by Andy Church.
 */

/*************************************************************************/

#include "services.h"
#include "modules.h"

static UserData *get_user_data(Channel *c, User *u);

E void moduleAddBotServCmds();

/*************************************************************************/

void moduleAddBotServCmds()
{
	ModuleManager::LoadModuleList(Config->BotServCoreModules);
}

/*************************************************************************/
/*************************************************************************/

/* Return information on memory use.  Assumes pointers are valid. */

void get_botserv_stats(long *nrec, long *memuse)
{
	long count = 0, mem = 0;

	for (patricia_tree<BotInfo *, ci::ci_char_traits>::iterator it(BotListByNick); it.next();)
	{
		BotInfo *bi = *it;

		++count;
		mem += sizeof(*bi);
		mem += bi->nick.length() + 1;
		mem += bi->GetIdent().length() + 1;
		mem += bi->host.length() + 1;
		mem += bi->realname.length() + 1;
	}

	*nrec = count;
	*memuse = mem;
}

/*************************************************************************/
/*************************************************************************/

/* BotServ initialization. */

void bs_init()
{
	if (!Config->s_BotServ.empty())
		moduleAddBotServCmds();
}

/*************************************************************************/

/* Handles all messages that are sent to registered channels where a
 * bot is on.
 */

void botchanmsgs(User *u, ChannelInfo *ci, const Anope::string &buf)
{
	if (!u || !ci || !ci->c || buf.empty())
		return;

	/* Answer to ping if needed */
	if (buf.substr(0, 6).equals_ci("\1PING ") && buf[buf.length() - 1] == '\1')
	{
		Anope::string ctcp = buf;
		ctcp.erase(ctcp.begin());
		ctcp.erase(ctcp.length() - 1);
		ircdproto->SendCTCP(ci->bi, u->nick, "%s", ctcp.c_str());
	}

	bool was_action = false;
	Anope::string realbuf = buf;

	/* If it's a /me, cut the CTCP part because the ACTION will cause
	 * problems with the caps or badwords kicker
	 */
	if (realbuf.substr(0, 8).equals_ci("\1ACTION ") && realbuf[realbuf.length() - 1] == '\1')
	{
		realbuf.erase(0, 8);
		realbuf.erase(realbuf.length() - 1);
		was_action = true;
	}

	if (realbuf.empty())
		return;

	/* Now we can make kicker stuff. We try to order the checks
	 * from the fastest one to the slowest one, since there's
	 * no need to process other kickers if a user is kicked before
	 * the last kicker check.
	 *
	 * But FIRST we check whether the user is protected in any
	 * way.
	 */

	bool Allow = false;
	if (!ci->botflags.HasFlag(BS_DONTKICKOPS) && !ci->botflags.HasFlag(BS_DONTKICKVOICES))
		Allow = true;
	else if (ci->botflags.HasFlag(BS_DONTKICKOPS) && (ci->c->HasUserStatus(u, CMODE_HALFOP) || ci->c->HasUserStatus(u, CMODE_OP) || ci->c->HasUserStatus(u, CMODE_PROTECT) || ci->c->HasUserStatus(u, CMODE_OWNER)))
		Allow = true;
	else if (ci->botflags.HasFlag(BS_DONTKICKVOICES) && ci->c->HasUserStatus(u, CMODE_VOICE))
		Allow = true;
	
	EventReturn MOD_RESULT;
	FOREACH_RESULT(I_OnPrivmsg, OnPrivmsg(u, ci, realbuf, Allow));
	if (MOD_RESULT == EVENT_STOP)
		return;

	if (!check_access(u, ci, CA_NOKICK) && Allow)
	{
		/* Bolds kicker */
		if (ci->botflags.HasFlag(BS_KICK_BOLDS) && realbuf.find(2) != Anope::string::npos)
		{
			check_ban(ci, u, TTB_BOLDS);
			bot_kick(ci, u, _("Don't use bolds on this channel!"));
			return;
		}

		/* Color kicker */
		if (ci->botflags.HasFlag(BS_KICK_COLORS) && realbuf.find(3) != Anope::string::npos)
		{
			check_ban(ci, u, TTB_COLORS);
			bot_kick(ci, u, _("Don't use colors on this channel!"));
			return;
		}

		/* Reverses kicker */
		if (ci->botflags.HasFlag(BS_KICK_REVERSES) && realbuf.find(22) != Anope::string::npos)
		{
			check_ban(ci, u, TTB_REVERSES);
			bot_kick(ci, u, _("Don't use reverses on this channel!"));
			return;
		}

		/* Italics kicker */
		if (ci->botflags.HasFlag(BS_KICK_ITALICS) && realbuf.find(29) != Anope::string::npos)
		{
			check_ban(ci, u, TTB_ITALICS);
			bot_kick(ci, u, _("Don't use italics on this channel!"));
			return;
		}

		/* Underlines kicker */
		if (ci->botflags.HasFlag(BS_KICK_UNDERLINES) && realbuf.find(31) != Anope::string::npos)
		{
			check_ban(ci, u, TTB_UNDERLINES);
			bot_kick(ci, u, _("Don't use underlines on this channel!"));
			return;
		}

		/* Caps kicker */
		if (ci->botflags.HasFlag(BS_KICK_CAPS) && realbuf.length() >= ci->capsmin)
		{
			int i = 0, l = 0;

			for (unsigned j = 0, end = realbuf.length(); j < end; ++j)
			{
				if (isupper(realbuf[j]))
					++i;
				else if (islower(realbuf[j]))
					++l;
			}

			/* i counts uppercase chars, l counts lowercase chars. Only
			 * alphabetic chars (so islower || isupper) qualify for the
			 * percentage of caps to kick for; the rest is ignored. -GD
			 */

			if (i && l && i >= ci->capsmin && i * 100 / (i + l) >= ci->capspercent)
			{
				check_ban(ci, u, TTB_CAPS);
				bot_kick(ci, u, _("Turn caps lock OFF!"));
				return;
			}
		}

		/* Bad words kicker */
		if (ci->botflags.HasFlag(BS_KICK_BADWORDS))
		{
			bool mustkick = false;

			/* Normalize the buffer */
			Anope::string nbuf = normalizeBuffer(realbuf);

			for (unsigned i = 0, end = ci->GetBadWordCount(); i < end; ++i)
			{
				BadWord *bw = ci->GetBadWord(i);

				if (bw->type == BW_ANY && ((Config->BSCaseSensitive && nbuf.find(bw->word) != Anope::string::npos) || (!Config->BSCaseSensitive && nbuf.find_ci(bw->word) != Anope::string::npos)))
					mustkick = true;
				else if (bw->type == BW_SINGLE)
				{
					size_t len = bw->word.length();

					if ((Config->BSCaseSensitive && bw->word.equals_cs(nbuf)) || (!Config->BSCaseSensitive && bw->word.equals_ci(nbuf)))
						mustkick = true;
					else if (nbuf.find(' ') == len && ((Config->BSCaseSensitive && bw->word.equals_cs(nbuf)) || (!Config->BSCaseSensitive && bw->word.equals_ci(nbuf))))
						mustkick = true;
					else
					{
						if (nbuf.rfind(' ') == nbuf.length() - len - 1 && ((Config->BSCaseSensitive && nbuf.find(bw->word) == nbuf.length() - len) || (!Config->BSCaseSensitive && nbuf.find_ci(bw->word) == nbuf.length() - len)))
							mustkick = true;
						else
						{
							Anope::string wordbuf = " " + bw->word + " ";

							if ((Config->BSCaseSensitive && nbuf.find(wordbuf) != Anope::string::npos) || (!Config->BSCaseSensitive && nbuf.find_ci(wordbuf) != Anope::string::npos))
								mustkick = true;
						}
					}
				}
				else if (bw->type == BW_START)
				{
					size_t len = bw->word.length();

					if ((Config->BSCaseSensitive && nbuf.substr(0, len).equals_cs(bw->word)) || (!Config->BSCaseSensitive && nbuf.substr(0, len).equals_ci(bw->word)))
						mustkick = true;
					else
					{
						Anope::string wordbuf = " " + bw->word;

						if ((Config->BSCaseSensitive && nbuf.find(wordbuf) != Anope::string::npos) || (!Config->BSCaseSensitive && nbuf.find_ci(wordbuf) != Anope::string::npos))
							mustkick = true;
					}
				}
				else if (bw->type == BW_END)
				{
					size_t len = bw->word.length();

					if ((Config->BSCaseSensitive && nbuf.substr(nbuf.length() - len).equals_cs(bw->word)) || (!Config->BSCaseSensitive && nbuf.substr(nbuf.length() - len).equals_ci(bw->word)))
						mustkick = true;
					else
					{
						Anope::string wordbuf = bw->word + " ";

						if ((Config->BSCaseSensitive && nbuf.find(wordbuf) != Anope::string::npos) || (!Config->BSCaseSensitive && nbuf.find_ci(wordbuf) != Anope::string::npos))
							mustkick = true;
					}
				}

				if (mustkick)
				{
					check_ban(ci, u, TTB_BADWORDS);
					if (Config->BSGentleBWReason)
						bot_kick(ci, u, _("Watch your language!"));
					else
						bot_kick(ci, u, _("Don't use the word \"%s\" on this channel!"), bw->word.c_str());

					return;
				}
			}
		}

		/* Flood kicker */
		if (ci->botflags.HasFlag(BS_KICK_FLOOD))
		{
			UserData *ud = get_user_data(ci->c, u);
			if (!ud)
				return;

			if (Anope::CurTime - ud->last_start > ci->floodsecs)
			{
				ud->last_start = Anope::CurTime;
				ud->lines = 0;
			}

			++ud->lines;
			if (ud->lines >= ci->floodlines)
			{
				check_ban(ci, u, TTB_FLOOD);
				bot_kick(ci, u, _("Stop flooding!"));
				return;
			}
		}

		/* Repeat kicker */
		if (ci->botflags.HasFlag(BS_KICK_REPEAT))
		{
			UserData *ud = get_user_data(ci->c, u);
			if (!ud)
				return;

			if (!ud->lastline.empty() && !ud->lastline.equals_ci(buf))
			{
				ud->lastline = buf;
				ud->times = 0;
			}
			else
			{
				if (ud->lastline.empty())
					ud->lastline = buf;
				++ud->times;
			}

			if (ud->times >= ci->repeattimes)
			{
				check_ban(ci, u, TTB_REPEAT);
				bot_kick(ci, u, _("Stop repeating yourself!"));
				return;
			}
		}
	}

	/* Fantaisist commands */
	if (ci->botflags.HasFlag(BS_FANTASY) && buf[0] == Config->BSFantasyCharacter[0] && !was_action)
	{
		spacesepstream sep(buf);
		Anope::string command;

		if (sep.GetToken(command) && command[0] == Config->BSFantasyCharacter[0])
		{
			/* Strip off the fantasy character */
			command.erase(command.begin());

			if (check_access(u, ci, CA_FANTASIA))
			{
				Anope::string message = sep.GetRemaining();

				FOREACH_RESULT(I_OnPreCommandRun, OnPreCommandRun(u, ci->bi, command, message, ci));
				if (MOD_RESULT == EVENT_STOP)
					return;

				Command *cmd = FindCommand(ChanServ, command);

				/* Command exists and can be called by fantasy */
				if (cmd && !cmd->HasFlag(CFLAG_DISABLE_FANTASY))
				{
					/* Some commands don't need the channel name added.. eg !help */
					if (!cmd->HasFlag(CFLAG_STRIP_CHANNEL))
						message = ci->name + " " + message;
					message = command + " " + message;

					mod_run_cmd(ChanServ, u, ci, message);
				}

				FOREACH_MOD(I_OnBotFantasy, OnBotFantasy(command, u, ci, sep.GetRemaining()));
			}
			else
			{
				FOREACH_MOD(I_OnBotNoFantasyAccess, OnBotNoFantasyAccess(command, u, ci, sep.GetRemaining()));
			}
		}
	}
}

/*************************************************************************/

BotInfo *findbot(const Anope::string &nick)
{
	BotInfo *bi;
	if (isdigit(nick[0]) && ircd->ts6)
		bi = BotListByUID.find(nick);
	else
		bi = BotListByNick.find(nick);
	
	FOREACH_MOD(I_OnFindBot, OnFindBot(nick));
	
	return bi;
}

/*************************************************************************/

/* Returns ban data associated with a user if it exists, allocates it
   otherwise. */

static BanData *get_ban_data(Channel *c, User *u)
{
	if (!c || !u)
		return NULL;

	Anope::string mask = u->GetIdent() + "@" + u->GetDisplayedHost();
	/* XXX This should really be on some sort of timer/garbage collector, and use std::map */
	for (std::list<BanData *>::iterator it = c->bd.begin(), it_end = c->bd.end(), it_next; it != it_end; it = it_next)
	{
		it_next = it;
		++it_next;

		if (Anope::CurTime - (*it)->last_use > Config->BSKeepData)
		{
			delete *it;
			c->bd.erase(it);
			continue;
		}
		if ((*it)->mask.equals_ci(mask))
		{
			(*it)->last_use = Anope::CurTime;
			return *it;
		}
	}

	/* If we fall here it is that we haven't found the record */
	BanData *bd = new BanData();
	bd->mask = mask;
	bd->last_use = Anope::CurTime;
	for (int x = 0; x < TTB_SIZE; ++x)
		bd->ttb[x] = 0;

	c->bd.push_front(bd);

	return bd;
}

/*************************************************************************/

/* Returns BotServ data associated with a user on a given channel.
 * Allocates it if necessary.
 */

static UserData *get_user_data(Channel *c, User *u)
{
	if (!c || !u)
		return NULL;

	for (CUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ++it)
	{
		UserContainer *uc = *it;

		if (uc->user == u)
		{
			/* Checks whether data is obsolete */
			if (Anope::CurTime - uc->ud.last_use > Config->BSKeepData)
			{
				/* We should not free and realloc, but reset to 0
				   instead. */
				uc->ud.Clear();
				uc->ud.last_use = Anope::CurTime;
			}

			return &uc->ud;
		}
	}

	return NULL;
}

/*************************************************************************/

/** Check if a user should be banned by botserv
 * @param ci The channel the user is on
 * @param u The user
 * @param ttbtype The type of bot kicker the user should be checked against
 */
void check_ban(ChannelInfo *ci, User *u, int ttbtype)
{
	BanData *bd = get_ban_data(ci->c, u);

	if (!bd)
		return;

	/* Don't ban ulines */
	if (u->server->IsULined())
		return;

	++bd->ttb[ttbtype];
	if (ci->ttb[ttbtype] && bd->ttb[ttbtype] >= ci->ttb[ttbtype])
	{
		/* Should not use == here because bd->ttb[ttbtype] could possibly be > ci->ttb[ttbtype]
		 * if the TTB was changed after it was not set (0) before and the user had already been
		 * kicked a few times. Bug #1056 - Adam */
		Anope::string mask;

		bd->ttb[ttbtype] = 0;

		get_idealban(ci, u, mask);

		if (ci->c)
			ci->c->SetMode(NULL, CMODE_BAN, mask);
		FOREACH_MOD(I_OnBotBan, OnBotBan(u, ci, mask));
	}
}

/*************************************************************************/

/* This makes a bot kick a user. Works somewhat like notice_lang in fact ;) */

void bot_kick(ChannelInfo *ci, User *u, const char *message, ...)
{
	va_list args;
	char buf[1024];

	if (!ci || !ci->bi || !ci->c || !u)
		return;

	Anope::string fmt = GetString(u->Account(), message);
	va_start(args, message);
	if (fmt.empty())
		return;
	vsnprintf(buf, sizeof(buf), fmt.c_str(), args);
	va_end(args);

	ci->c->Kick(ci->bi, u, "%s", buf);
}

/*************************************************************************/

/* Makes a simple ban and kicks the target
 * @param requester The user requesting the kickban
 * @param ci The channel
 * @param u The user being kicked
 * @param reason The reason
 */
void bot_raw_ban(User *requester, ChannelInfo *ci, User *u, const Anope::string &reason)
{
	if (!u || !ci)
		return;

	if (ModeManager::FindUserModeByName(UMODE_PROTECTED) && u->IsProtected() && requester != u)
	{
		ircdproto->SendPrivmsg(ci->bi, ci->name, "%s", GetString(requester->Account(), _(ACCESS_DENIED)).c_str());
		return;
	}

	ChanAccess *u_access = ci->GetAccess(u), *req_access = ci->GetAccess(requester);
	int16 u_level = u_access ? u_access->level : 0, req_level = req_access ? req_access->level : 0;
	if (ci->HasFlag(CI_PEACE) && !requester->nick.equals_ci(u->nick) && u_level >= req_level)
		return;

	if (matches_list(ci->c, u, CMODE_EXCEPT))
	{
		ircdproto->SendPrivmsg(ci->bi, ci->name, "%s", GetString(requester->Account(), _("User matches channel except.")).c_str());
		return;
	}

	Anope::string mask;
	get_idealban(ci, u, mask);

	ci->c->SetMode(NULL, CMODE_BAN, mask);

	/* Check if we need to do a signkick or not -GD */
	if (ci->HasFlag(CI_SIGNKICK) || (ci->HasFlag(CI_SIGNKICK_LEVEL) && !check_access(requester, ci, CA_SIGNKICK)))
		ci->c->Kick(ci->bi, u, "%s (%s)", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str(), requester->nick.c_str());
	else
		ci->c->Kick(ci->bi, u, "%s", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str());
}

/*************************************************************************/

/* Makes a kick with a "dynamic" reason ;)
 * @param requester The user requesting the kick
 * @param ci The channel
 * @param u The user being kicked
 * @param reason The reason for the kick
 */
void bot_raw_kick(User *requester, ChannelInfo *ci, User *u, const Anope::string &reason)
{
	if (!u || !ci || !ci->c || !ci->c->FindUser(u))
		return;

	if (ModeManager::FindUserModeByName(UMODE_PROTECTED) && u->IsProtected() && requester != u)
	{
		ircdproto->SendPrivmsg(ci->bi, ci->name, "%s", GetString(requester->Account(), _(ACCESS_DENIED)).c_str());
		return;
	}

	ChanAccess *u_access = ci->GetAccess(u), *req_access = ci->GetAccess(requester);
	int16 u_level = u_access ? u_access->level : 0, req_level = req_access ? req_access->level : 0;
	if (ci->HasFlag(CI_PEACE) && !requester->nick.equals_ci(u->nick) && u_level >= req_level)
		return;

	if (ci->HasFlag(CI_SIGNKICK) || (ci->HasFlag(CI_SIGNKICK_LEVEL) && !check_access(requester, ci, CA_SIGNKICK)))
		ci->c->Kick(ci->bi, u, "%s (%s)", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str(), requester->nick.c_str());
	else
		ci->c->Kick(ci->bi, u, "%s", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str());
}

/*************************************************************************/

/**
 * Normalize buffer stripping control characters and colors
 * @param A string to be parsed for control and color codes
 * @return A string stripped of control and color codes
 */
Anope::string normalizeBuffer(const Anope::string &buf)
{
	Anope::string newbuf;

	for (unsigned i = 0, end = buf.length(); i < end; ++i)
	{
		switch (buf[i])
		{
			/* ctrl char */
			case 1:
				break;
			/* Bold ctrl char */
			case 2:
				break;
			/* Color ctrl char */
			case 3:
				/* If the next character is a digit, its also removed */
				if (isdigit(buf[i + 1]))
				{
					++i;

					/* not the best way to remove colors
					 * which are two digit but no worse then
					 * how the Unreal does with +S - TSL
					 */
					if (isdigit(buf[i + 1]))
						++i;

					/* Check for background color code
					 * and remove it as well
					 */
					if (buf[i + 1] == ',')
					{
						++i;

						if (isdigit(buf[i + 1]))
							++i;
						/* not the best way to remove colors
						 * which are two digit but no worse then
						 * how the Unreal does with +S - TSL
						 */
						if (isdigit(buf[i + 1]))
							++i;
					}
				}

				break;
			/* line feed char */
			case 10:
				break;
			/* carriage returns char */
			case 13:
				break;
			/* Reverse ctrl char */
			case 22:
				break;
			/* Underline ctrl char */
			case 31:
				break;
			/* Italic ctrl char */
			case 29:
				break;
			/* A valid char gets copied into the new buffer */
			default:
				newbuf += buf[i];
		}
	}

	return newbuf;
}