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