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(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
243 : User(ServerInstance->GetUID(), ServerInstance->Config->ServerName, USERTYPE_LOCAL), eh(this)
245 bytes_in = bytes_out = cmds_in = cmds_out = 0;
246 server_sa.sa.sa_family = AF_UNSPEC;
248 lastping = nping = 0;
250 memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
251 memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
256 if (ServerInstance->Users->uuidlist->find(uuid) != ServerInstance->Users->uuidlist->end())
257 ServerInstance->Logs->Log("USERS", ERROR, "User destructor for %s called without cull", uuid.c_str());
260 const std::string& User::MakeHost()
262 if (!this->cached_makehost.empty())
263 return this->cached_makehost;
266 /* This is much faster than snprintf */
268 for(const char* n = ident.c_str(); *n; n++)
271 for(const char* n = host.c_str(); *n; n++)
275 this->cached_makehost.assign(nhost);
277 return this->cached_makehost;
280 const std::string& User::MakeHostIP()
282 if (!this->cached_hostip.empty())
283 return this->cached_hostip;
286 /* This is much faster than snprintf */
288 for(const char* n = ident.c_str(); *n; n++)
291 for(const char* n = this->GetIPString(); *n; n++)
295 this->cached_hostip = ihost;
297 return this->cached_hostip;
300 const std::string& User::GetFullHost()
302 if (!this->cached_fullhost.empty())
303 return this->cached_fullhost;
307 for(const char* n = nick.c_str(); *n; n++)
310 for(const char* n = ident.c_str(); *n; n++)
313 for(const char* n = dhost.c_str(); *n; n++)
317 this->cached_fullhost = result;
319 return this->cached_fullhost;
322 char* User::MakeWildHost()
324 static char nresult[MAXBUF];
326 *t++ = '*'; *t++ = '!';
327 *t++ = '*'; *t++ = '@';
328 for(const char* n = dhost.c_str(); *n; n++)
334 const std::string& User::GetFullRealHost()
336 if (!this->cached_fullrealhost.empty())
337 return this->cached_fullrealhost;
339 char fresult[MAXBUF];
341 for(const char* n = nick.c_str(); *n; n++)
344 for(const char* n = ident.c_str(); *n; n++)
347 for(const char* n = host.c_str(); *n; n++)
351 this->cached_fullrealhost = fresult;
353 return this->cached_fullrealhost;
356 bool LocalUser::IsInvited(const irc::string &channel)
358 time_t now = ServerInstance->Time();
359 InvitedList::iterator safei;
360 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
362 if (channel == i->first)
364 if (i->second != 0 && now > i->second)
366 /* Expired invite, remove it. */
369 invites.erase(safei);
378 InvitedList* LocalUser::GetInviteList()
380 time_t now = ServerInstance->Time();
381 /* Weed out expired invites here. */
382 InvitedList::iterator safei;
383 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
385 if (i->second != 0 && now > i->second)
387 /* Expired invite, remove it. */
390 invites.erase(safei);
396 void LocalUser::InviteTo(const irc::string &channel, time_t invtimeout)
398 time_t now = ServerInstance->Time();
399 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
400 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
402 if (channel == i->first)
404 if (i->second != 0 && invtimeout > i->second)
406 i->second = invtimeout;
412 invites.push_back(std::make_pair(channel, invtimeout));
415 void LocalUser::RemoveInvite(const irc::string &channel)
417 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
419 if (channel == i->first)
427 bool User::HasModePermission(unsigned char, ModeType)
432 bool LocalUser::HasModePermission(unsigned char mode, ModeType type)
437 if (mode < 'A' || mode > ('A' + 64)) return false;
439 return ((type == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
443 * users on remote servers can completely bypass all permissions based checks.
444 * This prevents desyncs when one server has different type/class tags to another.
445 * That having been said, this does open things up to the possibility of source changes
446 * allowing remote kills, etc - but if they have access to the src, they most likely have
447 * access to the conf - so it's an end to a means either way.
449 bool User::HasPermission(const std::string&)
454 bool LocalUser::HasPermission(const std::string &command)
456 // are they even an oper at all?
462 if (oper->AllowedOperCommands.find(command) != oper->AllowedOperCommands.end())
464 else if (oper->AllowedOperCommands.find("*") != oper->AllowedOperCommands.end())
470 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
475 bool LocalUser::HasPrivPermission(const std::string &privstr, bool noisy)
480 this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
484 if (oper->AllowedPrivs.find(privstr) != oper->AllowedPrivs.end())
488 else if (oper->AllowedPrivs.find("*") != oper->AllowedPrivs.end())
494 this->WriteServ("NOTICE %s :Oper type %s does not have access to priv %s", this->nick.c_str(), oper->NameStr(), privstr.c_str());
498 void UserIOHandler::OnDataReady()
503 if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
505 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
506 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
507 user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
509 unsigned long sendqmax = ULONG_MAX;
510 if (!user->HasPrivPermission("users/flood/increased-buffers"))
511 sendqmax = user->MyClass->GetSendqSoftMax();
512 int penaltymax = user->MyClass->GetPenaltyThreshold();
513 if (penaltymax == 0 || user->HasPrivPermission("users/flood/no-fakelag"))
514 penaltymax = INT_MAX;
516 while (user->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 user->bytes_in += qpos;
548 ServerInstance->Parser->ProcessBuffer(line, user);
552 // Add pseudo-penalty so that we continue processing after sendq recedes
553 if (user->Penalty == 0 && getSendQSize() >= sendqmax)
557 void UserIOHandler::AddWriteBuf(const std::string &data)
559 if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
560 !user->HasPrivPermission("users/flood/increased-buffers"))
563 * Quit the user FIRST, because otherwise we could recurse
564 * here and hit the same limit.
566 ServerInstance->Users->QuitUser(user, "SendQ exceeded");
567 ServerInstance->SNO->WriteToSnoMask('a', "User %s SendQ exceeds connect class maximum of %lu",
568 user->nick.c_str(), user->MyClass->GetSendqHardMax());
572 // We still want to append data to the sendq of a quitting user,
573 // e.g. their ERROR message that says 'closing link'
578 void UserIOHandler::OnError(BufferedSocketError)
580 ServerInstance->Users->QuitUser(user, getError());
583 CullResult User::cull()
586 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
587 PurgeEmptyChannels();
589 this->InvalidateCache();
590 this->DecrementModes();
592 if (client_sa.sa.sa_family != AF_UNSPEC)
593 ServerInstance->Users->RemoveCloneCounts(this);
595 ServerInstance->Users->uuidlist->erase(uuid);
596 return Extensible::cull();
599 CullResult LocalUser::cull()
601 std::vector<LocalUser*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
602 if (x != ServerInstance->Users->local_users.end())
603 ServerInstance->Users->local_users.erase(x);
605 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
611 CullResult FakeUser::cull()
613 // Fake users don't quit, they just get culled.
618 void User::Oper(OperInfo* info)
620 if (this->IsModeSet('o'))
623 this->modes[UM_OPERATOR] = 1;
625 this->WriteServ("MODE %s :+o", this->nick.c_str());
626 FOREACH_MOD(I_OnOper, OnOper(this, info->name));
628 std::string opername;
629 if (info->oper_block)
630 opername = info->oper_block->getString("name");
634 LocalUser* l = IS_LOCAL(this);
635 std::string vhost = oper->getConfig("vhost");
637 l->ChangeDisplayedHost(vhost.c_str());
638 std::string opClass = oper->getConfig("class");
639 if (!opClass.empty())
641 l->SetClass(opClass);
646 ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s (using oper '%s')",
647 nick.c_str(), ident.c_str(), host.c_str(), oper->NameStr(), opername.c_str());
648 this->WriteNumeric(381, "%s :You are now %s %s", nick.c_str(), strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->NameStr());
650 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());
651 ServerInstance->Users->all_opers.push_back(this);
653 // Expand permissions from config for faster lookup
657 FOREACH_MOD(I_OnPostOper,OnPostOper(this, oper->name, opername));
660 void OperInfo::init()
662 AllowedOperCommands.clear();
663 AllowedPrivs.clear();
664 AllowedUserModes.reset();
665 AllowedChanModes.reset();
666 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
668 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
670 ConfigTag* tag = *iter;
671 std::string mycmd, mypriv;
672 /* Process commands */
673 irc::spacesepstream CommandList(tag->getString("commands"));
674 while (CommandList.GetToken(mycmd))
676 AllowedOperCommands.insert(mycmd);
679 irc::spacesepstream PrivList(tag->getString("privs"));
680 while (PrivList.GetToken(mypriv))
682 AllowedPrivs.insert(mypriv);
685 for (unsigned char* c = (unsigned char*)tag->getString("usermodes").c_str(); *c; ++c)
689 this->AllowedUserModes.set();
693 this->AllowedUserModes[*c - 'A'] = true;
697 for (unsigned char* c = (unsigned char*)tag->getString("chanmodes").c_str(); *c; ++c)
701 this->AllowedChanModes.set();
705 this->AllowedChanModes[*c - 'A'] = true;
717 * unset their oper type (what IS_OPER checks).
718 * note, order is important - this must come before modes as -o attempts
719 * to call UnOper. -- w00t
724 /* Remove all oper only modes from the user when the deoper - Bug #466*/
725 std::string moderemove("-");
727 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
729 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
730 if (mh && mh->NeedsOper())
731 moderemove += letter;
735 std::vector<std::string> parameters;
736 parameters.push_back(this->nick);
737 parameters.push_back(moderemove);
739 ServerInstance->Parser->CallHandler("MODE", parameters, this);
741 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
742 ServerInstance->Users->all_opers.remove(this);
744 this->modes[UM_OPERATOR] = 0;
747 /* adds or updates an entry in the whowas list */
748 void User::AddToWhoWas()
750 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
753 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
760 * Check class restrictions
762 void LocalUser::CheckClass()
764 ConnectClass* a = this->MyClass;
768 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
770 else if (a->type == CC_DENY)
772 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
775 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
777 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
778 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
781 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
783 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
784 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
788 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
791 bool User::CheckLines(bool doZline)
793 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
797 for (int n = 0; check[n]; ++n)
799 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
812 void LocalUser::FullConnect()
814 ServerInstance->stats->statsConnects++;
815 this->idle_lastmsg = ServerInstance->Time();
818 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
819 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
820 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
821 * Don't remove this! -- w00t
825 /* Check the password, if one is required by the user's connect class.
826 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
828 if (!MyClass->pass.empty())
830 if (ServerInstance->PassCompare(this, MyClass->pass.c_str(), password.c_str(), MyClass->hash.c_str()))
832 ServerInstance->Users->QuitUser(this, "Invalid password");
837 if (this->CheckLines())
840 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
841 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());
842 this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-2.0",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
843 this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
844 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());
846 ServerInstance->Config->Send005(this);
847 this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
853 if (ServerInstance->Users->unregistered_count)
854 ServerInstance->Users->unregistered_count--;
856 /* Trigger LUSERS output, give modules a chance too */
857 ModResult MOD_RESULT;
858 std::string command("LUSERS");
859 std::vector<std::string> parameters;
860 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, "LUSERS"));
862 ServerInstance->CallCommandHandler(command, parameters, this);
865 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
866 * for a user that doesn't exist yet.
868 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
870 this->registered = REG_ALL;
872 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
874 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]",
875 this->GetServerPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
876 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
877 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
880 /** User::UpdateNick()
881 * re-allocates a nick in the user_hash after they change nicknames,
882 * returns a pointer to the new user as it may have moved
884 User* User::UpdateNickHash(const char* New)
886 //user_hash::iterator newnick;
887 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
889 if (!irc::string(this->nick.c_str()).compare(New))
890 return oldnick->second;
892 if (oldnick == ServerInstance->Users->clientlist->end())
893 return NULL; /* doesnt exist */
895 User* olduser = oldnick->second;
896 ServerInstance->Users->clientlist->erase(oldnick);
897 (*(ServerInstance->Users->clientlist))[New] = olduser;
901 void User::InvalidateCache()
903 /* Invalidate cache */
904 cached_fullhost.clear();
905 cached_hostip.clear();
906 cached_makehost.clear();
907 cached_fullrealhost.clear();
910 bool User::ForceNickChange(const char* newnick)
912 ModResult MOD_RESULT;
914 this->InvalidateCache();
916 ServerInstance->NICKForced.set(this, 1);
917 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
918 ServerInstance->NICKForced.set(this, 0);
920 if (MOD_RESULT == MOD_RES_DENY)
922 ServerInstance->stats->statsCollisions++;
926 std::deque<classbase*> dummy;
927 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
928 if (nickhandler) // wtfbbq, when would this not be here
930 std::vector<std::string> parameters;
931 parameters.push_back(newnick);
932 ServerInstance->NICKForced.set(this, 1);
933 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
934 ServerInstance->NICKForced.set(this, 0);
938 // Unreachable, we hope
942 int LocalUser::GetServerPort()
944 switch (this->server_sa.sa.sa_family)
947 return htons(this->server_sa.in6.sin6_port);
949 return htons(this->server_sa.in4.sin_port);
954 const char* User::GetIPString()
957 if (cachedip.empty())
959 irc::sockets::satoap(client_sa, cachedip, port);
960 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
961 if (cachedip.c_str()[0] == ':')
962 cachedip.insert(0,1,'0');
965 return cachedip.c_str();
968 irc::sockets::cidr_mask User::GetCIDRMask()
971 switch (client_sa.sa.sa_family)
974 range = ServerInstance->Config->c_ipv6_range;
977 range = ServerInstance->Config->c_ipv4_range;
980 return irc::sockets::cidr_mask(client_sa, range);
983 bool User::SetClientIP(const char* sip)
986 return irc::sockets::aptosa(sip, 0, client_sa);
989 static std::string wide_newline("\r\n");
991 void User::Write(const std::string& text)
995 void User::Write(const char *text, ...)
999 void LocalUser::Write(const std::string& text)
1001 if (!ServerInstance->SE->BoundsCheckFd(&eh))
1004 if (text.length() > MAXBUF - 2)
1006 // this should happen rarely or never. Crop the string at 512 and try again.
1007 std::string try_again = text.substr(0, MAXBUF - 2);
1012 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%s] O %s", uuid.c_str(), text.c_str());
1014 eh.AddWriteBuf(text);
1015 eh.AddWriteBuf(wide_newline);
1017 ServerInstance->stats->statsSent += text.length() + 2;
1018 this->bytes_out += text.length() + 2;
1024 void LocalUser::Write(const char *text, ...)
1027 char textbuffer[MAXBUF];
1029 va_start(argsPtr, text);
1030 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1033 this->Write(std::string(textbuffer));
1036 void User::WriteServ(const std::string& text)
1038 this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1042 * Same as Write(), except `text' is prefixed with `:server.name '.
1044 void User::WriteServ(const char* text, ...)
1047 char textbuffer[MAXBUF];
1049 va_start(argsPtr, text);
1050 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1053 this->WriteServ(std::string(textbuffer));
1057 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1060 char textbuffer[MAXBUF];
1062 va_start(argsPtr, text);
1063 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1066 this->WriteNumeric(numeric, std::string(textbuffer));
1069 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1071 char textbuffer[MAXBUF];
1072 ModResult MOD_RESULT;
1074 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1076 if (MOD_RESULT == MOD_RES_DENY)
1079 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1080 this->Write(std::string(textbuffer));
1083 void User::WriteFrom(User *user, const std::string &text)
1087 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1089 this->Write(std::string(tb));
1093 /* write text from an originating user to originating user */
1095 void User::WriteFrom(User *user, const char* text, ...)
1098 char textbuffer[MAXBUF];
1100 va_start(argsPtr, text);
1101 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1104 this->WriteFrom(user, std::string(textbuffer));
1108 /* write text to an destination user from a source user (e.g. user privmsg) */
1110 void User::WriteTo(User *dest, const char *data, ...)
1112 char textbuffer[MAXBUF];
1115 va_start(argsPtr, data);
1116 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1119 this->WriteTo(dest, std::string(textbuffer));
1122 void User::WriteTo(User *dest, const std::string &data)
1124 dest->WriteFrom(this, data);
1127 void User::WriteCommon(const char* text, ...)
1129 char textbuffer[MAXBUF];
1132 if (this->registered != REG_ALL || quitting)
1135 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1137 va_start(argsPtr, text);
1138 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1141 this->WriteCommonRaw(std::string(textbuffer), true);
1144 void User::WriteCommonExcept(const char* text, ...)
1146 char textbuffer[MAXBUF];
1149 if (this->registered != REG_ALL || quitting)
1152 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1154 va_start(argsPtr, text);
1155 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1158 this->WriteCommonRaw(std::string(textbuffer), false);
1161 void User::WriteCommonRaw(const std::string &line, bool include_self)
1163 if (this->registered != REG_ALL || quitting)
1166 uniq_id_t uniq_id = ++already_sent;
1168 UserChanList include_c(chans);
1169 std::map<User*,bool> exceptions;
1171 exceptions[this] = include_self;
1173 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1175 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1177 LocalUser* u = IS_LOCAL(i->first);
1178 if (u && !u->quitting)
1180 already_sent[u->GetFd()] = uniq_id;
1185 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1188 const UserMembList* ulist = c->GetUsers();
1189 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1191 LocalUser* u = IS_LOCAL(i->first);
1192 if (u && !u->quitting && already_sent[u->GetFd()] != uniq_id)
1194 already_sent[u->GetFd()] = uniq_id;
1201 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1206 if (this->registered != REG_ALL)
1209 uniq_id_t uniq_id = ++already_sent;
1211 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1212 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1213 std::string out1 = tb1;
1214 std::string out2 = tb2;
1216 UserChanList include_c(chans);
1217 std::map<User*,bool> exceptions;
1219 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1221 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1223 LocalUser* u = IS_LOCAL(i->first);
1224 if (u && !u->quitting)
1226 already_sent[u->GetFd()] = uniq_id;
1228 u->Write(IS_OPER(u) ? out2 : out1);
1231 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1233 const UserMembList* ulist = (*v)->GetUsers();
1234 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1236 LocalUser* u = IS_LOCAL(i->first);
1237 if (u && !u->quitting && (already_sent[u->GetFd()] != uniq_id))
1239 already_sent[u->GetFd()] = uniq_id;
1240 u->Write(IS_OPER(u) ? out2 : out1);
1246 void LocalUser::SendText(const std::string& line)
1251 void RemoteUser::SendText(const std::string& line)
1253 ServerInstance->PI->PushToClient(this, line);
1256 void FakeUser::SendText(const std::string& line)
1260 void User::SendText(const char *text, ...)
1265 va_start(argsPtr, text);
1266 vsnprintf(line, MAXBUF, text, argsPtr);
1269 SendText(std::string(line));
1272 void User::SendText(const std::string &LinePrefix, std::stringstream &TextStream)
1275 int start_pos = LinePrefix.length();
1276 int pos = start_pos;
1277 memcpy(line, LinePrefix.data(), pos);
1279 while (TextStream >> Word)
1281 int len = Word.length();
1282 if (pos + len + 12 > MAXBUF)
1285 SendText(std::string(line));
1289 memcpy(line + pos + 1, Word.data(), len);
1293 SendText(std::string(line));
1296 /* return 0 or 1 depending if users u and u2 share one or more common channels
1297 * (used by QUIT, NICK etc which arent channel specific notices)
1299 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1300 * the first users channels then the second users channels within the outer loop,
1301 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1302 * all possible iterations). However this new function instead checks against the
1303 * channel's userlist in the inner loop which is a std::map<User*,User*>
1304 * and saves us time as we already know what pointer value we are after.
1305 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1306 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1308 bool User::SharesChannelWith(User *other)
1310 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1314 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1316 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1317 * by replacing it with a map::find which *should* be more efficient
1319 if ((*i)->HasUser(other))
1325 bool User::ChangeName(const char* gecos)
1327 if (!this->fullname.compare(gecos))
1332 ModResult MOD_RESULT;
1333 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (IS_LOCAL(this),gecos));
1334 if (MOD_RESULT == MOD_RES_DENY)
1336 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1338 this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1343 void User::DoHostCycle(const std::string &quitline)
1345 char buffer[MAXBUF];
1347 if (!ServerInstance->Config->CycleHosts)
1350 uniq_id_t silent_id = ++already_sent;
1351 uniq_id_t seen_id = ++already_sent;
1353 UserChanList include_c(chans);
1354 std::map<User*,bool> exceptions;
1356 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1358 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1360 LocalUser* u = IS_LOCAL(i->first);
1361 if (u && !u->quitting)
1365 already_sent[u->GetFd()] = seen_id;
1370 already_sent[u->GetFd()] = silent_id;
1374 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1377 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1378 std::string joinline(buffer);
1379 Membership* memb = c->GetUser(this);
1380 std::string modeline = memb->modes;
1381 if (modeline.length() > 0)
1383 for(unsigned int i=0; i < memb->modes.length(); i++)
1384 modeline.append(" ").append(nick);
1385 snprintf(buffer, MAXBUF, ":%s MODE %s +%s", GetFullHost().c_str(), c->name.c_str(), modeline.c_str());
1389 const UserMembList *ulist = c->GetUsers();
1390 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1392 LocalUser* u = IS_LOCAL(i->first);
1393 if (u == NULL || u == this)
1395 if (already_sent[u->GetFd()] == silent_id)
1398 if (already_sent[u->GetFd()] != seen_id)
1401 already_sent[u->GetFd()] = seen_id;
1404 if (modeline.length() > 0)
1410 bool User::ChangeDisplayedHost(const char* shost)
1417 ModResult MOD_RESULT;
1418 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (IS_LOCAL(this),shost));
1419 if (MOD_RESULT == MOD_RES_DENY)
1423 FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1425 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1427 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1428 this->dhost.assign(shost, 0, 64);
1430 this->InvalidateCache();
1432 this->DoHostCycle(quitstr);
1435 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1440 bool User::ChangeIdent(const char* newident)
1442 if (this->ident == newident)
1445 FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1447 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1449 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1451 this->InvalidateCache();
1453 this->DoHostCycle(quitstr);
1458 void User::SendAll(const char* command, const char* text, ...)
1460 char textbuffer[MAXBUF];
1461 char formatbuffer[MAXBUF];
1464 va_start(argsPtr, text);
1465 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1468 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1469 std::string fmt = formatbuffer;
1471 for (std::vector<LocalUser*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1478 std::string User::ChannelList(User* source, bool spy)
1482 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1485 /* If the target is the sender, neither +p nor +s is set, or
1486 * the channel contains the user, it is not a spy channel
1488 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1489 list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1495 void User::SplitChanList(User* dest, const std::string &cl)
1498 std::ostringstream prefix;
1499 std::string::size_type start, pos, length;
1501 prefix << this->nick << " " << dest->nick << " :";
1502 line = prefix.str();
1503 int namelen = ServerInstance->Config->ServerName.length() + 6;
1505 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1507 length = (pos == std::string::npos) ? cl.length() : pos;
1509 if (line.length() + namelen + length - start > 510)
1511 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1512 line = prefix.str();
1515 if(pos == std::string::npos)
1517 line.append(cl.substr(start, length - start));
1522 line.append(cl.substr(start, length - start + 1));
1528 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1533 * Sets a user's connection class.
1534 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1535 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1536 * then their ip will be taken as 'priority' anyway, so for example,
1537 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1539 void LocalUser::SetClass(const std::string &explicit_name)
1541 ConnectClass *found = NULL;
1543 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1545 if (!explicit_name.empty())
1547 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1549 ConnectClass* c = *i;
1551 if (explicit_name == c->name)
1553 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1560 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1562 ConnectClass* c = *i;
1564 if (c->type == CC_ALLOW)
1566 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->host.c_str(), c->GetPort(), c->GetName().c_str());
1570 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1573 /* check if host matches.. */
1574 if (c->GetHost().length() && !InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1575 !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1577 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1582 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1583 * because we should attempt to find another class if this one doesn't match us. -- w00t
1585 if (c->limit && (c->GetReferenceCount() >= c->limit))
1587 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1591 /* if it requires a port ... */
1594 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1596 /* and our port doesn't match, fail. */
1597 if (this->GetServerPort() != c->GetPort())
1599 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetServerPort());
1604 /* we stop at the first class that meets ALL critera. */
1611 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1619 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1620 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1621 * then their ip will be taken as 'priority' anyway, so for example,
1622 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1624 ConnectClass* LocalUser::GetClass()
1629 ConnectClass* User::GetClass()
1634 void User::PurgeEmptyChannels()
1636 // firstly decrement the count on each channel
1637 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1646 void User::ShowMOTD()
1648 if (!ServerInstance->Config->MOTD.size())
1650 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1653 this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName.c_str());
1655 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1656 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1658 this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1661 void User::ShowRULES()
1663 if (!ServerInstance->Config->RULES.size())
1665 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1669 this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
1671 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1672 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1674 this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1677 const std::string& FakeUser::GetFullHost()
1679 if (!ServerInstance->Config->HideWhoisServer.empty())
1680 return ServerInstance->Config->HideWhoisServer;
1684 const std::string& FakeUser::GetFullRealHost()
1686 if (!ServerInstance->Config->HideWhoisServer.empty())
1687 return ServerInstance->Config->HideWhoisServer;
1691 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1692 : config(tag), type(t), name("unnamed"), registration_timeout(0), host(mask),
1693 pingtime(0), pass(""), hash(""), softsendqmax(0), hardsendqmax(0),
1694 recvqmax(0), penaltythreshold(0), maxlocal(0), maxglobal(0), maxchans(0), port(0), limit(0)
1698 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1699 : config(tag), type(t), name("unnamed"),
1700 registration_timeout(parent.registration_timeout), host(mask),
1701 pingtime(parent.pingtime), pass(parent.pass), hash(parent.hash),
1702 softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax),
1703 recvqmax(parent.recvqmax), penaltythreshold(parent.penaltythreshold), maxlocal(parent.maxlocal),
1704 maxglobal(parent.maxglobal), maxchans(parent.maxchans),
1705 port(parent.port), limit(parent.limit)
1709 void ConnectClass::Update(const ConnectClass* src)
1712 registration_timeout = src->registration_timeout;
1714 pingtime = src->pingtime;
1717 softsendqmax = src->softsendqmax;
1718 hardsendqmax = src->hardsendqmax;
1719 recvqmax = src->recvqmax;
1720 penaltythreshold = src->penaltythreshold;
1721 maxlocal = src->maxlocal;
1722 maxglobal = src->maxglobal;