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"
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);
86 void User::StartDNSLookup()
91 const char* ip = this->GetIPString();
93 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
94 if (!strncmp(ip, "0::ffff:", 8))
95 res_reverse = new UserResolver(this->ServerInstance, this, ip + 8, DNS_QUERY_PTR4, cached);
97 res_reverse = new UserResolver(this->ServerInstance, this, ip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
99 this->ServerInstance->AddResolver(res_reverse, cached);
101 catch (CoreException& e)
103 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
107 bool User::IsNoticeMaskSet(unsigned char sm)
109 return (snomasks[sm-65]);
112 void User::SetNoticeMask(unsigned char sm, bool value)
114 snomasks[sm-65] = value;
117 const char* User::FormatNoticeMasks()
119 static char data[MAXBUF];
122 for (int n = 0; n < 64; n++)
125 data[offset++] = n+65;
134 bool User::IsModeSet(unsigned char m)
136 return (modes[m-65]);
139 void User::SetMode(unsigned char m, bool value)
144 const char* User::FormatModes()
146 static char data[MAXBUF];
148 for (int n = 0; n < 64; n++)
151 data[offset++] = n+65;
157 void User::DecrementModes()
159 ServerInstance->Log(DEBUG,"DecrementModes()");
160 for (unsigned char n = 'A'; n <= 'z'; n++)
164 ServerInstance->Log(DEBUG,"DecrementModes() found mode %c", n);
165 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
168 ServerInstance->Log(DEBUG,"Found handler %c and call ChangeCount", n);
175 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
177 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
178 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
179 reset_due = ServerInstance->Time();
180 age = ServerInstance->Time(true);
182 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
183 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
184 OverPenalty = ExemptFromPenalty = muted = exempt = haspassed = dns_done = false;
189 res_forward = res_reverse = NULL;
195 memset(modes,0,sizeof(modes));
196 memset(snomasks,0,sizeof(snomasks));
197 /* Invalidate cache */
198 operquit = cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
201 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
203 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
205 ServerInstance->Log(DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
207 user_hash::iterator finduuid = Instance->uuidlist->find(uuid);
208 if (finduuid == Instance->uuidlist->end())
209 (*Instance->uuidlist)[uuid] = this;
211 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
214 void User::RemoveCloneCounts()
216 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
217 if (x != ServerInstance->local_clones.end())
222 ServerInstance->local_clones.erase(x);
226 clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
227 if (y != ServerInstance->global_clones.end())
232 ServerInstance->global_clones.erase(y);
239 /* NULL for remote users :) */
242 this->MyClass->RefCount--;
243 ServerInstance->Log(DEBUG, "User destructor -- connect refcount now: %u", this->MyClass->RefCount);
246 this->InvalidateCache();
247 this->DecrementModes();
252 this->RemoveCloneCounts();
254 if (this->GetProtocolFamily() == AF_INET)
256 delete (sockaddr_in*)ip;
258 #ifdef SUPPORT_IP6LINKS
261 delete (sockaddr_in6*)ip;
266 ServerInstance->uuidlist->erase(uuid);
269 char* User::MakeHost()
271 if (this->cached_makehost)
272 return this->cached_makehost;
275 /* This is much faster than snprintf */
277 for(char* n = ident; *n; n++)
280 for(char* n = host; *n; n++)
284 this->cached_makehost = strdup(nhost);
286 return this->cached_makehost;
289 char* User::MakeHostIP()
291 if (this->cached_hostip)
292 return this->cached_hostip;
295 /* This is much faster than snprintf */
297 for(char* n = ident; *n; n++)
300 for(const char* n = this->GetIPString(); *n; n++)
304 this->cached_hostip = strdup(ihost);
306 return this->cached_hostip;
309 void User::CloseSocket()
311 ServerInstance->SE->Shutdown(this, 2);
312 ServerInstance->SE->Close(this);
315 char* User::GetFullHost()
317 if (this->cached_fullhost)
318 return this->cached_fullhost;
322 for(char* n = nick; *n; n++)
325 for(char* n = ident; *n; n++)
328 for(char* n = dhost; *n; n++)
332 this->cached_fullhost = strdup(result);
334 return this->cached_fullhost;
337 char* User::MakeWildHost()
339 static char nresult[MAXBUF];
341 *t++ = '*'; *t++ = '!';
342 *t++ = '*'; *t++ = '@';
343 for(char* n = dhost; *n; n++)
349 int User::ReadData(void* buffer, size_t size)
354 return read(this->fd, buffer, size);
356 return recv(this->fd, (char*)buffer, size, 0);
364 char* User::GetFullRealHost()
366 if (this->cached_fullrealhost)
367 return this->cached_fullrealhost;
369 char fresult[MAXBUF];
371 for(char* n = nick; *n; n++)
374 for(char* n = ident; *n; n++)
377 for(char* n = host; *n; n++)
381 this->cached_fullrealhost = strdup(fresult);
383 return this->cached_fullrealhost;
386 bool User::IsInvited(const irc::string &channel)
388 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
398 InvitedList* User::GetInviteList()
403 void User::InviteTo(const irc::string &channel)
405 invites.push_back(channel);
408 void User::RemoveInvite(const irc::string &channel)
410 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
420 bool User::HasPermission(const std::string &command)
427 * users on remote servers can completely bypass all permissions based checks.
428 * This prevents desyncs when one server has different type/class tags to another.
429 * That having been said, this does open things up to the possibility of source changes
430 * allowing remote kills, etc - but if they have access to the src, they most likely have
431 * access to the conf - so it's an end to a means either way.
436 // are they even an oper at all?
442 // check their opertype exists (!). This won't affect local users, of course.
443 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
444 if (iter_opertype == ServerInstance->Config->opertypes.end())
449 /* XXX all this strtok/strdup stuff is a bit ick and horrid -- w00t */
450 char* Classes = strdup(iter_opertype->second);
451 char* myclass = strtok_r(Classes," ",&savept);
454 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
455 if (iter_operclass != ServerInstance->Config->operclass.end())
457 char* CommandList = strdup(iter_operclass->second);
458 mycmd = strtok_r(CommandList," ",&savept2);
461 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
467 mycmd = strtok_r(NULL," ",&savept2);
471 myclass = strtok_r(NULL," ",&savept);
478 /** NOTE: We cannot pass a const reference to this method.
479 * The string is changed by the workings of the method,
480 * so that if we pass const ref, we end up copying it to
481 * something we can change anyway. Makes sense to just let
482 * the compiler do that copy for us.
484 bool User::AddBuffer(std::string a)
488 std::string::size_type i = a.rfind('\r');
490 while (i != std::string::npos)
499 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
501 this->SetWriteError("RecvQ exceeded");
502 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
511 ServerInstance->Log(DEBUG,"Exception in User::AddBuffer()");
516 bool User::BufferIsReady()
518 return (recvq.find('\n') != std::string::npos);
521 void User::ClearBuffer()
526 std::string User::GetBuffer()
533 /* Strip any leading \r or \n off the string.
534 * Usually there are only one or two of these,
535 * so its is computationally cheap to do.
537 std::string::iterator t = recvq.begin();
538 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
544 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
546 /* Find the first complete line, return it as the
547 * result, and leave the recvq as whats left
551 std::string ret = std::string(recvq.begin(), x);
552 recvq.erase(recvq.begin(), x + 1);
561 ServerInstance->Log(DEBUG,"Exception in User::GetBuffer()");
566 void User::AddWriteBuf(const std::string &data)
568 if (*this->GetWriteError())
571 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
574 * Fix by brain - Set the error text BEFORE calling writeopers, because
575 * if we dont it'll recursively call here over and over again trying
576 * to repeatedly add the text to the sendq!
578 this->SetWriteError("SendQ exceeded");
579 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
585 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
586 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
592 this->SetWriteError("SendQ exceeded");
593 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
597 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
598 void User::FlushWriteBuf()
602 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
606 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
608 int old_sendq_length = sendq.length();
609 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
615 /* The socket buffer is full. This isnt fatal,
618 this->ServerInstance->SE->WantWrite(this);
622 /* Fatal error, set write error and bail
624 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
630 /* advance the queue */
632 this->sendq = this->sendq.substr(n_sent);
633 /* update the user's stats counters */
634 this->bytes_out += n_sent;
636 if (n_sent != old_sendq_length)
637 this->ServerInstance->SE->WantWrite(this);
644 ServerInstance->Log(DEBUG,"Exception in User::FlushWriteBuf()");
647 if (this->sendq.empty())
649 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
653 void User::SetWriteError(const std::string &error)
657 // don't try to set the error twice, its already set take the first string.
658 if (this->WriteError.empty())
659 this->WriteError = error;
664 ServerInstance->Log(DEBUG,"Exception in User::SetWriteError()");
668 const char* User::GetWriteError()
670 return this->WriteError.c_str();
673 void User::Oper(const std::string &opertype)
677 this->modes[UM_OPERATOR] = 1;
678 this->WriteServ("MODE %s :+o", this->nick);
679 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
680 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
681 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
682 ServerInstance->all_opers.push_back(this);
683 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
688 ServerInstance->Log(DEBUG,"Exception in User::Oper()");
698 // unset their oper type (what IS_OPER checks), and remove +o
700 this->modes[UM_OPERATOR] = 0;
702 // remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404
703 ServerInstance->all_opers.remove(this);
709 ServerInstance->Log(DEBUG,"Exception in User::UnOper()");
713 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
715 Instance->Log(DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
716 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
718 Instance->GlobalCulls.AddItem(user, quitreason.c_str(), operreason);
721 /* adds or updates an entry in the whowas list */
722 void User::AddToWhoWas()
724 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
727 std::deque<classbase*> params;
728 params.push_back(this);
729 whowas_command->HandleInternal(WHOWAS_ADD, params);
733 /* add a client connection to the sockets list */
734 void User::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, int socketfamily, sockaddr* ip)
736 /* NOTE: Calling this one parameter constructor for User automatically
737 * allocates a new UUID and places it in the hash_map.
742 New = new User(Instance);
746 Instance->Log(DEFAULT,"*** WTF *** Duplicated UUID! -- Crack smoking monkies have been unleashed.");
747 Instance->WriteOpers("*** WARNING *** Duplicate UUID allocated!");
751 Instance->Log(DEBUG,"New user fd: %d", socket);
755 Instance->unregistered_count++;
759 if (socketfamily == AF_INET6)
760 inet_ntop(AF_INET6, &((const sockaddr_in6*)ip)->sin6_addr, ipaddr, sizeof(ipaddr));
763 inet_ntop(AF_INET, &((const sockaddr_in*)ip)->sin_addr, ipaddr, sizeof(ipaddr));
765 (*(Instance->clientlist))[New->uuid] = New;
768 /* The users default nick is their UUID */
769 strlcpy(New->nick, New->uuid, NICKMAX - 1);
771 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
772 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
773 strcpy(New->ident, "unknown");
775 New->registered = REG_NONE;
776 New->signon = Instance->Time() + Instance->Config->dns_timeout;
779 New->SetSockAddr(socketfamily, ipaddr, port);
781 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
782 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
783 New->dhost[j] = New->host[j] = *temp;
784 New->dhost[j] = New->host[j] = 0;
786 Instance->AddLocalClone(New);
787 Instance->AddGlobalClone(New);
790 * First class check. We do this again in FullConnect after DNS is done, and NICK/USER is recieved.
791 * See my note down there for why this is required. DO NOT REMOVE. :) -- w00t
793 ConnectClass* i = New->SetClass();
797 User::QuitUser(Instance, New, "Access denied by configuration");
802 * Check connect class settings and initialise settings into User.
803 * This will be done again after DNS resolution. -- w00t
807 Instance->local_users.push_back(New);
809 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
811 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
812 User::QuitUser(Instance, New,"No more connections allowed");
818 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
819 * its a pretty big but for the moment valid assumption:
820 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
821 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
822 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
823 * which for the time being is a physical impossibility (even the largest networks dont have more
824 * than about 10,000 users on ONE server!)
827 if ((unsigned int)socket >= MAX_DESCRIPTORS)
829 User::QuitUser(Instance, New, "Server is full");
834 * even with bancache, we still have to keep User::exempt current.
835 * besides that, if we get a positive bancache hit, we still won't fuck
836 * them over if they are exempt. -- w00t
838 New->exempt = (Instance->XLines->MatchesLine("E",New) != NULL);
840 if (BanCacheHit *b = Instance->BanCache->GetHit(New->GetIPString()))
842 if (!b->Type.empty() && !New->exempt)
845 Instance->Log(DEBUG, std::string("BanCache: Positive hit for ") + New->GetIPString());
846 if (*Instance->Config->MoronBanner)
847 New->WriteServ("NOTICE %s :*** %s", New->nick, Instance->Config->MoronBanner);
848 User::QuitUser(Instance, New, b->Reason);
853 Instance->Log(DEBUG, std::string("BanCache: Negative hit for ") + New->GetIPString());
860 XLine* r = Instance->XLines->MatchesLine("Z",New);
872 if (!Instance->SE->AddFd(New))
874 Instance->Log(DEBUG,"Internal error on new connection");
875 User::QuitUser(Instance, New, "Internal error handling connection");
879 /* NOTE: even if dns lookups are *off*, we still need to display this.
880 * BOPM and other stuff requires it.
882 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
884 if (Instance->Config->NoUserDns)
886 New->dns_done = true;
890 New->StartDNSLookup();
894 unsigned long User::GlobalCloneCount()
896 clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
897 if (x != ServerInstance->global_clones.end())
903 unsigned long User::LocalCloneCount()
905 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
906 if (x != ServerInstance->local_clones.end())
913 * Check class restrictions
915 void User::CheckClass()
917 ConnectClass* a = this->MyClass;
919 if ((!a) || (a->GetType() == CC_DENY))
921 User::QuitUser(ServerInstance, this, "Unauthorised connection");
924 else if ((a->GetMaxLocal()) && (this->LocalCloneCount() > a->GetMaxLocal()))
926 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
927 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
930 else if ((a->GetMaxGlobal()) && (this->GlobalCloneCount() > a->GetMaxGlobal()))
932 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
933 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
937 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
938 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
939 this->MaxChans = a->GetMaxChans();
942 void User::FullConnect()
944 ServerInstance->stats->statsConnects++;
945 this->idle_lastmsg = ServerInstance->Time();
948 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
949 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
950 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
951 * Don't remove this! -- w00t
955 /* Check the password, if one is required by the user's connect class.
956 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
958 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
960 User::QuitUser(ServerInstance, this, "Invalid password");
966 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
975 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
985 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
986 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
987 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
988 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
989 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());
991 ServerInstance->Config->Send005(this);
993 this->WriteServ("042 %s %s :your unique ID", this->nick, this->uuid);
999 if (ServerInstance->unregistered_count)
1000 ServerInstance->unregistered_count--;
1002 /* Trigger LUSERS output, give modules a chance too */
1004 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
1006 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
1009 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
1010 * for a user that doesn't exist yet.
1012 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1014 this->registered = REG_ALL;
1016 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1018 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);
1021 /** User::UpdateNick()
1022 * re-allocates a nick in the user_hash after they change nicknames,
1023 * returns a pointer to the new user as it may have moved
1025 User* User::UpdateNickHash(const char* New)
1029 //user_hash::iterator newnick;
1030 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1032 if (!strcasecmp(this->nick,New))
1033 return oldnick->second;
1035 if (oldnick == ServerInstance->clientlist->end())
1036 return NULL; /* doesnt exist */
1038 User* olduser = oldnick->second;
1039 (*(ServerInstance->clientlist))[New] = olduser;
1040 ServerInstance->clientlist->erase(oldnick);
1046 ServerInstance->Log(DEBUG,"Exception in User::UpdateNickHash()");
1051 void User::InvalidateCache()
1053 /* Invalidate cache */
1054 if (cached_fullhost)
1055 free(cached_fullhost);
1057 free(cached_hostip);
1058 if (cached_makehost)
1059 free(cached_makehost);
1060 if (cached_fullrealhost)
1061 free(cached_fullrealhost);
1062 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1065 bool User::ForceNickChange(const char* newnick)
1071 this->InvalidateCache();
1073 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1077 ServerInstance->stats->statsCollisions++;
1081 if (ServerInstance->XLines->MatchesLine("Q",newnick))
1083 ServerInstance->stats->statsCollisions++;
1087 if (this->registered == REG_ALL)
1089 std::deque<classbase*> dummy;
1090 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1093 nickhandler->HandleInternal(1, dummy);
1094 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1095 nickhandler->HandleInternal(0, dummy);
1104 ServerInstance->Log(DEBUG,"Exception in User::ForceNickChange()");
1109 void User::SetSockAddr(int protocol_family, const char* ip, int port)
1111 switch (protocol_family)
1113 #ifdef SUPPORT_IP6LINKS
1116 sockaddr_in6* sin = new sockaddr_in6;
1117 sin->sin6_family = AF_INET6;
1118 sin->sin6_port = port;
1119 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1120 this->ip = (sockaddr*)sin;
1126 sockaddr_in* sin = new sockaddr_in;
1127 sin->sin_family = AF_INET;
1128 sin->sin_port = port;
1129 inet_pton(AF_INET, ip, &sin->sin_addr);
1130 this->ip = (sockaddr*)sin;
1134 ServerInstance->Log(DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1141 if (this->ip == NULL)
1144 switch (this->GetProtocolFamily())
1146 #ifdef SUPPORT_IP6LINKS
1149 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1150 return sin->sin6_port;
1156 sockaddr_in* sin = (sockaddr_in*)this->ip;
1157 return sin->sin_port;
1166 int User::GetProtocolFamily()
1168 if (this->ip == NULL)
1171 sockaddr_in* sin = (sockaddr_in*)this->ip;
1172 return sin->sin_family;
1176 * XXX the duplication here is horrid..
1177 * do we really need two methods doing essentially the same thing?
1179 const char* User::GetIPString()
1181 static char buf[1024];
1183 if (this->ip == NULL)
1186 switch (this->GetProtocolFamily())
1188 #ifdef SUPPORT_IP6LINKS
1191 static char temp[1024];
1193 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1194 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1195 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1198 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1208 sockaddr_in* sin = (sockaddr_in*)this->ip;
1209 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1219 /** NOTE: We cannot pass a const reference to this method.
1220 * The string is changed by the workings of the method,
1221 * so that if we pass const ref, we end up copying it to
1222 * something we can change anyway. Makes sense to just let
1223 * the compiler do that copy for us.
1225 void User::Write(std::string text)
1227 if (!ServerInstance->SE->BoundsCheckFd(this))
1232 /* ServerInstance->Log(DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1233 * WARNING: The above debug line is VERY loud, do NOT
1234 * enable it till we have a good way of filtering it
1235 * out of the logs (e.g. 1.2 would be good).
1237 text.append("\r\n");
1241 ServerInstance->Log(DEBUG,"Exception in User::Write() std::string::append");
1245 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1249 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1250 * implement their own buffering mechanisms
1252 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1254 catch (CoreException& modexcept)
1256 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1261 this->AddWriteBuf(text);
1263 ServerInstance->stats->statsSent += text.length();
1264 this->ServerInstance->SE->WantWrite(this);
1269 void User::Write(const char *text, ...)
1272 char textbuffer[MAXBUF];
1274 va_start(argsPtr, text);
1275 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1278 this->Write(std::string(textbuffer));
1281 void User::WriteServ(const std::string& text)
1283 char textbuffer[MAXBUF];
1285 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1286 this->Write(std::string(textbuffer));
1290 * Same as Write(), except `text' is prefixed with `:server.name '.
1292 void User::WriteServ(const char* text, ...)
1295 char textbuffer[MAXBUF];
1297 va_start(argsPtr, text);
1298 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1301 this->WriteServ(std::string(textbuffer));
1305 void User::WriteFrom(User *user, const std::string &text)
1309 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1311 this->Write(std::string(tb));
1315 /* write text from an originating user to originating user */
1317 void User::WriteFrom(User *user, const char* text, ...)
1320 char textbuffer[MAXBUF];
1322 va_start(argsPtr, text);
1323 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1326 this->WriteFrom(user, std::string(textbuffer));
1330 /* write text to an destination user from a source user (e.g. user privmsg) */
1332 void User::WriteTo(User *dest, const char *data, ...)
1334 char textbuffer[MAXBUF];
1337 va_start(argsPtr, data);
1338 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1341 this->WriteTo(dest, std::string(textbuffer));
1344 void User::WriteTo(User *dest, const std::string &data)
1346 dest->WriteFrom(this, data);
1350 void User::WriteCommon(const char* text, ...)
1352 char textbuffer[MAXBUF];
1355 if (this->registered != REG_ALL)
1358 va_start(argsPtr, text);
1359 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1362 this->WriteCommon(std::string(textbuffer));
1365 void User::WriteCommon(const std::string &text)
1369 bool sent_to_at_least_one = false;
1372 if (this->registered != REG_ALL)
1377 /* We dont want to be doing this n times, just once */
1378 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1379 std::string out = tb;
1381 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1383 CUList* ulist = v->first->GetUsers();
1384 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1386 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1388 already_sent[i->first->fd] = uniq_id;
1389 i->first->Write(out);
1390 sent_to_at_least_one = true;
1396 * if the user was not in any channels, no users will receive the text. Make sure the user
1397 * receives their OWN message for WriteCommon
1399 if (!sent_to_at_least_one)
1401 this->Write(std::string(tb));
1407 ServerInstance->Log(DEBUG,"Exception in User::WriteCommon()");
1412 /* write a formatted string to all users who share at least one common
1413 * channel, NOT including the source user e.g. for use in QUIT
1416 void User::WriteCommonExcept(const char* text, ...)
1418 char textbuffer[MAXBUF];
1421 va_start(argsPtr, text);
1422 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1425 this->WriteCommonExcept(std::string(textbuffer));
1428 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1433 if (this->registered != REG_ALL)
1437 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1438 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1439 std::string out1 = tb1;
1440 std::string out2 = tb2;
1442 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1444 CUList *ulist = v->first->GetUsers();
1445 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1447 if (this != i->first)
1449 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1451 already_sent[i->first->fd] = uniq_id;
1452 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1459 void User::WriteCommonExcept(const std::string &text)
1464 if (this->registered != REG_ALL)
1468 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1471 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1473 CUList *ulist = v->first->GetUsers();
1474 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1476 if (this != i->first)
1478 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1480 already_sent[i->first->fd] = uniq_id;
1481 i->first->Write(out1);
1489 void User::WriteWallOps(const std::string &text)
1491 if (!IS_OPER(this) && IS_LOCAL(this))
1494 std::string wallop("WALLOPS :");
1495 wallop.append(text);
1497 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1500 if (t->IsModeSet('w'))
1501 this->WriteTo(t,wallop);
1505 void User::WriteWallOps(const char* text, ...)
1507 char textbuffer[MAXBUF];
1510 va_start(argsPtr, text);
1511 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1514 this->WriteWallOps(std::string(textbuffer));
1517 /* return 0 or 1 depending if users u and u2 share one or more common channels
1518 * (used by QUIT, NICK etc which arent channel specific notices)
1520 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1521 * the first users channels then the second users channels within the outer loop,
1522 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1523 * all possible iterations). However this new function instead checks against the
1524 * channel's userlist in the inner loop which is a std::map<User*,User*>
1525 * and saves us time as we already know what pointer value we are after.
1526 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1527 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1529 bool User::SharesChannelWith(User *other)
1531 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1535 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1537 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1538 * by replacing it with a map::find which *should* be more efficient
1540 if (i->first->HasUser(other))
1546 bool User::ChangeName(const char* gecos)
1548 if (!strcmp(gecos, this->fullname))
1554 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1557 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1559 strlcpy(this->fullname,gecos,MAXGECOS+1);
1564 bool User::ChangeDisplayedHost(const char* host)
1566 if (!strcmp(host, this->dhost))
1572 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1575 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1577 if (this->ServerInstance->Config->CycleHosts)
1578 this->WriteCommonExcept("QUIT :Changing hosts");
1580 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1581 strlcpy(this->dhost,host,64);
1583 this->InvalidateCache();
1585 if (this->ServerInstance->Config->CycleHosts)
1587 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1589 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1590 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1592 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1597 this->WriteServ("396 %s %s :is now your displayed host",this->nick,this->dhost);
1602 bool User::ChangeIdent(const char* newident)
1604 if (!strcmp(newident, this->ident))
1607 if (this->ServerInstance->Config->CycleHosts)
1608 this->WriteCommonExcept("%s","QUIT :Changing ident");
1610 strlcpy(this->ident, newident, IDENTMAX+2);
1612 this->InvalidateCache();
1614 if (this->ServerInstance->Config->CycleHosts)
1616 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1618 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1619 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1621 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1628 void User::SendAll(const char* command, char* text, ...)
1630 char textbuffer[MAXBUF];
1631 char formatbuffer[MAXBUF];
1634 va_start(argsPtr, text);
1635 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1638 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1639 std::string fmt = formatbuffer;
1641 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1648 std::string User::ChannelList(User* source)
1653 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1655 /* If the target is the same as the sender, let them see all their channels.
1656 * If the channel is NOT private/secret OR the user shares a common channel
1657 * If the user is an oper, and the <options:operspywhois> option is set.
1659 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1661 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1668 ServerInstance->Log(DEBUG,"Exception in User::ChannelList()");
1673 void User::SplitChanList(User* dest, const std::string &cl)
1676 std::ostringstream prefix;
1677 std::string::size_type start, pos, length;
1681 prefix << this->nick << " " << dest->nick << " :";
1682 line = prefix.str();
1683 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1685 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1687 length = (pos == std::string::npos) ? cl.length() : pos;
1689 if (line.length() + namelen + length - start > 510)
1691 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1692 line = prefix.str();
1695 if(pos == std::string::npos)
1697 line.append(cl.substr(start, length - start));
1702 line.append(cl.substr(start, length - start + 1));
1708 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1714 ServerInstance->Log(DEBUG,"Exception in User::SplitChanList()");
1718 unsigned int User::GetMaxChans()
1720 return this->MaxChans;
1725 * Sets a user's connection class.
1726 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1727 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1728 * then their ip will be taken as 'priority' anyway, so for example,
1729 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1731 ConnectClass* User::SetClass(const std::string &explicit_name)
1733 ConnectClass *found = NULL;
1735 if (!IS_LOCAL(this))
1738 if (!explicit_name.empty())
1740 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1742 ConnectClass* c = *i;
1744 if (explicit_name == c->GetName() && !c->GetDisabled())
1752 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1754 ConnectClass* c = *i;
1756 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1760 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1769 if (!c->GetDisabled())
1776 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1779 /* deny change if change will take class over the limit */
1780 if (found->limit && (found->RefCount + 1 >= found->limit))
1782 ServerInstance->Log(DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1783 return this->MyClass;
1786 /* should always be valid, but just in case .. */
1789 if (found == this->MyClass) // no point changing this shit :P
1790 return this->MyClass;
1791 this->MyClass->RefCount--;
1792 ServerInstance->Log(DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1795 this->MyClass = found;
1796 this->MyClass->RefCount++;
1797 ServerInstance->Log(DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1800 return this->MyClass;
1803 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1804 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1805 * then their ip will be taken as 'priority' anyway, so for example,
1806 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1808 ConnectClass* User::GetClass()
1810 return this->MyClass;
1813 void User::PurgeEmptyChannels()
1815 std::vector<Channel*> to_delete;
1817 // firstly decrement the count on each channel
1818 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1820 f->first->RemoveAllPrefixes(this);
1821 if (f->first->DelUser(this) == 0)
1823 /* No users left in here, mark it for deletion */
1826 to_delete.push_back(f->first);
1830 ServerInstance->Log(DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1835 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1837 Channel* thischan = *n;
1838 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1839 if (i2 != ServerInstance->chanlist->end())
1841 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1843 ServerInstance->chanlist->erase(i2);
1844 this->chans.erase(*n);
1851 void User::ShowMOTD()
1853 if (!ServerInstance->Config->MOTD.size())
1855 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1858 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1860 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1861 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1863 this->WriteServ("376 %s :End of message of the day.", this->nick);
1866 void User::ShowRULES()
1868 if (!ServerInstance->Config->RULES.size())
1870 this->WriteServ("434 %s :RULES File is missing",this->nick);
1874 this->WriteServ("308 %s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1876 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1877 this->WriteServ("232 %s :- %s",this->nick,i->c_str());
1879 this->WriteServ("309 %s :End of RULES command.",this->nick);
1882 void User::HandleEvent(EventType et, int errornum)
1884 /* WARNING: May delete this user! */
1885 int thisfd = this->GetFd();
1892 ServerInstance->ProcessUser(this);
1895 this->FlushWriteBuf();
1898 /** This should be safe, but dont DARE do anything after it -- Brain */
1899 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1905 ServerInstance->Log(DEBUG,"Exception in User::HandleEvent intercepted");
1908 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1909 if ((ServerInstance->SE->GetRef(thisfd) == this))
1911 if (!WriteError.empty())
1913 User::QuitUser(ServerInstance, this, GetWriteError());
1918 void User::SetOperQuit(const std::string &oquit)
1923 operquit = strdup(oquit.c_str());
1926 const char* User::GetOperQuit()
1928 return operquit ? operquit : "";
1931 void User::IncreasePenalty(int increase)
1933 this->Penalty += increase;
1936 void User::DecreasePenalty(int decrease)
1938 this->Penalty -= decrease;
1949 bool VisData::VisibleTo(User* user)