1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2021 Herman <GermanAizek@yandex.ru>
5  *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6  *   Copyright (C) 2018 systocrat <systocrat@outlook.com>
7  *   Copyright (C) 2018 Dylan Frank <b00mx0r@aureus.pw>
8  *   Copyright (C) 2013, 2016-2021 Sadie Powell <sadie@witchery.services>
9  *   Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
10  *   Copyright (C) 2013 ChrisTX <xpipe@hotmail.de>
11  *   Copyright (C) 2013 Adam <Adam@anope.org>
12  *   Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
13  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
14  *   Copyright (C) 2012 DjSlash <djslash@djslash.org>
15  *   Copyright (C) 2011 jackmcbarn <jackmcbarn@inspircd.org>
16  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
17  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
18  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
19  *   Copyright (C) 2008 John Brooks <special@inspircd.org>
20  *   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
21  *   Copyright (C) 2006-2009 Robin Burchell <robin+git@viroteck.net>
22  *   Copyright (C) 2004, 2006-2009 Craig Edwards <brain@inspircd.org>
23  *
24  * This file is part of InspIRCd.  InspIRCd is free software: you can
25  * redistribute it and/or modify it under the terms of the GNU General Public
26  * License as published by the Free Software Foundation, version 2.
27  *
28  * This program is distributed in the hope that it will be useful, but WITHOUT
29  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
30  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
31  * details.
32  *
33  * You should have received a copy of the GNU General Public License
34  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
35  */
36 
37 
38 #include "inspircd.h"
39 #include "xline.h"
40 
41 ClientProtocol::MessageList LocalUser::sendmsglist;
42 
IsNoticeMaskSet(unsigned char sm)43 bool User::IsNoticeMaskSet(unsigned char sm)
44 {
45 	if (!isalpha(sm))
46 		return false;
47 	return (snomasks[sm-65]);
48 }
49 
IsModeSet(unsigned char m) const50 bool User::IsModeSet(unsigned char m) const
51 {
52 	ModeHandler* mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
53 	return (mh && modes[mh->GetId()]);
54 }
55 
GetModeLetters(bool includeparams) const56 std::string User::GetModeLetters(bool includeparams) const
57 {
58 	std::string ret(1, '+');
59 	std::string params;
60 
61 	for (unsigned char i = 'A'; i <= 'z'; i++)
62 	{
63 		const ModeHandler* const mh = ServerInstance->Modes.FindMode(i, MODETYPE_USER);
64 		if ((!mh) || (!IsModeSet(mh)))
65 			continue;
66 
67 		ret.push_back(mh->GetModeChar());
68 		if ((includeparams) && (mh->NeedsParam(true)))
69 		{
70 			const std::string val = mh->GetUserParameter(this);
71 			if (!val.empty())
72 				params.append(1, ' ').append(val);
73 		}
74 	}
75 
76 	ret += params;
77 	return ret;
78 }
79 
User(const std::string & uid,Server * srv,UserType type)80 User::User(const std::string& uid, Server* srv, UserType type)
81 	: age(ServerInstance->Time())
82 	, signon(0)
83 	, uuid(uid)
84 	, server(srv)
85 	, registered(REG_NONE)
86 	, quitting(false)
87 	, usertype(type)
88 {
89 	client_sa.sa.sa_family = AF_UNSPEC;
90 
91 	ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New UUID for user: %s", uuid.c_str());
92 
93 	if (srv->IsULine())
94 		ServerInstance->Users.all_ulines.push_back(this);
95 
96 	// Do not insert FakeUsers into the uuidlist so FindUUID() won't return them which is the desired behavior
97 	if (type != USERTYPE_SERVER)
98 	{
99 		if (!ServerInstance->Users.uuidlist.insert(std::make_pair(uuid, this)).second)
100 			throw CoreException("Duplicate UUID in User constructor: " + uuid);
101 	}
102 }
103 
LocalUser(int myfd,irc::sockets::sockaddrs * client,irc::sockets::sockaddrs * servaddr)104 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
105 	: User(ServerInstance->UIDGen.GetUID(), ServerInstance->FakeClient->server, USERTYPE_LOCAL)
106 	, eh(this)
107 	, serializer(NULL)
108 	, bytes_in(0)
109 	, bytes_out(0)
110 	, cmds_in(0)
111 	, cmds_out(0)
112 	, quitting_sendq(false)
113 	, lastping(true)
114 	, exempt(false)
115 	, nextping(0)
116 	, idle_lastmsg(0)
117 	, CommandFloodPenalty(0)
118 	, already_sent(0)
119 {
120 	signon = ServerInstance->Time();
121 	// The user's default nick is their UUID
122 	nick = uuid;
123 	ident = uuid;
124 	eh.SetFd(myfd);
125 	memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
126 	memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
127 	ChangeRealHost(GetIPString(), true);
128 }
129 
LocalUser(int myfd,const std::string & uid,Serializable::Data & data)130 LocalUser::LocalUser(int myfd, const std::string& uid, Serializable::Data& data)
131 	: User(uid, ServerInstance->FakeClient->server, USERTYPE_LOCAL)
132 	, eh(this)
133 	, already_sent(0)
134 {
135 	eh.SetFd(myfd);
136 	Deserialize(data);
137 }
138 
~User()139 User::~User()
140 {
141 }
142 
MakeHost()143 const std::string& User::MakeHost()
144 {
145 	if (!this->cached_makehost.empty())
146 		return this->cached_makehost;
147 
148 	this->cached_makehost = ident + "@" + GetRealHost();
149 	return this->cached_makehost;
150 }
151 
MakeHostIP()152 const std::string& User::MakeHostIP()
153 {
154 	if (!this->cached_hostip.empty())
155 		return this->cached_hostip;
156 
157 	this->cached_hostip = ident + "@" + this->GetIPString();
158 	return this->cached_hostip;
159 }
160 
GetFullHost()161 const std::string& User::GetFullHost()
162 {
163 	if (!this->cached_fullhost.empty())
164 		return this->cached_fullhost;
165 
166 	this->cached_fullhost = nick + "!" + ident + "@" + GetDisplayedHost();
167 	return this->cached_fullhost;
168 }
169 
GetFullRealHost()170 const std::string& User::GetFullRealHost()
171 {
172 	if (!this->cached_fullrealhost.empty())
173 		return this->cached_fullrealhost;
174 
175 	this->cached_fullrealhost = nick + "!" + ident + "@" + GetRealHost();
176 	return this->cached_fullrealhost;
177 }
178 
HasModePermission(const ModeHandler * mh) const179 bool User::HasModePermission(const ModeHandler* mh) const
180 {
181 	return true;
182 }
183 
HasModePermission(const ModeHandler * mh) const184 bool LocalUser::HasModePermission(const ModeHandler* mh) const
185 {
186 	if (!this->IsOper())
187 		return false;
188 
189 	const unsigned char mode = mh->GetModeChar();
190 	if (!ModeParser::IsModeChar(mode))
191 		return false;
192 
193 	return ((mh->GetModeType() == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
194 
195 }
196 /*
197  * users on remote servers can completely bypass all permissions based checks.
198  * This prevents desyncs when one server has different type/class tags to another.
199  * That having been said, this does open things up to the possibility of source changes
200  * allowing remote kills, etc - but if they have access to the src, they most likely have
201  * access to the conf - so it's an end to a means either way.
202  */
HasCommandPermission(const std::string &)203 bool User::HasCommandPermission(const std::string&)
204 {
205 	return true;
206 }
207 
HasCommandPermission(const std::string & command)208 bool LocalUser::HasCommandPermission(const std::string& command)
209 {
210 	// are they even an oper at all?
211 	if (!this->IsOper())
212 	{
213 		return false;
214 	}
215 
216 	return oper->AllowedOperCommands.Contains(command);
217 }
218 
HasPrivPermission(const std::string & privstr)219 bool User::HasPrivPermission(const std::string& privstr)
220 {
221 	return true;
222 }
223 
HasPrivPermission(const std::string & privstr)224 bool LocalUser::HasPrivPermission(const std::string& privstr)
225 {
226 	if (!this->IsOper())
227 		return false;
228 
229 	return oper->AllowedPrivs.Contains(privstr);
230 }
231 
HasSnomaskPermission(char chr) const232 bool User::HasSnomaskPermission(char chr) const
233 {
234 	return true;
235 }
236 
HasSnomaskPermission(char chr) const237 bool LocalUser::HasSnomaskPermission(char chr) const
238 {
239 	if (!this->IsOper() || !ModeParser::IsModeChar(chr))
240 		return false;
241 
242 	return this->oper->AllowedSnomasks[chr - 'A'];
243 }
244 
OnDataReady()245 void UserIOHandler::OnDataReady()
246 {
247 	if (user->quitting)
248 		return;
249 
250 	if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
251 	{
252 		ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
253 		ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
254 			user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
255 		return;
256 	}
257 
258 	unsigned long sendqmax = ULONG_MAX;
259 	if (!user->HasPrivPermission("users/flood/increased-buffers"))
260 		sendqmax = user->MyClass->GetSendqSoftMax();
261 
262 	unsigned long penaltymax = ULONG_MAX;
263 	if (!user->HasPrivPermission("users/flood/no-fakelag"))
264 		penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
265 
266 	// The cleaned message sent by the user or empty if not found yet.
267 	std::string line;
268 
269 	// The position of the most \n character or npos if not found yet.
270 	std::string::size_type eolpos;
271 
272 	// The position within the recvq of the current character.
273 	std::string::size_type qpos;
274 
275 	while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
276 	{
277 		// Check the newly received data for an EOL.
278 		eolpos = recvq.find('\n', checked_until);
279 		if (eolpos == std::string::npos)
280 		{
281 			checked_until = recvq.length();
282 			return;
283 		}
284 
285 		// We've found a line! Clean it up and move it to the line buffer.
286 		line.reserve(eolpos);
287 		for (qpos = 0; qpos < eolpos; ++qpos)
288 		{
289 			char c = recvq[qpos];
290 			switch (c)
291 			{
292 				case '\0':
293 					c = ' ';
294 					break;
295 				case '\r':
296 					continue;
297 			}
298 
299 			line.push_back(c);
300 		}
301 
302 		// just found a newline. Terminate the string, and pull it out of recvq
303 		recvq.erase(0, eolpos + 1);
304 		checked_until = 0;
305 
306 		// TODO should this be moved to when it was inserted in recvq?
307 		ServerInstance->stats.Recv += qpos;
308 		user->bytes_in += qpos;
309 		user->cmds_in++;
310 
311 		ServerInstance->Parser.ProcessBuffer(user, line);
312 		if (user->quitting)
313 			return;
314 
315 		// clear() does not reclaim memory associated with the string, so our .reserve() call is safe
316 		line.clear();
317 	}
318 
319 	if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
320 		ServerInstance->Users->QuitUser(user, "Excess Flood");
321 }
322 
AddWriteBuf(const std::string & data)323 void UserIOHandler::AddWriteBuf(const std::string &data)
324 {
325 	if (user->quitting_sendq)
326 		return;
327 	if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
328 		!user->HasPrivPermission("users/flood/increased-buffers"))
329 	{
330 		user->quitting_sendq = true;
331 		ServerInstance->GlobalCulls.AddSQItem(user);
332 		return;
333 	}
334 
335 	// We still want to append data to the sendq of a quitting user,
336 	// e.g. their ERROR message that says 'closing link'
337 
338 	WriteData(data);
339 }
340 
SwapInternals(UserIOHandler & other)341 void UserIOHandler::SwapInternals(UserIOHandler& other)
342 {
343 	StreamSocket::SwapInternals(other);
344 	std::swap(checked_until, other.checked_until);
345 }
346 
OnSetEndPoint(const irc::sockets::sockaddrs & server,const irc::sockets::sockaddrs & client)347 bool UserIOHandler::OnSetEndPoint(const irc::sockets::sockaddrs& server, const irc::sockets::sockaddrs& client)
348 {
349 	memcpy(&user->server_sa, &server, sizeof(irc::sockets::sockaddrs));
350 	user->SetClientIP(client);
351 	return !user->quitting;
352 }
353 
OnError(BufferedSocketError sockerr)354 void UserIOHandler::OnError(BufferedSocketError sockerr)
355 {
356 	ModResult res;
357 	FIRST_MOD_RESULT(OnConnectionFail, res, (user, sockerr));
358 	if (res != MOD_RES_ALLOW)
359 		ServerInstance->Users->QuitUser(user, getError());
360 }
361 
cull()362 CullResult User::cull()
363 {
364 	if (!quitting)
365 		ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
366 
367 	if (client_sa.family() != AF_UNSPEC)
368 		ServerInstance->Users->RemoveCloneCounts(this);
369 
370 	if (server->IsULine())
371 		stdalgo::erase(ServerInstance->Users->all_ulines, this);
372 
373 	return Extensible::cull();
374 }
375 
cull()376 CullResult LocalUser::cull()
377 {
378 	eh.cull();
379 	return User::cull();
380 }
381 
cull()382 CullResult FakeUser::cull()
383 {
384 	// Fake users don't quit, they just get culled.
385 	quitting = true;
386 	// Fake users are not inserted into UserManager::clientlist or uuidlist, so we don't need to modify those here
387 	return User::cull();
388 }
389 
Oper(OperInfo * info)390 void User::Oper(OperInfo* info)
391 {
392 	ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
393 	if (opermh)
394 	{
395 		if (this->IsModeSet(opermh))
396 			this->UnOper();
397 		this->SetMode(opermh, true);
398 	}
399 	this->oper = info;
400 
401 	LocalUser* localuser = IS_LOCAL(this);
402 	if (localuser)
403 	{
404 		Modes::ChangeList changelist;
405 		changelist.push_add(opermh);
406 		ClientProtocol::Events::Mode modemsg(ServerInstance->FakeClient, NULL, localuser, changelist);
407 		localuser->Send(modemsg);
408 	}
409 
410 	FOREACH_MOD(OnOper, (this, info->name));
411 
412 	std::string opername;
413 	if (info->oper_block)
414 		opername = info->oper_block->getString("name");
415 
416 	ServerInstance->SNO->WriteToSnoMask('o', "%s (%s@%s) is now a server operator of type %s (using oper '%s')",
417 		nick.c_str(), ident.c_str(), GetRealHost().c_str(), oper->name.c_str(), opername.c_str());
418 	this->WriteNumeric(RPL_YOUAREOPER, InspIRCd::Format("You are now %s %s", strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->name.c_str()));
419 
420 	ServerInstance->Users->all_opers.push_back(this);
421 
422 	// Expand permissions from config for faster lookup
423 	if (localuser)
424 		oper->init();
425 
426 	FOREACH_MOD(OnPostOper, (this, oper->name, opername));
427 }
428 
429 namespace
430 {
ParseModeList(std::bitset<64> & modeset,ConfigTag * tag,const std::string & field)431 	bool ParseModeList(std::bitset<64>& modeset, ConfigTag* tag, const std::string& field)
432 	{
433 		std::string modes;
434 		bool hasmodes = tag->readString(field, modes);
435 		for (std::string::const_iterator iter = modes.begin(); iter != modes.end(); ++iter)
436 		{
437 			const char& chr = *iter;
438 			if (chr == '*')
439 				modeset.set();
440 			else if (ModeParser::IsModeChar(chr))
441 				modeset.set(chr - 'A');
442 			else
443 				ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "'%c' is not a valid value for <class:%s>, ignoring...", chr, field.c_str());
444 		}
445 		return hasmodes;
446 	}
447 }
448 
init()449 void OperInfo::init()
450 {
451 	AllowedOperCommands.Clear();
452 	AllowedPrivs.Clear();
453 	AllowedUserModes.reset();
454 	AllowedChanModes.reset();
455 	AllowedSnomasks.reset();
456 	AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
457 
458 	bool defaultsnomasks = true;
459 	for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
460 	{
461 		ConfigTag* tag = *iter;
462 
463 		AllowedOperCommands.AddList(tag->getString("commands"));
464 		AllowedPrivs.AddList(tag->getString("privs"));
465 
466 		ParseModeList(AllowedChanModes, tag, "chanmodes");
467 		ParseModeList(AllowedUserModes, tag, "usermodes");
468 		if (ParseModeList(AllowedSnomasks, tag, "snomasks"))
469 			defaultsnomasks = false;
470 	}
471 
472 	// Compatibility for older configs that don't have the snomasks field.
473 	if (defaultsnomasks)
474 		AllowedSnomasks.set();
475 }
476 
UnOper()477 void User::UnOper()
478 {
479 	if (!this->IsOper())
480 		return;
481 
482 	/*
483 	 * unset their oper type (what IS_OPER checks).
484 	 * note, order is important - this must come before modes as -o attempts
485 	 * to call UnOper. -- w00t
486 	 */
487 	oper = NULL;
488 
489 	// Remove the user from the oper list
490 	stdalgo::vector::swaperase(ServerInstance->Users->all_opers, this);
491 
492 	// If the user is quitting we shouldn't remove any modes as it results in
493 	// mode messages being broadcast across the network.
494 	if (quitting)
495 		return;
496 
497 	/* Remove all oper only modes from the user when the deoper - Bug #466*/
498 	Modes::ChangeList changelist;
499 	const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
500 	for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); ++i)
501 	{
502 		ModeHandler* mh = i->second;
503 		if (mh->NeedsOper())
504 			changelist.push_remove(mh);
505 	}
506 
507 	ServerInstance->Modes->Process(this, NULL, this, changelist);
508 
509 	ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
510 	if (opermh)
511 		this->SetMode(opermh, false);
512 	FOREACH_MOD(OnPostDeoper, (this));
513 }
514 
515 /*
516  * Check class restrictions
517  */
CheckClass(bool clone_count)518 void LocalUser::CheckClass(bool clone_count)
519 {
520 	ConnectClass* a = this->MyClass;
521 
522 	if (!a)
523 	{
524 		ServerInstance->Users->QuitUser(this, "Access denied by configuration");
525 		return;
526 	}
527 	else if (a->type == CC_DENY)
528 	{
529 		ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection", 1));
530 		return;
531 	}
532 	else if (clone_count)
533 	{
534 		const UserManager::CloneCounts& clonecounts = ServerInstance->Users->GetCloneCounts(this);
535 		if ((a->GetMaxLocal()) && (clonecounts.local > a->GetMaxLocal()))
536 		{
537 			ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
538 			if (a->maxconnwarn)
539 			{
540 				ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum local connections for the %s class (%ld) exceeded by %s",
541 					a->name.c_str(), a->GetMaxLocal(), this->GetIPString().c_str());
542 			}
543 			return;
544 		}
545 		else if ((a->GetMaxGlobal()) && (clonecounts.global > a->GetMaxGlobal()))
546 		{
547 			ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
548 			if (a->maxconnwarn)
549 			{
550 				ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum global connections for the %s class (%ld) exceeded by %s",
551 				a->name.c_str(), a->GetMaxGlobal(), this->GetIPString().c_str());
552 			}
553 			return;
554 		}
555 	}
556 
557 	this->nextping = ServerInstance->Time() + a->GetPingTime();
558 }
559 
CheckLines(bool doZline)560 bool LocalUser::CheckLines(bool doZline)
561 {
562 	const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
563 
564 	if (!this->exempt)
565 	{
566 		for (int n = 0; check[n]; ++n)
567 		{
568 			XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
569 
570 			if (r)
571 			{
572 				r->Apply(this);
573 				return true;
574 			}
575 		}
576 	}
577 
578 	return false;
579 }
580 
FullConnect()581 void LocalUser::FullConnect()
582 {
583 	ServerInstance->stats.Connects++;
584 	this->idle_lastmsg = ServerInstance->Time();
585 
586 	/*
587 	 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
588 	 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
589 	 * may put the user into a totally separate class with different restrictions! so we *must* check again.
590 	 * Don't remove this! -- w00t
591 	 */
592 	MyClass = NULL;
593 	SetClass();
594 	CheckClass();
595 	CheckLines();
596 
597 	if (quitting)
598 		return;
599 
600 	/*
601 	 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
602 	 * for a user that doesn't exist yet.
603 	 */
604 	FOREACH_MOD(OnUserConnect, (this));
605 
606 	/* Now registered */
607 	if (ServerInstance->Users->unregistered_count)
608 		ServerInstance->Users->unregistered_count--;
609 	this->registered = REG_ALL;
610 
611 	FOREACH_MOD(OnPostConnect, (this));
612 
613 	ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s (%s) [%s]",
614 		this->server_sa.port(), this->MyClass->name.c_str(), GetFullRealHost().c_str(), this->GetIPString().c_str(), this->GetRealName().c_str());
615 	ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding NEGATIVE hit for " + this->GetIPString());
616 	ServerInstance->BanCache.AddHit(this->GetIPString(), "", "");
617 	// reset the flood penalty (which could have been raised due to things like auto +x)
618 	CommandFloodPenalty = 0;
619 }
620 
InvalidateCache()621 void User::InvalidateCache()
622 {
623 	/* Invalidate cache */
624 	cachedip.clear();
625 	cached_fullhost.clear();
626 	cached_hostip.clear();
627 	cached_makehost.clear();
628 	cached_fullrealhost.clear();
629 }
630 
ChangeNick(const std::string & newnick,time_t newts)631 bool User::ChangeNick(const std::string& newnick, time_t newts)
632 {
633 	if (quitting)
634 	{
635 		ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Attempted to change nick of a quitting user: " + this->nick);
636 		return false;
637 	}
638 
639 	User* const InUse = ServerInstance->FindNickOnly(newnick);
640 	if (InUse == this)
641 	{
642 		// case change, don't need to check campers
643 		// and, if it's identical including case, we can leave right now
644 		// We also don't update the nick TS if it's a case change, either
645 		if (newnick == nick)
646 			return true;
647 	}
648 	else
649 	{
650 		/*
651 		 * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
652 		 * then we have a potential collide. Check whether someone else is camping on the nick
653 		 * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
654 		 * camper to their UID, and allow the incoming nick change.
655 		 *
656 		 * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
657 		 * because the nick is already (rightfully) in use. -- w00t
658 		 */
659 		if (InUse)
660 		{
661 			if (InUse->registered != REG_ALL)
662 			{
663 				/* force the camper to their UUID, and ask them to re-send a NICK. */
664 				LocalUser* const localuser = static_cast<LocalUser*>(InUse);
665 				localuser->OverruleNick();
666 			}
667 			else
668 			{
669 				/* No camping, tell the incoming user  to stop trying to change nick ;p */
670 				this->WriteNumeric(ERR_NICKNAMEINUSE, newnick, "Nickname is already in use.");
671 				return false;
672 			}
673 		}
674 
675 		age = newts ? newts : ServerInstance->Time();
676 	}
677 
678 	if (this->registered == REG_ALL)
679 	{
680 		ClientProtocol::Messages::Nick nickmsg(this, newnick);
681 		ClientProtocol::Event nickevent(ServerInstance->GetRFCEvents().nick, nickmsg);
682 		this->WriteCommonRaw(nickevent, true);
683 	}
684 	const std::string oldnick = nick;
685 	nick = newnick;
686 
687 	InvalidateCache();
688 	ServerInstance->Users->clientlist.erase(oldnick);
689 	ServerInstance->Users->clientlist[newnick] = this;
690 
691 	if (registered == REG_ALL)
692 		FOREACH_MOD(OnUserPostNick, (this,oldnick));
693 
694 	return true;
695 }
696 
OverruleNick()697 void LocalUser::OverruleNick()
698 {
699 	{
700 		ClientProtocol::Messages::Nick nickmsg(this, this->uuid);
701 		this->Send(ServerInstance->GetRFCEvents().nick, nickmsg);
702 	}
703 	this->WriteNumeric(ERR_NICKNAMEINUSE, this->nick, "Nickname overruled.");
704 
705 	// Clear the bit before calling ChangeNick() to make it NOT run the OnUserPostNick() hook
706 	this->registered &= ~REG_NICK;
707 	this->ChangeNick(this->uuid);
708 }
709 
GetIPString()710 const std::string& User::GetIPString()
711 {
712 	if (cachedip.empty())
713 	{
714 		cachedip = client_sa.addr();
715 		/* IP addresses starting with a : on irc are a Bad Thing (tm) */
716 		if (cachedip[0] == ':')
717 			cachedip.insert(cachedip.begin(),1,'0');
718 	}
719 
720 	return cachedip;
721 }
722 
GetHost(bool uncloak) const723 const std::string& User::GetHost(bool uncloak) const
724 {
725 	return uncloak ? GetRealHost() : GetDisplayedHost();
726 }
727 
GetDisplayedHost() const728 const std::string& User::GetDisplayedHost() const
729 {
730 	return displayhost.empty() ? realhost : displayhost;
731 }
732 
GetRealHost() const733 const std::string& User::GetRealHost() const
734 {
735 	return realhost;
736 }
737 
GetRealName() const738 const std::string& User::GetRealName() const
739 {
740 	return realname;
741 }
742 
GetCIDRMask()743 irc::sockets::cidr_mask User::GetCIDRMask()
744 {
745 	unsigned char range = 0;
746 	switch (client_sa.family())
747 	{
748 		case AF_INET6:
749 			range = ServerInstance->Config->c_ipv6_range;
750 			break;
751 		case AF_INET:
752 			range = ServerInstance->Config->c_ipv4_range;
753 			break;
754 	}
755 	return irc::sockets::cidr_mask(client_sa, range);
756 }
757 
SetClientIP(const std::string & address)758 bool User::SetClientIP(const std::string& address)
759 {
760 	irc::sockets::sockaddrs sa;
761 	if (!irc::sockets::aptosa(address, client_sa.port(), sa))
762 		return false;
763 
764 	User::SetClientIP(sa);
765 	return true;
766 }
767 
SetClientIP(const irc::sockets::sockaddrs & sa)768 void User::SetClientIP(const irc::sockets::sockaddrs& sa)
769 {
770 	const std::string oldip(GetIPString());
771 	memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
772 	this->InvalidateCache();
773 
774 	// If the users hostname was their IP then update it.
775 	if (GetRealHost() == oldip)
776 		ChangeRealHost(GetIPString(), false);
777 	if (GetDisplayedHost() == oldip)
778 		ChangeDisplayedHost(GetIPString());
779 }
780 
SetClientIP(const std::string & address)781 bool LocalUser::SetClientIP(const std::string& address)
782 {
783 	irc::sockets::sockaddrs sa;
784 	if (!irc::sockets::aptosa(address, client_sa.port(), sa))
785 		return false;
786 
787 	LocalUser::SetClientIP(sa);
788 	return true;
789 }
790 
SetClientIP(const irc::sockets::sockaddrs & sa)791 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa)
792 {
793 	if (sa == client_sa)
794 		return;
795 
796 	ServerInstance->Users->RemoveCloneCounts(this);
797 	User::SetClientIP(sa);
798 	ServerInstance->Users->AddClone(this);
799 
800 	// Recheck the connect class.
801 	this->MyClass = NULL;
802 	this->SetClass();
803 	this->CheckClass();
804 
805 	if (!quitting)
806 		FOREACH_MOD(OnSetUserIP, (this));
807 }
808 
Write(const ClientProtocol::SerializedMessage & text)809 void LocalUser::Write(const ClientProtocol::SerializedMessage& text)
810 {
811 	if (!SocketEngine::BoundsCheckFd(&eh))
812 		return;
813 
814 	if (ServerInstance->Config->RawLog)
815 	{
816 		if (text.empty())
817 			return;
818 
819 		std::string::size_type nlpos = text.find_first_of("\r\n", 0, 2);
820 		if (nlpos == std::string::npos)
821 			nlpos = text.length(); // TODO is this ok, test it
822 
823 		ServerInstance->Logs->Log("USEROUTPUT", LOG_RAWIO, "C[%s] O %.*s", uuid.c_str(), (int) nlpos, text.c_str());
824 	}
825 
826 	eh.AddWriteBuf(text);
827 
828 	const size_t bytessent = text.length() + 2;
829 	ServerInstance->stats.Sent += bytessent;
830 	this->bytes_out += bytessent;
831 	this->cmds_out++;
832 }
833 
Send(ClientProtocol::Event & protoev)834 void LocalUser::Send(ClientProtocol::Event& protoev)
835 {
836 	if (!serializer)
837 	{
838 		ServerInstance->Logs->Log("USERS", LOG_DEBUG, "BUG: LocalUser::Send() called on %s who does not have a serializer!",
839 			GetFullRealHost().c_str());
840 		return;
841 	}
842 
843 	// In the most common case a static LocalUser field, sendmsglist, is passed to the event to be
844 	// populated. The list is cleared before returning.
845 	// To handle re-enters, if sendmsglist is non-empty upon entering the method then a temporary
846 	// list is used instead of the static one.
847 	if (sendmsglist.empty())
848 	{
849 		Send(protoev, sendmsglist);
850 		sendmsglist.clear();
851 	}
852 	else
853 	{
854 		ClientProtocol::MessageList msglist;
855 		Send(protoev, msglist);
856 	}
857 }
858 
Send(ClientProtocol::Event & protoev,ClientProtocol::MessageList & msglist)859 void LocalUser::Send(ClientProtocol::Event& protoev, ClientProtocol::MessageList& msglist)
860 {
861 	// Modules can personalize the messages sent per user for the event
862 	protoev.GetMessagesForUser(this, msglist);
863 	for (ClientProtocol::MessageList::const_iterator i = msglist.begin(); i != msglist.end(); ++i)
864 	{
865 		ClientProtocol::Message& curr = **i;
866 		ModResult res;
867 		FIRST_MOD_RESULT(OnUserWrite, res, (this, curr));
868 		if (res != MOD_RES_DENY)
869 			Write(serializer->SerializeForUser(this, curr));
870 	}
871 }
872 
WriteNumeric(const Numeric::Numeric & numeric)873 void User::WriteNumeric(const Numeric::Numeric& numeric)
874 {
875 	LocalUser* const localuser = IS_LOCAL(this);
876 	if (!localuser)
877 		return;
878 
879 	ModResult MOD_RESULT;
880 
881 	FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric));
882 
883 	if (MOD_RESULT == MOD_RES_DENY)
884 		return;
885 
886 	ClientProtocol::Messages::Numeric numericmsg(numeric, localuser);
887 	localuser->Send(ServerInstance->GetRFCEvents().numeric, numericmsg);
888 }
889 
WriteRemoteNotice(const std::string & text)890 void User::WriteRemoteNotice(const std::string& text)
891 {
892 	ServerInstance->PI->SendMessage(this, text, MSG_NOTICE);
893 }
894 
WriteRemoteNotice(const std::string & text)895 void LocalUser::WriteRemoteNotice(const std::string& text)
896 {
897 	WriteNotice(text);
898 }
899 
900 namespace
901 {
902 	class WriteCommonRawHandler : public User::ForEachNeighborHandler
903 	{
904 		ClientProtocol::Event& ev;
905 
Execute(LocalUser * user)906 		void Execute(LocalUser* user) CXX11_OVERRIDE
907 		{
908 			user->Send(ev);
909 		}
910 
911 	 public:
WriteCommonRawHandler(ClientProtocol::Event & protoev)912 		WriteCommonRawHandler(ClientProtocol::Event& protoev)
913 			: ev(protoev)
914 		{
915 		}
916 	};
917 }
918 
WriteCommonRaw(ClientProtocol::Event & protoev,bool include_self)919 void User::WriteCommonRaw(ClientProtocol::Event& protoev, bool include_self)
920 {
921 	WriteCommonRawHandler handler(protoev);
922 	ForEachNeighbor(handler, include_self);
923 }
924 
ForEachNeighbor(ForEachNeighborHandler & handler,bool include_self)925 already_sent_t User::ForEachNeighbor(ForEachNeighborHandler& handler, bool include_self)
926 {
927 	// The basic logic for visiting the neighbors of a user is to iterate the channel list of the user
928 	// and visit all users on those channels. Because two users may share more than one common channel,
929 	// we must skip users that we have already visited.
930 	// To do this, we make use of a global counter and an integral 'already_sent' field in LocalUser.
931 	// The global counter is incremented every time we do something for each neighbor of a user. Then,
932 	// before visiting a member we examine user->already_sent. If it's equal to the current counter, we
933 	// skip the member. Otherwise, we set it to the current counter and visit the member.
934 
935 	// Ask modules to build a list of exceptions.
936 	// Mods may also exclude entire channels by erasing them from include_chans.
937 	IncludeChanList include_chans(chans.begin(), chans.end());
938 	std::map<User*, bool> exceptions;
939 	exceptions[this] = include_self;
940 	FOREACH_MOD(OnBuildNeighborList, (this, include_chans, exceptions));
941 
942 	// Get next id, guaranteed to differ from the already_sent field of all users
943 	const already_sent_t newid = ServerInstance->Users.NextAlreadySentId();
944 
945 	// Handle exceptions first
946 	for (std::map<User*, bool>::const_iterator i = exceptions.begin(); i != exceptions.end(); ++i)
947 	{
948 		LocalUser* curr = IS_LOCAL(i->first);
949 		if (curr)
950 		{
951 			// Mark as visited to ensure we won't visit again if there is a common channel
952 			curr->already_sent = newid;
953 			// Always treat quitting users as excluded
954 			if ((i->second) && (!curr->quitting))
955 				handler.Execute(curr);
956 		}
957 	}
958 
959 	// Now consider the real neighbors
960 	for (IncludeChanList::const_iterator i = include_chans.begin(); i != include_chans.end(); ++i)
961 	{
962 		Channel* chan = (*i)->chan;
963 		const Channel::MemberMap& userlist = chan->GetUsers();
964 		for (Channel::MemberMap::const_iterator j = userlist.begin(); j != userlist.end(); ++j)
965 		{
966 			LocalUser* curr = IS_LOCAL(j->first);
967 			// User not yet visited?
968 			if ((curr) && (curr->already_sent != newid))
969 			{
970 				// Mark as visited and execute function
971 				curr->already_sent = newid;
972 				handler.Execute(curr);
973 			}
974 		}
975 	}
976 
977 	return newid;
978 }
979 
WriteRemoteNumeric(const Numeric::Numeric & numeric)980 void User::WriteRemoteNumeric(const Numeric::Numeric& numeric)
981 {
982 	WriteNumeric(numeric);
983 }
984 
985 /* return 0 or 1 depending if users u and u2 share one or more common channels
986  * (used by QUIT, NICK etc which arent channel specific notices)
987  *
988  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
989  * the first users channels then the second users channels within the outer loop,
990  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
991  * all possible iterations). However this new function instead checks against the
992  * channel's userlist in the inner loop which is a std::map<User*,User*>
993  * and saves us time as we already know what pointer value we are after.
994  * Don't quote me on the maths as i am not a mathematician or computer scientist,
995  * but i believe this algorithm is now x+(log y) maximum iterations instead.
996  */
SharesChannelWith(User * other)997 bool User::SharesChannelWith(User *other)
998 {
999 	/* Outer loop */
1000 	for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); ++i)
1001 	{
1002 		/* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1003 		 * by replacing it with a map::find which *should* be more efficient
1004 		 */
1005 		if ((*i)->chan->HasUser(other))
1006 			return true;
1007 	}
1008 	return false;
1009 }
1010 
ChangeRealName(const std::string & real)1011 bool User::ChangeRealName(const std::string& real)
1012 {
1013 	if (!this->realname.compare(real))
1014 		return true;
1015 
1016 	if (IS_LOCAL(this))
1017 	{
1018 		ModResult MOD_RESULT;
1019 		FIRST_MOD_RESULT(OnPreChangeRealName, MOD_RESULT, (IS_LOCAL(this), real));
1020 		if (MOD_RESULT == MOD_RES_DENY)
1021 			return false;
1022 	}
1023 	FOREACH_MOD(OnChangeRealName, (this, real));
1024 	this->realname.assign(real, 0, ServerInstance->Config->Limits.MaxReal);
1025 
1026 	return true;
1027 }
1028 
ChangeDisplayedHost(const std::string & shost)1029 bool User::ChangeDisplayedHost(const std::string& shost)
1030 {
1031 	if (GetDisplayedHost() == shost)
1032 		return true;
1033 
1034 	LocalUser* luser = IS_LOCAL(this);
1035 	if (luser)
1036 	{
1037 		ModResult MOD_RESULT;
1038 		FIRST_MOD_RESULT(OnPreChangeHost, MOD_RESULT, (luser, shost));
1039 		if (MOD_RESULT == MOD_RES_DENY)
1040 			return false;
1041 	}
1042 
1043 	FOREACH_MOD(OnChangeHost, (this,shost));
1044 
1045 	if (realhost == shost)
1046 		this->displayhost.clear();
1047 	else
1048 		this->displayhost.assign(shost, 0, ServerInstance->Config->Limits.MaxHost);
1049 
1050 	this->InvalidateCache();
1051 
1052 	if (IS_LOCAL(this) && this->registered != REG_NONE)
1053 		this->WriteNumeric(RPL_YOURDISPLAYEDHOST, this->GetDisplayedHost(), "is now your displayed host");
1054 
1055 	return true;
1056 }
1057 
ChangeRealHost(const std::string & host,bool resetdisplay)1058 void User::ChangeRealHost(const std::string& host, bool resetdisplay)
1059 {
1060 	// If the real host is the new host and we are not resetting the
1061 	// display host then we have nothing to do.
1062 	const bool changehost = (realhost != host);
1063 	if (!changehost && !resetdisplay)
1064 		return;
1065 
1066 	// If the displayhost is not set and we are not resetting it then
1067 	// we need to copy it to the displayhost field.
1068 	if (displayhost.empty() && !resetdisplay)
1069 		displayhost = realhost;
1070 
1071 	// If the displayhost is the new host or we are resetting it then
1072 	// we clear its contents to save memory.
1073 	else if (displayhost == host || resetdisplay)
1074 		displayhost.clear();
1075 
1076 	// If we are just resetting the display host then we don't need to
1077 	// do anything else.
1078 	if (!changehost)
1079 		return;
1080 
1081 	// Don't call the OnChangeRealHost event when initialising a user.
1082 	const bool initializing = realhost.empty();
1083 	if (!initializing)
1084 		FOREACH_MOD(OnChangeRealHost, (this, host));
1085 
1086 	realhost = host;
1087 	this->InvalidateCache();
1088 
1089 	// Don't call the OnPostChangeRealHost event when initialising a user.
1090 	if (!this->quitting && !initializing)
1091 		FOREACH_MOD(OnPostChangeRealHost, (this));
1092 }
1093 
ChangeIdent(const std::string & newident)1094 bool User::ChangeIdent(const std::string& newident)
1095 {
1096 	if (this->ident == newident)
1097 		return true;
1098 
1099 	FOREACH_MOD(OnChangeIdent, (this,newident));
1100 
1101 	this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax);
1102 	this->InvalidateCache();
1103 
1104 	return true;
1105 }
1106 
1107 /*
1108  * Sets a user's connection class.
1109  * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1110  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1111  * then their ip will be taken as 'priority' anyway, so for example,
1112  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1113  */
SetClass(const std::string & explicit_name)1114 void LocalUser::SetClass(const std::string &explicit_name)
1115 {
1116 	ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Setting connect class for %s (%s) ...",
1117 		this->uuid.c_str(), this->GetFullRealHost().c_str());
1118 
1119 	ConnectClass *found = NULL;
1120 	if (!explicit_name.empty())
1121 	{
1122 		for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1123 		{
1124 			ConnectClass* c = *i;
1125 
1126 			if (explicit_name == c->name)
1127 			{
1128 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Connect class explicitly set to %s",
1129 					explicit_name.c_str());
1130 				found = c;
1131 			}
1132 		}
1133 	}
1134 	else
1135 	{
1136 		for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1137 		{
1138 			ConnectClass* c = *i;
1139 			ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Checking the %s connect class ...",
1140 					c->GetName().c_str());
1141 
1142 			ModResult MOD_RESULT;
1143 			FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1144 			if (MOD_RESULT == MOD_RES_DENY)
1145 				continue;
1146 
1147 			if (MOD_RESULT == MOD_RES_ALLOW)
1148 			{
1149 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class was explicitly chosen by a module",
1150 					c->GetName().c_str());
1151 				found = c;
1152 				break;
1153 			}
1154 
1155 			if (c->type == CC_NAMED)
1156 			{
1157 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as neither <connect:allow> nor <connect:deny> are set",
1158 						c->GetName().c_str());
1159 				continue;
1160 			}
1161 
1162 			bool regdone = (registered != REG_NONE);
1163 			if (c->config->getBool("registered", regdone) != regdone)
1164 			{
1165 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it requires that the user is %s",
1166 						c->GetName().c_str(), regdone ? "not fully connected" : "fully connected");
1167 				continue;
1168 			}
1169 
1170 			bool hostmatches = false;
1171 			for (std::vector<std::string>::const_iterator host = c->GetHosts().begin(); host != c->GetHosts().end(); ++host)
1172 			{
1173 				if (InspIRCd::MatchCIDR(this->GetIPString(), *host) || InspIRCd::MatchCIDR(this->GetRealHost(), *host))
1174 				{
1175 					hostmatches = true;
1176 					break;
1177 				}
1178 			}
1179 			if (!hostmatches)
1180 			{
1181 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as neither the host (%s) nor the IP (%s) matches %s",
1182 					c->GetName().c_str(), this->GetRealHost().c_str(), this->GetIPString().c_str(), c->GetHost().c_str());
1183 				continue;
1184 			}
1185 
1186 			/*
1187 			 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1188 			 * because we should attempt to find another class if this one doesn't match us. -- w00t
1189 			 */
1190 			if (c->limit && (c->GetReferenceCount() >= c->limit))
1191 			{
1192 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it has reached its user limit (%lu)",
1193 						c->GetName().c_str(), c->limit);
1194 				continue;
1195 			}
1196 
1197 			/* if it requires a port and our port doesn't match, fail */
1198 			if (!c->ports.empty() && !c->ports.count(this->server_sa.port()))
1199 			{
1200 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as the connection port (%d) is not any of %s",
1201 					c->GetName().c_str(), this->server_sa.port(), stdalgo::string::join(c->ports).c_str());
1202 				continue;
1203 			}
1204 
1205 			if (regdone && !c->password.empty() && !ServerInstance->PassCompare(this, c->password, password, c->passwordhash))
1206 			{
1207 				ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as requires a password and %s",
1208 					c->GetName().c_str(), password.empty() ? "one was not provided" : "the provided password was incorrect");
1209 				continue;
1210 			}
1211 
1212 			/* we stop at the first class that meets ALL criteria. */
1213 			ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is suitable for %s (%s)",
1214 				c->GetName().c_str(), this->uuid.c_str(), this->GetFullRealHost().c_str());
1215 			found = c;
1216 			break;
1217 		}
1218 	}
1219 
1220 	/*
1221 	 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1222 	 */
1223 	if (found)
1224 	{
1225 		MyClass = found;
1226 	}
1227 }
1228 
PurgeEmptyChannels()1229 void User::PurgeEmptyChannels()
1230 {
1231 	// firstly decrement the count on each channel
1232 	for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); )
1233 	{
1234 		Channel* c = (*i)->chan;
1235 		++i;
1236 		c->DelUser(this);
1237 	}
1238 }
1239 
WriteNotice(const std::string & text)1240 void User::WriteNotice(const std::string& text)
1241 {
1242 	LocalUser* const localuser = IS_LOCAL(this);
1243 	if (!localuser)
1244 		return;
1245 
1246 	ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, localuser, text, MSG_NOTICE);
1247 	localuser->Send(ServerInstance->GetRFCEvents().privmsg, msg);
1248 }
1249 
GetFullHost()1250 const std::string& FakeUser::GetFullHost()
1251 {
1252 	if (!ServerInstance->Config->HideServer.empty())
1253 		return ServerInstance->Config->HideServer;
1254 	return server->GetName();
1255 }
1256 
GetFullRealHost()1257 const std::string& FakeUser::GetFullRealHost()
1258 {
1259 	return GetFullHost();
1260 }
1261 
ConnectClass(ConfigTag * tag,char t,const std::string & mask)1262 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1263 	: config(tag)
1264 	, type(t)
1265 	, fakelag(true)
1266 	, name("unnamed")
1267 	, registration_timeout(0)
1268 	, host(mask)
1269 	, pingtime(0)
1270 	, softsendqmax(0)
1271 	, hardsendqmax(0)
1272 	, recvqmax(0)
1273 	, penaltythreshold(0)
1274 	, commandrate(0)
1275 	, maxlocal(0)
1276 	, maxglobal(0)
1277 	, maxconnwarn(true)
1278 	, maxchans(0)
1279 	, limit(0)
1280 	, resolvehostnames(true)
1281 {
1282 	irc::spacesepstream hoststream(host);
1283 	for (std::string hostentry; hoststream.GetToken(hostentry); )
1284 		hosts.push_back(hostentry);
1285 }
1286 
ConnectClass(ConfigTag * tag,char t,const std::string & mask,const ConnectClass & parent)1287 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1288 {
1289 	Update(&parent);
1290 	name = "unnamed";
1291 	type = t;
1292 	host = mask;
1293 	hosts.clear();
1294 	irc::spacesepstream hoststream(host);
1295 	for (std::string hostentry; hoststream.GetToken(hostentry); )
1296 		hosts.push_back(hostentry);
1297 
1298 	// Connect classes can inherit from each other but this is problematic for modules which can't use
1299 	// ConnectClass::Update so we build a hybrid tag containing all of the values set on this class as
1300 	// well as the parent class.
1301 	ConfigItems* items = NULL;
1302 	config = ConfigTag::create(tag->tag, tag->src_name, tag->src_line, items);
1303 
1304 	const ConfigItems& parentkeys = parent.config->getItems();
1305 	for (ConfigItems::const_iterator piter = parentkeys.begin(); piter != parentkeys.end(); ++piter)
1306 	{
1307 		// The class name and parent name are not inherited
1308 		if (stdalgo::string::equalsci(piter->first, "name") || stdalgo::string::equalsci(piter->first, "parent"))
1309 			continue;
1310 
1311 		// Store the item in the config tag. If this item also
1312 		// exists in the child it will be overwritten.
1313 		(*items)[piter->first] = piter->second;
1314 	}
1315 
1316 	const ConfigItems& childkeys = tag->getItems();
1317 	for (ConfigItems::const_iterator citer = childkeys.begin(); citer != childkeys.end(); ++citer)
1318 	{
1319 		// This will overwrite the parent value if present.
1320 		(*items)[citer->first] = citer->second;
1321 	}
1322 }
1323 
Update(const ConnectClass * src)1324 void ConnectClass::Update(const ConnectClass* src)
1325 {
1326 	config = src->config;
1327 	type = src->type;
1328 	fakelag = src->fakelag;
1329 	name = src->name;
1330 	registration_timeout = src->registration_timeout;
1331 	host = src->host;
1332 	hosts = src->hosts;
1333 	pingtime = src->pingtime;
1334 	softsendqmax = src->softsendqmax;
1335 	hardsendqmax = src->hardsendqmax;
1336 	recvqmax = src->recvqmax;
1337 	penaltythreshold = src->penaltythreshold;
1338 	commandrate = src->commandrate;
1339 	maxlocal = src->maxlocal;
1340 	maxglobal = src->maxglobal;
1341 	maxconnwarn = src->maxconnwarn;
1342 	maxchans = src->maxchans;
1343 	limit = src->limit;
1344 	resolvehostnames = src->resolvehostnames;
1345 	ports = src->ports;
1346 	password = src->password;
1347 	passwordhash = src->passwordhash;
1348 }
1349