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)
113 bool userrec::ProcessNoticeMasks(const char *sm)
129 if ((*c >= 'A') && (*c <= 'z'))
130 this->SetNoticeMask(*c, adding);
140 bool userrec::IsNoticeMaskSet(unsigned char sm)
142 return (snomasks[sm-65]);
145 void userrec::SetNoticeMask(unsigned char sm, bool value)
147 snomasks[sm-65] = value;
150 const char* userrec::FormatNoticeMasks()
152 static char data[MAXBUF];
155 for (int n = 0; n < 64; n++)
158 data[offset++] = n+65;
167 bool userrec::IsModeSet(unsigned char m)
169 return (modes[m-65]);
172 void userrec::SetMode(unsigned char m, bool value)
177 const char* userrec::FormatModes()
179 static char data[MAXBUF];
181 for (int n = 0; n < 64; n++)
184 data[offset++] = n+65;
192 // the PROPER way to do it, AVOID bzero at *ALL* costs
193 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
194 server = (char*)FindServerNamePtr(Config->ServerName);
196 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
197 timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
198 haspassed = dns_done = false;
203 chans.resize(MAXCHANS);
204 memset(modes,0,sizeof(modes));
206 for (unsigned int n = 0; n < MAXCHANS; n++)
208 ucrec* x = new ucrec();
217 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
219 ucrec* x = (ucrec*)*n;
224 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
225 void userrec::MakeHost(char* nhost)
227 /* This is much faster than snprintf */
229 for(char* n = ident; *n; n++)
232 for(char* n = host; *n; n++)
237 void userrec::CloseSocket()
239 shutdown(this->fd,2);
243 char* userrec::GetFullHost()
245 static char result[MAXBUF];
247 for(char* n = nick; *n; n++)
250 for(char* n = ident; *n; n++)
253 for(char* n = dhost; *n; n++)
259 char* userrec::MakeWildHost()
261 static char nresult[MAXBUF];
263 *t++ = '*'; *t++ = '!';
264 *t++ = '*'; *t++ = '@';
265 for(char* n = dhost; *n; n++)
271 int userrec::ReadData(void* buffer, size_t size)
275 return read(this->fd, buffer, size);
282 char* userrec::GetFullRealHost()
284 static char fresult[MAXBUF];
286 for(char* n = nick; *n; n++)
289 for(char* n = ident; *n; n++)
292 for(char* n = host; *n; n++)
298 bool userrec::IsInvited(irc::string &channel)
300 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
302 irc::string compare = i->channel;
304 if (compare == channel)
313 InvitedList* userrec::GetInviteList()
318 void userrec::InviteTo(irc::string &channel)
323 invites.push_back(i);
326 void userrec::RemoveInvite(irc::string &channel)
328 log(DEBUG,"Removing invites");
332 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
334 irc::string compare = i->channel;
336 if (compare == channel)
345 bool userrec::HasPermission(const std::string &command)
352 * users on remote servers can completely bypass all permissions based checks.
353 * This prevents desyncs when one server has different type/class tags to another.
354 * That having been said, this does open things up to the possibility of source changes
355 * allowing remote kills, etc - but if they have access to the src, they most likely have
356 * access to the conf - so it's an end to a means either way.
361 // are they even an oper at all?
364 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
365 if (iter_opertype != opertypes.end())
367 char* Classes = strdup(iter_opertype->second);
368 char* myclass = strtok_r(Classes," ",&savept);
371 operclass_t::iterator iter_operclass = operclass.find(myclass);
372 if (iter_operclass != operclass.end())
374 char* CommandList = strdup(iter_operclass->second);
375 mycmd = strtok_r(CommandList," ",&savept2);
378 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
384 mycmd = strtok_r(NULL," ",&savept2);
388 myclass = strtok_r(NULL," ",&savept);
397 bool userrec::AddBuffer(const std::string &a)
401 for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
403 if ((*i != '\r') && (*i != '\0') && (*i != 7))
408 //unsigned int i = 0;
410 if (recvq.length() > (unsigned)this->recvqmax)
412 this->SetWriteError("RecvQ exceeded");
413 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
418 * return false if we've had more than 600 characters WITHOUT
419 * a carriage return (this is BAD, drop the socket)
424 bool userrec::BufferIsReady()
426 return (recvq.find('\n') != std::string::npos);
429 void userrec::ClearBuffer()
434 std::string userrec::GetBuffer()
439 const char* line = recvq.c_str();
441 std::string ret = "";
443 while ((*line != '\n') && (*line))
449 while ((*line == '\n') || (*line == '\r'))
457 void userrec::AddWriteBuf(const std::string &data)
459 if (*this->GetWriteError())
462 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
465 * Fix by brain - Set the error text BEFORE calling writeopers, because
466 * if we dont it'll recursively call here over and over again trying
467 * to repeatedly add the text to the sendq!
469 this->SetWriteError("SendQ exceeded");
470 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
477 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
478 void userrec::FlushWriteBuf()
480 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
482 char* tb = (char*)this->sendq.c_str();
483 int n_sent = write(this->fd,tb,this->sendq.length());
487 this->SetWriteError(strerror(errno));
494 // update the user's stats counters
495 this->bytes_out += n_sent;
501 void userrec::SetWriteError(const std::string &error)
503 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
504 // don't try to set the error twice, its already set take the first string.
505 if (this->WriteError == "")
506 this->WriteError = error;
509 const char* userrec::GetWriteError()
511 return this->WriteError.c_str();
514 void AddOper(userrec* user)
516 log(DEBUG,"Oper added to optimization list");
517 all_opers.push_back(user);
520 void DeleteOper(userrec* user)
522 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
526 log(DEBUG,"Oper removed from optimization list");
533 void kill_link(userrec *user,const char* r)
535 user_hash::iterator iter = clientlist.find(user->nick);
538 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
539 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
541 * I can't imagine this blowing up, so I'm commenting it out. We still check
542 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
544 * if (iter == clientlist.end())
550 strlcpy(reason,r,MAXQUIT-1);
551 log(DEBUG,"kill_link: %s %d '%s'",user->nick,user->fd,reason);
554 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
556 if (user->registered == 7)
558 purge_empty_chans(user);
559 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
560 WriteCommonExcept(user,"QUIT :%s",reason);
564 user->FlushWriteBuf();
566 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
570 if (Config->GetIOHook(user->port))
574 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
576 catch (ModuleException& modexcept)
578 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
582 ServerInstance->SE->DelFd(user->fd);
587 * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
588 * if they were an oper with +s.
591 * In the current implementation, we only show local quits, as we only show local connects. With
592 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
594 if (user->registered == 7)
597 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
601 if (iter != clientlist.end())
603 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
606 fd_ref_table[user->fd] = NULL;
607 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
609 local_users.erase(find(local_users.begin(),local_users.end(),user));
610 log(DEBUG,"Delete local user");
613 clientlist.erase(iter);
618 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
620 this->host = strdup(user->host);
621 this->dhost = strdup(user->dhost);
622 this->ident = strdup(user->ident);
623 this->server = user->server;
624 this->gecos = strdup(user->fullname);
627 WhoWasGroup::~WhoWasGroup()
639 /* adds or updates an entry in the whowas list */
640 void AddWhoWas(userrec* u)
642 whowas_users::iterator iter = whowas.find(u->nick);
644 if (iter == whowas.end())
646 whowas_set* n = new whowas_set;
647 WhoWasGroup *a = new WhoWasGroup(u);
653 whowas_set* group = (whowas_set*)iter->second;
655 if (group->size() > 10)
657 WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
662 WhoWasGroup *a = new WhoWasGroup(u);
667 /* every hour, run this function which removes all entries over 3 days */
668 void MaintainWhoWas(time_t TIME)
670 for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
672 whowas_set* n = (whowas_set*)iter->second;
675 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
677 WhoWasGroup *a = *(n->begin());
679 n->erase(n->begin());
685 /* add a client connection to the sockets list */
686 void AddClient(int socket, int port, bool iscached, in_addr ip4)
688 std::string tempnick = ConvToStr(socket) + "-unknown";
689 user_hash::iterator iter = clientlist.find(tempnick);
690 const char *ipaddr = inet_ntoa(ip4);
695 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
696 * using one as a registered connection. As they are per fd, we can also safely assume
697 * that we wont have collisions. Therefore, if the nick exists in the list, its only
698 * used by a dead socket, erase the iterator so that the new client may reclaim it.
699 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
700 * issue in earlier alphas/betas
702 if (iter != clientlist.end())
704 userrec* goner = iter->second;
706 clientlist.erase(iter);
709 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
711 clientlist[tempnick] = new userrec();
712 clientlist[tempnick]->fd = socket;
713 strlcpy(clientlist[tempnick]->nick,tempnick.c_str(),NICKMAX-1);
715 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
716 for (char* temp = (char*)ipaddr; *temp && j < 64; temp++, j++)
717 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = *temp;
718 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = 0;
720 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
721 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
722 strcpy(clientlist[tempnick]->ident, "unknown");
724 clientlist[tempnick]->registered = 0;
725 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
726 clientlist[tempnick]->lastping = 1;
727 clientlist[tempnick]->ip4 = ip4;
728 clientlist[tempnick]->port = port;
730 // set the registration timeout for this user
731 unsigned long class_regtimeout = 90;
733 long class_threshold = 5;
734 long class_sqmax = 262144; // 256kb
735 long class_rqmax = 4096; // 4k
737 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
739 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
741 class_regtimeout = (unsigned long)i->registration_timeout;
742 class_flood = i->flood;
743 clientlist[tempnick]->pingmax = i->pingtime;
744 class_threshold = i->threshold;
745 class_sqmax = i->sendqmax;
746 class_rqmax = i->recvqmax;
751 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
752 clientlist[tempnick]->timeout = TIME+class_regtimeout;
753 clientlist[tempnick]->flood = class_flood;
754 clientlist[tempnick]->threshold = class_threshold;
755 clientlist[tempnick]->sendqmax = class_sqmax;
756 clientlist[tempnick]->recvqmax = class_rqmax;
758 fd_ref_table[socket] = clientlist[tempnick];
759 local_users.push_back(clientlist[tempnick]);
761 if (local_users.size() > Config->SoftLimit)
763 kill_link(clientlist[tempnick],"No more connections allowed");
767 if (local_users.size() >= MAXCLIENTS)
769 kill_link(clientlist[tempnick],"No more connections allowed");
775 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
776 * its a pretty big but for the moment valid assumption:
777 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
778 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
779 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
780 * which for the time being is a physical impossibility (even the largest networks dont have more
781 * than about 10,000 users on ONE server!)
783 if ((unsigned)socket >= MAX_DESCRIPTORS)
785 kill_link(clientlist[tempnick],"Server is full");
788 char* e = matches_exception(ipaddr);
791 char* r = matches_zline(ipaddr);
795 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
796 kill_link(clientlist[tempnick],reason);
803 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
806 WriteServ(clientlist[tempnick]->fd,"NOTICE Auth :*** Looking up your hostname...");
809 long FindMatchingGlobal(userrec* user)
812 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
814 if (a->second->ip4.s_addr == user->ip4.s_addr)
820 long FindMatchingLocal(userrec* user)
823 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
825 userrec* comp = (userrec*)(*a);
826 if (comp->ip4.s_addr == user->ip4.s_addr)
832 void FullConnectUser(userrec* user, CullList* Goners)
834 ServerInstance->stats->statsConnects++;
835 user->idle_lastmsg = TIME;
836 log(DEBUG,"ConnectUser: %s",user->nick);
838 ConnectClass a = GetClass(user);
840 if (a.type == CC_DENY)
842 Goners->AddItem(user,"Unauthorised connection");
846 if ((*(a.pass.c_str())) && (!user->haspassed))
848 Goners->AddItem(user,"Invalid password");
852 if (FindMatchingLocal(user) > a.maxlocal)
854 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
855 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,(char*)inet_ntoa(user->ip4));
858 else if (FindMatchingGlobal(user) > a.maxglobal)
860 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
861 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,(char*)inet_ntoa(user->ip4));
865 char match_against[MAXBUF];
866 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
867 char* e = matches_exception(match_against);
871 char* r = matches_gline(match_against);
876 snprintf(reason,MAXBUF,"G-Lined: %s",r);
877 Goners->AddItem(user,reason);
881 r = matches_kline(match_against);
886 snprintf(reason,MAXBUF,"K-Lined: %s",r);
887 Goners->AddItem(user,reason);
893 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
894 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
895 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
896 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
897 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
899 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
900 // so i'd better split it :)
901 std::stringstream out(Config->data005);
902 std::string token = "";
903 std::string line5 = "";
904 int token_counter = 0;
909 line5 = line5 + token + " ";
912 if ((token_counter >= 13) || (out.eof() == true))
914 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
923 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
924 * changes dont go out onto the network and produce 'fake direction'.
926 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
927 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
928 user->registered = 7;
929 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));
933 * re-allocates a nick in the user_hash after they change nicknames,
934 * returns a pointer to the new user as it may have moved
936 userrec* ReHashNick(const char* Old, const char* New)
938 //user_hash::iterator newnick;
939 user_hash::iterator oldnick = clientlist.find(Old);
941 log(DEBUG,"ReHashNick: %s %s",Old,New);
943 if (!strcasecmp(Old,New))
945 log(DEBUG,"old nick is new nick, skipping");
946 return oldnick->second;
949 if (oldnick == clientlist.end())
950 return NULL; /* doesnt exist */
952 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
954 userrec* olduser = oldnick->second;
955 clientlist[New] = olduser;
956 clientlist.erase(oldnick);
958 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
960 return clientlist[New];
963 void force_nickchange(userrec* user,const char* newnick)
970 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
974 ServerInstance->stats->statsCollisions++;
975 kill_link(user,"Nickname collision");
979 if (matches_qline(newnick))
981 ServerInstance->stats->statsCollisions++;
982 kill_link(user,"Nickname collision");
990 strlcpy(nick,newnick,MAXBUF-1);
993 if (user->registered == 7)
997 std::string cmd = "NICK";
999 ServerInstance->Parser->CallHandler(cmd,pars,1,user);