2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
28 #include "socketengine.h"
31 #include "commands/cmd_whowas.h"
33 already_sent_t LocalUser::already_sent_id = 0;
35 std::string User::ProcessNoticeMasks(const char *sm)
37 bool adding = true, oldadding = false;
52 for (unsigned char d = 'a'; d <= 'z'; d++)
54 if (!ServerInstance->SNO->masks[d - 'a'].Description.empty())
56 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
58 if ((oldadding != adding) || (!output.length()))
59 output += (adding ? '+' : '-');
61 this->SetNoticeMask(d, adding);
67 if ((!IsNoticeMaskSet(u) && adding) || (IsNoticeMaskSet(u) && !adding))
69 if ((oldadding != adding) || (!output.length()))
70 output += (adding ? '+' : '-');
72 this->SetNoticeMask(u, adding);
83 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
85 if ((oldadding != adding) || (!output.length()))
86 output += (adding ? '+' : '-');
88 this->SetNoticeMask(*c, adding);
94 this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
103 std::string s = this->FormatNoticeMasks();
106 this->modes[UM_SNOMASK] = false;
112 void LocalUser::StartDNSLookup()
117 const char* sip = this->GetIPString();
118 UserResolver *res_reverse;
120 QueryType resolvtype = this->client_sa.sa.sa_family == AF_INET6 ? DNS_QUERY_PTR6 : DNS_QUERY_PTR4;
121 res_reverse = new UserResolver(this, sip, resolvtype, cached);
123 ServerInstance->AddResolver(res_reverse, cached);
125 catch (CoreException& e)
127 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
129 ServerInstance->stats->statsDnsBad++;
133 bool User::IsNoticeMaskSet(unsigned char sm)
137 return (snomasks[sm-65]);
140 void User::SetNoticeMask(unsigned char sm, bool value)
144 snomasks[sm-65] = value;
147 const char* User::FormatNoticeMasks()
149 static char data[MAXBUF];
152 for (int n = 0; n < 64; n++)
155 data[offset++] = n+65;
162 bool User::IsModeSet(unsigned char m)
166 return (modes[m-65]);
169 void User::SetMode(unsigned char m, bool value)
176 const char* User::FormatModes(bool showparameters)
178 static char data[MAXBUF];
182 for (unsigned char n = 0; n < 64; n++)
186 data[offset++] = n + 65;
187 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
188 if (showparameters && mh && mh->GetNumParams(true))
190 std::string p = mh->GetUserParameter(this);
192 params.append(" ").append(p);
197 strlcat(data, params.c_str(), MAXBUF);
201 User::User(const std::string &uid, const std::string& sid, int type)
202 : uuid(uid), server(sid), usertype(type)
204 age = ServerInstance->Time();
205 signon = idle_lastmsg = 0;
207 quietquit = quitting = exempt = dns_done = false;
208 quitting_sendq = false;
209 client_sa.sa.sa_family = AF_UNSPEC;
211 ServerInstance->Logs->Log("USERS", DEBUG, "New UUID for user: %s", uuid.c_str());
213 user_hash::iterator finduuid = ServerInstance->Users->uuidlist->find(uuid);
214 if (finduuid == ServerInstance->Users->uuidlist->end())
215 (*ServerInstance->Users->uuidlist)[uuid] = this;
217 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
220 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
221 : User(ServerInstance->GetUID(), ServerInstance->Config->ServerName, USERTYPE_LOCAL), eh(this),
222 bytes_in(0), bytes_out(0), cmds_in(0), cmds_out(0), nping(0), CommandFloodPenalty(0),
228 memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
231 * Initialize host and dhost here to the user's IP.
232 * It is important to do this before calling SetClientIP()
233 * as that passes execution to modules that expect these
234 * fields to be valid.
236 * We cannot call GetIPString() now as that will access
237 * client_sa, and that's only initialized after the first
238 * SetClientIP() call.
242 irc::sockets::satoap(*client, host, port);
244 host.insert(0, 1, '0');
246 SetClientIP(*client);
251 if (ServerInstance->Users->uuidlist->find(uuid) != ServerInstance->Users->uuidlist->end())
252 ServerInstance->Logs->Log("USERS", DEFAULT, "User destructor for %s called without cull", uuid.c_str());
255 const std::string& User::MakeHost()
257 if (!this->cached_makehost.empty())
258 return this->cached_makehost;
261 /* This is much faster than snprintf */
263 for(const char* n = ident.c_str(); *n; n++)
266 for(const char* n = host.c_str(); *n; n++)
270 this->cached_makehost.assign(nhost);
272 return this->cached_makehost;
275 const std::string& User::MakeHostIP()
277 if (!this->cached_hostip.empty())
278 return this->cached_hostip;
281 /* This is much faster than snprintf */
283 for(const char* n = ident.c_str(); *n; n++)
286 for(const char* n = this->GetIPString(); *n; n++)
290 this->cached_hostip = ihost;
292 return this->cached_hostip;
295 const std::string& User::GetFullHost()
297 if (!this->cached_fullhost.empty())
298 return this->cached_fullhost;
302 for(const char* n = nick.c_str(); *n; n++)
305 for(const char* n = ident.c_str(); *n; n++)
308 for(const char* n = dhost.c_str(); *n; n++)
312 this->cached_fullhost = result;
314 return this->cached_fullhost;
317 char* User::MakeWildHost()
319 static char nresult[MAXBUF];
321 *t++ = '*'; *t++ = '!';
322 *t++ = '*'; *t++ = '@';
323 for(const char* n = dhost.c_str(); *n; n++)
329 const std::string& User::GetFullRealHost()
331 if (!this->cached_fullrealhost.empty())
332 return this->cached_fullrealhost;
334 char fresult[MAXBUF];
336 for(const char* n = nick.c_str(); *n; n++)
339 for(const char* n = ident.c_str(); *n; n++)
342 for(const char* n = host.c_str(); *n; n++)
346 this->cached_fullrealhost = fresult;
348 return this->cached_fullrealhost;
351 bool LocalUser::IsInvited(const irc::string &channel)
353 Channel* chan = ServerInstance->FindChan(channel.c_str());
357 return (Invitation::Find(chan, this) != NULL);
360 InviteList& LocalUser::GetInviteList()
362 RemoveExpiredInvites();
366 void LocalUser::InviteTo(const irc::string &channel, time_t invtimeout)
368 Channel* chan = ServerInstance->FindChan(channel.c_str());
370 Invitation::Create(chan, this, invtimeout);
373 void LocalUser::RemoveInvite(const irc::string &channel)
375 Channel* chan = ServerInstance->FindChan(channel.c_str());
378 Invitation* inv = Invitation::Find(chan, this);
387 void LocalUser::RemoveExpiredInvites()
389 Invitation::Find(NULL, this);
392 bool User::HasModePermission(unsigned char, ModeType)
397 bool LocalUser::HasModePermission(unsigned char mode, ModeType type)
402 if (mode < 'A' || mode > ('A' + 64)) return false;
404 return ((type == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
408 * users on remote servers can completely bypass all permissions based checks.
409 * This prevents desyncs when one server has different type/class tags to another.
410 * That having been said, this does open things up to the possibility of source changes
411 * allowing remote kills, etc - but if they have access to the src, they most likely have
412 * access to the conf - so it's an end to a means either way.
414 bool User::HasPermission(const std::string&)
419 bool LocalUser::HasPermission(const std::string &command)
421 // are they even an oper at all?
427 if (oper->AllowedOperCommands.find(command) != oper->AllowedOperCommands.end())
429 else if (oper->AllowedOperCommands.find("*") != oper->AllowedOperCommands.end())
435 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
440 bool LocalUser::HasPrivPermission(const std::string &privstr, bool noisy)
445 this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
449 if (oper->AllowedPrivs.find(privstr) != oper->AllowedPrivs.end())
453 else if (oper->AllowedPrivs.find("*") != oper->AllowedPrivs.end())
459 this->WriteServ("NOTICE %s :Oper type %s does not have access to priv %s", this->nick.c_str(), oper->NameStr(), privstr.c_str());
463 void UserIOHandler::OnDataReady()
468 if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
470 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
471 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
472 user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
474 unsigned long sendqmax = ULONG_MAX;
475 if (!user->HasPrivPermission("users/flood/increased-buffers"))
476 sendqmax = user->MyClass->GetSendqSoftMax();
477 unsigned long penaltymax = ULONG_MAX;
478 if (!user->HasPrivPermission("users/flood/no-fakelag"))
479 penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
481 while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
484 line.reserve(MAXBUF);
485 std::string::size_type qpos = 0;
486 while (qpos < recvq.length())
488 char c = recvq[qpos++];
499 if (line.length() < MAXBUF - 2)
502 // if we got here, the recvq ran out before we found a newline
505 // just found a newline. Terminate the string, and pull it out of recvq
506 recvq = recvq.substr(qpos);
508 // TODO should this be moved to when it was inserted in recvq?
509 ServerInstance->stats->statsRecv += qpos;
510 user->bytes_in += qpos;
513 ServerInstance->Parser->ProcessBuffer(line, user);
517 if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
518 ServerInstance->Users->QuitUser(user, "Excess Flood");
521 void UserIOHandler::AddWriteBuf(const std::string &data)
523 if (user->quitting_sendq)
525 if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
526 !user->HasPrivPermission("users/flood/increased-buffers"))
528 user->quitting_sendq = true;
529 ServerInstance->GlobalCulls.AddSQItem(user);
533 // We still want to append data to the sendq of a quitting user,
534 // e.g. their ERROR message that says 'closing link'
539 void UserIOHandler::OnError(BufferedSocketError)
541 ServerInstance->Users->QuitUser(user, getError());
544 CullResult User::cull()
547 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
548 PurgeEmptyChannels();
550 if (client_sa.sa.sa_family != AF_UNSPEC)
551 ServerInstance->Users->RemoveCloneCounts(this);
553 return Extensible::cull();
556 CullResult LocalUser::cull()
558 std::vector<LocalUser*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
559 if (x != ServerInstance->Users->local_users.end())
560 ServerInstance->Users->local_users.erase(x);
562 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
569 CullResult FakeUser::cull()
571 // Fake users don't quit, they just get culled.
573 ServerInstance->Users->clientlist->erase(nick);
574 ServerInstance->Users->uuidlist->erase(uuid);
578 void User::Oper(OperInfo* info)
580 if (this->IsModeSet('o'))
583 this->modes[UM_OPERATOR] = 1;
585 this->WriteServ("MODE %s :+o", this->nick.c_str());
586 FOREACH_MOD(I_OnOper, OnOper(this, info->name));
588 std::string opername;
589 if (info->oper_block)
590 opername = info->oper_block->getString("name");
594 LocalUser* l = IS_LOCAL(this);
595 std::string vhost = oper->getConfig("vhost");
597 l->ChangeDisplayedHost(vhost.c_str());
598 std::string opClass = oper->getConfig("class");
599 if (!opClass.empty())
600 l->SetClass(opClass);
603 ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s (using oper '%s')",
604 nick.c_str(), ident.c_str(), host.c_str(), oper->NameStr(), opername.c_str());
605 this->WriteNumeric(381, "%s :You are now %s %s", nick.c_str(), strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->NameStr());
607 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick.c_str(), this->ident.c_str(), this->host.c_str(), oper->NameStr());
608 ServerInstance->Users->all_opers.push_back(this);
610 // Expand permissions from config for faster lookup
614 FOREACH_MOD(I_OnPostOper,OnPostOper(this, oper->name, opername));
617 void OperInfo::init()
619 AllowedOperCommands.clear();
620 AllowedPrivs.clear();
621 AllowedUserModes.reset();
622 AllowedChanModes.reset();
623 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
625 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
627 ConfigTag* tag = *iter;
628 std::string mycmd, mypriv;
629 /* Process commands */
630 irc::spacesepstream CommandList(tag->getString("commands"));
631 while (CommandList.GetToken(mycmd))
633 AllowedOperCommands.insert(mycmd);
636 irc::spacesepstream PrivList(tag->getString("privs"));
637 while (PrivList.GetToken(mypriv))
639 AllowedPrivs.insert(mypriv);
642 std::string modes = tag->getString("usermodes");
643 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
647 this->AllowedUserModes.set();
649 else if (*c >= 'A' && *c < 'z')
651 this->AllowedUserModes[*c - 'A'] = true;
655 modes = tag->getString("chanmodes");
656 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
660 this->AllowedChanModes.set();
662 else if (*c >= 'A' && *c < 'z')
664 this->AllowedChanModes[*c - 'A'] = true;
676 * unset their oper type (what IS_OPER checks).
677 * note, order is important - this must come before modes as -o attempts
678 * to call UnOper. -- w00t
683 /* Remove all oper only modes from the user when the deoper - Bug #466*/
684 std::string moderemove("-");
686 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
688 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
689 if (mh && mh->NeedsOper())
690 moderemove += letter;
694 std::vector<std::string> parameters;
695 parameters.push_back(this->nick);
696 parameters.push_back(moderemove);
698 ServerInstance->Parser->CallHandler("MODE", parameters, this);
700 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
701 ServerInstance->Users->all_opers.remove(this);
703 this->modes[UM_OPERATOR] = 0;
706 /* adds or updates an entry in the whowas list */
707 void User::AddToWhoWas()
709 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
712 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
719 * Check class restrictions
721 void LocalUser::CheckClass()
723 ConnectClass* a = this->MyClass;
727 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
730 else if (a->type == CC_DENY)
732 ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection"));
735 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
737 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
739 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
742 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
744 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
746 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
750 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
753 bool User::CheckLines(bool doZline)
755 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
759 for (int n = 0; check[n]; ++n)
761 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
774 void LocalUser::FullConnect()
776 ServerInstance->stats->statsConnects++;
777 this->idle_lastmsg = ServerInstance->Time();
780 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
781 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
782 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
783 * Don't remove this! -- w00t
793 if (ServerInstance->Config->WelcomeNotice)
794 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
795 this->WriteNumeric(RPL_WELCOME, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick.c_str(), ServerInstance->Config->Network.c_str(), this->nick.c_str(), this->ident.c_str(), this->host.c_str());
796 this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version %s",this->nick.c_str(),ServerInstance->Config->ServerName.c_str(),BRANCH);
797 this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
799 std::string umlist = ServerInstance->Modes->UserModeList();
800 std::string cmlist = ServerInstance->Modes->ChannelModeList();
801 std::string pmlist = ServerInstance->Modes->ParaModeList();
802 this->WriteNumeric(RPL_SERVERVERSION, "%s %s %s %s %s %s", this->nick.c_str(), ServerInstance->Config->ServerName.c_str(), BRANCH, umlist.c_str(), cmlist.c_str(), pmlist.c_str());
804 ServerInstance->Config->Send005(this);
805 this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
808 if (ServerInstance->Users->unregistered_count)
809 ServerInstance->Users->unregistered_count--;
811 /* Trigger MOTD and LUSERS output, give modules a chance too */
812 ModResult MOD_RESULT;
813 std::string command("MOTD");
814 std::vector<std::string> parameters;
815 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, command));
817 ServerInstance->CallCommandHandler(command, parameters, this);
819 MOD_RESULT = MOD_RES_PASSTHRU;
821 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, command));
823 ServerInstance->CallCommandHandler(command, parameters, this);
825 if (ServerInstance->Config->RawLog)
826 WriteServ("PRIVMSG %s :*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.", nick.c_str());
829 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
830 * for a user that doesn't exist yet.
832 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
834 this->registered = REG_ALL;
836 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
838 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s!%s@%s (%s) [%s]",
839 this->GetServerPort(), this->MyClass->name.c_str(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
840 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
841 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
842 // reset the flood penalty (which could have been raised due to things like auto +x)
843 CommandFloodPenalty = 0;
846 void User::InvalidateCache()
848 /* Invalidate cache */
849 cached_fullhost.clear();
850 cached_hostip.clear();
851 cached_makehost.clear();
852 cached_fullrealhost.clear();
855 bool User::ChangeNick(const std::string& newnick, bool force)
857 ModResult MOD_RESULT;
860 ServerInstance->NICKForced.set(this, 1);
861 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
862 ServerInstance->NICKForced.set(this, 0);
864 if (MOD_RESULT == MOD_RES_DENY)
866 ServerInstance->stats->statsCollisions++;
870 if (assign(newnick) == assign(nick))
872 // case change, don't need to check Q:lines and such
873 // and, if it's identical including case, we can leave right now
880 * Don't check Q:Lines if it's a server-enforced change, just on the off-chance some fucking *moron*
881 * tries to Q:Line SIDs, also, this means we just get our way period, as it really should be.
882 * Thanks Kein for finding this. -- w00t
884 * Also don't check Q:Lines for remote nickchanges, they should have our Q:Lines anyway to enforce themselves.
887 if (IS_LOCAL(this) && !force)
889 XLine* mq = ServerInstance->XLines->MatchesLine("Q",newnick);
892 if (this->registered == REG_ALL)
894 ServerInstance->SNO->WriteGlobalSno('a', "Q-Lined nickname %s from %s!%s@%s: %s",
895 newnick.c_str(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), mq->reason.c_str());
897 this->WriteNumeric(432, "%s %s :Invalid nickname: %s",this->nick.c_str(), newnick.c_str(), mq->reason.c_str());
901 if (ServerInstance->Config->RestrictBannedUsers)
903 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
906 if (chan->GetPrefixValue(this) < VOICE_VALUE && chan->IsBanned(this))
908 this->WriteNumeric(404, "%s %s :Cannot send to channel (you're banned)", this->nick.c_str(), chan->name.c_str());
916 * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
917 * then we have a potential collide. Check whether someone else is camping on the nick
918 * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
919 * camper to their UID, and allow the incoming nick change.
921 * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
922 * because the nick is already (rightfully) in use. -- w00t
924 User* InUse = ServerInstance->FindNickOnly(newnick);
925 if (InUse && (InUse != this))
927 if (InUse->registered != REG_ALL)
929 /* force the camper to their UUID, and ask them to re-send a NICK. */
930 InUse->WriteTo(InUse, "NICK %s", InUse->uuid.c_str());
931 InUse->WriteNumeric(433, "%s %s :Nickname overruled.", InUse->nick.c_str(), InUse->nick.c_str());
933 ServerInstance->Users->clientlist->erase(InUse->nick);
934 (*(ServerInstance->Users->clientlist))[InUse->uuid] = InUse;
936 InUse->nick = InUse->uuid;
937 InUse->InvalidateCache();
938 InUse->registered &= ~REG_NICK;
942 /* No camping, tell the incoming user to stop trying to change nick ;p */
943 this->WriteNumeric(433, "%s %s :Nickname is already in use.", this->registered >= REG_NICK ? this->nick.c_str() : "*", newnick.c_str());
949 if (this->registered == REG_ALL)
950 this->WriteCommon("NICK %s",newnick.c_str());
951 std::string oldnick = nick;
955 ServerInstance->Users->clientlist->erase(oldnick);
956 (*(ServerInstance->Users->clientlist))[newnick] = this;
958 if (registered == REG_ALL)
959 FOREACH_MOD(I_OnUserPostNick,OnUserPostNick(this,oldnick));
964 int LocalUser::GetServerPort()
966 switch (this->server_sa.sa.sa_family)
969 return htons(this->server_sa.in6.sin6_port);
971 return htons(this->server_sa.in4.sin_port);
976 const char* User::GetIPString()
979 if (cachedip.empty())
981 irc::sockets::satoap(client_sa, cachedip, port);
982 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
983 if (cachedip.c_str()[0] == ':')
984 cachedip.insert(0,1,'0');
987 return cachedip.c_str();
990 irc::sockets::cidr_mask User::GetCIDRMask()
993 switch (client_sa.sa.sa_family)
996 range = ServerInstance->Config->c_ipv6_range;
999 range = ServerInstance->Config->c_ipv4_range;
1002 return irc::sockets::cidr_mask(client_sa, range);
1005 bool User::SetClientIP(const char* sip)
1008 return irc::sockets::aptosa(sip, 0, client_sa);
1011 void User::SetClientIP(const irc::sockets::sockaddrs& sa)
1014 memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
1017 bool LocalUser::SetClientIP(const char* sip)
1019 irc::sockets::sockaddrs sa;
1020 if (!irc::sockets::aptosa(sip, 0, sa))
1024 LocalUser::SetClientIP(sa);
1028 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa)
1030 if (sa != client_sa)
1032 User::SetClientIP(sa);
1033 FOREACH_MOD(I_OnSetUserIP,OnSetUserIP(this));
1037 static std::string wide_newline("\r\n");
1039 void User::Write(const std::string& text)
1043 void User::Write(const char *text, ...)
1047 void LocalUser::Write(const std::string& text)
1049 if (!ServerInstance->SE->BoundsCheckFd(&eh))
1052 if (text.length() > MAXBUF - 2)
1054 // this should happen rarely or never. Crop the string at 512 and try again.
1055 std::string try_again = text.substr(0, MAXBUF - 2);
1060 ServerInstance->Logs->Log("USEROUTPUT", RAWIO, "C[%s] O %s", uuid.c_str(), text.c_str());
1062 eh.AddWriteBuf(text);
1063 eh.AddWriteBuf(wide_newline);
1065 ServerInstance->stats->statsSent += text.length() + 2;
1066 this->bytes_out += text.length() + 2;
1072 void LocalUser::Write(const char *text, ...)
1075 char textbuffer[MAXBUF];
1077 va_start(argsPtr, text);
1078 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1081 this->Write(std::string(textbuffer));
1084 void User::WriteServ(const std::string& text)
1086 this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1090 * Same as Write(), except `text' is prefixed with `:server.name '.
1092 void User::WriteServ(const char* text, ...)
1095 char textbuffer[MAXBUF];
1097 va_start(argsPtr, text);
1098 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1101 this->WriteServ(std::string(textbuffer));
1105 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1108 char textbuffer[MAXBUF];
1110 va_start(argsPtr, text);
1111 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1114 this->WriteNumeric(numeric, std::string(textbuffer));
1117 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1119 char textbuffer[MAXBUF];
1120 ModResult MOD_RESULT;
1122 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1124 if (MOD_RESULT == MOD_RES_DENY)
1127 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1128 this->Write(std::string(textbuffer));
1131 void User::WriteFrom(User *user, const std::string &text)
1135 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1137 this->Write(std::string(tb));
1141 /* write text from an originating user to originating user */
1143 void User::WriteFrom(User *user, const char* text, ...)
1146 char textbuffer[MAXBUF];
1148 va_start(argsPtr, text);
1149 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1152 this->WriteFrom(user, std::string(textbuffer));
1156 /* write text to an destination user from a source user (e.g. user privmsg) */
1158 void User::WriteTo(User *dest, const char *data, ...)
1160 char textbuffer[MAXBUF];
1163 va_start(argsPtr, data);
1164 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1167 this->WriteTo(dest, std::string(textbuffer));
1170 void User::WriteTo(User *dest, const std::string &data)
1172 dest->WriteFrom(this, data);
1175 void User::WriteCommon(const char* text, ...)
1177 char textbuffer[MAXBUF];
1180 if (this->registered != REG_ALL || quitting)
1183 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1185 va_start(argsPtr, text);
1186 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1189 this->WriteCommonRaw(std::string(textbuffer), true);
1192 void User::WriteCommonExcept(const char* text, ...)
1194 char textbuffer[MAXBUF];
1197 if (this->registered != REG_ALL || quitting)
1200 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1202 va_start(argsPtr, text);
1203 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1206 this->WriteCommonRaw(std::string(textbuffer), false);
1209 void User::WriteCommonRaw(const std::string &line, bool include_self)
1211 if (this->registered != REG_ALL || quitting)
1214 LocalUser::already_sent_id++;
1216 UserChanList include_c(chans);
1217 std::map<User*,bool> exceptions;
1219 exceptions[this] = include_self;
1221 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1223 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1225 LocalUser* u = IS_LOCAL(i->first);
1226 if (u && !u->quitting)
1228 u->already_sent = LocalUser::already_sent_id;
1233 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1236 const UserMembList* ulist = c->GetUsers();
1237 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1239 LocalUser* u = IS_LOCAL(i->first);
1240 if (u && !u->quitting && u->already_sent != LocalUser::already_sent_id)
1242 u->already_sent = LocalUser::already_sent_id;
1249 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1254 if (this->registered != REG_ALL)
1257 already_sent_t uniq_id = ++LocalUser::already_sent_id;
1259 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1260 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1261 std::string out1 = tb1;
1262 std::string out2 = tb2;
1264 UserChanList include_c(chans);
1265 std::map<User*,bool> exceptions;
1267 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1269 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1271 LocalUser* u = IS_LOCAL(i->first);
1272 if (u && !u->quitting)
1274 u->already_sent = uniq_id;
1276 u->Write(IS_OPER(u) ? out2 : out1);
1279 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1281 const UserMembList* ulist = (*v)->GetUsers();
1282 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1284 LocalUser* u = IS_LOCAL(i->first);
1285 if (u && !u->quitting && (u->already_sent != uniq_id))
1287 u->already_sent = uniq_id;
1288 u->Write(IS_OPER(u) ? out2 : out1);
1294 void LocalUser::SendText(const std::string& line)
1299 void RemoteUser::SendText(const std::string& line)
1301 ServerInstance->PI->PushToClient(this, line);
1304 void FakeUser::SendText(const std::string& line)
1308 void User::SendText(const char *text, ...)
1313 va_start(argsPtr, text);
1314 vsnprintf(line, MAXBUF, text, argsPtr);
1317 SendText(std::string(line));
1320 void User::SendText(const std::string &LinePrefix, std::stringstream &TextStream)
1323 int start_pos = LinePrefix.length();
1324 int pos = start_pos;
1325 memcpy(line, LinePrefix.data(), pos);
1327 while (TextStream >> Word)
1329 int len = Word.length();
1330 if (pos + len + 12 > MAXBUF)
1333 SendText(std::string(line));
1337 memcpy(line + pos + 1, Word.data(), len);
1341 SendText(std::string(line));
1344 /* return 0 or 1 depending if users u and u2 share one or more common channels
1345 * (used by QUIT, NICK etc which arent channel specific notices)
1347 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1348 * the first users channels then the second users channels within the outer loop,
1349 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1350 * all possible iterations). However this new function instead checks against the
1351 * channel's userlist in the inner loop which is a std::map<User*,User*>
1352 * and saves us time as we already know what pointer value we are after.
1353 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1354 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1356 bool User::SharesChannelWith(User *other)
1358 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1362 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1364 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1365 * by replacing it with a map::find which *should* be more efficient
1367 if ((*i)->HasUser(other))
1373 bool User::ChangeName(const char* gecos)
1375 if (!this->fullname.compare(gecos))
1380 ModResult MOD_RESULT;
1381 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (IS_LOCAL(this),gecos));
1382 if (MOD_RESULT == MOD_RES_DENY)
1384 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1386 this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1391 void User::DoHostCycle(const std::string &quitline)
1393 char buffer[MAXBUF];
1395 if (!ServerInstance->Config->CycleHosts)
1398 already_sent_t silent_id = ++LocalUser::already_sent_id;
1399 already_sent_t seen_id = ++LocalUser::already_sent_id;
1401 UserChanList include_c(chans);
1402 std::map<User*,bool> exceptions;
1404 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1406 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1408 LocalUser* u = IS_LOCAL(i->first);
1409 if (u && !u->quitting)
1413 u->already_sent = seen_id;
1418 u->already_sent = silent_id;
1422 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1425 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1426 std::string joinline(buffer);
1427 Membership* memb = c->GetUser(this);
1428 std::string modeline = memb->modes;
1429 if (modeline.length() > 0)
1431 for(unsigned int i=0; i < memb->modes.length(); i++)
1432 modeline.append(" ").append(nick);
1433 snprintf(buffer, MAXBUF, ":%s MODE %s +%s",
1434 ServerInstance->Config->CycleHostsFromUser ? GetFullHost().c_str() : ServerInstance->Config->ServerName.c_str(),
1435 c->name.c_str(), modeline.c_str());
1439 const UserMembList *ulist = c->GetUsers();
1440 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1442 LocalUser* u = IS_LOCAL(i->first);
1443 if (u == NULL || u == this)
1445 if (u->already_sent == silent_id)
1448 if (u->already_sent != seen_id)
1451 u->already_sent = seen_id;
1454 if (modeline.length() > 0)
1460 bool User::ChangeDisplayedHost(const char* shost)
1467 ModResult MOD_RESULT;
1468 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (IS_LOCAL(this),shost));
1469 if (MOD_RESULT == MOD_RES_DENY)
1473 FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1475 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1477 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1478 this->dhost.assign(shost, 0, 64);
1480 this->InvalidateCache();
1482 this->DoHostCycle(quitstr);
1485 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1490 bool User::ChangeIdent(const char* newident)
1492 if (this->ident == newident)
1495 FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1497 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1499 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1501 this->InvalidateCache();
1503 this->DoHostCycle(quitstr);
1508 void User::SendAll(const char* command, const char* text, ...)
1510 char textbuffer[MAXBUF];
1511 char formatbuffer[MAXBUF];
1514 va_start(argsPtr, text);
1515 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1518 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1519 std::string fmt = formatbuffer;
1521 for (std::vector<LocalUser*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1523 if ((*i)->registered == REG_ALL)
1529 std::string User::ChannelList(User* source, bool spy)
1533 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1536 /* If the target is the sender, neither +p nor +s is set, or
1537 * the channel contains the user, it is not a spy channel
1539 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1540 list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1546 void User::SplitChanList(User* dest, const std::string &cl)
1549 std::ostringstream prefix;
1550 std::string::size_type start, pos, length;
1552 prefix << this->nick << " " << dest->nick << " :";
1553 line = prefix.str();
1554 int namelen = ServerInstance->Config->ServerName.length() + 6;
1556 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1558 length = (pos == std::string::npos) ? cl.length() : pos;
1560 if (line.length() + namelen + length - start > 510)
1562 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1563 line = prefix.str();
1566 if(pos == std::string::npos)
1568 line.append(cl.substr(start, length - start));
1573 line.append(cl.substr(start, length - start + 1));
1577 if (line.length() != prefix.str().length())
1579 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1584 * Sets a user's connection class.
1585 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1586 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1587 * then their ip will be taken as 'priority' anyway, so for example,
1588 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1590 void LocalUser::SetClass(const std::string &explicit_name)
1592 ConnectClass *found = NULL;
1594 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1596 if (!explicit_name.empty())
1598 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1600 ConnectClass* c = *i;
1602 if (explicit_name == c->name)
1604 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1611 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1613 ConnectClass* c = *i;
1614 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Checking %s", c->GetName().c_str());
1616 ModResult MOD_RESULT;
1617 FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1618 if (MOD_RESULT == MOD_RES_DENY)
1620 if (MOD_RESULT == MOD_RES_ALLOW)
1622 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Class forced by module to %s", c->GetName().c_str());
1627 if (c->type == CC_NAMED)
1630 bool regdone = (registered != REG_NONE);
1631 if (c->config->getBool("registered", regdone) != regdone)
1634 /* check if host matches.. */
1635 if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1636 !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1638 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1643 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1644 * because we should attempt to find another class if this one doesn't match us. -- w00t
1646 if (c->limit && (c->GetReferenceCount() >= c->limit))
1648 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1652 /* if it requires a port ... */
1653 int port = c->config->getInt("port");
1656 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", port);
1658 /* and our port doesn't match, fail. */
1659 if (this->GetServerPort() != port)
1663 if (regdone && !c->config->getString("password").empty())
1665 if (ServerInstance->PassCompare(this, c->config->getString("password"), password, c->config->getString("hash")))
1667 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Bad password, skipping");
1672 /* we stop at the first class that meets ALL critera. */
1679 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1687 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1688 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1689 * then their ip will be taken as 'priority' anyway, so for example,
1690 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1692 ConnectClass* LocalUser::GetClass()
1697 ConnectClass* User::GetClass()
1702 void User::PurgeEmptyChannels()
1704 // firstly decrement the count on each channel
1705 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1714 const std::string& FakeUser::GetFullHost()
1716 if (!ServerInstance->Config->HideWhoisServer.empty())
1717 return ServerInstance->Config->HideWhoisServer;
1721 const std::string& FakeUser::GetFullRealHost()
1723 if (!ServerInstance->Config->HideWhoisServer.empty())
1724 return ServerInstance->Config->HideWhoisServer;
1728 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1729 : config(tag), type(t), fakelag(true), name("unnamed"), registration_timeout(0), host(mask),
1730 pingtime(0), softsendqmax(0), hardsendqmax(0), recvqmax(0),
1731 penaltythreshold(0), commandrate(0), maxlocal(0), maxglobal(0), maxconnwarn(true), maxchans(0), limit(0)
1735 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1736 : config(tag), type(t), fakelag(parent.fakelag), name("unnamed"),
1737 registration_timeout(parent.registration_timeout), host(mask), pingtime(parent.pingtime),
1738 softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax), recvqmax(parent.recvqmax),
1739 penaltythreshold(parent.penaltythreshold), commandrate(parent.commandrate),
1740 maxlocal(parent.maxlocal), maxglobal(parent.maxglobal), maxconnwarn(parent.maxconnwarn), maxchans(parent.maxchans),
1745 void ConnectClass::Update(const ConnectClass* src)
1747 config = src->config;
1749 fakelag = src->fakelag;
1751 registration_timeout = src->registration_timeout;
1753 pingtime = src->pingtime;
1754 softsendqmax = src->softsendqmax;
1755 hardsendqmax = src->hardsendqmax;
1756 recvqmax = src->recvqmax;
1757 penaltythreshold = src->penaltythreshold;
1758 commandrate = src->commandrate;
1759 maxlocal = src->maxlocal;
1760 maxglobal = src->maxglobal;
1761 maxconnwarn = src->maxconnwarn;
1762 maxchans = src->maxchans;