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;
223 if ((!dns_done) && (registered >= 3))
225 pthread_kill(this->dnsthread, SIGTERM);
230 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
231 void userrec::MakeHost(char* nhost)
233 /* This is much faster than snprintf */
235 for(char* n = ident; *n; n++)
238 for(char* n = host; *n; n++)
243 void userrec::CloseSocket()
245 shutdown(this->fd,2);
249 char* userrec::GetFullHost()
251 static char result[MAXBUF];
253 for(char* n = nick; *n; n++)
256 for(char* n = ident; *n; n++)
259 for(char* n = dhost; *n; n++)
265 char* userrec::MakeWildHost()
267 static char nresult[MAXBUF];
269 *t++ = '*'; *t++ = '!';
270 *t++ = '*'; *t++ = '@';
271 for(char* n = dhost; *n; n++)
277 int userrec::ReadData(void* buffer, size_t size)
281 return read(this->fd, buffer, size);
288 char* userrec::GetFullRealHost()
290 static char fresult[MAXBUF];
292 for(char* n = nick; *n; n++)
295 for(char* n = ident; *n; n++)
298 for(char* n = host; *n; n++)
304 bool userrec::IsInvited(irc::string &channel)
306 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
308 irc::string compare = i->channel;
310 if (compare == channel)
318 InvitedList* userrec::GetInviteList()
323 void userrec::InviteTo(irc::string &channel)
327 invites.push_back(i);
330 void userrec::RemoveInvite(irc::string &channel)
332 log(DEBUG,"Removing invites");
336 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
338 irc::string compare = i->channel;
340 if (compare == channel)
349 bool userrec::HasPermission(const std::string &command)
356 * users on remote servers can completely bypass all permissions based checks.
357 * This prevents desyncs when one server has different type/class tags to another.
358 * That having been said, this does open things up to the possibility of source changes
359 * allowing remote kills, etc - but if they have access to the src, they most likely have
360 * access to the conf - so it's an end to a means either way.
365 // are they even an oper at all?
368 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
369 if (iter_opertype != opertypes.end())
371 char* Classes = strdup(iter_opertype->second);
372 char* myclass = strtok_r(Classes," ",&savept);
375 operclass_t::iterator iter_operclass = operclass.find(myclass);
376 if (iter_operclass != operclass.end())
378 char* CommandList = strdup(iter_operclass->second);
379 mycmd = strtok_r(CommandList," ",&savept2);
382 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
388 mycmd = strtok_r(NULL," ",&savept2);
392 myclass = strtok_r(NULL," ",&savept);
401 bool userrec::AddBuffer(const std::string &a)
405 /* NB: std::string is arsey about \r and \n and tries to translate them
406 * somehow, so we CANNOT use std::string::find() here :(
408 for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
417 if (recvq.length() > (unsigned)this->recvqmax)
419 this->SetWriteError("RecvQ exceeded");
420 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
427 bool userrec::BufferIsReady()
429 return (recvq.find('\n') != std::string::npos);
432 void userrec::ClearBuffer()
437 std::string userrec::GetBuffer()
442 /* Strip any leading \r or \n off the string.
443 * Usually there are only one or two of these,
444 * so its is computationally cheap to do.
446 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
447 recvq.erase(recvq.begin());
449 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
451 /* Find the first complete line, return it as the
452 * result, and leave the recvq as whats left
456 std::string ret = std::string(recvq.begin(), x);
457 recvq.erase(recvq.begin(), x + 1);
464 void userrec::AddWriteBuf(const std::string &data)
466 if (*this->GetWriteError())
469 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
472 * Fix by brain - Set the error text BEFORE calling writeopers, because
473 * if we dont it'll recursively call here over and over again trying
474 * to repeatedly add the text to the sendq!
476 this->SetWriteError("SendQ exceeded");
477 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
481 if (data.length() > 512)
483 std::string newdata(data);
485 newdata.append("\r\n");
486 sendq.append(newdata);
494 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
495 void userrec::FlushWriteBuf()
497 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
499 const char* tb = this->sendq.c_str();
500 int n_sent = write(this->fd,tb,this->sendq.length());
504 this->SetWriteError(strerror(errno));
511 // update the user's stats counters
512 this->bytes_out += n_sent;
518 void userrec::SetWriteError(const std::string &error)
520 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
521 // don't try to set the error twice, its already set take the first string.
522 if (!this->WriteError.length())
523 this->WriteError = error;
526 const char* userrec::GetWriteError()
528 return this->WriteError.c_str();
531 void AddOper(userrec* user)
533 log(DEBUG,"Oper added to optimization list");
534 all_opers.push_back(user);
537 void DeleteOper(userrec* user)
539 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
543 log(DEBUG,"Oper removed from optimization list");
550 void kill_link(userrec *user,const char* r)
552 user_hash::iterator iter = clientlist.find(user->nick);
555 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
556 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
558 * I can't imagine this blowing up, so I'm commenting it out. We still check
559 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
561 * if (iter == clientlist.end())
567 strlcpy(reason,r,MAXQUIT-1);
568 log(DEBUG,"kill_link: %s %d '%s'",user->nick,user->fd,reason);
571 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
573 if (user->registered == 7)
575 purge_empty_chans(user);
576 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
577 WriteCommonExcept(user,"QUIT :%s",reason);
581 user->FlushWriteBuf();
583 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
587 if (Config->GetIOHook(user->port))
591 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
593 catch (ModuleException& modexcept)
595 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
599 ServerInstance->SE->DelFd(user->fd);
604 * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
605 * if they were an oper with +s.
608 * In the current implementation, we only show local quits, as we only show local connects. With
609 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
611 if (user->registered == 7)
614 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
618 if (iter != clientlist.end())
620 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
623 fd_ref_table[user->fd] = NULL;
624 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
626 local_users.erase(find(local_users.begin(),local_users.end(),user));
627 log(DEBUG,"Delete local user");
630 clientlist.erase(iter);
635 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
637 this->host = strdup(user->host);
638 this->dhost = strdup(user->dhost);
639 this->ident = strdup(user->ident);
640 this->server = user->server;
641 this->gecos = strdup(user->fullname);
644 WhoWasGroup::~WhoWasGroup()
656 /* adds or updates an entry in the whowas list */
657 void AddWhoWas(userrec* u)
659 whowas_users::iterator iter = whowas.find(u->nick);
661 if (iter == whowas.end())
663 whowas_set* n = new whowas_set;
664 WhoWasGroup *a = new WhoWasGroup(u);
670 whowas_set* group = (whowas_set*)iter->second;
672 if (group->size() > 10)
674 WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
679 WhoWasGroup *a = new WhoWasGroup(u);
684 /* every hour, run this function which removes all entries over 3 days */
685 void MaintainWhoWas(time_t TIME)
687 for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
689 whowas_set* n = (whowas_set*)iter->second;
692 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
694 WhoWasGroup *a = *(n->begin());
696 n->erase(n->begin());
702 /* add a client connection to the sockets list */
703 void AddClient(int socket, int port, bool iscached, in_addr ip4)
705 std::string tempnick = ConvToStr(socket) + "-unknown";
706 user_hash::iterator iter = clientlist.find(tempnick);
707 const char *ipaddr = inet_ntoa(ip4);
713 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
714 * using one as a registered connection. As they are per fd, we can also safely assume
715 * that we wont have collisions. Therefore, if the nick exists in the list, its only
716 * used by a dead socket, erase the iterator so that the new client may reclaim it.
717 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
718 * issue in earlier alphas/betas
720 if (iter != clientlist.end())
722 userrec* goner = iter->second;
724 clientlist.erase(iter);
727 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
729 _new = new userrec();
730 clientlist[tempnick] = _new;
732 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
734 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
735 for (const char* temp = ipaddr; *temp && j < 64; temp++, j++)
736 _new->dhost[j] = _new->host[j] = *temp;
737 _new->dhost[j] = _new->host[j] = 0;
739 _new->server = FindServerNamePtr(Config->ServerName);
740 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
741 strcpy(_new->ident, "unknown");
743 _new->registered = 0;
744 _new->signon = TIME + Config->dns_timeout;
749 // set the registration timeout for this user
750 unsigned long class_regtimeout = 90;
752 long class_threshold = 5;
753 long class_sqmax = 262144; // 256kb
754 long class_rqmax = 4096; // 4k
756 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
758 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
760 class_regtimeout = (unsigned long)i->registration_timeout;
761 class_flood = i->flood;
762 _new->pingmax = i->pingtime;
763 class_threshold = i->threshold;
764 class_sqmax = i->sendqmax;
765 class_rqmax = i->recvqmax;
770 _new->nping = TIME + _new->pingmax + Config->dns_timeout;
771 _new->timeout = TIME+class_regtimeout;
772 _new->flood = class_flood;
773 _new->threshold = class_threshold;
774 _new->sendqmax = class_sqmax;
775 _new->recvqmax = class_rqmax;
777 fd_ref_table[socket] = _new;
778 local_users.push_back(_new);
780 if (local_users.size() > Config->SoftLimit)
782 kill_link(_new,"No more connections allowed");
786 if (local_users.size() >= MAXCLIENTS)
788 kill_link(_new,"No more connections allowed");
794 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
795 * its a pretty big but for the moment valid assumption:
796 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
797 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
798 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
799 * which for the time being is a physical impossibility (even the largest networks dont have more
800 * than about 10,000 users on ONE server!)
802 if ((unsigned)socket >= MAX_DESCRIPTORS)
804 kill_link(_new,"Server is full");
807 char* e = matches_exception(ipaddr);
810 char* r = matches_zline(ipaddr);
814 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
815 kill_link(_new,reason);
822 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
825 WriteServ(_new->fd,"NOTICE Auth :*** Looking up your hostname...");
828 long FindMatchingGlobal(userrec* user)
831 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
833 if (a->second->ip4.s_addr == user->ip4.s_addr)
839 long FindMatchingLocal(userrec* user)
842 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
844 userrec* comp = (userrec*)(*a);
845 if (comp->ip4.s_addr == user->ip4.s_addr)
851 void FullConnectUser(userrec* user, CullList* Goners)
853 ServerInstance->stats->statsConnects++;
854 user->idle_lastmsg = TIME;
855 log(DEBUG,"ConnectUser: %s",user->nick);
857 ConnectClass a = GetClass(user);
859 if (a.type == CC_DENY)
861 Goners->AddItem(user,"Unauthorised connection");
865 if ((*(a.pass.c_str())) && (!user->haspassed))
867 Goners->AddItem(user,"Invalid password");
871 if (FindMatchingLocal(user) > a.maxlocal)
873 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
874 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,inet_ntoa(user->ip4));
877 else if (FindMatchingGlobal(user) > a.maxglobal)
879 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
880 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,inet_ntoa(user->ip4));
884 char match_against[MAXBUF];
885 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
886 char* e = matches_exception(match_against);
890 char* r = matches_gline(match_against);
895 snprintf(reason,MAXBUF,"G-Lined: %s",r);
896 Goners->AddItem(user,reason);
900 r = matches_kline(match_against);
905 snprintf(reason,MAXBUF,"K-Lined: %s",r);
906 Goners->AddItem(user,reason);
912 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
913 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
914 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
915 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
916 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
918 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
919 // so i'd better split it :)
920 std::stringstream out(Config->data005);
921 std::string token = "";
922 std::string line5 = "";
923 int token_counter = 0;
928 line5 = line5 + token + " ";
931 if ((token_counter >= 13) || (out.eof() == true))
933 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
942 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
943 * changes dont go out onto the network and produce 'fake direction'.
945 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
946 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
947 user->registered = 7;
948 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,inet_ntoa(user->ip4));
952 * re-allocates a nick in the user_hash after they change nicknames,
953 * returns a pointer to the new user as it may have moved
955 userrec* ReHashNick(const char* Old, const char* New)
957 //user_hash::iterator newnick;
958 user_hash::iterator oldnick = clientlist.find(Old);
960 log(DEBUG,"ReHashNick: %s %s",Old,New);
962 if (!strcasecmp(Old,New))
964 log(DEBUG,"old nick is new nick, skipping");
965 return oldnick->second;
968 if (oldnick == clientlist.end())
969 return NULL; /* doesnt exist */
971 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
973 userrec* olduser = oldnick->second;
974 clientlist[New] = olduser;
975 clientlist.erase(oldnick);
977 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
979 return clientlist[New];
982 void force_nickchange(userrec* user,const char* newnick)
989 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
993 ServerInstance->stats->statsCollisions++;
994 kill_link(user,"Nickname collision");
998 if (matches_qline(newnick))
1000 ServerInstance->stats->statsCollisions++;
1001 kill_link(user,"Nickname collision");
1009 strlcpy(nick,newnick,MAXBUF-1);
1012 if (user->registered == 7)
1014 const char* pars[1];
1016 std::string cmd = "NICK";
1018 ServerInstance->Parser->CallHandler(cmd,pars,1,user);