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