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->WriteServ("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 AllowedOperCommands = NULL;
199 memset(modes,0,sizeof(modes));
200 memset(snomasks,0,sizeof(snomasks));
201 /* Invalidate cache */
202 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
205 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
207 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
209 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
211 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
212 if (finduuid == Instance->Users->uuidlist->end())
213 (*Instance->Users->uuidlist)[uuid] = this;
215 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
220 /* NULL for remote users :) */
223 this->MyClass->RefCount--;
224 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %u", this->MyClass->RefCount);
226 if (this->AllowedOperCommands)
228 delete AllowedOperCommands;
229 AllowedOperCommands = NULL;
232 this->InvalidateCache();
233 this->DecrementModes();
237 ServerInstance->Users->RemoveCloneCounts(this);
239 if (this->GetProtocolFamily() == AF_INET)
241 delete (sockaddr_in*)ip;
243 #ifdef SUPPORT_IP6LINKS
246 delete (sockaddr_in6*)ip;
251 ServerInstance->Users->uuidlist->erase(uuid);
254 char* User::MakeHost()
256 if (this->cached_makehost)
257 return this->cached_makehost;
260 /* This is much faster than snprintf */
262 for(char* n = ident; *n; n++)
265 for(char* n = host; *n; n++)
269 this->cached_makehost = strdup(nhost);
271 return this->cached_makehost;
274 char* User::MakeHostIP()
276 if (this->cached_hostip)
277 return this->cached_hostip;
280 /* This is much faster than snprintf */
282 for(char* n = ident; *n; n++)
285 for(const char* n = this->GetIPString(); *n; n++)
289 this->cached_hostip = strdup(ihost);
291 return this->cached_hostip;
294 void User::CloseSocket()
296 ServerInstance->SE->Shutdown(this, 2);
297 ServerInstance->SE->Close(this);
300 char* User::GetFullHost()
302 if (this->cached_fullhost)
303 return this->cached_fullhost;
307 for(char* n = nick; *n; n++)
310 for(char* n = ident; *n; n++)
313 for(char* n = dhost; *n; n++)
317 this->cached_fullhost = strdup(result);
319 return this->cached_fullhost;
322 char* User::MakeWildHost()
324 static char nresult[MAXBUF];
326 *t++ = '*'; *t++ = '!';
327 *t++ = '*'; *t++ = '@';
328 for(char* n = dhost; *n; n++)
334 int User::ReadData(void* buffer, size_t size)
339 return read(this->fd, buffer, size);
341 return recv(this->fd, (char*)buffer, size, 0);
349 char* User::GetFullRealHost()
351 if (this->cached_fullrealhost)
352 return this->cached_fullrealhost;
354 char fresult[MAXBUF];
356 for(char* n = nick; *n; n++)
359 for(char* n = ident; *n; n++)
362 for(char* n = host; *n; n++)
366 this->cached_fullrealhost = strdup(fresult);
368 return this->cached_fullrealhost;
371 bool User::IsInvited(const irc::string &channel)
373 time_t now = time(NULL);
374 InvitedList::iterator safei;
375 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
377 if (channel == i->first)
379 if (i->second != 0 && now > i->second)
381 /* Expired invite, remove it. */
384 invites.erase(safei);
393 InvitedList* User::GetInviteList()
395 time_t now = time(NULL);
396 /* Weed out expired invites here. */
397 InvitedList::iterator safei;
398 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
400 if (i->second != 0 && now > i->second)
402 /* Expired invite, remove it. */
405 invites.erase(safei);
411 void User::InviteTo(const irc::string &channel, time_t invtimeout)
413 time_t now = time(NULL);
414 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
415 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
417 if (channel == i->first)
419 if (i->second != 0 && invtimeout > i->second)
421 i->second = invtimeout;
425 invites.push_back(std::make_pair(channel, invtimeout));
428 void User::RemoveInvite(const irc::string &channel)
430 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
432 if (channel == i->first)
440 bool User::HasPermission(const std::string &command)
443 * users on remote servers can completely bypass all permissions based checks.
444 * This prevents desyncs when one server has different type/class tags to another.
445 * That having been said, this does open things up to the possibility of source changes
446 * allowing remote kills, etc - but if they have access to the src, they most likely have
447 * access to the conf - so it's an end to a means either way.
452 // are they even an oper at all?
458 if (!AllowedOperCommands)
461 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
463 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
469 /** NOTE: We cannot pass a const reference to this method.
470 * The string is changed by the workings of the method,
471 * so that if we pass const ref, we end up copying it to
472 * something we can change anyway. Makes sense to just let
473 * the compiler do that copy for us.
475 bool User::AddBuffer(std::string a)
479 std::string::size_type i = a.rfind('\r');
481 while (i != std::string::npos)
490 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
492 this->SetWriteError("RecvQ exceeded");
493 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
502 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
507 bool User::BufferIsReady()
509 return (recvq.find('\n') != std::string::npos);
512 void User::ClearBuffer()
517 std::string User::GetBuffer()
524 /* Strip any leading \r or \n off the string.
525 * Usually there are only one or two of these,
526 * so its is computationally cheap to do.
528 std::string::iterator t = recvq.begin();
529 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
535 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
537 /* Find the first complete line, return it as the
538 * result, and leave the recvq as whats left
542 std::string ret = std::string(recvq.begin(), x);
543 recvq.erase(recvq.begin(), x + 1);
552 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
557 void User::AddWriteBuf(const std::string &data)
559 if (*this->GetWriteError())
562 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
565 * Fix by brain - Set the error text BEFORE calling, because
566 * if we dont it'll recursively call here over and over again trying
567 * to repeatedly add the text to the sendq!
569 this->SetWriteError("SendQ exceeded");
570 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
574 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
575 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
580 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
581 void User::FlushWriteBuf()
585 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
589 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
591 int old_sendq_length = sendq.length();
592 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
598 /* The socket buffer is full. This isnt fatal,
601 this->ServerInstance->SE->WantWrite(this);
605 /* Fatal error, set write error and bail
607 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
613 /* advance the queue */
615 this->sendq = this->sendq.substr(n_sent);
616 /* update the user's stats counters */
617 this->bytes_out += n_sent;
619 if (n_sent != old_sendq_length)
620 this->ServerInstance->SE->WantWrite(this);
627 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
630 if (this->sendq.empty())
632 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
636 void User::SetWriteError(const std::string &error)
638 // don't try to set the error twice, its already set take the first string.
639 if (this->WriteError.empty())
640 this->WriteError = error;
643 const char* User::GetWriteError()
645 return this->WriteError.c_str();
648 void User::Oper(const std::string &opertype, const std::string &opername)
656 this->modes[UM_OPERATOR] = 1;
657 this->WriteServ("MODE %s :+o", this->nick);
658 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
659 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
660 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
661 ServerInstance->Users->all_opers.push_back(this);
663 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
664 if (iter_opertype != ServerInstance->Config->opertypes.end())
667 if (AllowedOperCommands)
668 AllowedOperCommands->clear();
670 AllowedOperCommands = new std::map<std::string, bool>;
672 char* Classes = strdup(iter_opertype->second);
673 char* myclass = strtok_r(Classes," ",&savept);
676 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
677 if (iter_operclass != ServerInstance->Config->operclass.end())
679 char* CommandList = strdup(iter_operclass->second);
680 mycmd = strtok_r(CommandList," ",&savept2);
683 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
684 mycmd = strtok_r(NULL," ",&savept2);
688 myclass = strtok_r(NULL," ",&savept);
693 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
698 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
706 /* Remove all oper only modes from the user when the deoper - Bug #466*/
707 std::string moderemove("-");
709 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
713 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
714 if (mh && mh->NeedsOper())
715 moderemove += letter;
719 const char* parameters[] = { this->nick, moderemove.c_str() };
720 ServerInstance->Parser->CallHandler("MODE", parameters, 2, this);
722 /* unset their oper type (what IS_OPER checks), and remove +o */
724 this->modes[UM_OPERATOR] = 0;
726 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
727 ServerInstance->Users->all_opers.remove(this);
729 if (AllowedOperCommands)
731 delete AllowedOperCommands;
732 AllowedOperCommands = NULL;
737 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
739 Instance->Logs->Log("USERS", DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
740 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
741 user->quietquit = false;
742 user->quitmsg = quitreason;
745 user->operquitmsg = quitreason;
747 user->operquitmsg = operreason;
749 Instance->GlobalCulls.AddItem(user);
752 /* adds or updates an entry in the whowas list */
753 void User::AddToWhoWas()
755 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
758 std::deque<classbase*> params;
759 params.push_back(this);
760 whowas_command->HandleInternal(WHOWAS_ADD, params);
765 * Check class restrictions
767 void User::CheckClass()
769 ConnectClass* a = this->MyClass;
771 if ((!a) || (a->GetType() == CC_DENY))
773 User::QuitUser(ServerInstance, this, "Unauthorised connection");
776 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
778 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
779 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
782 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
784 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
785 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
789 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
790 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
791 this->MaxChans = a->GetMaxChans();
794 void User::FullConnect()
796 ServerInstance->stats->statsConnects++;
797 this->idle_lastmsg = ServerInstance->Time();
800 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
801 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
802 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
803 * Don't remove this! -- w00t
807 /* Check the password, if one is required by the user's connect class.
808 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
810 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
812 User::QuitUser(ServerInstance, this, "Invalid password");
818 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
826 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
835 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
836 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
837 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
838 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
839 this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
841 ServerInstance->Config->Send005(this);
843 this->WriteServ("042 %s %s :your unique ID", this->nick, this->uuid);
849 if (ServerInstance->Users->unregistered_count)
850 ServerInstance->Users->unregistered_count--;
852 /* Trigger LUSERS output, give modules a chance too */
854 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
856 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
859 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
860 * for a user that doesn't exist yet.
862 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
864 this->registered = REG_ALL;
866 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
868 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);
869 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
870 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
873 /** User::UpdateNick()
874 * re-allocates a nick in the user_hash after they change nicknames,
875 * returns a pointer to the new user as it may have moved
877 User* User::UpdateNickHash(const char* New)
879 //user_hash::iterator newnick;
880 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
882 if (!strcasecmp(this->nick,New))
883 return oldnick->second;
885 if (oldnick == ServerInstance->Users->clientlist->end())
886 return NULL; /* doesnt exist */
888 User* olduser = oldnick->second;
889 (*(ServerInstance->Users->clientlist))[New] = olduser;
890 ServerInstance->Users->clientlist->erase(oldnick);
894 void User::InvalidateCache()
896 /* Invalidate cache */
898 free(cached_fullhost);
902 free(cached_makehost);
903 if (cached_fullrealhost)
904 free(cached_fullrealhost);
905 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
908 bool User::ForceNickChange(const char* newnick)
911 * XXX this makes no sense..
912 * why do we do nothing for change on users not REG_ALL?
913 * why do we trigger events twice for everyone previously (and just them now)
914 * i think the first if () needs removing totally, or? -- w00t
916 if (this->registered != REG_ALL)
920 this->InvalidateCache();
922 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
926 ServerInstance->stats->statsCollisions++;
930 if (ServerInstance->XLines->MatchesLine("Q",newnick))
932 ServerInstance->stats->statsCollisions++;
938 std::deque<classbase*> dummy;
939 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
940 if (nickhandler) // wtfbbq, when would this not be here
942 nickhandler->HandleInternal(1, dummy);
943 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
944 nickhandler->HandleInternal(0, dummy);
953 void User::SetSockAddr(int protocol_family, const char* sip, int port)
957 switch (protocol_family)
959 #ifdef SUPPORT_IP6LINKS
962 sockaddr_in6* sin = new sockaddr_in6;
963 sin->sin6_family = AF_INET6;
964 sin->sin6_port = port;
965 inet_pton(AF_INET6, sip, &sin->sin6_addr);
966 this->ip = (sockaddr*)sin;
972 sockaddr_in* sin = new sockaddr_in;
973 sin->sin_family = AF_INET;
974 sin->sin_port = port;
975 inet_pton(AF_INET, sip, &sin->sin_addr);
976 this->ip = (sockaddr*)sin;
980 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
987 if (this->ip == NULL)
990 switch (this->GetProtocolFamily())
992 #ifdef SUPPORT_IP6LINKS
995 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
996 return sin->sin6_port;
1002 sockaddr_in* sin = (sockaddr_in*)this->ip;
1003 return sin->sin_port;
1012 int User::GetProtocolFamily()
1014 if (this->ip == NULL)
1017 sockaddr_in* sin = (sockaddr_in*)this->ip;
1018 return sin->sin_family;
1022 * XXX the duplication here is horrid..
1023 * do we really need two methods doing essentially the same thing?
1025 const char* User::GetIPString()
1027 static char buf[1024];
1029 if (this->ip == NULL)
1032 if (!this->cachedip.empty())
1033 return this->cachedip.c_str();
1035 switch (this->GetProtocolFamily())
1037 #ifdef SUPPORT_IP6LINKS
1040 static char temp[1024];
1042 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1043 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1044 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1047 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1049 this->cachedip = temp;
1053 this->cachedip = buf;
1060 sockaddr_in* sin = (sockaddr_in*)this->ip;
1061 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1062 this->cachedip = buf;
1070 // Unreachable, probably
1074 /** NOTE: We cannot pass a const reference to this method.
1075 * The string is changed by the workings of the method,
1076 * so that if we pass const ref, we end up copying it to
1077 * something we can change anyway. Makes sense to just let
1078 * the compiler do that copy for us.
1080 void User::Write(std::string text)
1082 if (!ServerInstance->SE->BoundsCheckFd(this))
1087 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1088 text.append("\r\n");
1092 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1096 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1098 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1099 * implement their own buffering mechanisms
1103 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1105 catch (CoreException& modexcept)
1107 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1112 this->AddWriteBuf(text);
1114 ServerInstance->stats->statsSent += text.length();
1115 this->ServerInstance->SE->WantWrite(this);
1120 void User::Write(const char *text, ...)
1123 char textbuffer[MAXBUF];
1125 va_start(argsPtr, text);
1126 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1129 this->Write(std::string(textbuffer));
1132 void User::WriteServ(const std::string& text)
1134 char textbuffer[MAXBUF];
1136 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1137 this->Write(std::string(textbuffer));
1141 * Same as Write(), except `text' is prefixed with `:server.name '.
1143 void User::WriteServ(const char* text, ...)
1146 char textbuffer[MAXBUF];
1148 va_start(argsPtr, text);
1149 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1152 this->WriteServ(std::string(textbuffer));
1156 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1159 char textbuffer[MAXBUF];
1161 va_start(argsPtr, text);
1162 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1165 this->WriteNumeric(numeric, std::string(textbuffer));
1168 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1170 char textbuffer[MAXBUF];
1173 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1178 snprintf(textbuffer,MAXBUF,":%s %u %s %s",ServerInstance->Config->ServerName, numeric, this->nick, text.c_str());
1179 this->Write(std::string(textbuffer));
1182 void User::WriteFrom(User *user, const std::string &text)
1186 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1188 this->Write(std::string(tb));
1192 /* write text from an originating user to originating user */
1194 void User::WriteFrom(User *user, const char* text, ...)
1197 char textbuffer[MAXBUF];
1199 va_start(argsPtr, text);
1200 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1203 this->WriteFrom(user, std::string(textbuffer));
1207 /* write text to an destination user from a source user (e.g. user privmsg) */
1209 void User::WriteTo(User *dest, const char *data, ...)
1211 char textbuffer[MAXBUF];
1214 va_start(argsPtr, data);
1215 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1218 this->WriteTo(dest, std::string(textbuffer));
1221 void User::WriteTo(User *dest, const std::string &data)
1223 dest->WriteFrom(this, data);
1227 void User::WriteCommon(const char* text, ...)
1229 char textbuffer[MAXBUF];
1232 if (this->registered != REG_ALL)
1235 va_start(argsPtr, text);
1236 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1239 this->WriteCommon(std::string(textbuffer));
1242 void User::WriteCommon(const std::string &text)
1244 bool sent_to_at_least_one = false;
1247 if (this->registered != REG_ALL)
1252 /* We dont want to be doing this n times, just once */
1253 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1254 std::string out = tb;
1256 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1258 CUList* ulist = v->first->GetUsers();
1259 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1261 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1263 already_sent[i->first->fd] = uniq_id;
1264 i->first->Write(out);
1265 sent_to_at_least_one = true;
1271 * if the user was not in any channels, no users will receive the text. Make sure the user
1272 * receives their OWN message for WriteCommon
1274 if (!sent_to_at_least_one)
1276 this->Write(std::string(tb));
1281 /* write a formatted string to all users who share at least one common
1282 * channel, NOT including the source user e.g. for use in QUIT
1285 void User::WriteCommonExcept(const char* text, ...)
1287 char textbuffer[MAXBUF];
1290 va_start(argsPtr, text);
1291 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1294 this->WriteCommonExcept(std::string(textbuffer));
1297 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1302 if (this->registered != REG_ALL)
1306 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1307 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1308 std::string out1 = tb1;
1309 std::string out2 = tb2;
1311 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1313 CUList *ulist = v->first->GetUsers();
1314 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1316 if (this != i->first)
1318 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1320 already_sent[i->first->fd] = uniq_id;
1321 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1328 void User::WriteCommonExcept(const std::string &text)
1333 if (this->registered != REG_ALL)
1337 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1340 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1342 CUList *ulist = v->first->GetUsers();
1343 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1345 if (this != i->first)
1347 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1349 already_sent[i->first->fd] = uniq_id;
1350 i->first->Write(out1);
1358 void User::WriteWallOps(const std::string &text)
1360 if (!IS_OPER(this) && IS_LOCAL(this))
1363 std::string wallop("WALLOPS :");
1364 wallop.append(text);
1366 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1369 if (t->IsModeSet('w'))
1370 this->WriteTo(t,wallop);
1374 void User::WriteWallOps(const char* text, ...)
1376 char textbuffer[MAXBUF];
1379 va_start(argsPtr, text);
1380 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1383 this->WriteWallOps(std::string(textbuffer));
1386 /* return 0 or 1 depending if users u and u2 share one or more common channels
1387 * (used by QUIT, NICK etc which arent channel specific notices)
1389 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1390 * the first users channels then the second users channels within the outer loop,
1391 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1392 * all possible iterations). However this new function instead checks against the
1393 * channel's userlist in the inner loop which is a std::map<User*,User*>
1394 * and saves us time as we already know what pointer value we are after.
1395 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1396 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1398 bool User::SharesChannelWith(User *other)
1400 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1404 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1406 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1407 * by replacing it with a map::find which *should* be more efficient
1409 if (i->first->HasUser(other))
1415 bool User::ChangeName(const char* gecos)
1417 if (!strcmp(gecos, this->fullname))
1423 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1426 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1428 strlcpy(this->fullname,gecos,MAXGECOS+1);
1433 bool User::ChangeDisplayedHost(const char* shost)
1435 if (!strcmp(shost, this->dhost))
1441 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1444 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1447 if (this->ServerInstance->Config->CycleHosts)
1448 this->WriteCommonExcept("QUIT :Changing hosts");
1450 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1451 strlcpy(this->dhost,shost,64);
1453 this->InvalidateCache();
1455 if (this->ServerInstance->Config->CycleHosts)
1457 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1459 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1460 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1462 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1467 this->WriteServ("396 %s %s :is now your displayed host",this->nick,this->dhost);
1472 bool User::ChangeIdent(const char* newident)
1474 if (!strcmp(newident, this->ident))
1477 if (this->ServerInstance->Config->CycleHosts)
1478 this->WriteCommonExcept("%s","QUIT :Changing ident");
1480 strlcpy(this->ident, newident, IDENTMAX+1);
1482 this->InvalidateCache();
1484 if (this->ServerInstance->Config->CycleHosts)
1486 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1488 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1489 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1491 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1498 void User::SendAll(const char* command, const char* text, ...)
1500 char textbuffer[MAXBUF];
1501 char formatbuffer[MAXBUF];
1504 va_start(argsPtr, text);
1505 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1508 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1509 std::string fmt = formatbuffer;
1511 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1518 std::string User::ChannelList(User* source)
1522 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1524 /* If the target is the same as the sender, let them see all their channels.
1525 * If the channel is NOT private/secret OR the user shares a common channel
1526 * If the user is an oper, and the <options:operspywhois> option is set.
1528 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1530 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1537 void User::SplitChanList(User* dest, const std::string &cl)
1540 std::ostringstream prefix;
1541 std::string::size_type start, pos, length;
1543 prefix << this->nick << " " << dest->nick << " :";
1544 line = prefix.str();
1545 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1547 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1549 length = (pos == std::string::npos) ? cl.length() : pos;
1551 if (line.length() + namelen + length - start > 510)
1553 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1554 line = prefix.str();
1557 if(pos == std::string::npos)
1559 line.append(cl.substr(start, length - start));
1564 line.append(cl.substr(start, length - start + 1));
1570 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1574 unsigned int User::GetMaxChans()
1576 return this->MaxChans;
1581 * Sets a user's connection class.
1582 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1583 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1584 * then their ip will be taken as 'priority' anyway, so for example,
1585 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1587 ConnectClass* User::SetClass(const std::string &explicit_name)
1589 ConnectClass *found = NULL;
1591 if (!IS_LOCAL(this))
1594 if (!explicit_name.empty())
1596 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1598 ConnectClass* c = *i;
1600 if (explicit_name == c->GetName() && !c->GetDisabled())
1608 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1610 ConnectClass* c = *i;
1612 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1616 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1625 if (!c->GetDisabled())
1632 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1635 /* deny change if change will take class over the limit */
1636 if (found->limit && (found->RefCount + 1 >= found->limit))
1638 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1639 return this->MyClass;
1642 /* should always be valid, but just in case .. */
1645 if (found == this->MyClass) // no point changing this shit :P
1646 return this->MyClass;
1647 this->MyClass->RefCount--;
1648 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1651 this->MyClass = found;
1652 this->MyClass->RefCount++;
1653 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1656 return this->MyClass;
1659 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1660 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1661 * then their ip will be taken as 'priority' anyway, so for example,
1662 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1664 ConnectClass* User::GetClass()
1666 return this->MyClass;
1669 void User::PurgeEmptyChannels()
1671 std::vector<Channel*> to_delete;
1673 // firstly decrement the count on each channel
1674 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1676 f->first->RemoveAllPrefixes(this);
1677 if (f->first->DelUser(this) == 0)
1679 /* No users left in here, mark it for deletion */
1682 to_delete.push_back(f->first);
1686 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1691 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1693 Channel* thischan = *n;
1694 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1695 if (i2 != ServerInstance->chanlist->end())
1697 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1699 ServerInstance->chanlist->erase(i2);
1700 this->chans.erase(*n);
1707 void User::ShowMOTD()
1709 if (!ServerInstance->Config->MOTD.size())
1711 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1714 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1716 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1717 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1719 this->WriteServ("376 %s :End of message of the day.", this->nick);
1722 void User::ShowRULES()
1724 if (!ServerInstance->Config->RULES.size())
1726 this->WriteServ("434 %s :RULES File is missing",this->nick);
1730 this->WriteServ("308 %s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1732 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1733 this->WriteServ("232 %s :- %s",this->nick,i->c_str());
1735 this->WriteServ("309 %s :End of RULES command.",this->nick);
1738 void User::HandleEvent(EventType et, int errornum)
1740 if (this->quitting) // drop everything, user is due to be quit
1743 /* WARNING: May delete this user! */
1744 int thisfd = this->GetFd();
1751 ServerInstance->ProcessUser(this);
1754 this->FlushWriteBuf();
1757 /** This should be safe, but dont DARE do anything after it -- Brain */
1758 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1764 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1767 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1768 if ((ServerInstance->SE->GetRef(thisfd) == this))
1770 if (!WriteError.empty())
1772 User::QuitUser(ServerInstance, this, GetWriteError());
1777 void User::SetOperQuit(const std::string &oquit)
1779 operquitmsg = oquit;
1782 const char* User::GetOperQuit()
1784 return operquitmsg.c_str();
1787 void User::IncreasePenalty(int increase)
1789 this->Penalty += increase;
1792 void User::DecreasePenalty(int decrease)
1794 this->Penalty -= decrease;
1805 bool VisData::VisibleTo(User* user)