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 = NULL;
27 void InitializeAlreadySent(SocketEngine* SE)
29 already_sent = new unsigned long[SE->GetMaxFds()];
30 memset(already_sent, 0, sizeof(already_sent));
33 /* XXX: Used for speeding up WriteCommon operations */
34 unsigned long uniq_id = 1;
36 std::string User::ProcessNoticeMasks(const char *sm)
38 bool adding = true, oldadding = false;
53 for (unsigned char d = 'A'; d <= 'z'; d++)
55 if (ServerInstance->SNO->IsEnabled(d))
57 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
59 if ((oldadding != adding) || (!output.length()))
60 output += (adding ? '+' : '-');
62 this->SetNoticeMask(d, adding);
71 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
73 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
75 if ((oldadding != adding) || (!output.length()))
76 output += (adding ? '+' : '-');
78 this->SetNoticeMask(*c, adding);
84 this->WriteNumeric(501, "%s %c :is unknown snomask char to me", this->nick, *c);
96 void User::StartDNSLookup()
101 const char* sip = this->GetIPString();
103 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
104 if (!strncmp(sip, "0::ffff:", 8))
105 res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
107 res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
109 this->ServerInstance->AddResolver(res_reverse, cached);
111 catch (CoreException& e)
113 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
117 bool User::IsNoticeMaskSet(unsigned char sm)
119 return (snomasks[sm-65]);
122 void User::SetNoticeMask(unsigned char sm, bool value)
124 snomasks[sm-65] = value;
127 const char* User::FormatNoticeMasks()
129 static char data[MAXBUF];
132 for (int n = 0; n < 64; n++)
135 data[offset++] = n+65;
144 bool User::IsModeSet(unsigned char m)
146 return (modes[m-65]);
149 void User::SetMode(unsigned char m, bool value)
154 const char* User::FormatModes()
156 static char data[MAXBUF];
158 for (int n = 0; n < 64; n++)
161 data[offset++] = n+65;
167 void User::DecrementModes()
169 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
170 for (unsigned char n = 'A'; n <= 'z'; n++)
174 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
175 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
178 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
185 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
187 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
188 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
189 reset_due = ServerInstance->Time();
190 age = ServerInstance->Time();
192 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
193 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
194 quietquit = OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
199 res_forward = res_reverse = NULL;
204 AllowedUserModes = NULL;
205 AllowedChanModes = NULL;
206 AllowedOperCommands = NULL;
209 memset(modes,0,sizeof(modes));
210 memset(snomasks,0,sizeof(snomasks));
211 /* Invalidate cache */
212 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
215 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
217 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
219 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
221 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
222 if (finduuid == Instance->Users->uuidlist->end())
223 (*Instance->Users->uuidlist)[uuid] = this;
225 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
230 /* NULL for remote users :) */
233 this->MyClass->RefCount--;
234 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %lu", this->MyClass->RefCount);
236 if (this->AllowedOperCommands)
238 delete AllowedOperCommands;
239 AllowedOperCommands = NULL;
242 if (this->AllowedUserModes)
244 delete[] AllowedUserModes;
245 AllowedUserModes = NULL;
248 if (this->AllowedChanModes)
250 delete[] AllowedChanModes;
251 AllowedChanModes = NULL;
254 this->InvalidateCache();
255 this->DecrementModes();
259 ServerInstance->Users->RemoveCloneCounts(this);
261 if (this->GetProtocolFamily() == AF_INET)
263 delete (sockaddr_in*)ip;
265 #ifdef SUPPORT_IP6LINKS
268 delete (sockaddr_in6*)ip;
273 ServerInstance->Users->uuidlist->erase(uuid);
276 char* User::MakeHost()
278 if (this->cached_makehost)
279 return this->cached_makehost;
282 /* This is much faster than snprintf */
284 for(char* n = ident; *n; n++)
287 for(char* n = host; *n; n++)
291 this->cached_makehost = strdup(nhost);
293 return this->cached_makehost;
296 char* User::MakeHostIP()
298 if (this->cached_hostip)
299 return this->cached_hostip;
302 /* This is much faster than snprintf */
304 for(char* n = ident; *n; n++)
307 for(const char* n = this->GetIPString(); *n; n++)
311 this->cached_hostip = strdup(ihost);
313 return this->cached_hostip;
316 void User::CloseSocket()
320 ServerInstance->SE->Shutdown(this, 2);
321 ServerInstance->SE->Close(this);
325 char* User::GetFullHost()
327 if (this->cached_fullhost)
328 return this->cached_fullhost;
332 for(char* n = nick; *n; n++)
335 for(char* n = ident; *n; n++)
338 for(char* n = dhost; *n; n++)
342 this->cached_fullhost = strdup(result);
344 return this->cached_fullhost;
347 char* User::MakeWildHost()
349 static char nresult[MAXBUF];
351 *t++ = '*'; *t++ = '!';
352 *t++ = '*'; *t++ = '@';
353 for(char* n = dhost; *n; n++)
359 int User::ReadData(void* buffer, size_t size)
364 return read(this->fd, buffer, size);
366 return recv(this->fd, (char*)buffer, size, 0);
374 char* User::GetFullRealHost()
376 if (this->cached_fullrealhost)
377 return this->cached_fullrealhost;
379 char fresult[MAXBUF];
381 for(char* n = nick; *n; n++)
384 for(char* n = ident; *n; n++)
387 for(char* n = host; *n; n++)
391 this->cached_fullrealhost = strdup(fresult);
393 return this->cached_fullrealhost;
396 bool User::IsInvited(const irc::string &channel)
398 time_t now = time(NULL);
399 InvitedList::iterator safei;
400 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
402 if (channel == i->first)
404 if (i->second != 0 && now > i->second)
406 /* Expired invite, remove it. */
409 invites.erase(safei);
418 InvitedList* User::GetInviteList()
420 time_t now = time(NULL);
421 /* Weed out expired invites here. */
422 InvitedList::iterator safei;
423 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
425 if (i->second != 0 && now > i->second)
427 /* Expired invite, remove it. */
430 invites.erase(safei);
436 void User::InviteTo(const irc::string &channel, time_t invtimeout)
438 time_t now = time(NULL);
439 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
440 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
442 if (channel == i->first)
444 if (i->second != 0 && invtimeout > i->second)
446 i->second = invtimeout;
450 invites.push_back(std::make_pair(channel, invtimeout));
453 void User::RemoveInvite(const irc::string &channel)
455 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
457 if (channel == i->first)
465 bool User::HasModePermission(unsigned char mode, ModeType type)
473 if (!AllowedUserModes || !AllowedChanModes)
476 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
480 bool User::HasPermission(const std::string &command)
483 * users on remote servers can completely bypass all permissions based checks.
484 * This prevents desyncs when one server has different type/class tags to another.
485 * That having been said, this does open things up to the possibility of source changes
486 * allowing remote kills, etc - but if they have access to the src, they most likely have
487 * access to the conf - so it's an end to a means either way.
492 // are they even an oper at all?
498 if (!AllowedOperCommands)
501 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
503 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
509 /** NOTE: We cannot pass a const reference to this method.
510 * The string is changed by the workings of the method,
511 * so that if we pass const ref, we end up copying it to
512 * something we can change anyway. Makes sense to just let
513 * the compiler do that copy for us.
515 bool User::AddBuffer(std::string a)
519 std::string::size_type i = a.rfind('\r');
521 while (i != std::string::npos)
530 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
532 this->SetWriteError("RecvQ exceeded");
533 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)recvq.length(),this->MyClass->GetRecvqMax());
542 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
547 bool User::BufferIsReady()
549 return (recvq.find('\n') != std::string::npos);
552 void User::ClearBuffer()
557 std::string User::GetBuffer()
564 /* Strip any leading \r or \n off the string.
565 * Usually there are only one or two of these,
566 * so its is computationally cheap to do.
568 std::string::iterator t = recvq.begin();
569 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
575 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
577 /* Find the first complete line, return it as the
578 * result, and leave the recvq as whats left
582 std::string ret = std::string(recvq.begin(), x);
583 recvq.erase(recvq.begin(), x + 1);
592 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
597 void User::AddWriteBuf(const std::string &data)
599 if (*this->GetWriteError())
602 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
605 * Fix by brain - Set the error text BEFORE calling, because
606 * if we dont it'll recursively call here over and over again trying
607 * to repeatedly add the text to the sendq!
609 this->SetWriteError("SendQ exceeded");
610 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)sendq.length() + data.length(),this->MyClass->GetSendqMax());
614 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
615 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
620 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
621 void User::FlushWriteBuf()
625 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
629 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
631 int old_sendq_length = sendq.length();
632 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
638 /* The socket buffer is full. This isnt fatal,
641 this->ServerInstance->SE->WantWrite(this);
645 /* Fatal error, set write error and bail
647 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
653 /* advance the queue */
655 this->sendq = this->sendq.substr(n_sent);
656 /* update the user's stats counters */
657 this->bytes_out += n_sent;
659 if (n_sent != old_sendq_length)
660 this->ServerInstance->SE->WantWrite(this);
667 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
670 if (this->sendq.empty())
672 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
676 void User::SetWriteError(const std::string &error)
678 // don't try to set the error twice, its already set take the first string.
679 if (this->WriteError.empty())
680 this->WriteError = error;
683 const char* User::GetWriteError()
685 return this->WriteError.c_str();
688 void User::Oper(const std::string &opertype, const std::string &opername)
696 this->modes[UM_OPERATOR] = 1;
697 this->WriteServ("MODE %s :+o", this->nick);
698 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
699 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
700 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
701 ServerInstance->Users->all_opers.push_back(this);
703 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
704 if (iter_opertype != ServerInstance->Config->opertypes.end())
707 if (AllowedOperCommands)
708 AllowedOperCommands->clear();
710 AllowedOperCommands = new std::map<std::string, bool>;
712 if (!AllowedChanModes)
713 AllowedChanModes = new bool[64];
715 if (!AllowedUserModes)
716 AllowedUserModes = new bool[64];
718 memset(AllowedUserModes, 0, 64);
719 memset(AllowedChanModes, 0, 64);
721 char* Classes = strdup(iter_opertype->second);
722 char* myclass = strtok_r(Classes," ",&savept);
725 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
726 if (iter_operclass != ServerInstance->Config->operclass.end())
728 char* CommandList = strdup(iter_operclass->second.commandlist);
729 mycmd = strtok_r(CommandList," ",&savept2);
732 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
733 mycmd = strtok_r(NULL," ",&savept2);
736 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
737 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
741 memset(this->AllowedUserModes, (int)(true), 64);
745 this->AllowedUserModes[*c - 'A'] = true;
748 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
752 memset(this->AllowedChanModes, (int)(true), 64);
756 this->AllowedChanModes[*c - 'A'] = true;
760 myclass = strtok_r(NULL," ",&savept);
765 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
770 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
778 /* Remove all oper only modes from the user when the deoper - Bug #466*/
779 std::string moderemove("-");
781 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
785 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
786 if (mh && mh->NeedsOper())
787 moderemove += letter;
791 const char* parameters[] = { this->nick, moderemove.c_str() };
792 ServerInstance->Parser->CallHandler("MODE", parameters, 2, this);
794 /* unset their oper type (what IS_OPER checks), and remove +o */
796 this->modes[UM_OPERATOR] = 0;
798 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
799 ServerInstance->Users->all_opers.remove(this);
801 if (AllowedOperCommands)
803 delete AllowedOperCommands;
804 AllowedOperCommands = NULL;
806 if (AllowedUserModes)
808 delete[] AllowedUserModes;
809 AllowedUserModes = NULL;
811 if (AllowedChanModes)
813 delete[] AllowedChanModes;
814 AllowedChanModes = NULL;
820 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
822 Instance->Logs->Log("USERS", DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
823 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
824 user->quietquit = false;
825 user->quitmsg = quitreason;
828 user->operquitmsg = quitreason;
830 user->operquitmsg = operreason;
832 Instance->GlobalCulls.AddItem(user);
835 /* adds or updates an entry in the whowas list */
836 void User::AddToWhoWas()
838 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
841 std::deque<classbase*> params;
842 params.push_back(this);
843 whowas_command->HandleInternal(WHOWAS_ADD, params);
848 * Check class restrictions
850 void User::CheckClass()
852 ConnectClass* a = this->MyClass;
854 if ((!a) || (a->GetType() == CC_DENY))
856 User::QuitUser(ServerInstance, this, "Unauthorised connection");
859 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
861 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
862 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
865 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
867 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
868 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
872 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
873 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
874 this->MaxChans = a->GetMaxChans();
877 void User::FullConnect()
879 ServerInstance->stats->statsConnects++;
880 this->idle_lastmsg = ServerInstance->Time();
883 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
884 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
885 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
886 * Don't remove this! -- w00t
890 /* Check the password, if one is required by the user's connect class.
891 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
893 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
895 User::QuitUser(ServerInstance, this, "Invalid password");
901 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
909 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
918 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
919 this->WriteNumeric(001, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
920 this->WriteNumeric(002, "%s :Your host is %s, running version InspIRCd-1.2",this->nick,ServerInstance->Config->ServerName);
921 this->WriteNumeric(003, "%s :This server was created %s %s", this->nick, __TIME__, __DATE__);
922 this->WriteNumeric(004, "%s %s InspIRCd-1.2 %s %s %s", this->nick, ServerInstance->Config->ServerName, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
924 ServerInstance->Config->Send005(this);
925 this->WriteNumeric(42, "%s %s :your unique ID", this->nick, this->uuid);
931 if (ServerInstance->Users->unregistered_count)
932 ServerInstance->Users->unregistered_count--;
934 /* Trigger LUSERS output, give modules a chance too */
936 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
938 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
941 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
942 * for a user that doesn't exist yet.
944 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
946 this->registered = REG_ALL;
948 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
950 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);
951 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
952 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
955 /** User::UpdateNick()
956 * re-allocates a nick in the user_hash after they change nicknames,
957 * returns a pointer to the new user as it may have moved
959 User* User::UpdateNickHash(const char* New)
961 //user_hash::iterator newnick;
962 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
964 if (!strcasecmp(this->nick,New))
965 return oldnick->second;
967 if (oldnick == ServerInstance->Users->clientlist->end())
968 return NULL; /* doesnt exist */
970 User* olduser = oldnick->second;
971 (*(ServerInstance->Users->clientlist))[New] = olduser;
972 ServerInstance->Users->clientlist->erase(oldnick);
976 void User::InvalidateCache()
978 /* Invalidate cache */
980 free(cached_fullhost);
984 free(cached_makehost);
985 if (cached_fullrealhost)
986 free(cached_fullrealhost);
987 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
990 bool User::ForceNickChange(const char* newnick)
994 this->InvalidateCache();
996 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1000 ServerInstance->stats->statsCollisions++;
1004 if (ServerInstance->XLines->MatchesLine("Q",newnick))
1006 ServerInstance->stats->statsCollisions++;
1010 std::deque<classbase*> dummy;
1011 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1012 if (nickhandler) // wtfbbq, when would this not be here
1014 nickhandler->HandleInternal(1, dummy);
1015 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1016 nickhandler->HandleInternal(0, dummy);
1020 // Unreachable, we hope
1024 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1026 this->cachedip = "";
1028 switch (protocol_family)
1030 #ifdef SUPPORT_IP6LINKS
1033 sockaddr_in6* sin = new sockaddr_in6;
1034 sin->sin6_family = AF_INET6;
1035 sin->sin6_port = port;
1036 inet_pton(AF_INET6, sip, &sin->sin6_addr);
1037 this->ip = (sockaddr*)sin;
1043 sockaddr_in* sin = new sockaddr_in;
1044 sin->sin_family = AF_INET;
1045 sin->sin_port = port;
1046 inet_pton(AF_INET, sip, &sin->sin_addr);
1047 this->ip = (sockaddr*)sin;
1051 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1058 if (this->ip == NULL)
1061 switch (this->GetProtocolFamily())
1063 #ifdef SUPPORT_IP6LINKS
1066 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1067 return sin->sin6_port;
1073 sockaddr_in* sin = (sockaddr_in*)this->ip;
1074 return sin->sin_port;
1083 int User::GetProtocolFamily()
1085 if (this->ip == NULL)
1088 sockaddr_in* sin = (sockaddr_in*)this->ip;
1089 return sin->sin_family;
1093 * XXX the duplication here is horrid..
1094 * do we really need two methods doing essentially the same thing?
1096 const char* User::GetIPString()
1098 static char buf[1024];
1100 if (this->ip == NULL)
1103 if (!this->cachedip.empty())
1104 return this->cachedip.c_str();
1106 switch (this->GetProtocolFamily())
1108 #ifdef SUPPORT_IP6LINKS
1111 static char temp[1024];
1113 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1114 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1115 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1118 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1120 this->cachedip = temp;
1124 this->cachedip = buf;
1131 sockaddr_in* sin = (sockaddr_in*)this->ip;
1132 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1133 this->cachedip = buf;
1141 // Unreachable, probably
1145 /** NOTE: We cannot pass a const reference to this method.
1146 * The string is changed by the workings of the method,
1147 * so that if we pass const ref, we end up copying it to
1148 * something we can change anyway. Makes sense to just let
1149 * the compiler do that copy for us.
1151 void User::Write(std::string text)
1153 if (!ServerInstance->SE->BoundsCheckFd(this))
1158 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1159 text.append("\r\n");
1163 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1169 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1170 * implement their own buffering mechanisms
1174 this->io->OnRawSocketWrite(this->fd, text.data(), text.length());
1176 catch (CoreException& modexcept)
1178 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1183 this->AddWriteBuf(text);
1185 ServerInstance->stats->statsSent += text.length();
1186 this->ServerInstance->SE->WantWrite(this);
1191 void User::Write(const char *text, ...)
1194 char textbuffer[MAXBUF];
1196 va_start(argsPtr, text);
1197 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1200 this->Write(std::string(textbuffer));
1203 void User::WriteServ(const std::string& text)
1205 char textbuffer[MAXBUF];
1207 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1208 this->Write(std::string(textbuffer));
1212 * Same as Write(), except `text' is prefixed with `:server.name '.
1214 void User::WriteServ(const char* text, ...)
1217 char textbuffer[MAXBUF];
1219 va_start(argsPtr, text);
1220 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1223 this->WriteServ(std::string(textbuffer));
1227 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1230 char textbuffer[MAXBUF];
1232 va_start(argsPtr, text);
1233 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1236 this->WriteNumeric(numeric, std::string(textbuffer));
1239 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1241 char textbuffer[MAXBUF];
1244 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1249 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1250 this->Write(std::string(textbuffer));
1253 void User::WriteFrom(User *user, const std::string &text)
1257 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1259 this->Write(std::string(tb));
1263 /* write text from an originating user to originating user */
1265 void User::WriteFrom(User *user, const char* text, ...)
1268 char textbuffer[MAXBUF];
1270 va_start(argsPtr, text);
1271 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1274 this->WriteFrom(user, std::string(textbuffer));
1278 /* write text to an destination user from a source user (e.g. user privmsg) */
1280 void User::WriteTo(User *dest, const char *data, ...)
1282 char textbuffer[MAXBUF];
1285 va_start(argsPtr, data);
1286 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1289 this->WriteTo(dest, std::string(textbuffer));
1292 void User::WriteTo(User *dest, const std::string &data)
1294 dest->WriteFrom(this, data);
1298 void User::WriteCommon(const char* text, ...)
1300 char textbuffer[MAXBUF];
1303 if (this->registered != REG_ALL)
1306 va_start(argsPtr, text);
1307 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1310 this->WriteCommon(std::string(textbuffer));
1313 void User::WriteCommon(const std::string &text)
1315 bool sent_to_at_least_one = false;
1318 if (this->registered != REG_ALL)
1324 InitializeAlreadySent(ServerInstance->SE);
1326 /* We dont want to be doing this n times, just once */
1327 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1328 std::string out = tb;
1330 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1332 CUList* ulist = v->first->GetUsers();
1333 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1335 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1337 already_sent[i->first->fd] = uniq_id;
1338 i->first->Write(out);
1339 sent_to_at_least_one = true;
1345 * if the user was not in any channels, no users will receive the text. Make sure the user
1346 * receives their OWN message for WriteCommon
1348 if (!sent_to_at_least_one)
1350 this->Write(std::string(tb));
1355 /* write a formatted string to all users who share at least one common
1356 * channel, NOT including the source user e.g. for use in QUIT
1359 void User::WriteCommonExcept(const char* text, ...)
1361 char textbuffer[MAXBUF];
1364 va_start(argsPtr, text);
1365 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1368 this->WriteCommonExcept(std::string(textbuffer));
1371 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1376 if (this->registered != REG_ALL)
1382 InitializeAlreadySent(ServerInstance->SE);
1384 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1385 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1386 std::string out1 = tb1;
1387 std::string out2 = tb2;
1389 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1391 CUList *ulist = v->first->GetUsers();
1392 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1394 if (this != i->first)
1396 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1398 already_sent[i->first->fd] = uniq_id;
1399 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1406 void User::WriteCommonExcept(const std::string &text)
1411 if (this->registered != REG_ALL)
1417 InitializeAlreadySent(ServerInstance->SE);
1419 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1422 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1424 CUList *ulist = v->first->GetUsers();
1425 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1427 if (this != i->first)
1429 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1431 already_sent[i->first->fd] = uniq_id;
1432 i->first->Write(out1);
1440 void User::WriteWallOps(const std::string &text)
1442 if (!IS_LOCAL(this))
1445 std::string wallop("WALLOPS :");
1446 wallop.append(text);
1448 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1451 if (t->IsModeSet('w'))
1452 this->WriteTo(t,wallop);
1456 void User::WriteWallOps(const char* text, ...)
1458 if (!IS_LOCAL(this))
1461 char textbuffer[MAXBUF];
1464 va_start(argsPtr, text);
1465 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1468 this->WriteWallOps(std::string(textbuffer));
1471 /* return 0 or 1 depending if users u and u2 share one or more common channels
1472 * (used by QUIT, NICK etc which arent channel specific notices)
1474 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1475 * the first users channels then the second users channels within the outer loop,
1476 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1477 * all possible iterations). However this new function instead checks against the
1478 * channel's userlist in the inner loop which is a std::map<User*,User*>
1479 * and saves us time as we already know what pointer value we are after.
1480 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1481 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1483 bool User::SharesChannelWith(User *other)
1485 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1489 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1491 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1492 * by replacing it with a map::find which *should* be more efficient
1494 if (i->first->HasUser(other))
1500 bool User::ChangeName(const char* gecos)
1502 if (!strcmp(gecos, this->fullname))
1508 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1511 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1513 strlcpy(this->fullname,gecos,MAXGECOS+1);
1518 bool User::ChangeDisplayedHost(const char* shost)
1520 if (!strcmp(shost, this->dhost))
1526 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1529 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1532 if (this->ServerInstance->Config->CycleHosts)
1533 this->WriteCommonExcept("QUIT :Changing hosts");
1535 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1536 strlcpy(this->dhost,shost,64);
1538 this->InvalidateCache();
1540 if (this->ServerInstance->Config->CycleHosts)
1542 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1544 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1545 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1547 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1552 this->WriteNumeric(396, "%s %s :is now your displayed host",this->nick,this->dhost);
1557 bool User::ChangeIdent(const char* newident)
1559 if (!strcmp(newident, this->ident))
1562 if (this->ServerInstance->Config->CycleHosts)
1563 this->WriteCommonExcept("%s","QUIT :Changing ident");
1565 strlcpy(this->ident, newident, IDENTMAX+1);
1567 this->InvalidateCache();
1569 if (this->ServerInstance->Config->CycleHosts)
1571 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1573 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1574 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1576 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1583 void User::SendAll(const char* command, const char* text, ...)
1585 char textbuffer[MAXBUF];
1586 char formatbuffer[MAXBUF];
1589 va_start(argsPtr, text);
1590 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1593 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1594 std::string fmt = formatbuffer;
1596 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1603 std::string User::ChannelList(User* source)
1607 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1609 /* If the target is the same as the sender, let them see all their channels.
1610 * If the channel is NOT private/secret OR the user shares a common channel
1611 * If the user is an oper, and the <options:operspywhois> option is set.
1613 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1615 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1622 void User::SplitChanList(User* dest, const std::string &cl)
1625 std::ostringstream prefix;
1626 std::string::size_type start, pos, length;
1628 prefix << this->nick << " " << dest->nick << " :";
1629 line = prefix.str();
1630 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1632 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1634 length = (pos == std::string::npos) ? cl.length() : pos;
1636 if (line.length() + namelen + length - start > 510)
1638 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1639 line = prefix.str();
1642 if(pos == std::string::npos)
1644 line.append(cl.substr(start, length - start));
1649 line.append(cl.substr(start, length - start + 1));
1655 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1659 unsigned int User::GetMaxChans()
1661 return this->MaxChans;
1666 * Sets a user's connection class.
1667 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1668 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1669 * then their ip will be taken as 'priority' anyway, so for example,
1670 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1672 ConnectClass* User::SetClass(const std::string &explicit_name)
1674 ConnectClass *found = NULL;
1676 if (!IS_LOCAL(this))
1679 if (!explicit_name.empty())
1681 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1683 ConnectClass* c = *i;
1685 if (explicit_name == c->GetName() && !c->GetDisabled())
1693 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1695 ConnectClass* c = *i;
1697 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1701 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1710 if (!c->GetDisabled())
1717 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1720 /* deny change if change will take class over the limit */
1721 if (found->limit && (found->RefCount + 1 >= found->limit))
1723 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", found->limit);
1724 return this->MyClass;
1727 /* should always be valid, but just in case .. */
1730 if (found == this->MyClass) // no point changing this shit :P
1731 return this->MyClass;
1732 this->MyClass->RefCount--;
1733 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %lu", this->MyClass->RefCount);
1736 this->MyClass = found;
1737 this->MyClass->RefCount++;
1738 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %lu", this->MyClass->RefCount);
1741 return this->MyClass;
1744 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1745 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1746 * then their ip will be taken as 'priority' anyway, so for example,
1747 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1749 ConnectClass* User::GetClass()
1751 return this->MyClass;
1754 void User::PurgeEmptyChannels()
1756 std::vector<Channel*> to_delete;
1758 // firstly decrement the count on each channel
1759 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1761 f->first->RemoveAllPrefixes(this);
1762 if (f->first->DelUser(this) == 0)
1764 /* No users left in here, mark it for deletion */
1767 to_delete.push_back(f->first);
1771 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1776 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1778 Channel* thischan = *n;
1779 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1780 if (i2 != ServerInstance->chanlist->end())
1782 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1784 ServerInstance->chanlist->erase(i2);
1785 this->chans.erase(*n);
1792 void User::ShowMOTD()
1794 if (!ServerInstance->Config->MOTD.size())
1796 this->WriteNumeric(422, "%s :Message of the day file is missing.",this->nick);
1799 this->WriteNumeric(375, "%s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1801 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1802 this->WriteNumeric(372, "%s :- %s",this->nick,i->c_str());
1804 this->WriteNumeric(376, "%s :End of message of the day.", this->nick);
1807 void User::ShowRULES()
1809 if (!ServerInstance->Config->RULES.size())
1811 this->WriteNumeric(434, "%s :RULES File is missing",this->nick);
1815 this->WriteNumeric(308, "%s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1817 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1818 this->WriteNumeric(232, "%s :- %s",this->nick,i->c_str());
1820 this->WriteNumeric(309, "%s :End of RULES command.",this->nick);
1823 void User::HandleEvent(EventType et, int errornum)
1825 if (this->quitting) // drop everything, user is due to be quit
1828 /* WARNING: May delete this user! */
1829 int thisfd = this->GetFd();
1836 ServerInstance->ProcessUser(this);
1839 this->FlushWriteBuf();
1842 /** This should be safe, but dont DARE do anything after it -- Brain */
1843 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1849 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1852 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1853 if ((ServerInstance->SE->GetRef(thisfd) == this))
1855 if (!WriteError.empty())
1857 User::QuitUser(ServerInstance, this, GetWriteError());
1862 void User::SetOperQuit(const std::string &oquit)
1864 operquitmsg = oquit;
1867 const char* User::GetOperQuit()
1869 return operquitmsg.c_str();
1872 void User::IncreasePenalty(int increase)
1874 this->Penalty += increase;
1877 void User::DecreasePenalty(int decrease)
1879 this->Penalty -= decrease;
1890 bool VisData::VisibleTo(User* user)