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);
77 this->WriteNumeric(501, "%s %c :is unknown snomask char to me", this->nick, *c);
89 void User::StartDNSLookup()
94 const char* sip = this->GetIPString();
96 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
97 if (!strncmp(sip, "0::ffff:", 8))
98 res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
100 res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
102 this->ServerInstance->AddResolver(res_reverse, cached);
104 catch (CoreException& e)
106 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
110 bool User::IsNoticeMaskSet(unsigned char sm)
112 return (snomasks[sm-65]);
115 void User::SetNoticeMask(unsigned char sm, bool value)
117 snomasks[sm-65] = value;
120 const char* User::FormatNoticeMasks()
122 static char data[MAXBUF];
125 for (int n = 0; n < 64; n++)
128 data[offset++] = n+65;
137 bool User::IsModeSet(unsigned char m)
139 return (modes[m-65]);
142 void User::SetMode(unsigned char m, bool value)
147 const char* User::FormatModes()
149 static char data[MAXBUF];
151 for (int n = 0; n < 64; n++)
154 data[offset++] = n+65;
160 void User::DecrementModes()
162 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
163 for (unsigned char n = 'A'; n <= 'z'; n++)
167 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
168 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
171 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
178 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
180 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
181 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
182 reset_due = ServerInstance->Time();
183 age = ServerInstance->Time();
185 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
186 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
187 quietquit = OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
192 res_forward = res_reverse = NULL;
196 AllowedUserModes = NULL;
197 AllowedChanModes = NULL;
198 AllowedOperCommands = NULL;
201 memset(modes,0,sizeof(modes));
202 memset(snomasks,0,sizeof(snomasks));
203 /* Invalidate cache */
204 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
207 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
209 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
211 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
213 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
214 if (finduuid == Instance->Users->uuidlist->end())
215 (*Instance->Users->uuidlist)[uuid] = this;
217 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
222 /* NULL for remote users :) */
225 this->MyClass->RefCount--;
226 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %u", this->MyClass->RefCount);
228 if (this->AllowedOperCommands)
230 delete AllowedOperCommands;
231 AllowedOperCommands = NULL;
234 if (this->AllowedUserModes)
236 delete AllowedUserModes;
237 AllowedUserModes = NULL;
240 if (this->AllowedChanModes)
242 delete AllowedChanModes;
243 AllowedChanModes = NULL;
246 this->InvalidateCache();
247 this->DecrementModes();
251 ServerInstance->Users->RemoveCloneCounts(this);
253 if (this->GetProtocolFamily() == AF_INET)
255 delete (sockaddr_in*)ip;
257 #ifdef SUPPORT_IP6LINKS
260 delete (sockaddr_in6*)ip;
265 ServerInstance->Users->uuidlist->erase(uuid);
268 char* User::MakeHost()
270 if (this->cached_makehost)
271 return this->cached_makehost;
274 /* This is much faster than snprintf */
276 for(char* n = ident; *n; n++)
279 for(char* n = host; *n; n++)
283 this->cached_makehost = strdup(nhost);
285 return this->cached_makehost;
288 char* User::MakeHostIP()
290 if (this->cached_hostip)
291 return this->cached_hostip;
294 /* This is much faster than snprintf */
296 for(char* n = ident; *n; n++)
299 for(const char* n = this->GetIPString(); *n; n++)
303 this->cached_hostip = strdup(ihost);
305 return this->cached_hostip;
308 void User::CloseSocket()
310 ServerInstance->SE->Shutdown(this, 2);
311 ServerInstance->SE->Close(this);
314 char* User::GetFullHost()
316 if (this->cached_fullhost)
317 return this->cached_fullhost;
321 for(char* n = nick; *n; n++)
324 for(char* n = ident; *n; n++)
327 for(char* n = dhost; *n; n++)
331 this->cached_fullhost = strdup(result);
333 return this->cached_fullhost;
336 char* User::MakeWildHost()
338 static char nresult[MAXBUF];
340 *t++ = '*'; *t++ = '!';
341 *t++ = '*'; *t++ = '@';
342 for(char* n = dhost; *n; n++)
348 int User::ReadData(void* buffer, size_t size)
353 return read(this->fd, buffer, size);
355 return recv(this->fd, (char*)buffer, size, 0);
363 char* User::GetFullRealHost()
365 if (this->cached_fullrealhost)
366 return this->cached_fullrealhost;
368 char fresult[MAXBUF];
370 for(char* n = nick; *n; n++)
373 for(char* n = ident; *n; n++)
376 for(char* n = host; *n; n++)
380 this->cached_fullrealhost = strdup(fresult);
382 return this->cached_fullrealhost;
385 bool User::IsInvited(const irc::string &channel)
387 time_t now = time(NULL);
388 InvitedList::iterator safei;
389 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
391 if (channel == i->first)
393 if (i->second != 0 && now > i->second)
395 /* Expired invite, remove it. */
398 invites.erase(safei);
407 InvitedList* User::GetInviteList()
409 time_t now = time(NULL);
410 /* Weed out expired invites here. */
411 InvitedList::iterator safei;
412 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
414 if (i->second != 0 && now > i->second)
416 /* Expired invite, remove it. */
419 invites.erase(safei);
425 void User::InviteTo(const irc::string &channel, time_t invtimeout)
427 time_t now = time(NULL);
428 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
429 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
431 if (channel == i->first)
433 if (i->second != 0 && invtimeout > i->second)
435 i->second = invtimeout;
439 invites.push_back(std::make_pair(channel, invtimeout));
442 void User::RemoveInvite(const irc::string &channel)
444 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
446 if (channel == i->first)
454 bool User::HasModePermission(unsigned char mode, ModeType type)
462 if (!AllowedUserModes || !AllowedChanModes)
465 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
469 bool User::HasPermission(const std::string &command)
472 * users on remote servers can completely bypass all permissions based checks.
473 * This prevents desyncs when one server has different type/class tags to another.
474 * That having been said, this does open things up to the possibility of source changes
475 * allowing remote kills, etc - but if they have access to the src, they most likely have
476 * access to the conf - so it's an end to a means either way.
481 // are they even an oper at all?
487 if (!AllowedOperCommands)
490 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
492 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
498 /** NOTE: We cannot pass a const reference to this method.
499 * The string is changed by the workings of the method,
500 * so that if we pass const ref, we end up copying it to
501 * something we can change anyway. Makes sense to just let
502 * the compiler do that copy for us.
504 bool User::AddBuffer(std::string a)
508 std::string::size_type i = a.rfind('\r');
510 while (i != std::string::npos)
519 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
521 this->SetWriteError("RecvQ exceeded");
522 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
531 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
536 bool User::BufferIsReady()
538 return (recvq.find('\n') != std::string::npos);
541 void User::ClearBuffer()
546 std::string User::GetBuffer()
553 /* Strip any leading \r or \n off the string.
554 * Usually there are only one or two of these,
555 * so its is computationally cheap to do.
557 std::string::iterator t = recvq.begin();
558 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
564 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
566 /* Find the first complete line, return it as the
567 * result, and leave the recvq as whats left
571 std::string ret = std::string(recvq.begin(), x);
572 recvq.erase(recvq.begin(), x + 1);
581 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
586 void User::AddWriteBuf(const std::string &data)
588 if (*this->GetWriteError())
591 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
594 * Fix by brain - Set the error text BEFORE calling, because
595 * if we dont it'll recursively call here over and over again trying
596 * to repeatedly add the text to the sendq!
598 this->SetWriteError("SendQ exceeded");
599 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
603 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
604 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
609 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
610 void User::FlushWriteBuf()
614 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
618 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
620 int old_sendq_length = sendq.length();
621 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
627 /* The socket buffer is full. This isnt fatal,
630 this->ServerInstance->SE->WantWrite(this);
634 /* Fatal error, set write error and bail
636 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
642 /* advance the queue */
644 this->sendq = this->sendq.substr(n_sent);
645 /* update the user's stats counters */
646 this->bytes_out += n_sent;
648 if (n_sent != old_sendq_length)
649 this->ServerInstance->SE->WantWrite(this);
656 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
659 if (this->sendq.empty())
661 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
665 void User::SetWriteError(const std::string &error)
667 // don't try to set the error twice, its already set take the first string.
668 if (this->WriteError.empty())
669 this->WriteError = error;
672 const char* User::GetWriteError()
674 return this->WriteError.c_str();
677 void User::Oper(const std::string &opertype, const std::string &opername)
685 this->modes[UM_OPERATOR] = 1;
686 this->WriteServ("MODE %s :+o", this->nick);
687 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
688 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
689 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
690 ServerInstance->Users->all_opers.push_back(this);
692 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
693 if (iter_opertype != ServerInstance->Config->opertypes.end())
696 if (AllowedOperCommands)
697 AllowedOperCommands->clear();
699 AllowedOperCommands = new std::map<std::string, bool>;
701 if (!AllowedChanModes)
702 AllowedChanModes = new bool[64];
704 if (!AllowedUserModes)
705 AllowedUserModes = new bool[64];
707 memset(AllowedUserModes, 0, 64);
708 memset(AllowedChanModes, 0, 64);
710 char* Classes = strdup(iter_opertype->second);
711 char* myclass = strtok_r(Classes," ",&savept);
714 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
715 if (iter_operclass != ServerInstance->Config->operclass.end())
717 char* CommandList = strdup(iter_operclass->second.commandlist);
718 mycmd = strtok_r(CommandList," ",&savept2);
721 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
722 mycmd = strtok_r(NULL," ",&savept2);
725 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
726 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
730 memset(this->AllowedUserModes, (int)(true), sizeof(this->AllowedUserModes));
734 this->AllowedUserModes[*c - 'A'] = true;
737 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
741 memset(this->AllowedChanModes, (int)(true), sizeof(this->AllowedChanModes));
745 this->AllowedChanModes[*c - 'A'] = true;
749 myclass = strtok_r(NULL," ",&savept);
754 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
759 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
767 /* Remove all oper only modes from the user when the deoper - Bug #466*/
768 std::string moderemove("-");
770 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
774 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
775 if (mh && mh->NeedsOper())
776 moderemove += letter;
780 const char* parameters[] = { this->nick, moderemove.c_str() };
781 ServerInstance->Parser->CallHandler("MODE", parameters, 2, this);
783 /* unset their oper type (what IS_OPER checks), and remove +o */
785 this->modes[UM_OPERATOR] = 0;
787 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
788 ServerInstance->Users->all_opers.remove(this);
790 if (AllowedOperCommands)
792 delete AllowedOperCommands;
793 AllowedOperCommands = NULL;
798 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
800 Instance->Logs->Log("USERS", DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
801 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
802 user->quietquit = false;
803 user->quitmsg = quitreason;
806 user->operquitmsg = quitreason;
808 user->operquitmsg = operreason;
810 Instance->GlobalCulls.AddItem(user);
813 /* adds or updates an entry in the whowas list */
814 void User::AddToWhoWas()
816 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
819 std::deque<classbase*> params;
820 params.push_back(this);
821 whowas_command->HandleInternal(WHOWAS_ADD, params);
826 * Check class restrictions
828 void User::CheckClass()
830 ConnectClass* a = this->MyClass;
832 if ((!a) || (a->GetType() == CC_DENY))
834 User::QuitUser(ServerInstance, this, "Unauthorised connection");
837 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
839 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
840 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
843 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
845 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
846 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
850 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
851 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
852 this->MaxChans = a->GetMaxChans();
855 void User::FullConnect()
857 ServerInstance->stats->statsConnects++;
858 this->idle_lastmsg = ServerInstance->Time();
861 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
862 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
863 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
864 * Don't remove this! -- w00t
868 /* Check the password, if one is required by the user's connect class.
869 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
871 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
873 User::QuitUser(ServerInstance, this, "Invalid password");
879 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
887 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
896 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
897 this->WriteNumeric(001, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
898 this->WriteNumeric(002, "%s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
899 this->WriteNumeric(003, "%s :This server was created %s %s", this->nick, __TIME__, __DATE__);
900 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());
902 ServerInstance->Config->Send005(this);
904 this->WriteNumeric(42, "%s %s :your unique ID", this->nick, this->uuid);
910 if (ServerInstance->Users->unregistered_count)
911 ServerInstance->Users->unregistered_count--;
913 /* Trigger LUSERS output, give modules a chance too */
915 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
917 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
920 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
921 * for a user that doesn't exist yet.
923 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
925 this->registered = REG_ALL;
927 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
929 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);
930 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
931 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
934 /** User::UpdateNick()
935 * re-allocates a nick in the user_hash after they change nicknames,
936 * returns a pointer to the new user as it may have moved
938 User* User::UpdateNickHash(const char* New)
940 //user_hash::iterator newnick;
941 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
943 if (!strcasecmp(this->nick,New))
944 return oldnick->second;
946 if (oldnick == ServerInstance->Users->clientlist->end())
947 return NULL; /* doesnt exist */
949 User* olduser = oldnick->second;
950 (*(ServerInstance->Users->clientlist))[New] = olduser;
951 ServerInstance->Users->clientlist->erase(oldnick);
955 void User::InvalidateCache()
957 /* Invalidate cache */
959 free(cached_fullhost);
963 free(cached_makehost);
964 if (cached_fullrealhost)
965 free(cached_fullrealhost);
966 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
969 bool User::ForceNickChange(const char* newnick)
972 * XXX this makes no sense..
973 * why do we do nothing for change on users not REG_ALL?
974 * why do we trigger events twice for everyone previously (and just them now)
975 * i think the first if () needs removing totally, or? -- w00t
977 if (this->registered != REG_ALL)
981 this->InvalidateCache();
983 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
987 ServerInstance->stats->statsCollisions++;
991 if (ServerInstance->XLines->MatchesLine("Q",newnick))
993 ServerInstance->stats->statsCollisions++;
999 std::deque<classbase*> dummy;
1000 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1001 if (nickhandler) // wtfbbq, when would this not be here
1003 nickhandler->HandleInternal(1, dummy);
1004 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1005 nickhandler->HandleInternal(0, dummy);
1014 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1016 this->cachedip = "";
1018 switch (protocol_family)
1020 #ifdef SUPPORT_IP6LINKS
1023 sockaddr_in6* sin = new sockaddr_in6;
1024 sin->sin6_family = AF_INET6;
1025 sin->sin6_port = port;
1026 inet_pton(AF_INET6, sip, &sin->sin6_addr);
1027 this->ip = (sockaddr*)sin;
1033 sockaddr_in* sin = new sockaddr_in;
1034 sin->sin_family = AF_INET;
1035 sin->sin_port = port;
1036 inet_pton(AF_INET, sip, &sin->sin_addr);
1037 this->ip = (sockaddr*)sin;
1041 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1048 if (this->ip == NULL)
1051 switch (this->GetProtocolFamily())
1053 #ifdef SUPPORT_IP6LINKS
1056 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1057 return sin->sin6_port;
1063 sockaddr_in* sin = (sockaddr_in*)this->ip;
1064 return sin->sin_port;
1073 int User::GetProtocolFamily()
1075 if (this->ip == NULL)
1078 sockaddr_in* sin = (sockaddr_in*)this->ip;
1079 return sin->sin_family;
1083 * XXX the duplication here is horrid..
1084 * do we really need two methods doing essentially the same thing?
1086 const char* User::GetIPString()
1088 static char buf[1024];
1090 if (this->ip == NULL)
1093 if (!this->cachedip.empty())
1094 return this->cachedip.c_str();
1096 switch (this->GetProtocolFamily())
1098 #ifdef SUPPORT_IP6LINKS
1101 static char temp[1024];
1103 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1104 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1105 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1108 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1110 this->cachedip = temp;
1114 this->cachedip = buf;
1121 sockaddr_in* sin = (sockaddr_in*)this->ip;
1122 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1123 this->cachedip = buf;
1131 // Unreachable, probably
1135 /** NOTE: We cannot pass a const reference to this method.
1136 * The string is changed by the workings of the method,
1137 * so that if we pass const ref, we end up copying it to
1138 * something we can change anyway. Makes sense to just let
1139 * the compiler do that copy for us.
1141 void User::Write(std::string text)
1143 if (!ServerInstance->SE->BoundsCheckFd(this))
1148 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1149 text.append("\r\n");
1153 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1157 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1159 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1160 * implement their own buffering mechanisms
1164 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1166 catch (CoreException& modexcept)
1168 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1173 this->AddWriteBuf(text);
1175 ServerInstance->stats->statsSent += text.length();
1176 this->ServerInstance->SE->WantWrite(this);
1181 void User::Write(const char *text, ...)
1184 char textbuffer[MAXBUF];
1186 va_start(argsPtr, text);
1187 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1190 this->Write(std::string(textbuffer));
1193 void User::WriteServ(const std::string& text)
1195 char textbuffer[MAXBUF];
1197 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1198 this->Write(std::string(textbuffer));
1202 * Same as Write(), except `text' is prefixed with `:server.name '.
1204 void User::WriteServ(const char* text, ...)
1207 char textbuffer[MAXBUF];
1209 va_start(argsPtr, text);
1210 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1213 this->WriteServ(std::string(textbuffer));
1217 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1220 char textbuffer[MAXBUF];
1222 va_start(argsPtr, text);
1223 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1226 this->WriteNumeric(numeric, std::string(textbuffer));
1229 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1231 char textbuffer[MAXBUF];
1234 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1239 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1240 this->Write(std::string(textbuffer));
1243 void User::WriteFrom(User *user, const std::string &text)
1247 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1249 this->Write(std::string(tb));
1253 /* write text from an originating user to originating user */
1255 void User::WriteFrom(User *user, const char* text, ...)
1258 char textbuffer[MAXBUF];
1260 va_start(argsPtr, text);
1261 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1264 this->WriteFrom(user, std::string(textbuffer));
1268 /* write text to an destination user from a source user (e.g. user privmsg) */
1270 void User::WriteTo(User *dest, const char *data, ...)
1272 char textbuffer[MAXBUF];
1275 va_start(argsPtr, data);
1276 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1279 this->WriteTo(dest, std::string(textbuffer));
1282 void User::WriteTo(User *dest, const std::string &data)
1284 dest->WriteFrom(this, data);
1288 void User::WriteCommon(const char* text, ...)
1290 char textbuffer[MAXBUF];
1293 if (this->registered != REG_ALL)
1296 va_start(argsPtr, text);
1297 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1300 this->WriteCommon(std::string(textbuffer));
1303 void User::WriteCommon(const std::string &text)
1305 bool sent_to_at_least_one = false;
1308 if (this->registered != REG_ALL)
1313 /* We dont want to be doing this n times, just once */
1314 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1315 std::string out = tb;
1317 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1319 CUList* ulist = v->first->GetUsers();
1320 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1322 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1324 already_sent[i->first->fd] = uniq_id;
1325 i->first->Write(out);
1326 sent_to_at_least_one = true;
1332 * if the user was not in any channels, no users will receive the text. Make sure the user
1333 * receives their OWN message for WriteCommon
1335 if (!sent_to_at_least_one)
1337 this->Write(std::string(tb));
1342 /* write a formatted string to all users who share at least one common
1343 * channel, NOT including the source user e.g. for use in QUIT
1346 void User::WriteCommonExcept(const char* text, ...)
1348 char textbuffer[MAXBUF];
1351 va_start(argsPtr, text);
1352 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1355 this->WriteCommonExcept(std::string(textbuffer));
1358 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1363 if (this->registered != REG_ALL)
1367 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1368 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1369 std::string out1 = tb1;
1370 std::string out2 = tb2;
1372 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1374 CUList *ulist = v->first->GetUsers();
1375 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1377 if (this != i->first)
1379 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1381 already_sent[i->first->fd] = uniq_id;
1382 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1389 void User::WriteCommonExcept(const std::string &text)
1394 if (this->registered != REG_ALL)
1398 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1401 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1403 CUList *ulist = v->first->GetUsers();
1404 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1406 if (this != i->first)
1408 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1410 already_sent[i->first->fd] = uniq_id;
1411 i->first->Write(out1);
1419 void User::WriteWallOps(const std::string &text)
1421 if (!IS_OPER(this) && IS_LOCAL(this))
1424 std::string wallop("WALLOPS :");
1425 wallop.append(text);
1427 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1430 if (t->IsModeSet('w'))
1431 this->WriteTo(t,wallop);
1435 void User::WriteWallOps(const char* text, ...)
1437 char textbuffer[MAXBUF];
1440 va_start(argsPtr, text);
1441 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1444 this->WriteWallOps(std::string(textbuffer));
1447 /* return 0 or 1 depending if users u and u2 share one or more common channels
1448 * (used by QUIT, NICK etc which arent channel specific notices)
1450 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1451 * the first users channels then the second users channels within the outer loop,
1452 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1453 * all possible iterations). However this new function instead checks against the
1454 * channel's userlist in the inner loop which is a std::map<User*,User*>
1455 * and saves us time as we already know what pointer value we are after.
1456 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1457 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1459 bool User::SharesChannelWith(User *other)
1461 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1465 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1467 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1468 * by replacing it with a map::find which *should* be more efficient
1470 if (i->first->HasUser(other))
1476 bool User::ChangeName(const char* gecos)
1478 if (!strcmp(gecos, this->fullname))
1484 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1487 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1489 strlcpy(this->fullname,gecos,MAXGECOS+1);
1494 bool User::ChangeDisplayedHost(const char* shost)
1496 if (!strcmp(shost, this->dhost))
1502 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1505 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1508 if (this->ServerInstance->Config->CycleHosts)
1509 this->WriteCommonExcept("QUIT :Changing hosts");
1511 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1512 strlcpy(this->dhost,shost,64);
1514 this->InvalidateCache();
1516 if (this->ServerInstance->Config->CycleHosts)
1518 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1520 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1521 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1523 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1528 this->WriteNumeric(396, "%s %s :is now your displayed host",this->nick,this->dhost);
1533 bool User::ChangeIdent(const char* newident)
1535 if (!strcmp(newident, this->ident))
1538 if (this->ServerInstance->Config->CycleHosts)
1539 this->WriteCommonExcept("%s","QUIT :Changing ident");
1541 strlcpy(this->ident, newident, IDENTMAX+1);
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());
1559 void User::SendAll(const char* command, const char* text, ...)
1561 char textbuffer[MAXBUF];
1562 char formatbuffer[MAXBUF];
1565 va_start(argsPtr, text);
1566 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1569 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1570 std::string fmt = formatbuffer;
1572 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1579 std::string User::ChannelList(User* source)
1583 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1585 /* If the target is the same as the sender, let them see all their channels.
1586 * If the channel is NOT private/secret OR the user shares a common channel
1587 * If the user is an oper, and the <options:operspywhois> option is set.
1589 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1591 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1598 void User::SplitChanList(User* dest, const std::string &cl)
1601 std::ostringstream prefix;
1602 std::string::size_type start, pos, length;
1604 prefix << this->nick << " " << dest->nick << " :";
1605 line = prefix.str();
1606 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1608 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1610 length = (pos == std::string::npos) ? cl.length() : pos;
1612 if (line.length() + namelen + length - start > 510)
1614 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1615 line = prefix.str();
1618 if(pos == std::string::npos)
1620 line.append(cl.substr(start, length - start));
1625 line.append(cl.substr(start, length - start + 1));
1631 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1635 unsigned int User::GetMaxChans()
1637 return this->MaxChans;
1642 * Sets a user's connection class.
1643 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1644 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1645 * then their ip will be taken as 'priority' anyway, so for example,
1646 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1648 ConnectClass* User::SetClass(const std::string &explicit_name)
1650 ConnectClass *found = NULL;
1652 if (!IS_LOCAL(this))
1655 if (!explicit_name.empty())
1657 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1659 ConnectClass* c = *i;
1661 if (explicit_name == c->GetName() && !c->GetDisabled())
1669 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1671 ConnectClass* c = *i;
1673 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1677 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1686 if (!c->GetDisabled())
1693 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1696 /* deny change if change will take class over the limit */
1697 if (found->limit && (found->RefCount + 1 >= found->limit))
1699 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1700 return this->MyClass;
1703 /* should always be valid, but just in case .. */
1706 if (found == this->MyClass) // no point changing this shit :P
1707 return this->MyClass;
1708 this->MyClass->RefCount--;
1709 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1712 this->MyClass = found;
1713 this->MyClass->RefCount++;
1714 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1717 return this->MyClass;
1720 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1721 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1722 * then their ip will be taken as 'priority' anyway, so for example,
1723 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1725 ConnectClass* User::GetClass()
1727 return this->MyClass;
1730 void User::PurgeEmptyChannels()
1732 std::vector<Channel*> to_delete;
1734 // firstly decrement the count on each channel
1735 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1737 f->first->RemoveAllPrefixes(this);
1738 if (f->first->DelUser(this) == 0)
1740 /* No users left in here, mark it for deletion */
1743 to_delete.push_back(f->first);
1747 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1752 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1754 Channel* thischan = *n;
1755 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1756 if (i2 != ServerInstance->chanlist->end())
1758 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1760 ServerInstance->chanlist->erase(i2);
1761 this->chans.erase(*n);
1768 void User::ShowMOTD()
1770 if (!ServerInstance->Config->MOTD.size())
1772 this->WriteNumeric(422, "%s :Message of the day file is missing.",this->nick);
1775 this->WriteNumeric(375, "%s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1777 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1778 this->WriteNumeric(372, "%s :- %s",this->nick,i->c_str());
1780 this->WriteNumeric(376, "%s :End of message of the day.", this->nick);
1783 void User::ShowRULES()
1785 if (!ServerInstance->Config->RULES.size())
1787 this->WriteNumeric(434, "%s :RULES File is missing",this->nick);
1791 this->WriteNumeric(308, "%s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1793 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1794 this->WriteNumeric(232, "%s :- %s",this->nick,i->c_str());
1796 this->WriteNumeric(309, "%s :End of RULES command.",this->nick);
1799 void User::HandleEvent(EventType et, int errornum)
1801 if (this->quitting) // drop everything, user is due to be quit
1804 /* WARNING: May delete this user! */
1805 int thisfd = this->GetFd();
1812 ServerInstance->ProcessUser(this);
1815 this->FlushWriteBuf();
1818 /** This should be safe, but dont DARE do anything after it -- Brain */
1819 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1825 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1828 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1829 if ((ServerInstance->SE->GetRef(thisfd) == this))
1831 if (!WriteError.empty())
1833 User::QuitUser(ServerInstance, this, GetWriteError());
1838 void User::SetOperQuit(const std::string &oquit)
1840 operquitmsg = oquit;
1843 const char* User::GetOperQuit()
1845 return operquitmsg.c_str();
1848 void User::IncreasePenalty(int increase)
1850 this->Penalty += increase;
1853 void User::DecreasePenalty(int decrease)
1855 this->Penalty -= decrease;
1866 bool VisData::VisibleTo(User* user)