1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include "socketengine.h"
19 #include "commands/cmd_whowas.h"
21 typedef unsigned int uniq_id_t;
29 array = new uniq_id_t[ServerInstance->SE->GetMaxFds()];
30 memset(array, 0, ServerInstance->SE->GetMaxFds() * sizeof(uniq_id_t));
34 sent() : uniq_id(static_cast<uniq_id_t>(-1)), array(NULL) {}
35 inline uniq_id_t operator++()
41 inline uniq_id_t& operator[](int i)
51 static sent already_sent;
53 std::string User::ProcessNoticeMasks(const char *sm)
55 bool adding = true, oldadding = false;
70 for (unsigned char d = 'A'; d <= 'z'; d++)
72 if (ServerInstance->SNO->IsEnabled(d))
74 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
76 if ((oldadding != adding) || (!output.length()))
77 output += (adding ? '+' : '-');
79 this->SetNoticeMask(d, adding);
88 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
90 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
92 if ((oldadding != adding) || (!output.length()))
93 output += (adding ? '+' : '-');
95 this->SetNoticeMask(*c, adding);
101 this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
110 std::string s = this->FormatNoticeMasks();
113 this->modes[UM_SNOMASK] = false;
119 void LocalUser::StartDNSLookup()
124 const char* sip = this->GetIPString();
125 UserResolver *res_reverse;
127 QueryType resolvtype = this->client_sa.sa.sa_family == AF_INET6 ? DNS_QUERY_PTR6 : DNS_QUERY_PTR4;
128 res_reverse = new UserResolver(this, sip, resolvtype, cached);
130 ServerInstance->AddResolver(res_reverse, cached);
132 catch (CoreException& e)
134 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
138 bool User::IsNoticeMaskSet(unsigned char sm)
142 return (snomasks[sm-65]);
145 void User::SetNoticeMask(unsigned char sm, bool value)
149 snomasks[sm-65] = value;
152 const char* User::FormatNoticeMasks()
154 static char data[MAXBUF];
157 for (int n = 0; n < 64; n++)
160 data[offset++] = n+65;
167 bool User::IsModeSet(unsigned char m)
171 return (modes[m-65]);
174 void User::SetMode(unsigned char m, bool value)
181 const char* User::FormatModes(bool showparameters)
183 static char data[MAXBUF];
187 for (unsigned char n = 0; n < 64; n++)
191 data[offset++] = n + 65;
192 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
193 if (showparameters && mh && mh->GetNumParams(true))
195 std::string p = mh->GetUserParameter(this);
197 params.append(" ").append(p);
202 strlcat(data, params.c_str(), MAXBUF);
206 void User::DecrementModes()
208 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
209 for (unsigned char n = 'A'; n <= 'z'; n++)
213 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
214 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
217 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
224 User::User(const std::string &uid, const std::string& sid, int type)
225 : uuid(uid), server(sid), usertype(type)
227 age = ServerInstance->Time();
228 signon = idle_lastmsg = 0;
230 quietquit = quitting = exempt = dns_done = false;
231 client_sa.sa.sa_family = AF_UNSPEC;
233 ServerInstance->Logs->Log("USERS", DEBUG, "New UUID for user: %s", uuid.c_str());
235 user_hash::iterator finduuid = ServerInstance->Users->uuidlist->find(uuid);
236 if (finduuid == ServerInstance->Users->uuidlist->end())
237 (*ServerInstance->Users->uuidlist)[uuid] = this;
239 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
242 LocalUser::LocalUser() : User(ServerInstance->GetUID(), ServerInstance->Config->ServerName, USERTYPE_LOCAL)
244 bytes_in = bytes_out = cmds_in = cmds_out = 0;
245 server_sa.sa.sa_family = AF_UNSPEC;
247 lastping = nping = 0;
252 if (ServerInstance->Users->uuidlist->find(uuid) != ServerInstance->Users->uuidlist->end())
253 ServerInstance->Logs->Log("USERS", ERROR, "User destructor for %s called without cull", uuid.c_str());
256 const std::string& User::MakeHost()
258 if (!this->cached_makehost.empty())
259 return this->cached_makehost;
262 /* This is much faster than snprintf */
264 for(const char* n = ident.c_str(); *n; n++)
267 for(const char* n = host.c_str(); *n; n++)
271 this->cached_makehost.assign(nhost);
273 return this->cached_makehost;
276 const std::string& User::MakeHostIP()
278 if (!this->cached_hostip.empty())
279 return this->cached_hostip;
282 /* This is much faster than snprintf */
284 for(const char* n = ident.c_str(); *n; n++)
287 for(const char* n = this->GetIPString(); *n; n++)
291 this->cached_hostip = ihost;
293 return this->cached_hostip;
296 const std::string& User::GetFullHost()
298 if (!this->cached_fullhost.empty())
299 return this->cached_fullhost;
303 for(const char* n = nick.c_str(); *n; n++)
306 for(const char* n = ident.c_str(); *n; n++)
309 for(const char* n = dhost.c_str(); *n; n++)
313 this->cached_fullhost = result;
315 return this->cached_fullhost;
318 char* User::MakeWildHost()
320 static char nresult[MAXBUF];
322 *t++ = '*'; *t++ = '!';
323 *t++ = '*'; *t++ = '@';
324 for(const char* n = dhost.c_str(); *n; n++)
330 const std::string& User::GetFullRealHost()
332 if (!this->cached_fullrealhost.empty())
333 return this->cached_fullrealhost;
335 char fresult[MAXBUF];
337 for(const char* n = nick.c_str(); *n; n++)
340 for(const char* n = ident.c_str(); *n; n++)
343 for(const char* n = host.c_str(); *n; n++)
347 this->cached_fullrealhost = fresult;
349 return this->cached_fullrealhost;
352 bool LocalUser::IsInvited(const irc::string &channel)
354 time_t now = ServerInstance->Time();
355 InvitedList::iterator safei;
356 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
358 if (channel == i->first)
360 if (i->second != 0 && now > i->second)
362 /* Expired invite, remove it. */
365 invites.erase(safei);
374 InvitedList* LocalUser::GetInviteList()
376 time_t now = ServerInstance->Time();
377 /* Weed out expired invites here. */
378 InvitedList::iterator safei;
379 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
381 if (i->second != 0 && now > i->second)
383 /* Expired invite, remove it. */
386 invites.erase(safei);
392 void LocalUser::InviteTo(const irc::string &channel, time_t invtimeout)
394 time_t now = ServerInstance->Time();
395 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
396 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
398 if (channel == i->first)
400 if (i->second != 0 && invtimeout > i->second)
402 i->second = invtimeout;
408 invites.push_back(std::make_pair(channel, invtimeout));
411 void LocalUser::RemoveInvite(const irc::string &channel)
413 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
415 if (channel == i->first)
423 bool User::HasModePermission(unsigned char, ModeType)
428 bool LocalUser::HasModePermission(unsigned char mode, ModeType type)
433 if (mode < 'A' || mode > ('A' + 64)) return false;
435 return ((type == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
439 * users on remote servers can completely bypass all permissions based checks.
440 * This prevents desyncs when one server has different type/class tags to another.
441 * That having been said, this does open things up to the possibility of source changes
442 * allowing remote kills, etc - but if they have access to the src, they most likely have
443 * access to the conf - so it's an end to a means either way.
445 bool User::HasPermission(const std::string&)
450 bool LocalUser::HasPermission(const std::string &command)
452 // are they even an oper at all?
458 if (oper->AllowedOperCommands.find(command) != oper->AllowedOperCommands.end())
460 else if (oper->AllowedOperCommands.find("*") != oper->AllowedOperCommands.end())
466 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
471 bool LocalUser::HasPrivPermission(const std::string &privstr, bool noisy)
476 this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
480 if (oper->AllowedPrivs.find(privstr) != oper->AllowedPrivs.end())
484 else if (oper->AllowedPrivs.find("*") != oper->AllowedPrivs.end())
490 this->WriteServ("NOTICE %s :Oper type %s does not have access to priv %s", this->nick.c_str(), oper->NameStr(), privstr.c_str());
494 void User::OnDataReady()
498 void LocalUser::OnDataReady()
503 if (recvq.length() > MyClass->GetRecvqMax() && !HasPrivPermission("users/flood/increased-buffers"))
505 ServerInstance->Users->QuitUser(this, "RecvQ exceeded");
506 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
507 nick.c_str(), (unsigned long)recvq.length(), MyClass->GetRecvqMax());
509 unsigned long sendqmax = ULONG_MAX;
510 if (!HasPrivPermission("users/flood/increased-buffers"))
511 sendqmax = MyClass->GetSendqSoftMax();
512 int penaltymax = MyClass->GetPenaltyThreshold();
513 if (penaltymax == 0 || HasPrivPermission("users/flood/no-fakelag"))
514 penaltymax = INT_MAX;
516 while (Penalty < penaltymax && getSendQSize() < sendqmax)
519 line.reserve(MAXBUF);
520 std::string::size_type qpos = 0;
521 while (qpos < recvq.length())
523 char c = recvq[qpos++];
534 if (line.length() < MAXBUF - 2)
537 // if we got here, the recvq ran out before we found a newline
540 // just found a newline. Terminate the string, and pull it out of recvq
541 recvq = recvq.substr(qpos);
543 // TODO should this be moved to when it was inserted in recvq?
544 ServerInstance->stats->statsRecv += qpos;
545 this->bytes_in += qpos;
548 ServerInstance->Parser->ProcessBuffer(line, this);
552 // Add pseudo-penalty so that we continue processing after sendq recedes
553 if (Penalty == 0 && getSendQSize() >= sendqmax)
557 void LocalUser::AddWriteBuf(const std::string &data)
559 if (!quitting && getSendQSize() + data.length() > MyClass->GetSendqHardMax() && !HasPrivPermission("users/flood/increased-buffers"))
562 * Quit the user FIRST, because otherwise we could recurse
563 * here and hit the same limit.
565 ServerInstance->Users->QuitUser(this, "SendQ exceeded");
566 ServerInstance->SNO->WriteToSnoMask('a', "User %s SendQ exceeds connect class maximum of %lu",
567 nick.c_str(), MyClass->GetSendqHardMax());
571 // We still want to append data to the sendq of a quitting user,
572 // e.g. their ERROR message that says 'closing link'
577 void User::OnError(BufferedSocketError)
579 ServerInstance->Users->QuitUser(this, getError());
582 CullResult User::cull()
585 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
586 PurgeEmptyChannels();
588 this->InvalidateCache();
589 this->DecrementModes();
591 ServerInstance->Users->uuidlist->erase(uuid);
592 return Extensible::cull();
595 CullResult LocalUser::cull()
597 std::vector<LocalUser*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
598 if (x != ServerInstance->Users->local_users.end())
599 ServerInstance->Users->local_users.erase(x);
601 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
603 if (client_sa.sa.sa_family != AF_UNSPEC)
604 ServerInstance->Users->RemoveCloneCounts(this);
609 CullResult FakeUser::cull()
611 // Fake users don't quit, they just get culled.
616 void User::Oper(OperInfo* info)
618 if (this->IsModeSet('o'))
621 this->modes[UM_OPERATOR] = 1;
623 this->WriteServ("MODE %s :+o", this->nick.c_str());
624 FOREACH_MOD(I_OnOper, OnOper(this, info->name));
626 std::string opername;
627 if (info->oper_block)
628 opername = info->oper_block->getString("name");
632 LocalUser* l = IS_LOCAL(this);
633 std::string vhost = oper->getConfig("vhost");
635 l->ChangeDisplayedHost(vhost.c_str());
636 std::string opClass = oper->getConfig("class");
637 if (!opClass.empty())
639 l->SetClass(opClass);
644 ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s (using oper '%s')",
645 nick.c_str(), ident.c_str(), host.c_str(), oper->NameStr(), opername.c_str());
646 this->WriteNumeric(381, "%s :You are now %s %s", nick.c_str(), strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->NameStr());
648 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());
649 ServerInstance->Users->all_opers.push_back(this);
651 // Expand permissions from config for faster lookup
655 FOREACH_MOD(I_OnPostOper,OnPostOper(this, oper->name, opername));
658 void OperInfo::init()
660 AllowedOperCommands.clear();
661 AllowedPrivs.clear();
662 AllowedUserModes.reset();
663 AllowedChanModes.reset();
664 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
666 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
668 ConfigTag* tag = *iter;
669 std::string mycmd, mypriv;
670 /* Process commands */
671 irc::spacesepstream CommandList(tag->getString("commands"));
672 while (CommandList.GetToken(mycmd))
674 AllowedOperCommands.insert(mycmd);
677 irc::spacesepstream PrivList(tag->getString("privs"));
678 while (PrivList.GetToken(mypriv))
680 AllowedPrivs.insert(mypriv);
683 for (unsigned char* c = (unsigned char*)tag->getString("usermodes").c_str(); *c; ++c)
687 this->AllowedUserModes.set();
691 this->AllowedUserModes[*c - 'A'] = true;
695 for (unsigned char* c = (unsigned char*)tag->getString("chanmodes").c_str(); *c; ++c)
699 this->AllowedChanModes.set();
703 this->AllowedChanModes[*c - 'A'] = true;
715 * unset their oper type (what IS_OPER checks).
716 * note, order is important - this must come before modes as -o attempts
717 * to call UnOper. -- w00t
722 /* Remove all oper only modes from the user when the deoper - Bug #466*/
723 std::string moderemove("-");
725 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
727 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
728 if (mh && mh->NeedsOper())
729 moderemove += letter;
733 std::vector<std::string> parameters;
734 parameters.push_back(this->nick);
735 parameters.push_back(moderemove);
737 ServerInstance->Parser->CallHandler("MODE", parameters, this);
739 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
740 ServerInstance->Users->all_opers.remove(this);
742 this->modes[UM_OPERATOR] = 0;
745 /* adds or updates an entry in the whowas list */
746 void User::AddToWhoWas()
748 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
751 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
758 * Check class restrictions
760 void LocalUser::CheckClass()
762 ConnectClass* a = this->MyClass;
766 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
768 else if (a->type == CC_DENY)
770 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
773 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
775 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
776 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
779 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
781 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
782 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
786 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
789 bool User::CheckLines(bool doZline)
791 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
795 for (int n = 0; check[n]; ++n)
797 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
810 void LocalUser::FullConnect()
812 ServerInstance->stats->statsConnects++;
813 this->idle_lastmsg = ServerInstance->Time();
816 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
817 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
818 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
819 * Don't remove this! -- w00t
823 /* Check the password, if one is required by the user's connect class.
824 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
826 if (!MyClass->pass.empty())
828 if (ServerInstance->PassCompare(this, MyClass->pass.c_str(), password.c_str(), MyClass->hash.c_str()))
830 ServerInstance->Users->QuitUser(this, "Invalid password");
835 if (this->CheckLines())
838 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
839 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());
840 this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-2.0",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
841 this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
842 this->WriteNumeric(RPL_SERVERVERSION, "%s %s InspIRCd-2.0 %s %s %s", this->nick.c_str(), ServerInstance->Config->ServerName.c_str(), ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
844 ServerInstance->Config->Send005(this);
845 this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
851 if (ServerInstance->Users->unregistered_count)
852 ServerInstance->Users->unregistered_count--;
854 /* Trigger LUSERS output, give modules a chance too */
855 ModResult MOD_RESULT;
856 std::string command("LUSERS");
857 std::vector<std::string> parameters;
858 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, "LUSERS"));
860 ServerInstance->CallCommandHandler(command, parameters, this);
863 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
864 * for a user that doesn't exist yet.
866 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
868 this->registered = REG_ALL;
870 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
872 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]",
873 this->GetServerPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
874 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
875 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
878 /** User::UpdateNick()
879 * re-allocates a nick in the user_hash after they change nicknames,
880 * returns a pointer to the new user as it may have moved
882 User* User::UpdateNickHash(const char* New)
884 //user_hash::iterator newnick;
885 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
887 if (!irc::string(this->nick.c_str()).compare(New))
888 return oldnick->second;
890 if (oldnick == ServerInstance->Users->clientlist->end())
891 return NULL; /* doesnt exist */
893 User* olduser = oldnick->second;
894 ServerInstance->Users->clientlist->erase(oldnick);
895 (*(ServerInstance->Users->clientlist))[New] = olduser;
899 void User::InvalidateCache()
901 /* Invalidate cache */
902 cached_fullhost.clear();
903 cached_hostip.clear();
904 cached_makehost.clear();
905 cached_fullrealhost.clear();
908 bool User::ForceNickChange(const char* newnick)
910 ModResult MOD_RESULT;
912 this->InvalidateCache();
914 ServerInstance->NICKForced.set(this, 1);
915 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
916 ServerInstance->NICKForced.set(this, 0);
918 if (MOD_RESULT == MOD_RES_DENY)
920 ServerInstance->stats->statsCollisions++;
924 std::deque<classbase*> dummy;
925 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
926 if (nickhandler) // wtfbbq, when would this not be here
928 std::vector<std::string> parameters;
929 parameters.push_back(newnick);
930 ServerInstance->NICKForced.set(this, 1);
931 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
932 ServerInstance->NICKForced.set(this, 0);
936 // Unreachable, we hope
940 int LocalUser::GetServerPort()
942 switch (this->server_sa.sa.sa_family)
945 return htons(this->server_sa.in6.sin6_port);
947 return htons(this->server_sa.in4.sin_port);
952 const char* User::GetIPString()
955 if (cachedip.empty())
957 irc::sockets::satoap(client_sa, cachedip, port);
958 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
959 if (cachedip.c_str()[0] == ':')
960 cachedip.insert(0,1,'0');
963 return cachedip.c_str();
966 irc::sockets::cidr_mask User::GetCIDRMask()
969 switch (client_sa.sa.sa_family)
972 range = ServerInstance->Config->c_ipv6_range;
975 range = ServerInstance->Config->c_ipv4_range;
978 return irc::sockets::cidr_mask(client_sa, range);
981 bool User::SetClientIP(const char* sip)
984 return irc::sockets::aptosa(sip, 0, client_sa);
987 static std::string wide_newline("\r\n");
989 void User::Write(const std::string& text)
993 void User::Write(const char *text, ...)
997 void LocalUser::Write(const std::string& text)
999 if (!ServerInstance->SE->BoundsCheckFd(this))
1002 if (text.length() > MAXBUF - 2)
1004 // this should happen rarely or never. Crop the string at 512 and try again.
1005 std::string try_again = text.substr(0, MAXBUF - 2);
1010 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1012 this->AddWriteBuf(text);
1013 this->AddWriteBuf(wide_newline);
1015 ServerInstance->stats->statsSent += text.length() + 2;
1016 this->bytes_out += text.length() + 2;
1022 void LocalUser::Write(const char *text, ...)
1025 char textbuffer[MAXBUF];
1027 va_start(argsPtr, text);
1028 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1031 this->Write(std::string(textbuffer));
1034 void User::WriteServ(const std::string& text)
1036 this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1040 * Same as Write(), except `text' is prefixed with `:server.name '.
1042 void User::WriteServ(const char* text, ...)
1045 char textbuffer[MAXBUF];
1047 va_start(argsPtr, text);
1048 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1051 this->WriteServ(std::string(textbuffer));
1055 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1058 char textbuffer[MAXBUF];
1060 va_start(argsPtr, text);
1061 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1064 this->WriteNumeric(numeric, std::string(textbuffer));
1067 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1069 char textbuffer[MAXBUF];
1070 ModResult MOD_RESULT;
1072 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1074 if (MOD_RESULT == MOD_RES_DENY)
1077 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1078 this->Write(std::string(textbuffer));
1081 void User::WriteFrom(User *user, const std::string &text)
1085 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1087 this->Write(std::string(tb));
1091 /* write text from an originating user to originating user */
1093 void User::WriteFrom(User *user, const char* text, ...)
1096 char textbuffer[MAXBUF];
1098 va_start(argsPtr, text);
1099 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1102 this->WriteFrom(user, std::string(textbuffer));
1106 /* write text to an destination user from a source user (e.g. user privmsg) */
1108 void User::WriteTo(User *dest, const char *data, ...)
1110 char textbuffer[MAXBUF];
1113 va_start(argsPtr, data);
1114 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1117 this->WriteTo(dest, std::string(textbuffer));
1120 void User::WriteTo(User *dest, const std::string &data)
1122 dest->WriteFrom(this, data);
1125 void User::WriteCommon(const char* text, ...)
1127 char textbuffer[MAXBUF];
1130 if (this->registered != REG_ALL || quitting)
1133 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1135 va_start(argsPtr, text);
1136 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1139 this->WriteCommonRaw(std::string(textbuffer), true);
1142 void User::WriteCommonExcept(const char* text, ...)
1144 char textbuffer[MAXBUF];
1147 if (this->registered != REG_ALL || quitting)
1150 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1152 va_start(argsPtr, text);
1153 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1156 this->WriteCommonRaw(std::string(textbuffer), false);
1159 void User::WriteCommonRaw(const std::string &line, bool include_self)
1161 if (this->registered != REG_ALL || quitting)
1164 uniq_id_t uniq_id = ++already_sent;
1166 UserChanList include_c(chans);
1167 std::map<User*,bool> exceptions;
1169 exceptions[this] = include_self;
1171 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1173 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1175 LocalUser* u = IS_LOCAL(i->first);
1176 if (u && !u->quitting)
1178 already_sent[u->GetFd()] = uniq_id;
1183 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1186 const UserMembList* ulist = c->GetUsers();
1187 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1189 LocalUser* u = IS_LOCAL(i->first);
1190 if (u && !u->quitting && already_sent[u->GetFd()] != uniq_id)
1192 already_sent[u->GetFd()] = uniq_id;
1199 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1204 if (this->registered != REG_ALL)
1207 uniq_id_t uniq_id = ++already_sent;
1209 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1210 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1211 std::string out1 = tb1;
1212 std::string out2 = tb2;
1214 UserChanList include_c(chans);
1215 std::map<User*,bool> exceptions;
1217 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1219 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1221 LocalUser* u = IS_LOCAL(i->first);
1222 if (u && !u->quitting)
1224 already_sent[u->GetFd()] = uniq_id;
1226 u->Write(IS_OPER(u) ? out2 : out1);
1229 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1231 const UserMembList* ulist = (*v)->GetUsers();
1232 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1234 LocalUser* u = IS_LOCAL(i->first);
1235 if (u && !u->quitting && (already_sent[u->GetFd()] != uniq_id))
1237 already_sent[u->GetFd()] = uniq_id;
1238 u->Write(IS_OPER(u) ? out2 : out1);
1244 void LocalUser::SendText(const std::string& line)
1249 void RemoteUser::SendText(const std::string& line)
1251 ServerInstance->PI->PushToClient(this, line);
1254 void FakeUser::SendText(const std::string& line)
1258 void User::SendText(const char *text, ...)
1263 va_start(argsPtr, text);
1264 vsnprintf(line, MAXBUF, text, argsPtr);
1267 SendText(std::string(line));
1270 void User::SendText(const std::string &LinePrefix, std::stringstream &TextStream)
1273 int start_pos = LinePrefix.length();
1274 int pos = start_pos;
1275 memcpy(line, LinePrefix.data(), pos);
1277 while (TextStream >> Word)
1279 int len = Word.length();
1280 if (pos + len + 12 > MAXBUF)
1283 SendText(std::string(line));
1287 memcpy(line + pos + 1, Word.data(), len);
1291 SendText(std::string(line));
1294 /* return 0 or 1 depending if users u and u2 share one or more common channels
1295 * (used by QUIT, NICK etc which arent channel specific notices)
1297 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1298 * the first users channels then the second users channels within the outer loop,
1299 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1300 * all possible iterations). However this new function instead checks against the
1301 * channel's userlist in the inner loop which is a std::map<User*,User*>
1302 * and saves us time as we already know what pointer value we are after.
1303 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1304 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1306 bool User::SharesChannelWith(User *other)
1308 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1312 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1314 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1315 * by replacing it with a map::find which *should* be more efficient
1317 if ((*i)->HasUser(other))
1323 bool User::ChangeName(const char* gecos)
1325 if (!this->fullname.compare(gecos))
1330 ModResult MOD_RESULT;
1331 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (IS_LOCAL(this),gecos));
1332 if (MOD_RESULT == MOD_RES_DENY)
1334 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1336 this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1341 void User::DoHostCycle(const std::string &quitline)
1343 char buffer[MAXBUF];
1345 if (!ServerInstance->Config->CycleHosts)
1348 uniq_id_t silent_id = ++already_sent;
1349 uniq_id_t seen_id = ++already_sent;
1351 UserChanList include_c(chans);
1352 std::map<User*,bool> exceptions;
1354 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1356 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1358 LocalUser* u = IS_LOCAL(i->first);
1359 if (u && !u->quitting)
1363 already_sent[u->GetFd()] = seen_id;
1368 already_sent[u->GetFd()] = silent_id;
1372 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1375 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1376 std::string joinline(buffer);
1377 Membership* memb = c->GetUser(this);
1378 std::string modeline = memb->modes;
1379 if (modeline.length() > 0)
1381 for(unsigned int i=0; i < memb->modes.length(); i++)
1382 modeline.append(" ").append(nick);
1383 snprintf(buffer, MAXBUF, ":%s MODE %s +%s", GetFullHost().c_str(), c->name.c_str(), modeline.c_str());
1387 const UserMembList *ulist = c->GetUsers();
1388 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1390 LocalUser* u = IS_LOCAL(i->first);
1391 if (u == NULL || u == this)
1393 if (already_sent[u->GetFd()] == silent_id)
1396 if (already_sent[u->GetFd()] != seen_id)
1399 already_sent[u->GetFd()] = seen_id;
1402 if (modeline.length() > 0)
1408 bool User::ChangeDisplayedHost(const char* shost)
1415 ModResult MOD_RESULT;
1416 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (IS_LOCAL(this),shost));
1417 if (MOD_RESULT == MOD_RES_DENY)
1421 FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1423 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1425 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1426 this->dhost.assign(shost, 0, 64);
1428 this->InvalidateCache();
1430 this->DoHostCycle(quitstr);
1433 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1438 bool User::ChangeIdent(const char* newident)
1440 if (this->ident == newident)
1443 FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1445 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1447 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1449 this->InvalidateCache();
1451 this->DoHostCycle(quitstr);
1456 void User::SendAll(const char* command, const char* text, ...)
1458 char textbuffer[MAXBUF];
1459 char formatbuffer[MAXBUF];
1462 va_start(argsPtr, text);
1463 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1466 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1467 std::string fmt = formatbuffer;
1469 for (std::vector<LocalUser*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1476 std::string User::ChannelList(User* source, bool spy)
1480 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1483 /* If the target is the sender, neither +p nor +s is set, or
1484 * the channel contains the user, it is not a spy channel
1486 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1487 list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1493 void User::SplitChanList(User* dest, const std::string &cl)
1496 std::ostringstream prefix;
1497 std::string::size_type start, pos, length;
1499 prefix << this->nick << " " << dest->nick << " :";
1500 line = prefix.str();
1501 int namelen = ServerInstance->Config->ServerName.length() + 6;
1503 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1505 length = (pos == std::string::npos) ? cl.length() : pos;
1507 if (line.length() + namelen + length - start > 510)
1509 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1510 line = prefix.str();
1513 if(pos == std::string::npos)
1515 line.append(cl.substr(start, length - start));
1520 line.append(cl.substr(start, length - start + 1));
1526 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1531 * Sets a user's connection class.
1532 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1533 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1534 * then their ip will be taken as 'priority' anyway, so for example,
1535 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1537 void LocalUser::SetClass(const std::string &explicit_name)
1539 ConnectClass *found = NULL;
1541 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1543 if (!explicit_name.empty())
1545 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1547 ConnectClass* c = *i;
1549 if (explicit_name == c->name)
1551 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1558 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1560 ConnectClass* c = *i;
1562 if (c->type == CC_ALLOW)
1564 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->host.c_str(), c->GetPort(), c->GetName().c_str());
1568 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1571 /* check if host matches.. */
1572 if (c->GetHost().length() && !InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1573 !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1575 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1580 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1581 * because we should attempt to find another class if this one doesn't match us. -- w00t
1583 if (c->limit && (c->GetReferenceCount() >= c->limit))
1585 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1589 /* if it requires a port ... */
1592 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1594 /* and our port doesn't match, fail. */
1595 if (this->GetServerPort() != c->GetPort())
1597 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetServerPort());
1602 /* we stop at the first class that meets ALL critera. */
1609 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1617 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1618 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1619 * then their ip will be taken as 'priority' anyway, so for example,
1620 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1622 ConnectClass* LocalUser::GetClass()
1627 ConnectClass* User::GetClass()
1632 void User::PurgeEmptyChannels()
1634 // firstly decrement the count on each channel
1635 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1644 void User::ShowMOTD()
1646 if (!ServerInstance->Config->MOTD.size())
1648 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1651 this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName.c_str());
1653 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1654 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1656 this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1659 void User::ShowRULES()
1661 if (!ServerInstance->Config->RULES.size())
1663 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1667 this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
1669 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1670 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1672 this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1675 const std::string& FakeUser::GetFullHost()
1677 if (!ServerInstance->Config->HideWhoisServer.empty())
1678 return ServerInstance->Config->HideWhoisServer;
1682 const std::string& FakeUser::GetFullRealHost()
1684 if (!ServerInstance->Config->HideWhoisServer.empty())
1685 return ServerInstance->Config->HideWhoisServer;
1689 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1690 : config(tag), type(t), name("unnamed"), registration_timeout(0), host(mask),
1691 pingtime(0), pass(""), hash(""), softsendqmax(0), hardsendqmax(0),
1692 recvqmax(0), penaltythreshold(0), maxlocal(0), maxglobal(0), maxchans(0), port(0), limit(0)
1696 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1697 : config(tag), type(t), name("unnamed"),
1698 registration_timeout(parent.registration_timeout), host(mask),
1699 pingtime(parent.pingtime), pass(parent.pass), hash(parent.hash),
1700 softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax),
1701 recvqmax(parent.recvqmax), penaltythreshold(parent.penaltythreshold), maxlocal(parent.maxlocal),
1702 maxglobal(parent.maxglobal), maxchans(parent.maxchans),
1703 port(parent.port), limit(parent.limit)
1707 void ConnectClass::Update(const ConnectClass* src)
1710 registration_timeout = src->registration_timeout;
1712 pingtime = src->pingtime;
1715 softsendqmax = src->softsendqmax;
1716 hardsendqmax = src->hardsendqmax;
1717 recvqmax = src->recvqmax;
1718 penaltythreshold = src->penaltythreshold;
1719 maxlocal = src->maxlocal;
1720 maxglobal = src->maxglobal;