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 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
29 /* XXX: Used for speeding up WriteCommon operations */
30 unsigned long uniq_id = 0;
32 bool InitTypes(ServerConfig* conf, const char* tag)
34 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
40 conf->opertypes.clear();
44 bool InitClasses(ServerConfig* conf, const char* tag)
46 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
52 conf->operclass.clear();
56 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
58 char* TypeName = (char*)values[0];
59 char* Classes = (char*)values[1];
61 conf->opertypes[TypeName] = strdup(Classes);
62 conf->GetInstance()->Log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
66 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
68 char* ClassName = (char*)values[0];
69 char* CommandList = (char*)values[1];
71 conf->operclass[ClassName] = strdup(CommandList);
72 conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
76 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
81 std::string userrec::ProcessNoticeMasks(const char *sm)
83 bool adding = true, oldadding = false;
87 ServerInstance->Log(DEBUG,"Process notice masks");
91 ServerInstance->Log(DEBUG,"Process notice mask %c",*c);
102 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
104 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
106 if ((oldadding != adding) || (!output.length()))
107 output += (adding ? '+' : '-');
109 this->SetNoticeMask(*c, adding);
124 void userrec::StartDNSLookup()
126 ServerInstance->Log(DEBUG,"Commencing reverse lookup");
129 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
130 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
131 this->ServerInstance->AddResolver(res_reverse);
133 catch (ModuleException& e)
135 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
139 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
140 Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
143 this->bound_fd = user->GetFd();
146 void UserResolver::OnLookupComplete(const std::string &result)
148 if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
150 ServerInstance->Log(DEBUG,"Commencing forward lookup");
151 this->bound_user->stored_host = result;
154 /* Check we didnt time out */
155 if (this->bound_user->registered != REG_ALL)
157 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
158 this->ServerInstance->AddResolver(bound_user->res_forward);
161 catch (ModuleException& e)
163 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
166 else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
168 /* Both lookups completed */
169 if (this->bound_user->GetIPString() == result)
171 std::string hostname = this->bound_user->stored_host;
172 if (hostname.length() < 65)
174 /* Check we didnt time out */
175 if (this->bound_user->registered != REG_ALL)
177 /* Hostnames starting with : are not a good thing (tm) */
178 if (*(hostname.c_str()) == ':')
179 hostname = "0" + hostname;
181 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
182 this->bound_user->dns_done = true;
183 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
184 strlcpy(this->bound_user->host, hostname.c_str(),64);
189 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());
194 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());
199 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
201 if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
203 /* Error message here */
204 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
205 this->bound_user->dns_done = true;
210 bool userrec::IsNoticeMaskSet(unsigned char sm)
212 return (snomasks[sm-65]);
215 void userrec::SetNoticeMask(unsigned char sm, bool value)
217 snomasks[sm-65] = value;
220 const char* userrec::FormatNoticeMasks()
222 static char data[MAXBUF];
225 for (int n = 0; n < 64; n++)
228 data[offset++] = n+65;
237 bool userrec::IsModeSet(unsigned char m)
239 return (modes[m-65]);
242 void userrec::SetMode(unsigned char m, bool value)
247 const char* userrec::FormatModes()
249 static char data[MAXBUF];
251 for (int n = 0; n < 64; n++)
254 data[offset++] = n+65;
260 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
262 ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
263 // the PROPER way to do it, AVOID bzero at *ALL* costs
264 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
265 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
266 reset_due = ServerInstance->Time();
267 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
268 ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
269 haspassed = dns_done = false;
274 res_forward = res_reverse = NULL;
278 chans.resize(MAXCHANS);
279 memset(modes,0,sizeof(modes));
280 memset(snomasks,0,sizeof(snomasks));
282 for (unsigned int n = 0; n < MAXCHANS; n++)
284 ucrec* x = new ucrec();
293 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
295 ucrec* x = (ucrec*)*n;
301 if (this->GetProtocolFamily() == AF_INET)
303 delete (sockaddr_in*)ip;
305 #ifdef SUPPORT_IP6LINKS
308 delete (sockaddr_in6*)ip;
314 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
315 void userrec::MakeHost(char* nhost)
317 /* This is much faster than snprintf */
319 for(char* n = ident; *n; n++)
322 for(char* n = host; *n; n++)
327 void userrec::CloseSocket()
329 shutdown(this->fd,2);
333 char* userrec::GetFullHost()
335 static char result[MAXBUF];
337 for(char* n = nick; *n; n++)
340 for(char* n = ident; *n; n++)
343 for(char* n = dhost; *n; n++)
349 char* userrec::MakeWildHost()
351 static char nresult[MAXBUF];
353 *t++ = '*'; *t++ = '!';
354 *t++ = '*'; *t++ = '@';
355 for(char* n = dhost; *n; n++)
361 int userrec::ReadData(void* buffer, size_t size)
365 return read(this->fd, buffer, size);
372 char* userrec::GetFullRealHost()
374 static char fresult[MAXBUF];
376 for(char* n = nick; *n; n++)
379 for(char* n = ident; *n; n++)
382 for(char* n = host; *n; n++)
388 bool userrec::IsInvited(irc::string &channel)
390 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
392 irc::string compare = i->channel;
394 if (compare == channel)
402 InvitedList* userrec::GetInviteList()
407 void userrec::InviteTo(irc::string &channel)
411 invites.push_back(i);
414 void userrec::RemoveInvite(irc::string &channel)
416 ServerInstance->Log(DEBUG,"Removing invites");
420 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
422 irc::string compare = i->channel;
424 if (compare == channel)
433 bool userrec::HasPermission(const std::string &command)
440 * users on remote servers can completely bypass all permissions based checks.
441 * This prevents desyncs when one server has different type/class tags to another.
442 * That having been said, this does open things up to the possibility of source changes
443 * allowing remote kills, etc - but if they have access to the src, they most likely have
444 * access to the conf - so it's an end to a means either way.
449 // are they even an oper at all?
452 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
453 if (iter_opertype != ServerInstance->Config->opertypes.end())
455 char* Classes = strdup(iter_opertype->second);
456 char* myclass = strtok_r(Classes," ",&savept);
459 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
460 if (iter_operclass != ServerInstance->Config->operclass.end())
462 char* CommandList = strdup(iter_operclass->second);
463 mycmd = strtok_r(CommandList," ",&savept2);
466 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
472 mycmd = strtok_r(NULL," ",&savept2);
476 myclass = strtok_r(NULL," ",&savept);
484 /** NOTE: We cannot pass a const reference to this method.
485 * The string is changed by the workings of the method,
486 * so that if we pass const ref, we end up copying it to
487 * something we can change anyway. Makes sense to just let
488 * the compiler do that copy for us.
490 bool userrec::AddBuffer(std::string a)
494 std::string::size_type i = a.rfind('\r');
496 while (i != std::string::npos)
505 if (recvq.length() > (unsigned)this->recvqmax)
507 this->SetWriteError("RecvQ exceeded");
508 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
517 ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
522 bool userrec::BufferIsReady()
524 return (recvq.find('\n') != std::string::npos);
527 void userrec::ClearBuffer()
532 std::string userrec::GetBuffer()
539 /* Strip any leading \r or \n off the string.
540 * Usually there are only one or two of these,
541 * so its is computationally cheap to do.
543 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
544 recvq.erase(recvq.begin());
546 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
548 /* Find the first complete line, return it as the
549 * result, and leave the recvq as whats left
553 std::string ret = std::string(recvq.begin(), x);
554 recvq.erase(recvq.begin(), x + 1);
563 ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
568 void userrec::AddWriteBuf(const std::string &data)
570 if (*this->GetWriteError())
573 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
576 * Fix by brain - Set the error text BEFORE calling writeopers, because
577 * if we dont it'll recursively call here over and over again trying
578 * to repeatedly add the text to the sendq!
580 this->SetWriteError("SendQ exceeded");
581 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
587 if (data.length() > 512)
589 std::string newdata(data);
591 newdata.append("\r\n");
592 sendq.append(newdata);
601 this->SetWriteError("SendQ exceeded");
602 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
606 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
607 void userrec::FlushWriteBuf()
611 if (this->fd == FD_MAGIC_NUMBER)
615 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
617 const char* tb = this->sendq.c_str();
618 int n_sent = write(this->fd,tb,this->sendq.length());
622 this->SetWriteError(strerror(errno));
629 // update the user's stats counters
630 this->bytes_out += n_sent;
638 ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
642 void userrec::SetWriteError(const std::string &error)
646 ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
647 // don't try to set the error twice, its already set take the first string.
648 if (!this->WriteError.length())
650 ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
651 this->WriteError = error;
657 ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
661 const char* userrec::GetWriteError()
663 return this->WriteError.c_str();
666 void userrec::Oper(const std::string &opertype)
670 this->modes[UM_OPERATOR] = 1;
671 this->WriteServ("MODE %s :+o", this->nick);
672 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
673 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
674 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
675 ServerInstance->all_opers.push_back(this);
676 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
681 ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
685 void userrec::UnOper()
692 this->modes[UM_OPERATOR] = 0;
693 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
697 ServerInstance->Log(DEBUG,"Oper removed from optimization list");
698 ServerInstance->all_opers.erase(a);
707 ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
711 void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
713 user_hash::iterator iter = Instance->clientlist.find(user->nick);
714 std::string reason = quitreason;
716 if (reason.length() > MAXQUIT - 1)
717 reason.resize(MAXQUIT - 1);
720 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
722 if (user->registered == REG_ALL)
724 user->PurgeEmptyChannels();
725 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
726 user->WriteCommonExcept("QUIT :%s",reason.c_str());
730 user->FlushWriteBuf();
732 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
736 if (Instance->Config->GetIOHook(user->GetPort()))
740 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
742 catch (ModuleException& modexcept)
744 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
748 Instance->SE->DelFd(user);
753 * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
754 * if they were an oper with +sn +qQ.
756 if (user->registered == REG_ALL)
759 Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
761 Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
765 if (iter != Instance->clientlist.end())
767 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
770 if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
771 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
773 Instance->clientlist.erase(iter);
783 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
785 this->host = strdup(user->host);
786 this->dhost = strdup(user->dhost);
787 this->ident = strdup(user->ident);
788 this->server = user->server;
789 this->gecos = strdup(user->fullname);
792 WhoWasGroup::~WhoWasGroup()
804 /* every hour, run this function which removes all entries over 3 days */
805 void MaintainWhoWas(InspIRCd* ServerInstance, time_t t)
807 for (whowas_users::iterator iter = ServerInstance->whowas.begin(); iter != ServerInstance->whowas.end(); iter++)
809 whowas_set* n = (whowas_set*)iter->second;
812 while ((n->begin() != n->end()) && ((*n->begin())->signon < t - 259200)) // 3 days
814 WhoWasGroup *a = *(n->begin());
816 n->erase(n->begin());
824 /* adds or updates an entry in the whowas list */
825 void userrec::AddToWhoWas()
827 irc::whowas::whowas_users::iterator iter = ServerInstance->whowas.find(this->nick);
829 ServerInstance->Log(DEBUG,"Add to whowas lists");
831 if (iter == ServerInstance->whowas.end())
833 ServerInstance->Log(DEBUG,"Adding new whowas set for %s",this->nick);
834 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
835 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
837 ServerInstance->whowas[this->nick] = n;
841 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
843 ServerInstance->Log(DEBUG,"Using existing whowas group for %s",this->nick);
845 if (group->size() > 10)
847 ServerInstance->Log(DEBUG,"Trimming existing group to ten entries for %s",this->nick);
848 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
853 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
858 /* add a client connection to the sockets list */
859 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
861 std::string tempnick = ConvToStr(socket) + "-unknown";
862 user_hash::iterator iter = Instance->clientlist.find(tempnick);
863 const char *ipaddr = insp_ntoa(ip);
869 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
870 * using one as a registered connection. As they are per fd, we can also safely assume
871 * that we wont have collisions. Therefore, if the nick exists in the list, its only
872 * used by a dead socket, erase the iterator so that the new client may reclaim it.
873 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
874 * issue in earlier alphas/betas
876 if (iter != Instance->clientlist.end())
878 userrec* goner = iter->second;
880 Instance->clientlist.erase(iter);
883 Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
885 New = new userrec(Instance);
886 Instance->clientlist[tempnick] = New;
888 strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
890 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
891 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
892 strcpy(New->ident, "unknown");
894 New->registered = REG_NONE;
895 New->signon = Instance->Time() + Instance->Config->dns_timeout;
898 Instance->Log(DEBUG,"Setting socket addresses");
899 New->SetSockAddr(AF_FAMILY, ipaddr, port);
900 Instance->Log(DEBUG,"Socket addresses set.");
902 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
903 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
904 New->dhost[j] = New->host[j] = *temp;
905 New->dhost[j] = New->host[j] = 0;
907 // set the registration timeout for this user
908 unsigned long class_regtimeout = 90;
910 long class_threshold = 5;
911 long class_sqmax = 262144; // 256kb
912 long class_rqmax = 4096; // 4k
914 for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
916 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
918 class_regtimeout = (unsigned long)i->registration_timeout;
919 class_flood = i->flood;
920 New->pingmax = i->pingtime;
921 class_threshold = i->threshold;
922 class_sqmax = i->sendqmax;
923 class_rqmax = i->recvqmax;
928 New->nping = Instance->Time() + New->pingmax + Instance->Config->dns_timeout;
929 New->timeout = Instance->Time() + class_regtimeout;
930 New->flood = class_flood;
931 New->threshold = class_threshold;
932 New->sendqmax = class_sqmax;
933 New->recvqmax = class_rqmax;
935 Instance->local_users.push_back(New);
937 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
939 userrec::QuitUser(Instance, New,"No more connections allowed");
945 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
946 * its a pretty big but for the moment valid assumption:
947 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
948 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
949 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
950 * which for the time being is a physical impossibility (even the largest networks dont have more
951 * than about 10,000 users on ONE server!)
953 if ((unsigned)socket >= MAX_DESCRIPTORS)
955 userrec::QuitUser(Instance, New, "Server is full");
959 ELine* e = Instance->XLines->matches_exception(New);
962 ZLine* r = Instance->XLines->matches_zline(ipaddr);
966 snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
967 userrec::QuitUser(Instance, New, reason);
974 if (!Instance->SE->AddFd(New))
976 userrec::QuitUser(Instance, New, "Internal error handling connection");
981 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
984 long userrec::GlobalCloneCount()
990 for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
992 /* We have to match ip's as strings - we don't know what protocol
993 * a remote user may be using
995 if (strcmp(a->second->GetIPString(u1), this->GetIPString(u2)) == 0)
1002 long userrec::LocalCloneCount()
1005 for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
1009 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
1010 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
1011 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
1012 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
1015 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
1016 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
1017 if (s1->s_addr == s2->s_addr)
1024 void userrec::FullConnect(CullList* Goners)
1026 ServerInstance->stats->statsConnects++;
1027 this->idle_lastmsg = ServerInstance->Time();
1029 ConnectClass a = this->GetClass();
1031 if (a.type == CC_DENY)
1033 Goners->AddItem(this,"Unauthorised connection");
1037 if ((*(a.pass.c_str())) && (!this->haspassed))
1039 Goners->AddItem(this,"Invalid password");
1043 if (this->LocalCloneCount() > a.maxlocal)
1045 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1046 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
1049 else if (this->GlobalCloneCount() > a.maxglobal)
1051 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1052 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1056 ELine* e = ServerInstance->XLines->matches_exception(this);
1060 GLine* r = ServerInstance->XLines->matches_gline(this);
1064 char reason[MAXBUF];
1065 snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
1066 Goners->AddItem(this, reason);
1070 KLine* n = ServerInstance->XLines->matches_kline(this);
1074 char reason[MAXBUF];
1075 snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
1076 Goners->AddItem(this, reason);
1082 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1083 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1084 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1085 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1086 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());
1088 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1089 // so i'd better split it :)
1090 std::stringstream out(ServerInstance->Config->data005);
1091 std::string token = "";
1092 std::string line5 = "";
1093 int token_counter = 0;
1098 line5 = line5 + token + " ";
1101 if ((token_counter >= 13) || (out.eof() == true))
1103 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1112 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1113 * changes dont go out onto the network and produce 'fake direction'.
1115 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1116 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1117 this->registered = REG_ALL;
1118 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1121 /** userrec::UpdateNick()
1122 * re-allocates a nick in the user_hash after they change nicknames,
1123 * returns a pointer to the new user as it may have moved
1125 userrec* userrec::UpdateNickHash(const char* New)
1129 //user_hash::iterator newnick;
1130 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1132 if (!strcasecmp(this->nick,New))
1133 return oldnick->second;
1135 if (oldnick == ServerInstance->clientlist.end())
1136 return NULL; /* doesnt exist */
1138 userrec* olduser = oldnick->second;
1139 ServerInstance->clientlist[New] = olduser;
1140 ServerInstance->clientlist.erase(oldnick);
1141 return ServerInstance->clientlist[New];
1146 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1151 bool userrec::ForceNickChange(const char* newnick)
1157 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1161 ServerInstance->stats->statsCollisions++;
1165 if (ServerInstance->XLines->matches_qline(newnick))
1167 ServerInstance->stats->statsCollisions++;
1171 if (this->registered == REG_ALL)
1173 const char* pars[1];
1175 std::string cmd = "NICK";
1176 return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1183 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1188 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1190 switch (protocol_family)
1192 #ifdef SUPPORT_IP6LINKS
1195 ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1196 sockaddr_in6* sin = new sockaddr_in6;
1197 sin->sin6_family = AF_INET6;
1198 sin->sin6_port = port;
1199 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1200 this->ip = (sockaddr*)sin;
1206 ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1207 sockaddr_in* sin = new sockaddr_in;
1208 sin->sin_family = AF_INET;
1209 sin->sin_port = port;
1210 inet_pton(AF_INET, ip, &sin->sin_addr);
1211 this->ip = (sockaddr*)sin;
1215 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1220 int userrec::GetPort()
1222 if (this->ip == NULL)
1225 switch (this->GetProtocolFamily())
1227 #ifdef SUPPORT_IP6LINKS
1230 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1231 return sin->sin6_port;
1237 sockaddr_in* sin = (sockaddr_in*)this->ip;
1238 return sin->sin_port;
1242 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1248 int userrec::GetProtocolFamily()
1250 if (this->ip == NULL)
1253 sockaddr_in* sin = (sockaddr_in*)this->ip;
1254 return sin->sin_family;
1257 const char* userrec::GetIPString()
1259 static char buf[1024];
1261 if (this->ip == NULL)
1264 switch (this->GetProtocolFamily())
1266 #ifdef SUPPORT_IP6LINKS
1269 static char temp[1024];
1271 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1272 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1273 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1276 strlcpy(&temp[1], buf, sizeof(temp));
1286 sockaddr_in* sin = (sockaddr_in*)this->ip;
1287 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1292 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1298 const char* userrec::GetIPString(char* buf)
1300 if (this->ip == NULL)
1306 switch (this->GetProtocolFamily())
1308 #ifdef SUPPORT_IP6LINKS
1311 static char temp[1024];
1313 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1314 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1315 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1318 strlcpy(&temp[1], buf, sizeof(temp));
1320 strlcpy(buf, temp, sizeof(temp));
1328 sockaddr_in* sin = (sockaddr_in*)this->ip;
1329 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1335 ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1341 /** NOTE: We cannot pass a const reference to this method.
1342 * The string is changed by the workings of the method,
1343 * so that if we pass const ref, we end up copying it to
1344 * something we can change anyway. Makes sense to just let
1345 * the compiler do that copy for us.
1347 void userrec::Write(std::string text)
1349 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1354 text.append("\r\n");
1358 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1362 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1366 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1368 catch (ModuleException& modexcept)
1370 ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1375 this->AddWriteBuf(text);
1377 ServerInstance->stats->statsSent += text.length();
1382 void userrec::Write(const char *text, ...)
1385 char textbuffer[MAXBUF];
1387 va_start(argsPtr, text);
1388 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1391 this->Write(std::string(textbuffer));
1394 void userrec::WriteServ(const std::string& text)
1396 char textbuffer[MAXBUF];
1398 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1399 this->Write(std::string(textbuffer));
1403 * Same as Write(), except `text' is prefixed with `:server.name '.
1405 void userrec::WriteServ(const char* text, ...)
1408 char textbuffer[MAXBUF];
1410 va_start(argsPtr, text);
1411 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1414 this->WriteServ(std::string(textbuffer));
1418 void userrec::WriteFrom(userrec *user, const std::string &text)
1422 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1424 this->Write(std::string(tb));
1428 /* write text from an originating user to originating user */
1430 void userrec::WriteFrom(userrec *user, const char* text, ...)
1433 char textbuffer[MAXBUF];
1435 va_start(argsPtr, text);
1436 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1439 this->WriteFrom(user, std::string(textbuffer));
1443 /* write text to an destination user from a source user (e.g. user privmsg) */
1445 void userrec::WriteTo(userrec *dest, const char *data, ...)
1447 char textbuffer[MAXBUF];
1450 va_start(argsPtr, data);
1451 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1454 this->WriteTo(dest, std::string(textbuffer));
1457 void userrec::WriteTo(userrec *dest, const std::string &data)
1459 dest->WriteFrom(this, data);
1463 void userrec::WriteCommon(const char* text, ...)
1465 char textbuffer[MAXBUF];
1468 if (this->registered != REG_ALL)
1471 va_start(argsPtr, text);
1472 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1475 this->WriteCommon(std::string(textbuffer));
1478 void userrec::WriteCommon(const std::string &text)
1482 bool sent_to_at_least_one = false;
1484 if (this->registered != REG_ALL)
1489 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1494 CUList *ulist= n->channel->GetUsers();
1496 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1498 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1500 already_sent[i->second->fd] = uniq_id;
1501 i->second->WriteFrom(this, std::string(text));
1502 sent_to_at_least_one = true;
1509 * if the user was not in any channels, no users will receive the text. Make sure the user
1510 * receives their OWN message for WriteCommon
1512 if (!sent_to_at_least_one)
1514 this->WriteFrom(this,std::string(text));
1520 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1525 /* write a formatted string to all users who share at least one common
1526 * channel, NOT including the source user e.g. for use in QUIT
1529 void userrec::WriteCommonExcept(const char* text, ...)
1531 char textbuffer[MAXBUF];
1534 va_start(argsPtr, text);
1535 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1538 this->WriteCommonExcept(std::string(textbuffer));
1541 void userrec::WriteCommonExcept(const std::string &text)
1543 bool quit_munge = false;
1544 char oper_quit[MAXBUF];
1545 char textbuffer[MAXBUF];
1547 strlcpy(textbuffer, text.c_str(), MAXBUF);
1549 if (this->registered != REG_ALL)
1554 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1555 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1558 if (ServerInstance->Config->HideSplits)
1560 char* check = textbuffer + 6;
1562 if (!strncasecmp(textbuffer, "QUIT :",6))
1564 std::stringstream split(check);
1565 std::string server_one;
1566 std::string server_two;
1568 split >> server_one;
1569 split >> server_two;
1571 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1573 strlcpy(oper_quit,textbuffer,MAXQUIT);
1574 strlcpy(check,"*.net *.split",MAXQUIT);
1580 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1582 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1583 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1585 char* check = textbuffer + 13;
1586 strlcpy(oper_quit,textbuffer,MAXQUIT);
1587 *check = 0; // We don't need to strlcpy, we just chop it from the :
1592 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1597 CUList *ulist= n->channel->GetUsers();
1599 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1601 if (this != i->second)
1603 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1605 already_sent[i->second->fd] = uniq_id;
1607 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1609 i->second->WriteFrom(this, std::string(textbuffer));
1618 void userrec::WriteWallOps(const std::string &text)
1620 /* Does nothing if theyre not opered */
1621 if ((!*this->oper) && (IS_LOCAL(this)))
1624 std::string wallop = "WALLOPS :";
1628 wallop.append(text);
1632 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1636 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1639 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1640 this->WriteTo(t,wallop);
1644 void userrec::WriteWallOps(const char* text, ...)
1646 char textbuffer[MAXBUF];
1649 va_start(argsPtr, text);
1650 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1653 this->WriteWallOps(std::string(textbuffer));
1656 /* return 0 or 1 depending if users u and u2 share one or more common channels
1657 * (used by QUIT, NICK etc which arent channel specific notices)
1659 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1660 * the first users channels then the second users channels within the outer loop,
1661 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1662 * all possible iterations). However this new function instead checks against the
1663 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1664 * and saves us time as we already know what pointer value we are after.
1665 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1666 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1668 bool userrec::SharesChannelWith(userrec *other)
1670 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1674 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1676 /* Fetch the channel from the user */
1677 ucrec* user_channel = *i;
1679 if (user_channel->channel)
1681 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1682 * by replacing it with a map::find which *should* be more efficient
1684 if (user_channel->channel->HasUser(other))
1691 int userrec::CountChannels()
1693 return ChannelCount;
1696 void userrec::ModChannelCount(int n)
1701 bool userrec::ChangeName(const char* gecos)
1703 if (!strcmp(gecos, this->fullname))
1709 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1712 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1714 strlcpy(this->fullname,gecos,MAXGECOS+1);
1718 bool userrec::ChangeDisplayedHost(const char* host)
1720 if (!strcmp(host, this->dhost))
1726 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1729 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1731 if (this->ServerInstance->Config->CycleHosts)
1732 this->WriteCommonExcept("%s","QUIT :Changing hosts");
1734 strlcpy(this->dhost,host,63);
1736 if (this->ServerInstance->Config->CycleHosts)
1738 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1742 (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
1743 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1745 (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
1751 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1756 bool userrec::ChangeIdent(const char* newident)
1758 if (!strcmp(newident, this->ident))
1761 if (this->ServerInstance->Config->CycleHosts)
1762 this->WriteCommonExcept("%s","QUIT :Changing ident");
1764 strlcpy(this->ident, newident, IDENTMAX+2);
1766 if (this->ServerInstance->Config->CycleHosts)
1768 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1772 (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
1773 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1775 (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
1783 void userrec::NoticeAll(char* text, ...)
1785 char textbuffer[MAXBUF];
1786 char formatbuffer[MAXBUF];
1789 va_start(argsPtr, text);
1790 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1793 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1795 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1798 t->WriteFrom(this, std::string(formatbuffer));
1803 std::string userrec::ChannelList(userrec* source)
1808 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1812 if(rec->channel && rec->channel->name)
1814 /* If the target is the same as the sender, let them see all their channels.
1815 * If the channel is NOT private/secret OR the user shares a common channel
1816 * If the user is an oper, and the <options:operspywhois> option is set.
1818 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1820 list.append(rec->channel->GetPrefixChar(this)).append(rec->channel->name).append(" ");
1828 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1833 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1836 std::ostringstream prefix;
1837 std::string::size_type start, pos, length;
1841 prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
1842 line = prefix.str();
1844 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1846 length = (pos == std::string::npos) ? cl.length() : pos;
1848 if (line.length() + length - start > 510)
1851 line = prefix.str();
1854 if(pos == std::string::npos)
1856 line.append(cl.substr(start, length - start));
1861 line.append(cl.substr(start, length - start + 1));
1873 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1878 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1879 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1880 * then their ip will be taken as 'priority' anyway, so for example,
1881 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1883 ConnectClass& userrec::GetClass()
1885 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1887 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1891 return *(ServerInstance->Config->Classes.begin());
1894 void userrec::PurgeEmptyChannels()
1896 std::vector<chanrec*> to_delete;
1898 // firstly decrement the count on each channel
1899 for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1904 uc->channel->RemoveAllPrefixes(this);
1905 if (uc->channel->DelUser(this) == 0)
1907 /* No users left in here, mark it for deletion */
1910 to_delete.push_back(uc->channel);
1914 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1921 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1923 chanrec* thischan = *n;
1924 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1925 if (i2 != ServerInstance->chanlist.end())
1927 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1929 ServerInstance->chanlist.erase(i2);
1936 void userrec::ShowMOTD()
1938 if (!ServerInstance->Config->MOTD.size())
1940 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1943 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1945 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
1946 this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
1948 this->WriteServ("376 %s :End of message of the day.", this->nick);
1951 void userrec::ShowRULES()
1953 if (!ServerInstance->Config->RULES.size())
1955 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1958 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1960 for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
1961 this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
1963 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1966 void userrec::HandleEvent(EventType et)
1968 /* WARNING: May delete this user! */
1971 ServerInstance->ProcessUser(this);
1975 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");