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 *nick = *ident = *host = *dhost = *fullname = *modes = *awaymsg = *oper = *ip = 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 int userrec::ReadData(void* buffer, size_t size)
121 return read(this->fd, buffer, size);
127 char* userrec::GetFullRealHost()
129 static char fresult[MAXBUF];
131 for(char* n = nick; *n; n++)
134 for(char* n = ident; *n; n++)
137 for(char* n = host; *n; n++)
143 bool userrec::IsInvited(irc::string &channel)
145 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
147 irc::string compare = i->channel;
148 if (compare == channel)
156 InvitedList* userrec::GetInviteList()
161 void userrec::InviteTo(irc::string &channel)
165 invites.push_back(i);
168 void userrec::RemoveInvite(irc::string &channel)
170 log(DEBUG,"Removing invites");
173 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
175 irc::string compare = i->channel;
176 if (compare == channel)
185 bool userrec::HasPermission(std::string &command)
187 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
192 // users on u-lined servers can completely bypass
193 // all permissions based checks.
195 // of course, if this is sent to a remote server and this
196 // server is not ulined there, then that other server
197 // silently drops the command.
198 if (is_uline(this->server))
201 // are they even an oper at all?
202 if (strchr(this->modes,'o'))
204 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
206 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
207 if (!strcmp(TypeName,this->oper))
209 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
210 char* myclass = strtok_r(Classes," ",&savept);
213 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
215 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
216 if (!strcmp(ClassName,myclass))
218 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
219 mycmd = strtok_r(CommandList," ",&savept2);
222 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
226 mycmd = strtok_r(NULL," ",&savept2);
230 myclass = strtok_r(NULL," ",&savept);
239 bool userrec::AddBuffer(std::string a)
242 for (unsigned int i = 0; i < a.length(); i++)
243 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
245 std::stringstream stream(recvq);
247 recvq = stream.str();
249 // count the size of the first line in the buffer.
250 while (i < recvq.length())
252 if (recvq[i++] == '\n')
255 if (recvq.length() > (unsigned)this->recvqmax)
257 this->SetWriteError("RecvQ exceeded");
258 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
260 // return false if we've had more than 600 characters WITHOUT
261 // a carriage return (this is BAD, drop the socket)
265 bool userrec::BufferIsReady()
267 for (unsigned int i = 0; i < recvq.length(); i++)
268 if (recvq[i] == '\n')
273 void userrec::ClearBuffer()
278 std::string userrec::GetBuffer()
282 char* line = (char*)recvq.c_str();
283 std::string ret = "";
284 while ((*line != '\n') && (strlen(line)))
289 if ((*line == '\n') || (*line == '\r'))
295 void userrec::AddWriteBuf(std::string data)
297 if (this->GetWriteError() != "")
299 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
301 /* Fix by brain - Set the error text BEFORE calling writeopers, because
302 * if we dont it'll recursively call here over and over again trying
303 * to repeatedly add the text to the sendq!
305 this->SetWriteError("SendQ exceeded");
306 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
309 std::stringstream stream;
310 stream << sendq << data;
311 sendq = stream.str();
314 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
315 void userrec::FlushWriteBuf()
317 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
319 char* tb = (char*)this->sendq.c_str();
320 int n_sent = write(this->fd,tb,this->sendq.length());
323 this->SetWriteError(strerror(errno));
330 // update the user's stats counters
331 this->bytes_out += n_sent;
337 void userrec::SetWriteError(std::string error)
339 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
340 // don't try to set the error twice, its already set take the first string.
341 if (this->WriteError == "")
342 this->WriteError = error;
345 std::string userrec::GetWriteError()
347 return this->WriteError;
350 void AddOper(userrec* user)
352 log(DEBUG,"Oper added to optimization list");
353 all_opers.push_back(user);
356 void DeleteOper(userrec* user)
358 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
362 log(DEBUG,"Oper removed from optimization list");
369 void kill_link(userrec *user,const char* r)
371 user_hash::iterator iter = clientlist.find(user->nick);
375 strncpy(reason,r,MAXBUF);
377 if (strlen(reason)>MAXQUIT)
379 reason[MAXQUIT-1] = '\0';
382 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
383 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
384 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
386 if (user->registered == 7) {
387 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
388 WriteCommonExcept(user,"QUIT :%s",reason);
391 user->FlushWriteBuf();
393 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
397 if (Config->GetIOHook(user->port))
399 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
401 ServerInstance->SE->DelFd(user->fd);
405 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
406 // if they were an oper with +s.
407 if (user->registered == 7) {
408 purge_empty_chans(user);
409 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
411 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
415 if (iter != clientlist.end())
417 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
420 fd_ref_table[user->fd] = NULL;
421 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
423 local_users.erase(find(local_users.begin(),local_users.end(),user));
424 log(DEBUG,"Delete local user");
427 clientlist.erase(iter);
432 void kill_link_silent(userrec *user,const char* r)
434 user_hash::iterator iter = clientlist.find(user->nick);
438 strncpy(reason,r,MAXBUF);
440 if (strlen(reason)>MAXQUIT)
442 reason[MAXQUIT-1] = '\0';
445 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
446 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
447 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
449 user->FlushWriteBuf();
451 if (user->registered == 7) {
452 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
453 WriteCommonExcept(user,"QUIT :%s",reason);
456 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
460 if (Config->GetIOHook(user->port))
462 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
464 ServerInstance->SE->DelFd(user->fd);
468 if (user->registered == 7) {
469 purge_empty_chans(user);
472 if (iter != clientlist.end())
474 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
477 fd_ref_table[user->fd] = NULL;
478 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
480 log(DEBUG,"Delete local user");
481 local_users.erase(find(local_users.begin(),local_users.end(),user));
484 clientlist.erase(iter);
490 /* adds or updates an entry in the whowas list */
491 void AddWhoWas(userrec* u)
493 whowas_hash::iterator iter = whowas.find(u->nick);
494 WhoWasUser *a = new WhoWasUser();
495 strlcpy(a->nick,u->nick,NICKMAX);
496 strlcpy(a->ident,u->ident,IDENTMAX);
497 strlcpy(a->dhost,u->dhost,160);
498 strlcpy(a->host,u->host,160);
499 strlcpy(a->fullname,u->fullname,MAXGECOS);
501 strlcpy(a->server,u->server,256);
502 a->signon = u->signon;
504 /* MAX_WHOWAS: max number of /WHOWAS items
505 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
506 * can be replaced by a newer one
509 if (iter == whowas.end())
511 if (whowas.size() >= (unsigned)WHOWAS_MAX)
513 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
515 // 3600 seconds in an hour ;)
516 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
518 // delete the old one
519 if (i->second) delete i->second;
520 // replace with new one
522 log(DEBUG,"added WHOWAS entry, purged an old record");
526 // no space left and user doesnt exist. Don't leave ram in use!
527 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
532 log(DEBUG,"added fresh WHOWAS entry");
538 log(DEBUG,"updated WHOWAS entry");
539 if (iter->second) delete iter->second;
544 /* add a client connection to the sockets list */
545 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
549 user_hash::iterator iter;
551 tempnick = ConvToStr(socket) + "-unknown";
552 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
554 iter = clientlist.find(tempnick);
557 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
558 // using one as a registered connection. As theyre per fd, we can also safely assume
559 // that we wont have collisions. Therefore, if the nick exists in the list, its only
560 // used by a dead socket, erase the iterator so that the new client may reclaim it.
561 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
562 // issue in earlier alphas/betas
563 if (iter != clientlist.end())
565 userrec* goner = iter->second;
567 clientlist.erase(iter);
571 * It is OK to access the value here this way since we know
572 * it exists, we just created it above.
574 * At NO other time should you access a value in a map or a
577 clientlist[tempnick] = new userrec();
579 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
581 clientlist[tempnick]->fd = socket;
582 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
583 strlcpy(clientlist[tempnick]->host, host,160);
584 strlcpy(clientlist[tempnick]->dhost, host,160);
585 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
586 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
587 clientlist[tempnick]->registered = 0;
588 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
589 clientlist[tempnick]->lastping = 1;
590 clientlist[tempnick]->port = port;
591 strlcpy(clientlist[tempnick]->ip,ip,16);
593 // set the registration timeout for this user
594 unsigned long class_regtimeout = 90;
596 long class_threshold = 5;
597 long class_sqmax = 262144; // 256kb
598 long class_rqmax = 4096; // 4k
600 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
602 if (match(clientlist[tempnick]->host,i->host.c_str()) && (i->type == CC_ALLOW))
604 class_regtimeout = (unsigned long)i->registration_timeout;
605 class_flood = i->flood;
606 clientlist[tempnick]->pingmax = i->pingtime;
607 class_threshold = i->threshold;
608 class_sqmax = i->sendqmax;
609 class_rqmax = i->recvqmax;
614 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
615 clientlist[tempnick]->timeout = TIME+class_regtimeout;
616 clientlist[tempnick]->flood = class_flood;
617 clientlist[tempnick]->threshold = class_threshold;
618 clientlist[tempnick]->sendqmax = class_sqmax;
619 clientlist[tempnick]->recvqmax = class_rqmax;
624 for (int i = 0; i < MAXCHANS; i++)
625 clientlist[tempnick]->chans.push_back(a);
627 if (local_users.size() > Config->SoftLimit)
629 kill_link(clientlist[tempnick],"No more connections allowed");
633 if (local_users.size() >= MAXCLIENTS)
635 kill_link(clientlist[tempnick],"No more connections allowed");
639 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
640 // its a pretty big but for the moment valid assumption:
641 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
642 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
643 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
644 // which for the time being is a physical impossibility (even the largest networks dont have more
645 // than about 10,000 users on ONE server!)
646 if ((unsigned)socket > MAX_DESCRIPTORS)
648 kill_link(clientlist[tempnick],"Server is full");
651 char* e = matches_exception(ip);
654 char* r = matches_zline(ip);
658 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
659 kill_link(clientlist[tempnick],reason);
663 fd_ref_table[socket] = clientlist[tempnick];
664 local_users.push_back(clientlist[tempnick]);
665 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
667 WriteServ(clientlist[tempnick]->fd,"NOTICE Auth :*** Looking up your hostname...");
670 void FullConnectUser(userrec* user, CullList* Goners)
672 ServerInstance->stats->statsConnects++;
673 user->idle_lastmsg = TIME;
674 log(DEBUG,"ConnectUser: %s",user->nick);
676 ConnectClass a = GetClass(user);
678 if (a.type == CC_DENY)
680 Goners->AddItem(user,"Unauthorised connection");
683 if ((*(a.pass.c_str())) && (!user->haspassed))
685 Goners->AddItem(user,"Invalid password");
689 char match_against[MAXBUF];
690 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
691 char* e = matches_exception(match_against);
694 char* r = matches_gline(match_against);
698 snprintf(reason,MAXBUF,"G-Lined: %s",r);
699 Goners->AddItem(user,reason);
702 r = matches_kline(user->host);
706 snprintf(reason,MAXBUF,"K-Lined: %s",r);
707 Goners->AddItem(user,reason);
713 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
714 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
715 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
716 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
717 WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
718 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
719 // so i'd better split it :)
720 std::stringstream out(Config->data005);
721 std::string token = "";
722 std::string line5 = "";
723 int token_counter = 0;
727 line5 = line5 + token + " ";
729 if ((token_counter >= 13) || (out.eof() == true))
731 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
738 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
739 // onto the network and produce 'fake direction'
740 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
741 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
742 user->registered = 7;
743 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
746 /* re-allocates a nick in the user_hash after they change nicknames,
747 * returns a pointer to the new user as it may have moved */
749 userrec* ReHashNick(char* Old, char* New)
751 //user_hash::iterator newnick;
752 user_hash::iterator oldnick = clientlist.find(Old);
754 log(DEBUG,"ReHashNick: %s %s",Old,New);
756 if (!strcasecmp(Old,New))
758 log(DEBUG,"old nick is new nick, skipping");
759 return oldnick->second;
762 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
764 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
766 userrec* olduser = oldnick->second;
767 clientlist[New] = olduser;
768 clientlist.erase(oldnick);
770 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
772 return clientlist[New];
775 void force_nickchange(userrec* user,const char* newnick)
782 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
784 ServerInstance->stats->statsCollisions++;
785 kill_link(user,"Nickname collision");
788 if (matches_qline(newnick))
790 ServerInstance->stats->statsCollisions++;
791 kill_link(user,"Nickname collision");
799 strncpy(nick,newnick,MAXBUF);
801 if (user->registered == 7)
805 std::string cmd = "NICK";
806 ServerInstance->Parser->CallHandler(cmd,pars,1,user);