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