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;
52 extern whowas_hash whowas;
53 extern std::vector<userrec*> local_users;
55 std::vector<userrec*> all_opers;
57 typedef std::map<irc::string,char*> opertype_t;
58 typedef opertype_t operclass_t;
61 operclass_t operclass;
63 void ReadClassesAndTypes()
65 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
66 for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
71 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
78 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
80 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
81 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
82 opertypes[TypeName] = strdup(Classes);
83 log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
85 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
87 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
88 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
89 operclass[ClassName] = strdup(CommandList);
90 log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
94 template<typename T> inline string ConvToStr(const T &in)
97 if (!(tmp << in)) return string();
103 // the PROPER way to do it, AVOID bzero at *ALL* costs
104 *password = *nick = *ident = *host = *dhost = *fullname = *modes = *awaymsg = *oper = 0;
105 server = (char*)FindServerNamePtr(Config->ServerName);
107 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
108 timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
109 haspassed = dns_done = false;
120 void userrec::MakeHost(char* nhost)
122 /* This is much faster than snprintf */
124 for(char* n = ident; *n; n++)
127 for(char* n = host; *n; n++)
132 void userrec::CloseSocket()
134 shutdown(this->fd,2);
138 char* userrec::GetFullHost()
140 static char result[MAXBUF];
142 for(char* n = nick; *n; n++)
145 for(char* n = ident; *n; n++)
148 for(char* n = dhost; *n; n++)
154 char* userrec::MakeWildHost()
156 static char nresult[MAXBUF];
158 *t++ = '*'; *t++ = '!';
159 *t++ = '*'; *t++ = '@';
160 for(char* n = dhost; *n; n++)
166 int userrec::ReadData(void* buffer, size_t size)
170 return read(this->fd, buffer, size);
176 char* userrec::GetFullRealHost()
178 static char fresult[MAXBUF];
180 for(char* n = nick; *n; n++)
183 for(char* n = ident; *n; n++)
186 for(char* n = host; *n; n++)
192 bool userrec::IsInvited(irc::string &channel)
194 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
196 irc::string compare = i->channel;
197 if (compare == channel)
205 InvitedList* userrec::GetInviteList()
210 void userrec::InviteTo(irc::string &channel)
214 invites.push_back(i);
217 void userrec::RemoveInvite(irc::string &channel)
219 log(DEBUG,"Removing invites");
222 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
224 irc::string compare = i->channel;
225 if (compare == channel)
234 bool userrec::HasPermission(std::string &command)
240 // users on remote servers can completely bypass
241 // all permissions based checks.
242 // This prevents desyncs when one server has different
243 // type/class tags to another.
247 // are they even an oper at all?
250 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
251 if (iter_opertype != opertypes.end())
253 char* Classes = strdup(iter_opertype->second);
254 char* myclass = strtok_r(Classes," ",&savept);
257 operclass_t::iterator iter_operclass = operclass.find(myclass);
258 if (iter_operclass != operclass.end())
260 char* CommandList = strdup(iter_operclass->second);
261 mycmd = strtok_r(CommandList," ",&savept2);
264 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
270 mycmd = strtok_r(NULL," ",&savept2);
274 myclass = strtok_r(NULL," ",&savept);
283 bool userrec::AddBuffer(std::string a)
286 char* n = (char*)a.c_str();
287 for (char* i = n; *i; i++)
289 if ((*i != '\r') && (*i != '\0') && (*i != 7))
292 std::stringstream stream(recvq);
294 recvq = stream.str();
296 // count the size of the first line in the buffer.
297 while (i < recvq.length())
299 if (recvq[i++] == '\n')
302 if (recvq.length() > (unsigned)this->recvqmax)
304 this->SetWriteError("RecvQ exceeded");
305 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
307 // return false if we've had more than 600 characters WITHOUT
308 // a carriage return (this is BAD, drop the socket)
312 bool userrec::BufferIsReady()
314 unsigned int t = recvq.length();
315 for (unsigned int i = 0; i < t; i++)
316 if (recvq[i] == '\n')
321 void userrec::ClearBuffer()
326 std::string userrec::GetBuffer()
330 char* line = (char*)recvq.c_str();
331 std::string ret = "";
332 while ((*line != '\n') && (*line))
337 if ((*line == '\n') || (*line == '\r'))
343 void userrec::AddWriteBuf(std::string data)
345 if (this->GetWriteError() != "")
347 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
349 /* Fix by brain - Set the error text BEFORE calling writeopers, because
350 * if we dont it'll recursively call here over and over again trying
351 * to repeatedly add the text to the sendq!
353 this->SetWriteError("SendQ exceeded");
354 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
357 std::stringstream stream;
358 stream << sendq << data;
359 sendq = stream.str();
362 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
363 void userrec::FlushWriteBuf()
365 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
367 char* tb = (char*)this->sendq.c_str();
368 int n_sent = write(this->fd,tb,this->sendq.length());
371 this->SetWriteError(strerror(errno));
378 // update the user's stats counters
379 this->bytes_out += n_sent;
385 void userrec::SetWriteError(std::string error)
387 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
388 // don't try to set the error twice, its already set take the first string.
389 if (this->WriteError == "")
390 this->WriteError = error;
393 std::string userrec::GetWriteError()
395 return this->WriteError;
398 void AddOper(userrec* user)
400 log(DEBUG,"Oper added to optimization list");
401 all_opers.push_back(user);
404 void DeleteOper(userrec* user)
406 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
410 log(DEBUG,"Oper removed from optimization list");
417 void kill_link(userrec *user,const char* r)
419 user_hash::iterator iter = clientlist.find(user->nick);
423 strlcpy(reason,r,MAXBUF-1);
425 if (strlen(reason)>MAXQUIT)
427 reason[MAXQUIT-1] = '\0';
430 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
431 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
432 log(DEBUG,"closing fd %d",user->fd);
434 if (user->registered == 7) {
435 purge_empty_chans(user);
436 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
437 WriteCommonExcept(user,"QUIT :%s",reason);
440 user->FlushWriteBuf();
442 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
446 if (Config->GetIOHook(user->port))
450 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
452 catch (ModuleException& modexcept)
454 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
457 ServerInstance->SE->DelFd(user->fd);
461 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
462 // if they were an oper with +s.
463 if (user->registered == 7) {
464 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
466 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
470 if (iter != clientlist.end())
472 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
475 fd_ref_table[user->fd] = NULL;
476 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
478 local_users.erase(find(local_users.begin(),local_users.end(),user));
479 log(DEBUG,"Delete local user");
482 clientlist.erase(iter);
487 /* adds or updates an entry in the whowas list */
488 void AddWhoWas(userrec* u)
490 whowas_hash::iterator iter = whowas.find(u->nick);
491 WhoWasUser *a = new WhoWasUser();
492 strlcpy(a->nick,u->nick,NICKMAX-1);
493 strlcpy(a->ident,u->ident,IDENTMAX);
494 strlcpy(a->dhost,u->dhost,63);
495 strlcpy(a->host,u->host,63);
496 strlcpy(a->fullname,u->fullname,MAXGECOS);
498 strlcpy(a->server,u->server,256);
499 a->signon = u->signon;
501 /* MAX_WHOWAS: max number of /WHOWAS items
502 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
503 * can be replaced by a newer one
506 if (iter == whowas.end())
508 if (whowas.size() >= (unsigned)WHOWAS_MAX)
510 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
512 // 3600 seconds in an hour ;)
513 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
516 if (i->second) delete i->second;
518 // replace with new one
520 log(DEBUG,"added WHOWAS entry, purged an old record");
524 // no space left and user doesnt exist. Don't leave ram in use!
529 log(DEBUG,"added fresh WHOWAS entry");
535 log(DEBUG,"updated WHOWAS entry");
536 if (iter->second) delete iter->second;
541 /* add a client connection to the sockets list */
542 void AddClient(int socket, int port, bool iscached, in_addr ip4)
544 std::string tempnick = ConvToStr(socket) + "-unknown";
545 user_hash::iterator iter = clientlist.find(tempnick);
546 const char *ipaddr = inet_ntoa(ip4);
550 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
551 // using one as a registered connection. As theyre per fd, we can also safely assume
552 // that we wont have collisions. Therefore, if the nick exists in the list, its only
553 // used by a dead socket, erase the iterator so that the new client may reclaim it.
554 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
555 // issue in earlier alphas/betas
556 if (iter != clientlist.end())
558 userrec* goner = iter->second;
560 clientlist.erase(iter);
563 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
565 clientlist[tempnick] = new userrec();
566 clientlist[tempnick]->fd = socket;
567 strlcpy(clientlist[tempnick]->nick,tempnick.c_str(),NICKMAX-1);
569 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
570 for (char* temp = (char*)ipaddr; *temp && j < 64; temp++, j++)
571 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = *temp;
572 clientlist[tempnick]->dhost[j] = clientlist[tempnick]->host[j] = 0;
574 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
575 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
576 strcpy(clientlist[tempnick]->ident, "unknown");
578 clientlist[tempnick]->registered = 0;
579 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
580 clientlist[tempnick]->lastping = 1;
581 clientlist[tempnick]->ip4 = ip4;
582 clientlist[tempnick]->port = port;
584 // set the registration timeout for this user
585 unsigned long class_regtimeout = 90;
587 long class_threshold = 5;
588 long class_sqmax = 262144; // 256kb
589 long class_rqmax = 4096; // 4k
591 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
593 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
595 class_regtimeout = (unsigned long)i->registration_timeout;
596 class_flood = i->flood;
597 clientlist[tempnick]->pingmax = i->pingtime;
598 class_threshold = i->threshold;
599 class_sqmax = i->sendqmax;
600 class_rqmax = i->recvqmax;
605 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
606 clientlist[tempnick]->timeout = TIME+class_regtimeout;
607 clientlist[tempnick]->flood = class_flood;
608 clientlist[tempnick]->threshold = class_threshold;
609 clientlist[tempnick]->sendqmax = class_sqmax;
610 clientlist[tempnick]->recvqmax = class_rqmax;
615 for (int i = 0; i < MAXCHANS; i++)
616 clientlist[tempnick]->chans.push_back(a);
618 fd_ref_table[socket] = clientlist[tempnick];
619 local_users.push_back(clientlist[tempnick]);
621 if (local_users.size() > Config->SoftLimit)
623 kill_link(clientlist[tempnick],"No more connections allowed");
627 if (local_users.size() >= MAXCLIENTS)
629 kill_link(clientlist[tempnick],"No more connections allowed");
633 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
634 // its a pretty big but for the moment valid assumption:
635 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
636 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
637 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
638 // which for the time being is a physical impossibility (even the largest networks dont have more
639 // than about 10,000 users on ONE server!)
640 if ((unsigned)socket >= MAX_DESCRIPTORS)
642 kill_link(clientlist[tempnick],"Server is full");
645 char* e = matches_exception(ipaddr);
648 char* r = matches_zline(ipaddr);
652 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
653 kill_link(clientlist[tempnick],reason);
658 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
660 WriteServ(clientlist[tempnick]->fd,"NOTICE Auth :*** Looking up your hostname...");
663 long FindMatchingGlobal(userrec* user)
666 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
668 if (a->second->ip4.s_addr == user->ip4.s_addr)
674 long FindMatchingLocal(userrec* user)
677 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
679 userrec* comp = (userrec*)(*a);
680 if (comp->ip4.s_addr == user->ip4.s_addr)
686 void FullConnectUser(userrec* user, CullList* Goners)
688 ServerInstance->stats->statsConnects++;
689 user->idle_lastmsg = TIME;
690 log(DEBUG,"ConnectUser: %s",user->nick);
692 ConnectClass a = GetClass(user);
694 if (a.type == CC_DENY)
696 Goners->AddItem(user,"Unauthorised connection");
699 if ((*(a.pass.c_str())) && (!user->haspassed))
701 Goners->AddItem(user,"Invalid password");
704 if (FindMatchingLocal(user) > a.maxlocal)
706 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
707 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,(char*)inet_ntoa(user->ip4));
710 else if (FindMatchingGlobal(user) > a.maxglobal)
712 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
713 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,(char*)inet_ntoa(user->ip4));
717 char match_against[MAXBUF];
718 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
719 char* e = matches_exception(match_against);
722 char* r = matches_gline(match_against);
726 snprintf(reason,MAXBUF,"G-Lined: %s",r);
727 Goners->AddItem(user,reason);
730 r = matches_kline(user->host);
734 snprintf(reason,MAXBUF,"K-Lined: %s",r);
735 Goners->AddItem(user,reason);
741 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
742 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
743 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
744 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
745 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
746 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
747 // so i'd better split it :)
748 std::stringstream out(Config->data005);
749 std::string token = "";
750 std::string line5 = "";
751 int token_counter = 0;
755 line5 = line5 + token + " ";
757 if ((token_counter >= 13) || (out.eof() == true))
759 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
766 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
767 // onto the network and produce 'fake direction'
768 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
769 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
770 user->registered = 7;
771 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));
774 /* re-allocates a nick in the user_hash after they change nicknames,
775 * returns a pointer to the new user as it may have moved */
777 userrec* ReHashNick(char* Old, char* New)
779 //user_hash::iterator newnick;
780 user_hash::iterator oldnick = clientlist.find(Old);
782 log(DEBUG,"ReHashNick: %s %s",Old,New);
784 if (!strcasecmp(Old,New))
786 log(DEBUG,"old nick is new nick, skipping");
787 return oldnick->second;
790 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
792 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
794 userrec* olduser = oldnick->second;
795 clientlist[New] = olduser;
796 clientlist.erase(oldnick);
798 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
800 return clientlist[New];
803 void force_nickchange(userrec* user,const char* newnick)
810 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
812 ServerInstance->stats->statsCollisions++;
813 kill_link(user,"Nickname collision");
816 if (matches_qline(newnick))
818 ServerInstance->stats->statsCollisions++;
819 kill_link(user,"Nickname collision");
827 strlcpy(nick,newnick,MAXBUF-1);
829 if (user->registered == 7)
833 std::string cmd = "NICK";
834 ServerInstance->Parser->CallHandler(cmd,pars,1,user);