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 template<typename T> inline string ConvToStr(const T &in)
60 if (!(tmp << in)) return string();
66 // the PROPER way to do it, AVOID bzero at *ALL* costs
67 *password = *nick = *ident = *host = *dhost = *fullname = *modes = *awaymsg = *oper = 0;
68 server = (char*)FindServerNamePtr(Config->ServerName);
70 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
71 timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
72 haspassed = dns_done = false;
83 void userrec::MakeHost(char* nhost)
85 /* This is much faster than snprintf */
87 for(char* n = ident; *n; n++)
90 for(char* n = host; *n; n++)
95 void userrec::CloseSocket()
101 char* userrec::GetFullHost()
103 static char result[MAXBUF];
105 for(char* n = nick; *n; n++)
108 for(char* n = ident; *n; n++)
111 for(char* n = dhost; *n; n++)
117 char* userrec::MakeWildHost()
119 static char nresult[MAXBUF];
121 *t++ = '*'; *t++ = '!';
122 *t++ = '*'; *t++ = '@';
123 for(char* n = dhost; *n; n++)
129 int userrec::ReadData(void* buffer, size_t size)
133 return read(this->fd, buffer, size);
139 char* userrec::GetFullRealHost()
141 static char fresult[MAXBUF];
143 for(char* n = nick; *n; n++)
146 for(char* n = ident; *n; n++)
149 for(char* n = host; *n; n++)
155 bool userrec::IsInvited(irc::string &channel)
157 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
159 irc::string compare = i->channel;
160 if (compare == channel)
168 InvitedList* userrec::GetInviteList()
173 void userrec::InviteTo(irc::string &channel)
177 invites.push_back(i);
180 void userrec::RemoveInvite(irc::string &channel)
182 log(DEBUG,"Removing invites");
185 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
187 irc::string compare = i->channel;
188 if (compare == channel)
197 bool userrec::HasPermission(std::string &command)
199 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
204 // users on u-lined servers can completely bypass
205 // all permissions based checks.
207 // of course, if this is sent to a remote server and this
208 // server is not ulined there, then that other server
209 // silently drops the command.
210 if (is_uline(this->server))
213 // are they even an oper at all?
214 if (strchr(this->modes,'o'))
216 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
218 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
219 if (!strcmp(TypeName,this->oper))
221 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
222 char* myclass = strtok_r(Classes," ",&savept);
225 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
227 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
228 if (!strcmp(ClassName,myclass))
230 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
231 mycmd = strtok_r(CommandList," ",&savept2);
234 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
238 mycmd = strtok_r(NULL," ",&savept2);
242 myclass = strtok_r(NULL," ",&savept);
251 bool userrec::AddBuffer(std::string a)
254 for (unsigned int i = 0; i < a.length(); i++)
255 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
257 std::stringstream stream(recvq);
259 recvq = stream.str();
261 // count the size of the first line in the buffer.
262 while (i < recvq.length())
264 if (recvq[i++] == '\n')
267 if (recvq.length() > (unsigned)this->recvqmax)
269 this->SetWriteError("RecvQ exceeded");
270 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
272 // return false if we've had more than 600 characters WITHOUT
273 // a carriage return (this is BAD, drop the socket)
277 bool userrec::BufferIsReady()
279 unsigned int t = recvq.length();
280 for (unsigned int i = 0; i < t; i++)
281 if (recvq[i] == '\n')
286 void userrec::ClearBuffer()
291 std::string userrec::GetBuffer()
295 char* line = (char*)recvq.c_str();
296 std::string ret = "";
297 while ((*line != '\n') && (*line))
302 if ((*line == '\n') || (*line == '\r'))
308 void userrec::AddWriteBuf(std::string data)
310 if (this->GetWriteError() != "")
312 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
314 /* Fix by brain - Set the error text BEFORE calling writeopers, because
315 * if we dont it'll recursively call here over and over again trying
316 * to repeatedly add the text to the sendq!
318 this->SetWriteError("SendQ exceeded");
319 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
322 std::stringstream stream;
323 stream << sendq << data;
324 sendq = stream.str();
327 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
328 void userrec::FlushWriteBuf()
330 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
332 char* tb = (char*)this->sendq.c_str();
333 int n_sent = write(this->fd,tb,this->sendq.length());
336 this->SetWriteError(strerror(errno));
343 // update the user's stats counters
344 this->bytes_out += n_sent;
350 void userrec::SetWriteError(std::string error)
352 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
353 // don't try to set the error twice, its already set take the first string.
354 if (this->WriteError == "")
355 this->WriteError = error;
358 std::string userrec::GetWriteError()
360 return this->WriteError;
363 void AddOper(userrec* user)
365 log(DEBUG,"Oper added to optimization list");
366 all_opers.push_back(user);
369 void DeleteOper(userrec* user)
371 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
375 log(DEBUG,"Oper removed from optimization list");
382 void kill_link(userrec *user,const char* r)
384 user_hash::iterator iter = clientlist.find(user->nick);
388 strlcpy(reason,r,MAXBUF);
390 if (strlen(reason)>MAXQUIT)
392 reason[MAXQUIT-1] = '\0';
395 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
396 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
397 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
399 if (user->registered == 7) {
400 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
401 WriteCommonExcept(user,"QUIT :%s",reason);
404 user->FlushWriteBuf();
406 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
410 if (Config->GetIOHook(user->port))
412 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
414 ServerInstance->SE->DelFd(user->fd);
418 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
419 // if they were an oper with +s.
420 if (user->registered == 7) {
421 purge_empty_chans(user);
422 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
424 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
428 if (iter != clientlist.end())
430 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
433 fd_ref_table[user->fd] = NULL;
434 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
436 local_users.erase(find(local_users.begin(),local_users.end(),user));
437 log(DEBUG,"Delete local user");
440 clientlist.erase(iter);
445 void kill_link_silent(userrec *user,const char* r)
447 user_hash::iterator iter = clientlist.find(user->nick);
451 strlcpy(reason,r,MAXBUF);
453 if (strlen(reason)>MAXQUIT)
455 reason[MAXQUIT-1] = '\0';
458 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
459 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
460 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
462 user->FlushWriteBuf();
464 if (user->registered == 7) {
465 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
466 WriteCommonExcept(user,"QUIT :%s",reason);
469 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
473 if (Config->GetIOHook(user->port))
475 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
477 ServerInstance->SE->DelFd(user->fd);
481 if (user->registered == 7) {
482 purge_empty_chans(user);
485 if (iter != clientlist.end())
487 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
490 fd_ref_table[user->fd] = NULL;
491 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
493 log(DEBUG,"Delete local user");
494 local_users.erase(find(local_users.begin(),local_users.end(),user));
497 clientlist.erase(iter);
503 /* adds or updates an entry in the whowas list */
504 void AddWhoWas(userrec* u)
506 whowas_hash::iterator iter = whowas.find(u->nick);
507 WhoWasUser *a = new WhoWasUser();
508 strlcpy(a->nick,u->nick,NICKMAX);
509 strlcpy(a->ident,u->ident,IDENTMAX);
510 strlcpy(a->dhost,u->dhost,160);
511 strlcpy(a->host,u->host,160);
512 strlcpy(a->fullname,u->fullname,MAXGECOS);
514 strlcpy(a->server,u->server,256);
515 a->signon = u->signon;
517 /* MAX_WHOWAS: max number of /WHOWAS items
518 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
519 * can be replaced by a newer one
522 if (iter == whowas.end())
524 if (whowas.size() >= (unsigned)WHOWAS_MAX)
526 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
528 // 3600 seconds in an hour ;)
529 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
531 // delete the old one
532 if (i->second) delete i->second;
533 // replace with new one
535 log(DEBUG,"added WHOWAS entry, purged an old record");
539 // no space left and user doesnt exist. Don't leave ram in use!
540 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
545 log(DEBUG,"added fresh WHOWAS entry");
551 log(DEBUG,"updated WHOWAS entry");
552 if (iter->second) delete iter->second;
557 /* add a client connection to the sockets list */
558 void AddClient(int socket, int port, bool iscached, in_addr ip4)
562 user_hash::iterator iter;
564 tempnick = ConvToStr(socket) + "-unknown";
565 sprintf(tn2,"%d-unknown",socket);
567 iter = clientlist.find(tempnick);
570 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
571 // using one as a registered connection. As theyre per fd, we can also safely assume
572 // that we wont have collisions. Therefore, if the nick exists in the list, its only
573 // used by a dead socket, erase the iterator so that the new client may reclaim it.
574 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
575 // issue in earlier alphas/betas
576 if (iter != clientlist.end())
578 userrec* goner = iter->second;
580 clientlist.erase(iter);
584 * It is OK to access the value here this way since we know
585 * it exists, we just created it above.
587 * At NO other time should you access a value in a map or a
590 clientlist[tempnick] = new userrec();
592 char *ipaddr = (char*)inet_ntoa(ip4);
594 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
596 clientlist[tempnick]->fd = socket;
597 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
598 /* We don't know the host yet, dns lookup could still be going on,
599 * so instead we just put the ip address here, for now.
601 strlcpy(clientlist[tempnick]->host, ipaddr, 160);
602 strlcpy(clientlist[tempnick]->dhost, ipaddr, 160);
603 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
604 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
605 clientlist[tempnick]->registered = 0;
606 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
607 clientlist[tempnick]->lastping = 1;
608 clientlist[tempnick]->ip4 = ip4;
609 clientlist[tempnick]->port = port;
611 // set the registration timeout for this user
612 unsigned long class_regtimeout = 90;
614 long class_threshold = 5;
615 long class_sqmax = 262144; // 256kb
616 long class_rqmax = 4096; // 4k
618 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
620 if (match(ipaddr,i->host.c_str()) && (i->type == CC_ALLOW))
622 class_regtimeout = (unsigned long)i->registration_timeout;
623 class_flood = i->flood;
624 clientlist[tempnick]->pingmax = i->pingtime;
625 class_threshold = i->threshold;
626 class_sqmax = i->sendqmax;
627 class_rqmax = i->recvqmax;
632 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
633 clientlist[tempnick]->timeout = TIME+class_regtimeout;
634 clientlist[tempnick]->flood = class_flood;
635 clientlist[tempnick]->threshold = class_threshold;
636 clientlist[tempnick]->sendqmax = class_sqmax;
637 clientlist[tempnick]->recvqmax = class_rqmax;
642 for (int i = 0; i < MAXCHANS; i++)
643 clientlist[tempnick]->chans.push_back(a);
645 if (local_users.size() > Config->SoftLimit)
647 kill_link(clientlist[tempnick],"No more connections allowed");
651 if (local_users.size() >= MAXCLIENTS)
653 kill_link(clientlist[tempnick],"No more connections allowed");
657 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
658 // its a pretty big but for the moment valid assumption:
659 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
660 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
661 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
662 // which for the time being is a physical impossibility (even the largest networks dont have more
663 // than about 10,000 users on ONE server!)
664 if ((unsigned)socket > MAX_DESCRIPTORS)
666 kill_link(clientlist[tempnick],"Server is full");
669 char* e = matches_exception(ipaddr);
672 char* r = matches_zline(ipaddr);
676 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
677 kill_link(clientlist[tempnick],reason);
681 fd_ref_table[socket] = clientlist[tempnick];
682 local_users.push_back(clientlist[tempnick]);
683 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
685 WriteServ(clientlist[tempnick]->fd,"NOTICE Auth :*** Looking up your hostname...");
688 long FindMatchingGlobal(userrec* user)
691 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
693 if (a->second->ip4.s_addr == user->ip4.s_addr)
699 long FindMatchingLocal(userrec* user)
702 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
704 userrec* comp = (userrec*)(*a);
705 if (comp->ip4.s_addr == user->ip4.s_addr)
711 void FullConnectUser(userrec* user, CullList* Goners)
713 ServerInstance->stats->statsConnects++;
714 user->idle_lastmsg = TIME;
715 log(DEBUG,"ConnectUser: %s",user->nick);
717 ConnectClass a = GetClass(user);
719 if (a.type == CC_DENY)
721 Goners->AddItem(user,"Unauthorised connection");
724 if ((*(a.pass.c_str())) && (!user->haspassed))
726 Goners->AddItem(user,"Invalid password");
729 if (FindMatchingLocal(user) > a.maxlocal)
731 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
732 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,(char*)inet_ntoa(user->ip4));
735 else if (FindMatchingGlobal(user) > a.maxglobal)
737 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
738 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,(char*)inet_ntoa(user->ip4));
742 char match_against[MAXBUF];
743 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
744 char* e = matches_exception(match_against);
747 char* r = matches_gline(match_against);
751 snprintf(reason,MAXBUF,"G-Lined: %s",r);
752 Goners->AddItem(user,reason);
755 r = matches_kline(user->host);
759 snprintf(reason,MAXBUF,"K-Lined: %s",r);
760 Goners->AddItem(user,reason);
766 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
767 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
768 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
769 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
770 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
771 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
772 // so i'd better split it :)
773 std::stringstream out(Config->data005);
774 std::string token = "";
775 std::string line5 = "";
776 int token_counter = 0;
780 line5 = line5 + token + " ";
782 if ((token_counter >= 13) || (out.eof() == true))
784 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
791 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
792 // onto the network and produce 'fake direction'
793 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
794 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
795 user->registered = 7;
796 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));
799 /* re-allocates a nick in the user_hash after they change nicknames,
800 * returns a pointer to the new user as it may have moved */
802 userrec* ReHashNick(char* Old, char* New)
804 //user_hash::iterator newnick;
805 user_hash::iterator oldnick = clientlist.find(Old);
807 log(DEBUG,"ReHashNick: %s %s",Old,New);
809 if (!strcasecmp(Old,New))
811 log(DEBUG,"old nick is new nick, skipping");
812 return oldnick->second;
815 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
817 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
819 userrec* olduser = oldnick->second;
820 clientlist[New] = olduser;
821 clientlist.erase(oldnick);
823 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
825 return clientlist[New];
828 void force_nickchange(userrec* user,const char* newnick)
835 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
837 ServerInstance->stats->statsCollisions++;
838 kill_link(user,"Nickname collision");
841 if (matches_qline(newnick))
843 ServerInstance->stats->statsCollisions++;
844 kill_link(user,"Nickname collision");
852 strlcpy(nick,newnick,MAXBUF);
854 if (user->registered == 7)
858 std::string cmd = "NICK";
859 ServerInstance->Parser->CallHandler(cmd,pars,1,user);