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