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