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