1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire 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::CloseSocket()
89 char* userrec::GetFullHost()
91 static char result[MAXBUF];
92 snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
96 int userrec::ReadData(void* buffer, size_t size)
100 return read(this->fd, buffer, size);
106 char* userrec::GetFullRealHost()
108 static char fresult[MAXBUF];
109 snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
113 bool userrec::IsInvited(irc::string &channel)
115 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
117 irc::string compare = i->channel;
118 if (compare == channel)
126 InvitedList* userrec::GetInviteList()
131 void userrec::InviteTo(irc::string &channel)
135 invites.push_back(i);
138 void userrec::RemoveInvite(irc::string &channel)
140 log(DEBUG,"Removing invites");
143 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
145 irc::string compare = i->channel;
146 if (compare == channel)
155 bool userrec::HasPermission(std::string &command)
157 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
162 // users on u-lined servers can completely bypass
163 // all permissions based checks.
165 // of course, if this is sent to a remote server and this
166 // server is not ulined there, then that other server
167 // silently drops the command.
168 if (is_uline(this->server))
171 // are they even an oper at all?
172 if (strchr(this->modes,'o'))
174 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
176 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
177 if (!strcmp(TypeName,this->oper))
179 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
180 char* myclass = strtok_r(Classes," ",&savept);
183 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
185 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
186 if (!strcmp(ClassName,myclass))
188 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
189 mycmd = strtok_r(CommandList," ",&savept2);
192 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
196 mycmd = strtok_r(NULL," ",&savept2);
200 myclass = strtok_r(NULL," ",&savept);
209 bool userrec::AddBuffer(std::string a)
212 for (unsigned int i = 0; i < a.length(); i++)
213 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
215 std::stringstream stream(recvq);
217 recvq = stream.str();
219 // count the size of the first line in the buffer.
220 while (i < recvq.length())
222 if (recvq[i++] == '\n')
225 if (recvq.length() > (unsigned)this->recvqmax)
227 this->SetWriteError("RecvQ exceeded");
228 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
230 // return false if we've had more than 600 characters WITHOUT
231 // a carriage return (this is BAD, drop the socket)
235 bool userrec::BufferIsReady()
237 for (unsigned int i = 0; i < recvq.length(); i++)
238 if (recvq[i] == '\n')
243 void userrec::ClearBuffer()
248 std::string userrec::GetBuffer()
252 char* line = (char*)recvq.c_str();
253 std::string ret = "";
254 while ((*line != '\n') && (strlen(line)))
259 if ((*line == '\n') || (*line == '\r'))
265 void userrec::AddWriteBuf(std::string data)
267 if (this->GetWriteError() != "")
269 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
271 /* Fix by brain - Set the error text BEFORE calling writeopers, because
272 * if we dont it'll recursively call here over and over again trying
273 * to repeatedly add the text to the sendq!
275 this->SetWriteError("SendQ exceeded");
276 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
279 std::stringstream stream;
280 stream << sendq << data;
281 sendq = stream.str();
284 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
285 void userrec::FlushWriteBuf()
287 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
289 char* tb = (char*)this->sendq.c_str();
290 int n_sent = write(this->fd,tb,this->sendq.length());
293 this->SetWriteError(strerror(errno));
300 // update the user's stats counters
301 this->bytes_out += n_sent;
307 void userrec::SetWriteError(std::string error)
309 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
310 // don't try to set the error twice, its already set take the first string.
311 if (this->WriteError == "")
312 this->WriteError = error;
315 std::string userrec::GetWriteError()
317 return this->WriteError;
320 void AddOper(userrec* user)
322 log(DEBUG,"Oper added to optimization list");
323 all_opers.push_back(user);
326 void DeleteOper(userrec* user)
328 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
332 log(DEBUG,"Oper removed from optimization list");
339 void kill_link(userrec *user,const char* r)
341 user_hash::iterator iter = clientlist.find(user->nick);
345 strncpy(reason,r,MAXBUF);
347 if (strlen(reason)>MAXQUIT)
349 reason[MAXQUIT-1] = '\0';
352 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
353 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
354 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
356 if (user->registered == 7) {
357 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
358 WriteCommonExcept(user,"QUIT :%s",reason);
361 user->FlushWriteBuf();
363 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
367 if (Config->GetIOHook(user->port))
369 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
371 ServerInstance->SE->DelFd(user->fd);
375 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
376 // if they were an oper with +s.
377 if (user->registered == 7) {
378 purge_empty_chans(user);
379 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
381 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
385 if (iter != clientlist.end())
387 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
390 fd_ref_table[user->fd] = NULL;
391 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
393 local_users.erase(find(local_users.begin(),local_users.end(),user));
394 log(DEBUG,"Delete local user");
397 clientlist.erase(iter);
402 void kill_link_silent(userrec *user,const char* r)
404 user_hash::iterator iter = clientlist.find(user->nick);
408 strncpy(reason,r,MAXBUF);
410 if (strlen(reason)>MAXQUIT)
412 reason[MAXQUIT-1] = '\0';
415 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
416 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
417 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
419 user->FlushWriteBuf();
421 if (user->registered == 7) {
422 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
423 WriteCommonExcept(user,"QUIT :%s",reason);
426 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
430 if (Config->GetIOHook(user->port))
432 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
434 ServerInstance->SE->DelFd(user->fd);
438 if (user->registered == 7) {
439 purge_empty_chans(user);
442 if (iter != clientlist.end())
444 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
447 fd_ref_table[user->fd] = NULL;
448 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
450 log(DEBUG,"Delete local user");
451 local_users.erase(find(local_users.begin(),local_users.end(),user));
454 clientlist.erase(iter);
460 /* adds or updates an entry in the whowas list */
461 void AddWhoWas(userrec* u)
463 whowas_hash::iterator iter = whowas.find(u->nick);
464 WhoWasUser *a = new WhoWasUser();
465 strlcpy(a->nick,u->nick,NICKMAX);
466 strlcpy(a->ident,u->ident,IDENTMAX);
467 strlcpy(a->dhost,u->dhost,160);
468 strlcpy(a->host,u->host,160);
469 strlcpy(a->fullname,u->fullname,MAXGECOS);
471 strlcpy(a->server,u->server,256);
472 a->signon = u->signon;
474 /* MAX_WHOWAS: max number of /WHOWAS items
475 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
476 * can be replaced by a newer one
479 if (iter == whowas.end())
481 if (whowas.size() >= (unsigned)WHOWAS_MAX)
483 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
485 // 3600 seconds in an hour ;)
486 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
488 // delete the old one
489 if (i->second) delete i->second;
490 // replace with new one
492 log(DEBUG,"added WHOWAS entry, purged an old record");
496 // no space left and user doesnt exist. Don't leave ram in use!
497 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
502 log(DEBUG,"added fresh WHOWAS entry");
508 log(DEBUG,"updated WHOWAS entry");
509 if (iter->second) delete iter->second;
514 /* add a client connection to the sockets list */
515 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
519 user_hash::iterator iter;
521 tempnick = ConvToStr(socket) + "-unknown";
522 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
524 iter = clientlist.find(tempnick);
527 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
528 // using one as a registered connection. As theyre per fd, we can also safely assume
529 // that we wont have collisions. Therefore, if the nick exists in the list, its only
530 // used by a dead socket, erase the iterator so that the new client may reclaim it.
531 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
532 // issue in earlier alphas/betas
533 if (iter != clientlist.end())
535 userrec* goner = iter->second;
537 clientlist.erase(iter);
541 * It is OK to access the value here this way since we know
542 * it exists, we just created it above.
544 * At NO other time should you access a value in a map or a
547 clientlist[tempnick] = new userrec();
549 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
551 clientlist[tempnick]->fd = socket;
552 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
553 strlcpy(clientlist[tempnick]->host, host,160);
554 strlcpy(clientlist[tempnick]->dhost, host,160);
555 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
556 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
557 clientlist[tempnick]->registered = 0;
558 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
559 clientlist[tempnick]->lastping = 1;
560 clientlist[tempnick]->port = port;
561 strlcpy(clientlist[tempnick]->ip,ip,16);
563 // set the registration timeout for this user
564 unsigned long class_regtimeout = 90;
566 long class_threshold = 5;
567 long class_sqmax = 262144; // 256kb
568 long class_rqmax = 4096; // 4k
570 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
572 if (match(clientlist[tempnick]->host,i->host.c_str()) && (i->type == CC_ALLOW))
574 class_regtimeout = (unsigned long)i->registration_timeout;
575 class_flood = i->flood;
576 clientlist[tempnick]->pingmax = i->pingtime;
577 class_threshold = i->threshold;
578 class_sqmax = i->sendqmax;
579 class_rqmax = i->recvqmax;
584 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
585 clientlist[tempnick]->timeout = TIME+class_regtimeout;
586 clientlist[tempnick]->flood = class_flood;
587 clientlist[tempnick]->threshold = class_threshold;
588 clientlist[tempnick]->sendqmax = class_sqmax;
589 clientlist[tempnick]->recvqmax = class_rqmax;
594 for (int i = 0; i < MAXCHANS; i++)
595 clientlist[tempnick]->chans.push_back(a);
597 if (local_users.size() > Config->SoftLimit)
599 kill_link(clientlist[tempnick],"No more connections allowed");
603 if (local_users.size() >= MAXCLIENTS)
605 kill_link(clientlist[tempnick],"No more connections allowed");
609 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
610 // its a pretty big but for the moment valid assumption:
611 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
612 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
613 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
614 // which for the time being is a physical impossibility (even the largest networks dont have more
615 // than about 10,000 users on ONE server!)
616 if ((unsigned)socket > MAX_DESCRIPTORS)
618 kill_link(clientlist[tempnick],"Server is full");
621 char* e = matches_exception(ip);
624 char* r = matches_zline(ip);
628 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
629 kill_link(clientlist[tempnick],reason);
633 fd_ref_table[socket] = clientlist[tempnick];
634 local_users.push_back(clientlist[tempnick]);
635 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
637 WriteServ(clientlist[tempnick]->fd,"NOTICE Auth :*** Looking up your hostname...");
640 void FullConnectUser(userrec* user, CullList* Goners)
642 ServerInstance->stats->statsConnects++;
643 user->idle_lastmsg = TIME;
644 log(DEBUG,"ConnectUser: %s",user->nick);
646 ConnectClass a = GetClass(user);
648 if (a.type == CC_DENY)
650 Goners->AddItem(user,"Unauthorised connection");
653 if ((*(a.pass.c_str())) && (!user->haspassed))
655 Goners->AddItem(user,"Invalid password");
659 char match_against[MAXBUF];
660 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
661 char* e = matches_exception(match_against);
664 char* r = matches_gline(match_against);
668 snprintf(reason,MAXBUF,"G-Lined: %s",r);
669 Goners->AddItem(user,reason);
672 r = matches_kline(user->host);
676 snprintf(reason,MAXBUF,"K-Lined: %s",r);
677 Goners->AddItem(user,reason);
683 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
684 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
685 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
686 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
687 WriteServ(user->fd,"004 %s %s %s :iowghrasxRVSCWBG lvhopsmntikrcaqbegOLQRSKVHGCNT",user->nick,Config->ServerName,VERSION);
688 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
689 // so i'd better split it :)
690 std::stringstream out(Config->data005);
691 std::string token = "";
692 std::string line5 = "";
693 int token_counter = 0;
697 line5 = line5 + token + " ";
699 if ((token_counter >= 13) || (out.eof() == true))
701 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
708 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
709 // onto the network and produce 'fake direction'
710 FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
711 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
712 user->registered = 7;
713 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
716 /* re-allocates a nick in the user_hash after they change nicknames,
717 * returns a pointer to the new user as it may have moved */
719 userrec* ReHashNick(char* Old, char* New)
721 //user_hash::iterator newnick;
722 user_hash::iterator oldnick = clientlist.find(Old);
724 log(DEBUG,"ReHashNick: %s %s",Old,New);
726 if (!strcasecmp(Old,New))
728 log(DEBUG,"old nick is new nick, skipping");
729 return oldnick->second;
732 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
734 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
736 userrec* olduser = oldnick->second;
737 clientlist[New] = olduser;
738 clientlist.erase(oldnick);
740 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
742 return clientlist[New];
745 void force_nickchange(userrec* user,const char* newnick)
752 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
754 ServerInstance->stats->statsCollisions++;
755 kill_link(user,"Nickname collision");
758 if (matches_qline(newnick))
760 ServerInstance->stats->statsCollisions++;
761 kill_link(user,"Nickname collision");
769 strncpy(nick,newnick,MAXBUF);
771 if (user->registered == 7)
775 std::string cmd = "NICK";
776 ServerInstance->Parser->CallHandler(cmd,pars,1,user);