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 * ---------------------------------------------------
16 #include "socketengine.h"
19 #include "commands/cmd_whowas.h"
21 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
23 /* XXX: Used for speeding up WriteCommon operations */
24 unsigned long uniq_id = 0;
26 std::string User::ProcessNoticeMasks(const char *sm)
28 bool adding = true, oldadding = false;
43 for (unsigned char d = 'A'; d <= 'z'; d++)
45 if (ServerInstance->SNO->IsEnabled(d))
47 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
49 if ((oldadding != adding) || (!output.length()))
50 output += (adding ? '+' : '-');
52 this->SetNoticeMask(d, adding);
61 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
63 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
65 if ((oldadding != adding) || (!output.length()))
66 output += (adding ? '+' : '-');
68 this->SetNoticeMask(*c, adding);
83 void User::StartDNSLookup()
88 const char* ip = this->GetIPString();
90 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
91 if (!strncmp(ip, "0::ffff:", 8))
92 res_reverse = new UserResolver(this->ServerInstance, this, ip + 8, DNS_QUERY_PTR4, cached);
94 res_reverse = new UserResolver(this->ServerInstance, this, ip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
96 this->ServerInstance->AddResolver(res_reverse, cached);
98 catch (CoreException& e)
100 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
104 bool User::IsNoticeMaskSet(unsigned char sm)
106 return (snomasks[sm-65]);
109 void User::SetNoticeMask(unsigned char sm, bool value)
111 snomasks[sm-65] = value;
114 const char* User::FormatNoticeMasks()
116 static char data[MAXBUF];
119 for (int n = 0; n < 64; n++)
122 data[offset++] = n+65;
131 bool User::IsModeSet(unsigned char m)
133 return (modes[m-65]);
136 void User::SetMode(unsigned char m, bool value)
141 const char* User::FormatModes()
143 static char data[MAXBUF];
145 for (int n = 0; n < 64; n++)
148 data[offset++] = n+65;
154 void User::DecrementModes()
156 ServerInstance->Log(DEBUG,"DecrementModes()");
157 for (unsigned char n = 'A'; n <= 'z'; n++)
161 ServerInstance->Log(DEBUG,"DecrementModes() found mode %c", n);
162 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
165 ServerInstance->Log(DEBUG,"Found handler %c and call ChangeCount", n);
172 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
174 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
175 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
176 reset_due = ServerInstance->Time();
177 age = ServerInstance->Time(true);
179 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
180 ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
181 OverPenalty = ExemptFromPenalty = muted = exempt = haspassed = dns_done = false;
186 res_forward = res_reverse = NULL;
191 memset(modes,0,sizeof(modes));
192 memset(snomasks,0,sizeof(snomasks));
193 /* Invalidate cache */
194 operquit = cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
197 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
199 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
201 ServerInstance->Log(DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
203 user_hash::iterator finduuid = Instance->uuidlist->find(uuid);
204 if (finduuid == Instance->uuidlist->end())
205 (*Instance->uuidlist)[uuid] = this;
207 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
210 void User::RemoveCloneCounts()
212 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
213 if (x != ServerInstance->local_clones.end())
218 ServerInstance->local_clones.erase(x);
222 clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
223 if (y != ServerInstance->global_clones.end())
228 ServerInstance->global_clones.erase(y);
235 this->InvalidateCache();
236 this->DecrementModes();
241 this->RemoveCloneCounts();
243 if (this->GetProtocolFamily() == AF_INET)
245 delete (sockaddr_in*)ip;
247 #ifdef SUPPORT_IP6LINKS
250 delete (sockaddr_in6*)ip;
255 ServerInstance->uuidlist->erase(uuid);
258 char* User::MakeHost()
260 if (this->cached_makehost)
261 return this->cached_makehost;
264 /* This is much faster than snprintf */
266 for(char* n = ident; *n; n++)
269 for(char* n = host; *n; n++)
273 this->cached_makehost = strdup(nhost);
275 return this->cached_makehost;
278 char* User::MakeHostIP()
280 if (this->cached_hostip)
281 return this->cached_hostip;
284 /* This is much faster than snprintf */
286 for(char* n = ident; *n; n++)
289 for(const char* n = this->GetIPString(); *n; n++)
293 this->cached_hostip = strdup(ihost);
295 return this->cached_hostip;
298 void User::CloseSocket()
300 ServerInstance->SE->Shutdown(this, 2);
301 ServerInstance->SE->Close(this);
304 char* User::GetFullHost()
306 if (this->cached_fullhost)
307 return this->cached_fullhost;
311 for(char* n = nick; *n; n++)
314 for(char* n = ident; *n; n++)
317 for(char* n = dhost; *n; n++)
321 this->cached_fullhost = strdup(result);
323 return this->cached_fullhost;
326 char* User::MakeWildHost()
328 static char nresult[MAXBUF];
330 *t++ = '*'; *t++ = '!';
331 *t++ = '*'; *t++ = '@';
332 for(char* n = dhost; *n; n++)
338 int User::ReadData(void* buffer, size_t size)
343 return read(this->fd, buffer, size);
345 return recv(this->fd, (char*)buffer, size, 0);
353 char* User::GetFullRealHost()
355 if (this->cached_fullrealhost)
356 return this->cached_fullrealhost;
358 char fresult[MAXBUF];
360 for(char* n = nick; *n; n++)
363 for(char* n = ident; *n; n++)
366 for(char* n = host; *n; n++)
370 this->cached_fullrealhost = strdup(fresult);
372 return this->cached_fullrealhost;
375 bool User::IsInvited(const irc::string &channel)
377 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
387 InvitedList* User::GetInviteList()
392 void User::InviteTo(const irc::string &channel)
394 invites.push_back(channel);
397 void User::RemoveInvite(const irc::string &channel)
399 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
409 bool User::HasPermission(const std::string &command)
416 * users on remote servers can completely bypass all permissions based checks.
417 * This prevents desyncs when one server has different type/class tags to another.
418 * That having been said, this does open things up to the possibility of source changes
419 * allowing remote kills, etc - but if they have access to the src, they most likely have
420 * access to the conf - so it's an end to a means either way.
425 // are they even an oper at all?
431 // check their opertype exists (!). This won't affect local users, of course.
432 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
433 if (iter_opertype == ServerInstance->Config->opertypes.end())
438 /* XXX all this strtok/strdup stuff is a bit ick and horrid -- w00t */
439 char* Classes = strdup(iter_opertype->second);
440 char* myclass = strtok_r(Classes," ",&savept);
443 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
444 if (iter_operclass != ServerInstance->Config->operclass.end())
446 char* CommandList = strdup(iter_operclass->second);
447 mycmd = strtok_r(CommandList," ",&savept2);
450 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
456 mycmd = strtok_r(NULL," ",&savept2);
460 myclass = strtok_r(NULL," ",&savept);
467 /** NOTE: We cannot pass a const reference to this method.
468 * The string is changed by the workings of the method,
469 * so that if we pass const ref, we end up copying it to
470 * something we can change anyway. Makes sense to just let
471 * the compiler do that copy for us.
473 bool User::AddBuffer(std::string a)
477 std::string::size_type i = a.rfind('\r');
479 while (i != std::string::npos)
488 if (recvq.length() > (unsigned)this->recvqmax)
490 this->SetWriteError("RecvQ exceeded");
491 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
500 ServerInstance->Log(DEBUG,"Exception in User::AddBuffer()");
505 bool User::BufferIsReady()
507 return (recvq.find('\n') != std::string::npos);
510 void User::ClearBuffer()
515 std::string User::GetBuffer()
522 /* Strip any leading \r or \n off the string.
523 * Usually there are only one or two of these,
524 * so its is computationally cheap to do.
526 std::string::iterator t = recvq.begin();
527 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
533 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
535 /* Find the first complete line, return it as the
536 * result, and leave the recvq as whats left
540 std::string ret = std::string(recvq.begin(), x);
541 recvq.erase(recvq.begin(), x + 1);
550 ServerInstance->Log(DEBUG,"Exception in User::GetBuffer()");
555 void User::AddWriteBuf(const std::string &data)
557 if (*this->GetWriteError())
560 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
563 * Fix by brain - Set the error text BEFORE calling writeopers, because
564 * if we dont it'll recursively call here over and over again trying
565 * to repeatedly add the text to the sendq!
567 this->SetWriteError("SendQ exceeded");
568 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
574 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
575 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
581 this->SetWriteError("SendQ exceeded");
582 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
586 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
587 void User::FlushWriteBuf()
591 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
595 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
597 int old_sendq_length = sendq.length();
598 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
604 /* The socket buffer is full. This isnt fatal,
607 this->ServerInstance->SE->WantWrite(this);
611 /* Fatal error, set write error and bail
613 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
619 /* advance the queue */
621 this->sendq = this->sendq.substr(n_sent);
622 /* update the user's stats counters */
623 this->bytes_out += n_sent;
625 if (n_sent != old_sendq_length)
626 this->ServerInstance->SE->WantWrite(this);
633 ServerInstance->Log(DEBUG,"Exception in User::FlushWriteBuf()");
636 if (this->sendq.empty())
638 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
642 void User::SetWriteError(const std::string &error)
646 // don't try to set the error twice, its already set take the first string.
647 if (this->WriteError.empty())
648 this->WriteError = error;
653 ServerInstance->Log(DEBUG,"Exception in User::SetWriteError()");
657 const char* User::GetWriteError()
659 return this->WriteError.c_str();
662 void User::Oper(const std::string &opertype)
666 this->modes[UM_OPERATOR] = 1;
667 this->WriteServ("MODE %s :+o", this->nick);
668 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
669 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
670 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
671 ServerInstance->all_opers.push_back(this);
672 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
677 ServerInstance->Log(DEBUG,"Exception in User::Oper()");
687 // unset their oper type (what IS_OPER checks), and remove +o
689 this->modes[UM_OPERATOR] = 0;
691 // remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404
692 ServerInstance->all_opers.remove(this);
698 ServerInstance->Log(DEBUG,"Exception in User::UnOper()");
702 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
704 Instance->Log(DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
705 user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
707 Instance->GlobalCulls.AddItem(user, quitreason.c_str(), operreason);
710 /* adds or updates an entry in the whowas list */
711 void User::AddToWhoWas()
713 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
716 std::deque<classbase*> params;
717 params.push_back(this);
718 whowas_command->HandleInternal(WHOWAS_ADD, params);
722 /* add a client connection to the sockets list */
723 void User::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, int socketfamily, sockaddr* ip)
725 /* NOTE: Calling this one parameter constructor for User automatically
726 * allocates a new UUID and places it in the hash_map.
731 New = new User(Instance);
735 Instance->Log(DEFAULT,"*** WTF *** Duplicated UUID! -- Crack smoking monkies have been unleashed.");
736 Instance->WriteOpers("*** WARNING *** Duplicate UUID allocated!");
740 Instance->Log(DEBUG,"New user fd: %d", socket);
744 Instance->unregistered_count++;
748 if (socketfamily == AF_INET6)
749 inet_ntop(AF_INET6, &((const sockaddr_in6*)ip)->sin6_addr, ipaddr, sizeof(ipaddr));
752 inet_ntop(AF_INET, &((const sockaddr_in*)ip)->sin_addr, ipaddr, sizeof(ipaddr));
754 (*(Instance->clientlist))[New->uuid] = New;
757 /* The users default nick is their UUID */
758 strlcpy(New->nick, New->uuid, NICKMAX - 1);
760 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
761 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
762 strcpy(New->ident, "unknown");
764 New->registered = REG_NONE;
765 New->signon = Instance->Time() + Instance->Config->dns_timeout;
768 New->SetSockAddr(socketfamily, ipaddr, port);
770 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
771 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
772 New->dhost[j] = New->host[j] = *temp;
773 New->dhost[j] = New->host[j] = 0;
775 Instance->AddLocalClone(New);
776 Instance->AddGlobalClone(New);
779 * First class check. We do this again in FullConnect after DNS is done, and NICK/USER is recieved.
780 * See my note down there for why this is required. DO NOT REMOVE. :) -- w00t
782 ConnectClass* i = New->GetClass();
786 User::QuitUser(Instance, New, "Access denied by configuration");
791 * Check connect class settings and initialise settings into User.
792 * This will be done again after DNS resolution. -- w00t
796 Instance->local_users.push_back(New);
798 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
800 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
801 User::QuitUser(Instance, New,"No more connections allowed");
807 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
808 * its a pretty big but for the moment valid assumption:
809 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
810 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
811 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
812 * which for the time being is a physical impossibility (even the largest networks dont have more
813 * than about 10,000 users on ONE server!)
816 if ((unsigned int)socket >= MAX_DESCRIPTORS)
818 User::QuitUser(Instance, New, "Server is full");
823 New->exempt = (Instance->XLines->matches_exception(New) != NULL);
826 ZLine* r = Instance->XLines->matches_zline(ipaddr);
830 if (*Instance->Config->MoronBanner)
831 New->WriteServ("NOTICE %s :*** %s", New->nick, Instance->Config->MoronBanner);
832 snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
833 User::QuitUser(Instance, New, reason);
840 if (!Instance->SE->AddFd(New))
842 Instance->Log(DEBUG,"Internal error on new connection");
843 User::QuitUser(Instance, New, "Internal error handling connection");
847 /* NOTE: even if dns lookups are *off*, we still need to display this.
848 * BOPM and other stuff requires it.
850 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
853 unsigned long User::GlobalCloneCount()
855 clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
856 if (x != ServerInstance->global_clones.end())
862 unsigned long User::LocalCloneCount()
864 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
865 if (x != ServerInstance->local_clones.end())
872 * Check class restrictions
874 void User::CheckClass(const std::string &explicit_class)
876 ConnectClass* a = this->GetClass(explicit_class);
878 if ((!a) || (a->GetType() == CC_DENY))
880 User::QuitUser(ServerInstance, this, "Unauthorised connection");
883 else if ((a->GetMaxLocal()) && (this->LocalCloneCount() > a->GetMaxLocal()))
885 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
886 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
889 else if ((a->GetMaxGlobal()) && (this->GlobalCloneCount() > a->GetMaxGlobal()))
891 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
892 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
896 this->pingmax = a->GetPingTime();
897 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
898 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
899 this->flood = a->GetFlood();
900 this->threshold = a->GetThreshold();
901 this->sendqmax = a->GetSendqMax();
902 this->recvqmax = a->GetRecvqMax();
903 this->MaxChans = a->GetMaxChans();
906 void User::FullConnect()
908 ServerInstance->stats->statsConnects++;
909 this->idle_lastmsg = ServerInstance->Time();
912 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
913 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
914 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
915 * Don't remove this! -- w00t
919 /* Check the password, if one is required by the user's connect class.
920 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
922 if ((!this->GetClass()->GetPass().empty()) && (!this->haspassed))
924 User::QuitUser(ServerInstance, this, "Invalid password");
930 GLine* r = ServerInstance->XLines->matches_gline(this);
936 if (*ServerInstance->Config->MoronBanner)
937 this->WriteServ("NOTICE %s :*** %s", this->nick, ServerInstance->Config->MoronBanner);
938 snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
939 User::QuitUser(ServerInstance, this, reason);
943 KLine* n = ServerInstance->XLines->matches_kline(this);
949 if (*ServerInstance->Config->MoronBanner)
950 this->WriteServ("NOTICE %s :*** %s", this, ServerInstance->Config->MoronBanner);
951 snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
952 User::QuitUser(ServerInstance, this, reason);
957 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
958 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
959 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
960 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
961 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());
963 ServerInstance->Config->Send005(this);
965 this->WriteServ("042 %s %s :your unique ID", this->nick, this->uuid);
971 if (ServerInstance->unregistered_count)
972 ServerInstance->unregistered_count--;
974 /* Trigger LUSERS output, give modules a chance too */
976 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
978 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
981 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
982 * for a user that doesn't exist yet.
984 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
986 this->registered = REG_ALL;
988 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
990 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);
993 /** User::UpdateNick()
994 * re-allocates a nick in the user_hash after they change nicknames,
995 * returns a pointer to the new user as it may have moved
997 User* User::UpdateNickHash(const char* New)
1001 //user_hash::iterator newnick;
1002 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1004 if (!strcasecmp(this->nick,New))
1005 return oldnick->second;
1007 if (oldnick == ServerInstance->clientlist->end())
1008 return NULL; /* doesnt exist */
1010 User* olduser = oldnick->second;
1011 (*(ServerInstance->clientlist))[New] = olduser;
1012 ServerInstance->clientlist->erase(oldnick);
1018 ServerInstance->Log(DEBUG,"Exception in User::UpdateNickHash()");
1023 void User::InvalidateCache()
1025 /* Invalidate cache */
1026 if (cached_fullhost)
1027 free(cached_fullhost);
1029 free(cached_hostip);
1030 if (cached_makehost)
1031 free(cached_makehost);
1032 if (cached_fullrealhost)
1033 free(cached_fullrealhost);
1034 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1037 bool User::ForceNickChange(const char* newnick)
1043 this->InvalidateCache();
1045 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1049 ServerInstance->stats->statsCollisions++;
1053 if (ServerInstance->XLines->matches_qline(newnick))
1055 ServerInstance->stats->statsCollisions++;
1059 if (this->registered == REG_ALL)
1061 std::deque<classbase*> dummy;
1062 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1065 nickhandler->HandleInternal(1, dummy);
1066 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1067 nickhandler->HandleInternal(0, dummy);
1076 ServerInstance->Log(DEBUG,"Exception in User::ForceNickChange()");
1081 void User::SetSockAddr(int protocol_family, const char* ip, int port)
1083 switch (protocol_family)
1085 #ifdef SUPPORT_IP6LINKS
1088 sockaddr_in6* sin = new sockaddr_in6;
1089 sin->sin6_family = AF_INET6;
1090 sin->sin6_port = port;
1091 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1092 this->ip = (sockaddr*)sin;
1098 sockaddr_in* sin = new sockaddr_in;
1099 sin->sin_family = AF_INET;
1100 sin->sin_port = port;
1101 inet_pton(AF_INET, ip, &sin->sin_addr);
1102 this->ip = (sockaddr*)sin;
1106 ServerInstance->Log(DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1113 if (this->ip == NULL)
1116 switch (this->GetProtocolFamily())
1118 #ifdef SUPPORT_IP6LINKS
1121 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1122 return sin->sin6_port;
1128 sockaddr_in* sin = (sockaddr_in*)this->ip;
1129 return sin->sin_port;
1138 int User::GetProtocolFamily()
1140 if (this->ip == NULL)
1143 sockaddr_in* sin = (sockaddr_in*)this->ip;
1144 return sin->sin_family;
1148 * XXX the duplication here is horrid..
1149 * do we really need two methods doing essentially the same thing?
1151 const char* User::GetIPString()
1153 static char buf[1024];
1155 if (this->ip == NULL)
1158 switch (this->GetProtocolFamily())
1160 #ifdef SUPPORT_IP6LINKS
1163 static char temp[1024];
1165 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1166 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1167 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1170 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1180 sockaddr_in* sin = (sockaddr_in*)this->ip;
1181 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1191 /** NOTE: We cannot pass a const reference to this method.
1192 * The string is changed by the workings of the method,
1193 * so that if we pass const ref, we end up copying it to
1194 * something we can change anyway. Makes sense to just let
1195 * the compiler do that copy for us.
1197 void User::Write(std::string text)
1199 if (!ServerInstance->SE->BoundsCheckFd(this))
1204 /* ServerInstance->Log(DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1205 * WARNING: The above debug line is VERY loud, do NOT
1206 * enable it till we have a good way of filtering it
1207 * out of the logs (e.g. 1.2 would be good).
1209 text.append("\r\n");
1213 ServerInstance->Log(DEBUG,"Exception in User::Write() std::string::append");
1217 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1221 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1222 * implement their own buffering mechanisms
1224 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1226 catch (CoreException& modexcept)
1228 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1233 this->AddWriteBuf(text);
1235 ServerInstance->stats->statsSent += text.length();
1236 this->ServerInstance->SE->WantWrite(this);
1241 void User::Write(const char *text, ...)
1244 char textbuffer[MAXBUF];
1246 va_start(argsPtr, text);
1247 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1250 this->Write(std::string(textbuffer));
1253 void User::WriteServ(const std::string& text)
1255 char textbuffer[MAXBUF];
1257 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1258 this->Write(std::string(textbuffer));
1262 * Same as Write(), except `text' is prefixed with `:server.name '.
1264 void User::WriteServ(const char* text, ...)
1267 char textbuffer[MAXBUF];
1269 va_start(argsPtr, text);
1270 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1273 this->WriteServ(std::string(textbuffer));
1277 void User::WriteFrom(User *user, const std::string &text)
1281 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1283 this->Write(std::string(tb));
1287 /* write text from an originating user to originating user */
1289 void User::WriteFrom(User *user, const char* text, ...)
1292 char textbuffer[MAXBUF];
1294 va_start(argsPtr, text);
1295 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1298 this->WriteFrom(user, std::string(textbuffer));
1302 /* write text to an destination user from a source user (e.g. user privmsg) */
1304 void User::WriteTo(User *dest, const char *data, ...)
1306 char textbuffer[MAXBUF];
1309 va_start(argsPtr, data);
1310 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1313 this->WriteTo(dest, std::string(textbuffer));
1316 void User::WriteTo(User *dest, const std::string &data)
1318 dest->WriteFrom(this, data);
1322 void User::WriteCommon(const char* text, ...)
1324 char textbuffer[MAXBUF];
1327 if (this->registered != REG_ALL)
1330 va_start(argsPtr, text);
1331 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1334 this->WriteCommon(std::string(textbuffer));
1337 void User::WriteCommon(const std::string &text)
1341 bool sent_to_at_least_one = false;
1344 if (this->registered != REG_ALL)
1349 /* We dont want to be doing this n times, just once */
1350 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1351 std::string out = tb;
1353 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1355 CUList* ulist = v->first->GetUsers();
1356 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1358 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1360 already_sent[i->first->fd] = uniq_id;
1361 i->first->Write(out);
1362 sent_to_at_least_one = true;
1368 * if the user was not in any channels, no users will receive the text. Make sure the user
1369 * receives their OWN message for WriteCommon
1371 if (!sent_to_at_least_one)
1373 this->Write(std::string(tb));
1379 ServerInstance->Log(DEBUG,"Exception in User::WriteCommon()");
1384 /* write a formatted string to all users who share at least one common
1385 * channel, NOT including the source user e.g. for use in QUIT
1388 void User::WriteCommonExcept(const char* text, ...)
1390 char textbuffer[MAXBUF];
1393 va_start(argsPtr, text);
1394 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1397 this->WriteCommonExcept(std::string(textbuffer));
1400 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1405 if (this->registered != REG_ALL)
1409 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1410 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1411 std::string out1 = tb1;
1412 std::string out2 = tb2;
1414 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1416 CUList *ulist = v->first->GetUsers();
1417 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1419 if (this != i->first)
1421 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1423 already_sent[i->first->fd] = uniq_id;
1424 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1431 void User::WriteCommonExcept(const std::string &text)
1436 if (this->registered != REG_ALL)
1440 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1443 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1445 CUList *ulist = v->first->GetUsers();
1446 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1448 if (this != i->first)
1450 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1452 already_sent[i->first->fd] = uniq_id;
1453 i->first->Write(out1);
1461 void User::WriteWallOps(const std::string &text)
1463 if (!IS_OPER(this) && IS_LOCAL(this))
1466 std::string wallop("WALLOPS :");
1467 wallop.append(text);
1469 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1472 if (t->IsModeSet('w'))
1473 this->WriteTo(t,wallop);
1477 void User::WriteWallOps(const char* text, ...)
1479 char textbuffer[MAXBUF];
1482 va_start(argsPtr, text);
1483 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1486 this->WriteWallOps(std::string(textbuffer));
1489 /* return 0 or 1 depending if users u and u2 share one or more common channels
1490 * (used by QUIT, NICK etc which arent channel specific notices)
1492 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1493 * the first users channels then the second users channels within the outer loop,
1494 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1495 * all possible iterations). However this new function instead checks against the
1496 * channel's userlist in the inner loop which is a std::map<User*,User*>
1497 * and saves us time as we already know what pointer value we are after.
1498 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1499 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1501 bool User::SharesChannelWith(User *other)
1503 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1507 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1509 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1510 * by replacing it with a map::find which *should* be more efficient
1512 if (i->first->HasUser(other))
1518 bool User::ChangeName(const char* gecos)
1520 if (!strcmp(gecos, this->fullname))
1526 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1529 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1531 strlcpy(this->fullname,gecos,MAXGECOS+1);
1536 bool User::ChangeDisplayedHost(const char* host)
1538 if (!strcmp(host, this->dhost))
1544 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1547 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1549 if (this->ServerInstance->Config->CycleHosts)
1550 this->WriteCommonExcept("QUIT :Changing hosts");
1552 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1553 strlcpy(this->dhost,host,64);
1555 this->InvalidateCache();
1557 if (this->ServerInstance->Config->CycleHosts)
1559 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1561 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1562 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1564 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1569 this->WriteServ("396 %s %s :is now your displayed host",this->nick,this->dhost);
1574 bool User::ChangeIdent(const char* newident)
1576 if (!strcmp(newident, this->ident))
1579 if (this->ServerInstance->Config->CycleHosts)
1580 this->WriteCommonExcept("%s","QUIT :Changing ident");
1582 strlcpy(this->ident, newident, IDENTMAX+2);
1584 this->InvalidateCache();
1586 if (this->ServerInstance->Config->CycleHosts)
1588 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1590 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1591 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1593 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1600 void User::SendAll(const char* command, char* text, ...)
1602 char textbuffer[MAXBUF];
1603 char formatbuffer[MAXBUF];
1606 va_start(argsPtr, text);
1607 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1610 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1611 std::string fmt = formatbuffer;
1613 for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1620 std::string User::ChannelList(User* source)
1625 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1627 /* If the target is the same as the sender, let them see all their channels.
1628 * If the channel is NOT private/secret OR the user shares a common channel
1629 * If the user is an oper, and the <options:operspywhois> option is set.
1631 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1633 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1640 ServerInstance->Log(DEBUG,"Exception in User::ChannelList()");
1645 void User::SplitChanList(User* dest, const std::string &cl)
1648 std::ostringstream prefix;
1649 std::string::size_type start, pos, length;
1653 prefix << this->nick << " " << dest->nick << " :";
1654 line = prefix.str();
1655 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1657 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1659 length = (pos == std::string::npos) ? cl.length() : pos;
1661 if (line.length() + namelen + length - start > 510)
1663 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1664 line = prefix.str();
1667 if(pos == std::string::npos)
1669 line.append(cl.substr(start, length - start));
1674 line.append(cl.substr(start, length - start + 1));
1680 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1686 ServerInstance->Log(DEBUG,"Exception in User::SplitChanList()");
1690 unsigned int User::GetMaxChans()
1692 return this->MaxChans;
1695 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1696 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1697 * then their ip will be taken as 'priority' anyway, so for example,
1698 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1700 ConnectClass* User::GetClass(const std::string &explicit_name)
1702 if (!explicit_name.empty())
1704 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1706 if (explicit_name == i->GetName())
1712 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1714 if (((match(this->GetIPString(),i->GetHost().c_str(),true)) || (match(this->host,i->GetHost().c_str()))))
1718 if (this->GetPort() == i->GetPort())
1731 void User::PurgeEmptyChannels()
1733 std::vector<Channel*> to_delete;
1735 // firstly decrement the count on each channel
1736 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1738 f->first->RemoveAllPrefixes(this);
1739 if (f->first->DelUser(this) == 0)
1741 /* No users left in here, mark it for deletion */
1744 to_delete.push_back(f->first);
1748 ServerInstance->Log(DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1753 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1755 Channel* thischan = *n;
1756 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1757 if (i2 != ServerInstance->chanlist->end())
1759 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1761 ServerInstance->chanlist->erase(i2);
1762 this->chans.erase(*n);
1769 void User::ShowMOTD()
1771 if (!ServerInstance->Config->MOTD.size())
1773 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1776 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1778 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1779 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1781 this->WriteServ("376 %s :End of message of the day.", this->nick);
1784 void User::ShowRULES()
1786 if (!ServerInstance->Config->RULES.size())
1788 this->WriteServ("434 %s :RULES File is missing",this->nick);
1792 this->WriteServ("308 %s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1794 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1795 this->WriteServ("232 %s :- %s",this->nick,i->c_str());
1797 this->WriteServ("309 %s :End of RULES command.",this->nick);
1800 void User::HandleEvent(EventType et, int errornum)
1802 /* WARNING: May delete this user! */
1803 int thisfd = this->GetFd();
1810 ServerInstance->ProcessUser(this);
1813 this->FlushWriteBuf();
1816 /** This should be safe, but dont DARE do anything after it -- Brain */
1817 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1823 ServerInstance->Log(DEBUG,"Exception in User::HandleEvent intercepted");
1826 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1827 if ((ServerInstance->SE->GetRef(thisfd) == this))
1829 if (!WriteError.empty())
1831 User::QuitUser(ServerInstance, this, GetWriteError());
1836 void User::SetOperQuit(const std::string &oquit)
1841 operquit = strdup(oquit.c_str());
1844 const char* User::GetOperQuit()
1846 return operquit ? operquit : "";
1849 void User::IncreasePenalty(int increase)
1851 this->Penalty += increase;
1854 void User::DecreasePenalty(int decrease)
1856 this->Penalty -= decrease;
1867 bool VisData::VisibleTo(User* user)