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