1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 #include "inspircd_config.h"
18 #include "configreader.h"
20 #include "connection.h"
24 #include "inspstring.h"
26 #include "helperfuncs.h"
28 #include "socketengine.h"
33 #include "cull_list.h"
35 extern std::vector<Module*> modules;
36 extern std::vector<ircd_module*> factory;
39 extern Server* MyServer;
41 irc::whowas::whowas_users whowas;
42 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
43 std::vector<userrec*> all_opers;
45 typedef std::map<irc::string,char*> opertype_t;
46 typedef opertype_t operclass_t;
49 operclass_t operclass;
51 /* XXX: Used for speeding up WriteCommon operations */
52 unsigned long uniq_id = 0;
54 bool InitTypes(ServerConfig* conf, const char* tag)
56 for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
66 bool InitClasses(ServerConfig* conf, const char* tag)
68 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
78 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
80 char* TypeName = (char*)values[0];
81 char* Classes = (char*)values[1];
83 opertypes[TypeName] = strdup(Classes);
84 log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
88 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
90 char* ClassName = (char*)values[0];
91 char* CommandList = (char*)values[1];
93 operclass[ClassName] = strdup(CommandList);
94 log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
98 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
103 bool userrec::ProcessNoticeMasks(const char *sm)
119 if ((*c >= 'A') && (*c <= 'z'))
120 this->SetNoticeMask(*c, adding);
130 void userrec::StartDNSLookup()
132 log(DEBUG,"Commencing reverse lookup");
135 log(DEBUG,"Passing instance: %08x",this->ServerInstance);
136 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
137 MyServer->AddResolver(res_reverse);
139 catch (ModuleException& e)
141 log(DEBUG,"Error in resolver: %s",e.GetReason());
145 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
146 Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
149 this->bound_fd = user->fd;
152 void UserResolver::OnLookupComplete(const std::string &result)
154 if ((!this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
156 log(DEBUG,"Commencing forward lookup");
157 this->bound_user->stored_host = result;
160 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
161 MyServer->AddResolver(bound_user->res_forward);
163 catch (ModuleException& e)
165 log(DEBUG,"Error in resolver: %s",e.GetReason());
168 else if ((this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
170 /* Both lookups completed */
171 if (this->bound_user->GetIPString() == result)
173 std::string hostname = this->bound_user->stored_host;
174 if (hostname.length() < 65)
176 /* Hostnames starting with : are not a good thing (tm) */
177 if (*(hostname.c_str()) == ':')
178 hostname = "0" + hostname;
180 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
181 this->bound_user->dns_done = true;
182 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
183 strlcpy(this->bound_user->host, hostname.c_str(),64);
187 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname is longer than the maximum of 64 characters, using your IP address (%s) instead.", this->bound_user->GetIPString());
192 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname does not match up with your IP address. Sorry, using your IP address (%s) instead.", this->bound_user->GetIPString());
197 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
199 if (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user)
201 /* Error message here */
202 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
203 this->bound_user->dns_done = true;
208 bool userrec::IsNoticeMaskSet(unsigned char sm)
210 return (snomasks[sm-65]);
213 void userrec::SetNoticeMask(unsigned char sm, bool value)
215 snomasks[sm-65] = value;
218 const char* userrec::FormatNoticeMasks()
220 static char data[MAXBUF];
223 for (int n = 0; n < 64; n++)
226 data[offset++] = n+65;
235 bool userrec::IsModeSet(unsigned char m)
237 return (modes[m-65]);
240 void userrec::SetMode(unsigned char m, bool value)
245 const char* userrec::FormatModes()
247 static char data[MAXBUF];
249 for (int n = 0; n < 64; n++)
252 data[offset++] = n+65;
258 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
260 log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
261 // the PROPER way to do it, AVOID bzero at *ALL* costs
262 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
263 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
265 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
266 timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
267 haspassed = dns_done = false;
271 res_forward = res_reverse = NULL;
275 chans.resize(MAXCHANS);
276 memset(modes,0,sizeof(modes));
278 for (unsigned int n = 0; n < MAXCHANS; n++)
280 ucrec* x = new ucrec();
289 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
291 ucrec* x = (ucrec*)*n;
297 if (this->GetProtocolFamily() == AF_INET)
299 delete (sockaddr_in*)ip;
301 #ifdef SUPPORT_IP6LINKS
304 delete (sockaddr_in6*)ip;
310 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
311 void userrec::MakeHost(char* nhost)
313 /* This is much faster than snprintf */
315 for(char* n = ident; *n; n++)
318 for(char* n = host; *n; n++)
323 void userrec::CloseSocket()
325 shutdown(this->fd,2);
329 char* userrec::GetFullHost()
331 static char result[MAXBUF];
333 for(char* n = nick; *n; n++)
336 for(char* n = ident; *n; n++)
339 for(char* n = dhost; *n; n++)
345 char* userrec::MakeWildHost()
347 static char nresult[MAXBUF];
349 *t++ = '*'; *t++ = '!';
350 *t++ = '*'; *t++ = '@';
351 for(char* n = dhost; *n; n++)
357 int userrec::ReadData(void* buffer, size_t size)
361 return read(this->fd, buffer, size);
368 char* userrec::GetFullRealHost()
370 static char fresult[MAXBUF];
372 for(char* n = nick; *n; n++)
375 for(char* n = ident; *n; n++)
378 for(char* n = host; *n; n++)
384 bool userrec::IsInvited(irc::string &channel)
386 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
388 irc::string compare = i->channel;
390 if (compare == channel)
398 InvitedList* userrec::GetInviteList()
403 void userrec::InviteTo(irc::string &channel)
407 invites.push_back(i);
410 void userrec::RemoveInvite(irc::string &channel)
412 log(DEBUG,"Removing invites");
416 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
418 irc::string compare = i->channel;
420 if (compare == channel)
429 bool userrec::HasPermission(const std::string &command)
436 * users on remote servers can completely bypass all permissions based checks.
437 * This prevents desyncs when one server has different type/class tags to another.
438 * That having been said, this does open things up to the possibility of source changes
439 * allowing remote kills, etc - but if they have access to the src, they most likely have
440 * access to the conf - so it's an end to a means either way.
445 // are they even an oper at all?
448 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
449 if (iter_opertype != opertypes.end())
451 char* Classes = strdup(iter_opertype->second);
452 char* myclass = strtok_r(Classes," ",&savept);
455 operclass_t::iterator iter_operclass = operclass.find(myclass);
456 if (iter_operclass != operclass.end())
458 char* CommandList = strdup(iter_operclass->second);
459 mycmd = strtok_r(CommandList," ",&savept2);
462 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
468 mycmd = strtok_r(NULL," ",&savept2);
472 myclass = strtok_r(NULL," ",&savept);
481 bool userrec::AddBuffer(const std::string &a)
485 /* NB: std::string is arsey about \r and \n and tries to translate them
486 * somehow, so we CANNOT use std::string::find() here :(
488 for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
497 if (recvq.length() > (unsigned)this->recvqmax)
499 this->SetWriteError("RecvQ exceeded");
500 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
507 bool userrec::BufferIsReady()
509 return (recvq.find('\n') != std::string::npos);
512 void userrec::ClearBuffer()
517 std::string userrec::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 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
527 recvq.erase(recvq.begin());
529 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
531 /* Find the first complete line, return it as the
532 * result, and leave the recvq as whats left
536 std::string ret = std::string(recvq.begin(), x);
537 recvq.erase(recvq.begin(), x + 1);
544 void userrec::AddWriteBuf(const std::string &data)
546 if (*this->GetWriteError())
549 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
552 * Fix by brain - Set the error text BEFORE calling writeopers, because
553 * if we dont it'll recursively call here over and over again trying
554 * to repeatedly add the text to the sendq!
556 this->SetWriteError("SendQ exceeded");
557 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
561 if (data.length() > 512)
563 std::string newdata(data);
565 newdata.append("\r\n");
566 sendq.append(newdata);
574 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
575 void userrec::FlushWriteBuf()
577 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
579 const char* tb = this->sendq.c_str();
580 int n_sent = write(this->fd,tb,this->sendq.length());
584 this->SetWriteError(strerror(errno));
591 // update the user's stats counters
592 this->bytes_out += n_sent;
598 void userrec::SetWriteError(const std::string &error)
600 log(DEBUG,"SetWriteError: %s",error.c_str());
601 // don't try to set the error twice, its already set take the first string.
602 if (!this->WriteError.length())
604 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
605 this->WriteError = error;
609 const char* userrec::GetWriteError()
611 return this->WriteError.c_str();
614 void userrec::Oper(const std::string &opertype)
616 this->modes[UM_OPERATOR] = 1;
617 this->WriteServ("MODE %s :+o", this->nick);
618 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
619 log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
620 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
621 all_opers.push_back(this);
622 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
625 void userrec::UnOper()
630 this->modes[UM_OPERATOR] = 0;
631 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
635 log(DEBUG,"Oper removed from optimization list");
643 void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quitreason)
645 user_hash::iterator iter = Instance->clientlist.find(user->nick);
648 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
649 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
651 * I can't imagine this blowing up, so I'm commenting it out. We still check
652 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
654 * if (iter == clientlist.end())
657 std::string reason = quitreason;
659 if (reason.length() > MAXQUIT - 1)
660 reason.resize(MAXQUIT - 1);
663 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
665 if (user->registered == REG_ALL)
667 user->PurgeEmptyChannels();
668 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
669 user->WriteCommonExcept("QUIT :%s",reason.c_str());
673 user->FlushWriteBuf();
675 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
679 if (Instance->Config->GetIOHook(user->GetPort()))
683 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
685 catch (ModuleException& modexcept)
687 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
691 Instance->SE->DelFd(user->fd);
696 * this must come before the ServerInstance->WriteOpers so that it doesnt try to fill their buffer with anything
697 * if they were an oper with +s.
700 * In the current implementation, we only show local quits, as we only show local connects. With
701 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
703 if (user->registered == REG_ALL)
706 Instance->WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
710 if (iter != Instance->clientlist.end())
712 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
715 Instance->fd_ref_table[user->fd] = NULL;
716 if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
717 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
719 Instance->clientlist.erase(iter);
729 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
731 this->host = strdup(user->host);
732 this->dhost = strdup(user->dhost);
733 this->ident = strdup(user->ident);
734 this->server = user->server;
735 this->gecos = strdup(user->fullname);
738 WhoWasGroup::~WhoWasGroup()
750 /* every hour, run this function which removes all entries over 3 days */
751 void MaintainWhoWas(time_t TIME)
753 for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
755 whowas_set* n = (whowas_set*)iter->second;
758 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
760 WhoWasGroup *a = *(n->begin());
762 n->erase(n->begin());
770 /* adds or updates an entry in the whowas list */
771 void userrec::AddToWhoWas()
773 irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
775 if (iter == whowas.end())
777 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
778 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
780 whowas[this->nick] = n;
784 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
786 if (group->size() > 10)
788 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
793 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
798 /* add a client connection to the sockets list */
799 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
801 std::string tempnick = ConvToStr(socket) + "-unknown";
802 user_hash::iterator iter = Instance->clientlist.find(tempnick);
803 const char *ipaddr = insp_ntoa(ip);
809 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
810 * using one as a registered connection. As they are per fd, we can also safely assume
811 * that we wont have collisions. Therefore, if the nick exists in the list, its only
812 * used by a dead socket, erase the iterator so that the new client may reclaim it.
813 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
814 * issue in earlier alphas/betas
816 if (iter != Instance->clientlist.end())
818 userrec* goner = iter->second;
820 Instance->clientlist.erase(iter);
823 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
825 _new = new userrec(Instance);
826 Instance->clientlist[tempnick] = _new;
828 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
830 _new->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
831 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
832 strcpy(_new->ident, "unknown");
834 _new->registered = REG_NONE;
835 _new->signon = TIME + Instance->Config->dns_timeout;
838 log(DEBUG,"Setting socket addresses");
839 _new->SetSockAddr(AF_FAMILY, ipaddr, port);
840 log(DEBUG,"Socket addresses set.");
842 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
843 for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
844 _new->dhost[j] = _new->host[j] = *temp;
845 _new->dhost[j] = _new->host[j] = 0;
847 // set the registration timeout for this user
848 unsigned long class_regtimeout = 90;
850 long class_threshold = 5;
851 long class_sqmax = 262144; // 256kb
852 long class_rqmax = 4096; // 4k
854 for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
856 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
858 class_regtimeout = (unsigned long)i->registration_timeout;
859 class_flood = i->flood;
860 _new->pingmax = i->pingtime;
861 class_threshold = i->threshold;
862 class_sqmax = i->sendqmax;
863 class_rqmax = i->recvqmax;
868 _new->nping = TIME + _new->pingmax + Instance->Config->dns_timeout;
869 _new->timeout = TIME+class_regtimeout;
870 _new->flood = class_flood;
871 _new->threshold = class_threshold;
872 _new->sendqmax = class_sqmax;
873 _new->recvqmax = class_rqmax;
875 Instance->fd_ref_table[socket] = _new;
876 Instance->local_users.push_back(_new);
878 if (Instance->local_users.size() > Instance->Config->SoftLimit)
880 userrec::QuitUser(Instance, _new,"No more connections allowed");
884 if (Instance->local_users.size() >= MAXCLIENTS)
886 userrec::QuitUser(Instance, _new,"No more connections allowed");
892 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
893 * its a pretty big but for the moment valid assumption:
894 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
895 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
896 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
897 * which for the time being is a physical impossibility (even the largest networks dont have more
898 * than about 10,000 users on ONE server!)
900 if ((unsigned)socket >= MAX_DESCRIPTORS)
902 userrec::QuitUser(Instance, _new,"Server is full");
905 char* e = matches_exception(ipaddr);
908 char* r = matches_zline(ipaddr);
912 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
913 userrec::QuitUser(Instance, _new,reason);
920 if (!Instance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
922 userrec::QuitUser(Instance, _new, "Internal error handling connection");
927 _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
930 long userrec::GlobalCloneCount()
935 for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
937 /* We have to match ip's as strings - we don't know what protocol
938 * a remote user may be using
940 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
946 long userrec::LocalCloneCount()
949 for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
953 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
954 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
955 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
956 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
959 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
960 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
961 if (s1->s_addr == s2->s_addr)
968 void userrec::FullConnect(CullList* Goners)
970 ServerInstance->stats->statsConnects++;
971 this->idle_lastmsg = TIME;
973 ConnectClass a = this->GetClass();
975 if (a.type == CC_DENY)
977 Goners->AddItem(this,"Unauthorised connection");
981 if ((*(a.pass.c_str())) && (!this->haspassed))
983 Goners->AddItem(this,"Invalid password");
987 if (this->LocalCloneCount() > a.maxlocal)
989 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
990 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
993 else if (this->GlobalCloneCount() > a.maxglobal)
995 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
996 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1000 char match_against[MAXBUF];
1001 snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
1002 char* e = matches_exception(match_against);
1006 char* r = matches_gline(match_against);
1010 char reason[MAXBUF];
1011 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1012 Goners->AddItem(this, reason);
1016 r = matches_kline(match_against);
1020 char reason[MAXBUF];
1021 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1022 Goners->AddItem(this, reason);
1028 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1029 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1030 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1031 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1032 this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->ModeGrok->UserModeList().c_str(), ServerInstance->ModeGrok->ChannelModeList().c_str(), ServerInstance->ModeGrok->ParaModeList().c_str());
1034 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1035 // so i'd better split it :)
1036 std::stringstream out(ServerInstance->Config->data005);
1037 std::string token = "";
1038 std::string line5 = "";
1039 int token_counter = 0;
1044 line5 = line5 + token + " ";
1047 if ((token_counter >= 13) || (out.eof() == true))
1049 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1058 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1059 * changes dont go out onto the network and produce 'fake direction'.
1061 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1062 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(this));
1063 this->registered = REG_ALL;
1064 ServerInstance->WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1067 /** userrec::UpdateNick()
1068 * re-allocates a nick in the user_hash after they change nicknames,
1069 * returns a pointer to the new user as it may have moved
1071 userrec* userrec::UpdateNickHash(const char* New)
1073 //user_hash::iterator newnick;
1074 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1076 if (!strcasecmp(this->nick,New))
1077 return oldnick->second;
1079 if (oldnick == ServerInstance->clientlist.end())
1080 return NULL; /* doesnt exist */
1082 userrec* olduser = oldnick->second;
1083 ServerInstance->clientlist[New] = olduser;
1084 ServerInstance->clientlist.erase(oldnick);
1085 return ServerInstance->clientlist[New];
1088 bool userrec::ForceNickChange(const char* newnick)
1095 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1099 ServerInstance->stats->statsCollisions++;
1103 if (matches_qline(newnick))
1105 ServerInstance->stats->statsCollisions++;
1111 strlcpy(this->nick, newnick, NICKMAX - 1);
1113 if (this->registered == REG_ALL)
1115 const char* pars[1];
1117 std::string cmd = "NICK";
1118 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1123 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1125 switch (protocol_family)
1127 #ifdef SUPPORT_IP6LINKS
1130 log(DEBUG,"Set inet6 protocol address");
1131 sockaddr_in6* sin = new sockaddr_in6;
1132 sin->sin6_family = AF_INET6;
1133 sin->sin6_port = port;
1134 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1135 this->ip = (sockaddr*)sin;
1141 log(DEBUG,"Set inet4 protocol address");
1142 sockaddr_in* sin = new sockaddr_in;
1143 sin->sin_family = AF_INET;
1144 sin->sin_port = port;
1145 inet_pton(AF_INET, ip, &sin->sin_addr);
1146 this->ip = (sockaddr*)sin;
1150 log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1155 int userrec::GetPort()
1157 if (this->ip == NULL)
1160 switch (this->GetProtocolFamily())
1162 #ifdef SUPPORT_IP6LINKS
1165 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1166 return sin->sin6_port;
1172 sockaddr_in* sin = (sockaddr_in*)this->ip;
1173 return sin->sin_port;
1177 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1183 int userrec::GetProtocolFamily()
1185 if (this->ip == NULL)
1188 sockaddr_in* sin = (sockaddr_in*)this->ip;
1189 return sin->sin_family;
1192 const char* userrec::GetIPString()
1194 static char buf[1024];
1195 static char temp[1024];
1197 if (this->ip == NULL)
1200 switch (this->GetProtocolFamily())
1202 #ifdef SUPPORT_IP6LINKS
1205 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1206 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1207 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1210 strlcpy(&temp[1], buf, sizeof(temp));
1220 sockaddr_in* sin = (sockaddr_in*)this->ip;
1221 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1226 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1232 const char* userrec::GetIPString(char* buf)
1234 static char temp[1024];
1236 if (this->ip == NULL)
1242 switch (this->GetProtocolFamily())
1244 #ifdef SUPPORT_IP6LINKS
1247 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1248 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1249 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1252 strlcpy(&temp[1], buf, sizeof(temp));
1254 strlcpy(buf, temp, sizeof(temp));
1262 sockaddr_in* sin = (sockaddr_in*)this->ip;
1263 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1269 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1276 void userrec::Write(const std::string &text)
1278 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1281 std::string crlf = text;
1282 crlf.append("\r\n");
1284 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1288 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, crlf.data(), crlf.length());
1290 catch (ModuleException& modexcept)
1292 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1297 this->AddWriteBuf(crlf);
1299 ServerInstance->stats->statsSent += crlf.length();
1304 void userrec::Write(const char *text, ...)
1307 char textbuffer[MAXBUF];
1309 va_start(argsPtr, text);
1310 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1313 this->Write(std::string(textbuffer));
1316 void userrec::WriteServ(const std::string& text)
1318 char textbuffer[MAXBUF];
1320 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1321 this->Write(std::string(textbuffer));
1325 * Same as Write(), except `text' is prefixed with `:server.name '.
1327 void userrec::WriteServ(const char* text, ...)
1330 char textbuffer[MAXBUF];
1332 va_start(argsPtr, text);
1333 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1336 this->WriteServ(std::string(textbuffer));
1340 void userrec::WriteFrom(userrec *user, const std::string &text)
1344 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1346 this->Write(std::string(tb));
1350 /* write text from an originating user to originating user */
1352 void userrec::WriteFrom(userrec *user, const char* text, ...)
1355 char textbuffer[MAXBUF];
1357 va_start(argsPtr, text);
1358 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1361 this->WriteFrom(user, std::string(textbuffer));
1365 /* write text to an destination user from a source user (e.g. user privmsg) */
1367 void userrec::WriteTo(userrec *dest, const char *data, ...)
1369 char textbuffer[MAXBUF];
1372 va_start(argsPtr, data);
1373 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1376 this->WriteTo(dest, std::string(textbuffer));
1379 void userrec::WriteTo(userrec *dest, const std::string &data)
1381 dest->WriteFrom(this, data);
1385 void userrec::WriteCommon(const char* text, ...)
1387 char textbuffer[MAXBUF];
1390 if (this->registered != REG_ALL)
1393 va_start(argsPtr, text);
1394 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1397 this->WriteCommon(std::string(textbuffer));
1400 void userrec::WriteCommon(const std::string &text)
1402 bool sent_to_at_least_one = false;
1404 if (this->registered != REG_ALL)
1409 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1414 CUList *ulist= n->channel->GetUsers();
1416 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1418 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1420 already_sent[i->second->fd] = uniq_id;
1421 i->second->WriteFrom(this, std::string(text));
1422 sent_to_at_least_one = true;
1429 * if the user was not in any channels, no users will receive the text. Make sure the user
1430 * receives their OWN message for WriteCommon
1432 if (!sent_to_at_least_one)
1434 this->WriteFrom(this,std::string(text));
1439 /* write a formatted string to all users who share at least one common
1440 * channel, NOT including the source user e.g. for use in QUIT
1443 void userrec::WriteCommonExcept(const char* text, ...)
1445 char textbuffer[MAXBUF];
1448 va_start(argsPtr, text);
1449 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1452 this->WriteCommonExcept(std::string(textbuffer));
1455 void userrec::WriteCommonExcept(const std::string &text)
1457 bool quit_munge = true;
1458 char oper_quit[MAXBUF];
1459 char textbuffer[MAXBUF];
1461 strlcpy(textbuffer, text.c_str(), MAXBUF);
1463 if (this->registered != REG_ALL)
1468 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1469 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1472 if (ServerInstance->Config->HideSplits)
1474 char* check = textbuffer + 6;
1476 if (!strncasecmp(textbuffer, "QUIT :",6))
1478 std::stringstream split(check);
1479 std::string server_one;
1480 std::string server_two;
1482 split >> server_one;
1483 split >> server_two;
1485 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1487 strlcpy(oper_quit,textbuffer,MAXQUIT);
1488 strlcpy(check,"*.net *.split",MAXQUIT);
1494 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1496 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1497 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1499 char* check = textbuffer + 13;
1500 strlcpy(oper_quit,textbuffer,MAXQUIT);
1501 *check = 0; // We don't need to strlcpy, we just chop it from the :
1506 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1511 CUList *ulist= n->channel->GetUsers();
1513 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1515 if (this != i->second)
1517 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1519 already_sent[i->second->fd] = uniq_id;
1521 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1523 i->second->WriteFrom(this, std::string(textbuffer));
1532 void userrec::WriteWallOps(const std::string &text)
1534 /* Does nothing if theyre not opered */
1535 if ((!*this->oper) && (IS_LOCAL(this)))
1538 std::string wallop = "WALLOPS :";
1539 wallop.append(text);
1541 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1544 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1545 this->WriteTo(t,wallop);
1549 void userrec::WriteWallOps(const char* text, ...)
1551 char textbuffer[MAXBUF];
1554 va_start(argsPtr, text);
1555 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1558 this->WriteWallOps(std::string(textbuffer));
1561 /* return 0 or 1 depending if users u and u2 share one or more common channels
1562 * (used by QUIT, NICK etc which arent channel specific notices)
1564 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1565 * the first users channels then the second users channels within the outer loop,
1566 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1567 * all possible iterations). However this new function instead checks against the
1568 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1569 * and saves us time as we already know what pointer value we are after.
1570 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1571 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1573 bool userrec::SharesChannelWith(userrec *other)
1575 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1579 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1581 /* Fetch the channel from the user */
1582 ucrec* user_channel = *i;
1584 if (user_channel->channel)
1586 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1587 * by replacing it with a map::find which *should* be more efficient
1589 if (user_channel->channel->HasUser(other))
1596 int userrec::CountChannels()
1599 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1605 bool userrec::ChangeName(const char* gecos)
1610 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1613 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1615 strlcpy(this->fullname,gecos,MAXGECOS+1);
1619 bool userrec::ChangeDisplayedHost(const char* host)
1624 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1627 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1629 strlcpy(this->dhost,host,63);
1632 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1637 void userrec::NoticeAll(char* text, ...)
1639 char textbuffer[MAXBUF];
1640 char formatbuffer[MAXBUF];
1643 va_start(argsPtr, text);
1644 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1647 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1649 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1652 t->WriteFrom(this, std::string(formatbuffer));
1657 std::string userrec::ChannelList(userrec* source)
1660 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1664 if(rec->channel && rec->channel->name)
1666 /* If the target is the same as the sender, let them see all their channels.
1667 * If the channel is NOT private/secret OR the user shares a common channel
1668 * If the user is an oper, and the <options:operspywhois> option is set.
1670 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1672 list.append(cmode(this, rec->channel)).append(rec->channel->name).append(" ");
1679 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1682 std::ostringstream prefix;
1683 std::string::size_type start, pos, length;
1685 prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
1686 line = prefix.str();
1688 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1690 length = (pos == std::string::npos) ? cl.length() : pos;
1692 if (line.length() + length - start > 510)
1695 line = prefix.str();
1698 if(pos == std::string::npos)
1700 line += cl.substr(start, length - start);
1705 line += cl.substr(start, length - start + 1);
1716 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1717 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1718 * then their ip will be taken as 'priority' anyway, so for example,
1719 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1721 ConnectClass& userrec::GetClass()
1723 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1725 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1729 return *(ServerInstance->Config->Classes.begin());
1732 void userrec::PurgeEmptyChannels()
1734 std::vector<chanrec*> to_delete;
1736 // firstly decrement the count on each channel
1737 for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1742 if (uc->channel->DelUser(this) == 0)
1744 /* No users left in here, mark it for deletion */
1745 to_delete.push_back(uc->channel);
1751 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1753 chanrec* thischan = *n;
1754 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1755 if (i2 != ServerInstance->chanlist.end())
1757 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1759 ServerInstance->chanlist.erase(i2);