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 * ---------------------------------------------------
19 #include "inspircd_config.h"
21 #include "connection.h"
29 #include "inspstring.h"
31 #include "helperfuncs.h"
33 #include "socketengine.h"
38 #include "cull_list.h"
40 extern InspIRCd* ServerInstance;
41 extern int WHOWAS_STALE;
42 extern int WHOWAS_MAX;
43 extern std::vector<Module*> modules;
44 extern std::vector<ircd_module*> factory;
45 extern std::vector<InspSocket*> module_sockets;
47 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
49 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
50 extern ServerConfig *Config;
51 extern user_hash clientlist;
55 extern std::vector<userrec*> local_users;
57 std::vector<userrec*> all_opers;
59 typedef std::map<irc::string,char*> opertype_t;
60 typedef opertype_t operclass_t;
63 operclass_t operclass;
65 bool InitTypes(const char* tag)
67 for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
76 bool InitClasses(const char* tag)
78 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
87 bool DoType(const char* tag, char** entries, void** values, int* types)
89 char* TypeName = (char*)values[0];
90 char* Classes = (char*)values[1];
91 /*Config->ConfValue("type","name",j,TypeName,&Config->config_f);
92 Config->ConfValue("type","classes",j,Classes,&Config->config_f);*/
93 opertypes[TypeName] = strdup(Classes);
94 log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
98 bool DoClass(const char* tag, char** entries, void** values, int* types)
100 char* ClassName = (char*)values[0];
101 char* CommandList = (char*)values[1];
102 /*Config->ConfValue("class","name",k,ClassName,&Config->config_f);
103 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);*/
104 operclass[ClassName] = strdup(CommandList);
105 log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
109 bool DoneClassesAndTypes()
114 template<typename T> inline string ConvToStr(const T &in)
117 if (!(tmp << in)) return string();
123 // the PROPER way to do it, AVOID bzero at *ALL* costs
124 *password = *nick = *ident = *host = *dhost = *fullname = *modes = *awaymsg = *oper = 0;
125 server = (char*)FindServerNamePtr(Config->ServerName);
127 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
128 modebits = timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
129 haspassed = dns_done = false;
134 chans.resize(MAXCHANS);
135 for (unsigned int n = 0; n < MAXCHANS; n++)
137 ucrec* x = new ucrec();
146 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
148 ucrec* x = (ucrec*)*n;
153 void userrec::MakeHost(char* nhost)
155 /* This is much faster than snprintf */
157 for(char* n = ident; *n; n++)
160 for(char* n = host; *n; n++)
165 void userrec::CloseSocket()
167 shutdown(this->fd,2);
171 char* userrec::GetFullHost()
173 static char result[MAXBUF];
175 for(char* n = nick; *n; n++)
178 for(char* n = ident; *n; n++)
181 for(char* n = dhost; *n; n++)
187 char* userrec::MakeWildHost()
189 static char nresult[MAXBUF];
191 *t++ = '*'; *t++ = '!';
192 *t++ = '*'; *t++ = '@';
193 for(char* n = dhost; *n; n++)
199 int userrec::ReadData(void* buffer, size_t size)
203 return read(this->fd, buffer, size);
209 char* userrec::GetFullRealHost()
211 static char fresult[MAXBUF];
213 for(char* n = nick; *n; n++)
216 for(char* n = ident; *n; n++)
219 for(char* n = host; *n; n++)
225 bool userrec::IsInvited(irc::string &channel)
227 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
229 irc::string compare = i->channel;
230 if (compare == channel)
238 InvitedList* userrec::GetInviteList()
243 void userrec::InviteTo(irc::string &channel)
247 invites.push_back(i);
250 void userrec::RemoveInvite(irc::string &channel)
252 log(DEBUG,"Removing invites");
255 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
257 irc::string compare = i->channel;
258 if (compare == channel)
267 bool userrec::HasPermission(const std::string &command)
273 // users on remote servers can completely bypass
274 // all permissions based checks.
275 // This prevents desyncs when one server has different
276 // type/class tags to another.
280 // are they even an oper at all?
283 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
284 if (iter_opertype != opertypes.end())
286 char* Classes = strdup(iter_opertype->second);
287 char* myclass = strtok_r(Classes," ",&savept);
290 operclass_t::iterator iter_operclass = operclass.find(myclass);
291 if (iter_operclass != operclass.end())
293 char* CommandList = strdup(iter_operclass->second);
294 mycmd = strtok_r(CommandList," ",&savept2);
297 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
303 mycmd = strtok_r(NULL," ",&savept2);
307 myclass = strtok_r(NULL," ",&savept);
316 bool userrec::AddBuffer(const std::string &a)
319 char* n = (char*)a.c_str();
320 for (char* i = n; *i; i++)
322 if ((*i != '\r') && (*i != '\0') && (*i != 7))
325 std::stringstream stream(recvq);
327 recvq = stream.str();
329 // count the size of the first line in the buffer.
330 while (i < recvq.length())
332 if (recvq[i++] == '\n')
335 if (recvq.length() > (unsigned)this->recvqmax)
337 this->SetWriteError("RecvQ exceeded");
338 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
340 // return false if we've had more than 600 characters WITHOUT
341 // a carriage return (this is BAD, drop the socket)
345 bool userrec::BufferIsReady()
347 unsigned int t = recvq.length();
348 for (unsigned int i = 0; i < t; i++)
349 if (recvq[i] == '\n')
354 void userrec::ClearBuffer()
359 std::string userrec::GetBuffer()
363 char* line = (char*)recvq.c_str();
364 std::string ret = "";
365 while ((*line != '\n') && (*line))
370 if ((*line == '\n') || (*line == '\r'))
376 void userrec::AddWriteBuf(const std::string &data)
378 if (*this->GetWriteError())
380 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
382 /* Fix by brain - Set the error text BEFORE calling writeopers, because
383 * if we dont it'll recursively call here over and over again trying
384 * to repeatedly add the text to the sendq!
386 this->SetWriteError("SendQ exceeded");
387 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
390 std::stringstream stream;
391 stream << sendq << data;
392 sendq = stream.str();
395 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
396 void userrec::FlushWriteBuf()
398 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
400 char* tb = (char*)this->sendq.c_str();
401 int n_sent = write(this->fd,tb,this->sendq.length());
404 this->SetWriteError(strerror(errno));
411 // update the user's stats counters
412 this->bytes_out += n_sent;
418 void userrec::SetWriteError(const std::string &error)
420 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
421 // don't try to set the error twice, its already set take the first string.
422 if (this->WriteError == "")
423 this->WriteError = error;
426 const char* userrec::GetWriteError()
428 return this->WriteError.c_str();
431 void AddOper(userrec* user)
433 log(DEBUG,"Oper added to optimization list");
434 all_opers.push_back(user);
437 void DeleteOper(userrec* user)
439 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
443 log(DEBUG,"Oper removed from optimization list");
450 void kill_link(userrec *user,const char* r)
452 user_hash::iterator iter = clientlist.find(user->nick);
456 strlcpy(reason,r,MAXQUIT-1);
458 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
459 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
460 log(DEBUG,"closing fd %d",user->fd);
462 if (user->registered == 7) {
463 purge_empty_chans(user);
464 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
465 WriteCommonExcept(user,"QUIT :%s",reason);
468 user->FlushWriteBuf();
470 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
474 if (Config->GetIOHook(user->port))
478 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
480 catch (ModuleException& modexcept)
482 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
485 ServerInstance->SE->DelFd(user->fd);
489 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
490 // if they were an oper with +s.
491 if (user->registered == 7) {
492 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
494 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
498 if (iter != clientlist.end())
500 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
503 fd_ref_table[user->fd] = NULL;
504 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
506 local_users.erase(find(local_users.begin(),local_users.end(),user));
507 log(DEBUG,"Delete local user");
510 clientlist.erase(iter);
515 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
517 this->host = strdup(user->host);
518 this->dhost = strdup(user->dhost);
519 this->ident = strdup(user->ident);
520 this->server = user->server;
521 this->gecos = strdup(user->fullname);
524 WhoWasGroup::~WhoWasGroup()
536 /* adds or updates an entry in the whowas list */
537 void AddWhoWas(userrec* u)
539 whowas_users::iterator iter = whowas.find(u->nick);
540 if (iter == whowas.end())
542 whowas_set* n = new whowas_set;
543 WhoWasGroup *a = new WhoWasGroup(u);
549 whowas_set* group = (whowas_set*)iter->second;
550 if (group->size() > 10)
552 WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
556 WhoWasGroup *a = new WhoWasGroup(u);
561 /* every hour, run this function which removes all entries over 3 days */
562 void MaintainWhoWas(time_t TIME)
564 for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
566 whowas_set* n = (whowas_set*)iter->second;
569 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
571 WhoWasGroup *a = *(n->begin());
573 n->erase(n->begin());
579 /* add a client connection to the sockets list */
580 void AddClient(int socket, int port, bool iscached, in_addr ip4)
582 std::string tempnick = ConvToStr(socket) + "-unknown";
583 user_hash::iterator iter = clientlist.find(tempnick);
584 const char *ipaddr = inet_ntoa(ip4);
588 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
589 // using one as a registered connection. As theyre per fd, we can also safely assume
590 // that we wont have collisions. Therefore, if the nick exists in the list, its only
591 // used by a dead socket, erase the iterator so that the new client may reclaim it.
592 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
593 // issue in earlier alphas/betas
594 if (iter != clientlist.end())
596 userrec* goner = iter->second;
598 clientlist.erase(iter);
601 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
603 clientlist[tempnick] = new userrec();
604 clientlist[tempnick]->fd = socket;
605 strlcpy(clientlist[tempnick]->nick,tempnick.c_str(),NICKMAX-1);
607 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
608 for (char* temp = (char*)ipaddr; *temp && j < 64; temp++, j++)
609 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = *temp;
610 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = 0;
612 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
613 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
614 strcpy(clientlist[tempnick]->ident, "unknown");
616 clientlist[tempnick]->registered = 0;
617 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
618 clientlist[tempnick]->lastping = 1;
619 clientlist[tempnick]->ip4 = ip4;
620 clientlist[tempnick]->port = port;
622 // set the registration timeout for this user
623 unsigned long class_regtimeout = 90;
625 long class_threshold = 5;
626 long class_sqmax = 262144; // 256kb
627 long class_rqmax = 4096; // 4k
629 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
631 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
633 class_regtimeout = (unsigned long)i->registration_timeout;
634 class_flood = i->flood;
635 clientlist[tempnick]->pingmax = i->pingtime;
636 class_threshold = i->threshold;
637 class_sqmax = i->sendqmax;
638 class_rqmax = i->recvqmax;
643 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
644 clientlist[tempnick]->timeout = TIME+class_regtimeout;
645 clientlist[tempnick]->flood = class_flood;
646 clientlist[tempnick]->threshold = class_threshold;
647 clientlist[tempnick]->sendqmax = class_sqmax;
648 clientlist[tempnick]->recvqmax = class_rqmax;
650 fd_ref_table[socket] = clientlist[tempnick];
651 local_users.push_back(clientlist[tempnick]);
653 if (local_users.size() > Config->SoftLimit)
655 kill_link(clientlist[tempnick],"No more connections allowed");
659 if (local_users.size() >= MAXCLIENTS)
661 kill_link(clientlist[tempnick],"No more connections allowed");
665 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
666 // its a pretty big but for the moment valid assumption:
667 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
668 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
669 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
670 // which for the time being is a physical impossibility (even the largest networks dont have more
671 // than about 10,000 users on ONE server!)
672 if ((unsigned)socket >= MAX_DESCRIPTORS)
674 kill_link(clientlist[tempnick],"Server is full");
677 char* e = matches_exception(ipaddr);
680 char* r = matches_zline(ipaddr);
684 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
685 kill_link(clientlist[tempnick],reason);
690 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
692 WriteServ(clientlist[tempnick]->fd,"NOTICE Auth :*** Looking up your hostname...");
695 long FindMatchingGlobal(userrec* user)
698 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
700 if (a->second->ip4.s_addr == user->ip4.s_addr)
706 long FindMatchingLocal(userrec* user)
709 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
711 userrec* comp = (userrec*)(*a);
712 if (comp->ip4.s_addr == user->ip4.s_addr)
718 void FullConnectUser(userrec* user, CullList* Goners)
720 ServerInstance->stats->statsConnects++;
721 user->idle_lastmsg = TIME;
722 log(DEBUG,"ConnectUser: %s",user->nick);
724 ConnectClass a = GetClass(user);
726 if (a.type == CC_DENY)
728 Goners->AddItem(user,"Unauthorised connection");
731 if ((*(a.pass.c_str())) && (!user->haspassed))
733 Goners->AddItem(user,"Invalid password");
736 if (FindMatchingLocal(user) > a.maxlocal)
738 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
739 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,(char*)inet_ntoa(user->ip4));
742 else if (FindMatchingGlobal(user) > a.maxglobal)
744 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
745 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,(char*)inet_ntoa(user->ip4));
749 char match_against[MAXBUF];
750 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
751 char* e = matches_exception(match_against);
754 char* r = matches_gline(match_against);
758 snprintf(reason,MAXBUF,"G-Lined: %s",r);
759 Goners->AddItem(user,reason);
762 r = matches_kline(user->host);
766 snprintf(reason,MAXBUF,"K-Lined: %s",r);
767 Goners->AddItem(user,reason);
773 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
774 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
775 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
776 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
777 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
778 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
779 // so i'd better split it :)
780 std::stringstream out(Config->data005);
781 std::string token = "";
782 std::string line5 = "";
783 int token_counter = 0;
787 line5 = line5 + token + " ";
789 if ((token_counter >= 13) || (out.eof() == true))
791 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
798 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
799 // onto the network and produce 'fake direction'
800 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
801 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
802 user->registered = 7;
803 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,(char*)inet_ntoa(user->ip4));
806 /* re-allocates a nick in the user_hash after they change nicknames,
807 * returns a pointer to the new user as it may have moved */
809 userrec* ReHashNick(char* Old, char* New)
811 //user_hash::iterator newnick;
812 user_hash::iterator oldnick = clientlist.find(Old);
814 log(DEBUG,"ReHashNick: %s %s",Old,New);
816 if (!strcasecmp(Old,New))
818 log(DEBUG,"old nick is new nick, skipping");
819 return oldnick->second;
822 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
824 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
826 userrec* olduser = oldnick->second;
827 clientlist[New] = olduser;
828 clientlist.erase(oldnick);
830 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
832 return clientlist[New];
835 void force_nickchange(userrec* user,const char* newnick)
842 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
844 ServerInstance->stats->statsCollisions++;
845 kill_link(user,"Nickname collision");
848 if (matches_qline(newnick))
850 ServerInstance->stats->statsCollisions++;
851 kill_link(user,"Nickname collision");
859 strlcpy(nick,newnick,MAXBUF-1);
861 if (user->registered == 7)
865 std::string cmd = "NICK";
866 ServerInstance->Parser->CallHandler(cmd,pars,1,user);