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