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 "configreader.h"
22 #include "socketengine.h"
25 #include "cull_list.h"
27 irc::whowas::whowas_users whowas;
28 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
30 typedef std::map<irc::string,char*> opertype_t;
31 typedef opertype_t operclass_t;
34 operclass_t operclass;
36 /* XXX: Used for speeding up WriteCommon operations */
37 unsigned long uniq_id = 0;
39 bool InitTypes(ServerConfig* conf, const char* tag)
41 for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
51 bool InitClasses(ServerConfig* conf, const char* tag)
53 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
63 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
65 char* TypeName = (char*)values[0];
66 char* Classes = (char*)values[1];
68 opertypes[TypeName] = strdup(Classes);
69 conf->GetInstance()->Log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
73 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
75 char* ClassName = (char*)values[0];
76 char* CommandList = (char*)values[1];
78 operclass[ClassName] = strdup(CommandList);
79 conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
83 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
88 std::string userrec::ProcessNoticeMasks(const char *sm)
90 bool adding = true, oldadding = false;
94 ServerInstance->Log(DEBUG,"Process notice masks");
98 ServerInstance->Log(DEBUG,"Process notice mask %c",*c);
109 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
111 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
113 if ((oldadding != adding) || (!output.length()))
114 output += (adding ? '+' : '-');
116 this->SetNoticeMask(*c, adding);
131 void userrec::StartDNSLookup()
133 ServerInstance->Log(DEBUG,"Commencing reverse lookup");
136 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
137 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
138 this->ServerInstance->AddResolver(res_reverse);
140 catch (ModuleException& e)
142 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
146 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
147 Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
150 this->bound_fd = user->GetFd();
153 void UserResolver::OnLookupComplete(const std::string &result)
155 if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
157 ServerInstance->Log(DEBUG,"Commencing forward lookup");
158 this->bound_user->stored_host = result;
161 /* Check we didnt time out */
162 if (this->bound_user->registered != REG_ALL)
164 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
165 this->ServerInstance->AddResolver(bound_user->res_forward);
168 catch (ModuleException& e)
170 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
173 else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
175 /* Both lookups completed */
176 if (this->bound_user->GetIPString() == result)
178 std::string hostname = this->bound_user->stored_host;
179 if (hostname.length() < 65)
181 /* Check we didnt time out */
182 if (this->bound_user->registered != REG_ALL)
184 /* Hostnames starting with : are not a good thing (tm) */
185 if (*(hostname.c_str()) == ':')
186 hostname = "0" + hostname;
188 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
189 this->bound_user->dns_done = true;
190 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
191 strlcpy(this->bound_user->host, hostname.c_str(),64);
196 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());
201 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());
206 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
208 if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
210 /* Error message here */
211 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
212 this->bound_user->dns_done = true;
217 bool userrec::IsNoticeMaskSet(unsigned char sm)
219 return (snomasks[sm-65]);
222 void userrec::SetNoticeMask(unsigned char sm, bool value)
224 snomasks[sm-65] = value;
227 const char* userrec::FormatNoticeMasks()
229 static char data[MAXBUF];
232 for (int n = 0; n < 64; n++)
235 data[offset++] = n+65;
244 bool userrec::IsModeSet(unsigned char m)
246 return (modes[m-65]);
249 void userrec::SetMode(unsigned char m, bool value)
254 const char* userrec::FormatModes()
256 static char data[MAXBUF];
258 for (int n = 0; n < 64; n++)
261 data[offset++] = n+65;
267 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
269 ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
270 // the PROPER way to do it, AVOID bzero at *ALL* costs
271 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
272 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
273 reset_due = ServerInstance->Time();
274 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
275 ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
276 haspassed = dns_done = false;
281 res_forward = res_reverse = NULL;
285 chans.resize(MAXCHANS);
286 memset(modes,0,sizeof(modes));
287 memset(snomasks,0,sizeof(snomasks));
289 for (unsigned int n = 0; n < MAXCHANS; n++)
291 ucrec* x = new ucrec();
300 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
302 ucrec* x = (ucrec*)*n;
308 if (this->GetProtocolFamily() == AF_INET)
310 delete (sockaddr_in*)ip;
312 #ifdef SUPPORT_IP6LINKS
315 delete (sockaddr_in6*)ip;
321 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
322 void userrec::MakeHost(char* nhost)
324 /* This is much faster than snprintf */
326 for(char* n = ident; *n; n++)
329 for(char* n = host; *n; n++)
334 void userrec::CloseSocket()
336 shutdown(this->fd,2);
340 char* userrec::GetFullHost()
342 static char result[MAXBUF];
344 for(char* n = nick; *n; n++)
347 for(char* n = ident; *n; n++)
350 for(char* n = dhost; *n; n++)
356 char* userrec::MakeWildHost()
358 static char nresult[MAXBUF];
360 *t++ = '*'; *t++ = '!';
361 *t++ = '*'; *t++ = '@';
362 for(char* n = dhost; *n; n++)
368 int userrec::ReadData(void* buffer, size_t size)
372 return read(this->fd, buffer, size);
379 char* userrec::GetFullRealHost()
381 static char fresult[MAXBUF];
383 for(char* n = nick; *n; n++)
386 for(char* n = ident; *n; n++)
389 for(char* n = host; *n; n++)
395 bool userrec::IsInvited(irc::string &channel)
397 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
399 irc::string compare = i->channel;
401 if (compare == channel)
409 InvitedList* userrec::GetInviteList()
414 void userrec::InviteTo(irc::string &channel)
418 invites.push_back(i);
421 void userrec::RemoveInvite(irc::string &channel)
423 ServerInstance->Log(DEBUG,"Removing invites");
427 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
429 irc::string compare = i->channel;
431 if (compare == channel)
440 bool userrec::HasPermission(const std::string &command)
447 * users on remote servers can completely bypass all permissions based checks.
448 * This prevents desyncs when one server has different type/class tags to another.
449 * That having been said, this does open things up to the possibility of source changes
450 * allowing remote kills, etc - but if they have access to the src, they most likely have
451 * access to the conf - so it's an end to a means either way.
456 // are they even an oper at all?
459 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
460 if (iter_opertype != opertypes.end())
462 char* Classes = strdup(iter_opertype->second);
463 char* myclass = strtok_r(Classes," ",&savept);
466 operclass_t::iterator iter_operclass = operclass.find(myclass);
467 if (iter_operclass != operclass.end())
469 char* CommandList = strdup(iter_operclass->second);
470 mycmd = strtok_r(CommandList," ",&savept2);
473 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
479 mycmd = strtok_r(NULL," ",&savept2);
483 myclass = strtok_r(NULL," ",&savept);
491 /** NOTE: We cannot pass a const reference to this method.
492 * The string is changed by the workings of the method,
493 * so that if we pass const ref, we end up copying it to
494 * something we can change anyway. Makes sense to just let
495 * the compiler do that copy for us.
497 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);
524 ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
529 bool userrec::BufferIsReady()
531 return (recvq.find('\n') != std::string::npos);
534 void userrec::ClearBuffer()
539 std::string userrec::GetBuffer()
546 /* Strip any leading \r or \n off the string.
547 * Usually there are only one or two of these,
548 * so its is computationally cheap to do.
550 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
551 recvq.erase(recvq.begin());
553 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
555 /* Find the first complete line, return it as the
556 * result, and leave the recvq as whats left
560 std::string ret = std::string(recvq.begin(), x);
561 recvq.erase(recvq.begin(), x + 1);
570 ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
575 void userrec::AddWriteBuf(const std::string &data)
577 if (*this->GetWriteError())
580 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
583 * Fix by brain - Set the error text BEFORE calling writeopers, because
584 * if we dont it'll recursively call here over and over again trying
585 * to repeatedly add the text to the sendq!
587 this->SetWriteError("SendQ exceeded");
588 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
594 if (data.length() > 512)
596 std::string newdata(data);
598 newdata.append("\r\n");
599 sendq.append(newdata);
608 this->SetWriteError("SendQ exceeded");
609 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
613 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
614 void userrec::FlushWriteBuf()
618 if (this->fd == FD_MAGIC_NUMBER)
622 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
624 const char* tb = this->sendq.c_str();
625 int n_sent = write(this->fd,tb,this->sendq.length());
629 this->SetWriteError(strerror(errno));
636 // update the user's stats counters
637 this->bytes_out += n_sent;
645 ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
649 void userrec::SetWriteError(const std::string &error)
653 ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
654 // don't try to set the error twice, its already set take the first string.
655 if (!this->WriteError.length())
657 ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
658 this->WriteError = error;
664 ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
668 const char* userrec::GetWriteError()
670 return this->WriteError.c_str();
673 void userrec::Oper(const std::string &opertype)
677 this->modes[UM_OPERATOR] = 1;
678 this->WriteServ("MODE %s :+o", this->nick);
679 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
680 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
681 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
682 ServerInstance->all_opers.push_back(this);
683 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
688 ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
692 void userrec::UnOper()
699 this->modes[UM_OPERATOR] = 0;
700 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
704 ServerInstance->Log(DEBUG,"Oper removed from optimization list");
705 ServerInstance->all_opers.erase(a);
714 ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
718 void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
720 user_hash::iterator iter = Instance->clientlist.find(user->nick);
721 std::string reason = quitreason;
723 if (reason.length() > MAXQUIT - 1)
724 reason.resize(MAXQUIT - 1);
727 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
729 if (user->registered == REG_ALL)
731 user->PurgeEmptyChannels();
732 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
733 user->WriteCommonExcept("QUIT :%s",reason.c_str());
737 user->FlushWriteBuf();
739 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
743 if (Instance->Config->GetIOHook(user->GetPort()))
747 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
749 catch (ModuleException& modexcept)
751 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
755 Instance->SE->DelFd(user);
760 * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
761 * if they were an oper with +sn +qQ.
763 if (user->registered == REG_ALL)
766 Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
768 Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
772 if (iter != Instance->clientlist.end())
774 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
777 if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
778 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
780 Instance->clientlist.erase(iter);
790 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
792 this->host = strdup(user->host);
793 this->dhost = strdup(user->dhost);
794 this->ident = strdup(user->ident);
795 this->server = user->server;
796 this->gecos = strdup(user->fullname);
799 WhoWasGroup::~WhoWasGroup()
811 /* every hour, run this function which removes all entries over 3 days */
812 void MaintainWhoWas(time_t t)
814 for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
816 whowas_set* n = (whowas_set*)iter->second;
819 while ((n->begin() != n->end()) && ((*n->begin())->signon < t - 259200)) // 3 days
821 WhoWasGroup *a = *(n->begin());
823 n->erase(n->begin());
831 /* adds or updates an entry in the whowas list */
832 void userrec::AddToWhoWas()
834 irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
836 if (iter == whowas.end())
838 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
839 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
841 whowas[this->nick] = n;
845 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
847 if (group->size() > 10)
849 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
854 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
859 /* add a client connection to the sockets list */
860 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
862 std::string tempnick = ConvToStr(socket) + "-unknown";
863 user_hash::iterator iter = Instance->clientlist.find(tempnick);
864 const char *ipaddr = insp_ntoa(ip);
870 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
871 * using one as a registered connection. As they are per fd, we can also safely assume
872 * that we wont have collisions. Therefore, if the nick exists in the list, its only
873 * used by a dead socket, erase the iterator so that the new client may reclaim it.
874 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
875 * issue in earlier alphas/betas
877 if (iter != Instance->clientlist.end())
879 userrec* goner = iter->second;
881 Instance->clientlist.erase(iter);
884 Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
886 New = new userrec(Instance);
887 Instance->clientlist[tempnick] = New;
889 strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
891 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
892 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
893 strcpy(New->ident, "unknown");
895 New->registered = REG_NONE;
896 New->signon = Instance->Time() + Instance->Config->dns_timeout;
899 Instance->Log(DEBUG,"Setting socket addresses");
900 New->SetSockAddr(AF_FAMILY, ipaddr, port);
901 Instance->Log(DEBUG,"Socket addresses set.");
903 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
904 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
905 New->dhost[j] = New->host[j] = *temp;
906 New->dhost[j] = New->host[j] = 0;
908 // set the registration timeout for this user
909 unsigned long class_regtimeout = 90;
911 long class_threshold = 5;
912 long class_sqmax = 262144; // 256kb
913 long class_rqmax = 4096; // 4k
915 for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
917 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
919 class_regtimeout = (unsigned long)i->registration_timeout;
920 class_flood = i->flood;
921 New->pingmax = i->pingtime;
922 class_threshold = i->threshold;
923 class_sqmax = i->sendqmax;
924 class_rqmax = i->recvqmax;
929 New->nping = Instance->Time() + New->pingmax + Instance->Config->dns_timeout;
930 New->timeout = Instance->Time() + class_regtimeout;
931 New->flood = class_flood;
932 New->threshold = class_threshold;
933 New->sendqmax = class_sqmax;
934 New->recvqmax = class_rqmax;
936 Instance->local_users.push_back(New);
938 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
940 userrec::QuitUser(Instance, New,"No more connections allowed");
946 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
947 * its a pretty big but for the moment valid assumption:
948 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
949 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
950 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
951 * which for the time being is a physical impossibility (even the largest networks dont have more
952 * than about 10,000 users on ONE server!)
954 if ((unsigned)socket >= MAX_DESCRIPTORS)
956 userrec::QuitUser(Instance, New, "Server is full");
960 ELine* e = Instance->XLines->matches_exception(New);
963 ZLine* r = Instance->XLines->matches_zline(ipaddr);
967 snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
968 userrec::QuitUser(Instance, New, reason);
975 if (!Instance->SE->AddFd(New))
977 userrec::QuitUser(Instance, New, "Internal error handling connection");
982 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
985 long userrec::GlobalCloneCount()
991 for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
993 /* We have to match ip's as strings - we don't know what protocol
994 * a remote user may be using
996 if (strcmp(a->second->GetIPString(u1), this->GetIPString(u2)) == 0)
1003 long userrec::LocalCloneCount()
1006 for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
1010 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
1011 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
1012 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
1013 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
1016 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
1017 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
1018 if (s1->s_addr == s2->s_addr)
1025 void userrec::FullConnect(CullList* Goners)
1027 ServerInstance->stats->statsConnects++;
1028 this->idle_lastmsg = ServerInstance->Time();
1030 ConnectClass a = this->GetClass();
1032 if (a.type == CC_DENY)
1034 Goners->AddItem(this,"Unauthorised connection");
1038 if ((*(a.pass.c_str())) && (!this->haspassed))
1040 Goners->AddItem(this,"Invalid password");
1044 if (this->LocalCloneCount() > a.maxlocal)
1046 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1047 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
1050 else if (this->GlobalCloneCount() > a.maxglobal)
1052 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1053 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1057 ELine* e = ServerInstance->XLines->matches_exception(this);
1061 GLine* r = ServerInstance->XLines->matches_gline(this);
1065 char reason[MAXBUF];
1066 snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
1067 Goners->AddItem(this, reason);
1071 KLine* n = ServerInstance->XLines->matches_kline(this);
1075 char reason[MAXBUF];
1076 snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
1077 Goners->AddItem(this, reason);
1083 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1084 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1085 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1086 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1087 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());
1089 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1090 // so i'd better split it :)
1091 std::stringstream out(ServerInstance->Config->data005);
1092 std::string token = "";
1093 std::string line5 = "";
1094 int token_counter = 0;
1099 line5 = line5 + token + " ";
1102 if ((token_counter >= 13) || (out.eof() == true))
1104 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1113 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1114 * changes dont go out onto the network and produce 'fake direction'.
1116 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1117 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1118 this->registered = REG_ALL;
1119 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1122 /** userrec::UpdateNick()
1123 * re-allocates a nick in the user_hash after they change nicknames,
1124 * returns a pointer to the new user as it may have moved
1126 userrec* userrec::UpdateNickHash(const char* New)
1130 //user_hash::iterator newnick;
1131 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1133 if (!strcasecmp(this->nick,New))
1134 return oldnick->second;
1136 if (oldnick == ServerInstance->clientlist.end())
1137 return NULL; /* doesnt exist */
1139 userrec* olduser = oldnick->second;
1140 ServerInstance->clientlist[New] = olduser;
1141 ServerInstance->clientlist.erase(oldnick);
1142 return ServerInstance->clientlist[New];
1147 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1152 bool userrec::ForceNickChange(const char* newnick)
1158 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1162 ServerInstance->stats->statsCollisions++;
1166 if (ServerInstance->XLines->matches_qline(newnick))
1168 ServerInstance->stats->statsCollisions++;
1172 if (this->registered == REG_ALL)
1174 const char* pars[1];
1176 std::string cmd = "NICK";
1177 return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1184 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1189 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1191 switch (protocol_family)
1193 #ifdef SUPPORT_IP6LINKS
1196 ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1197 sockaddr_in6* sin = new sockaddr_in6;
1198 sin->sin6_family = AF_INET6;
1199 sin->sin6_port = port;
1200 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1201 this->ip = (sockaddr*)sin;
1207 ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1208 sockaddr_in* sin = new sockaddr_in;
1209 sin->sin_family = AF_INET;
1210 sin->sin_port = port;
1211 inet_pton(AF_INET, ip, &sin->sin_addr);
1212 this->ip = (sockaddr*)sin;
1216 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1221 int userrec::GetPort()
1223 if (this->ip == NULL)
1226 switch (this->GetProtocolFamily())
1228 #ifdef SUPPORT_IP6LINKS
1231 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1232 return sin->sin6_port;
1238 sockaddr_in* sin = (sockaddr_in*)this->ip;
1239 return sin->sin_port;
1243 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1249 int userrec::GetProtocolFamily()
1251 if (this->ip == NULL)
1254 sockaddr_in* sin = (sockaddr_in*)this->ip;
1255 return sin->sin_family;
1258 const char* userrec::GetIPString()
1260 static char buf[1024];
1262 if (this->ip == NULL)
1265 switch (this->GetProtocolFamily())
1267 #ifdef SUPPORT_IP6LINKS
1270 static char temp[1024];
1272 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1273 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1274 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1277 strlcpy(&temp[1], buf, sizeof(temp));
1287 sockaddr_in* sin = (sockaddr_in*)this->ip;
1288 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1293 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1299 const char* userrec::GetIPString(char* buf)
1301 if (this->ip == NULL)
1307 switch (this->GetProtocolFamily())
1309 #ifdef SUPPORT_IP6LINKS
1312 static char temp[1024];
1314 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1315 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1316 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1319 strlcpy(&temp[1], buf, sizeof(temp));
1321 strlcpy(buf, temp, sizeof(temp));
1329 sockaddr_in* sin = (sockaddr_in*)this->ip;
1330 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1336 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1342 /** NOTE: We cannot pass a const reference to this method.
1343 * The string is changed by the workings of the method,
1344 * so that if we pass const ref, we end up copying it to
1345 * something we can change anyway. Makes sense to just let
1346 * the compiler do that copy for us.
1348 void userrec::Write(std::string text)
1350 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1355 text.append("\r\n");
1359 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1363 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1367 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1369 catch (ModuleException& modexcept)
1371 ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1376 this->AddWriteBuf(text);
1378 ServerInstance->stats->statsSent += text.length();
1383 void userrec::Write(const char *text, ...)
1386 char textbuffer[MAXBUF];
1388 va_start(argsPtr, text);
1389 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1392 this->Write(std::string(textbuffer));
1395 void userrec::WriteServ(const std::string& text)
1397 char textbuffer[MAXBUF];
1399 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1400 this->Write(std::string(textbuffer));
1404 * Same as Write(), except `text' is prefixed with `:server.name '.
1406 void userrec::WriteServ(const char* text, ...)
1409 char textbuffer[MAXBUF];
1411 va_start(argsPtr, text);
1412 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1415 this->WriteServ(std::string(textbuffer));
1419 void userrec::WriteFrom(userrec *user, const std::string &text)
1423 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1425 this->Write(std::string(tb));
1429 /* write text from an originating user to originating user */
1431 void userrec::WriteFrom(userrec *user, const char* text, ...)
1434 char textbuffer[MAXBUF];
1436 va_start(argsPtr, text);
1437 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1440 this->WriteFrom(user, std::string(textbuffer));
1444 /* write text to an destination user from a source user (e.g. user privmsg) */
1446 void userrec::WriteTo(userrec *dest, const char *data, ...)
1448 char textbuffer[MAXBUF];
1451 va_start(argsPtr, data);
1452 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1455 this->WriteTo(dest, std::string(textbuffer));
1458 void userrec::WriteTo(userrec *dest, const std::string &data)
1460 dest->WriteFrom(this, data);
1464 void userrec::WriteCommon(const char* text, ...)
1466 char textbuffer[MAXBUF];
1469 if (this->registered != REG_ALL)
1472 va_start(argsPtr, text);
1473 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1476 this->WriteCommon(std::string(textbuffer));
1479 void userrec::WriteCommon(const std::string &text)
1483 bool sent_to_at_least_one = false;
1485 if (this->registered != REG_ALL)
1490 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1495 CUList *ulist= n->channel->GetUsers();
1497 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1499 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1501 already_sent[i->second->fd] = uniq_id;
1502 i->second->WriteFrom(this, std::string(text));
1503 sent_to_at_least_one = true;
1510 * if the user was not in any channels, no users will receive the text. Make sure the user
1511 * receives their OWN message for WriteCommon
1513 if (!sent_to_at_least_one)
1515 this->WriteFrom(this,std::string(text));
1521 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1526 /* write a formatted string to all users who share at least one common
1527 * channel, NOT including the source user e.g. for use in QUIT
1530 void userrec::WriteCommonExcept(const char* text, ...)
1532 char textbuffer[MAXBUF];
1535 va_start(argsPtr, text);
1536 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1539 this->WriteCommonExcept(std::string(textbuffer));
1542 void userrec::WriteCommonExcept(const std::string &text)
1544 bool quit_munge = false;
1545 char oper_quit[MAXBUF];
1546 char textbuffer[MAXBUF];
1548 strlcpy(textbuffer, text.c_str(), MAXBUF);
1550 if (this->registered != REG_ALL)
1555 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1556 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1559 if (ServerInstance->Config->HideSplits)
1561 char* check = textbuffer + 6;
1563 if (!strncasecmp(textbuffer, "QUIT :",6))
1565 std::stringstream split(check);
1566 std::string server_one;
1567 std::string server_two;
1569 split >> server_one;
1570 split >> server_two;
1572 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1574 strlcpy(oper_quit,textbuffer,MAXQUIT);
1575 strlcpy(check,"*.net *.split",MAXQUIT);
1581 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1583 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1584 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1586 char* check = textbuffer + 13;
1587 strlcpy(oper_quit,textbuffer,MAXQUIT);
1588 *check = 0; // We don't need to strlcpy, we just chop it from the :
1593 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1598 CUList *ulist= n->channel->GetUsers();
1600 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1602 if (this != i->second)
1604 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1606 already_sent[i->second->fd] = uniq_id;
1608 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1610 i->second->WriteFrom(this, std::string(textbuffer));
1619 void userrec::WriteWallOps(const std::string &text)
1621 /* Does nothing if theyre not opered */
1622 if ((!*this->oper) && (IS_LOCAL(this)))
1625 std::string wallop = "WALLOPS :";
1629 wallop.append(text);
1633 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1637 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1640 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1641 this->WriteTo(t,wallop);
1645 void userrec::WriteWallOps(const char* text, ...)
1647 char textbuffer[MAXBUF];
1650 va_start(argsPtr, text);
1651 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1654 this->WriteWallOps(std::string(textbuffer));
1657 /* return 0 or 1 depending if users u and u2 share one or more common channels
1658 * (used by QUIT, NICK etc which arent channel specific notices)
1660 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1661 * the first users channels then the second users channels within the outer loop,
1662 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1663 * all possible iterations). However this new function instead checks against the
1664 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1665 * and saves us time as we already know what pointer value we are after.
1666 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1667 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1669 bool userrec::SharesChannelWith(userrec *other)
1671 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1675 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1677 /* Fetch the channel from the user */
1678 ucrec* user_channel = *i;
1680 if (user_channel->channel)
1682 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1683 * by replacing it with a map::find which *should* be more efficient
1685 if (user_channel->channel->HasUser(other))
1692 int userrec::CountChannels()
1694 return ChannelCount;
1697 void userrec::ModChannelCount(int n)
1702 bool userrec::ChangeName(const char* gecos)
1704 if (!strcmp(gecos, this->fullname))
1710 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1713 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1715 strlcpy(this->fullname,gecos,MAXGECOS+1);
1719 bool userrec::ChangeDisplayedHost(const char* host)
1721 if (!strcmp(host, this->dhost))
1727 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1730 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1732 if (this->ServerInstance->Config->CycleHosts)
1733 this->WriteCommonExcept("%s","QUIT :Changing hosts");
1735 strlcpy(this->dhost,host,63);
1737 if (this->ServerInstance->Config->CycleHosts)
1739 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1743 (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
1744 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1746 (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
1752 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1757 bool userrec::ChangeIdent(const char* newident)
1759 if (!strcmp(newident, this->ident))
1762 if (this->ServerInstance->Config->CycleHosts)
1763 this->WriteCommonExcept("%s","QUIT :Changing ident");
1765 strlcpy(this->ident, newident, IDENTMAX+2);
1767 if (this->ServerInstance->Config->CycleHosts)
1769 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1773 (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
1774 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1776 (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
1784 void userrec::NoticeAll(char* text, ...)
1786 char textbuffer[MAXBUF];
1787 char formatbuffer[MAXBUF];
1790 va_start(argsPtr, text);
1791 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1794 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1796 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1799 t->WriteFrom(this, std::string(formatbuffer));
1804 std::string userrec::ChannelList(userrec* source)
1809 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1813 if(rec->channel && rec->channel->name)
1815 /* If the target is the same as the sender, let them see all their channels.
1816 * If the channel is NOT private/secret OR the user shares a common channel
1817 * If the user is an oper, and the <options:operspywhois> option is set.
1819 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1821 list.append(rec->channel->GetPrefixChar(this)).append(rec->channel->name).append(" ");
1829 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1834 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1837 std::ostringstream prefix;
1838 std::string::size_type start, pos, length;
1842 prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
1843 line = prefix.str();
1845 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1847 length = (pos == std::string::npos) ? cl.length() : pos;
1849 if (line.length() + length - start > 510)
1852 line = prefix.str();
1855 if(pos == std::string::npos)
1857 line.append(cl.substr(start, length - start));
1862 line.append(cl.substr(start, length - start + 1));
1874 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1879 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1880 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1881 * then their ip will be taken as 'priority' anyway, so for example,
1882 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1884 ConnectClass& userrec::GetClass()
1886 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1888 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1892 return *(ServerInstance->Config->Classes.begin());
1895 void userrec::PurgeEmptyChannels()
1897 std::vector<chanrec*> to_delete;
1899 // firstly decrement the count on each channel
1900 for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1905 uc->channel->RemoveAllPrefixes(this);
1906 if (uc->channel->DelUser(this) == 0)
1908 /* No users left in here, mark it for deletion */
1911 to_delete.push_back(uc->channel);
1915 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1922 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1924 chanrec* thischan = *n;
1925 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1926 if (i2 != ServerInstance->chanlist.end())
1928 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1930 ServerInstance->chanlist.erase(i2);
1937 void userrec::ShowMOTD()
1939 if (!ServerInstance->Config->MOTD.size())
1941 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1944 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1946 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
1947 this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
1949 this->WriteServ("376 %s :End of message of the day.", this->nick);
1952 void userrec::ShowRULES()
1954 if (!ServerInstance->Config->RULES.size())
1956 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1959 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1961 for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
1962 this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
1964 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1967 void userrec::HandleEvent(EventType et)
1969 /* WARNING: May delete this user! */
1972 ServerInstance->ProcessUser(this);
1976 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");