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 = "";
101 ServerInstance->Log(DEBUG,"Process notice masks");
105 ServerInstance->Log(DEBUG,"Process notice mask %c",*c);
116 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
118 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
120 if ((oldadding != adding) || (!output.length()))
121 output += (adding ? '+' : '-');
123 this->SetNoticeMask(*c, adding);
138 void userrec::StartDNSLookup()
140 ServerInstance->Log(DEBUG,"Commencing reverse lookup");
143 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
144 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
145 this->ServerInstance->AddResolver(res_reverse);
147 catch (ModuleException& e)
149 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
153 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
154 Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
157 this->bound_fd = user->GetFd();
160 void UserResolver::OnLookupComplete(const std::string &result)
162 if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
164 ServerInstance->Log(DEBUG,"Commencing forward lookup");
165 this->bound_user->stored_host = result;
168 /* Check we didnt time out */
169 if (this->bound_user->registered != REG_ALL)
171 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
172 this->ServerInstance->AddResolver(bound_user->res_forward);
175 catch (ModuleException& e)
177 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
180 else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
182 /* Both lookups completed */
183 if (this->bound_user->GetIPString() == result)
185 std::string hostname = this->bound_user->stored_host;
186 if (hostname.length() < 65)
188 /* Check we didnt time out */
189 if (this->bound_user->registered != REG_ALL)
191 /* Hostnames starting with : are not a good thing (tm) */
192 if (*(hostname.c_str()) == ':')
193 hostname = "0" + hostname;
195 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
196 this->bound_user->dns_done = true;
197 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
198 strlcpy(this->bound_user->host, hostname.c_str(),64);
203 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());
208 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());
213 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
215 if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
217 /* Error message here */
218 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
219 this->bound_user->dns_done = true;
224 bool userrec::IsNoticeMaskSet(unsigned char sm)
226 return (snomasks[sm-65]);
229 void userrec::SetNoticeMask(unsigned char sm, bool value)
231 snomasks[sm-65] = value;
234 const char* userrec::FormatNoticeMasks()
236 static char data[MAXBUF];
239 for (int n = 0; n < 64; n++)
242 data[offset++] = n+65;
251 bool userrec::IsModeSet(unsigned char m)
253 return (modes[m-65]);
256 void userrec::SetMode(unsigned char m, bool value)
261 const char* userrec::FormatModes()
263 static char data[MAXBUF];
265 for (int n = 0; n < 64; n++)
268 data[offset++] = n+65;
274 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
276 ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
277 // the PROPER way to do it, AVOID bzero at *ALL* costs
278 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
279 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
280 reset_due = ServerInstance->Time();
281 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
282 timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
283 haspassed = dns_done = false;
288 res_forward = res_reverse = NULL;
292 chans.resize(MAXCHANS);
293 memset(modes,0,sizeof(modes));
294 memset(snomasks,0,sizeof(snomasks));
296 for (unsigned int n = 0; n < MAXCHANS; n++)
298 ucrec* x = new ucrec();
307 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
309 ucrec* x = (ucrec*)*n;
315 if (this->GetProtocolFamily() == AF_INET)
317 delete (sockaddr_in*)ip;
319 #ifdef SUPPORT_IP6LINKS
322 delete (sockaddr_in6*)ip;
328 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
329 void userrec::MakeHost(char* nhost)
331 /* This is much faster than snprintf */
333 for(char* n = ident; *n; n++)
336 for(char* n = host; *n; n++)
341 void userrec::CloseSocket()
343 shutdown(this->fd,2);
347 char* userrec::GetFullHost()
349 static char result[MAXBUF];
351 for(char* n = nick; *n; n++)
354 for(char* n = ident; *n; n++)
357 for(char* n = dhost; *n; n++)
363 char* userrec::MakeWildHost()
365 static char nresult[MAXBUF];
367 *t++ = '*'; *t++ = '!';
368 *t++ = '*'; *t++ = '@';
369 for(char* n = dhost; *n; n++)
375 int userrec::ReadData(void* buffer, size_t size)
379 return read(this->fd, buffer, size);
386 char* userrec::GetFullRealHost()
388 static char fresult[MAXBUF];
390 for(char* n = nick; *n; n++)
393 for(char* n = ident; *n; n++)
396 for(char* n = host; *n; n++)
402 bool userrec::IsInvited(irc::string &channel)
404 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
406 irc::string compare = i->channel;
408 if (compare == channel)
416 InvitedList* userrec::GetInviteList()
421 void userrec::InviteTo(irc::string &channel)
425 invites.push_back(i);
428 void userrec::RemoveInvite(irc::string &channel)
430 ServerInstance->Log(DEBUG,"Removing invites");
434 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
436 irc::string compare = i->channel;
438 if (compare == channel)
447 bool userrec::HasPermission(const std::string &command)
454 * users on remote servers can completely bypass all permissions based checks.
455 * This prevents desyncs when one server has different type/class tags to another.
456 * That having been said, this does open things up to the possibility of source changes
457 * allowing remote kills, etc - but if they have access to the src, they most likely have
458 * access to the conf - so it's an end to a means either way.
463 // are they even an oper at all?
466 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
467 if (iter_opertype != opertypes.end())
469 char* Classes = strdup(iter_opertype->second);
470 char* myclass = strtok_r(Classes," ",&savept);
473 operclass_t::iterator iter_operclass = operclass.find(myclass);
474 if (iter_operclass != operclass.end())
476 char* CommandList = strdup(iter_operclass->second);
477 mycmd = strtok_r(CommandList," ",&savept2);
480 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
486 mycmd = strtok_r(NULL," ",&savept2);
490 myclass = strtok_r(NULL," ",&savept);
498 /** NOTE: We cannot pass a const reference to this method.
499 * The string is changed by the workings of the method,
500 * so that if we pass const ref, we end up copying it to
501 * something we can change anyway. Makes sense to just let
502 * the compiler do that copy for us.
504 bool userrec::AddBuffer(std::string a)
506 std::string::size_type i = a.rfind('\r');
508 while (i != std::string::npos)
517 if (recvq.length() > (unsigned)this->recvqmax)
519 this->SetWriteError("RecvQ exceeded");
520 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
527 bool userrec::BufferIsReady()
529 return (recvq.find('\n') != std::string::npos);
532 void userrec::ClearBuffer()
537 std::string userrec::GetBuffer()
542 /* Strip any leading \r or \n off the string.
543 * Usually there are only one or two of these,
544 * so its is computationally cheap to do.
546 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
547 recvq.erase(recvq.begin());
549 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
551 /* Find the first complete line, return it as the
552 * result, and leave the recvq as whats left
556 std::string ret = std::string(recvq.begin(), x);
557 recvq.erase(recvq.begin(), x + 1);
564 void userrec::AddWriteBuf(const std::string &data)
566 if (*this->GetWriteError())
569 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
572 * Fix by brain - Set the error text BEFORE calling writeopers, because
573 * if we dont it'll recursively call here over and over again trying
574 * to repeatedly add the text to the sendq!
576 this->SetWriteError("SendQ exceeded");
577 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
581 if (data.length() > 512)
583 std::string newdata(data);
585 newdata.append("\r\n");
586 sendq.append(newdata);
594 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
595 void userrec::FlushWriteBuf()
597 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
599 const char* tb = this->sendq.c_str();
600 int n_sent = write(this->fd,tb,this->sendq.length());
604 this->SetWriteError(strerror(errno));
611 // update the user's stats counters
612 this->bytes_out += n_sent;
618 void userrec::SetWriteError(const std::string &error)
620 ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
621 // don't try to set the error twice, its already set take the first string.
622 if (!this->WriteError.length())
624 ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
625 this->WriteError = error;
629 const char* userrec::GetWriteError()
631 return this->WriteError.c_str();
634 void userrec::Oper(const std::string &opertype)
636 this->modes[UM_OPERATOR] = 1;
637 this->WriteServ("MODE %s :+o", this->nick);
638 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
639 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
640 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
641 ServerInstance->all_opers.push_back(this);
642 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
645 void userrec::UnOper()
650 this->modes[UM_OPERATOR] = 0;
651 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
655 ServerInstance->Log(DEBUG,"Oper removed from optimization list");
656 ServerInstance->all_opers.erase(a);
663 void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quitreason)
665 user_hash::iterator iter = Instance->clientlist.find(user->nick);
668 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
669 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
671 * I can't imagine this blowing up, so I'm commenting it out. We still check
672 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
674 * if (iter == clientlist.end())
677 std::string reason = quitreason;
679 if (reason.length() > MAXQUIT - 1)
680 reason.resize(MAXQUIT - 1);
683 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
685 if (user->registered == REG_ALL)
687 user->PurgeEmptyChannels();
688 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
689 user->WriteCommonExcept("QUIT :%s",reason.c_str());
693 user->FlushWriteBuf();
695 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
699 if (Instance->Config->GetIOHook(user->GetPort()))
703 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
705 catch (ModuleException& modexcept)
707 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
711 Instance->SE->DelFd(user);
716 * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
717 * if they were an oper with +sn +qQ.
719 if (user->registered == REG_ALL)
722 Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
724 Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
728 if (iter != Instance->clientlist.end())
730 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
733 if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
734 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
736 Instance->clientlist.erase(iter);
746 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
748 this->host = strdup(user->host);
749 this->dhost = strdup(user->dhost);
750 this->ident = strdup(user->ident);
751 this->server = user->server;
752 this->gecos = strdup(user->fullname);
755 WhoWasGroup::~WhoWasGroup()
767 /* every hour, run this function which removes all entries over 3 days */
768 void MaintainWhoWas(time_t t)
770 for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
772 whowas_set* n = (whowas_set*)iter->second;
775 while ((n->begin() != n->end()) && ((*n->begin())->signon < t - 259200)) // 3 days
777 WhoWasGroup *a = *(n->begin());
779 n->erase(n->begin());
787 /* adds or updates an entry in the whowas list */
788 void userrec::AddToWhoWas()
790 irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
792 if (iter == whowas.end())
794 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
795 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
797 whowas[this->nick] = n;
801 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
803 if (group->size() > 10)
805 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
810 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
815 /* add a client connection to the sockets list */
816 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
818 std::string tempnick = ConvToStr(socket) + "-unknown";
819 user_hash::iterator iter = Instance->clientlist.find(tempnick);
820 const char *ipaddr = insp_ntoa(ip);
826 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
827 * using one as a registered connection. As they are per fd, we can also safely assume
828 * that we wont have collisions. Therefore, if the nick exists in the list, its only
829 * used by a dead socket, erase the iterator so that the new client may reclaim it.
830 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
831 * issue in earlier alphas/betas
833 if (iter != Instance->clientlist.end())
835 userrec* goner = iter->second;
837 Instance->clientlist.erase(iter);
840 Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
842 _new = new userrec(Instance);
843 Instance->clientlist[tempnick] = _new;
845 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
847 _new->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
848 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
849 strcpy(_new->ident, "unknown");
851 _new->registered = REG_NONE;
852 _new->signon = Instance->Time() + Instance->Config->dns_timeout;
855 Instance->Log(DEBUG,"Setting socket addresses");
856 _new->SetSockAddr(AF_FAMILY, ipaddr, port);
857 Instance->Log(DEBUG,"Socket addresses set.");
859 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
860 for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
861 _new->dhost[j] = _new->host[j] = *temp;
862 _new->dhost[j] = _new->host[j] = 0;
864 // set the registration timeout for this user
865 unsigned long class_regtimeout = 90;
867 long class_threshold = 5;
868 long class_sqmax = 262144; // 256kb
869 long class_rqmax = 4096; // 4k
871 for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
873 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
875 class_regtimeout = (unsigned long)i->registration_timeout;
876 class_flood = i->flood;
877 _new->pingmax = i->pingtime;
878 class_threshold = i->threshold;
879 class_sqmax = i->sendqmax;
880 class_rqmax = i->recvqmax;
885 _new->nping = Instance->Time() + _new->pingmax + Instance->Config->dns_timeout;
886 _new->timeout = Instance->Time() + class_regtimeout;
887 _new->flood = class_flood;
888 _new->threshold = class_threshold;
889 _new->sendqmax = class_sqmax;
890 _new->recvqmax = class_rqmax;
892 Instance->local_users.push_back(_new);
894 if (Instance->local_users.size() > Instance->Config->SoftLimit)
896 userrec::QuitUser(Instance, _new,"No more connections allowed");
900 if (Instance->local_users.size() >= MAXCLIENTS)
902 userrec::QuitUser(Instance, _new,"No more connections allowed");
908 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
909 * its a pretty big but for the moment valid assumption:
910 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
911 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
912 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
913 * which for the time being is a physical impossibility (even the largest networks dont have more
914 * than about 10,000 users on ONE server!)
916 if ((unsigned)socket >= MAX_DESCRIPTORS)
918 userrec::QuitUser(Instance, _new,"Server is full");
921 char* e = Instance->XLines->matches_exception(ipaddr);
924 char* r = Instance->XLines->matches_zline(ipaddr);
928 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
929 userrec::QuitUser(Instance, _new,reason);
936 if (!Instance->SE->AddFd(_new))
938 userrec::QuitUser(Instance, _new, "Internal error handling connection");
943 _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
946 long userrec::GlobalCloneCount()
951 for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
953 /* We have to match ip's as strings - we don't know what protocol
954 * a remote user may be using
956 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
962 long userrec::LocalCloneCount()
965 for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
969 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
970 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
971 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
972 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
975 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
976 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
977 if (s1->s_addr == s2->s_addr)
984 void userrec::FullConnect(CullList* Goners)
986 ServerInstance->stats->statsConnects++;
987 this->idle_lastmsg = ServerInstance->Time();
989 ConnectClass a = this->GetClass();
991 if (a.type == CC_DENY)
993 Goners->AddItem(this,"Unauthorised connection");
997 if ((*(a.pass.c_str())) && (!this->haspassed))
999 Goners->AddItem(this,"Invalid password");
1003 if (this->LocalCloneCount() > a.maxlocal)
1005 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1006 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
1009 else if (this->GlobalCloneCount() > a.maxglobal)
1011 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1012 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1016 char match_against[MAXBUF];
1017 snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
1018 char* e = ServerInstance->XLines->matches_exception(match_against);
1022 char* r = ServerInstance->XLines->matches_gline(match_against);
1026 char reason[MAXBUF];
1027 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1028 Goners->AddItem(this, reason);
1032 r = ServerInstance->XLines->matches_kline(match_against);
1036 char reason[MAXBUF];
1037 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1038 Goners->AddItem(this, reason);
1044 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1045 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1046 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1047 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1048 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());
1050 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1051 // so i'd better split it :)
1052 std::stringstream out(ServerInstance->Config->data005);
1053 std::string token = "";
1054 std::string line5 = "";
1055 int token_counter = 0;
1060 line5 = line5 + token + " ";
1063 if ((token_counter >= 13) || (out.eof() == true))
1065 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1074 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1075 * changes dont go out onto the network and produce 'fake direction'.
1077 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1078 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1079 this->registered = REG_ALL;
1080 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1083 /** userrec::UpdateNick()
1084 * re-allocates a nick in the user_hash after they change nicknames,
1085 * returns a pointer to the new user as it may have moved
1087 userrec* userrec::UpdateNickHash(const char* New)
1089 //user_hash::iterator newnick;
1090 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1092 if (!strcasecmp(this->nick,New))
1093 return oldnick->second;
1095 if (oldnick == ServerInstance->clientlist.end())
1096 return NULL; /* doesnt exist */
1098 userrec* olduser = oldnick->second;
1099 ServerInstance->clientlist[New] = olduser;
1100 ServerInstance->clientlist.erase(oldnick);
1101 return ServerInstance->clientlist[New];
1104 bool userrec::ForceNickChange(const char* newnick)
1111 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1115 ServerInstance->stats->statsCollisions++;
1119 if (ServerInstance->XLines->matches_qline(newnick))
1121 ServerInstance->stats->statsCollisions++;
1127 strlcpy(this->nick, newnick, NICKMAX - 1);
1129 if (this->registered == REG_ALL)
1131 const char* pars[1];
1133 std::string cmd = "NICK";
1134 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1139 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1141 switch (protocol_family)
1143 #ifdef SUPPORT_IP6LINKS
1146 ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1147 sockaddr_in6* sin = new sockaddr_in6;
1148 sin->sin6_family = AF_INET6;
1149 sin->sin6_port = port;
1150 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1151 this->ip = (sockaddr*)sin;
1157 ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1158 sockaddr_in* sin = new sockaddr_in;
1159 sin->sin_family = AF_INET;
1160 sin->sin_port = port;
1161 inet_pton(AF_INET, ip, &sin->sin_addr);
1162 this->ip = (sockaddr*)sin;
1166 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1171 int userrec::GetPort()
1173 if (this->ip == NULL)
1176 switch (this->GetProtocolFamily())
1178 #ifdef SUPPORT_IP6LINKS
1181 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1182 return sin->sin6_port;
1188 sockaddr_in* sin = (sockaddr_in*)this->ip;
1189 return sin->sin_port;
1193 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1199 int userrec::GetProtocolFamily()
1201 if (this->ip == NULL)
1204 sockaddr_in* sin = (sockaddr_in*)this->ip;
1205 return sin->sin_family;
1208 const char* userrec::GetIPString()
1210 static char buf[1024];
1212 if (this->ip == NULL)
1215 switch (this->GetProtocolFamily())
1217 #ifdef SUPPORT_IP6LINKS
1220 static char temp[1024];
1222 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1223 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1224 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1227 strlcpy(&temp[1], buf, sizeof(temp));
1237 sockaddr_in* sin = (sockaddr_in*)this->ip;
1238 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1243 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1249 const char* userrec::GetIPString(char* buf)
1251 if (this->ip == NULL)
1257 switch (this->GetProtocolFamily())
1259 #ifdef SUPPORT_IP6LINKS
1262 static char temp[1024];
1264 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1265 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1266 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1269 strlcpy(&temp[1], buf, sizeof(temp));
1271 strlcpy(buf, temp, sizeof(temp));
1279 sockaddr_in* sin = (sockaddr_in*)this->ip;
1280 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1286 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1292 /** NOTE: We cannot pass a const reference to this method.
1293 * The string is changed by the workings of the method,
1294 * so that if we pass const ref, we end up copying it to
1295 * something we can change anyway. Makes sense to just let
1296 * the compiler do that copy for us.
1298 void userrec::Write(std::string text)
1300 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1303 text.append("\r\n");
1305 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1309 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1311 catch (ModuleException& modexcept)
1313 ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1318 this->AddWriteBuf(text);
1320 ServerInstance->stats->statsSent += text.length();
1325 void userrec::Write(const char *text, ...)
1328 char textbuffer[MAXBUF];
1330 va_start(argsPtr, text);
1331 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1334 this->Write(std::string(textbuffer));
1337 void userrec::WriteServ(const std::string& text)
1339 char textbuffer[MAXBUF];
1341 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1342 this->Write(std::string(textbuffer));
1346 * Same as Write(), except `text' is prefixed with `:server.name '.
1348 void userrec::WriteServ(const char* text, ...)
1351 char textbuffer[MAXBUF];
1353 va_start(argsPtr, text);
1354 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1357 this->WriteServ(std::string(textbuffer));
1361 void userrec::WriteFrom(userrec *user, const std::string &text)
1365 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1367 this->Write(std::string(tb));
1371 /* write text from an originating user to originating user */
1373 void userrec::WriteFrom(userrec *user, const char* text, ...)
1376 char textbuffer[MAXBUF];
1378 va_start(argsPtr, text);
1379 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1382 this->WriteFrom(user, std::string(textbuffer));
1386 /* write text to an destination user from a source user (e.g. user privmsg) */
1388 void userrec::WriteTo(userrec *dest, const char *data, ...)
1390 char textbuffer[MAXBUF];
1393 va_start(argsPtr, data);
1394 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1397 this->WriteTo(dest, std::string(textbuffer));
1400 void userrec::WriteTo(userrec *dest, const std::string &data)
1402 dest->WriteFrom(this, data);
1406 void userrec::WriteCommon(const char* text, ...)
1408 char textbuffer[MAXBUF];
1411 if (this->registered != REG_ALL)
1414 va_start(argsPtr, text);
1415 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1418 this->WriteCommon(std::string(textbuffer));
1421 void userrec::WriteCommon(const std::string &text)
1423 bool sent_to_at_least_one = false;
1425 if (this->registered != REG_ALL)
1430 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1435 CUList *ulist= n->channel->GetUsers();
1437 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1439 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1441 already_sent[i->second->fd] = uniq_id;
1442 i->second->WriteFrom(this, std::string(text));
1443 sent_to_at_least_one = true;
1450 * if the user was not in any channels, no users will receive the text. Make sure the user
1451 * receives their OWN message for WriteCommon
1453 if (!sent_to_at_least_one)
1455 this->WriteFrom(this,std::string(text));
1460 /* write a formatted string to all users who share at least one common
1461 * channel, NOT including the source user e.g. for use in QUIT
1464 void userrec::WriteCommonExcept(const char* text, ...)
1466 char textbuffer[MAXBUF];
1469 va_start(argsPtr, text);
1470 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1473 this->WriteCommonExcept(std::string(textbuffer));
1476 void userrec::WriteCommonExcept(const std::string &text)
1478 bool quit_munge = false;
1479 char oper_quit[MAXBUF];
1480 char textbuffer[MAXBUF];
1482 strlcpy(textbuffer, text.c_str(), MAXBUF);
1484 if (this->registered != REG_ALL)
1489 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1490 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1493 if (ServerInstance->Config->HideSplits)
1495 char* check = textbuffer + 6;
1497 if (!strncasecmp(textbuffer, "QUIT :",6))
1499 std::stringstream split(check);
1500 std::string server_one;
1501 std::string server_two;
1503 split >> server_one;
1504 split >> server_two;
1506 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1508 strlcpy(oper_quit,textbuffer,MAXQUIT);
1509 strlcpy(check,"*.net *.split",MAXQUIT);
1515 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1517 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1518 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1520 char* check = textbuffer + 13;
1521 strlcpy(oper_quit,textbuffer,MAXQUIT);
1522 *check = 0; // We don't need to strlcpy, we just chop it from the :
1527 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1532 CUList *ulist= n->channel->GetUsers();
1534 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1536 if (this != i->second)
1538 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1540 already_sent[i->second->fd] = uniq_id;
1542 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1544 i->second->WriteFrom(this, std::string(textbuffer));
1553 void userrec::WriteWallOps(const std::string &text)
1555 /* Does nothing if theyre not opered */
1556 if ((!*this->oper) && (IS_LOCAL(this)))
1559 std::string wallop = "WALLOPS :";
1560 wallop.append(text);
1562 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1565 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1566 this->WriteTo(t,wallop);
1570 void userrec::WriteWallOps(const char* text, ...)
1572 char textbuffer[MAXBUF];
1575 va_start(argsPtr, text);
1576 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1579 this->WriteWallOps(std::string(textbuffer));
1582 /* return 0 or 1 depending if users u and u2 share one or more common channels
1583 * (used by QUIT, NICK etc which arent channel specific notices)
1585 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1586 * the first users channels then the second users channels within the outer loop,
1587 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1588 * all possible iterations). However this new function instead checks against the
1589 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1590 * and saves us time as we already know what pointer value we are after.
1591 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1592 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1594 bool userrec::SharesChannelWith(userrec *other)
1596 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1600 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1602 /* Fetch the channel from the user */
1603 ucrec* user_channel = *i;
1605 if (user_channel->channel)
1607 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1608 * by replacing it with a map::find which *should* be more efficient
1610 if (user_channel->channel->HasUser(other))
1617 int userrec::CountChannels()
1620 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1626 bool userrec::ChangeName(const char* gecos)
1631 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1634 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1636 strlcpy(this->fullname,gecos,MAXGECOS+1);
1640 bool userrec::ChangeDisplayedHost(const char* host)
1645 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1648 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1650 if (this->ServerInstance->Config->CycleHosts)
1651 this->WriteCommonExcept("%s","QUIT :Changing hosts");
1653 strlcpy(this->dhost,host,63);
1655 if (this->ServerInstance->Config->CycleHosts)
1657 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1661 (*i)->channel->WriteAllExceptSender(this, 0, "JOIN %s", (*i)->channel->name);
1662 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1664 (*i)->channel->WriteChannelWithServ(this->ServerInstance->Config->ServerName, "MODE %s +%s", (*i)->channel->name, n.c_str());
1670 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1675 bool userrec::ChangeIdent(const char* newident)
1677 if (this->ServerInstance->Config->CycleHosts)
1678 this->WriteCommonExcept("%s","QUIT :Changing ident");
1680 strlcpy(this->ident, newident, IDENTMAX+2);
1682 if (this->ServerInstance->Config->CycleHosts)
1684 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1688 (*i)->channel->WriteAllExceptSender(this, 0, "JOIN %s", (*i)->channel->name);
1689 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1691 (*i)->channel->WriteChannelWithServ(this->ServerInstance->Config->ServerName, "MODE %s +%s", (*i)->channel->name, n.c_str());
1699 void userrec::NoticeAll(char* text, ...)
1701 char textbuffer[MAXBUF];
1702 char formatbuffer[MAXBUF];
1705 va_start(argsPtr, text);
1706 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1709 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1711 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1714 t->WriteFrom(this, std::string(formatbuffer));
1719 std::string userrec::ChannelList(userrec* source)
1722 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1726 if(rec->channel && rec->channel->name)
1728 /* If the target is the same as the sender, let them see all their channels.
1729 * If the channel is NOT private/secret OR the user shares a common channel
1730 * If the user is an oper, and the <options:operspywhois> option is set.
1732 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1734 list.append(rec->channel->GetPrefixChar(this)).append(rec->channel->name).append(" ");
1741 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1744 std::ostringstream prefix;
1745 std::string::size_type start, pos, length;
1747 prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
1748 line = prefix.str();
1750 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1752 length = (pos == std::string::npos) ? cl.length() : pos;
1754 if (line.length() + length - start > 510)
1757 line = prefix.str();
1760 if(pos == std::string::npos)
1762 line.append(cl.substr(start, length - start));
1767 line.append(cl.substr(start, length - start + 1));
1778 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1779 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1780 * then their ip will be taken as 'priority' anyway, so for example,
1781 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1783 ConnectClass& userrec::GetClass()
1785 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1787 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1791 return *(ServerInstance->Config->Classes.begin());
1794 void userrec::PurgeEmptyChannels()
1796 std::vector<chanrec*> to_delete;
1798 // firstly decrement the count on each channel
1799 for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1804 uc->channel->RemoveAllPrefixes(this);
1805 if (uc->channel->DelUser(this) == 0)
1807 /* No users left in here, mark it for deletion */
1808 to_delete.push_back(uc->channel);
1814 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1816 chanrec* thischan = *n;
1817 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1818 if (i2 != ServerInstance->chanlist.end())
1820 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1822 ServerInstance->chanlist.erase(i2);
1829 void userrec::ShowMOTD()
1831 if (!ServerInstance->Config->MOTD.size())
1833 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1836 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1838 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
1839 this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
1841 this->WriteServ("376 %s :End of message of the day.", this->nick);
1844 void userrec::ShowRULES()
1846 if (!ServerInstance->Config->RULES.size())
1848 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1851 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1853 for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
1854 this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
1856 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1859 void userrec::HandleEvent(EventType et)
1861 /* WARNING: May delete this user! */
1862 ServerInstance->ProcessUser(this);