1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $Core: libIRCDusers */
18 #include "socketengine.h"
22 #include "commands/cmd_whowas.h"
24 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
26 /* XXX: Used for speeding up WriteCommon operations */
27 unsigned long uniq_id = 0;
29 std::string User::ProcessNoticeMasks(const char *sm)
31 bool adding = true, oldadding = false;
46 for (unsigned char d = 'A'; d <= 'z'; d++)
48 if (ServerInstance->SNO->IsEnabled(d))
50 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
52 if ((oldadding != adding) || (!output.length()))
53 output += (adding ? '+' : '-');
55 this->SetNoticeMask(d, adding);
64 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
66 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
68 if ((oldadding != adding) || (!output.length()))
69 output += (adding ? '+' : '-');
71 this->SetNoticeMask(*c, adding);
86 void User::StartDNSLookup()
91 const char* ip = this->GetIPString();
93 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
94 if (!strncmp(ip, "0::ffff:", 8))
95 res_reverse = new UserResolver(this->ServerInstance, this, ip + 8, DNS_QUERY_PTR4, cached);
97 res_reverse = new UserResolver(this->ServerInstance, this, ip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
99 this->ServerInstance->AddResolver(res_reverse, cached);
101 catch (CoreException& e)
103 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
107 bool User::IsNoticeMaskSet(unsigned char sm)
109 return (snomasks[sm-65]);
112 void User::SetNoticeMask(unsigned char sm, bool value)
114 snomasks[sm-65] = value;
117 const char* User::FormatNoticeMasks()
119 static char data[MAXBUF];
122 for (int n = 0; n < 64; n++)
125 data[offset++] = n+65;
134 bool User::IsModeSet(unsigned char m)
136 return (modes[m-65]);
139 void User::SetMode(unsigned char m, bool value)
144 const char* User::FormatModes()
146 static char data[MAXBUF];
148 for (int n = 0; n < 64; n++)
151 data[offset++] = n+65;
157 void User::DecrementModes()
159 ServerInstance->Log(DEBUG,"DecrementModes()");
160 for (unsigned char n = 'A'; n <= 'z'; n++)
164 ServerInstance->Log(DEBUG,"DecrementModes() found mode %c", n);
165 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
168 ServerInstance->Log(DEBUG,"Found handler %c and call ChangeCount", n);
175 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
177 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
178 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
179 reset_due = ServerInstance->Time();
180 age = ServerInstance->Time(true);
182 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
183 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
184 OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
189 res_forward = res_reverse = NULL;
193 AllowedOperCommands = NULL;
196 memset(modes,0,sizeof(modes));
197 memset(snomasks,0,sizeof(snomasks));
198 /* Invalidate cache */
199 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
202 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
204 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
206 ServerInstance->Log(DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
208 user_hash::iterator finduuid = Instance->uuidlist->find(uuid);
209 if (finduuid == Instance->uuidlist->end())
210 (*Instance->uuidlist)[uuid] = this;
212 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
217 /* NULL for remote users :) */
220 this->MyClass->RefCount--;
221 ServerInstance->Log(DEBUG, "User destructor -- connect refcount now: %u", this->MyClass->RefCount);
223 if (this->AllowedOperCommands)
225 delete AllowedOperCommands;
226 AllowedOperCommands = NULL;
229 this->InvalidateCache();
230 this->DecrementModes();
234 ServerInstance->Users->RemoveCloneCounts(this);
236 if (this->GetProtocolFamily() == AF_INET)
238 delete (sockaddr_in*)ip;
240 #ifdef SUPPORT_IP6LINKS
243 delete (sockaddr_in6*)ip;
248 ServerInstance->uuidlist->erase(uuid);
251 char* User::MakeHost()
253 if (this->cached_makehost)
254 return this->cached_makehost;
257 /* This is much faster than snprintf */
259 for(char* n = ident; *n; n++)
262 for(char* n = host; *n; n++)
266 this->cached_makehost = strdup(nhost);
268 return this->cached_makehost;
271 char* User::MakeHostIP()
273 if (this->cached_hostip)
274 return this->cached_hostip;
277 /* This is much faster than snprintf */
279 for(char* n = ident; *n; n++)
282 for(const char* n = this->GetIPString(); *n; n++)
286 this->cached_hostip = strdup(ihost);
288 return this->cached_hostip;
291 void User::CloseSocket()
293 ServerInstance->SE->Shutdown(this, 2);
294 ServerInstance->SE->Close(this);
297 char* User::GetFullHost()
299 if (this->cached_fullhost)
300 return this->cached_fullhost;
304 for(char* n = nick; *n; n++)
307 for(char* n = ident; *n; n++)
310 for(char* n = dhost; *n; n++)
314 this->cached_fullhost = strdup(result);
316 return this->cached_fullhost;
319 char* User::MakeWildHost()
321 static char nresult[MAXBUF];
323 *t++ = '*'; *t++ = '!';
324 *t++ = '*'; *t++ = '@';
325 for(char* n = dhost; *n; n++)
331 int User::ReadData(void* buffer, size_t size)
336 return read(this->fd, buffer, size);
338 return recv(this->fd, (char*)buffer, size, 0);
346 char* User::GetFullRealHost()
348 if (this->cached_fullrealhost)
349 return this->cached_fullrealhost;
351 char fresult[MAXBUF];
353 for(char* n = nick; *n; n++)
356 for(char* n = ident; *n; n++)
359 for(char* n = host; *n; n++)
363 this->cached_fullrealhost = strdup(fresult);
365 return this->cached_fullrealhost;
368 bool User::IsInvited(const irc::string &channel)
370 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
380 InvitedList* User::GetInviteList()
385 void User::InviteTo(const irc::string &channel)
387 invites.push_back(channel);
390 void User::RemoveInvite(const irc::string &channel)
392 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
402 bool User::HasPermission(const std::string &command)
405 * users on remote servers can completely bypass all permissions based checks.
406 * This prevents desyncs when one server has different type/class tags to another.
407 * That having been said, this does open things up to the possibility of source changes
408 * allowing remote kills, etc - but if they have access to the src, they most likely have
409 * access to the conf - so it's an end to a means either way.
414 // are they even an oper at all?
420 if (!AllowedOperCommands)
423 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
425 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
431 /** NOTE: We cannot pass a const reference to this method.
432 * The string is changed by the workings of the method,
433 * so that if we pass const ref, we end up copying it to
434 * something we can change anyway. Makes sense to just let
435 * the compiler do that copy for us.
437 bool User::AddBuffer(std::string a)
441 std::string::size_type i = a.rfind('\r');
443 while (i != std::string::npos)
452 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
454 this->SetWriteError("RecvQ exceeded");
455 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
464 ServerInstance->Log(DEBUG,"Exception in User::AddBuffer()");
469 bool User::BufferIsReady()
471 return (recvq.find('\n') != std::string::npos);
474 void User::ClearBuffer()
479 std::string User::GetBuffer()
486 /* Strip any leading \r or \n off the string.
487 * Usually there are only one or two of these,
488 * so its is computationally cheap to do.
490 std::string::iterator t = recvq.begin();
491 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
497 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
499 /* Find the first complete line, return it as the
500 * result, and leave the recvq as whats left
504 std::string ret = std::string(recvq.begin(), x);
505 recvq.erase(recvq.begin(), x + 1);
514 ServerInstance->Log(DEBUG,"Exception in User::GetBuffer()");
519 void User::AddWriteBuf(const std::string &data)
521 if (*this->GetWriteError())
524 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
527 * Fix by brain - Set the error text BEFORE calling, because
528 * if we dont it'll recursively call here over and over again trying
529 * to repeatedly add the text to the sendq!
531 this->SetWriteError("SendQ exceeded");
532 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
538 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
539 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
545 this->SetWriteError("SendQ exceeded");
546 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ got an exception",this->nick);
550 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
551 void User::FlushWriteBuf()
555 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
559 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
561 int old_sendq_length = sendq.length();
562 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
568 /* The socket buffer is full. This isnt fatal,
571 this->ServerInstance->SE->WantWrite(this);
575 /* Fatal error, set write error and bail
577 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
583 /* advance the queue */
585 this->sendq = this->sendq.substr(n_sent);
586 /* update the user's stats counters */
587 this->bytes_out += n_sent;
589 if (n_sent != old_sendq_length)
590 this->ServerInstance->SE->WantWrite(this);
597 ServerInstance->Log(DEBUG,"Exception in User::FlushWriteBuf()");
600 if (this->sendq.empty())
602 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
606 void User::SetWriteError(const std::string &error)
610 // don't try to set the error twice, its already set take the first string.
611 if (this->WriteError.empty())
612 this->WriteError = error;
617 ServerInstance->Log(DEBUG,"Exception in User::SetWriteError()");
621 const char* User::GetWriteError()
623 return this->WriteError.c_str();
626 void User::Oper(const std::string &opertype, const std::string &opername)
634 this->modes[UM_OPERATOR] = 1;
635 this->WriteServ("MODE %s :+o", this->nick);
636 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
637 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
638 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
639 ServerInstance->all_opers.push_back(this);
641 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
642 if (iter_opertype != ServerInstance->Config->opertypes.end())
645 if (AllowedOperCommands)
646 AllowedOperCommands->clear();
648 AllowedOperCommands = new std::map<std::string, bool>;
650 char* Classes = strdup(iter_opertype->second);
651 char* myclass = strtok_r(Classes," ",&savept);
654 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
655 if (iter_operclass != ServerInstance->Config->operclass.end())
657 char* CommandList = strdup(iter_operclass->second);
658 mycmd = strtok_r(CommandList," ",&savept2);
661 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
662 mycmd = strtok_r(NULL," ",&savept2);
666 myclass = strtok_r(NULL," ",&savept);
671 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
676 ServerInstance->Log(DEBUG,"Exception in User::Oper()");
686 // unset their oper type (what IS_OPER checks), and remove +o
688 this->modes[UM_OPERATOR] = 0;
690 // remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404
691 ServerInstance->all_opers.remove(this);
693 if (AllowedOperCommands)
695 delete AllowedOperCommands;
696 AllowedOperCommands = NULL;
703 ServerInstance->Log(DEBUG,"Exception in User::UnOper()");
707 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
709 Instance->Log(DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
710 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
711 user->quietquit = false;
712 user->quitmsg = quitreason;
713 user->operquitmsg = operreason;
714 Instance->GlobalCulls.AddItem(user);
717 /* adds or updates an entry in the whowas list */
718 void User::AddToWhoWas()
720 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
723 std::deque<classbase*> params;
724 params.push_back(this);
725 whowas_command->HandleInternal(WHOWAS_ADD, params);
730 * Check class restrictions
732 void User::CheckClass()
734 ConnectClass* a = this->MyClass;
736 if ((!a) || (a->GetType() == CC_DENY))
738 User::QuitUser(ServerInstance, this, "Unauthorised connection");
741 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
743 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
744 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
747 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
749 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
750 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
754 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
755 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
756 this->MaxChans = a->GetMaxChans();
759 void User::FullConnect()
761 ServerInstance->stats->statsConnects++;
762 this->idle_lastmsg = ServerInstance->Time();
765 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
766 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
767 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
768 * Don't remove this! -- w00t
772 /* Check the password, if one is required by the user's connect class.
773 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
775 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
777 User::QuitUser(ServerInstance, this, "Invalid password");
783 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
791 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
800 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
801 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
802 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
803 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
804 this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
806 ServerInstance->Config->Send005(this);
808 this->WriteServ("042 %s %s :your unique ID", this->nick, this->uuid);
814 if (ServerInstance->unregistered_count)
815 ServerInstance->unregistered_count--;
817 /* Trigger LUSERS output, give modules a chance too */
819 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
821 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
824 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
825 * for a user that doesn't exist yet.
827 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
829 this->registered = REG_ALL;
831 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
833 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString(), this->fullname);
835 ServerInstance->Log(DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
836 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
839 /** User::UpdateNick()
840 * re-allocates a nick in the user_hash after they change nicknames,
841 * returns a pointer to the new user as it may have moved
843 User* User::UpdateNickHash(const char* New)
847 //user_hash::iterator newnick;
848 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
850 if (!strcasecmp(this->nick,New))
851 return oldnick->second;
853 if (oldnick == ServerInstance->clientlist->end())
854 return NULL; /* doesnt exist */
856 User* olduser = oldnick->second;
857 (*(ServerInstance->clientlist))[New] = olduser;
858 ServerInstance->clientlist->erase(oldnick);
864 ServerInstance->Log(DEBUG,"Exception in User::UpdateNickHash()");
869 void User::InvalidateCache()
871 /* Invalidate cache */
873 free(cached_fullhost);
877 free(cached_makehost);
878 if (cached_fullrealhost)
879 free(cached_fullrealhost);
880 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
883 bool User::ForceNickChange(const char* newnick)
889 this->InvalidateCache();
891 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
895 ServerInstance->stats->statsCollisions++;
899 if (ServerInstance->XLines->MatchesLine("Q",newnick))
901 ServerInstance->stats->statsCollisions++;
905 if (this->registered == REG_ALL)
907 std::deque<classbase*> dummy;
908 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
911 nickhandler->HandleInternal(1, dummy);
912 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
913 nickhandler->HandleInternal(0, dummy);
922 ServerInstance->Log(DEBUG,"Exception in User::ForceNickChange()");
927 void User::SetSockAddr(int protocol_family, const char* ip, int port)
929 switch (protocol_family)
931 #ifdef SUPPORT_IP6LINKS
934 sockaddr_in6* sin = new sockaddr_in6;
935 sin->sin6_family = AF_INET6;
936 sin->sin6_port = port;
937 inet_pton(AF_INET6, ip, &sin->sin6_addr);
938 this->ip = (sockaddr*)sin;
944 sockaddr_in* sin = new sockaddr_in;
945 sin->sin_family = AF_INET;
946 sin->sin_port = port;
947 inet_pton(AF_INET, ip, &sin->sin_addr);
948 this->ip = (sockaddr*)sin;
952 ServerInstance->Log(DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
959 if (this->ip == NULL)
962 switch (this->GetProtocolFamily())
964 #ifdef SUPPORT_IP6LINKS
967 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
968 return sin->sin6_port;
974 sockaddr_in* sin = (sockaddr_in*)this->ip;
975 return sin->sin_port;
984 int User::GetProtocolFamily()
986 if (this->ip == NULL)
989 sockaddr_in* sin = (sockaddr_in*)this->ip;
990 return sin->sin_family;
994 * XXX the duplication here is horrid..
995 * do we really need two methods doing essentially the same thing?
997 const char* User::GetIPString()
999 static char buf[1024];
1001 if (this->ip == NULL)
1004 switch (this->GetProtocolFamily())
1006 #ifdef SUPPORT_IP6LINKS
1009 static char temp[1024];
1011 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1012 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1013 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1016 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1026 sockaddr_in* sin = (sockaddr_in*)this->ip;
1027 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1037 /** NOTE: We cannot pass a const reference to this method.
1038 * The string is changed by the workings of the method,
1039 * so that if we pass const ref, we end up copying it to
1040 * something we can change anyway. Makes sense to just let
1041 * the compiler do that copy for us.
1043 void User::Write(std::string text)
1045 if (!ServerInstance->SE->BoundsCheckFd(this))
1050 /* ServerInstance->Log(DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1051 * WARNING: The above debug line is VERY loud, do NOT
1052 * enable it till we have a good way of filtering it
1053 * out of the logs (e.g. 1.2 would be good).
1055 text.append("\r\n");
1059 ServerInstance->Log(DEBUG,"Exception in User::Write() std::string::append");
1063 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1067 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1068 * implement their own buffering mechanisms
1070 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1072 catch (CoreException& modexcept)
1074 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1079 this->AddWriteBuf(text);
1081 ServerInstance->stats->statsSent += text.length();
1082 this->ServerInstance->SE->WantWrite(this);
1087 void User::Write(const char *text, ...)
1090 char textbuffer[MAXBUF];
1092 va_start(argsPtr, text);
1093 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1096 this->Write(std::string(textbuffer));
1099 void User::WriteServ(const std::string& text)
1101 char textbuffer[MAXBUF];
1103 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1104 this->Write(std::string(textbuffer));
1108 * Same as Write(), except `text' is prefixed with `:server.name '.
1110 void User::WriteServ(const char* text, ...)
1113 char textbuffer[MAXBUF];
1115 va_start(argsPtr, text);
1116 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1119 this->WriteServ(std::string(textbuffer));
1123 void User::WriteFrom(User *user, const std::string &text)
1127 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1129 this->Write(std::string(tb));
1133 /* write text from an originating user to originating user */
1135 void User::WriteFrom(User *user, const char* text, ...)
1138 char textbuffer[MAXBUF];
1140 va_start(argsPtr, text);
1141 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1144 this->WriteFrom(user, std::string(textbuffer));
1148 /* write text to an destination user from a source user (e.g. user privmsg) */
1150 void User::WriteTo(User *dest, const char *data, ...)
1152 char textbuffer[MAXBUF];
1155 va_start(argsPtr, data);
1156 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1159 this->WriteTo(dest, std::string(textbuffer));
1162 void User::WriteTo(User *dest, const std::string &data)
1164 dest->WriteFrom(this, data);
1168 void User::WriteCommon(const char* text, ...)
1170 char textbuffer[MAXBUF];
1173 if (this->registered != REG_ALL)
1176 va_start(argsPtr, text);
1177 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1180 this->WriteCommon(std::string(textbuffer));
1183 void User::WriteCommon(const std::string &text)
1187 bool sent_to_at_least_one = false;
1190 if (this->registered != REG_ALL)
1195 /* We dont want to be doing this n times, just once */
1196 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1197 std::string out = tb;
1199 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1201 CUList* ulist = v->first->GetUsers();
1202 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1204 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1206 already_sent[i->first->fd] = uniq_id;
1207 i->first->Write(out);
1208 sent_to_at_least_one = true;
1214 * if the user was not in any channels, no users will receive the text. Make sure the user
1215 * receives their OWN message for WriteCommon
1217 if (!sent_to_at_least_one)
1219 this->Write(std::string(tb));
1225 ServerInstance->Log(DEBUG,"Exception in User::WriteCommon()");
1230 /* write a formatted string to all users who share at least one common
1231 * channel, NOT including the source user e.g. for use in QUIT
1234 void User::WriteCommonExcept(const char* text, ...)
1236 char textbuffer[MAXBUF];
1239 va_start(argsPtr, text);
1240 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1243 this->WriteCommonExcept(std::string(textbuffer));
1246 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1251 if (this->registered != REG_ALL)
1255 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1256 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1257 std::string out1 = tb1;
1258 std::string out2 = tb2;
1260 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1262 CUList *ulist = v->first->GetUsers();
1263 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1265 if (this != i->first)
1267 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1269 already_sent[i->first->fd] = uniq_id;
1270 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1277 void User::WriteCommonExcept(const std::string &text)
1282 if (this->registered != REG_ALL)
1286 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1289 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1291 CUList *ulist = v->first->GetUsers();
1292 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1294 if (this != i->first)
1296 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1298 already_sent[i->first->fd] = uniq_id;
1299 i->first->Write(out1);
1307 void User::WriteWallOps(const std::string &text)
1309 if (!IS_OPER(this) && IS_LOCAL(this))
1312 std::string wallop("WALLOPS :");
1313 wallop.append(text);
1315 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1318 if (t->IsModeSet('w'))
1319 this->WriteTo(t,wallop);
1323 void User::WriteWallOps(const char* text, ...)
1325 char textbuffer[MAXBUF];
1328 va_start(argsPtr, text);
1329 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1332 this->WriteWallOps(std::string(textbuffer));
1335 /* return 0 or 1 depending if users u and u2 share one or more common channels
1336 * (used by QUIT, NICK etc which arent channel specific notices)
1338 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1339 * the first users channels then the second users channels within the outer loop,
1340 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1341 * all possible iterations). However this new function instead checks against the
1342 * channel's userlist in the inner loop which is a std::map<User*,User*>
1343 * and saves us time as we already know what pointer value we are after.
1344 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1345 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1347 bool User::SharesChannelWith(User *other)
1349 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1353 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1355 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1356 * by replacing it with a map::find which *should* be more efficient
1358 if (i->first->HasUser(other))
1364 bool User::ChangeName(const char* gecos)
1366 if (!strcmp(gecos, this->fullname))
1372 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1375 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1377 strlcpy(this->fullname,gecos,MAXGECOS+1);
1382 bool User::ChangeDisplayedHost(const char* host)
1384 if (!strcmp(host, this->dhost))
1390 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1393 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1395 if (this->ServerInstance->Config->CycleHosts)
1396 this->WriteCommonExcept("QUIT :Changing hosts");
1398 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1399 strlcpy(this->dhost,host,64);
1401 this->InvalidateCache();
1403 if (this->ServerInstance->Config->CycleHosts)
1405 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1407 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1408 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1410 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1415 this->WriteServ("396 %s %s :is now your displayed host",this->nick,this->dhost);
1420 bool User::ChangeIdent(const char* newident)
1422 if (!strcmp(newident, this->ident))
1425 if (this->ServerInstance->Config->CycleHosts)
1426 this->WriteCommonExcept("%s","QUIT :Changing ident");
1428 strlcpy(this->ident, newident, IDENTMAX+2);
1430 this->InvalidateCache();
1432 if (this->ServerInstance->Config->CycleHosts)
1434 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1436 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1437 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1439 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1446 void User::SendAll(const char* command, char* text, ...)
1448 char textbuffer[MAXBUF];
1449 char formatbuffer[MAXBUF];
1452 va_start(argsPtr, text);
1453 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1456 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1457 std::string fmt = formatbuffer;
1459 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1466 std::string User::ChannelList(User* source)
1471 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1473 /* If the target is the same as the sender, let them see all their channels.
1474 * If the channel is NOT private/secret OR the user shares a common channel
1475 * If the user is an oper, and the <options:operspywhois> option is set.
1477 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1479 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1486 ServerInstance->Log(DEBUG,"Exception in User::ChannelList()");
1491 void User::SplitChanList(User* dest, const std::string &cl)
1494 std::ostringstream prefix;
1495 std::string::size_type start, pos, length;
1499 prefix << this->nick << " " << dest->nick << " :";
1500 line = prefix.str();
1501 int namelen = strlen(ServerInstance->Config->ServerName) + 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());
1532 ServerInstance->Log(DEBUG,"Exception in User::SplitChanList()");
1536 unsigned int User::GetMaxChans()
1538 return this->MaxChans;
1543 * Sets a user's connection class.
1544 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1545 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1546 * then their ip will be taken as 'priority' anyway, so for example,
1547 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1549 ConnectClass* User::SetClass(const std::string &explicit_name)
1551 ConnectClass *found = NULL;
1553 if (!IS_LOCAL(this))
1556 if (!explicit_name.empty())
1558 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1560 ConnectClass* c = *i;
1562 if (explicit_name == c->GetName() && !c->GetDisabled())
1570 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1572 ConnectClass* c = *i;
1574 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1578 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1587 if (!c->GetDisabled())
1594 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1597 /* deny change if change will take class over the limit */
1598 if (found->limit && (found->RefCount + 1 >= found->limit))
1600 ServerInstance->Log(DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1601 return this->MyClass;
1604 /* should always be valid, but just in case .. */
1607 if (found == this->MyClass) // no point changing this shit :P
1608 return this->MyClass;
1609 this->MyClass->RefCount--;
1610 ServerInstance->Log(DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1613 this->MyClass = found;
1614 this->MyClass->RefCount++;
1615 ServerInstance->Log(DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1618 return this->MyClass;
1621 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1622 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1623 * then their ip will be taken as 'priority' anyway, so for example,
1624 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1626 ConnectClass* User::GetClass()
1628 return this->MyClass;
1631 void User::PurgeEmptyChannels()
1633 std::vector<Channel*> to_delete;
1635 // firstly decrement the count on each channel
1636 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1638 f->first->RemoveAllPrefixes(this);
1639 if (f->first->DelUser(this) == 0)
1641 /* No users left in here, mark it for deletion */
1644 to_delete.push_back(f->first);
1648 ServerInstance->Log(DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1653 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1655 Channel* thischan = *n;
1656 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1657 if (i2 != ServerInstance->chanlist->end())
1659 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1661 ServerInstance->chanlist->erase(i2);
1662 this->chans.erase(*n);
1669 void User::ShowMOTD()
1671 if (!ServerInstance->Config->MOTD.size())
1673 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1676 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1678 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1679 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1681 this->WriteServ("376 %s :End of message of the day.", this->nick);
1684 void User::ShowRULES()
1686 if (!ServerInstance->Config->RULES.size())
1688 this->WriteServ("434 %s :RULES File is missing",this->nick);
1692 this->WriteServ("308 %s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1694 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1695 this->WriteServ("232 %s :- %s",this->nick,i->c_str());
1697 this->WriteServ("309 %s :End of RULES command.",this->nick);
1700 void User::HandleEvent(EventType et, int errornum)
1702 if (this->quitting) // drop everything, user is due to be quit
1705 /* WARNING: May delete this user! */
1706 int thisfd = this->GetFd();
1713 ServerInstance->ProcessUser(this);
1716 this->FlushWriteBuf();
1719 /** This should be safe, but dont DARE do anything after it -- Brain */
1720 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1726 ServerInstance->Log(DEBUG,"Exception in User::HandleEvent intercepted");
1729 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1730 if ((ServerInstance->SE->GetRef(thisfd) == this))
1732 if (!WriteError.empty())
1734 User::QuitUser(ServerInstance, this, GetWriteError());
1739 void User::SetOperQuit(const std::string &oquit)
1741 operquitmsg = oquit;
1744 const char* User::GetOperQuit()
1746 return operquitmsg.c_str();
1749 void User::IncreasePenalty(int increase)
1751 this->Penalty += increase;
1754 void User::DecreasePenalty(int decrease)
1756 this->Penalty -= decrease;
1767 bool VisData::VisibleTo(User* user)