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