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"
32 #include "cull_list.h"
34 irc::whowas::whowas_users whowas;
35 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
37 typedef std::map<irc::string,char*> opertype_t;
38 typedef opertype_t operclass_t;
41 operclass_t operclass;
43 /* XXX: Used for speeding up WriteCommon operations */
44 unsigned long uniq_id = 0;
46 bool InitTypes(ServerConfig* conf, const char* tag)
48 for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
58 bool InitClasses(ServerConfig* conf, const char* tag)
60 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
70 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
72 char* TypeName = (char*)values[0];
73 char* Classes = (char*)values[1];
75 opertypes[TypeName] = strdup(Classes);
76 conf->GetInstance()->Log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
80 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
82 char* ClassName = (char*)values[0];
83 char* CommandList = (char*)values[1];
85 operclass[ClassName] = strdup(CommandList);
86 conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
90 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
95 bool userrec::ProcessNoticeMasks(const char *sm)
111 if ((*c >= 'A') && (*c <= 'z'))
112 this->SetNoticeMask(*c, adding);
122 void userrec::StartDNSLookup()
124 ServerInstance->Log(DEBUG,"Commencing reverse lookup");
127 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
128 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
129 this->ServerInstance->AddResolver(res_reverse);
131 catch (ModuleException& e)
133 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
137 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
138 Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
141 this->bound_fd = user->fd;
144 void UserResolver::OnLookupComplete(const std::string &result)
146 if ((!this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
148 ServerInstance->Log(DEBUG,"Commencing forward lookup");
149 this->bound_user->stored_host = result;
152 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
153 this->ServerInstance->AddResolver(bound_user->res_forward);
155 catch (ModuleException& e)
157 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
160 else if ((this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
162 /* Both lookups completed */
163 if (this->bound_user->GetIPString() == result)
165 std::string hostname = this->bound_user->stored_host;
166 if (hostname.length() < 65)
168 /* Hostnames starting with : are not a good thing (tm) */
169 if (*(hostname.c_str()) == ':')
170 hostname = "0" + hostname;
172 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
173 this->bound_user->dns_done = true;
174 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
175 strlcpy(this->bound_user->host, hostname.c_str(),64);
179 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());
184 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());
189 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
191 if (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user)
193 /* Error message here */
194 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
195 this->bound_user->dns_done = true;
200 bool userrec::IsNoticeMaskSet(unsigned char sm)
202 return (snomasks[sm-65]);
205 void userrec::SetNoticeMask(unsigned char sm, bool value)
207 snomasks[sm-65] = value;
210 const char* userrec::FormatNoticeMasks()
212 static char data[MAXBUF];
215 for (int n = 0; n < 64; n++)
218 data[offset++] = n+65;
227 bool userrec::IsModeSet(unsigned char m)
229 return (modes[m-65]);
232 void userrec::SetMode(unsigned char m, bool value)
237 const char* userrec::FormatModes()
239 static char data[MAXBUF];
241 for (int n = 0; n < 64; n++)
244 data[offset++] = n+65;
250 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
252 ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
253 // the PROPER way to do it, AVOID bzero at *ALL* costs
254 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
255 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
256 reset_due = ServerInstance->Time();
257 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
258 timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
259 haspassed = dns_done = false;
263 res_forward = res_reverse = NULL;
267 chans.resize(MAXCHANS);
268 memset(modes,0,sizeof(modes));
270 for (unsigned int n = 0; n < MAXCHANS; n++)
272 ucrec* x = new ucrec();
281 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
283 ucrec* x = (ucrec*)*n;
289 if (this->GetProtocolFamily() == AF_INET)
291 delete (sockaddr_in*)ip;
293 #ifdef SUPPORT_IP6LINKS
296 delete (sockaddr_in6*)ip;
302 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
303 void userrec::MakeHost(char* nhost)
305 /* This is much faster than snprintf */
307 for(char* n = ident; *n; n++)
310 for(char* n = host; *n; n++)
315 void userrec::CloseSocket()
317 shutdown(this->fd,2);
321 char* userrec::GetFullHost()
323 static char result[MAXBUF];
325 for(char* n = nick; *n; n++)
328 for(char* n = ident; *n; n++)
331 for(char* n = dhost; *n; n++)
337 char* userrec::MakeWildHost()
339 static char nresult[MAXBUF];
341 *t++ = '*'; *t++ = '!';
342 *t++ = '*'; *t++ = '@';
343 for(char* n = dhost; *n; n++)
349 int userrec::ReadData(void* buffer, size_t size)
353 return read(this->fd, buffer, size);
360 char* userrec::GetFullRealHost()
362 static char fresult[MAXBUF];
364 for(char* n = nick; *n; n++)
367 for(char* n = ident; *n; n++)
370 for(char* n = host; *n; n++)
376 bool userrec::IsInvited(irc::string &channel)
378 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
380 irc::string compare = i->channel;
382 if (compare == channel)
390 InvitedList* userrec::GetInviteList()
395 void userrec::InviteTo(irc::string &channel)
399 invites.push_back(i);
402 void userrec::RemoveInvite(irc::string &channel)
404 ServerInstance->Log(DEBUG,"Removing invites");
408 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
410 irc::string compare = i->channel;
412 if (compare == channel)
421 bool userrec::HasPermission(const std::string &command)
428 * users on remote servers can completely bypass all permissions based checks.
429 * This prevents desyncs when one server has different type/class tags to another.
430 * That having been said, this does open things up to the possibility of source changes
431 * allowing remote kills, etc - but if they have access to the src, they most likely have
432 * access to the conf - so it's an end to a means either way.
437 // are they even an oper at all?
440 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
441 if (iter_opertype != opertypes.end())
443 char* Classes = strdup(iter_opertype->second);
444 char* myclass = strtok_r(Classes," ",&savept);
447 operclass_t::iterator iter_operclass = operclass.find(myclass);
448 if (iter_operclass != operclass.end())
450 char* CommandList = strdup(iter_operclass->second);
451 mycmd = strtok_r(CommandList," ",&savept2);
454 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
460 mycmd = strtok_r(NULL," ",&savept2);
464 myclass = strtok_r(NULL," ",&savept);
473 bool userrec::AddBuffer(const std::string &a)
477 /* NB: std::string is arsey about \r and \n and tries to translate them
478 * somehow, so we CANNOT use std::string::find() here :(
480 for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
489 if (recvq.length() > (unsigned)this->recvqmax)
491 this->SetWriteError("RecvQ exceeded");
492 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
499 bool userrec::BufferIsReady()
501 return (recvq.find('\n') != std::string::npos);
504 void userrec::ClearBuffer()
509 std::string userrec::GetBuffer()
514 /* Strip any leading \r or \n off the string.
515 * Usually there are only one or two of these,
516 * so its is computationally cheap to do.
518 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
519 recvq.erase(recvq.begin());
521 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
523 /* Find the first complete line, return it as the
524 * result, and leave the recvq as whats left
528 std::string ret = std::string(recvq.begin(), x);
529 recvq.erase(recvq.begin(), x + 1);
536 void userrec::AddWriteBuf(const std::string &data)
538 if (*this->GetWriteError())
541 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
544 * Fix by brain - Set the error text BEFORE calling writeopers, because
545 * if we dont it'll recursively call here over and over again trying
546 * to repeatedly add the text to the sendq!
548 this->SetWriteError("SendQ exceeded");
549 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
553 if (data.length() > 512)
555 std::string newdata(data);
557 newdata.append("\r\n");
558 sendq.append(newdata);
566 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
567 void userrec::FlushWriteBuf()
569 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
571 const char* tb = this->sendq.c_str();
572 int n_sent = write(this->fd,tb,this->sendq.length());
576 this->SetWriteError(strerror(errno));
583 // update the user's stats counters
584 this->bytes_out += n_sent;
590 void userrec::SetWriteError(const std::string &error)
592 ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
593 // don't try to set the error twice, its already set take the first string.
594 if (!this->WriteError.length())
596 ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
597 this->WriteError = error;
601 const char* userrec::GetWriteError()
603 return this->WriteError.c_str();
606 void userrec::Oper(const std::string &opertype)
608 this->modes[UM_OPERATOR] = 1;
609 this->WriteServ("MODE %s :+o", this->nick);
610 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
611 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
612 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
613 ServerInstance->all_opers.push_back(this);
614 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
617 void userrec::UnOper()
622 this->modes[UM_OPERATOR] = 0;
623 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
627 ServerInstance->Log(DEBUG,"Oper removed from optimization list");
628 ServerInstance->all_opers.erase(a);
635 void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quitreason)
637 user_hash::iterator iter = Instance->clientlist.find(user->nick);
640 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
641 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
643 * I can't imagine this blowing up, so I'm commenting it out. We still check
644 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
646 * if (iter == clientlist.end())
649 std::string reason = quitreason;
651 if (reason.length() > MAXQUIT - 1)
652 reason.resize(MAXQUIT - 1);
655 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
657 if (user->registered == REG_ALL)
659 user->PurgeEmptyChannels();
660 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
661 user->WriteCommonExcept("QUIT :%s",reason.c_str());
665 user->FlushWriteBuf();
667 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
671 if (Instance->Config->GetIOHook(user->GetPort()))
675 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
677 catch (ModuleException& modexcept)
679 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
683 Instance->SE->DelFd(user->fd);
688 * this must come before the ServerInstance->WriteOpers so that it doesnt try to fill their buffer with anything
689 * if they were an oper with +s.
692 * In the current implementation, we only show local quits, as we only show local connects. With
693 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
695 if (user->registered == REG_ALL)
698 Instance->WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
702 if (iter != Instance->clientlist.end())
704 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
707 Instance->fd_ref_table[user->fd] = NULL;
708 if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
709 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
711 Instance->clientlist.erase(iter);
721 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
723 this->host = strdup(user->host);
724 this->dhost = strdup(user->dhost);
725 this->ident = strdup(user->ident);
726 this->server = user->server;
727 this->gecos = strdup(user->fullname);
730 WhoWasGroup::~WhoWasGroup()
742 /* every hour, run this function which removes all entries over 3 days */
743 void MaintainWhoWas(time_t t)
745 for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
747 whowas_set* n = (whowas_set*)iter->second;
750 while ((n->begin() != n->end()) && ((*n->begin())->signon < t - 259200)) // 3 days
752 WhoWasGroup *a = *(n->begin());
754 n->erase(n->begin());
762 /* adds or updates an entry in the whowas list */
763 void userrec::AddToWhoWas()
765 irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
767 if (iter == whowas.end())
769 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
770 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
772 whowas[this->nick] = n;
776 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
778 if (group->size() > 10)
780 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
785 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
790 /* add a client connection to the sockets list */
791 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
793 std::string tempnick = ConvToStr(socket) + "-unknown";
794 user_hash::iterator iter = Instance->clientlist.find(tempnick);
795 const char *ipaddr = insp_ntoa(ip);
801 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
802 * using one as a registered connection. As they are per fd, we can also safely assume
803 * that we wont have collisions. Therefore, if the nick exists in the list, its only
804 * used by a dead socket, erase the iterator so that the new client may reclaim it.
805 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
806 * issue in earlier alphas/betas
808 if (iter != Instance->clientlist.end())
810 userrec* goner = iter->second;
812 Instance->clientlist.erase(iter);
815 Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
817 _new = new userrec(Instance);
818 Instance->clientlist[tempnick] = _new;
820 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
822 _new->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
823 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
824 strcpy(_new->ident, "unknown");
826 _new->registered = REG_NONE;
827 _new->signon = Instance->Time() + Instance->Config->dns_timeout;
830 Instance->Log(DEBUG,"Setting socket addresses");
831 _new->SetSockAddr(AF_FAMILY, ipaddr, port);
832 Instance->Log(DEBUG,"Socket addresses set.");
834 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
835 for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
836 _new->dhost[j] = _new->host[j] = *temp;
837 _new->dhost[j] = _new->host[j] = 0;
839 // set the registration timeout for this user
840 unsigned long class_regtimeout = 90;
842 long class_threshold = 5;
843 long class_sqmax = 262144; // 256kb
844 long class_rqmax = 4096; // 4k
846 for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
848 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
850 class_regtimeout = (unsigned long)i->registration_timeout;
851 class_flood = i->flood;
852 _new->pingmax = i->pingtime;
853 class_threshold = i->threshold;
854 class_sqmax = i->sendqmax;
855 class_rqmax = i->recvqmax;
860 _new->nping = Instance->Time() + _new->pingmax + Instance->Config->dns_timeout;
861 _new->timeout = Instance->Time() + class_regtimeout;
862 _new->flood = class_flood;
863 _new->threshold = class_threshold;
864 _new->sendqmax = class_sqmax;
865 _new->recvqmax = class_rqmax;
867 Instance->fd_ref_table[socket] = _new;
868 Instance->local_users.push_back(_new);
870 if (Instance->local_users.size() > Instance->Config->SoftLimit)
872 userrec::QuitUser(Instance, _new,"No more connections allowed");
876 if (Instance->local_users.size() >= MAXCLIENTS)
878 userrec::QuitUser(Instance, _new,"No more connections allowed");
884 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
885 * its a pretty big but for the moment valid assumption:
886 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
887 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
888 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
889 * which for the time being is a physical impossibility (even the largest networks dont have more
890 * than about 10,000 users on ONE server!)
892 if ((unsigned)socket >= MAX_DESCRIPTORS)
894 userrec::QuitUser(Instance, _new,"Server is full");
897 char* e = Instance->XLines->matches_exception(ipaddr);
900 char* r = Instance->XLines->matches_zline(ipaddr);
904 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
905 userrec::QuitUser(Instance, _new,reason);
912 if (!Instance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
914 userrec::QuitUser(Instance, _new, "Internal error handling connection");
919 _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
922 long userrec::GlobalCloneCount()
927 for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
929 /* We have to match ip's as strings - we don't know what protocol
930 * a remote user may be using
932 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
938 long userrec::LocalCloneCount()
941 for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
945 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
946 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
947 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
948 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
951 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
952 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
953 if (s1->s_addr == s2->s_addr)
960 void userrec::FullConnect(CullList* Goners)
962 ServerInstance->stats->statsConnects++;
963 this->idle_lastmsg = ServerInstance->Time();
965 ConnectClass a = this->GetClass();
967 if (a.type == CC_DENY)
969 Goners->AddItem(this,"Unauthorised connection");
973 if ((*(a.pass.c_str())) && (!this->haspassed))
975 Goners->AddItem(this,"Invalid password");
979 if (this->LocalCloneCount() > a.maxlocal)
981 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
982 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
985 else if (this->GlobalCloneCount() > a.maxglobal)
987 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
988 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
992 char match_against[MAXBUF];
993 snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
994 char* e = ServerInstance->XLines->matches_exception(match_against);
998 char* r = ServerInstance->XLines->matches_gline(match_against);
1002 char reason[MAXBUF];
1003 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1004 Goners->AddItem(this, reason);
1008 r = ServerInstance->XLines->matches_kline(match_against);
1012 char reason[MAXBUF];
1013 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1014 Goners->AddItem(this, reason);
1020 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1021 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1022 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1023 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1024 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());
1026 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1027 // so i'd better split it :)
1028 std::stringstream out(ServerInstance->Config->data005);
1029 std::string token = "";
1030 std::string line5 = "";
1031 int token_counter = 0;
1036 line5 = line5 + token + " ";
1039 if ((token_counter >= 13) || (out.eof() == true))
1041 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1050 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1051 * changes dont go out onto the network and produce 'fake direction'.
1053 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1054 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(this));
1055 this->registered = REG_ALL;
1056 ServerInstance->WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1059 /** userrec::UpdateNick()
1060 * re-allocates a nick in the user_hash after they change nicknames,
1061 * returns a pointer to the new user as it may have moved
1063 userrec* userrec::UpdateNickHash(const char* New)
1065 //user_hash::iterator newnick;
1066 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1068 if (!strcasecmp(this->nick,New))
1069 return oldnick->second;
1071 if (oldnick == ServerInstance->clientlist.end())
1072 return NULL; /* doesnt exist */
1074 userrec* olduser = oldnick->second;
1075 ServerInstance->clientlist[New] = olduser;
1076 ServerInstance->clientlist.erase(oldnick);
1077 return ServerInstance->clientlist[New];
1080 bool userrec::ForceNickChange(const char* newnick)
1087 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1091 ServerInstance->stats->statsCollisions++;
1095 if (ServerInstance->XLines->matches_qline(newnick))
1097 ServerInstance->stats->statsCollisions++;
1103 strlcpy(this->nick, newnick, NICKMAX - 1);
1105 if (this->registered == REG_ALL)
1107 const char* pars[1];
1109 std::string cmd = "NICK";
1110 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1115 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1117 switch (protocol_family)
1119 #ifdef SUPPORT_IP6LINKS
1122 ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1123 sockaddr_in6* sin = new sockaddr_in6;
1124 sin->sin6_family = AF_INET6;
1125 sin->sin6_port = port;
1126 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1127 this->ip = (sockaddr*)sin;
1133 ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1134 sockaddr_in* sin = new sockaddr_in;
1135 sin->sin_family = AF_INET;
1136 sin->sin_port = port;
1137 inet_pton(AF_INET, ip, &sin->sin_addr);
1138 this->ip = (sockaddr*)sin;
1142 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1147 int userrec::GetPort()
1149 if (this->ip == NULL)
1152 switch (this->GetProtocolFamily())
1154 #ifdef SUPPORT_IP6LINKS
1157 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1158 return sin->sin6_port;
1164 sockaddr_in* sin = (sockaddr_in*)this->ip;
1165 return sin->sin_port;
1169 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1175 int userrec::GetProtocolFamily()
1177 if (this->ip == NULL)
1180 sockaddr_in* sin = (sockaddr_in*)this->ip;
1181 return sin->sin_family;
1184 const char* userrec::GetIPString()
1186 static char buf[1024];
1187 static char temp[1024];
1189 if (this->ip == NULL)
1192 switch (this->GetProtocolFamily())
1194 #ifdef SUPPORT_IP6LINKS
1197 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1198 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1199 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1202 strlcpy(&temp[1], buf, sizeof(temp));
1212 sockaddr_in* sin = (sockaddr_in*)this->ip;
1213 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1218 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1224 const char* userrec::GetIPString(char* buf)
1226 static char temp[1024];
1228 if (this->ip == NULL)
1234 switch (this->GetProtocolFamily())
1236 #ifdef SUPPORT_IP6LINKS
1239 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1240 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1241 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1244 strlcpy(&temp[1], buf, sizeof(temp));
1246 strlcpy(buf, temp, sizeof(temp));
1254 sockaddr_in* sin = (sockaddr_in*)this->ip;
1255 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1261 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1268 void userrec::Write(const std::string &text)
1270 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1273 std::string crlf = text;
1274 crlf.append("\r\n");
1276 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1280 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, crlf.data(), crlf.length());
1282 catch (ModuleException& modexcept)
1284 ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1289 this->AddWriteBuf(crlf);
1291 ServerInstance->stats->statsSent += crlf.length();
1296 void userrec::Write(const char *text, ...)
1299 char textbuffer[MAXBUF];
1301 va_start(argsPtr, text);
1302 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1305 this->Write(std::string(textbuffer));
1308 void userrec::WriteServ(const std::string& text)
1310 char textbuffer[MAXBUF];
1312 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1313 this->Write(std::string(textbuffer));
1317 * Same as Write(), except `text' is prefixed with `:server.name '.
1319 void userrec::WriteServ(const char* text, ...)
1322 char textbuffer[MAXBUF];
1324 va_start(argsPtr, text);
1325 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1328 this->WriteServ(std::string(textbuffer));
1332 void userrec::WriteFrom(userrec *user, const std::string &text)
1336 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1338 this->Write(std::string(tb));
1342 /* write text from an originating user to originating user */
1344 void userrec::WriteFrom(userrec *user, const char* text, ...)
1347 char textbuffer[MAXBUF];
1349 va_start(argsPtr, text);
1350 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1353 this->WriteFrom(user, std::string(textbuffer));
1357 /* write text to an destination user from a source user (e.g. user privmsg) */
1359 void userrec::WriteTo(userrec *dest, const char *data, ...)
1361 char textbuffer[MAXBUF];
1364 va_start(argsPtr, data);
1365 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1368 this->WriteTo(dest, std::string(textbuffer));
1371 void userrec::WriteTo(userrec *dest, const std::string &data)
1373 dest->WriteFrom(this, data);
1377 void userrec::WriteCommon(const char* text, ...)
1379 char textbuffer[MAXBUF];
1382 if (this->registered != REG_ALL)
1385 va_start(argsPtr, text);
1386 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1389 this->WriteCommon(std::string(textbuffer));
1392 void userrec::WriteCommon(const std::string &text)
1394 bool sent_to_at_least_one = false;
1396 if (this->registered != REG_ALL)
1401 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1406 CUList *ulist= n->channel->GetUsers();
1408 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1410 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1412 already_sent[i->second->fd] = uniq_id;
1413 i->second->WriteFrom(this, std::string(text));
1414 sent_to_at_least_one = true;
1421 * if the user was not in any channels, no users will receive the text. Make sure the user
1422 * receives their OWN message for WriteCommon
1424 if (!sent_to_at_least_one)
1426 this->WriteFrom(this,std::string(text));
1431 /* write a formatted string to all users who share at least one common
1432 * channel, NOT including the source user e.g. for use in QUIT
1435 void userrec::WriteCommonExcept(const char* text, ...)
1437 char textbuffer[MAXBUF];
1440 va_start(argsPtr, text);
1441 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1444 this->WriteCommonExcept(std::string(textbuffer));
1447 void userrec::WriteCommonExcept(const std::string &text)
1449 bool quit_munge = true;
1450 char oper_quit[MAXBUF];
1451 char textbuffer[MAXBUF];
1453 strlcpy(textbuffer, text.c_str(), MAXBUF);
1455 if (this->registered != REG_ALL)
1460 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1461 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1464 if (ServerInstance->Config->HideSplits)
1466 char* check = textbuffer + 6;
1468 if (!strncasecmp(textbuffer, "QUIT :",6))
1470 std::stringstream split(check);
1471 std::string server_one;
1472 std::string server_two;
1474 split >> server_one;
1475 split >> server_two;
1477 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1479 strlcpy(oper_quit,textbuffer,MAXQUIT);
1480 strlcpy(check,"*.net *.split",MAXQUIT);
1486 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1488 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1489 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1491 char* check = textbuffer + 13;
1492 strlcpy(oper_quit,textbuffer,MAXQUIT);
1493 *check = 0; // We don't need to strlcpy, we just chop it from the :
1498 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1503 CUList *ulist= n->channel->GetUsers();
1505 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1507 if (this != i->second)
1509 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1511 already_sent[i->second->fd] = uniq_id;
1513 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1515 i->second->WriteFrom(this, std::string(textbuffer));
1524 void userrec::WriteWallOps(const std::string &text)
1526 /* Does nothing if theyre not opered */
1527 if ((!*this->oper) && (IS_LOCAL(this)))
1530 std::string wallop = "WALLOPS :";
1531 wallop.append(text);
1533 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1536 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1537 this->WriteTo(t,wallop);
1541 void userrec::WriteWallOps(const char* text, ...)
1543 char textbuffer[MAXBUF];
1546 va_start(argsPtr, text);
1547 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1550 this->WriteWallOps(std::string(textbuffer));
1553 /* return 0 or 1 depending if users u and u2 share one or more common channels
1554 * (used by QUIT, NICK etc which arent channel specific notices)
1556 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1557 * the first users channels then the second users channels within the outer loop,
1558 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1559 * all possible iterations). However this new function instead checks against the
1560 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1561 * and saves us time as we already know what pointer value we are after.
1562 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1563 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1565 bool userrec::SharesChannelWith(userrec *other)
1567 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1571 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1573 /* Fetch the channel from the user */
1574 ucrec* user_channel = *i;
1576 if (user_channel->channel)
1578 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1579 * by replacing it with a map::find which *should* be more efficient
1581 if (user_channel->channel->HasUser(other))
1588 int userrec::CountChannels()
1591 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1597 bool userrec::ChangeName(const char* gecos)
1602 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1605 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1607 strlcpy(this->fullname,gecos,MAXGECOS+1);
1611 bool userrec::ChangeDisplayedHost(const char* host)
1616 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1619 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1621 strlcpy(this->dhost,host,63);
1624 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1629 void userrec::NoticeAll(char* text, ...)
1631 char textbuffer[MAXBUF];
1632 char formatbuffer[MAXBUF];
1635 va_start(argsPtr, text);
1636 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1639 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1641 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1644 t->WriteFrom(this, std::string(formatbuffer));
1649 std::string userrec::ChannelList(userrec* source)
1652 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1656 if(rec->channel && rec->channel->name)
1658 /* If the target is the same as the sender, let them see all their channels.
1659 * If the channel is NOT private/secret OR the user shares a common channel
1660 * If the user is an oper, and the <options:operspywhois> option is set.
1662 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1664 list.append(rec->channel->GetStatusChar(this)).append(rec->channel->name).append(" ");
1671 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1674 std::ostringstream prefix;
1675 std::string::size_type start, pos, length;
1677 prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
1678 line = prefix.str();
1680 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1682 length = (pos == std::string::npos) ? cl.length() : pos;
1684 if (line.length() + length - start > 510)
1687 line = prefix.str();
1690 if(pos == std::string::npos)
1692 line += cl.substr(start, length - start);
1697 line += cl.substr(start, length - start + 1);
1708 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1709 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1710 * then their ip will be taken as 'priority' anyway, so for example,
1711 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1713 ConnectClass& userrec::GetClass()
1715 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1717 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1721 return *(ServerInstance->Config->Classes.begin());
1724 void userrec::PurgeEmptyChannels()
1726 std::vector<chanrec*> to_delete;
1728 // firstly decrement the count on each channel
1729 for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1734 if (uc->channel->DelUser(this) == 0)
1736 /* No users left in here, mark it for deletion */
1737 to_delete.push_back(uc->channel);
1743 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1745 chanrec* thischan = *n;
1746 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1747 if (i2 != ServerInstance->chanlist.end())
1749 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1751 ServerInstance->chanlist.erase(i2);
1758 void userrec::ShowMOTD()
1760 if (!ServerInstance->Config->MOTD.size())
1762 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1765 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1767 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
1768 this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
1770 this->WriteServ("376 %s :End of message of the day.", this->nick);
1773 void userrec::ShowRULES()
1775 if (!ServerInstance->Config->RULES.size())
1777 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1780 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1782 for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
1783 this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
1785 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);