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()];
32 /* XXX: Used for speeding up WriteCommon operations */
33 unsigned long uniq_id = 0;
35 std::string User::ProcessNoticeMasks(const char *sm)
37 bool adding = true, oldadding = false;
52 for (unsigned char d = 'A'; d <= 'z'; d++)
54 if (ServerInstance->SNO->IsEnabled(d))
56 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
58 if ((oldadding != adding) || (!output.length()))
59 output += (adding ? '+' : '-');
61 this->SetNoticeMask(d, adding);
70 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
72 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
74 if ((oldadding != adding) || (!output.length()))
75 output += (adding ? '+' : '-');
77 this->SetNoticeMask(*c, adding);
83 this->WriteNumeric(501, "%s %c :is unknown snomask char to me", this->nick, *c);
95 void User::StartDNSLookup()
100 const char* sip = this->GetIPString();
102 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
103 if (!strncmp(sip, "0::ffff:", 8))
104 res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
106 res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
108 this->ServerInstance->AddResolver(res_reverse, cached);
110 catch (CoreException& e)
112 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
116 bool User::IsNoticeMaskSet(unsigned char sm)
118 return (snomasks[sm-65]);
121 void User::SetNoticeMask(unsigned char sm, bool value)
123 snomasks[sm-65] = value;
126 const char* User::FormatNoticeMasks()
128 static char data[MAXBUF];
131 for (int n = 0; n < 64; n++)
134 data[offset++] = n+65;
143 bool User::IsModeSet(unsigned char m)
145 return (modes[m-65]);
148 void User::SetMode(unsigned char m, bool value)
153 const char* User::FormatModes()
155 static char data[MAXBUF];
157 for (int n = 0; n < 64; n++)
160 data[offset++] = n+65;
166 void User::DecrementModes()
168 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
169 for (unsigned char n = 'A'; n <= 'z'; n++)
173 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
174 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
177 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
184 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
186 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
187 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
188 reset_due = ServerInstance->Time();
189 age = ServerInstance->Time();
191 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
192 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
193 quietquit = OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
198 res_forward = res_reverse = NULL;
203 AllowedUserModes = NULL;
204 AllowedChanModes = NULL;
205 AllowedOperCommands = NULL;
208 memset(modes,0,sizeof(modes));
209 memset(snomasks,0,sizeof(snomasks));
210 /* Invalidate cache */
211 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
214 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
216 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
218 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
220 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
221 if (finduuid == Instance->Users->uuidlist->end())
222 (*Instance->Users->uuidlist)[uuid] = this;
224 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
229 /* NULL for remote users :) */
232 this->MyClass->RefCount--;
233 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %lu", this->MyClass->RefCount);
235 if (this->AllowedOperCommands)
237 delete AllowedOperCommands;
238 AllowedOperCommands = NULL;
241 if (this->AllowedUserModes)
243 delete[] AllowedUserModes;
244 AllowedUserModes = NULL;
247 if (this->AllowedChanModes)
249 delete[] AllowedChanModes;
250 AllowedChanModes = NULL;
253 this->InvalidateCache();
254 this->DecrementModes();
258 ServerInstance->Users->RemoveCloneCounts(this);
260 if (this->GetProtocolFamily() == AF_INET)
262 delete (sockaddr_in*)ip;
264 #ifdef SUPPORT_IP6LINKS
267 delete (sockaddr_in6*)ip;
272 ServerInstance->Users->uuidlist->erase(uuid);
275 char* User::MakeHost()
277 if (this->cached_makehost)
278 return this->cached_makehost;
281 /* This is much faster than snprintf */
283 for(char* n = ident; *n; n++)
286 for(char* n = host; *n; n++)
290 this->cached_makehost = strdup(nhost);
292 return this->cached_makehost;
295 char* User::MakeHostIP()
297 if (this->cached_hostip)
298 return this->cached_hostip;
301 /* This is much faster than snprintf */
303 for(char* n = ident; *n; n++)
306 for(const char* n = this->GetIPString(); *n; n++)
310 this->cached_hostip = strdup(ihost);
312 return this->cached_hostip;
315 void User::CloseSocket()
317 ServerInstance->SE->Shutdown(this, 2);
318 ServerInstance->SE->Close(this);
321 char* User::GetFullHost()
323 if (this->cached_fullhost)
324 return this->cached_fullhost;
328 for(char* n = nick; *n; n++)
331 for(char* n = ident; *n; n++)
334 for(char* n = dhost; *n; n++)
338 this->cached_fullhost = strdup(result);
340 return this->cached_fullhost;
343 char* User::MakeWildHost()
345 static char nresult[MAXBUF];
347 *t++ = '*'; *t++ = '!';
348 *t++ = '*'; *t++ = '@';
349 for(char* n = dhost; *n; n++)
355 int User::ReadData(void* buffer, size_t size)
360 return read(this->fd, buffer, size);
362 return recv(this->fd, (char*)buffer, size, 0);
370 char* User::GetFullRealHost()
372 if (this->cached_fullrealhost)
373 return this->cached_fullrealhost;
375 char fresult[MAXBUF];
377 for(char* n = nick; *n; n++)
380 for(char* n = ident; *n; n++)
383 for(char* n = host; *n; n++)
387 this->cached_fullrealhost = strdup(fresult);
389 return this->cached_fullrealhost;
392 bool User::IsInvited(const irc::string &channel)
394 time_t now = time(NULL);
395 InvitedList::iterator safei;
396 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
398 if (channel == i->first)
400 if (i->second != 0 && now > i->second)
402 /* Expired invite, remove it. */
405 invites.erase(safei);
414 InvitedList* User::GetInviteList()
416 time_t now = time(NULL);
417 /* Weed out expired invites here. */
418 InvitedList::iterator safei;
419 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
421 if (i->second != 0 && now > i->second)
423 /* Expired invite, remove it. */
426 invites.erase(safei);
432 void User::InviteTo(const irc::string &channel, time_t invtimeout)
434 time_t now = time(NULL);
435 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
436 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
438 if (channel == i->first)
440 if (i->second != 0 && invtimeout > i->second)
442 i->second = invtimeout;
446 invites.push_back(std::make_pair(channel, invtimeout));
449 void User::RemoveInvite(const irc::string &channel)
451 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
453 if (channel == i->first)
461 bool User::HasModePermission(unsigned char mode, ModeType type)
469 if (!AllowedUserModes || !AllowedChanModes)
472 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
476 bool User::HasPermission(const std::string &command)
479 * users on remote servers can completely bypass all permissions based checks.
480 * This prevents desyncs when one server has different type/class tags to another.
481 * That having been said, this does open things up to the possibility of source changes
482 * allowing remote kills, etc - but if they have access to the src, they most likely have
483 * access to the conf - so it's an end to a means either way.
488 // are they even an oper at all?
494 if (!AllowedOperCommands)
497 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
499 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
505 /** NOTE: We cannot pass a const reference to this method.
506 * The string is changed by the workings of the method,
507 * so that if we pass const ref, we end up copying it to
508 * something we can change anyway. Makes sense to just let
509 * the compiler do that copy for us.
511 bool User::AddBuffer(std::string a)
515 std::string::size_type i = a.rfind('\r');
517 while (i != std::string::npos)
526 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
528 this->SetWriteError("RecvQ exceeded");
529 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());
538 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
543 bool User::BufferIsReady()
545 return (recvq.find('\n') != std::string::npos);
548 void User::ClearBuffer()
553 std::string User::GetBuffer()
560 /* Strip any leading \r or \n off the string.
561 * Usually there are only one or two of these,
562 * so its is computationally cheap to do.
564 std::string::iterator t = recvq.begin();
565 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
571 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
573 /* Find the first complete line, return it as the
574 * result, and leave the recvq as whats left
578 std::string ret = std::string(recvq.begin(), x);
579 recvq.erase(recvq.begin(), x + 1);
588 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
593 void User::AddWriteBuf(const std::string &data)
595 if (*this->GetWriteError())
598 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
601 * Fix by brain - Set the error text BEFORE calling, because
602 * if we dont it'll recursively call here over and over again trying
603 * to repeatedly add the text to the sendq!
605 this->SetWriteError("SendQ exceeded");
606 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());
610 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
611 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
616 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
617 void User::FlushWriteBuf()
621 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
625 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
627 int old_sendq_length = sendq.length();
628 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
634 /* The socket buffer is full. This isnt fatal,
637 this->ServerInstance->SE->WantWrite(this);
641 /* Fatal error, set write error and bail
643 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
649 /* advance the queue */
651 this->sendq = this->sendq.substr(n_sent);
652 /* update the user's stats counters */
653 this->bytes_out += n_sent;
655 if (n_sent != old_sendq_length)
656 this->ServerInstance->SE->WantWrite(this);
663 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
666 if (this->sendq.empty())
668 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
672 void User::SetWriteError(const std::string &error)
674 // don't try to set the error twice, its already set take the first string.
675 if (this->WriteError.empty())
676 this->WriteError = error;
679 const char* User::GetWriteError()
681 return this->WriteError.c_str();
684 void User::Oper(const std::string &opertype, const std::string &opername)
692 this->modes[UM_OPERATOR] = 1;
693 this->WriteServ("MODE %s :+o", this->nick);
694 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
695 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
696 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
697 ServerInstance->Users->all_opers.push_back(this);
699 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
700 if (iter_opertype != ServerInstance->Config->opertypes.end())
703 if (AllowedOperCommands)
704 AllowedOperCommands->clear();
706 AllowedOperCommands = new std::map<std::string, bool>;
708 if (!AllowedChanModes)
709 AllowedChanModes = new bool[64];
711 if (!AllowedUserModes)
712 AllowedUserModes = new bool[64];
714 memset(AllowedUserModes, 0, 64);
715 memset(AllowedChanModes, 0, 64);
717 char* Classes = strdup(iter_opertype->second);
718 char* myclass = strtok_r(Classes," ",&savept);
721 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
722 if (iter_operclass != ServerInstance->Config->operclass.end())
724 char* CommandList = strdup(iter_operclass->second.commandlist);
725 mycmd = strtok_r(CommandList," ",&savept2);
728 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
729 mycmd = strtok_r(NULL," ",&savept2);
732 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
733 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
737 memset(this->AllowedUserModes, (int)(true), 64);
741 this->AllowedUserModes[*c - 'A'] = true;
744 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
748 memset(this->AllowedChanModes, (int)(true), 64);
752 this->AllowedChanModes[*c - 'A'] = true;
756 myclass = strtok_r(NULL," ",&savept);
761 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
766 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
774 /* Remove all oper only modes from the user when the deoper - Bug #466*/
775 std::string moderemove("-");
777 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
781 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
782 if (mh && mh->NeedsOper())
783 moderemove += letter;
787 const char* parameters[] = { this->nick, moderemove.c_str() };
788 ServerInstance->Parser->CallHandler("MODE", parameters, 2, this);
790 /* unset their oper type (what IS_OPER checks), and remove +o */
792 this->modes[UM_OPERATOR] = 0;
794 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
795 ServerInstance->Users->all_opers.remove(this);
797 if (AllowedOperCommands)
799 delete AllowedOperCommands;
800 AllowedOperCommands = NULL;
802 if (AllowedUserModes)
804 delete[] AllowedUserModes;
805 AllowedUserModes = NULL;
807 if (AllowedChanModes)
809 delete[] AllowedChanModes;
810 AllowedChanModes = NULL;
816 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
818 Instance->Logs->Log("USERS", DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
819 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
820 user->quietquit = false;
821 user->quitmsg = quitreason;
824 user->operquitmsg = quitreason;
826 user->operquitmsg = operreason;
828 Instance->GlobalCulls.AddItem(user);
831 /* adds or updates an entry in the whowas list */
832 void User::AddToWhoWas()
834 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
837 std::deque<classbase*> params;
838 params.push_back(this);
839 whowas_command->HandleInternal(WHOWAS_ADD, params);
844 * Check class restrictions
846 void User::CheckClass()
848 ConnectClass* a = this->MyClass;
850 if ((!a) || (a->GetType() == CC_DENY))
852 User::QuitUser(ServerInstance, this, "Unauthorised connection");
855 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
857 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
858 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
861 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
863 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
864 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
868 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
869 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
870 this->MaxChans = a->GetMaxChans();
873 void User::FullConnect()
875 ServerInstance->stats->statsConnects++;
876 this->idle_lastmsg = ServerInstance->Time();
879 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
880 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
881 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
882 * Don't remove this! -- w00t
886 /* Check the password, if one is required by the user's connect class.
887 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
889 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
891 User::QuitUser(ServerInstance, this, "Invalid password");
897 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
905 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
914 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
915 this->WriteNumeric(001, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
916 this->WriteNumeric(002, "%s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
917 this->WriteNumeric(003, "%s :This server was created %s %s", this->nick, __TIME__, __DATE__);
918 this->WriteNumeric(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());
920 ServerInstance->Config->Send005(this);
922 this->WriteNumeric(42, "%s %s :your unique ID", this->nick, this->uuid);
928 if (ServerInstance->Users->unregistered_count)
929 ServerInstance->Users->unregistered_count--;
931 /* Trigger LUSERS output, give modules a chance too */
933 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
935 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
938 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
939 * for a user that doesn't exist yet.
941 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
943 this->registered = REG_ALL;
945 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
947 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);
948 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
949 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
952 /** User::UpdateNick()
953 * re-allocates a nick in the user_hash after they change nicknames,
954 * returns a pointer to the new user as it may have moved
956 User* User::UpdateNickHash(const char* New)
958 //user_hash::iterator newnick;
959 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
961 if (!strcasecmp(this->nick,New))
962 return oldnick->second;
964 if (oldnick == ServerInstance->Users->clientlist->end())
965 return NULL; /* doesnt exist */
967 User* olduser = oldnick->second;
968 (*(ServerInstance->Users->clientlist))[New] = olduser;
969 ServerInstance->Users->clientlist->erase(oldnick);
973 void User::InvalidateCache()
975 /* Invalidate cache */
977 free(cached_fullhost);
981 free(cached_makehost);
982 if (cached_fullrealhost)
983 free(cached_fullrealhost);
984 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
987 bool User::ForceNickChange(const char* newnick)
990 * XXX this makes no sense..
991 * why do we do nothing for change on users not REG_ALL?
992 * why do we trigger events twice for everyone previously (and just them now)
993 * i think the first if () needs removing totally, or? -- w00t
995 if (this->registered != REG_ALL)
999 this->InvalidateCache();
1001 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1005 ServerInstance->stats->statsCollisions++;
1009 if (ServerInstance->XLines->MatchesLine("Q",newnick))
1011 ServerInstance->stats->statsCollisions++;
1017 std::deque<classbase*> dummy;
1018 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1019 if (nickhandler) // wtfbbq, when would this not be here
1021 nickhandler->HandleInternal(1, dummy);
1022 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1023 nickhandler->HandleInternal(0, dummy);
1032 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1034 this->cachedip = "";
1036 switch (protocol_family)
1038 #ifdef SUPPORT_IP6LINKS
1041 sockaddr_in6* sin = new sockaddr_in6;
1042 sin->sin6_family = AF_INET6;
1043 sin->sin6_port = port;
1044 inet_pton(AF_INET6, sip, &sin->sin6_addr);
1045 this->ip = (sockaddr*)sin;
1051 sockaddr_in* sin = new sockaddr_in;
1052 sin->sin_family = AF_INET;
1053 sin->sin_port = port;
1054 inet_pton(AF_INET, sip, &sin->sin_addr);
1055 this->ip = (sockaddr*)sin;
1059 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1066 if (this->ip == NULL)
1069 switch (this->GetProtocolFamily())
1071 #ifdef SUPPORT_IP6LINKS
1074 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1075 return sin->sin6_port;
1081 sockaddr_in* sin = (sockaddr_in*)this->ip;
1082 return sin->sin_port;
1091 int User::GetProtocolFamily()
1093 if (this->ip == NULL)
1096 sockaddr_in* sin = (sockaddr_in*)this->ip;
1097 return sin->sin_family;
1101 * XXX the duplication here is horrid..
1102 * do we really need two methods doing essentially the same thing?
1104 const char* User::GetIPString()
1106 static char buf[1024];
1108 if (this->ip == NULL)
1111 if (!this->cachedip.empty())
1112 return this->cachedip.c_str();
1114 switch (this->GetProtocolFamily())
1116 #ifdef SUPPORT_IP6LINKS
1119 static char temp[1024];
1121 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1122 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1123 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1126 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1128 this->cachedip = temp;
1132 this->cachedip = buf;
1139 sockaddr_in* sin = (sockaddr_in*)this->ip;
1140 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1141 this->cachedip = buf;
1149 // Unreachable, probably
1153 /** NOTE: We cannot pass a const reference to this method.
1154 * The string is changed by the workings of the method,
1155 * so that if we pass const ref, we end up copying it to
1156 * something we can change anyway. Makes sense to just let
1157 * the compiler do that copy for us.
1159 void User::Write(std::string text)
1161 if (!ServerInstance->SE->BoundsCheckFd(this))
1166 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1167 text.append("\r\n");
1171 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1177 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1178 * implement their own buffering mechanisms
1182 this->io->OnRawSocketWrite(this->fd, text.data(), text.length());
1184 catch (CoreException& modexcept)
1186 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1191 this->AddWriteBuf(text);
1193 ServerInstance->stats->statsSent += text.length();
1194 this->ServerInstance->SE->WantWrite(this);
1199 void User::Write(const char *text, ...)
1202 char textbuffer[MAXBUF];
1204 va_start(argsPtr, text);
1205 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1208 this->Write(std::string(textbuffer));
1211 void User::WriteServ(const std::string& text)
1213 char textbuffer[MAXBUF];
1215 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1216 this->Write(std::string(textbuffer));
1220 * Same as Write(), except `text' is prefixed with `:server.name '.
1222 void User::WriteServ(const char* text, ...)
1225 char textbuffer[MAXBUF];
1227 va_start(argsPtr, text);
1228 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1231 this->WriteServ(std::string(textbuffer));
1235 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1238 char textbuffer[MAXBUF];
1240 va_start(argsPtr, text);
1241 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1244 this->WriteNumeric(numeric, std::string(textbuffer));
1247 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1249 char textbuffer[MAXBUF];
1252 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1257 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1258 this->Write(std::string(textbuffer));
1261 void User::WriteFrom(User *user, const std::string &text)
1265 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1267 this->Write(std::string(tb));
1271 /* write text from an originating user to originating user */
1273 void User::WriteFrom(User *user, const char* text, ...)
1276 char textbuffer[MAXBUF];
1278 va_start(argsPtr, text);
1279 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1282 this->WriteFrom(user, std::string(textbuffer));
1286 /* write text to an destination user from a source user (e.g. user privmsg) */
1288 void User::WriteTo(User *dest, const char *data, ...)
1290 char textbuffer[MAXBUF];
1293 va_start(argsPtr, data);
1294 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1297 this->WriteTo(dest, std::string(textbuffer));
1300 void User::WriteTo(User *dest, const std::string &data)
1302 dest->WriteFrom(this, data);
1306 void User::WriteCommon(const char* text, ...)
1308 char textbuffer[MAXBUF];
1311 if (this->registered != REG_ALL)
1314 va_start(argsPtr, text);
1315 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1318 this->WriteCommon(std::string(textbuffer));
1321 void User::WriteCommon(const std::string &text)
1323 bool sent_to_at_least_one = false;
1326 if (this->registered != REG_ALL)
1332 InitializeAlreadySent(ServerInstance->SE);
1334 /* We dont want to be doing this n times, just once */
1335 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1336 std::string out = tb;
1338 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1340 CUList* ulist = v->first->GetUsers();
1341 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1343 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1345 already_sent[i->first->fd] = uniq_id;
1346 i->first->Write(out);
1347 sent_to_at_least_one = true;
1353 * if the user was not in any channels, no users will receive the text. Make sure the user
1354 * receives their OWN message for WriteCommon
1356 if (!sent_to_at_least_one)
1358 this->Write(std::string(tb));
1363 /* write a formatted string to all users who share at least one common
1364 * channel, NOT including the source user e.g. for use in QUIT
1367 void User::WriteCommonExcept(const char* text, ...)
1369 char textbuffer[MAXBUF];
1372 va_start(argsPtr, text);
1373 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1376 this->WriteCommonExcept(std::string(textbuffer));
1379 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1384 if (this->registered != REG_ALL)
1390 InitializeAlreadySent(ServerInstance->SE);
1392 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1393 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1394 std::string out1 = tb1;
1395 std::string out2 = tb2;
1397 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1399 CUList *ulist = v->first->GetUsers();
1400 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1402 if (this != i->first)
1404 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1406 already_sent[i->first->fd] = uniq_id;
1407 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1414 void User::WriteCommonExcept(const std::string &text)
1419 if (this->registered != REG_ALL)
1425 InitializeAlreadySent(ServerInstance->SE);
1427 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1430 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1432 CUList *ulist = v->first->GetUsers();
1433 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1435 if (this != i->first)
1437 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1439 already_sent[i->first->fd] = uniq_id;
1440 i->first->Write(out1);
1448 void User::WriteWallOps(const std::string &text)
1450 if (!IS_OPER(this) && IS_LOCAL(this))
1453 std::string wallop("WALLOPS :");
1454 wallop.append(text);
1456 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1459 if (t->IsModeSet('w'))
1460 this->WriteTo(t,wallop);
1464 void User::WriteWallOps(const char* text, ...)
1466 char textbuffer[MAXBUF];
1469 va_start(argsPtr, text);
1470 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1473 this->WriteWallOps(std::string(textbuffer));
1476 /* return 0 or 1 depending if users u and u2 share one or more common channels
1477 * (used by QUIT, NICK etc which arent channel specific notices)
1479 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1480 * the first users channels then the second users channels within the outer loop,
1481 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1482 * all possible iterations). However this new function instead checks against the
1483 * channel's userlist in the inner loop which is a std::map<User*,User*>
1484 * and saves us time as we already know what pointer value we are after.
1485 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1486 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1488 bool User::SharesChannelWith(User *other)
1490 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1494 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1496 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1497 * by replacing it with a map::find which *should* be more efficient
1499 if (i->first->HasUser(other))
1505 bool User::ChangeName(const char* gecos)
1507 if (!strcmp(gecos, this->fullname))
1513 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1516 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1518 strlcpy(this->fullname,gecos,MAXGECOS+1);
1523 bool User::ChangeDisplayedHost(const char* shost)
1525 if (!strcmp(shost, this->dhost))
1531 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1534 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1537 if (this->ServerInstance->Config->CycleHosts)
1538 this->WriteCommonExcept("QUIT :Changing hosts");
1540 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1541 strlcpy(this->dhost,shost,64);
1543 this->InvalidateCache();
1545 if (this->ServerInstance->Config->CycleHosts)
1547 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1549 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1550 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1552 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1557 this->WriteNumeric(396, "%s %s :is now your displayed host",this->nick,this->dhost);
1562 bool User::ChangeIdent(const char* newident)
1564 if (!strcmp(newident, this->ident))
1567 if (this->ServerInstance->Config->CycleHosts)
1568 this->WriteCommonExcept("%s","QUIT :Changing ident");
1570 strlcpy(this->ident, newident, IDENTMAX+1);
1572 this->InvalidateCache();
1574 if (this->ServerInstance->Config->CycleHosts)
1576 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1578 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1579 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1581 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1588 void User::SendAll(const char* command, const char* text, ...)
1590 char textbuffer[MAXBUF];
1591 char formatbuffer[MAXBUF];
1594 va_start(argsPtr, text);
1595 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1598 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1599 std::string fmt = formatbuffer;
1601 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1608 std::string User::ChannelList(User* source)
1612 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1614 /* If the target is the same as the sender, let them see all their channels.
1615 * If the channel is NOT private/secret OR the user shares a common channel
1616 * If the user is an oper, and the <options:operspywhois> option is set.
1618 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1620 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1627 void User::SplitChanList(User* dest, const std::string &cl)
1630 std::ostringstream prefix;
1631 std::string::size_type start, pos, length;
1633 prefix << this->nick << " " << dest->nick << " :";
1634 line = prefix.str();
1635 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1637 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1639 length = (pos == std::string::npos) ? cl.length() : pos;
1641 if (line.length() + namelen + length - start > 510)
1643 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1644 line = prefix.str();
1647 if(pos == std::string::npos)
1649 line.append(cl.substr(start, length - start));
1654 line.append(cl.substr(start, length - start + 1));
1660 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1664 unsigned int User::GetMaxChans()
1666 return this->MaxChans;
1671 * Sets a user's connection class.
1672 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1673 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1674 * then their ip will be taken as 'priority' anyway, so for example,
1675 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1677 ConnectClass* User::SetClass(const std::string &explicit_name)
1679 ConnectClass *found = NULL;
1681 if (!IS_LOCAL(this))
1684 if (!explicit_name.empty())
1686 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1688 ConnectClass* c = *i;
1690 if (explicit_name == c->GetName() && !c->GetDisabled())
1698 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1700 ConnectClass* c = *i;
1702 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1706 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1715 if (!c->GetDisabled())
1722 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1725 /* deny change if change will take class over the limit */
1726 if (found->limit && (found->RefCount + 1 >= found->limit))
1728 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", found->limit);
1729 return this->MyClass;
1732 /* should always be valid, but just in case .. */
1735 if (found == this->MyClass) // no point changing this shit :P
1736 return this->MyClass;
1737 this->MyClass->RefCount--;
1738 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %lu", this->MyClass->RefCount);
1741 this->MyClass = found;
1742 this->MyClass->RefCount++;
1743 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %lu", this->MyClass->RefCount);
1746 return this->MyClass;
1749 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1750 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1751 * then their ip will be taken as 'priority' anyway, so for example,
1752 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1754 ConnectClass* User::GetClass()
1756 return this->MyClass;
1759 void User::PurgeEmptyChannels()
1761 std::vector<Channel*> to_delete;
1763 // firstly decrement the count on each channel
1764 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1766 f->first->RemoveAllPrefixes(this);
1767 if (f->first->DelUser(this) == 0)
1769 /* No users left in here, mark it for deletion */
1772 to_delete.push_back(f->first);
1776 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1781 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1783 Channel* thischan = *n;
1784 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1785 if (i2 != ServerInstance->chanlist->end())
1787 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1789 ServerInstance->chanlist->erase(i2);
1790 this->chans.erase(*n);
1797 void User::ShowMOTD()
1799 if (!ServerInstance->Config->MOTD.size())
1801 this->WriteNumeric(422, "%s :Message of the day file is missing.",this->nick);
1804 this->WriteNumeric(375, "%s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1806 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1807 this->WriteNumeric(372, "%s :- %s",this->nick,i->c_str());
1809 this->WriteNumeric(376, "%s :End of message of the day.", this->nick);
1812 void User::ShowRULES()
1814 if (!ServerInstance->Config->RULES.size())
1816 this->WriteNumeric(434, "%s :RULES File is missing",this->nick);
1820 this->WriteNumeric(308, "%s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1822 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1823 this->WriteNumeric(232, "%s :- %s",this->nick,i->c_str());
1825 this->WriteNumeric(309, "%s :End of RULES command.",this->nick);
1828 void User::HandleEvent(EventType et, int errornum)
1830 if (this->quitting) // drop everything, user is due to be quit
1833 /* WARNING: May delete this user! */
1834 int thisfd = this->GetFd();
1841 ServerInstance->ProcessUser(this);
1844 this->FlushWriteBuf();
1847 /** This should be safe, but dont DARE do anything after it -- Brain */
1848 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1854 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1857 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1858 if ((ServerInstance->SE->GetRef(thisfd) == this))
1860 if (!WriteError.empty())
1862 User::QuitUser(ServerInstance, this, GetWriteError());
1867 void User::SetOperQuit(const std::string &oquit)
1869 operquitmsg = oquit;
1872 const char* User::GetOperQuit()
1874 return operquitmsg.c_str();
1877 void User::IncreasePenalty(int increase)
1879 this->Penalty += increase;
1882 void User::DecreasePenalty(int decrease)
1884 this->Penalty -= decrease;
1895 bool VisData::VisibleTo(User* user)