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;
51 extern Server* MyServer;
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++)
77 bool InitClasses(const char* tag)
79 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
89 bool DoType(const char* tag, char** entries, void** values, int* types)
91 char* TypeName = (char*)values[0];
92 char* Classes = (char*)values[1];
94 opertypes[TypeName] = strdup(Classes);
95 log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
99 bool DoClass(const char* tag, char** entries, void** values, int* types)
101 char* ClassName = (char*)values[0];
102 char* CommandList = (char*)values[1];
104 operclass[ClassName] = strdup(CommandList);
105 log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
109 bool DoneClassesAndTypes(const char* tag)
114 bool userrec::ProcessNoticeMasks(const char *sm)
130 if ((*c >= 'A') && (*c <= 'z'))
131 this->SetNoticeMask(*c, adding);
141 void userrec::StartDNSLookup()
143 log(DEBUG,"Commencing forward lookup");
144 res_reverse = new UserResolver(this, insp_ntoa(this->ip4), false);
145 MyServer->AddResolver(res_reverse);
148 UserResolver::UserResolver(userrec* user, std::string to_resolve, bool forward) : Resolver(to_resolve, forward), bound_user(user)
150 this->bound_fd = user->fd;
153 void UserResolver::OnLookupComplete(const std::string &result)
155 if ((!this->fwd) && (fd_ref_table[this->bound_fd] == this->bound_user))
157 log(DEBUG,"Commencing reverse lookup");
158 this->bound_user->stored_host = result;
159 bound_user->res_forward = new UserResolver(this->bound_user, result, true);
160 MyServer->AddResolver(bound_user->res_forward);
162 else if ((this->fwd) && (fd_ref_table[this->bound_fd] == this->bound_user))
164 /* Both lookups completed */
165 if (insp_ntoa(this->bound_user->ip4) == result)
167 std::string hostname = this->bound_user->stored_host;
168 if (hostname.length() < 64)
170 WriteServ(this->bound_fd, "*** Found your hostname (%s)", this->bound_user->stored_host.c_str());
171 this->bound_user->dns_done = true;
172 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
173 strlcpy(this->bound_user->host, hostname.c_str(),64);
179 void UserResolver::OnError(ResolverError e)
181 if (fd_ref_table[this->bound_fd] == this->bound_user)
183 /* Error message here */
184 WriteServ(this->bound_fd, "*** Could not resolve your hostname, using your IP address (%s) instead.", insp_ntoa(this->bound_user->ip4));
185 this->bound_user->dns_done = true;
190 bool userrec::IsNoticeMaskSet(unsigned char sm)
192 return (snomasks[sm-65]);
195 void userrec::SetNoticeMask(unsigned char sm, bool value)
197 snomasks[sm-65] = value;
200 const char* userrec::FormatNoticeMasks()
202 static char data[MAXBUF];
205 for (int n = 0; n < 64; n++)
208 data[offset++] = n+65;
217 bool userrec::IsModeSet(unsigned char m)
219 return (modes[m-65]);
222 void userrec::SetMode(unsigned char m, bool value)
227 const char* userrec::FormatModes()
229 static char data[MAXBUF];
231 for (int n = 0; n < 64; n++)
234 data[offset++] = n+65;
242 // the PROPER way to do it, AVOID bzero at *ALL* costs
243 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
244 server = (char*)FindServerNamePtr(Config->ServerName);
246 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
247 timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
248 haspassed = dns_done = false;
251 res_forward = res_reverse = NULL;
254 chans.resize(MAXCHANS);
255 memset(modes,0,sizeof(modes));
257 for (unsigned int n = 0; n < MAXCHANS; n++)
259 ucrec* x = new ucrec();
268 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
270 ucrec* x = (ucrec*)*n;
274 if ((IS_LOCAL(this)) && (!dns_done) && (registered >= REG_NICKUSER))
276 pthread_kill(this->dnsthread, SIGTERM);
281 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
282 void userrec::MakeHost(char* nhost)
284 /* This is much faster than snprintf */
286 for(char* n = ident; *n; n++)
289 for(char* n = host; *n; n++)
294 void userrec::CloseSocket()
296 shutdown(this->fd,2);
300 char* userrec::GetFullHost()
302 static char result[MAXBUF];
304 for(char* n = nick; *n; n++)
307 for(char* n = ident; *n; n++)
310 for(char* n = dhost; *n; n++)
316 char* userrec::MakeWildHost()
318 static char nresult[MAXBUF];
320 *t++ = '*'; *t++ = '!';
321 *t++ = '*'; *t++ = '@';
322 for(char* n = dhost; *n; n++)
328 int userrec::ReadData(void* buffer, size_t size)
332 return read(this->fd, buffer, size);
339 char* userrec::GetFullRealHost()
341 static char fresult[MAXBUF];
343 for(char* n = nick; *n; n++)
346 for(char* n = ident; *n; n++)
349 for(char* n = host; *n; n++)
355 bool userrec::IsInvited(irc::string &channel)
357 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
359 irc::string compare = i->channel;
361 if (compare == channel)
369 InvitedList* userrec::GetInviteList()
374 void userrec::InviteTo(irc::string &channel)
378 invites.push_back(i);
381 void userrec::RemoveInvite(irc::string &channel)
383 log(DEBUG,"Removing invites");
387 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
389 irc::string compare = i->channel;
391 if (compare == channel)
400 bool userrec::HasPermission(const std::string &command)
407 * users on remote servers can completely bypass all permissions based checks.
408 * This prevents desyncs when one server has different type/class tags to another.
409 * That having been said, this does open things up to the possibility of source changes
410 * allowing remote kills, etc - but if they have access to the src, they most likely have
411 * access to the conf - so it's an end to a means either way.
416 // are they even an oper at all?
419 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
420 if (iter_opertype != opertypes.end())
422 char* Classes = strdup(iter_opertype->second);
423 char* myclass = strtok_r(Classes," ",&savept);
426 operclass_t::iterator iter_operclass = operclass.find(myclass);
427 if (iter_operclass != operclass.end())
429 char* CommandList = strdup(iter_operclass->second);
430 mycmd = strtok_r(CommandList," ",&savept2);
433 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
439 mycmd = strtok_r(NULL," ",&savept2);
443 myclass = strtok_r(NULL," ",&savept);
452 bool userrec::AddBuffer(const std::string &a)
456 /* NB: std::string is arsey about \r and \n and tries to translate them
457 * somehow, so we CANNOT use std::string::find() here :(
459 for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
468 if (recvq.length() > (unsigned)this->recvqmax)
470 this->SetWriteError("RecvQ exceeded");
471 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
478 bool userrec::BufferIsReady()
480 return (recvq.find('\n') != std::string::npos);
483 void userrec::ClearBuffer()
488 std::string userrec::GetBuffer()
493 /* Strip any leading \r or \n off the string.
494 * Usually there are only one or two of these,
495 * so its is computationally cheap to do.
497 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
498 recvq.erase(recvq.begin());
500 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
502 /* Find the first complete line, return it as the
503 * result, and leave the recvq as whats left
507 std::string ret = std::string(recvq.begin(), x);
508 recvq.erase(recvq.begin(), x + 1);
515 void userrec::AddWriteBuf(const std::string &data)
517 if (*this->GetWriteError())
520 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
523 * Fix by brain - Set the error text BEFORE calling writeopers, because
524 * if we dont it'll recursively call here over and over again trying
525 * to repeatedly add the text to the sendq!
527 this->SetWriteError("SendQ exceeded");
528 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
532 if (data.length() > 512)
534 std::string newdata(data);
536 newdata.append("\r\n");
537 sendq.append(newdata);
545 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
546 void userrec::FlushWriteBuf()
548 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
550 const char* tb = this->sendq.c_str();
551 int n_sent = write(this->fd,tb,this->sendq.length());
555 this->SetWriteError(strerror(errno));
562 // update the user's stats counters
563 this->bytes_out += n_sent;
569 void userrec::SetWriteError(const std::string &error)
571 // don't try to set the error twice, its already set take the first string.
572 if (!this->WriteError.length())
574 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
575 this->WriteError = error;
579 const char* userrec::GetWriteError()
581 return this->WriteError.c_str();
584 void AddOper(userrec* user)
586 log(DEBUG,"Oper added to optimization list");
587 all_opers.push_back(user);
590 void DeleteOper(userrec* user)
592 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
596 log(DEBUG,"Oper removed from optimization list");
603 void kill_link(userrec *user,const char* r)
605 user_hash::iterator iter = clientlist.find(user->nick);
608 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
609 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
611 * I can't imagine this blowing up, so I'm commenting it out. We still check
612 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
614 * if (iter == clientlist.end())
620 strlcpy(reason,r,MAXQUIT-1);
621 log(DEBUG,"kill_link: %s %d '%s'",user->nick,user->fd,reason);
624 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
626 if (user->registered == REG_ALL)
628 purge_empty_chans(user);
629 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
630 WriteCommonExcept(user,"QUIT :%s",reason);
634 user->FlushWriteBuf();
636 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
640 if (Config->GetIOHook(user->port))
644 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
646 catch (ModuleException& modexcept)
648 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
652 ServerInstance->SE->DelFd(user->fd);
657 * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
658 * if they were an oper with +s.
661 * In the current implementation, we only show local quits, as we only show local connects. With
662 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
664 if (user->registered == REG_ALL)
667 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
671 if (iter != clientlist.end())
673 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
676 fd_ref_table[user->fd] = NULL;
677 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
679 local_users.erase(find(local_users.begin(),local_users.end(),user));
680 log(DEBUG,"Delete local user");
683 clientlist.erase(iter);
688 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
690 this->host = strdup(user->host);
691 this->dhost = strdup(user->dhost);
692 this->ident = strdup(user->ident);
693 this->server = user->server;
694 this->gecos = strdup(user->fullname);
697 WhoWasGroup::~WhoWasGroup()
709 /* adds or updates an entry in the whowas list */
710 void AddWhoWas(userrec* u)
712 whowas_users::iterator iter = whowas.find(u->nick);
714 if (iter == whowas.end())
716 whowas_set* n = new whowas_set;
717 WhoWasGroup *a = new WhoWasGroup(u);
723 whowas_set* group = (whowas_set*)iter->second;
725 if (group->size() > 10)
727 WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
732 WhoWasGroup *a = new WhoWasGroup(u);
737 /* every hour, run this function which removes all entries over 3 days */
738 void MaintainWhoWas(time_t TIME)
740 for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
742 whowas_set* n = (whowas_set*)iter->second;
745 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
747 WhoWasGroup *a = *(n->begin());
749 n->erase(n->begin());
755 /* add a client connection to the sockets list */
756 void AddClient(int socket, int port, bool iscached, insp_inaddr ip4)
758 std::string tempnick = ConvToStr(socket) + "-unknown";
759 user_hash::iterator iter = clientlist.find(tempnick);
760 const char *ipaddr = insp_ntoa(ip4);
766 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
767 * using one as a registered connection. As they are per fd, we can also safely assume
768 * that we wont have collisions. Therefore, if the nick exists in the list, its only
769 * used by a dead socket, erase the iterator so that the new client may reclaim it.
770 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
771 * issue in earlier alphas/betas
773 if (iter != clientlist.end())
775 userrec* goner = iter->second;
777 clientlist.erase(iter);
780 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
782 _new = new userrec();
783 clientlist[tempnick] = _new;
785 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
787 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
788 for (const char* temp = ipaddr; *temp && j < 64; temp++, j++)
789 _new->dhost[j] = _new->host[j] = *temp;
790 _new->dhost[j] = _new->host[j] = 0;
792 _new->server = FindServerNamePtr(Config->ServerName);
793 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
794 strcpy(_new->ident, "unknown");
796 _new->registered = REG_NONE;
797 _new->signon = TIME + Config->dns_timeout;
802 // set the registration timeout for this user
803 unsigned long class_regtimeout = 90;
805 long class_threshold = 5;
806 long class_sqmax = 262144; // 256kb
807 long class_rqmax = 4096; // 4k
809 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
811 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
813 class_regtimeout = (unsigned long)i->registration_timeout;
814 class_flood = i->flood;
815 _new->pingmax = i->pingtime;
816 class_threshold = i->threshold;
817 class_sqmax = i->sendqmax;
818 class_rqmax = i->recvqmax;
823 _new->nping = TIME + _new->pingmax + Config->dns_timeout;
824 _new->timeout = TIME+class_regtimeout;
825 _new->flood = class_flood;
826 _new->threshold = class_threshold;
827 _new->sendqmax = class_sqmax;
828 _new->recvqmax = class_rqmax;
830 fd_ref_table[socket] = _new;
831 local_users.push_back(_new);
833 if (local_users.size() > Config->SoftLimit)
835 kill_link(_new,"No more connections allowed");
839 if (local_users.size() >= MAXCLIENTS)
841 kill_link(_new,"No more connections allowed");
847 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
848 * its a pretty big but for the moment valid assumption:
849 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
850 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
851 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
852 * which for the time being is a physical impossibility (even the largest networks dont have more
853 * than about 10,000 users on ONE server!)
855 if ((unsigned)socket >= MAX_DESCRIPTORS)
857 kill_link(_new,"Server is full");
860 char* e = matches_exception(ipaddr);
863 char* r = matches_zline(ipaddr);
867 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
868 kill_link(_new,reason);
875 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
878 WriteServ(_new->fd,"NOTICE Auth :*** Looking up your hostname...");
881 long FindMatchingGlobal(userrec* user)
884 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
887 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp
888 * Let me know if you think of one.
890 if (!memcmp(a->second->ip4.s6_addr, user->ip4.s6_addr, sizeof(in6_addr)))
893 if (a->second->ip4.s_addr == user->ip4.s_addr)
900 long FindMatchingLocal(userrec* user)
903 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
907 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
908 if (!memcmp(comp->ip4.s6_addr, user->ip4.s6_addr, sizeof(in6_addr)))
911 if (comp->ip4.s_addr == user->ip4.s_addr)
918 void FullConnectUser(userrec* user, CullList* Goners)
920 ServerInstance->stats->statsConnects++;
921 user->idle_lastmsg = TIME;
922 log(DEBUG,"ConnectUser: %s",user->nick);
924 ConnectClass a = GetClass(user);
926 if (a.type == CC_DENY)
928 Goners->AddItem(user,"Unauthorised connection");
932 if ((*(a.pass.c_str())) && (!user->haspassed))
934 Goners->AddItem(user,"Invalid password");
938 if (FindMatchingLocal(user) > a.maxlocal)
940 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
941 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,insp_ntoa(user->ip4));
944 else if (FindMatchingGlobal(user) > a.maxglobal)
946 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
947 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,insp_ntoa(user->ip4));
951 char match_against[MAXBUF];
952 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
953 char* e = matches_exception(match_against);
957 char* r = matches_gline(match_against);
962 snprintf(reason,MAXBUF,"G-Lined: %s",r);
963 Goners->AddItem(user,reason);
967 r = matches_kline(match_against);
972 snprintf(reason,MAXBUF,"K-Lined: %s",r);
973 Goners->AddItem(user,reason);
979 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
980 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
981 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
982 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
983 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
985 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
986 // so i'd better split it :)
987 std::stringstream out(Config->data005);
988 std::string token = "";
989 std::string line5 = "";
990 int token_counter = 0;
995 line5 = line5 + token + " ";
998 if ((token_counter >= 13) || (out.eof() == true))
1000 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1009 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1010 * changes dont go out onto the network and produce 'fake direction'.
1012 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
1013 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
1014 user->registered = REG_ALL;
1015 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,insp_ntoa(user->ip4));
1019 * re-allocates a nick in the user_hash after they change nicknames,
1020 * returns a pointer to the new user as it may have moved
1022 userrec* ReHashNick(const char* Old, const char* New)
1024 //user_hash::iterator newnick;
1025 user_hash::iterator oldnick = clientlist.find(Old);
1027 log(DEBUG,"ReHashNick: %s %s",Old,New);
1029 if (!strcasecmp(Old,New))
1031 log(DEBUG,"old nick is new nick, skipping");
1032 return oldnick->second;
1035 if (oldnick == clientlist.end())
1036 return NULL; /* doesnt exist */
1038 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1040 userrec* olduser = oldnick->second;
1041 clientlist[New] = olduser;
1042 clientlist.erase(oldnick);
1044 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1046 return clientlist[New];
1049 void force_nickchange(userrec* user,const char* newnick)
1056 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
1060 ServerInstance->stats->statsCollisions++;
1061 kill_link(user,"Nickname collision");
1065 if (matches_qline(newnick))
1067 ServerInstance->stats->statsCollisions++;
1068 kill_link(user,"Nickname collision");
1076 strlcpy(nick,newnick,MAXBUF-1);
1079 if (user->registered == REG_ALL)
1081 const char* pars[1];
1083 std::string cmd = "NICK";
1085 ServerInstance->Parser->CallHandler(cmd,pars,1,user);