1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $Core: libIRCDusers */
18 #include "socketengine.h"
22 #include "commands/cmd_whowas.h"
24 static unsigned long* already_sent = NULL;
27 void InitializeAlreadySent(SocketEngine* SE)
29 already_sent = new unsigned long[SE->GetMaxFds()];
32 /* XXX: Used for speeding up WriteCommon operations */
33 unsigned long uniq_id = 0;
35 std::string User::ProcessNoticeMasks(const char *sm)
37 bool adding = true, oldadding = false;
52 for (unsigned char d = 'A'; d <= 'z'; d++)
54 if (ServerInstance->SNO->IsEnabled(d))
56 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
58 if ((oldadding != adding) || (!output.length()))
59 output += (adding ? '+' : '-');
61 this->SetNoticeMask(d, adding);
70 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
72 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
74 if ((oldadding != adding) || (!output.length()))
75 output += (adding ? '+' : '-');
77 this->SetNoticeMask(*c, adding);
83 this->WriteNumeric(501, "%s %c :is unknown snomask char to me", this->nick, *c);
95 void User::StartDNSLookup()
100 const char* sip = this->GetIPString();
102 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
103 if (!strncmp(sip, "0::ffff:", 8))
104 res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
106 res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
108 this->ServerInstance->AddResolver(res_reverse, cached);
110 catch (CoreException& e)
112 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
116 bool User::IsNoticeMaskSet(unsigned char sm)
118 return (snomasks[sm-65]);
121 void User::SetNoticeMask(unsigned char sm, bool value)
123 snomasks[sm-65] = value;
126 const char* User::FormatNoticeMasks()
128 static char data[MAXBUF];
131 for (int n = 0; n < 64; n++)
134 data[offset++] = n+65;
143 bool User::IsModeSet(unsigned char m)
145 return (modes[m-65]);
148 void User::SetMode(unsigned char m, bool value)
153 const char* User::FormatModes()
155 static char data[MAXBUF];
157 for (int n = 0; n < 64; n++)
160 data[offset++] = n+65;
166 void User::DecrementModes()
168 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
169 for (unsigned char n = 'A'; n <= 'z'; n++)
173 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
174 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
177 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
184 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
186 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
187 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
188 reset_due = ServerInstance->Time();
189 age = ServerInstance->Time();
191 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
192 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
193 quietquit = OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
198 res_forward = res_reverse = NULL;
203 AllowedUserModes = NULL;
204 AllowedChanModes = NULL;
205 AllowedOperCommands = NULL;
208 memset(modes,0,sizeof(modes));
209 memset(snomasks,0,sizeof(snomasks));
210 /* Invalidate cache */
211 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
214 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
216 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
218 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
220 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
221 if (finduuid == Instance->Users->uuidlist->end())
222 (*Instance->Users->uuidlist)[uuid] = this;
224 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
229 /* NULL for remote users :) */
232 this->MyClass->RefCount--;
233 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %lu", this->MyClass->RefCount);
235 if (this->AllowedOperCommands)
237 delete AllowedOperCommands;
238 AllowedOperCommands = NULL;
241 if (this->AllowedUserModes)
243 delete[] AllowedUserModes;
244 AllowedUserModes = NULL;
247 if (this->AllowedChanModes)
249 delete[] AllowedChanModes;
250 AllowedChanModes = NULL;
253 this->InvalidateCache();
254 this->DecrementModes();
258 ServerInstance->Users->RemoveCloneCounts(this);
260 if (this->GetProtocolFamily() == AF_INET)
262 delete (sockaddr_in*)ip;
264 #ifdef SUPPORT_IP6LINKS
267 delete (sockaddr_in6*)ip;
272 ServerInstance->Users->uuidlist->erase(uuid);
275 char* User::MakeHost()
277 if (this->cached_makehost)
278 return this->cached_makehost;
281 /* This is much faster than snprintf */
283 for(char* n = ident; *n; n++)
286 for(char* n = host; *n; n++)
290 this->cached_makehost = strdup(nhost);
292 return this->cached_makehost;
295 char* User::MakeHostIP()
297 if (this->cached_hostip)
298 return this->cached_hostip;
301 /* This is much faster than snprintf */
303 for(char* n = ident; *n; n++)
306 for(const char* n = this->GetIPString(); *n; n++)
310 this->cached_hostip = strdup(ihost);
312 return this->cached_hostip;
315 void User::CloseSocket()
319 ServerInstance->SE->Shutdown(this, 2);
320 ServerInstance->SE->Close(this);
324 char* User::GetFullHost()
326 if (this->cached_fullhost)
327 return this->cached_fullhost;
331 for(char* n = nick; *n; n++)
334 for(char* n = ident; *n; n++)
337 for(char* n = dhost; *n; n++)
341 this->cached_fullhost = strdup(result);
343 return this->cached_fullhost;
346 char* User::MakeWildHost()
348 static char nresult[MAXBUF];
350 *t++ = '*'; *t++ = '!';
351 *t++ = '*'; *t++ = '@';
352 for(char* n = dhost; *n; n++)
358 int User::ReadData(void* buffer, size_t size)
363 return read(this->fd, buffer, size);
365 return recv(this->fd, (char*)buffer, size, 0);
373 char* User::GetFullRealHost()
375 if (this->cached_fullrealhost)
376 return this->cached_fullrealhost;
378 char fresult[MAXBUF];
380 for(char* n = nick; *n; n++)
383 for(char* n = ident; *n; n++)
386 for(char* n = host; *n; n++)
390 this->cached_fullrealhost = strdup(fresult);
392 return this->cached_fullrealhost;
395 bool User::IsInvited(const irc::string &channel)
397 time_t now = time(NULL);
398 InvitedList::iterator safei;
399 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
401 if (channel == i->first)
403 if (i->second != 0 && now > i->second)
405 /* Expired invite, remove it. */
408 invites.erase(safei);
417 InvitedList* User::GetInviteList()
419 time_t now = time(NULL);
420 /* Weed out expired invites here. */
421 InvitedList::iterator safei;
422 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
424 if (i->second != 0 && now > i->second)
426 /* Expired invite, remove it. */
429 invites.erase(safei);
435 void User::InviteTo(const irc::string &channel, time_t invtimeout)
437 time_t now = time(NULL);
438 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
439 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
441 if (channel == i->first)
443 if (i->second != 0 && invtimeout > i->second)
445 i->second = invtimeout;
449 invites.push_back(std::make_pair(channel, invtimeout));
452 void User::RemoveInvite(const irc::string &channel)
454 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
456 if (channel == i->first)
464 bool User::HasModePermission(unsigned char mode, ModeType type)
472 if (!AllowedUserModes || !AllowedChanModes)
475 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
479 bool User::HasPermission(const std::string &command)
482 * users on remote servers can completely bypass all permissions based checks.
483 * This prevents desyncs when one server has different type/class tags to another.
484 * That having been said, this does open things up to the possibility of source changes
485 * allowing remote kills, etc - but if they have access to the src, they most likely have
486 * access to the conf - so it's an end to a means either way.
491 // are they even an oper at all?
497 if (!AllowedOperCommands)
500 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
502 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
508 /** NOTE: We cannot pass a const reference to this method.
509 * The string is changed by the workings of the method,
510 * so that if we pass const ref, we end up copying it to
511 * something we can change anyway. Makes sense to just let
512 * the compiler do that copy for us.
514 bool User::AddBuffer(std::string a)
518 std::string::size_type i = a.rfind('\r');
520 while (i != std::string::npos)
529 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
531 this->SetWriteError("RecvQ exceeded");
532 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)recvq.length(),this->MyClass->GetRecvqMax());
541 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
546 bool User::BufferIsReady()
548 return (recvq.find('\n') != std::string::npos);
551 void User::ClearBuffer()
556 std::string User::GetBuffer()
563 /* Strip any leading \r or \n off the string.
564 * Usually there are only one or two of these,
565 * so its is computationally cheap to do.
567 std::string::iterator t = recvq.begin();
568 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
574 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
576 /* Find the first complete line, return it as the
577 * result, and leave the recvq as whats left
581 std::string ret = std::string(recvq.begin(), x);
582 recvq.erase(recvq.begin(), x + 1);
591 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
596 void User::AddWriteBuf(const std::string &data)
598 if (*this->GetWriteError())
601 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
604 * Fix by brain - Set the error text BEFORE calling, because
605 * if we dont it'll recursively call here over and over again trying
606 * to repeatedly add the text to the sendq!
608 this->SetWriteError("SendQ exceeded");
609 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)sendq.length() + data.length(),this->MyClass->GetSendqMax());
613 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
614 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
619 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
620 void User::FlushWriteBuf()
624 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
628 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
630 int old_sendq_length = sendq.length();
631 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
637 /* The socket buffer is full. This isnt fatal,
640 this->ServerInstance->SE->WantWrite(this);
644 /* Fatal error, set write error and bail
646 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
652 /* advance the queue */
654 this->sendq = this->sendq.substr(n_sent);
655 /* update the user's stats counters */
656 this->bytes_out += n_sent;
658 if (n_sent != old_sendq_length)
659 this->ServerInstance->SE->WantWrite(this);
666 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
669 if (this->sendq.empty())
671 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
675 void User::SetWriteError(const std::string &error)
677 // don't try to set the error twice, its already set take the first string.
678 if (this->WriteError.empty())
679 this->WriteError = error;
682 const char* User::GetWriteError()
684 return this->WriteError.c_str();
687 void User::Oper(const std::string &opertype, const std::string &opername)
695 this->modes[UM_OPERATOR] = 1;
696 this->WriteServ("MODE %s :+o", this->nick);
697 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
698 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
699 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
700 ServerInstance->Users->all_opers.push_back(this);
702 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
703 if (iter_opertype != ServerInstance->Config->opertypes.end())
706 if (AllowedOperCommands)
707 AllowedOperCommands->clear();
709 AllowedOperCommands = new std::map<std::string, bool>;
711 if (!AllowedChanModes)
712 AllowedChanModes = new bool[64];
714 if (!AllowedUserModes)
715 AllowedUserModes = new bool[64];
717 memset(AllowedUserModes, 0, 64);
718 memset(AllowedChanModes, 0, 64);
720 char* Classes = strdup(iter_opertype->second);
721 char* myclass = strtok_r(Classes," ",&savept);
724 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
725 if (iter_operclass != ServerInstance->Config->operclass.end())
727 char* CommandList = strdup(iter_operclass->second.commandlist);
728 mycmd = strtok_r(CommandList," ",&savept2);
731 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
732 mycmd = strtok_r(NULL," ",&savept2);
735 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
736 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
740 memset(this->AllowedUserModes, (int)(true), 64);
744 this->AllowedUserModes[*c - 'A'] = true;
747 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
751 memset(this->AllowedChanModes, (int)(true), 64);
755 this->AllowedChanModes[*c - 'A'] = true;
759 myclass = strtok_r(NULL," ",&savept);
764 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
769 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
777 /* Remove all oper only modes from the user when the deoper - Bug #466*/
778 std::string moderemove("-");
780 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
784 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
785 if (mh && mh->NeedsOper())
786 moderemove += letter;
790 const char* parameters[] = { this->nick, moderemove.c_str() };
791 ServerInstance->Parser->CallHandler("MODE", parameters, 2, this);
793 /* unset their oper type (what IS_OPER checks), and remove +o */
795 this->modes[UM_OPERATOR] = 0;
797 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
798 ServerInstance->Users->all_opers.remove(this);
800 if (AllowedOperCommands)
802 delete AllowedOperCommands;
803 AllowedOperCommands = NULL;
805 if (AllowedUserModes)
807 delete[] AllowedUserModes;
808 AllowedUserModes = NULL;
810 if (AllowedChanModes)
812 delete[] AllowedChanModes;
813 AllowedChanModes = NULL;
819 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
821 Instance->Logs->Log("USERS", DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
822 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
823 user->quietquit = false;
824 user->quitmsg = quitreason;
827 user->operquitmsg = quitreason;
829 user->operquitmsg = operreason;
831 Instance->GlobalCulls.AddItem(user);
834 /* adds or updates an entry in the whowas list */
835 void User::AddToWhoWas()
837 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
840 std::deque<classbase*> params;
841 params.push_back(this);
842 whowas_command->HandleInternal(WHOWAS_ADD, params);
847 * Check class restrictions
849 void User::CheckClass()
851 ConnectClass* a = this->MyClass;
853 if ((!a) || (a->GetType() == CC_DENY))
855 User::QuitUser(ServerInstance, this, "Unauthorised connection");
858 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
860 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
861 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
864 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
866 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
867 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
871 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
872 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
873 this->MaxChans = a->GetMaxChans();
876 void User::FullConnect()
878 ServerInstance->stats->statsConnects++;
879 this->idle_lastmsg = ServerInstance->Time();
882 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
883 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
884 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
885 * Don't remove this! -- w00t
889 /* Check the password, if one is required by the user's connect class.
890 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
892 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
894 User::QuitUser(ServerInstance, this, "Invalid password");
900 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
908 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
917 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
918 this->WriteNumeric(001, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
919 this->WriteNumeric(002, "%s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
920 this->WriteNumeric(003, "%s :This server was created %s %s", this->nick, __TIME__, __DATE__);
921 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());
923 ServerInstance->Config->Send005(this);
925 this->WriteNumeric(42, "%s %s :your unique ID", this->nick, this->uuid);
931 if (ServerInstance->Users->unregistered_count)
932 ServerInstance->Users->unregistered_count--;
934 /* Trigger LUSERS output, give modules a chance too */
936 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
938 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
941 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
942 * for a user that doesn't exist yet.
944 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
946 this->registered = REG_ALL;
948 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
950 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString(), this->fullname);
951 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
952 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
955 /** User::UpdateNick()
956 * re-allocates a nick in the user_hash after they change nicknames,
957 * returns a pointer to the new user as it may have moved
959 User* User::UpdateNickHash(const char* New)
961 //user_hash::iterator newnick;
962 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
964 if (!strcasecmp(this->nick,New))
965 return oldnick->second;
967 if (oldnick == ServerInstance->Users->clientlist->end())
968 return NULL; /* doesnt exist */
970 User* olduser = oldnick->second;
971 (*(ServerInstance->Users->clientlist))[New] = olduser;
972 ServerInstance->Users->clientlist->erase(oldnick);
976 void User::InvalidateCache()
978 /* Invalidate cache */
980 free(cached_fullhost);
984 free(cached_makehost);
985 if (cached_fullrealhost)
986 free(cached_fullrealhost);
987 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
990 bool User::ForceNickChange(const char* newnick)
993 * XXX this makes no sense..
994 * why do we do nothing for change on users not REG_ALL?
995 * why do we trigger events twice for everyone previously (and just them now)
996 * i think the first if () needs removing totally, or? -- w00t
998 if (this->registered != REG_ALL)
1002 this->InvalidateCache();
1004 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1008 ServerInstance->stats->statsCollisions++;
1012 if (ServerInstance->XLines->MatchesLine("Q",newnick))
1014 ServerInstance->stats->statsCollisions++;
1020 std::deque<classbase*> dummy;
1021 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1022 if (nickhandler) // wtfbbq, when would this not be here
1024 nickhandler->HandleInternal(1, dummy);
1025 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1026 nickhandler->HandleInternal(0, dummy);
1035 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1037 this->cachedip = "";
1039 switch (protocol_family)
1041 #ifdef SUPPORT_IP6LINKS
1044 sockaddr_in6* sin = new sockaddr_in6;
1045 sin->sin6_family = AF_INET6;
1046 sin->sin6_port = port;
1047 inet_pton(AF_INET6, sip, &sin->sin6_addr);
1048 this->ip = (sockaddr*)sin;
1054 sockaddr_in* sin = new sockaddr_in;
1055 sin->sin_family = AF_INET;
1056 sin->sin_port = port;
1057 inet_pton(AF_INET, sip, &sin->sin_addr);
1058 this->ip = (sockaddr*)sin;
1062 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1069 if (this->ip == NULL)
1072 switch (this->GetProtocolFamily())
1074 #ifdef SUPPORT_IP6LINKS
1077 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1078 return sin->sin6_port;
1084 sockaddr_in* sin = (sockaddr_in*)this->ip;
1085 return sin->sin_port;
1094 int User::GetProtocolFamily()
1096 if (this->ip == NULL)
1099 sockaddr_in* sin = (sockaddr_in*)this->ip;
1100 return sin->sin_family;
1104 * XXX the duplication here is horrid..
1105 * do we really need two methods doing essentially the same thing?
1107 const char* User::GetIPString()
1109 static char buf[1024];
1111 if (this->ip == NULL)
1114 if (!this->cachedip.empty())
1115 return this->cachedip.c_str();
1117 switch (this->GetProtocolFamily())
1119 #ifdef SUPPORT_IP6LINKS
1122 static char temp[1024];
1124 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1125 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1126 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1129 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1131 this->cachedip = temp;
1135 this->cachedip = buf;
1142 sockaddr_in* sin = (sockaddr_in*)this->ip;
1143 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1144 this->cachedip = buf;
1152 // Unreachable, probably
1156 /** NOTE: We cannot pass a const reference to this method.
1157 * The string is changed by the workings of the method,
1158 * so that if we pass const ref, we end up copying it to
1159 * something we can change anyway. Makes sense to just let
1160 * the compiler do that copy for us.
1162 void User::Write(std::string text)
1164 if (!ServerInstance->SE->BoundsCheckFd(this))
1169 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1170 text.append("\r\n");
1174 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1180 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1181 * implement their own buffering mechanisms
1185 this->io->OnRawSocketWrite(this->fd, text.data(), text.length());
1187 catch (CoreException& modexcept)
1189 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1194 this->AddWriteBuf(text);
1196 ServerInstance->stats->statsSent += text.length();
1197 this->ServerInstance->SE->WantWrite(this);
1202 void User::Write(const char *text, ...)
1205 char textbuffer[MAXBUF];
1207 va_start(argsPtr, text);
1208 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1211 this->Write(std::string(textbuffer));
1214 void User::WriteServ(const std::string& text)
1216 char textbuffer[MAXBUF];
1218 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1219 this->Write(std::string(textbuffer));
1223 * Same as Write(), except `text' is prefixed with `:server.name '.
1225 void User::WriteServ(const char* text, ...)
1228 char textbuffer[MAXBUF];
1230 va_start(argsPtr, text);
1231 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1234 this->WriteServ(std::string(textbuffer));
1238 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1241 char textbuffer[MAXBUF];
1243 va_start(argsPtr, text);
1244 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1247 this->WriteNumeric(numeric, std::string(textbuffer));
1250 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1252 char textbuffer[MAXBUF];
1255 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1260 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1261 this->Write(std::string(textbuffer));
1264 void User::WriteFrom(User *user, const std::string &text)
1268 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1270 this->Write(std::string(tb));
1274 /* write text from an originating user to originating user */
1276 void User::WriteFrom(User *user, const char* text, ...)
1279 char textbuffer[MAXBUF];
1281 va_start(argsPtr, text);
1282 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1285 this->WriteFrom(user, std::string(textbuffer));
1289 /* write text to an destination user from a source user (e.g. user privmsg) */
1291 void User::WriteTo(User *dest, const char *data, ...)
1293 char textbuffer[MAXBUF];
1296 va_start(argsPtr, data);
1297 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1300 this->WriteTo(dest, std::string(textbuffer));
1303 void User::WriteTo(User *dest, const std::string &data)
1305 dest->WriteFrom(this, data);
1309 void User::WriteCommon(const char* text, ...)
1311 char textbuffer[MAXBUF];
1314 if (this->registered != REG_ALL)
1317 va_start(argsPtr, text);
1318 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1321 this->WriteCommon(std::string(textbuffer));
1324 void User::WriteCommon(const std::string &text)
1326 bool sent_to_at_least_one = false;
1329 if (this->registered != REG_ALL)
1335 InitializeAlreadySent(ServerInstance->SE);
1337 /* We dont want to be doing this n times, just once */
1338 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1339 std::string out = tb;
1341 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1343 CUList* ulist = v->first->GetUsers();
1344 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1346 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1348 already_sent[i->first->fd] = uniq_id;
1349 i->first->Write(out);
1350 sent_to_at_least_one = true;
1356 * if the user was not in any channels, no users will receive the text. Make sure the user
1357 * receives their OWN message for WriteCommon
1359 if (!sent_to_at_least_one)
1361 this->Write(std::string(tb));
1366 /* write a formatted string to all users who share at least one common
1367 * channel, NOT including the source user e.g. for use in QUIT
1370 void User::WriteCommonExcept(const char* text, ...)
1372 char textbuffer[MAXBUF];
1375 va_start(argsPtr, text);
1376 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1379 this->WriteCommonExcept(std::string(textbuffer));
1382 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1387 if (this->registered != REG_ALL)
1393 InitializeAlreadySent(ServerInstance->SE);
1395 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1396 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1397 std::string out1 = tb1;
1398 std::string out2 = tb2;
1400 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1402 CUList *ulist = v->first->GetUsers();
1403 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1405 if (this != i->first)
1407 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1409 already_sent[i->first->fd] = uniq_id;
1410 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1417 void User::WriteCommonExcept(const std::string &text)
1422 if (this->registered != REG_ALL)
1428 InitializeAlreadySent(ServerInstance->SE);
1430 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1433 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1435 CUList *ulist = v->first->GetUsers();
1436 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1438 if (this != i->first)
1440 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1442 already_sent[i->first->fd] = uniq_id;
1443 i->first->Write(out1);
1451 void User::WriteWallOps(const std::string &text)
1453 if (!IS_OPER(this) && IS_LOCAL(this))
1456 std::string wallop("WALLOPS :");
1457 wallop.append(text);
1459 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1462 if (t->IsModeSet('w'))
1463 this->WriteTo(t,wallop);
1467 void User::WriteWallOps(const char* text, ...)
1469 char textbuffer[MAXBUF];
1472 va_start(argsPtr, text);
1473 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1476 this->WriteWallOps(std::string(textbuffer));
1479 /* return 0 or 1 depending if users u and u2 share one or more common channels
1480 * (used by QUIT, NICK etc which arent channel specific notices)
1482 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1483 * the first users channels then the second users channels within the outer loop,
1484 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1485 * all possible iterations). However this new function instead checks against the
1486 * channel's userlist in the inner loop which is a std::map<User*,User*>
1487 * and saves us time as we already know what pointer value we are after.
1488 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1489 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1491 bool User::SharesChannelWith(User *other)
1493 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1497 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1499 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1500 * by replacing it with a map::find which *should* be more efficient
1502 if (i->first->HasUser(other))
1508 bool User::ChangeName(const char* gecos)
1510 if (!strcmp(gecos, this->fullname))
1516 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1519 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1521 strlcpy(this->fullname,gecos,MAXGECOS+1);
1526 bool User::ChangeDisplayedHost(const char* shost)
1528 if (!strcmp(shost, this->dhost))
1534 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1537 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1540 if (this->ServerInstance->Config->CycleHosts)
1541 this->WriteCommonExcept("QUIT :Changing hosts");
1543 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1544 strlcpy(this->dhost,shost,64);
1546 this->InvalidateCache();
1548 if (this->ServerInstance->Config->CycleHosts)
1550 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1552 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1553 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1555 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1560 this->WriteNumeric(396, "%s %s :is now your displayed host",this->nick,this->dhost);
1565 bool User::ChangeIdent(const char* newident)
1567 if (!strcmp(newident, this->ident))
1570 if (this->ServerInstance->Config->CycleHosts)
1571 this->WriteCommonExcept("%s","QUIT :Changing ident");
1573 strlcpy(this->ident, newident, IDENTMAX+1);
1575 this->InvalidateCache();
1577 if (this->ServerInstance->Config->CycleHosts)
1579 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1581 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1582 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1584 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1591 void User::SendAll(const char* command, const char* text, ...)
1593 char textbuffer[MAXBUF];
1594 char formatbuffer[MAXBUF];
1597 va_start(argsPtr, text);
1598 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1601 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1602 std::string fmt = formatbuffer;
1604 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1611 std::string User::ChannelList(User* source)
1615 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1617 /* If the target is the same as the sender, let them see all their channels.
1618 * If the channel is NOT private/secret OR the user shares a common channel
1619 * If the user is an oper, and the <options:operspywhois> option is set.
1621 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1623 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1630 void User::SplitChanList(User* dest, const std::string &cl)
1633 std::ostringstream prefix;
1634 std::string::size_type start, pos, length;
1636 prefix << this->nick << " " << dest->nick << " :";
1637 line = prefix.str();
1638 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1640 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1642 length = (pos == std::string::npos) ? cl.length() : pos;
1644 if (line.length() + namelen + length - start > 510)
1646 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1647 line = prefix.str();
1650 if(pos == std::string::npos)
1652 line.append(cl.substr(start, length - start));
1657 line.append(cl.substr(start, length - start + 1));
1663 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1667 unsigned int User::GetMaxChans()
1669 return this->MaxChans;
1674 * Sets a user's connection class.
1675 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1676 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1677 * then their ip will be taken as 'priority' anyway, so for example,
1678 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1680 ConnectClass* User::SetClass(const std::string &explicit_name)
1682 ConnectClass *found = NULL;
1684 if (!IS_LOCAL(this))
1687 if (!explicit_name.empty())
1689 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1691 ConnectClass* c = *i;
1693 if (explicit_name == c->GetName() && !c->GetDisabled())
1701 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1703 ConnectClass* c = *i;
1705 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1709 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1718 if (!c->GetDisabled())
1725 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1728 /* deny change if change will take class over the limit */
1729 if (found->limit && (found->RefCount + 1 >= found->limit))
1731 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", found->limit);
1732 return this->MyClass;
1735 /* should always be valid, but just in case .. */
1738 if (found == this->MyClass) // no point changing this shit :P
1739 return this->MyClass;
1740 this->MyClass->RefCount--;
1741 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %lu", this->MyClass->RefCount);
1744 this->MyClass = found;
1745 this->MyClass->RefCount++;
1746 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %lu", this->MyClass->RefCount);
1749 return this->MyClass;
1752 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1753 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1754 * then their ip will be taken as 'priority' anyway, so for example,
1755 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1757 ConnectClass* User::GetClass()
1759 return this->MyClass;
1762 void User::PurgeEmptyChannels()
1764 std::vector<Channel*> to_delete;
1766 // firstly decrement the count on each channel
1767 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1769 f->first->RemoveAllPrefixes(this);
1770 if (f->first->DelUser(this) == 0)
1772 /* No users left in here, mark it for deletion */
1775 to_delete.push_back(f->first);
1779 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1784 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1786 Channel* thischan = *n;
1787 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1788 if (i2 != ServerInstance->chanlist->end())
1790 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1792 ServerInstance->chanlist->erase(i2);
1793 this->chans.erase(*n);
1800 void User::ShowMOTD()
1802 if (!ServerInstance->Config->MOTD.size())
1804 this->WriteNumeric(422, "%s :Message of the day file is missing.",this->nick);
1807 this->WriteNumeric(375, "%s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1809 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1810 this->WriteNumeric(372, "%s :- %s",this->nick,i->c_str());
1812 this->WriteNumeric(376, "%s :End of message of the day.", this->nick);
1815 void User::ShowRULES()
1817 if (!ServerInstance->Config->RULES.size())
1819 this->WriteNumeric(434, "%s :RULES File is missing",this->nick);
1823 this->WriteNumeric(308, "%s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1825 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1826 this->WriteNumeric(232, "%s :- %s",this->nick,i->c_str());
1828 this->WriteNumeric(309, "%s :End of RULES command.",this->nick);
1831 void User::HandleEvent(EventType et, int errornum)
1833 if (this->quitting) // drop everything, user is due to be quit
1836 /* WARNING: May delete this user! */
1837 int thisfd = this->GetFd();
1844 ServerInstance->ProcessUser(this);
1847 this->FlushWriteBuf();
1850 /** This should be safe, but dont DARE do anything after it -- Brain */
1851 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1857 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1860 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1861 if ((ServerInstance->SE->GetRef(thisfd) == this))
1863 if (!WriteError.empty())
1865 User::QuitUser(ServerInstance, this, GetWriteError());
1870 void User::SetOperQuit(const std::string &oquit)
1872 operquitmsg = oquit;
1875 const char* User::GetOperQuit()
1877 return operquitmsg.c_str();
1880 void User::IncreasePenalty(int increase)
1882 this->Penalty += increase;
1885 void User::DecreasePenalty(int decrease)
1887 this->Penalty -= decrease;
1898 bool VisData::VisibleTo(User* user)