1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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"
21 #include "commands/cmd_whowas.h"
23 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
25 /* XXX: Used for speeding up WriteCommon operations */
26 unsigned long uniq_id = 0;
28 std::string User::ProcessNoticeMasks(const char *sm)
30 bool adding = true, oldadding = false;
45 for (unsigned char d = 'A'; d <= 'z'; d++)
47 if (ServerInstance->SNO->IsEnabled(d))
49 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
51 if ((oldadding != adding) || (!output.length()))
52 output += (adding ? '+' : '-');
54 this->SetNoticeMask(d, adding);
63 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
65 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
67 if ((oldadding != adding) || (!output.length()))
68 output += (adding ? '+' : '-');
70 this->SetNoticeMask(*c, adding);
85 void User::StartDNSLookup()
90 const char* ip = this->GetIPString();
92 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
93 if (!strncmp(ip, "0::ffff:", 8))
94 res_reverse = new UserResolver(this->ServerInstance, this, ip + 8, DNS_QUERY_PTR4, cached);
96 res_reverse = new UserResolver(this->ServerInstance, this, ip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
98 this->ServerInstance->AddResolver(res_reverse, cached);
100 catch (CoreException& e)
102 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
106 bool User::IsNoticeMaskSet(unsigned char sm)
108 return (snomasks[sm-65]);
111 void User::SetNoticeMask(unsigned char sm, bool value)
113 snomasks[sm-65] = value;
116 const char* User::FormatNoticeMasks()
118 static char data[MAXBUF];
121 for (int n = 0; n < 64; n++)
124 data[offset++] = n+65;
133 bool User::IsModeSet(unsigned char m)
135 return (modes[m-65]);
138 void User::SetMode(unsigned char m, bool value)
143 const char* User::FormatModes()
145 static char data[MAXBUF];
147 for (int n = 0; n < 64; n++)
150 data[offset++] = n+65;
156 void User::DecrementModes()
158 ServerInstance->Log(DEBUG,"DecrementModes()");
159 for (unsigned char n = 'A'; n <= 'z'; n++)
163 ServerInstance->Log(DEBUG,"DecrementModes() found mode %c", n);
164 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
167 ServerInstance->Log(DEBUG,"Found handler %c and call ChangeCount", n);
174 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
176 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
177 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
178 reset_due = ServerInstance->Time();
179 age = ServerInstance->Time(true);
181 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
182 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
183 OverPenalty = ExemptFromPenalty = muted = exempt = haspassed = dns_done = false;
188 res_forward = res_reverse = NULL;
194 memset(modes,0,sizeof(modes));
195 memset(snomasks,0,sizeof(snomasks));
196 /* Invalidate cache */
197 operquit = cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
200 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
202 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
204 ServerInstance->Log(DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
206 user_hash::iterator finduuid = Instance->uuidlist->find(uuid);
207 if (finduuid == Instance->uuidlist->end())
208 (*Instance->uuidlist)[uuid] = this;
210 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
213 void User::RemoveCloneCounts()
215 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
216 if (x != ServerInstance->local_clones.end())
221 ServerInstance->local_clones.erase(x);
225 clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
226 if (y != ServerInstance->global_clones.end())
231 ServerInstance->global_clones.erase(y);
238 /* NULL for remote users :) */
241 this->MyClass->RefCount--;
242 ServerInstance->Log(DEBUG, "User destructor -- connect refcount now: %u", this->MyClass->RefCount);
245 this->InvalidateCache();
246 this->DecrementModes();
251 this->RemoveCloneCounts();
253 if (this->GetProtocolFamily() == AF_INET)
255 delete (sockaddr_in*)ip;
257 #ifdef SUPPORT_IP6LINKS
260 delete (sockaddr_in6*)ip;
265 ServerInstance->uuidlist->erase(uuid);
268 char* User::MakeHost()
270 if (this->cached_makehost)
271 return this->cached_makehost;
274 /* This is much faster than snprintf */
276 for(char* n = ident; *n; n++)
279 for(char* n = host; *n; n++)
283 this->cached_makehost = strdup(nhost);
285 return this->cached_makehost;
288 char* User::MakeHostIP()
290 if (this->cached_hostip)
291 return this->cached_hostip;
294 /* This is much faster than snprintf */
296 for(char* n = ident; *n; n++)
299 for(const char* n = this->GetIPString(); *n; n++)
303 this->cached_hostip = strdup(ihost);
305 return this->cached_hostip;
308 void User::CloseSocket()
310 ServerInstance->SE->Shutdown(this, 2);
311 ServerInstance->SE->Close(this);
314 char* User::GetFullHost()
316 if (this->cached_fullhost)
317 return this->cached_fullhost;
321 for(char* n = nick; *n; n++)
324 for(char* n = ident; *n; n++)
327 for(char* n = dhost; *n; n++)
331 this->cached_fullhost = strdup(result);
333 return this->cached_fullhost;
336 char* User::MakeWildHost()
338 static char nresult[MAXBUF];
340 *t++ = '*'; *t++ = '!';
341 *t++ = '*'; *t++ = '@';
342 for(char* n = dhost; *n; n++)
348 int User::ReadData(void* buffer, size_t size)
353 return read(this->fd, buffer, size);
355 return recv(this->fd, (char*)buffer, size, 0);
363 char* User::GetFullRealHost()
365 if (this->cached_fullrealhost)
366 return this->cached_fullrealhost;
368 char fresult[MAXBUF];
370 for(char* n = nick; *n; n++)
373 for(char* n = ident; *n; n++)
376 for(char* n = host; *n; n++)
380 this->cached_fullrealhost = strdup(fresult);
382 return this->cached_fullrealhost;
385 bool User::IsInvited(const irc::string &channel)
387 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
397 InvitedList* User::GetInviteList()
402 void User::InviteTo(const irc::string &channel)
404 invites.push_back(channel);
407 void User::RemoveInvite(const irc::string &channel)
409 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
419 bool User::HasPermission(const std::string &command)
426 * users on remote servers can completely bypass all permissions based checks.
427 * This prevents desyncs when one server has different type/class tags to another.
428 * That having been said, this does open things up to the possibility of source changes
429 * allowing remote kills, etc - but if they have access to the src, they most likely have
430 * access to the conf - so it's an end to a means either way.
435 // are they even an oper at all?
441 // check their opertype exists (!). This won't affect local users, of course.
442 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
443 if (iter_opertype == ServerInstance->Config->opertypes.end())
448 /* XXX all this strtok/strdup stuff is a bit ick and horrid -- w00t */
449 char* Classes = strdup(iter_opertype->second);
450 char* myclass = strtok_r(Classes," ",&savept);
453 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
454 if (iter_operclass != ServerInstance->Config->operclass.end())
456 char* CommandList = strdup(iter_operclass->second);
457 mycmd = strtok_r(CommandList," ",&savept2);
460 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
466 mycmd = strtok_r(NULL," ",&savept2);
470 myclass = strtok_r(NULL," ",&savept);
477 /** NOTE: We cannot pass a const reference to this method.
478 * The string is changed by the workings of the method,
479 * so that if we pass const ref, we end up copying it to
480 * something we can change anyway. Makes sense to just let
481 * the compiler do that copy for us.
483 bool User::AddBuffer(std::string a)
487 std::string::size_type i = a.rfind('\r');
489 while (i != std::string::npos)
498 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
500 this->SetWriteError("RecvQ exceeded");
501 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
510 ServerInstance->Log(DEBUG,"Exception in User::AddBuffer()");
515 bool User::BufferIsReady()
517 return (recvq.find('\n') != std::string::npos);
520 void User::ClearBuffer()
525 std::string User::GetBuffer()
532 /* Strip any leading \r or \n off the string.
533 * Usually there are only one or two of these,
534 * so its is computationally cheap to do.
536 std::string::iterator t = recvq.begin();
537 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
543 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
545 /* Find the first complete line, return it as the
546 * result, and leave the recvq as whats left
550 std::string ret = std::string(recvq.begin(), x);
551 recvq.erase(recvq.begin(), x + 1);
560 ServerInstance->Log(DEBUG,"Exception in User::GetBuffer()");
565 void User::AddWriteBuf(const std::string &data)
567 if (*this->GetWriteError())
570 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
573 * Fix by brain - Set the error text BEFORE calling writeopers, because
574 * if we dont it'll recursively call here over and over again trying
575 * to repeatedly add the text to the sendq!
577 this->SetWriteError("SendQ exceeded");
578 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
584 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
585 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
591 this->SetWriteError("SendQ exceeded");
592 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
596 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
597 void User::FlushWriteBuf()
601 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
605 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
607 int old_sendq_length = sendq.length();
608 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
614 /* The socket buffer is full. This isnt fatal,
617 this->ServerInstance->SE->WantWrite(this);
621 /* Fatal error, set write error and bail
623 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
629 /* advance the queue */
631 this->sendq = this->sendq.substr(n_sent);
632 /* update the user's stats counters */
633 this->bytes_out += n_sent;
635 if (n_sent != old_sendq_length)
636 this->ServerInstance->SE->WantWrite(this);
643 ServerInstance->Log(DEBUG,"Exception in User::FlushWriteBuf()");
646 if (this->sendq.empty())
648 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
652 void User::SetWriteError(const std::string &error)
656 // don't try to set the error twice, its already set take the first string.
657 if (this->WriteError.empty())
658 this->WriteError = error;
663 ServerInstance->Log(DEBUG,"Exception in User::SetWriteError()");
667 const char* User::GetWriteError()
669 return this->WriteError.c_str();
672 void User::Oper(const std::string &opertype)
676 this->modes[UM_OPERATOR] = 1;
677 this->WriteServ("MODE %s :+o", this->nick);
678 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
679 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
680 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
681 ServerInstance->all_opers.push_back(this);
682 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
687 ServerInstance->Log(DEBUG,"Exception in User::Oper()");
697 // unset their oper type (what IS_OPER checks), and remove +o
699 this->modes[UM_OPERATOR] = 0;
701 // remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404
702 ServerInstance->all_opers.remove(this);
708 ServerInstance->Log(DEBUG,"Exception in User::UnOper()");
712 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
714 Instance->Log(DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
715 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
717 Instance->GlobalCulls.AddItem(user, quitreason.c_str(), operreason);
720 /* adds or updates an entry in the whowas list */
721 void User::AddToWhoWas()
723 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
726 std::deque<classbase*> params;
727 params.push_back(this);
728 whowas_command->HandleInternal(WHOWAS_ADD, params);
732 /* add a client connection to the sockets list */
733 void User::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, int socketfamily, sockaddr* ip)
735 /* NOTE: Calling this one parameter constructor for User automatically
736 * allocates a new UUID and places it in the hash_map.
741 New = new User(Instance);
745 Instance->Log(DEFAULT,"*** WTF *** Duplicated UUID! -- Crack smoking monkies have been unleashed.");
746 Instance->WriteOpers("*** WARNING *** Duplicate UUID allocated!");
750 Instance->Log(DEBUG,"New user fd: %d", socket);
754 Instance->unregistered_count++;
758 if (socketfamily == AF_INET6)
759 inet_ntop(AF_INET6, &((const sockaddr_in6*)ip)->sin6_addr, ipaddr, sizeof(ipaddr));
762 inet_ntop(AF_INET, &((const sockaddr_in*)ip)->sin_addr, ipaddr, sizeof(ipaddr));
764 (*(Instance->clientlist))[New->uuid] = New;
767 /* The users default nick is their UUID */
768 strlcpy(New->nick, New->uuid, NICKMAX - 1);
770 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
771 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
772 strcpy(New->ident, "unknown");
774 New->registered = REG_NONE;
775 New->signon = Instance->Time() + Instance->Config->dns_timeout;
778 New->SetSockAddr(socketfamily, ipaddr, port);
780 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
781 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
782 New->dhost[j] = New->host[j] = *temp;
783 New->dhost[j] = New->host[j] = 0;
785 Instance->AddLocalClone(New);
786 Instance->AddGlobalClone(New);
789 * First class check. We do this again in FullConnect after DNS is done, and NICK/USER is recieved.
790 * See my note down there for why this is required. DO NOT REMOVE. :) -- w00t
792 ConnectClass* i = New->SetClass();
796 User::QuitUser(Instance, New, "Access denied by configuration");
801 * Check connect class settings and initialise settings into User.
802 * This will be done again after DNS resolution. -- w00t
806 Instance->local_users.push_back(New);
808 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
810 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
811 User::QuitUser(Instance, New,"No more connections allowed");
817 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
818 * its a pretty big but for the moment valid assumption:
819 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
820 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
821 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
822 * which for the time being is a physical impossibility (even the largest networks dont have more
823 * than about 10,000 users on ONE server!)
826 if ((unsigned int)socket >= MAX_DESCRIPTORS)
828 User::QuitUser(Instance, New, "Server is full");
833 New->exempt = (Instance->XLines->MatchesLine("E",New) != NULL);
836 XLine* r = Instance->XLines->MatchesLine("Z",New);
841 if (*Instance->Config->MoronBanner)
842 New->WriteServ("NOTICE %s :*** %s", New->nick, Instance->Config->MoronBanner);
843 snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
844 User::QuitUser(Instance, New, reason);
851 if (!Instance->SE->AddFd(New))
853 Instance->Log(DEBUG,"Internal error on new connection");
854 User::QuitUser(Instance, New, "Internal error handling connection");
858 /* NOTE: even if dns lookups are *off*, we still need to display this.
859 * BOPM and other stuff requires it.
861 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
863 if (Instance->Config->NoUserDns)
865 New->dns_done = true;
869 New->StartDNSLookup();
873 unsigned long User::GlobalCloneCount()
875 clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
876 if (x != ServerInstance->global_clones.end())
882 unsigned long User::LocalCloneCount()
884 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
885 if (x != ServerInstance->local_clones.end())
892 * Check class restrictions
894 void User::CheckClass()
896 ConnectClass* a = this->MyClass;
898 if ((!a) || (a->GetType() == CC_DENY))
900 User::QuitUser(ServerInstance, this, "Unauthorised connection");
903 else if ((a->GetMaxLocal()) && (this->LocalCloneCount() > a->GetMaxLocal()))
905 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
906 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
909 else if ((a->GetMaxGlobal()) && (this->GlobalCloneCount() > a->GetMaxGlobal()))
911 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
912 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
916 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
917 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
918 this->MaxChans = a->GetMaxChans();
921 void User::FullConnect()
923 ServerInstance->stats->statsConnects++;
924 this->idle_lastmsg = ServerInstance->Time();
927 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
928 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
929 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
930 * Don't remove this! -- w00t
934 /* Check the password, if one is required by the user's connect class.
935 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
937 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
939 User::QuitUser(ServerInstance, this, "Invalid password");
945 XLine* r = ServerInstance->XLines->MatchesLine("G",this);
951 if (*ServerInstance->Config->MoronBanner)
952 this->WriteServ("NOTICE %s :*** %s", this->nick, ServerInstance->Config->MoronBanner);
953 snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
954 User::QuitUser(ServerInstance, this, reason);
958 XLine* n = ServerInstance->XLines->MatchesLine("K",this);
964 if (*ServerInstance->Config->MoronBanner)
965 this->WriteServ("NOTICE %s :*** %s", this, ServerInstance->Config->MoronBanner);
966 snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
967 User::QuitUser(ServerInstance, this, reason);
972 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
973 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
974 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
975 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
976 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());
978 ServerInstance->Config->Send005(this);
980 this->WriteServ("042 %s %s :your unique ID", this->nick, this->uuid);
986 if (ServerInstance->unregistered_count)
987 ServerInstance->unregistered_count--;
989 /* Trigger LUSERS output, give modules a chance too */
991 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
993 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
996 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
997 * for a user that doesn't exist yet.
999 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1001 this->registered = REG_ALL;
1003 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1005 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);
1008 /** User::UpdateNick()
1009 * re-allocates a nick in the user_hash after they change nicknames,
1010 * returns a pointer to the new user as it may have moved
1012 User* User::UpdateNickHash(const char* New)
1016 //user_hash::iterator newnick;
1017 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1019 if (!strcasecmp(this->nick,New))
1020 return oldnick->second;
1022 if (oldnick == ServerInstance->clientlist->end())
1023 return NULL; /* doesnt exist */
1025 User* olduser = oldnick->second;
1026 (*(ServerInstance->clientlist))[New] = olduser;
1027 ServerInstance->clientlist->erase(oldnick);
1033 ServerInstance->Log(DEBUG,"Exception in User::UpdateNickHash()");
1038 void User::InvalidateCache()
1040 /* Invalidate cache */
1041 if (cached_fullhost)
1042 free(cached_fullhost);
1044 free(cached_hostip);
1045 if (cached_makehost)
1046 free(cached_makehost);
1047 if (cached_fullrealhost)
1048 free(cached_fullrealhost);
1049 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1052 bool User::ForceNickChange(const char* newnick)
1058 this->InvalidateCache();
1060 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1064 ServerInstance->stats->statsCollisions++;
1068 if (ServerInstance->XLines->MatchesLine("Q",newnick))
1070 ServerInstance->stats->statsCollisions++;
1074 if (this->registered == REG_ALL)
1076 std::deque<classbase*> dummy;
1077 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1080 nickhandler->HandleInternal(1, dummy);
1081 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1082 nickhandler->HandleInternal(0, dummy);
1091 ServerInstance->Log(DEBUG,"Exception in User::ForceNickChange()");
1096 void User::SetSockAddr(int protocol_family, const char* ip, int port)
1098 switch (protocol_family)
1100 #ifdef SUPPORT_IP6LINKS
1103 sockaddr_in6* sin = new sockaddr_in6;
1104 sin->sin6_family = AF_INET6;
1105 sin->sin6_port = port;
1106 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1107 this->ip = (sockaddr*)sin;
1113 sockaddr_in* sin = new sockaddr_in;
1114 sin->sin_family = AF_INET;
1115 sin->sin_port = port;
1116 inet_pton(AF_INET, ip, &sin->sin_addr);
1117 this->ip = (sockaddr*)sin;
1121 ServerInstance->Log(DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1128 if (this->ip == NULL)
1131 switch (this->GetProtocolFamily())
1133 #ifdef SUPPORT_IP6LINKS
1136 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1137 return sin->sin6_port;
1143 sockaddr_in* sin = (sockaddr_in*)this->ip;
1144 return sin->sin_port;
1153 int User::GetProtocolFamily()
1155 if (this->ip == NULL)
1158 sockaddr_in* sin = (sockaddr_in*)this->ip;
1159 return sin->sin_family;
1163 * XXX the duplication here is horrid..
1164 * do we really need two methods doing essentially the same thing?
1166 const char* User::GetIPString()
1168 static char buf[1024];
1170 if (this->ip == NULL)
1173 switch (this->GetProtocolFamily())
1175 #ifdef SUPPORT_IP6LINKS
1178 static char temp[1024];
1180 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1181 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1182 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1185 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1195 sockaddr_in* sin = (sockaddr_in*)this->ip;
1196 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1206 /** NOTE: We cannot pass a const reference to this method.
1207 * The string is changed by the workings of the method,
1208 * so that if we pass const ref, we end up copying it to
1209 * something we can change anyway. Makes sense to just let
1210 * the compiler do that copy for us.
1212 void User::Write(std::string text)
1214 if (!ServerInstance->SE->BoundsCheckFd(this))
1219 /* ServerInstance->Log(DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1220 * WARNING: The above debug line is VERY loud, do NOT
1221 * enable it till we have a good way of filtering it
1222 * out of the logs (e.g. 1.2 would be good).
1224 text.append("\r\n");
1228 ServerInstance->Log(DEBUG,"Exception in User::Write() std::string::append");
1232 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1236 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1237 * implement their own buffering mechanisms
1239 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1241 catch (CoreException& modexcept)
1243 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1248 this->AddWriteBuf(text);
1250 ServerInstance->stats->statsSent += text.length();
1251 this->ServerInstance->SE->WantWrite(this);
1256 void User::Write(const char *text, ...)
1259 char textbuffer[MAXBUF];
1261 va_start(argsPtr, text);
1262 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1265 this->Write(std::string(textbuffer));
1268 void User::WriteServ(const std::string& text)
1270 char textbuffer[MAXBUF];
1272 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1273 this->Write(std::string(textbuffer));
1277 * Same as Write(), except `text' is prefixed with `:server.name '.
1279 void User::WriteServ(const char* text, ...)
1282 char textbuffer[MAXBUF];
1284 va_start(argsPtr, text);
1285 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1288 this->WriteServ(std::string(textbuffer));
1292 void User::WriteFrom(User *user, const std::string &text)
1296 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1298 this->Write(std::string(tb));
1302 /* write text from an originating user to originating user */
1304 void User::WriteFrom(User *user, const char* text, ...)
1307 char textbuffer[MAXBUF];
1309 va_start(argsPtr, text);
1310 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1313 this->WriteFrom(user, std::string(textbuffer));
1317 /* write text to an destination user from a source user (e.g. user privmsg) */
1319 void User::WriteTo(User *dest, const char *data, ...)
1321 char textbuffer[MAXBUF];
1324 va_start(argsPtr, data);
1325 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1328 this->WriteTo(dest, std::string(textbuffer));
1331 void User::WriteTo(User *dest, const std::string &data)
1333 dest->WriteFrom(this, data);
1337 void User::WriteCommon(const char* text, ...)
1339 char textbuffer[MAXBUF];
1342 if (this->registered != REG_ALL)
1345 va_start(argsPtr, text);
1346 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1349 this->WriteCommon(std::string(textbuffer));
1352 void User::WriteCommon(const std::string &text)
1356 bool sent_to_at_least_one = false;
1359 if (this->registered != REG_ALL)
1364 /* We dont want to be doing this n times, just once */
1365 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1366 std::string out = tb;
1368 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1370 CUList* ulist = v->first->GetUsers();
1371 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1373 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1375 already_sent[i->first->fd] = uniq_id;
1376 i->first->Write(out);
1377 sent_to_at_least_one = true;
1383 * if the user was not in any channels, no users will receive the text. Make sure the user
1384 * receives their OWN message for WriteCommon
1386 if (!sent_to_at_least_one)
1388 this->Write(std::string(tb));
1394 ServerInstance->Log(DEBUG,"Exception in User::WriteCommon()");
1399 /* write a formatted string to all users who share at least one common
1400 * channel, NOT including the source user e.g. for use in QUIT
1403 void User::WriteCommonExcept(const char* text, ...)
1405 char textbuffer[MAXBUF];
1408 va_start(argsPtr, text);
1409 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1412 this->WriteCommonExcept(std::string(textbuffer));
1415 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1420 if (this->registered != REG_ALL)
1424 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1425 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1426 std::string out1 = tb1;
1427 std::string out2 = tb2;
1429 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1431 CUList *ulist = v->first->GetUsers();
1432 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1434 if (this != i->first)
1436 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1438 already_sent[i->first->fd] = uniq_id;
1439 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1446 void User::WriteCommonExcept(const std::string &text)
1451 if (this->registered != REG_ALL)
1455 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1458 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1460 CUList *ulist = v->first->GetUsers();
1461 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1463 if (this != i->first)
1465 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1467 already_sent[i->first->fd] = uniq_id;
1468 i->first->Write(out1);
1476 void User::WriteWallOps(const std::string &text)
1478 if (!IS_OPER(this) && IS_LOCAL(this))
1481 std::string wallop("WALLOPS :");
1482 wallop.append(text);
1484 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1487 if (t->IsModeSet('w'))
1488 this->WriteTo(t,wallop);
1492 void User::WriteWallOps(const char* text, ...)
1494 char textbuffer[MAXBUF];
1497 va_start(argsPtr, text);
1498 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1501 this->WriteWallOps(std::string(textbuffer));
1504 /* return 0 or 1 depending if users u and u2 share one or more common channels
1505 * (used by QUIT, NICK etc which arent channel specific notices)
1507 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1508 * the first users channels then the second users channels within the outer loop,
1509 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1510 * all possible iterations). However this new function instead checks against the
1511 * channel's userlist in the inner loop which is a std::map<User*,User*>
1512 * and saves us time as we already know what pointer value we are after.
1513 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1514 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1516 bool User::SharesChannelWith(User *other)
1518 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1522 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1524 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1525 * by replacing it with a map::find which *should* be more efficient
1527 if (i->first->HasUser(other))
1533 bool User::ChangeName(const char* gecos)
1535 if (!strcmp(gecos, this->fullname))
1541 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1544 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1546 strlcpy(this->fullname,gecos,MAXGECOS+1);
1551 bool User::ChangeDisplayedHost(const char* host)
1553 if (!strcmp(host, this->dhost))
1559 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1562 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1564 if (this->ServerInstance->Config->CycleHosts)
1565 this->WriteCommonExcept("QUIT :Changing hosts");
1567 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1568 strlcpy(this->dhost,host,64);
1570 this->InvalidateCache();
1572 if (this->ServerInstance->Config->CycleHosts)
1574 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1576 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1577 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1579 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1584 this->WriteServ("396 %s %s :is now your displayed host",this->nick,this->dhost);
1589 bool User::ChangeIdent(const char* newident)
1591 if (!strcmp(newident, this->ident))
1594 if (this->ServerInstance->Config->CycleHosts)
1595 this->WriteCommonExcept("%s","QUIT :Changing ident");
1597 strlcpy(this->ident, newident, IDENTMAX+2);
1599 this->InvalidateCache();
1601 if (this->ServerInstance->Config->CycleHosts)
1603 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1605 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1606 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1608 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1615 void User::SendAll(const char* command, char* text, ...)
1617 char textbuffer[MAXBUF];
1618 char formatbuffer[MAXBUF];
1621 va_start(argsPtr, text);
1622 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1625 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1626 std::string fmt = formatbuffer;
1628 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1635 std::string User::ChannelList(User* source)
1640 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1642 /* If the target is the same as the sender, let them see all their channels.
1643 * If the channel is NOT private/secret OR the user shares a common channel
1644 * If the user is an oper, and the <options:operspywhois> option is set.
1646 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1648 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1655 ServerInstance->Log(DEBUG,"Exception in User::ChannelList()");
1660 void User::SplitChanList(User* dest, const std::string &cl)
1663 std::ostringstream prefix;
1664 std::string::size_type start, pos, length;
1668 prefix << this->nick << " " << dest->nick << " :";
1669 line = prefix.str();
1670 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1672 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1674 length = (pos == std::string::npos) ? cl.length() : pos;
1676 if (line.length() + namelen + length - start > 510)
1678 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1679 line = prefix.str();
1682 if(pos == std::string::npos)
1684 line.append(cl.substr(start, length - start));
1689 line.append(cl.substr(start, length - start + 1));
1695 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1701 ServerInstance->Log(DEBUG,"Exception in User::SplitChanList()");
1705 unsigned int User::GetMaxChans()
1707 return this->MaxChans;
1712 * Sets a user's connection class.
1713 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1714 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1715 * then their ip will be taken as 'priority' anyway, so for example,
1716 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1718 ConnectClass* User::SetClass(const std::string &explicit_name)
1720 ConnectClass *found = NULL;
1722 if (!IS_LOCAL(this))
1725 if (!explicit_name.empty())
1727 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1729 ConnectClass* c = *i;
1731 if (explicit_name == c->GetName() && !c->GetDisabled())
1739 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1741 ConnectClass* c = *i;
1743 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1747 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1756 if (!c->GetDisabled())
1763 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1766 /* deny change if change will take class over the limit */
1767 if (found->limit && (found->RefCount + 1 >= found->limit))
1769 ServerInstance->Log(DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1770 return this->MyClass;
1773 /* should always be valid, but just in case .. */
1776 if (found == this->MyClass) // no point changing this shit :P
1777 return this->MyClass;
1778 this->MyClass->RefCount--;
1779 ServerInstance->Log(DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1782 this->MyClass = found;
1783 this->MyClass->RefCount++;
1784 ServerInstance->Log(DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1787 return this->MyClass;
1790 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1791 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1792 * then their ip will be taken as 'priority' anyway, so for example,
1793 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1795 ConnectClass* User::GetClass()
1797 return this->MyClass;
1800 void User::PurgeEmptyChannels()
1802 std::vector<Channel*> to_delete;
1804 // firstly decrement the count on each channel
1805 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1807 f->first->RemoveAllPrefixes(this);
1808 if (f->first->DelUser(this) == 0)
1810 /* No users left in here, mark it for deletion */
1813 to_delete.push_back(f->first);
1817 ServerInstance->Log(DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1822 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1824 Channel* thischan = *n;
1825 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1826 if (i2 != ServerInstance->chanlist->end())
1828 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1830 ServerInstance->chanlist->erase(i2);
1831 this->chans.erase(*n);
1838 void User::ShowMOTD()
1840 if (!ServerInstance->Config->MOTD.size())
1842 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1845 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1847 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1848 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1850 this->WriteServ("376 %s :End of message of the day.", this->nick);
1853 void User::ShowRULES()
1855 if (!ServerInstance->Config->RULES.size())
1857 this->WriteServ("434 %s :RULES File is missing",this->nick);
1861 this->WriteServ("308 %s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1863 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1864 this->WriteServ("232 %s :- %s",this->nick,i->c_str());
1866 this->WriteServ("309 %s :End of RULES command.",this->nick);
1869 void User::HandleEvent(EventType et, int errornum)
1871 /* WARNING: May delete this user! */
1872 int thisfd = this->GetFd();
1879 ServerInstance->ProcessUser(this);
1882 this->FlushWriteBuf();
1885 /** This should be safe, but dont DARE do anything after it -- Brain */
1886 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1892 ServerInstance->Log(DEBUG,"Exception in User::HandleEvent intercepted");
1895 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1896 if ((ServerInstance->SE->GetRef(thisfd) == this))
1898 if (!WriteError.empty())
1900 User::QuitUser(ServerInstance, this, GetWriteError());
1905 void User::SetOperQuit(const std::string &oquit)
1910 operquit = strdup(oquit.c_str());
1913 const char* User::GetOperQuit()
1915 return operquit ? operquit : "";
1918 void User::IncreasePenalty(int increase)
1920 this->Penalty += increase;
1923 void User::DecreasePenalty(int decrease)
1925 this->Penalty -= decrease;
1936 bool VisData::VisibleTo(User* user)