1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $Core: libIRCDusers */
18 #include "socketengine.h"
22 #include "commands/cmd_whowas.h"
24 /* XXX: Used for speeding up WriteCommon operations */
25 unsigned long uniq_id = 1;
27 static unsigned long* already_sent = NULL;
30 void InitializeAlreadySent(SocketEngine* SE)
32 already_sent = new unsigned long[SE->GetMaxFds()];
33 memset(already_sent, 0, SE->GetMaxFds() * sizeof(long));
34 printf("\n\nInit Already Sent, uniq id = %lu\n\n", uniq_id);
38 std::string User::ProcessNoticeMasks(const char *sm)
40 bool adding = true, oldadding = false;
55 for (unsigned char d = 'A'; d <= 'z'; d++)
57 if (ServerInstance->SNO->IsEnabled(d))
59 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
61 if ((oldadding != adding) || (!output.length()))
62 output += (adding ? '+' : '-');
64 this->SetNoticeMask(d, adding);
73 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
75 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
77 if ((oldadding != adding) || (!output.length()))
78 output += (adding ? '+' : '-');
80 this->SetNoticeMask(*c, adding);
86 this->WriteNumeric(501, "%s %c :is unknown snomask char to me", this->nick, *c);
98 void User::StartDNSLookup()
103 const char* sip = this->GetIPString(false);
105 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
106 if (!strncmp(sip, "0::ffff:", 8))
107 res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
109 res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
111 this->ServerInstance->AddResolver(res_reverse, cached);
113 catch (CoreException& e)
115 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
119 bool User::IsNoticeMaskSet(unsigned char sm)
121 return (snomasks[sm-65]);
124 void User::SetNoticeMask(unsigned char sm, bool value)
126 snomasks[sm-65] = value;
129 const char* User::FormatNoticeMasks()
131 static char data[MAXBUF];
134 for (int n = 0; n < 64; n++)
137 data[offset++] = n+65;
146 bool User::IsModeSet(unsigned char m)
148 return (modes[m-65]);
151 void User::SetMode(unsigned char m, bool value)
156 const char* User::FormatModes()
158 static char data[MAXBUF];
160 for (int n = 0; n < 64; n++)
163 data[offset++] = n+65;
169 void User::DecrementModes()
171 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
172 for (unsigned char n = 'A'; n <= 'z'; n++)
176 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
177 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
180 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
187 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
189 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
190 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
191 reset_due = ServerInstance->Time();
192 age = ServerInstance->Time();
194 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
195 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
196 quietquit = OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
201 res_forward = res_reverse = NULL;
206 AllowedUserModes = NULL;
207 AllowedChanModes = NULL;
208 AllowedOperCommands = NULL;
211 memset(modes,0,sizeof(modes));
212 memset(snomasks,0,sizeof(snomasks));
213 /* Invalidate cache */
214 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
217 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
219 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
221 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
223 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
224 if (finduuid == Instance->Users->uuidlist->end())
225 (*Instance->Users->uuidlist)[uuid] = this;
227 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
232 /* NULL for remote users :) */
235 this->MyClass->RefCount--;
236 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %lu", this->MyClass->RefCount);
238 if (this->AllowedOperCommands)
240 delete AllowedOperCommands;
241 AllowedOperCommands = NULL;
244 if (this->AllowedUserModes)
246 delete[] AllowedUserModes;
247 AllowedUserModes = NULL;
250 if (this->AllowedChanModes)
252 delete[] AllowedChanModes;
253 AllowedChanModes = NULL;
256 this->InvalidateCache();
257 this->DecrementModes();
261 ServerInstance->Users->RemoveCloneCounts(this);
263 if (this->GetProtocolFamily() == AF_INET)
265 delete (sockaddr_in*)ip;
267 #ifdef SUPPORT_IP6LINKS
270 delete (sockaddr_in6*)ip;
275 ServerInstance->Users->uuidlist->erase(uuid);
278 char* User::MakeHost()
280 if (this->cached_makehost)
281 return this->cached_makehost;
284 /* This is much faster than snprintf */
286 for(char* n = ident; *n; n++)
289 for(char* n = host; *n; n++)
293 this->cached_makehost = strdup(nhost);
295 return this->cached_makehost;
298 char* User::MakeHostIP()
300 if (this->cached_hostip)
301 return this->cached_hostip;
304 /* This is much faster than snprintf */
306 for(char* n = ident; *n; n++)
309 for(const char* n = this->GetIPString(); *n; n++)
313 this->cached_hostip = strdup(ihost);
315 return this->cached_hostip;
318 void User::CloseSocket()
322 ServerInstance->SE->Shutdown(this, 2);
323 ServerInstance->SE->Close(this);
327 char* User::GetFullHost()
329 if (this->cached_fullhost)
330 return this->cached_fullhost;
334 for(char* n = nick; *n; n++)
337 for(char* n = ident; *n; n++)
340 for(char* n = dhost; *n; n++)
344 this->cached_fullhost = strdup(result);
346 return this->cached_fullhost;
349 char* User::MakeWildHost()
351 static char nresult[MAXBUF];
353 *t++ = '*'; *t++ = '!';
354 *t++ = '*'; *t++ = '@';
355 for(char* n = dhost; *n; n++)
361 int User::ReadData(void* buffer, size_t size)
366 return read(this->fd, buffer, size);
368 return recv(this->fd, (char*)buffer, size, 0);
376 char* User::GetFullRealHost()
378 if (this->cached_fullrealhost)
379 return this->cached_fullrealhost;
381 char fresult[MAXBUF];
383 for(char* n = nick; *n; n++)
386 for(char* n = ident; *n; n++)
389 for(char* n = host; *n; n++)
393 this->cached_fullrealhost = strdup(fresult);
395 return this->cached_fullrealhost;
398 bool User::IsInvited(const irc::string &channel)
400 time_t now = time(NULL);
401 InvitedList::iterator safei;
402 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
404 if (channel == i->first)
406 if (i->second != 0 && now > i->second)
408 /* Expired invite, remove it. */
411 invites.erase(safei);
420 InvitedList* User::GetInviteList()
422 time_t now = time(NULL);
423 /* Weed out expired invites here. */
424 InvitedList::iterator safei;
425 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
427 if (i->second != 0 && now > i->second)
429 /* Expired invite, remove it. */
432 invites.erase(safei);
438 void User::InviteTo(const irc::string &channel, time_t invtimeout)
440 time_t now = time(NULL);
441 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
442 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
444 if (channel == i->first)
446 if (i->second != 0 && invtimeout > i->second)
448 i->second = invtimeout;
452 invites.push_back(std::make_pair(channel, invtimeout));
455 void User::RemoveInvite(const irc::string &channel)
457 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
459 if (channel == i->first)
467 bool User::HasModePermission(unsigned char mode, ModeType type)
475 if (!AllowedUserModes || !AllowedChanModes)
478 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
482 bool User::HasPermission(const std::string &command)
485 * users on remote servers can completely bypass all permissions based checks.
486 * This prevents desyncs when one server has different type/class tags to another.
487 * That having been said, this does open things up to the possibility of source changes
488 * allowing remote kills, etc - but if they have access to the src, they most likely have
489 * access to the conf - so it's an end to a means either way.
494 // are they even an oper at all?
500 if (!AllowedOperCommands)
503 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
505 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
511 /** NOTE: We cannot pass a const reference to this method.
512 * The string is changed by the workings of the method,
513 * so that if we pass const ref, we end up copying it to
514 * something we can change anyway. Makes sense to just let
515 * the compiler do that copy for us.
517 bool User::AddBuffer(std::string a)
521 std::string::size_type i = a.rfind('\r');
523 while (i != std::string::npos)
532 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
534 this->SetWriteError("RecvQ exceeded");
535 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)recvq.length(),this->MyClass->GetRecvqMax());
544 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::AddBuffer()");
549 bool User::BufferIsReady()
551 return (recvq.find('\n') != std::string::npos);
554 void User::ClearBuffer()
559 std::string User::GetBuffer()
566 /* Strip any leading \r or \n off the string.
567 * Usually there are only one or two of these,
568 * so its is computationally cheap to do.
570 std::string::iterator t = recvq.begin();
571 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
577 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
579 /* Find the first complete line, return it as the
580 * result, and leave the recvq as whats left
584 std::string ret = std::string(recvq.begin(), x);
585 recvq.erase(recvq.begin(), x + 1);
594 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
599 void User::AddWriteBuf(const std::string &data)
601 if (*this->GetWriteError())
604 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
607 * Fix by brain - Set the error text BEFORE calling, because
608 * if we dont it'll recursively call here over and over again trying
609 * to repeatedly add the text to the sendq!
611 this->SetWriteError("SendQ exceeded");
612 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)sendq.length() + data.length(),this->MyClass->GetSendqMax());
616 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
617 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
622 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
623 void User::FlushWriteBuf()
625 printf("\nFlush buffer on %d\n", this->GetFd());
629 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
631 printf("Write error set, clear sendq: %s\n", this->GetWriteError());
634 printf("2 sendq len = %u fd = %d\n", sendq.length(), this->fd);
635 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
638 int old_sendq_length = sendq.length();
639 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
641 printf("\nWrote %d\n", n_sent);
647 /* The socket buffer is full. This isnt fatal,
650 this->ServerInstance->SE->WantWrite(this);
654 /* Fatal error, set write error and bail
656 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
657 printf("\nError on %d\n", this->GetFd());
663 /* advance the queue */
665 this->sendq = this->sendq.substr(n_sent);
666 /* update the user's stats counters */
667 this->bytes_out += n_sent;
669 if (n_sent != old_sendq_length)
670 this->ServerInstance->SE->WantWrite(this);
677 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
680 printf("end flush\n");
682 if (this->sendq.empty())
684 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
688 void User::SetWriteError(const std::string &error)
690 printf("SET WRITE ERROR: %s\n", error.c_str());
691 // don't try to set the error twice, its already set take the first string.
692 if (this->WriteError.empty())
693 this->WriteError = error;
696 const char* User::GetWriteError()
698 return this->WriteError.c_str();
701 void User::Oper(const std::string &opertype, const std::string &opername)
709 this->modes[UM_OPERATOR] = 1;
710 this->WriteServ("MODE %s :+o", this->nick);
711 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
712 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
713 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
714 ServerInstance->Users->all_opers.push_back(this);
716 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
717 if (iter_opertype != ServerInstance->Config->opertypes.end())
720 if (AllowedOperCommands)
721 AllowedOperCommands->clear();
723 AllowedOperCommands = new std::map<std::string, bool>;
725 if (!AllowedChanModes)
726 AllowedChanModes = new bool[64];
728 if (!AllowedUserModes)
729 AllowedUserModes = new bool[64];
731 memset(AllowedUserModes, 0, 64);
732 memset(AllowedChanModes, 0, 64);
734 char* Classes = strdup(iter_opertype->second);
735 char* myclass = strtok_r(Classes," ",&savept);
738 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
739 if (iter_operclass != ServerInstance->Config->operclass.end())
741 char* CommandList = strdup(iter_operclass->second.commandlist);
742 mycmd = strtok_r(CommandList," ",&savept2);
745 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
746 mycmd = strtok_r(NULL," ",&savept2);
749 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
750 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
754 memset(this->AllowedUserModes, (int)(true), 64);
758 this->AllowedUserModes[*c - 'A'] = true;
761 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
765 memset(this->AllowedChanModes, (int)(true), 64);
769 this->AllowedChanModes[*c - 'A'] = true;
773 myclass = strtok_r(NULL," ",&savept);
778 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
783 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
791 /* Remove all oper only modes from the user when the deoper - Bug #466*/
792 std::string moderemove("-");
794 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
798 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
799 if (mh && mh->NeedsOper())
800 moderemove += letter;
804 const char* parameters[] = { this->nick, moderemove.c_str() };
805 ServerInstance->Parser->CallHandler("MODE", parameters, 2, this);
807 /* unset their oper type (what IS_OPER checks), and remove +o */
809 this->modes[UM_OPERATOR] = 0;
811 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
812 ServerInstance->Users->all_opers.remove(this);
814 if (AllowedOperCommands)
816 delete AllowedOperCommands;
817 AllowedOperCommands = NULL;
819 if (AllowedUserModes)
821 delete[] AllowedUserModes;
822 AllowedUserModes = NULL;
824 if (AllowedChanModes)
826 delete[] AllowedChanModes;
827 AllowedChanModes = NULL;
833 /* adds or updates an entry in the whowas list */
834 void User::AddToWhoWas()
836 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
839 std::deque<classbase*> params;
840 params.push_back(this);
841 whowas_command->HandleInternal(WHOWAS_ADD, params);
846 * Check class restrictions
848 void User::CheckClass()
850 ConnectClass* a = this->MyClass;
852 if ((!a) || (a->GetType() == CC_DENY))
854 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
857 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
859 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
860 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
863 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
865 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
866 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
870 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
871 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
872 this->MaxChans = a->GetMaxChans();
875 void User::CheckLines()
877 const char* check[] = { "G" , "K", NULL };
881 for (int n = 0; check[n]; ++n)
883 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
894 void User::FullConnect()
896 ServerInstance->stats->statsConnects++;
897 this->idle_lastmsg = ServerInstance->Time();
900 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
901 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
902 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
903 * Don't remove this! -- w00t
907 /* Check the password, if one is required by the user's connect class.
908 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
910 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
912 ServerInstance->Users->QuitUser(this, "Invalid password");
918 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
919 this->WriteNumeric(001, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
920 this->WriteNumeric(002, "%s :Your host is %s, running version InspIRCd-1.2",this->nick,ServerInstance->Config->ServerName);
921 this->WriteNumeric(003, "%s :This server was created %s %s", this->nick, __TIME__, __DATE__);
922 this->WriteNumeric(004, "%s %s InspIRCd-1.2 %s %s %s", this->nick, ServerInstance->Config->ServerName, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
924 ServerInstance->Config->Send005(this);
925 this->WriteNumeric(42, "%s %s :your unique ID", this->nick, this->uuid);
931 if (ServerInstance->Users->unregistered_count)
932 ServerInstance->Users->unregistered_count--;
934 /* Trigger LUSERS output, give modules a chance too */
936 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
938 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
941 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
942 * for a user that doesn't exist yet.
944 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
946 this->registered = REG_ALL;
948 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
950 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString(), this->fullname);
951 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
952 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
955 /** User::UpdateNick()
956 * re-allocates a nick in the user_hash after they change nicknames,
957 * returns a pointer to the new user as it may have moved
959 User* User::UpdateNickHash(const char* New)
961 //user_hash::iterator newnick;
962 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
964 if (!strcasecmp(this->nick,New))
965 return oldnick->second;
967 if (oldnick == ServerInstance->Users->clientlist->end())
968 return NULL; /* doesnt exist */
970 User* olduser = oldnick->second;
971 (*(ServerInstance->Users->clientlist))[New] = olduser;
972 ServerInstance->Users->clientlist->erase(oldnick);
976 void User::InvalidateCache()
978 /* Invalidate cache */
980 free(cached_fullhost);
984 free(cached_makehost);
985 if (cached_fullrealhost)
986 free(cached_fullrealhost);
987 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
990 bool User::ForceNickChange(const char* newnick)
994 this->InvalidateCache();
996 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1000 ServerInstance->stats->statsCollisions++;
1004 std::deque<classbase*> dummy;
1005 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1006 if (nickhandler) // wtfbbq, when would this not be here
1008 nickhandler->HandleInternal(1, dummy);
1009 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1010 nickhandler->HandleInternal(0, dummy);
1014 // Unreachable, we hope
1018 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1020 this->cachedip = "";
1022 switch (protocol_family)
1024 #ifdef SUPPORT_IP6LINKS
1027 sockaddr_in6* sin = new sockaddr_in6;
1028 sin->sin6_family = AF_INET6;
1029 sin->sin6_port = port;
1030 inet_pton(AF_INET6, sip, &sin->sin6_addr);
1031 this->ip = (sockaddr*)sin;
1037 sockaddr_in* sin = new sockaddr_in;
1038 sin->sin_family = AF_INET;
1039 sin->sin_port = port;
1040 inet_pton(AF_INET, sip, &sin->sin_addr);
1041 this->ip = (sockaddr*)sin;
1045 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1052 if (this->ip == NULL)
1055 switch (this->GetProtocolFamily())
1057 #ifdef SUPPORT_IP6LINKS
1060 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1061 return sin->sin6_port;
1067 sockaddr_in* sin = (sockaddr_in*)this->ip;
1068 return sin->sin_port;
1077 int User::GetProtocolFamily()
1079 if (this->ip == NULL)
1082 sockaddr_in* sin = (sockaddr_in*)this->ip;
1083 return sin->sin_family;
1087 * XXX the duplication here is horrid..
1088 * do we really need two methods doing essentially the same thing?
1090 const char* User::GetIPString(bool translate4in6)
1092 static char buf[1024];
1094 if (this->ip == NULL)
1097 if (!this->cachedip.empty())
1098 return this->cachedip.c_str();
1100 switch (this->GetProtocolFamily())
1102 #ifdef SUPPORT_IP6LINKS
1105 static char temp[1024];
1107 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1108 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1109 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1112 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1114 if (translate4in6 && !strncmp(temp, "0::ffff:", 8))
1116 this->cachedip = temp + 8;
1120 this->cachedip = temp;
1124 this->cachedip = buf;
1131 sockaddr_in* sin = (sockaddr_in*)this->ip;
1132 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1133 this->cachedip = buf;
1141 // Unreachable, probably
1145 /** NOTE: We cannot pass a const reference to this method.
1146 * The string is changed by the workings of the method,
1147 * so that if we pass const ref, we end up copying it to
1148 * something we can change anyway. Makes sense to just let
1149 * the compiler do that copy for us.
1151 void User::Write(std::string text)
1153 printf("Write Error is %s\n", *(GetWriteError()) ? "set" : "unset");
1154 if (!ServerInstance->SE->BoundsCheckFd(this))
1159 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1160 text.append("\r\n");
1164 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1170 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1171 * implement their own buffering mechanisms
1175 this->io->OnRawSocketWrite(this->fd, text.data(), text.length());
1177 catch (CoreException& modexcept)
1179 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1184 this->AddWriteBuf(text);
1186 ServerInstance->stats->statsSent += text.length();
1187 this->ServerInstance->SE->WantWrite(this);
1192 void User::Write(const char *text, ...)
1195 char textbuffer[MAXBUF];
1197 va_start(argsPtr, text);
1198 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1201 this->Write(std::string(textbuffer));
1204 void User::WriteServ(const std::string& text)
1206 char textbuffer[MAXBUF];
1208 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1209 this->Write(std::string(textbuffer));
1213 * Same as Write(), except `text' is prefixed with `:server.name '.
1215 void User::WriteServ(const char* text, ...)
1218 char textbuffer[MAXBUF];
1220 va_start(argsPtr, text);
1221 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1224 this->WriteServ(std::string(textbuffer));
1228 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1231 char textbuffer[MAXBUF];
1233 va_start(argsPtr, text);
1234 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1237 this->WriteNumeric(numeric, std::string(textbuffer));
1240 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1242 char textbuffer[MAXBUF];
1245 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1250 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1251 this->Write(std::string(textbuffer));
1254 void User::WriteFrom(User *user, const std::string &text)
1258 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1260 this->Write(std::string(tb));
1264 /* write text from an originating user to originating user */
1266 void User::WriteFrom(User *user, const char* text, ...)
1269 char textbuffer[MAXBUF];
1271 va_start(argsPtr, text);
1272 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1275 this->WriteFrom(user, std::string(textbuffer));
1279 /* write text to an destination user from a source user (e.g. user privmsg) */
1281 void User::WriteTo(User *dest, const char *data, ...)
1283 char textbuffer[MAXBUF];
1286 va_start(argsPtr, data);
1287 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1290 this->WriteTo(dest, std::string(textbuffer));
1293 void User::WriteTo(User *dest, const std::string &data)
1295 dest->WriteFrom(this, data);
1299 void User::WriteCommon(const char* text, ...)
1301 char textbuffer[MAXBUF];
1304 if (this->registered != REG_ALL)
1307 va_start(argsPtr, text);
1308 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1311 this->WriteCommon(std::string(textbuffer));
1314 void User::WriteCommon(const std::string &text)
1316 bool sent_to_at_least_one = false;
1319 if (this->registered != REG_ALL)
1325 InitializeAlreadySent(ServerInstance->SE);
1327 /* We dont want to be doing this n times, just once */
1328 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1329 std::string out = tb;
1331 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1333 CUList* ulist = v->first->GetUsers();
1334 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1336 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1338 already_sent[i->first->fd] = uniq_id;
1339 i->first->Write(out);
1340 sent_to_at_least_one = true;
1346 * if the user was not in any channels, no users will receive the text. Make sure the user
1347 * receives their OWN message for WriteCommon
1349 if (!sent_to_at_least_one)
1351 this->Write(std::string(tb));
1356 /* write a formatted string to all users who share at least one common
1357 * channel, NOT including the source user e.g. for use in QUIT
1360 void User::WriteCommonExcept(const char* text, ...)
1362 char textbuffer[MAXBUF];
1365 va_start(argsPtr, text);
1366 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1369 this->WriteCommonExcept(std::string(textbuffer));
1372 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1377 if (this->registered != REG_ALL)
1383 InitializeAlreadySent(ServerInstance->SE);
1385 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1386 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1387 std::string out1 = tb1;
1388 std::string out2 = tb2;
1390 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1392 CUList *ulist = v->first->GetUsers();
1393 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1395 if (this != i->first)
1397 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1399 already_sent[i->first->fd] = uniq_id;
1400 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1407 void User::WriteCommonExcept(const std::string &text)
1412 if (this->registered != REG_ALL)
1418 InitializeAlreadySent(ServerInstance->SE);
1420 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1423 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1425 CUList *ulist = v->first->GetUsers();
1426 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1428 if (this != i->first)
1430 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1432 already_sent[i->first->fd] = uniq_id;
1433 i->first->Write(out1);
1441 void User::WriteWallOps(const std::string &text)
1443 if (!IS_LOCAL(this))
1446 std::string wallop("WALLOPS :");
1447 wallop.append(text);
1449 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1452 if (t->IsModeSet('w'))
1453 this->WriteTo(t,wallop);
1457 void User::WriteWallOps(const char* text, ...)
1459 if (!IS_LOCAL(this))
1462 char textbuffer[MAXBUF];
1465 va_start(argsPtr, text);
1466 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1469 this->WriteWallOps(std::string(textbuffer));
1472 /* return 0 or 1 depending if users u and u2 share one or more common channels
1473 * (used by QUIT, NICK etc which arent channel specific notices)
1475 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1476 * the first users channels then the second users channels within the outer loop,
1477 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1478 * all possible iterations). However this new function instead checks against the
1479 * channel's userlist in the inner loop which is a std::map<User*,User*>
1480 * and saves us time as we already know what pointer value we are after.
1481 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1482 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1484 bool User::SharesChannelWith(User *other)
1486 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1490 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1492 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1493 * by replacing it with a map::find which *should* be more efficient
1495 if (i->first->HasUser(other))
1501 bool User::ChangeName(const char* gecos)
1503 if (!strcmp(gecos, this->fullname))
1509 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1512 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1514 strlcpy(this->fullname,gecos,MAXGECOS+1);
1519 bool User::ChangeDisplayedHost(const char* shost)
1521 if (!strcmp(shost, this->dhost))
1527 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1530 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1533 if (this->ServerInstance->Config->CycleHosts)
1534 this->WriteCommonExcept("QUIT :Changing hosts");
1536 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1537 strlcpy(this->dhost,shost,64);
1539 this->InvalidateCache();
1541 if (this->ServerInstance->Config->CycleHosts)
1543 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1545 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1546 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1548 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1553 this->WriteNumeric(396, "%s %s :is now your displayed host",this->nick,this->dhost);
1558 bool User::ChangeIdent(const char* newident)
1560 if (!strcmp(newident, this->ident))
1563 if (this->ServerInstance->Config->CycleHosts)
1564 this->WriteCommonExcept("%s","QUIT :Changing ident");
1566 strlcpy(this->ident, newident, IDENTMAX+1);
1568 this->InvalidateCache();
1570 if (this->ServerInstance->Config->CycleHosts)
1572 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1574 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1575 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1577 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1584 void User::SendAll(const char* command, const char* text, ...)
1586 char textbuffer[MAXBUF];
1587 char formatbuffer[MAXBUF];
1590 va_start(argsPtr, text);
1591 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1594 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1595 std::string fmt = formatbuffer;
1597 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1604 std::string User::ChannelList(User* source)
1608 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1610 /* If the target is the same as the sender, let them see all their channels.
1611 * If the channel is NOT private/secret OR the user shares a common channel
1612 * If the user is an oper, and the <options:operspywhois> option is set.
1614 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1616 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1623 void User::SplitChanList(User* dest, const std::string &cl)
1626 std::ostringstream prefix;
1627 std::string::size_type start, pos, length;
1629 prefix << this->nick << " " << dest->nick << " :";
1630 line = prefix.str();
1631 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1633 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1635 length = (pos == std::string::npos) ? cl.length() : pos;
1637 if (line.length() + namelen + length - start > 510)
1639 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1640 line = prefix.str();
1643 if(pos == std::string::npos)
1645 line.append(cl.substr(start, length - start));
1650 line.append(cl.substr(start, length - start + 1));
1656 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1660 unsigned int User::GetMaxChans()
1662 return this->MaxChans;
1667 * Sets a user's connection class.
1668 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1669 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1670 * then their ip will be taken as 'priority' anyway, so for example,
1671 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1673 ConnectClass* User::SetClass(const std::string &explicit_name)
1675 ConnectClass *found = NULL;
1677 if (!IS_LOCAL(this))
1680 if (!explicit_name.empty())
1682 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1684 ConnectClass* c = *i;
1686 if (explicit_name == c->GetName() && !c->GetDisabled())
1694 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1696 ConnectClass* c = *i;
1698 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1702 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1711 if (!c->GetDisabled())
1718 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1721 /* deny change if change will take class over the limit */
1722 if (found->limit && (found->RefCount + 1 >= found->limit))
1724 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", found->limit);
1725 return this->MyClass;
1728 /* should always be valid, but just in case .. */
1731 if (found == this->MyClass) // no point changing this shit :P
1732 return this->MyClass;
1733 this->MyClass->RefCount--;
1734 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %lu", this->MyClass->RefCount);
1737 this->MyClass = found;
1738 this->MyClass->RefCount++;
1739 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %lu", this->MyClass->RefCount);
1742 return this->MyClass;
1745 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1746 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1747 * then their ip will be taken as 'priority' anyway, so for example,
1748 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1750 ConnectClass* User::GetClass()
1752 return this->MyClass;
1755 void User::PurgeEmptyChannels()
1757 std::vector<Channel*> to_delete;
1759 // firstly decrement the count on each channel
1760 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1762 f->first->RemoveAllPrefixes(this);
1763 if (f->first->DelUser(this) == 0)
1765 /* No users left in here, mark it for deletion */
1768 to_delete.push_back(f->first);
1772 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1777 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1779 Channel* thischan = *n;
1780 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1781 if (i2 != ServerInstance->chanlist->end())
1783 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1785 ServerInstance->chanlist->erase(i2);
1786 this->chans.erase(*n);
1793 void User::ShowMOTD()
1795 if (!ServerInstance->Config->MOTD.size())
1797 this->WriteNumeric(422, "%s :Message of the day file is missing.",this->nick);
1800 this->WriteNumeric(375, "%s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1802 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1803 this->WriteNumeric(372, "%s :- %s",this->nick,i->c_str());
1805 this->WriteNumeric(376, "%s :End of message of the day.", this->nick);
1808 void User::ShowRULES()
1810 if (!ServerInstance->Config->RULES.size())
1812 this->WriteNumeric(434, "%s :RULES File is missing",this->nick);
1816 this->WriteNumeric(308, "%s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1818 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1819 this->WriteNumeric(232, "%s :- %s",this->nick,i->c_str());
1821 this->WriteNumeric(309, "%s :End of RULES command.",this->nick);
1824 void User::HandleEvent(EventType et, int errornum)
1826 if (this->quitting) // drop everything, user is due to be quit
1829 /* WARNING: May delete this user! */
1830 int thisfd = this->GetFd();
1837 ServerInstance->ProcessUser(this);
1840 this->FlushWriteBuf();
1843 /** This should be safe, but dont DARE do anything after it -- Brain */
1844 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1850 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1853 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1854 if ((ServerInstance->SE->GetRef(thisfd) == this))
1856 if (!WriteError.empty())
1858 ServerInstance->Users->QuitUser(this, GetWriteError());
1863 void User::SetOperQuit(const std::string &oquit)
1865 operquitmsg = oquit;
1868 const char* User::GetOperQuit()
1870 return operquitmsg.c_str();
1873 void User::IncreasePenalty(int increase)
1875 this->Penalty += increase;
1878 void User::DecreasePenalty(int decrease)
1880 this->Penalty -= decrease;
1891 bool VisData::VisibleTo(User* user)