1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 #include "inspircd_config.h"
18 #include "configreader.h"
20 #include "connection.h"
28 #include "inspstring.h"
30 #include "helperfuncs.h"
32 #include "socketengine.h"
37 #include "cull_list.h"
39 extern InspIRCd* ServerInstance;
40 extern int WHOWAS_STALE;
41 extern int WHOWAS_MAX;
42 extern std::vector<Module*> modules;
43 extern std::vector<ircd_module*> factory;
44 extern std::vector<InspSocket*> module_sockets;
46 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
48 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
49 extern ServerConfig *Config;
50 extern user_hash clientlist;
54 extern std::vector<userrec*> local_users;
56 std::vector<userrec*> all_opers;
58 typedef std::map<irc::string,char*> opertype_t;
59 typedef opertype_t operclass_t;
62 operclass_t operclass;
64 bool InitTypes(const char* tag)
66 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++)
88 bool DoType(const char* tag, char** entries, void** values, int* types)
90 char* TypeName = (char*)values[0];
91 char* Classes = (char*)values[1];
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];
103 operclass[ClassName] = strdup(CommandList);
104 log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
108 bool DoneClassesAndTypes(const char* tag)
115 // the PROPER way to do it, AVOID bzero at *ALL* costs
116 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
117 server = (char*)FindServerNamePtr(Config->ServerName);
119 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
120 timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
121 haspassed = dns_done = false;
126 chans.resize(MAXCHANS);
127 memset(modes,0,sizeof(modes));
129 for (unsigned int n = 0; n < MAXCHANS; n++)
131 ucrec* x = new ucrec();
140 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
142 ucrec* x = (ucrec*)*n;
147 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
148 void userrec::MakeHost(char* nhost)
150 /* This is much faster than snprintf */
152 for(char* n = ident; *n; n++)
155 for(char* n = host; *n; n++)
160 void userrec::CloseSocket()
162 shutdown(this->fd,2);
166 char* userrec::GetFullHost()
168 static char result[MAXBUF];
170 for(char* n = nick; *n; n++)
173 for(char* n = ident; *n; n++)
176 for(char* n = dhost; *n; n++)
182 char* userrec::MakeWildHost()
184 static char nresult[MAXBUF];
186 *t++ = '*'; *t++ = '!';
187 *t++ = '*'; *t++ = '@';
188 for(char* n = dhost; *n; n++)
194 int userrec::ReadData(void* buffer, size_t size)
198 return read(this->fd, buffer, size);
205 char* userrec::GetFullRealHost()
207 static char fresult[MAXBUF];
209 for(char* n = nick; *n; n++)
212 for(char* n = ident; *n; n++)
215 for(char* n = host; *n; n++)
221 bool userrec::IsInvited(irc::string &channel)
223 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
225 irc::string compare = i->channel;
227 if (compare == channel)
236 InvitedList* userrec::GetInviteList()
241 void userrec::InviteTo(irc::string &channel)
246 invites.push_back(i);
249 void userrec::RemoveInvite(irc::string &channel)
251 log(DEBUG,"Removing invites");
255 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
257 irc::string compare = i->channel;
259 if (compare == channel)
268 bool userrec::HasPermission(const std::string &command)
275 * users on remote servers can completely bypass all permissions based checks.
276 * This prevents desyncs when one server has different type/class tags to another.
277 * That having been said, this does open things up to the possibility of source changes
278 * allowing remote kills, etc - but if they have access to the src, they most likely have
279 * access to the conf - so it's an end to a means either way.
284 // are they even an oper at all?
287 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
288 if (iter_opertype != opertypes.end())
290 char* Classes = strdup(iter_opertype->second);
291 char* myclass = strtok_r(Classes," ",&savept);
294 operclass_t::iterator iter_operclass = operclass.find(myclass);
295 if (iter_operclass != operclass.end())
297 char* CommandList = strdup(iter_operclass->second);
298 mycmd = strtok_r(CommandList," ",&savept2);
301 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
307 mycmd = strtok_r(NULL," ",&savept2);
311 myclass = strtok_r(NULL," ",&savept);
320 bool userrec::AddBuffer(const std::string &a)
323 char* n = (char*)a.c_str();
325 for (char* i = n; *i; i++)
327 if ((*i != '\r') && (*i != '\0') && (*i != 7))
334 // count the size of the first line in the buffer.
335 while (i < recvq.length())
337 if (recvq[i++] == '\n')
340 if (recvq.length() > (unsigned)this->recvqmax)
342 this->SetWriteError("RecvQ exceeded");
343 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
347 * return false if we've had more than 600 characters WITHOUT
348 * a carriage return (this is BAD, drop the socket)
353 bool userrec::BufferIsReady()
355 unsigned int t = recvq.length();
357 for (unsigned int i = 0; i < t; i++)
358 if (recvq[i] == '\n')
363 void userrec::ClearBuffer()
368 std::string userrec::GetBuffer()
373 char* line = (char*)recvq.c_str();
375 std::string ret = "";
377 while ((*line != '\n') && (*line))
383 while ((*line == '\n') || (*line == '\r'))
391 void userrec::AddWriteBuf(const std::string &data)
393 if (*this->GetWriteError())
396 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
399 * Fix by brain - Set the error text BEFORE calling writeopers, because
400 * if we dont it'll recursively call here over and over again trying
401 * to repeatedly add the text to the sendq!
403 this->SetWriteError("SendQ exceeded");
404 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
411 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
412 void userrec::FlushWriteBuf()
414 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
416 char* tb = (char*)this->sendq.c_str();
417 int n_sent = write(this->fd,tb,this->sendq.length());
421 this->SetWriteError(strerror(errno));
428 // update the user's stats counters
429 this->bytes_out += n_sent;
435 void userrec::SetWriteError(const std::string &error)
437 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
438 // don't try to set the error twice, its already set take the first string.
439 if (this->WriteError == "")
440 this->WriteError = error;
443 const char* userrec::GetWriteError()
445 return this->WriteError.c_str();
448 void AddOper(userrec* user)
450 log(DEBUG,"Oper added to optimization list");
451 all_opers.push_back(user);
454 void DeleteOper(userrec* user)
456 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
460 log(DEBUG,"Oper removed from optimization list");
467 void kill_link(userrec *user,const char* r)
469 user_hash::iterator iter = clientlist.find(user->nick);
472 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
473 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
475 * I can't imagine this blowing up, so I'm commenting it out. We still check
476 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
478 * if (iter == clientlist.end())
484 strlcpy(reason,r,MAXQUIT-1);
485 log(DEBUG,"kill_link: %s %d '%s'",user->nick,user->fd,reason);
488 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
490 if (user->registered == 7)
492 purge_empty_chans(user);
493 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
494 WriteCommonExcept(user,"QUIT :%s",reason);
498 user->FlushWriteBuf();
500 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
504 if (Config->GetIOHook(user->port))
508 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
510 catch (ModuleException& modexcept)
512 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
516 ServerInstance->SE->DelFd(user->fd);
521 * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
522 * if they were an oper with +s.
525 * In the current implementation, we only show local quits, as we only show local connects. With
526 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
528 if (user->registered == 7)
531 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
535 if (iter != clientlist.end())
537 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
540 fd_ref_table[user->fd] = NULL;
541 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
543 local_users.erase(find(local_users.begin(),local_users.end(),user));
544 log(DEBUG,"Delete local user");
547 clientlist.erase(iter);
552 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
554 this->host = strdup(user->host);
555 this->dhost = strdup(user->dhost);
556 this->ident = strdup(user->ident);
557 this->server = user->server;
558 this->gecos = strdup(user->fullname);
561 WhoWasGroup::~WhoWasGroup()
573 /* adds or updates an entry in the whowas list */
574 void AddWhoWas(userrec* u)
576 whowas_users::iterator iter = whowas.find(u->nick);
578 if (iter == whowas.end())
580 whowas_set* n = new whowas_set;
581 WhoWasGroup *a = new WhoWasGroup(u);
587 whowas_set* group = (whowas_set*)iter->second;
589 if (group->size() > 10)
591 WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
596 WhoWasGroup *a = new WhoWasGroup(u);
601 /* every hour, run this function which removes all entries over 3 days */
602 void MaintainWhoWas(time_t TIME)
604 for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
606 whowas_set* n = (whowas_set*)iter->second;
609 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
611 WhoWasGroup *a = *(n->begin());
613 n->erase(n->begin());
619 /* add a client connection to the sockets list */
620 void AddClient(int socket, int port, bool iscached, in_addr ip4)
622 std::string tempnick = ConvToStr(socket) + "-unknown";
623 user_hash::iterator iter = clientlist.find(tempnick);
624 const char *ipaddr = inet_ntoa(ip4);
629 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
630 * using one as a registered connection. As they are per fd, we can also safely assume
631 * that we wont have collisions. Therefore, if the nick exists in the list, its only
632 * used by a dead socket, erase the iterator so that the new client may reclaim it.
633 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
634 * issue in earlier alphas/betas
636 if (iter != clientlist.end())
638 userrec* goner = iter->second;
640 clientlist.erase(iter);
643 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
645 clientlist[tempnick] = new userrec();
646 clientlist[tempnick]->fd = socket;
647 strlcpy(clientlist[tempnick]->nick,tempnick.c_str(),NICKMAX-1);
649 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
650 for (char* temp = (char*)ipaddr; *temp && j < 64; temp++, j++)
651 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = *temp;
652 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = 0;
654 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
655 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
656 strcpy(clientlist[tempnick]->ident, "unknown");
658 clientlist[tempnick]->registered = 0;
659 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
660 clientlist[tempnick]->lastping = 1;
661 clientlist[tempnick]->ip4 = ip4;
662 clientlist[tempnick]->port = port;
664 // set the registration timeout for this user
665 unsigned long class_regtimeout = 90;
667 long class_threshold = 5;
668 long class_sqmax = 262144; // 256kb
669 long class_rqmax = 4096; // 4k
671 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
673 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
675 class_regtimeout = (unsigned long)i->registration_timeout;
676 class_flood = i->flood;
677 clientlist[tempnick]->pingmax = i->pingtime;
678 class_threshold = i->threshold;
679 class_sqmax = i->sendqmax;
680 class_rqmax = i->recvqmax;
685 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
686 clientlist[tempnick]->timeout = TIME+class_regtimeout;
687 clientlist[tempnick]->flood = class_flood;
688 clientlist[tempnick]->threshold = class_threshold;
689 clientlist[tempnick]->sendqmax = class_sqmax;
690 clientlist[tempnick]->recvqmax = class_rqmax;
692 fd_ref_table[socket] = clientlist[tempnick];
693 local_users.push_back(clientlist[tempnick]);
695 if (local_users.size() > Config->SoftLimit)
697 kill_link(clientlist[tempnick],"No more connections allowed");
701 if (local_users.size() >= MAXCLIENTS)
703 kill_link(clientlist[tempnick],"No more connections allowed");
709 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
710 * its a pretty big but for the moment valid assumption:
711 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
712 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
713 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
714 * which for the time being is a physical impossibility (even the largest networks dont have more
715 * than about 10,000 users on ONE server!)
717 if ((unsigned)socket >= MAX_DESCRIPTORS)
719 kill_link(clientlist[tempnick],"Server is full");
722 char* e = matches_exception(ipaddr);
725 char* r = matches_zline(ipaddr);
729 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
730 kill_link(clientlist[tempnick],reason);
737 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
740 WriteServ(clientlist[tempnick]->fd,"NOTICE Auth :*** Looking up your hostname...");
743 long FindMatchingGlobal(userrec* user)
746 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
748 if (a->second->ip4.s_addr == user->ip4.s_addr)
754 long FindMatchingLocal(userrec* user)
757 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
759 userrec* comp = (userrec*)(*a);
760 if (comp->ip4.s_addr == user->ip4.s_addr)
766 void FullConnectUser(userrec* user, CullList* Goners)
768 ServerInstance->stats->statsConnects++;
769 user->idle_lastmsg = TIME;
770 log(DEBUG,"ConnectUser: %s",user->nick);
772 ConnectClass a = GetClass(user);
774 if (a.type == CC_DENY)
776 Goners->AddItem(user,"Unauthorised connection");
780 if ((*(a.pass.c_str())) && (!user->haspassed))
782 Goners->AddItem(user,"Invalid password");
786 if (FindMatchingLocal(user) > a.maxlocal)
788 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
789 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,(char*)inet_ntoa(user->ip4));
792 else if (FindMatchingGlobal(user) > a.maxglobal)
794 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
795 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,(char*)inet_ntoa(user->ip4));
799 char match_against[MAXBUF];
800 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
801 char* e = matches_exception(match_against);
805 char* r = matches_gline(match_against);
810 snprintf(reason,MAXBUF,"G-Lined: %s",r);
811 Goners->AddItem(user,reason);
815 r = matches_kline(match_against);
820 snprintf(reason,MAXBUF,"K-Lined: %s",r);
821 Goners->AddItem(user,reason);
827 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
828 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
829 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
830 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
831 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
833 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
834 // so i'd better split it :)
835 std::stringstream out(Config->data005);
836 std::string token = "";
837 std::string line5 = "";
838 int token_counter = 0;
843 line5 = line5 + token + " ";
846 if ((token_counter >= 13) || (out.eof() == true))
848 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
857 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
858 * changes dont go out onto the network and produce 'fake direction'.
860 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
861 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
862 user->registered = 7;
863 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));
867 * re-allocates a nick in the user_hash after they change nicknames,
868 * returns a pointer to the new user as it may have moved
870 userrec* ReHashNick(char* Old, char* New)
872 //user_hash::iterator newnick;
873 user_hash::iterator oldnick = clientlist.find(Old);
875 log(DEBUG,"ReHashNick: %s %s",Old,New);
877 if (!strcasecmp(Old,New))
879 log(DEBUG,"old nick is new nick, skipping");
880 return oldnick->second;
883 if (oldnick == clientlist.end())
884 return NULL; /* doesnt exist */
886 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
888 userrec* olduser = oldnick->second;
889 clientlist[New] = olduser;
890 clientlist.erase(oldnick);
892 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
894 return clientlist[New];
897 void force_nickchange(userrec* user,const char* newnick)
904 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
908 ServerInstance->stats->statsCollisions++;
909 kill_link(user,"Nickname collision");
913 if (matches_qline(newnick))
915 ServerInstance->stats->statsCollisions++;
916 kill_link(user,"Nickname collision");
924 strlcpy(nick,newnick,MAXBUF-1);
927 if (user->registered == 7)
932 std::string cmd = "NICK";
933 ServerInstance->Parser->CallHandler(cmd,pars,1,user);