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