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"
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 std::string userrec::ProcessNoticeMasks(const char *sm)
97 bool adding = true, oldadding = false;
99 std::string output = "";
112 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
114 if ((IsNoticeMaskSet(*c) && adding) || (!IsNoticeMaskSet(*c) && !adding))
116 if ((oldadding != adding) || (sm == c))
117 output += (adding ? '+' : '-');
119 this->SetNoticeMask(*c, adding);
134 void userrec::StartDNSLookup()
136 ServerInstance->Log(DEBUG,"Commencing reverse lookup");
139 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
140 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
141 this->ServerInstance->AddResolver(res_reverse);
143 catch (ModuleException& e)
145 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
149 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
150 Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
153 this->bound_fd = user->GetFd();
156 void UserResolver::OnLookupComplete(const std::string &result)
158 if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
160 ServerInstance->Log(DEBUG,"Commencing forward lookup");
161 this->bound_user->stored_host = result;
164 /* Check we didnt time out */
165 if (this->bound_user->registered != REG_ALL)
167 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
168 this->ServerInstance->AddResolver(bound_user->res_forward);
171 catch (ModuleException& e)
173 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
176 else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
178 /* Both lookups completed */
179 if (this->bound_user->GetIPString() == result)
181 std::string hostname = this->bound_user->stored_host;
182 if (hostname.length() < 65)
184 /* Check we didnt time out */
185 if (this->bound_user->registered != REG_ALL)
187 /* Hostnames starting with : are not a good thing (tm) */
188 if (*(hostname.c_str()) == ':')
189 hostname = "0" + hostname;
191 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
192 this->bound_user->dns_done = true;
193 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
194 strlcpy(this->bound_user->host, hostname.c_str(),64);
199 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());
204 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());
209 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
211 if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
213 /* Error message here */
214 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
215 this->bound_user->dns_done = true;
220 bool userrec::IsNoticeMaskSet(unsigned char sm)
222 return (snomasks[sm-65]);
225 void userrec::SetNoticeMask(unsigned char sm, bool value)
227 snomasks[sm-65] = value;
230 const char* userrec::FormatNoticeMasks()
232 static char data[MAXBUF];
235 for (int n = 0; n < 64; n++)
238 data[offset++] = n+65;
247 bool userrec::IsModeSet(unsigned char m)
249 return (modes[m-65]);
252 void userrec::SetMode(unsigned char m, bool value)
257 const char* userrec::FormatModes()
259 static char data[MAXBUF];
261 for (int n = 0; n < 64; n++)
264 data[offset++] = n+65;
270 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
272 ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
273 // the PROPER way to do it, AVOID bzero at *ALL* costs
274 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
275 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
276 reset_due = ServerInstance->Time();
277 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
278 timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
279 haspassed = dns_done = false;
284 res_forward = res_reverse = NULL;
288 chans.resize(MAXCHANS);
289 memset(modes,0,sizeof(modes));
291 for (unsigned int n = 0; n < MAXCHANS; n++)
293 ucrec* x = new ucrec();
302 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
304 ucrec* x = (ucrec*)*n;
310 if (this->GetProtocolFamily() == AF_INET)
312 delete (sockaddr_in*)ip;
314 #ifdef SUPPORT_IP6LINKS
317 delete (sockaddr_in6*)ip;
323 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
324 void userrec::MakeHost(char* nhost)
326 /* This is much faster than snprintf */
328 for(char* n = ident; *n; n++)
331 for(char* n = host; *n; n++)
336 void userrec::CloseSocket()
338 shutdown(this->fd,2);
342 char* userrec::GetFullHost()
344 static char result[MAXBUF];
346 for(char* n = nick; *n; n++)
349 for(char* n = ident; *n; n++)
352 for(char* n = dhost; *n; n++)
358 char* userrec::MakeWildHost()
360 static char nresult[MAXBUF];
362 *t++ = '*'; *t++ = '!';
363 *t++ = '*'; *t++ = '@';
364 for(char* n = dhost; *n; n++)
370 int userrec::ReadData(void* buffer, size_t size)
374 return read(this->fd, buffer, size);
381 char* userrec::GetFullRealHost()
383 static char fresult[MAXBUF];
385 for(char* n = nick; *n; n++)
388 for(char* n = ident; *n; n++)
391 for(char* n = host; *n; n++)
397 bool userrec::IsInvited(irc::string &channel)
399 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
401 irc::string compare = i->channel;
403 if (compare == channel)
411 InvitedList* userrec::GetInviteList()
416 void userrec::InviteTo(irc::string &channel)
420 invites.push_back(i);
423 void userrec::RemoveInvite(irc::string &channel)
425 ServerInstance->Log(DEBUG,"Removing invites");
429 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
431 irc::string compare = i->channel;
433 if (compare == channel)
442 bool userrec::HasPermission(const std::string &command)
449 * users on remote servers can completely bypass all permissions based checks.
450 * This prevents desyncs when one server has different type/class tags to another.
451 * That having been said, this does open things up to the possibility of source changes
452 * allowing remote kills, etc - but if they have access to the src, they most likely have
453 * access to the conf - so it's an end to a means either way.
458 // are they even an oper at all?
461 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
462 if (iter_opertype != opertypes.end())
464 char* Classes = strdup(iter_opertype->second);
465 char* myclass = strtok_r(Classes," ",&savept);
468 operclass_t::iterator iter_operclass = operclass.find(myclass);
469 if (iter_operclass != operclass.end())
471 char* CommandList = strdup(iter_operclass->second);
472 mycmd = strtok_r(CommandList," ",&savept2);
475 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
481 mycmd = strtok_r(NULL," ",&savept2);
485 myclass = strtok_r(NULL," ",&savept);
493 /** NOTE: We cannot pass a const reference to this method.
494 * The string is changed by the workings of the method,
495 * so that if we pass const ref, we end up copying it to
496 * something we can change anyway. Makes sense to just let
497 * the compiler do that copy for us.
499 bool userrec::AddBuffer(std::string a)
501 std::string::size_type i = a.rfind('\r');
503 while (i != std::string::npos)
512 if (recvq.length() > (unsigned)this->recvqmax)
514 this->SetWriteError("RecvQ exceeded");
515 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
522 bool userrec::BufferIsReady()
524 return (recvq.find('\n') != std::string::npos);
527 void userrec::ClearBuffer()
532 std::string userrec::GetBuffer()
537 /* Strip any leading \r or \n off the string.
538 * Usually there are only one or two of these,
539 * so its is computationally cheap to do.
541 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
542 recvq.erase(recvq.begin());
544 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
546 /* Find the first complete line, return it as the
547 * result, and leave the recvq as whats left
551 std::string ret = std::string(recvq.begin(), x);
552 recvq.erase(recvq.begin(), x + 1);
559 void userrec::AddWriteBuf(const std::string &data)
561 if (*this->GetWriteError())
564 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
567 * Fix by brain - Set the error text BEFORE calling writeopers, because
568 * if we dont it'll recursively call here over and over again trying
569 * to repeatedly add the text to the sendq!
571 this->SetWriteError("SendQ exceeded");
572 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
576 if (data.length() > 512)
578 std::string newdata(data);
580 newdata.append("\r\n");
581 sendq.append(newdata);
589 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
590 void userrec::FlushWriteBuf()
592 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
594 const char* tb = this->sendq.c_str();
595 int n_sent = write(this->fd,tb,this->sendq.length());
599 this->SetWriteError(strerror(errno));
606 // update the user's stats counters
607 this->bytes_out += n_sent;
613 void userrec::SetWriteError(const std::string &error)
615 ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
616 // don't try to set the error twice, its already set take the first string.
617 if (!this->WriteError.length())
619 ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
620 this->WriteError = error;
624 const char* userrec::GetWriteError()
626 return this->WriteError.c_str();
629 void userrec::Oper(const std::string &opertype)
631 this->modes[UM_OPERATOR] = 1;
632 this->WriteServ("MODE %s :+o", this->nick);
633 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
634 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
635 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
636 ServerInstance->all_opers.push_back(this);
637 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
640 void userrec::UnOper()
645 this->modes[UM_OPERATOR] = 0;
646 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
650 ServerInstance->Log(DEBUG,"Oper removed from optimization list");
651 ServerInstance->all_opers.erase(a);
658 void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quitreason)
660 user_hash::iterator iter = Instance->clientlist.find(user->nick);
663 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
664 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
666 * I can't imagine this blowing up, so I'm commenting it out. We still check
667 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
669 * if (iter == clientlist.end())
672 std::string reason = quitreason;
674 if (reason.length() > MAXQUIT - 1)
675 reason.resize(MAXQUIT - 1);
678 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
680 if (user->registered == REG_ALL)
682 user->PurgeEmptyChannels();
683 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
684 user->WriteCommonExcept("QUIT :%s",reason.c_str());
688 user->FlushWriteBuf();
690 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
694 if (Instance->Config->GetIOHook(user->GetPort()))
698 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
700 catch (ModuleException& modexcept)
702 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
706 Instance->SE->DelFd(user);
711 * this must come before the ServerInstance->WriteOpers so that it doesnt try to fill their buffer with anything
712 * if they were an oper with +s.
715 * In the current implementation, we only show local quits, as we only show local connects. With
716 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
718 if (user->registered == REG_ALL)
721 Instance->WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
725 if (iter != Instance->clientlist.end())
727 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
730 if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
731 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
733 Instance->clientlist.erase(iter);
743 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
745 this->host = strdup(user->host);
746 this->dhost = strdup(user->dhost);
747 this->ident = strdup(user->ident);
748 this->server = user->server;
749 this->gecos = strdup(user->fullname);
752 WhoWasGroup::~WhoWasGroup()
764 /* every hour, run this function which removes all entries over 3 days */
765 void MaintainWhoWas(time_t t)
767 for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
769 whowas_set* n = (whowas_set*)iter->second;
772 while ((n->begin() != n->end()) && ((*n->begin())->signon < t - 259200)) // 3 days
774 WhoWasGroup *a = *(n->begin());
776 n->erase(n->begin());
784 /* adds or updates an entry in the whowas list */
785 void userrec::AddToWhoWas()
787 irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
789 if (iter == whowas.end())
791 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
792 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
794 whowas[this->nick] = n;
798 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
800 if (group->size() > 10)
802 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
807 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
812 /* add a client connection to the sockets list */
813 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
815 std::string tempnick = ConvToStr(socket) + "-unknown";
816 user_hash::iterator iter = Instance->clientlist.find(tempnick);
817 const char *ipaddr = insp_ntoa(ip);
823 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
824 * using one as a registered connection. As they are per fd, we can also safely assume
825 * that we wont have collisions. Therefore, if the nick exists in the list, its only
826 * used by a dead socket, erase the iterator so that the new client may reclaim it.
827 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
828 * issue in earlier alphas/betas
830 if (iter != Instance->clientlist.end())
832 userrec* goner = iter->second;
834 Instance->clientlist.erase(iter);
837 Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
839 _new = new userrec(Instance);
840 Instance->clientlist[tempnick] = _new;
842 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
844 _new->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
845 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
846 strcpy(_new->ident, "unknown");
848 _new->registered = REG_NONE;
849 _new->signon = Instance->Time() + Instance->Config->dns_timeout;
852 Instance->Log(DEBUG,"Setting socket addresses");
853 _new->SetSockAddr(AF_FAMILY, ipaddr, port);
854 Instance->Log(DEBUG,"Socket addresses set.");
856 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
857 for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
858 _new->dhost[j] = _new->host[j] = *temp;
859 _new->dhost[j] = _new->host[j] = 0;
861 // set the registration timeout for this user
862 unsigned long class_regtimeout = 90;
864 long class_threshold = 5;
865 long class_sqmax = 262144; // 256kb
866 long class_rqmax = 4096; // 4k
868 for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
870 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
872 class_regtimeout = (unsigned long)i->registration_timeout;
873 class_flood = i->flood;
874 _new->pingmax = i->pingtime;
875 class_threshold = i->threshold;
876 class_sqmax = i->sendqmax;
877 class_rqmax = i->recvqmax;
882 _new->nping = Instance->Time() + _new->pingmax + Instance->Config->dns_timeout;
883 _new->timeout = Instance->Time() + class_regtimeout;
884 _new->flood = class_flood;
885 _new->threshold = class_threshold;
886 _new->sendqmax = class_sqmax;
887 _new->recvqmax = class_rqmax;
889 Instance->local_users.push_back(_new);
891 if (Instance->local_users.size() > Instance->Config->SoftLimit)
893 userrec::QuitUser(Instance, _new,"No more connections allowed");
897 if (Instance->local_users.size() >= MAXCLIENTS)
899 userrec::QuitUser(Instance, _new,"No more connections allowed");
905 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
906 * its a pretty big but for the moment valid assumption:
907 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
908 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
909 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
910 * which for the time being is a physical impossibility (even the largest networks dont have more
911 * than about 10,000 users on ONE server!)
913 if ((unsigned)socket >= MAX_DESCRIPTORS)
915 userrec::QuitUser(Instance, _new,"Server is full");
918 char* e = Instance->XLines->matches_exception(ipaddr);
921 char* r = Instance->XLines->matches_zline(ipaddr);
925 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
926 userrec::QuitUser(Instance, _new,reason);
933 if (!Instance->SE->AddFd(_new))
935 userrec::QuitUser(Instance, _new, "Internal error handling connection");
940 _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
943 long userrec::GlobalCloneCount()
948 for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
950 /* We have to match ip's as strings - we don't know what protocol
951 * a remote user may be using
953 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
959 long userrec::LocalCloneCount()
962 for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
966 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
967 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
968 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
969 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
972 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
973 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
974 if (s1->s_addr == s2->s_addr)
981 void userrec::FullConnect(CullList* Goners)
983 ServerInstance->stats->statsConnects++;
984 this->idle_lastmsg = ServerInstance->Time();
986 ConnectClass a = this->GetClass();
988 if (a.type == CC_DENY)
990 Goners->AddItem(this,"Unauthorised connection");
994 if ((*(a.pass.c_str())) && (!this->haspassed))
996 Goners->AddItem(this,"Invalid password");
1000 if (this->LocalCloneCount() > a.maxlocal)
1002 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1003 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
1006 else if (this->GlobalCloneCount() > a.maxglobal)
1008 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1009 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1013 char match_against[MAXBUF];
1014 snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
1015 char* e = ServerInstance->XLines->matches_exception(match_against);
1019 char* r = ServerInstance->XLines->matches_gline(match_against);
1023 char reason[MAXBUF];
1024 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1025 Goners->AddItem(this, reason);
1029 r = ServerInstance->XLines->matches_kline(match_against);
1033 char reason[MAXBUF];
1034 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1035 Goners->AddItem(this, reason);
1041 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1042 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1043 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1044 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1045 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());
1047 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1048 // so i'd better split it :)
1049 std::stringstream out(ServerInstance->Config->data005);
1050 std::string token = "";
1051 std::string line5 = "";
1052 int token_counter = 0;
1057 line5 = line5 + token + " ";
1060 if ((token_counter >= 13) || (out.eof() == true))
1062 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1071 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1072 * changes dont go out onto the network and produce 'fake direction'.
1074 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1075 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1076 this->registered = REG_ALL;
1077 ServerInstance->WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1080 /** userrec::UpdateNick()
1081 * re-allocates a nick in the user_hash after they change nicknames,
1082 * returns a pointer to the new user as it may have moved
1084 userrec* userrec::UpdateNickHash(const char* New)
1086 //user_hash::iterator newnick;
1087 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1089 if (!strcasecmp(this->nick,New))
1090 return oldnick->second;
1092 if (oldnick == ServerInstance->clientlist.end())
1093 return NULL; /* doesnt exist */
1095 userrec* olduser = oldnick->second;
1096 ServerInstance->clientlist[New] = olduser;
1097 ServerInstance->clientlist.erase(oldnick);
1098 return ServerInstance->clientlist[New];
1101 bool userrec::ForceNickChange(const char* newnick)
1108 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1112 ServerInstance->stats->statsCollisions++;
1116 if (ServerInstance->XLines->matches_qline(newnick))
1118 ServerInstance->stats->statsCollisions++;
1124 strlcpy(this->nick, newnick, NICKMAX - 1);
1126 if (this->registered == REG_ALL)
1128 const char* pars[1];
1130 std::string cmd = "NICK";
1131 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1136 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1138 switch (protocol_family)
1140 #ifdef SUPPORT_IP6LINKS
1143 ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1144 sockaddr_in6* sin = new sockaddr_in6;
1145 sin->sin6_family = AF_INET6;
1146 sin->sin6_port = port;
1147 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1148 this->ip = (sockaddr*)sin;
1154 ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1155 sockaddr_in* sin = new sockaddr_in;
1156 sin->sin_family = AF_INET;
1157 sin->sin_port = port;
1158 inet_pton(AF_INET, ip, &sin->sin_addr);
1159 this->ip = (sockaddr*)sin;
1163 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1168 int userrec::GetPort()
1170 if (this->ip == NULL)
1173 switch (this->GetProtocolFamily())
1175 #ifdef SUPPORT_IP6LINKS
1178 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1179 return sin->sin6_port;
1185 sockaddr_in* sin = (sockaddr_in*)this->ip;
1186 return sin->sin_port;
1190 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1196 int userrec::GetProtocolFamily()
1198 if (this->ip == NULL)
1201 sockaddr_in* sin = (sockaddr_in*)this->ip;
1202 return sin->sin_family;
1205 const char* userrec::GetIPString()
1207 static char buf[1024];
1209 if (this->ip == NULL)
1212 switch (this->GetProtocolFamily())
1214 #ifdef SUPPORT_IP6LINKS
1217 static char temp[1024];
1219 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1220 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1221 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1224 strlcpy(&temp[1], buf, sizeof(temp));
1234 sockaddr_in* sin = (sockaddr_in*)this->ip;
1235 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1240 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1246 const char* userrec::GetIPString(char* buf)
1248 if (this->ip == NULL)
1254 switch (this->GetProtocolFamily())
1256 #ifdef SUPPORT_IP6LINKS
1259 static char temp[1024];
1261 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1262 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1263 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1266 strlcpy(&temp[1], buf, sizeof(temp));
1268 strlcpy(buf, temp, sizeof(temp));
1276 sockaddr_in* sin = (sockaddr_in*)this->ip;
1277 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1283 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1289 /** NOTE: We cannot pass a const reference to this method.
1290 * The string is changed by the workings of the method,
1291 * so that if we pass const ref, we end up copying it to
1292 * something we can change anyway. Makes sense to just let
1293 * the compiler do that copy for us.
1295 void userrec::Write(std::string text)
1297 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1300 text.append("\r\n");
1302 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1306 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1308 catch (ModuleException& modexcept)
1310 ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1315 this->AddWriteBuf(text);
1317 ServerInstance->stats->statsSent += text.length();
1322 void userrec::Write(const char *text, ...)
1325 char textbuffer[MAXBUF];
1327 va_start(argsPtr, text);
1328 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1331 this->Write(std::string(textbuffer));
1334 void userrec::WriteServ(const std::string& text)
1336 char textbuffer[MAXBUF];
1338 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1339 this->Write(std::string(textbuffer));
1343 * Same as Write(), except `text' is prefixed with `:server.name '.
1345 void userrec::WriteServ(const char* text, ...)
1348 char textbuffer[MAXBUF];
1350 va_start(argsPtr, text);
1351 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1354 this->WriteServ(std::string(textbuffer));
1358 void userrec::WriteFrom(userrec *user, const std::string &text)
1362 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1364 this->Write(std::string(tb));
1368 /* write text from an originating user to originating user */
1370 void userrec::WriteFrom(userrec *user, const char* text, ...)
1373 char textbuffer[MAXBUF];
1375 va_start(argsPtr, text);
1376 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1379 this->WriteFrom(user, std::string(textbuffer));
1383 /* write text to an destination user from a source user (e.g. user privmsg) */
1385 void userrec::WriteTo(userrec *dest, const char *data, ...)
1387 char textbuffer[MAXBUF];
1390 va_start(argsPtr, data);
1391 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1394 this->WriteTo(dest, std::string(textbuffer));
1397 void userrec::WriteTo(userrec *dest, const std::string &data)
1399 dest->WriteFrom(this, data);
1403 void userrec::WriteCommon(const char* text, ...)
1405 char textbuffer[MAXBUF];
1408 if (this->registered != REG_ALL)
1411 va_start(argsPtr, text);
1412 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1415 this->WriteCommon(std::string(textbuffer));
1418 void userrec::WriteCommon(const std::string &text)
1420 bool sent_to_at_least_one = false;
1422 if (this->registered != REG_ALL)
1427 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1432 CUList *ulist= n->channel->GetUsers();
1434 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1436 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1438 already_sent[i->second->fd] = uniq_id;
1439 i->second->WriteFrom(this, std::string(text));
1440 sent_to_at_least_one = true;
1447 * if the user was not in any channels, no users will receive the text. Make sure the user
1448 * receives their OWN message for WriteCommon
1450 if (!sent_to_at_least_one)
1452 this->WriteFrom(this,std::string(text));
1457 /* write a formatted string to all users who share at least one common
1458 * channel, NOT including the source user e.g. for use in QUIT
1461 void userrec::WriteCommonExcept(const char* text, ...)
1463 char textbuffer[MAXBUF];
1466 va_start(argsPtr, text);
1467 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1470 this->WriteCommonExcept(std::string(textbuffer));
1473 void userrec::WriteCommonExcept(const std::string &text)
1475 bool quit_munge = false;
1476 char oper_quit[MAXBUF];
1477 char textbuffer[MAXBUF];
1479 strlcpy(textbuffer, text.c_str(), MAXBUF);
1481 if (this->registered != REG_ALL)
1486 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1487 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1490 if (ServerInstance->Config->HideSplits)
1492 char* check = textbuffer + 6;
1494 if (!strncasecmp(textbuffer, "QUIT :",6))
1496 std::stringstream split(check);
1497 std::string server_one;
1498 std::string server_two;
1500 split >> server_one;
1501 split >> server_two;
1503 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1505 strlcpy(oper_quit,textbuffer,MAXQUIT);
1506 strlcpy(check,"*.net *.split",MAXQUIT);
1512 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1514 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1515 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1517 char* check = textbuffer + 13;
1518 strlcpy(oper_quit,textbuffer,MAXQUIT);
1519 *check = 0; // We don't need to strlcpy, we just chop it from the :
1524 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1529 CUList *ulist= n->channel->GetUsers();
1531 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1533 if (this != i->second)
1535 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1537 already_sent[i->second->fd] = uniq_id;
1539 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1541 i->second->WriteFrom(this, std::string(textbuffer));
1550 void userrec::WriteWallOps(const std::string &text)
1552 /* Does nothing if theyre not opered */
1553 if ((!*this->oper) && (IS_LOCAL(this)))
1556 std::string wallop = "WALLOPS :";
1557 wallop.append(text);
1559 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1562 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1563 this->WriteTo(t,wallop);
1567 void userrec::WriteWallOps(const char* text, ...)
1569 char textbuffer[MAXBUF];
1572 va_start(argsPtr, text);
1573 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1576 this->WriteWallOps(std::string(textbuffer));
1579 /* return 0 or 1 depending if users u and u2 share one or more common channels
1580 * (used by QUIT, NICK etc which arent channel specific notices)
1582 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1583 * the first users channels then the second users channels within the outer loop,
1584 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1585 * all possible iterations). However this new function instead checks against the
1586 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1587 * and saves us time as we already know what pointer value we are after.
1588 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1589 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1591 bool userrec::SharesChannelWith(userrec *other)
1593 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1597 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1599 /* Fetch the channel from the user */
1600 ucrec* user_channel = *i;
1602 if (user_channel->channel)
1604 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1605 * by replacing it with a map::find which *should* be more efficient
1607 if (user_channel->channel->HasUser(other))
1614 int userrec::CountChannels()
1617 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1623 bool userrec::ChangeName(const char* gecos)
1628 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1631 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1633 strlcpy(this->fullname,gecos,MAXGECOS+1);
1637 bool userrec::ChangeDisplayedHost(const char* host)
1642 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1645 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1647 if (this->ServerInstance->Config->CycleHosts)
1648 this->WriteCommonExcept("%s","QUIT :Changing hosts");
1650 strlcpy(this->dhost,host,63);
1652 if (this->ServerInstance->Config->CycleHosts)
1654 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1658 (*i)->channel->WriteAllExceptSender(this, 0, "JOIN %s", (*i)->channel->name);
1659 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1661 (*i)->channel->WriteChannelWithServ(this->ServerInstance->Config->ServerName, "MODE %s +%s", (*i)->channel->name, n.c_str());
1667 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1672 bool userrec::ChangeIdent(const char* newident)
1674 if (this->ServerInstance->Config->CycleHosts)
1675 this->WriteCommonExcept("%s","QUIT :Changing ident");
1677 strlcpy(this->ident, newident, IDENTMAX+2);
1679 if (this->ServerInstance->Config->CycleHosts)
1681 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1685 (*i)->channel->WriteAllExceptSender(this, 0, "JOIN %s", (*i)->channel->name);
1686 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1688 (*i)->channel->WriteChannelWithServ(this->ServerInstance->Config->ServerName, "MODE %s +%s", (*i)->channel->name, n.c_str());
1696 void userrec::NoticeAll(char* text, ...)
1698 char textbuffer[MAXBUF];
1699 char formatbuffer[MAXBUF];
1702 va_start(argsPtr, text);
1703 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1706 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1708 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1711 t->WriteFrom(this, std::string(formatbuffer));
1716 std::string userrec::ChannelList(userrec* source)
1719 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1723 if(rec->channel && rec->channel->name)
1725 /* If the target is the same as the sender, let them see all their channels.
1726 * If the channel is NOT private/secret OR the user shares a common channel
1727 * If the user is an oper, and the <options:operspywhois> option is set.
1729 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1731 list.append(rec->channel->GetPrefixChar(this)).append(rec->channel->name).append(" ");
1738 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1741 std::ostringstream prefix;
1742 std::string::size_type start, pos, length;
1744 prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
1745 line = prefix.str();
1747 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1749 length = (pos == std::string::npos) ? cl.length() : pos;
1751 if (line.length() + length - start > 510)
1754 line = prefix.str();
1757 if(pos == std::string::npos)
1759 line.append(cl.substr(start, length - start));
1764 line.append(cl.substr(start, length - start + 1));
1775 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1776 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1777 * then their ip will be taken as 'priority' anyway, so for example,
1778 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1780 ConnectClass& userrec::GetClass()
1782 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1784 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1788 return *(ServerInstance->Config->Classes.begin());
1791 void userrec::PurgeEmptyChannels()
1793 std::vector<chanrec*> to_delete;
1795 // firstly decrement the count on each channel
1796 for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1801 uc->channel->RemoveAllPrefixes(this);
1802 if (uc->channel->DelUser(this) == 0)
1804 /* No users left in here, mark it for deletion */
1805 to_delete.push_back(uc->channel);
1811 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1813 chanrec* thischan = *n;
1814 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1815 if (i2 != ServerInstance->chanlist.end())
1817 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1819 ServerInstance->chanlist.erase(i2);
1826 void userrec::ShowMOTD()
1828 if (!ServerInstance->Config->MOTD.size())
1830 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1833 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1835 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
1836 this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
1838 this->WriteServ("376 %s :End of message of the day.", this->nick);
1841 void userrec::ShowRULES()
1843 if (!ServerInstance->Config->RULES.size())
1845 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1848 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1850 for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
1851 this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
1853 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1856 void userrec::HandleEvent(EventType et)
1858 /* WARNING: May delete this user! */
1859 ServerInstance->ProcessUser(this);