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