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* sip = this->GetIPString();
93 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
94 if (!strncmp(sip, "0::ffff:", 8))
95 res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
97 res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
99 this->ServerInstance->AddResolver(res_reverse, cached);
101 catch (CoreException& e)
103 ServerInstance->Logs->Log("USERS", 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->Logs->Log("USERS", DEBUG, "DecrementModes()");
160 for (unsigned char n = 'A'; n <= 'z'; n++)
164 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
165 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
168 ServerInstance->Logs->Log("USERS", 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();
182 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
183 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
184 quietquit = 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->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
208 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
209 if (finduuid == Instance->Users->uuidlist->end())
210 (*Instance->Users->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->Logs->Log("USERS", 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->Users->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 time_t now = time(NULL);
371 InvitedList::iterator safei;
372 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
374 if (channel == i->first)
376 if (i->second != 0 && now > i->second)
378 /* Expired invite, remove it. */
381 invites.erase(safei);
390 InvitedList* User::GetInviteList()
392 time_t now = time(NULL);
393 /* Weed out expired invites here. */
394 InvitedList::iterator safei;
395 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
397 if (i->second != 0 && now > i->second)
399 /* Expired invite, remove it. */
402 invites.erase(safei);
408 void User::InviteTo(const irc::string &channel, time_t invtimeout)
410 time_t now = time(NULL);
411 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
412 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
414 if (channel == i->first)
416 if (i->second != 0 && invtimeout > i->second)
418 i->second = invtimeout;
422 invites.push_back(std::make_pair(channel, invtimeout));
425 void User::RemoveInvite(const irc::string &channel)
427 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
429 if (channel == i->first)
437 bool User::HasPermission(const std::string &command)
440 * users on remote servers can completely bypass all permissions based checks.
441 * This prevents desyncs when one server has different type/class tags to another.
442 * That having been said, this does open things up to the possibility of source changes
443 * allowing remote kills, etc - but if they have access to the src, they most likely have
444 * access to the conf - so it's an end to a means either way.
449 // are they even an oper at all?
455 if (!AllowedOperCommands)
458 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
460 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
466 /** NOTE: We cannot pass a const reference to this method.
467 * The string is changed by the workings of the method,
468 * so that if we pass const ref, we end up copying it to
469 * something we can change anyway. Makes sense to just let
470 * the compiler do that copy for us.
472 bool User::AddBuffer(std::string a)
476 std::string::size_type i = a.rfind('\r');
478 while (i != std::string::npos)
487 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
489 this->SetWriteError("RecvQ exceeded");
490 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
499 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
504 bool User::BufferIsReady()
506 return (recvq.find('\n') != std::string::npos);
509 void User::ClearBuffer()
514 std::string User::GetBuffer()
521 /* Strip any leading \r or \n off the string.
522 * Usually there are only one or two of these,
523 * so its is computationally cheap to do.
525 std::string::iterator t = recvq.begin();
526 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
532 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
534 /* Find the first complete line, return it as the
535 * result, and leave the recvq as whats left
539 std::string ret = std::string(recvq.begin(), x);
540 recvq.erase(recvq.begin(), x + 1);
549 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
554 void User::AddWriteBuf(const std::string &data)
556 if (*this->GetWriteError())
559 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
562 * Fix by brain - Set the error text BEFORE calling, because
563 * if we dont it'll recursively call here over and over again trying
564 * to repeatedly add the text to the sendq!
566 this->SetWriteError("SendQ exceeded");
567 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
571 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
572 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
577 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
578 void User::FlushWriteBuf()
582 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
586 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
588 int old_sendq_length = sendq.length();
589 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
595 /* The socket buffer is full. This isnt fatal,
598 this->ServerInstance->SE->WantWrite(this);
602 /* Fatal error, set write error and bail
604 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
610 /* advance the queue */
612 this->sendq = this->sendq.substr(n_sent);
613 /* update the user's stats counters */
614 this->bytes_out += n_sent;
616 if (n_sent != old_sendq_length)
617 this->ServerInstance->SE->WantWrite(this);
624 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
627 if (this->sendq.empty())
629 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
633 void User::SetWriteError(const std::string &error)
635 // don't try to set the error twice, its already set take the first string.
636 if (this->WriteError.empty())
637 this->WriteError = error;
640 const char* User::GetWriteError()
642 return this->WriteError.c_str();
645 void User::Oper(const std::string &opertype, const std::string &opername)
653 this->modes[UM_OPERATOR] = 1;
654 this->WriteServ("MODE %s :+o", this->nick);
655 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
656 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
657 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
658 ServerInstance->Users->all_opers.push_back(this);
660 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
661 if (iter_opertype != ServerInstance->Config->opertypes.end())
664 if (AllowedOperCommands)
665 AllowedOperCommands->clear();
667 AllowedOperCommands = new std::map<std::string, bool>;
669 char* Classes = strdup(iter_opertype->second);
670 char* myclass = strtok_r(Classes," ",&savept);
673 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
674 if (iter_operclass != ServerInstance->Config->operclass.end())
676 char* CommandList = strdup(iter_operclass->second);
677 mycmd = strtok_r(CommandList," ",&savept2);
680 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
681 mycmd = strtok_r(NULL," ",&savept2);
685 myclass = strtok_r(NULL," ",&savept);
690 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
695 ServerInstance->Log(DEBUG,"Exception in User::Oper()");
703 // unset their oper type (what IS_OPER checks), and remove +o
705 this->modes[UM_OPERATOR] = 0;
707 // remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404
708 ServerInstance->Users->all_opers.remove(this);
710 if (AllowedOperCommands)
712 delete AllowedOperCommands;
713 AllowedOperCommands = NULL;
718 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
720 Instance->Logs->Log("USERS", DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
721 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
722 user->quietquit = false;
723 user->quitmsg = quitreason;
726 user->operquitmsg = quitreason;
728 user->operquitmsg = operreason;
730 Instance->GlobalCulls.AddItem(user);
733 /* adds or updates an entry in the whowas list */
734 void User::AddToWhoWas()
736 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
739 std::deque<classbase*> params;
740 params.push_back(this);
741 whowas_command->HandleInternal(WHOWAS_ADD, params);
746 * Check class restrictions
748 void User::CheckClass()
750 ConnectClass* a = this->MyClass;
752 if ((!a) || (a->GetType() == CC_DENY))
754 User::QuitUser(ServerInstance, this, "Unauthorised connection");
757 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
759 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
760 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
763 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
765 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
766 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
770 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
771 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
772 this->MaxChans = a->GetMaxChans();
775 void User::FullConnect()
777 ServerInstance->stats->statsConnects++;
778 this->idle_lastmsg = ServerInstance->Time();
781 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
782 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
783 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
784 * Don't remove this! -- w00t
788 /* Check the password, if one is required by the user's connect class.
789 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
791 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
793 User::QuitUser(ServerInstance, this, "Invalid password");
799 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
807 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
816 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
817 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
818 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
819 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
820 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());
822 ServerInstance->Config->Send005(this);
824 this->WriteServ("042 %s %s :your unique ID", this->nick, this->uuid);
830 if (ServerInstance->Users->unregistered_count)
831 ServerInstance->Users->unregistered_count--;
833 /* Trigger LUSERS output, give modules a chance too */
835 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
837 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
840 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
841 * for a user that doesn't exist yet.
843 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
845 this->registered = REG_ALL;
847 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
849 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);
850 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
851 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
854 /** User::UpdateNick()
855 * re-allocates a nick in the user_hash after they change nicknames,
856 * returns a pointer to the new user as it may have moved
858 User* User::UpdateNickHash(const char* New)
860 //user_hash::iterator newnick;
861 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
863 if (!strcasecmp(this->nick,New))
864 return oldnick->second;
866 if (oldnick == ServerInstance->Users->clientlist->end())
867 return NULL; /* doesnt exist */
869 User* olduser = oldnick->second;
870 (*(ServerInstance->Users->clientlist))[New] = olduser;
871 ServerInstance->Users->clientlist->erase(oldnick);
875 void User::InvalidateCache()
877 /* Invalidate cache */
879 free(cached_fullhost);
883 free(cached_makehost);
884 if (cached_fullrealhost)
885 free(cached_fullrealhost);
886 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
889 bool User::ForceNickChange(const char* newnick)
892 * XXX this makes no sense..
893 * why do we do nothing for change on users not REG_ALL?
894 * why do we trigger events twice for everyone previously (and just them now)
895 * i think the first if () needs removing totally, or? -- w00t
897 if (this->registered != REG_ALL)
901 this->InvalidateCache();
903 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
907 ServerInstance->stats->statsCollisions++;
911 if (ServerInstance->XLines->MatchesLine("Q",newnick))
913 ServerInstance->stats->statsCollisions++;
919 std::deque<classbase*> dummy;
920 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
921 if (nickhandler) // wtfbbq, when would this not be here
923 nickhandler->HandleInternal(1, dummy);
924 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
925 nickhandler->HandleInternal(0, dummy);
934 void User::SetSockAddr(int protocol_family, const char* sip, int port)
938 switch (protocol_family)
940 #ifdef SUPPORT_IP6LINKS
943 sockaddr_in6* sin = new sockaddr_in6;
944 sin->sin6_family = AF_INET6;
945 sin->sin6_port = port;
946 inet_pton(AF_INET6, sip, &sin->sin6_addr);
947 this->ip = (sockaddr*)sin;
953 sockaddr_in* sin = new sockaddr_in;
954 sin->sin_family = AF_INET;
955 sin->sin_port = port;
956 inet_pton(AF_INET, sip, &sin->sin_addr);
957 this->ip = (sockaddr*)sin;
961 ServerInstance->Log(DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
968 if (this->ip == NULL)
971 switch (this->GetProtocolFamily())
973 #ifdef SUPPORT_IP6LINKS
976 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
977 return sin->sin6_port;
983 sockaddr_in* sin = (sockaddr_in*)this->ip;
984 return sin->sin_port;
993 int User::GetProtocolFamily()
995 if (this->ip == NULL)
998 sockaddr_in* sin = (sockaddr_in*)this->ip;
999 return sin->sin_family;
1003 * XXX the duplication here is horrid..
1004 * do we really need two methods doing essentially the same thing?
1006 const char* User::GetIPString()
1008 static char buf[1024];
1010 if (this->ip == NULL)
1013 if (!this->cachedip.empty())
1014 return this->cachedip.c_str();
1016 switch (this->GetProtocolFamily())
1018 #ifdef SUPPORT_IP6LINKS
1021 static char temp[1024];
1023 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1024 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1025 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1028 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1030 this->cachedip = temp;
1034 this->cachedip = buf;
1041 sockaddr_in* sin = (sockaddr_in*)this->ip;
1042 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1043 this->cachedip = buf;
1051 // Unreachable, probably
1055 /** NOTE: We cannot pass a const reference to this method.
1056 * The string is changed by the workings of the method,
1057 * so that if we pass const ref, we end up copying it to
1058 * something we can change anyway. Makes sense to just let
1059 * the compiler do that copy for us.
1061 void User::Write(std::string text)
1063 if (!ServerInstance->SE->BoundsCheckFd(this))
1068 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1069 text.append("\r\n");
1073 ServerInstance->Log(DEBUG,"Exception in User::Write() std::string::append");
1077 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1079 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1080 * implement their own buffering mechanisms
1084 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1086 catch (CoreException& modexcept)
1088 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1093 this->AddWriteBuf(text);
1095 ServerInstance->stats->statsSent += text.length();
1096 this->ServerInstance->SE->WantWrite(this);
1101 void User::Write(const char *text, ...)
1104 char textbuffer[MAXBUF];
1106 va_start(argsPtr, text);
1107 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1110 this->Write(std::string(textbuffer));
1113 void User::WriteServ(const std::string& text)
1115 char textbuffer[MAXBUF];
1117 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1118 this->Write(std::string(textbuffer));
1122 * Same as Write(), except `text' is prefixed with `:server.name '.
1124 void User::WriteServ(const char* text, ...)
1127 char textbuffer[MAXBUF];
1129 va_start(argsPtr, text);
1130 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1133 this->WriteServ(std::string(textbuffer));
1137 void User::WriteFrom(User *user, const std::string &text)
1141 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1143 this->Write(std::string(tb));
1147 /* write text from an originating user to originating user */
1149 void User::WriteFrom(User *user, const char* text, ...)
1152 char textbuffer[MAXBUF];
1154 va_start(argsPtr, text);
1155 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1158 this->WriteFrom(user, std::string(textbuffer));
1162 /* write text to an destination user from a source user (e.g. user privmsg) */
1164 void User::WriteTo(User *dest, const char *data, ...)
1166 char textbuffer[MAXBUF];
1169 va_start(argsPtr, data);
1170 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1173 this->WriteTo(dest, std::string(textbuffer));
1176 void User::WriteTo(User *dest, const std::string &data)
1178 dest->WriteFrom(this, data);
1182 void User::WriteCommon(const char* text, ...)
1184 char textbuffer[MAXBUF];
1187 if (this->registered != REG_ALL)
1190 va_start(argsPtr, text);
1191 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1194 this->WriteCommon(std::string(textbuffer));
1197 void User::WriteCommon(const std::string &text)
1199 bool sent_to_at_least_one = false;
1202 if (this->registered != REG_ALL)
1207 /* We dont want to be doing this n times, just once */
1208 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1209 std::string out = tb;
1211 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1213 CUList* ulist = v->first->GetUsers();
1214 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1216 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1218 already_sent[i->first->fd] = uniq_id;
1219 i->first->Write(out);
1220 sent_to_at_least_one = true;
1226 * if the user was not in any channels, no users will receive the text. Make sure the user
1227 * receives their OWN message for WriteCommon
1229 if (!sent_to_at_least_one)
1231 this->Write(std::string(tb));
1236 /* write a formatted string to all users who share at least one common
1237 * channel, NOT including the source user e.g. for use in QUIT
1240 void User::WriteCommonExcept(const char* text, ...)
1242 char textbuffer[MAXBUF];
1245 va_start(argsPtr, text);
1246 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1249 this->WriteCommonExcept(std::string(textbuffer));
1252 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1257 if (this->registered != REG_ALL)
1261 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1262 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1263 std::string out1 = tb1;
1264 std::string out2 = tb2;
1266 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1268 CUList *ulist = v->first->GetUsers();
1269 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1271 if (this != i->first)
1273 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1275 already_sent[i->first->fd] = uniq_id;
1276 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1283 void User::WriteCommonExcept(const std::string &text)
1288 if (this->registered != REG_ALL)
1292 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1295 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1297 CUList *ulist = v->first->GetUsers();
1298 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1300 if (this != i->first)
1302 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1304 already_sent[i->first->fd] = uniq_id;
1305 i->first->Write(out1);
1313 void User::WriteWallOps(const std::string &text)
1315 if (!IS_OPER(this) && IS_LOCAL(this))
1318 std::string wallop("WALLOPS :");
1319 wallop.append(text);
1321 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1324 if (t->IsModeSet('w'))
1325 this->WriteTo(t,wallop);
1329 void User::WriteWallOps(const char* text, ...)
1331 char textbuffer[MAXBUF];
1334 va_start(argsPtr, text);
1335 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1338 this->WriteWallOps(std::string(textbuffer));
1341 /* return 0 or 1 depending if users u and u2 share one or more common channels
1342 * (used by QUIT, NICK etc which arent channel specific notices)
1344 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1345 * the first users channels then the second users channels within the outer loop,
1346 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1347 * all possible iterations). However this new function instead checks against the
1348 * channel's userlist in the inner loop which is a std::map<User*,User*>
1349 * and saves us time as we already know what pointer value we are after.
1350 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1351 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1353 bool User::SharesChannelWith(User *other)
1355 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1359 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1361 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1362 * by replacing it with a map::find which *should* be more efficient
1364 if (i->first->HasUser(other))
1370 bool User::ChangeName(const char* gecos)
1372 if (!strcmp(gecos, this->fullname))
1378 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1381 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1383 strlcpy(this->fullname,gecos,MAXGECOS+1);
1388 bool User::ChangeDisplayedHost(const char* shost)
1390 if (!strcmp(shost, this->dhost))
1396 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1399 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1402 if (this->ServerInstance->Config->CycleHosts)
1403 this->WriteCommonExcept("QUIT :Changing hosts");
1405 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1406 strlcpy(this->dhost,shost,64);
1408 this->InvalidateCache();
1410 if (this->ServerInstance->Config->CycleHosts)
1412 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1414 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1415 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1417 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1422 this->WriteServ("396 %s %s :is now your displayed host",this->nick,this->dhost);
1427 bool User::ChangeIdent(const char* newident)
1429 if (!strcmp(newident, this->ident))
1432 if (this->ServerInstance->Config->CycleHosts)
1433 this->WriteCommonExcept("%s","QUIT :Changing ident");
1435 strlcpy(this->ident, newident, IDENTMAX+1);
1437 this->InvalidateCache();
1439 if (this->ServerInstance->Config->CycleHosts)
1441 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1443 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1444 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1446 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1453 void User::SendAll(const char* command, const char* text, ...)
1455 char textbuffer[MAXBUF];
1456 char formatbuffer[MAXBUF];
1459 va_start(argsPtr, text);
1460 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1463 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1464 std::string fmt = formatbuffer;
1466 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1473 std::string User::ChannelList(User* source)
1477 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1479 /* If the target is the same as the sender, let them see all their channels.
1480 * If the channel is NOT private/secret OR the user shares a common channel
1481 * If the user is an oper, and the <options:operspywhois> option is set.
1483 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1485 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1492 void User::SplitChanList(User* dest, const std::string &cl)
1495 std::ostringstream prefix;
1496 std::string::size_type start, pos, length;
1498 prefix << this->nick << " " << dest->nick << " :";
1499 line = prefix.str();
1500 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1502 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1504 length = (pos == std::string::npos) ? cl.length() : pos;
1506 if (line.length() + namelen + length - start > 510)
1508 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1509 line = prefix.str();
1512 if(pos == std::string::npos)
1514 line.append(cl.substr(start, length - start));
1519 line.append(cl.substr(start, length - start + 1));
1525 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1529 unsigned int User::GetMaxChans()
1531 return this->MaxChans;
1536 * Sets a user's connection class.
1537 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1538 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1539 * then their ip will be taken as 'priority' anyway, so for example,
1540 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1542 ConnectClass* User::SetClass(const std::string &explicit_name)
1544 ConnectClass *found = NULL;
1546 if (!IS_LOCAL(this))
1549 if (!explicit_name.empty())
1551 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1553 ConnectClass* c = *i;
1555 if (explicit_name == c->GetName() && !c->GetDisabled())
1563 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1565 ConnectClass* c = *i;
1567 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1571 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1580 if (!c->GetDisabled())
1587 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1590 /* deny change if change will take class over the limit */
1591 if (found->limit && (found->RefCount + 1 >= found->limit))
1593 ServerInstance->Log(DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1594 return this->MyClass;
1597 /* should always be valid, but just in case .. */
1600 if (found == this->MyClass) // no point changing this shit :P
1601 return this->MyClass;
1602 this->MyClass->RefCount--;
1603 ServerInstance->Log(DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1606 this->MyClass = found;
1607 this->MyClass->RefCount++;
1608 ServerInstance->Log(DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1611 return this->MyClass;
1614 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1615 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1616 * then their ip will be taken as 'priority' anyway, so for example,
1617 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1619 ConnectClass* User::GetClass()
1621 return this->MyClass;
1624 void User::PurgeEmptyChannels()
1626 std::vector<Channel*> to_delete;
1628 // firstly decrement the count on each channel
1629 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1631 f->first->RemoveAllPrefixes(this);
1632 if (f->first->DelUser(this) == 0)
1634 /* No users left in here, mark it for deletion */
1637 to_delete.push_back(f->first);
1641 ServerInstance->Log(DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1646 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1648 Channel* thischan = *n;
1649 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1650 if (i2 != ServerInstance->chanlist->end())
1652 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1654 ServerInstance->chanlist->erase(i2);
1655 this->chans.erase(*n);
1662 void User::ShowMOTD()
1664 if (!ServerInstance->Config->MOTD.size())
1666 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1669 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1671 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1672 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1674 this->WriteServ("376 %s :End of message of the day.", this->nick);
1677 void User::ShowRULES()
1679 if (!ServerInstance->Config->RULES.size())
1681 this->WriteServ("434 %s :RULES File is missing",this->nick);
1685 this->WriteServ("308 %s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1687 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1688 this->WriteServ("232 %s :- %s",this->nick,i->c_str());
1690 this->WriteServ("309 %s :End of RULES command.",this->nick);
1693 void User::HandleEvent(EventType et, int errornum)
1695 if (this->quitting) // drop everything, user is due to be quit
1698 /* WARNING: May delete this user! */
1699 int thisfd = this->GetFd();
1706 ServerInstance->ProcessUser(this);
1709 this->FlushWriteBuf();
1712 /** This should be safe, but dont DARE do anything after it -- Brain */
1713 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1719 ServerInstance->Log(DEBUG,"Exception in User::HandleEvent intercepted");
1722 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1723 if ((ServerInstance->SE->GetRef(thisfd) == this))
1725 if (!WriteError.empty())
1727 User::QuitUser(ServerInstance, this, GetWriteError());
1732 void User::SetOperQuit(const std::string &oquit)
1734 operquitmsg = oquit;
1737 const char* User::GetOperQuit()
1739 return operquitmsg.c_str();
1742 void User::IncreasePenalty(int increase)
1744 this->Penalty += increase;
1747 void User::DecreasePenalty(int decrease)
1749 this->Penalty -= decrease;
1760 bool VisData::VisibleTo(User* user)