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 AllowedOperCommands = NULL;
197 memset(AllowedUserModes, 0, sizeof(AllowedUserModes));
198 memset(AllowedChanModes, 0, sizeof(AllowedChanModes));
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 this->InvalidateCache();
235 this->DecrementModes();
239 ServerInstance->Users->RemoveCloneCounts(this);
241 if (this->GetProtocolFamily() == AF_INET)
243 delete (sockaddr_in*)ip;
245 #ifdef SUPPORT_IP6LINKS
248 delete (sockaddr_in6*)ip;
253 ServerInstance->Users->uuidlist->erase(uuid);
256 char* User::MakeHost()
258 if (this->cached_makehost)
259 return this->cached_makehost;
262 /* This is much faster than snprintf */
264 for(char* n = ident; *n; n++)
267 for(char* n = host; *n; n++)
271 this->cached_makehost = strdup(nhost);
273 return this->cached_makehost;
276 char* User::MakeHostIP()
278 if (this->cached_hostip)
279 return this->cached_hostip;
282 /* This is much faster than snprintf */
284 for(char* n = ident; *n; n++)
287 for(const char* n = this->GetIPString(); *n; n++)
291 this->cached_hostip = strdup(ihost);
293 return this->cached_hostip;
296 void User::CloseSocket()
298 ServerInstance->SE->Shutdown(this, 2);
299 ServerInstance->SE->Close(this);
302 char* User::GetFullHost()
304 if (this->cached_fullhost)
305 return this->cached_fullhost;
309 for(char* n = nick; *n; n++)
312 for(char* n = ident; *n; n++)
315 for(char* n = dhost; *n; n++)
319 this->cached_fullhost = strdup(result);
321 return this->cached_fullhost;
324 char* User::MakeWildHost()
326 static char nresult[MAXBUF];
328 *t++ = '*'; *t++ = '!';
329 *t++ = '*'; *t++ = '@';
330 for(char* n = dhost; *n; n++)
336 int User::ReadData(void* buffer, size_t size)
341 return read(this->fd, buffer, size);
343 return recv(this->fd, (char*)buffer, size, 0);
351 char* User::GetFullRealHost()
353 if (this->cached_fullrealhost)
354 return this->cached_fullrealhost;
356 char fresult[MAXBUF];
358 for(char* n = nick; *n; n++)
361 for(char* n = ident; *n; n++)
364 for(char* n = host; *n; n++)
368 this->cached_fullrealhost = strdup(fresult);
370 return this->cached_fullrealhost;
373 bool User::IsInvited(const irc::string &channel)
375 time_t now = time(NULL);
376 InvitedList::iterator safei;
377 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
379 if (channel == i->first)
381 if (i->second != 0 && now > i->second)
383 /* Expired invite, remove it. */
386 invites.erase(safei);
395 InvitedList* User::GetInviteList()
397 time_t now = time(NULL);
398 /* Weed out expired invites here. */
399 InvitedList::iterator safei;
400 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
402 if (i->second != 0 && now > i->second)
404 /* Expired invite, remove it. */
407 invites.erase(safei);
413 void User::InviteTo(const irc::string &channel, time_t invtimeout)
415 time_t now = time(NULL);
416 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
417 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
419 if (channel == i->first)
421 if (i->second != 0 && invtimeout > i->second)
423 i->second = invtimeout;
427 invites.push_back(std::make_pair(channel, invtimeout));
430 void User::RemoveInvite(const irc::string &channel)
432 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
434 if (channel == i->first)
442 bool User::HasModePermission(unsigned char mode, ModeType type)
450 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
454 bool User::HasPermission(const std::string &command)
457 * users on remote servers can completely bypass all permissions based checks.
458 * This prevents desyncs when one server has different type/class tags to another.
459 * That having been said, this does open things up to the possibility of source changes
460 * allowing remote kills, etc - but if they have access to the src, they most likely have
461 * access to the conf - so it's an end to a means either way.
466 // are they even an oper at all?
472 if (!AllowedOperCommands)
475 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
477 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
483 /** NOTE: We cannot pass a const reference to this method.
484 * The string is changed by the workings of the method,
485 * so that if we pass const ref, we end up copying it to
486 * something we can change anyway. Makes sense to just let
487 * the compiler do that copy for us.
489 bool User::AddBuffer(std::string a)
493 std::string::size_type i = a.rfind('\r');
495 while (i != std::string::npos)
504 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
506 this->SetWriteError("RecvQ exceeded");
507 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
516 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
521 bool User::BufferIsReady()
523 return (recvq.find('\n') != std::string::npos);
526 void User::ClearBuffer()
531 std::string User::GetBuffer()
538 /* Strip any leading \r or \n off the string.
539 * Usually there are only one or two of these,
540 * so its is computationally cheap to do.
542 std::string::iterator t = recvq.begin();
543 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
549 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
551 /* Find the first complete line, return it as the
552 * result, and leave the recvq as whats left
556 std::string ret = std::string(recvq.begin(), x);
557 recvq.erase(recvq.begin(), x + 1);
566 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
571 void User::AddWriteBuf(const std::string &data)
573 if (*this->GetWriteError())
576 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
579 * Fix by brain - Set the error text BEFORE calling, because
580 * if we dont it'll recursively call here over and over again trying
581 * to repeatedly add the text to the sendq!
583 this->SetWriteError("SendQ exceeded");
584 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
588 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
589 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
594 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
595 void User::FlushWriteBuf()
599 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
603 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
605 int old_sendq_length = sendq.length();
606 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
612 /* The socket buffer is full. This isnt fatal,
615 this->ServerInstance->SE->WantWrite(this);
619 /* Fatal error, set write error and bail
621 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
627 /* advance the queue */
629 this->sendq = this->sendq.substr(n_sent);
630 /* update the user's stats counters */
631 this->bytes_out += n_sent;
633 if (n_sent != old_sendq_length)
634 this->ServerInstance->SE->WantWrite(this);
641 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
644 if (this->sendq.empty())
646 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
650 void User::SetWriteError(const std::string &error)
652 // don't try to set the error twice, its already set take the first string.
653 if (this->WriteError.empty())
654 this->WriteError = error;
657 const char* User::GetWriteError()
659 return this->WriteError.c_str();
662 void User::Oper(const std::string &opertype, const std::string &opername)
670 this->modes[UM_OPERATOR] = 1;
671 this->WriteServ("MODE %s :+o", this->nick);
672 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
673 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
674 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
675 ServerInstance->Users->all_opers.push_back(this);
677 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
678 if (iter_opertype != ServerInstance->Config->opertypes.end())
681 if (AllowedOperCommands)
682 AllowedOperCommands->clear();
684 AllowedOperCommands = new std::map<std::string, bool>;
686 char* Classes = strdup(iter_opertype->second);
687 char* myclass = strtok_r(Classes," ",&savept);
690 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
691 if (iter_operclass != ServerInstance->Config->operclass.end())
693 char* CommandList = strdup(iter_operclass->second.commandlist);
694 mycmd = strtok_r(CommandList," ",&savept2);
697 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
698 mycmd = strtok_r(NULL," ",&savept2);
701 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
702 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
706 memset(this->AllowedUserModes, (int)(true), sizeof(this->AllowedUserModes));
710 this->AllowedUserModes[*c - 'A'] = true;
713 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
717 memset(this->AllowedChanModes, (int)(true), sizeof(this->AllowedChanModes));
721 this->AllowedChanModes[*c - 'A'] = true;
725 myclass = strtok_r(NULL," ",&savept);
730 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
735 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
743 /* Remove all oper only modes from the user when the deoper - Bug #466*/
744 std::string moderemove("-");
746 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
750 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
751 if (mh && mh->NeedsOper())
752 moderemove += letter;
756 const char* parameters[] = { this->nick, moderemove.c_str() };
757 ServerInstance->Parser->CallHandler("MODE", parameters, 2, this);
759 /* unset their oper type (what IS_OPER checks), and remove +o */
761 this->modes[UM_OPERATOR] = 0;
763 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
764 ServerInstance->Users->all_opers.remove(this);
766 if (AllowedOperCommands)
768 delete AllowedOperCommands;
769 AllowedOperCommands = NULL;
774 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
776 Instance->Logs->Log("USERS", DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
777 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
778 user->quietquit = false;
779 user->quitmsg = quitreason;
782 user->operquitmsg = quitreason;
784 user->operquitmsg = operreason;
786 Instance->GlobalCulls.AddItem(user);
789 /* adds or updates an entry in the whowas list */
790 void User::AddToWhoWas()
792 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
795 std::deque<classbase*> params;
796 params.push_back(this);
797 whowas_command->HandleInternal(WHOWAS_ADD, params);
802 * Check class restrictions
804 void User::CheckClass()
806 ConnectClass* a = this->MyClass;
808 if ((!a) || (a->GetType() == CC_DENY))
810 User::QuitUser(ServerInstance, this, "Unauthorised connection");
813 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
815 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
816 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
819 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
821 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
822 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
826 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
827 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
828 this->MaxChans = a->GetMaxChans();
831 void User::FullConnect()
833 ServerInstance->stats->statsConnects++;
834 this->idle_lastmsg = ServerInstance->Time();
837 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
838 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
839 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
840 * Don't remove this! -- w00t
844 /* Check the password, if one is required by the user's connect class.
845 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
847 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
849 User::QuitUser(ServerInstance, this, "Invalid password");
855 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
863 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
872 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
873 this->WriteNumeric(001, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
874 this->WriteNumeric(002, "%s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
875 this->WriteNumeric(003, "%s :This server was created %s %s", this->nick, __TIME__, __DATE__);
876 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());
878 ServerInstance->Config->Send005(this);
880 this->WriteNumeric(42, "%s %s :your unique ID", this->nick, this->uuid);
886 if (ServerInstance->Users->unregistered_count)
887 ServerInstance->Users->unregistered_count--;
889 /* Trigger LUSERS output, give modules a chance too */
891 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
893 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
896 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
897 * for a user that doesn't exist yet.
899 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
901 this->registered = REG_ALL;
903 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
905 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);
906 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
907 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
910 /** User::UpdateNick()
911 * re-allocates a nick in the user_hash after they change nicknames,
912 * returns a pointer to the new user as it may have moved
914 User* User::UpdateNickHash(const char* New)
916 //user_hash::iterator newnick;
917 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
919 if (!strcasecmp(this->nick,New))
920 return oldnick->second;
922 if (oldnick == ServerInstance->Users->clientlist->end())
923 return NULL; /* doesnt exist */
925 User* olduser = oldnick->second;
926 (*(ServerInstance->Users->clientlist))[New] = olduser;
927 ServerInstance->Users->clientlist->erase(oldnick);
931 void User::InvalidateCache()
933 /* Invalidate cache */
935 free(cached_fullhost);
939 free(cached_makehost);
940 if (cached_fullrealhost)
941 free(cached_fullrealhost);
942 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
945 bool User::ForceNickChange(const char* newnick)
948 * XXX this makes no sense..
949 * why do we do nothing for change on users not REG_ALL?
950 * why do we trigger events twice for everyone previously (and just them now)
951 * i think the first if () needs removing totally, or? -- w00t
953 if (this->registered != REG_ALL)
957 this->InvalidateCache();
959 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
963 ServerInstance->stats->statsCollisions++;
967 if (ServerInstance->XLines->MatchesLine("Q",newnick))
969 ServerInstance->stats->statsCollisions++;
975 std::deque<classbase*> dummy;
976 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
977 if (nickhandler) // wtfbbq, when would this not be here
979 nickhandler->HandleInternal(1, dummy);
980 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
981 nickhandler->HandleInternal(0, dummy);
990 void User::SetSockAddr(int protocol_family, const char* sip, int port)
994 switch (protocol_family)
996 #ifdef SUPPORT_IP6LINKS
999 sockaddr_in6* sin = new sockaddr_in6;
1000 sin->sin6_family = AF_INET6;
1001 sin->sin6_port = port;
1002 inet_pton(AF_INET6, sip, &sin->sin6_addr);
1003 this->ip = (sockaddr*)sin;
1009 sockaddr_in* sin = new sockaddr_in;
1010 sin->sin_family = AF_INET;
1011 sin->sin_port = port;
1012 inet_pton(AF_INET, sip, &sin->sin_addr);
1013 this->ip = (sockaddr*)sin;
1017 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1024 if (this->ip == NULL)
1027 switch (this->GetProtocolFamily())
1029 #ifdef SUPPORT_IP6LINKS
1032 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1033 return sin->sin6_port;
1039 sockaddr_in* sin = (sockaddr_in*)this->ip;
1040 return sin->sin_port;
1049 int User::GetProtocolFamily()
1051 if (this->ip == NULL)
1054 sockaddr_in* sin = (sockaddr_in*)this->ip;
1055 return sin->sin_family;
1059 * XXX the duplication here is horrid..
1060 * do we really need two methods doing essentially the same thing?
1062 const char* User::GetIPString()
1064 static char buf[1024];
1066 if (this->ip == NULL)
1069 if (!this->cachedip.empty())
1070 return this->cachedip.c_str();
1072 switch (this->GetProtocolFamily())
1074 #ifdef SUPPORT_IP6LINKS
1077 static char temp[1024];
1079 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1080 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1081 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1084 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1086 this->cachedip = temp;
1090 this->cachedip = buf;
1097 sockaddr_in* sin = (sockaddr_in*)this->ip;
1098 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1099 this->cachedip = buf;
1107 // Unreachable, probably
1111 /** NOTE: We cannot pass a const reference to this method.
1112 * The string is changed by the workings of the method,
1113 * so that if we pass const ref, we end up copying it to
1114 * something we can change anyway. Makes sense to just let
1115 * the compiler do that copy for us.
1117 void User::Write(std::string text)
1119 if (!ServerInstance->SE->BoundsCheckFd(this))
1124 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1125 text.append("\r\n");
1129 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1133 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1135 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1136 * implement their own buffering mechanisms
1140 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1142 catch (CoreException& modexcept)
1144 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1149 this->AddWriteBuf(text);
1151 ServerInstance->stats->statsSent += text.length();
1152 this->ServerInstance->SE->WantWrite(this);
1157 void User::Write(const char *text, ...)
1160 char textbuffer[MAXBUF];
1162 va_start(argsPtr, text);
1163 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1166 this->Write(std::string(textbuffer));
1169 void User::WriteServ(const std::string& text)
1171 char textbuffer[MAXBUF];
1173 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1174 this->Write(std::string(textbuffer));
1178 * Same as Write(), except `text' is prefixed with `:server.name '.
1180 void User::WriteServ(const char* text, ...)
1183 char textbuffer[MAXBUF];
1185 va_start(argsPtr, text);
1186 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1189 this->WriteServ(std::string(textbuffer));
1193 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1196 char textbuffer[MAXBUF];
1198 va_start(argsPtr, text);
1199 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1202 this->WriteNumeric(numeric, std::string(textbuffer));
1205 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1207 char textbuffer[MAXBUF];
1210 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1215 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1216 this->Write(std::string(textbuffer));
1219 void User::WriteFrom(User *user, const std::string &text)
1223 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1225 this->Write(std::string(tb));
1229 /* write text from an originating user to originating user */
1231 void User::WriteFrom(User *user, const char* text, ...)
1234 char textbuffer[MAXBUF];
1236 va_start(argsPtr, text);
1237 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1240 this->WriteFrom(user, std::string(textbuffer));
1244 /* write text to an destination user from a source user (e.g. user privmsg) */
1246 void User::WriteTo(User *dest, const char *data, ...)
1248 char textbuffer[MAXBUF];
1251 va_start(argsPtr, data);
1252 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1255 this->WriteTo(dest, std::string(textbuffer));
1258 void User::WriteTo(User *dest, const std::string &data)
1260 dest->WriteFrom(this, data);
1264 void User::WriteCommon(const char* text, ...)
1266 char textbuffer[MAXBUF];
1269 if (this->registered != REG_ALL)
1272 va_start(argsPtr, text);
1273 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1276 this->WriteCommon(std::string(textbuffer));
1279 void User::WriteCommon(const std::string &text)
1281 bool sent_to_at_least_one = false;
1284 if (this->registered != REG_ALL)
1289 /* We dont want to be doing this n times, just once */
1290 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1291 std::string out = tb;
1293 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1295 CUList* ulist = v->first->GetUsers();
1296 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1298 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1300 already_sent[i->first->fd] = uniq_id;
1301 i->first->Write(out);
1302 sent_to_at_least_one = true;
1308 * if the user was not in any channels, no users will receive the text. Make sure the user
1309 * receives their OWN message for WriteCommon
1311 if (!sent_to_at_least_one)
1313 this->Write(std::string(tb));
1318 /* write a formatted string to all users who share at least one common
1319 * channel, NOT including the source user e.g. for use in QUIT
1322 void User::WriteCommonExcept(const char* text, ...)
1324 char textbuffer[MAXBUF];
1327 va_start(argsPtr, text);
1328 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1331 this->WriteCommonExcept(std::string(textbuffer));
1334 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1339 if (this->registered != REG_ALL)
1343 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1344 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1345 std::string out1 = tb1;
1346 std::string out2 = tb2;
1348 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1350 CUList *ulist = v->first->GetUsers();
1351 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1353 if (this != i->first)
1355 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1357 already_sent[i->first->fd] = uniq_id;
1358 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1365 void User::WriteCommonExcept(const std::string &text)
1370 if (this->registered != REG_ALL)
1374 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1377 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1379 CUList *ulist = v->first->GetUsers();
1380 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1382 if (this != i->first)
1384 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1386 already_sent[i->first->fd] = uniq_id;
1387 i->first->Write(out1);
1395 void User::WriteWallOps(const std::string &text)
1397 if (!IS_OPER(this) && IS_LOCAL(this))
1400 std::string wallop("WALLOPS :");
1401 wallop.append(text);
1403 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1406 if (t->IsModeSet('w'))
1407 this->WriteTo(t,wallop);
1411 void User::WriteWallOps(const char* text, ...)
1413 char textbuffer[MAXBUF];
1416 va_start(argsPtr, text);
1417 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1420 this->WriteWallOps(std::string(textbuffer));
1423 /* return 0 or 1 depending if users u and u2 share one or more common channels
1424 * (used by QUIT, NICK etc which arent channel specific notices)
1426 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1427 * the first users channels then the second users channels within the outer loop,
1428 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1429 * all possible iterations). However this new function instead checks against the
1430 * channel's userlist in the inner loop which is a std::map<User*,User*>
1431 * and saves us time as we already know what pointer value we are after.
1432 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1433 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1435 bool User::SharesChannelWith(User *other)
1437 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1441 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1443 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1444 * by replacing it with a map::find which *should* be more efficient
1446 if (i->first->HasUser(other))
1452 bool User::ChangeName(const char* gecos)
1454 if (!strcmp(gecos, this->fullname))
1460 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1463 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1465 strlcpy(this->fullname,gecos,MAXGECOS+1);
1470 bool User::ChangeDisplayedHost(const char* shost)
1472 if (!strcmp(shost, this->dhost))
1478 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1481 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1484 if (this->ServerInstance->Config->CycleHosts)
1485 this->WriteCommonExcept("QUIT :Changing hosts");
1487 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1488 strlcpy(this->dhost,shost,64);
1490 this->InvalidateCache();
1492 if (this->ServerInstance->Config->CycleHosts)
1494 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1496 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1497 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1499 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1504 this->WriteNumeric(396, "%s %s :is now your displayed host",this->nick,this->dhost);
1509 bool User::ChangeIdent(const char* newident)
1511 if (!strcmp(newident, this->ident))
1514 if (this->ServerInstance->Config->CycleHosts)
1515 this->WriteCommonExcept("%s","QUIT :Changing ident");
1517 strlcpy(this->ident, newident, IDENTMAX+1);
1519 this->InvalidateCache();
1521 if (this->ServerInstance->Config->CycleHosts)
1523 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1525 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1526 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1528 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1535 void User::SendAll(const char* command, const char* text, ...)
1537 char textbuffer[MAXBUF];
1538 char formatbuffer[MAXBUF];
1541 va_start(argsPtr, text);
1542 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1545 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1546 std::string fmt = formatbuffer;
1548 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1555 std::string User::ChannelList(User* source)
1559 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1561 /* If the target is the same as the sender, let them see all their channels.
1562 * If the channel is NOT private/secret OR the user shares a common channel
1563 * If the user is an oper, and the <options:operspywhois> option is set.
1565 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1567 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1574 void User::SplitChanList(User* dest, const std::string &cl)
1577 std::ostringstream prefix;
1578 std::string::size_type start, pos, length;
1580 prefix << this->nick << " " << dest->nick << " :";
1581 line = prefix.str();
1582 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1584 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1586 length = (pos == std::string::npos) ? cl.length() : pos;
1588 if (line.length() + namelen + length - start > 510)
1590 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1591 line = prefix.str();
1594 if(pos == std::string::npos)
1596 line.append(cl.substr(start, length - start));
1601 line.append(cl.substr(start, length - start + 1));
1607 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1611 unsigned int User::GetMaxChans()
1613 return this->MaxChans;
1618 * Sets a user's connection class.
1619 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1620 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1621 * then their ip will be taken as 'priority' anyway, so for example,
1622 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1624 ConnectClass* User::SetClass(const std::string &explicit_name)
1626 ConnectClass *found = NULL;
1628 if (!IS_LOCAL(this))
1631 if (!explicit_name.empty())
1633 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1635 ConnectClass* c = *i;
1637 if (explicit_name == c->GetName() && !c->GetDisabled())
1645 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1647 ConnectClass* c = *i;
1649 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1653 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1662 if (!c->GetDisabled())
1669 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1672 /* deny change if change will take class over the limit */
1673 if (found->limit && (found->RefCount + 1 >= found->limit))
1675 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1676 return this->MyClass;
1679 /* should always be valid, but just in case .. */
1682 if (found == this->MyClass) // no point changing this shit :P
1683 return this->MyClass;
1684 this->MyClass->RefCount--;
1685 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1688 this->MyClass = found;
1689 this->MyClass->RefCount++;
1690 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1693 return this->MyClass;
1696 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1697 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1698 * then their ip will be taken as 'priority' anyway, so for example,
1699 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1701 ConnectClass* User::GetClass()
1703 return this->MyClass;
1706 void User::PurgeEmptyChannels()
1708 std::vector<Channel*> to_delete;
1710 // firstly decrement the count on each channel
1711 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1713 f->first->RemoveAllPrefixes(this);
1714 if (f->first->DelUser(this) == 0)
1716 /* No users left in here, mark it for deletion */
1719 to_delete.push_back(f->first);
1723 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1728 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1730 Channel* thischan = *n;
1731 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1732 if (i2 != ServerInstance->chanlist->end())
1734 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1736 ServerInstance->chanlist->erase(i2);
1737 this->chans.erase(*n);
1744 void User::ShowMOTD()
1746 if (!ServerInstance->Config->MOTD.size())
1748 this->WriteNumeric(422, "%s :Message of the day file is missing.",this->nick);
1751 this->WriteNumeric(375, "%s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1753 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1754 this->WriteNumeric(372, "%s :- %s",this->nick,i->c_str());
1756 this->WriteNumeric(376, "%s :End of message of the day.", this->nick);
1759 void User::ShowRULES()
1761 if (!ServerInstance->Config->RULES.size())
1763 this->WriteNumeric(434, "%s :RULES File is missing",this->nick);
1767 this->WriteNumeric(308, "%s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1769 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1770 this->WriteNumeric(232, "%s :- %s",this->nick,i->c_str());
1772 this->WriteNumeric(309, "%s :End of RULES command.",this->nick);
1775 void User::HandleEvent(EventType et, int errornum)
1777 if (this->quitting) // drop everything, user is due to be quit
1780 /* WARNING: May delete this user! */
1781 int thisfd = this->GetFd();
1788 ServerInstance->ProcessUser(this);
1791 this->FlushWriteBuf();
1794 /** This should be safe, but dont DARE do anything after it -- Brain */
1795 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1801 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1804 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1805 if ((ServerInstance->SE->GetRef(thisfd) == this))
1807 if (!WriteError.empty())
1809 User::QuitUser(ServerInstance, this, GetWriteError());
1814 void User::SetOperQuit(const std::string &oquit)
1816 operquitmsg = oquit;
1819 const char* User::GetOperQuit()
1821 return operquitmsg.c_str();
1824 void User::IncreasePenalty(int increase)
1826 this->Penalty += increase;
1829 void User::DecreasePenalty(int decrease)
1831 this->Penalty -= decrease;
1842 bool VisData::VisibleTo(User* user)