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