1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 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"
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[65535];
48 extern userrec* fd_ref_table[65536];
49 extern ServerConfig *Config;
50 extern user_hash clientlist;
51 extern whowas_hash whowas;
52 extern std::vector<userrec*> local_users;
54 std::vector<userrec*> all_opers;
56 template<typename T> inline string ConvToStr(const T &in)
59 if (!(tmp << in)) return string();
65 // the PROPER way to do it, AVOID bzero at *ALL* costs
66 *nick = *ident = *host = *dhost = *fullname = *modes = *awaymsg = *oper = *ip = 0;
67 server = (char*)FindServerNamePtr(Config->ServerName);
69 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
70 timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
71 haspassed = dns_done = false;
82 void userrec::CloseSocket()
88 char* userrec::GetFullHost()
90 static char result[MAXBUF];
91 snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
95 int userrec::ReadData(void* buffer, size_t size)
99 return read(this->fd, buffer, size);
105 char* userrec::GetFullRealHost()
107 static char fresult[MAXBUF];
108 snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
112 bool userrec::IsInvited(irc::string &channel)
114 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
116 irc::string compare = i->channel;
117 if (compare == channel)
125 InvitedList* userrec::GetInviteList()
130 void userrec::InviteTo(irc::string &channel)
134 invites.push_back(i);
137 void userrec::RemoveInvite(irc::string &channel)
139 log(DEBUG,"Removing invites");
142 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
144 irc::string compare = i->channel;
145 if (compare == channel)
154 bool userrec::HasPermission(std::string &command)
156 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
161 // users on u-lined servers can completely bypass
162 // all permissions based checks.
164 // of course, if this is sent to a remote server and this
165 // server is not ulined there, then that other server
166 // silently drops the command.
167 if (is_uline(this->server))
170 // are they even an oper at all?
171 if (strchr(this->modes,'o'))
173 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
175 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
176 if (!strcmp(TypeName,this->oper))
178 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
179 char* myclass = strtok_r(Classes," ",&savept);
182 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
184 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
185 if (!strcmp(ClassName,myclass))
187 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
188 mycmd = strtok_r(CommandList," ",&savept2);
191 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
195 mycmd = strtok_r(NULL," ",&savept2);
199 myclass = strtok_r(NULL," ",&savept);
208 bool userrec::AddBuffer(std::string a)
211 for (unsigned int i = 0; i < a.length(); i++)
212 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
214 std::stringstream stream(recvq);
216 recvq = stream.str();
218 // count the size of the first line in the buffer.
219 while (i < recvq.length())
221 if (recvq[i++] == '\n')
224 if (recvq.length() > (unsigned)this->recvqmax)
226 this->SetWriteError("RecvQ exceeded");
227 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
229 // return false if we've had more than 600 characters WITHOUT
230 // a carriage return (this is BAD, drop the socket)
234 bool userrec::BufferIsReady()
236 for (unsigned int i = 0; i < recvq.length(); i++)
237 if (recvq[i] == '\n')
242 void userrec::ClearBuffer()
247 std::string userrec::GetBuffer()
251 char* line = (char*)recvq.c_str();
252 std::string ret = "";
253 while ((*line != '\n') && (strlen(line)))
258 if ((*line == '\n') || (*line == '\r'))
264 void userrec::AddWriteBuf(std::string data)
266 if (this->GetWriteError() != "")
268 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
270 /* Fix by brain - Set the error text BEFORE calling writeopers, because
271 * if we dont it'll recursively call here over and over again trying
272 * to repeatedly add the text to the sendq!
274 this->SetWriteError("SendQ exceeded");
275 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
278 std::stringstream stream;
279 stream << sendq << data;
280 sendq = stream.str();
283 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
284 void userrec::FlushWriteBuf()
288 char* tb = (char*)this->sendq.c_str();
289 int n_sent = write(this->fd,tb,this->sendq.length());
292 this->SetWriteError(strerror(errno));
299 // update the user's stats counters
300 this->bytes_out += n_sent;
306 void userrec::SetWriteError(std::string error)
308 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
309 // don't try to set the error twice, its already set take the first string.
310 if (this->WriteError == "")
311 this->WriteError = error;
314 std::string userrec::GetWriteError()
316 return this->WriteError;
319 void AddOper(userrec* user)
321 log(DEBUG,"Oper added to optimization list");
322 all_opers.push_back(user);
325 void DeleteOper(userrec* user)
327 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
331 log(DEBUG,"Oper removed from optimization list");
338 void kill_link(userrec *user,const char* r)
340 user_hash::iterator iter = clientlist.find(user->nick);
344 strncpy(reason,r,MAXBUF);
346 if (strlen(reason)>MAXQUIT)
348 reason[MAXQUIT-1] = '\0';
351 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
352 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
353 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
355 if (user->registered == 7) {
356 FOREACH_MOD OnUserQuit(user,reason);
357 WriteCommonExcept(user,"QUIT :%s",reason);
360 user->FlushWriteBuf();
362 FOREACH_MOD OnUserDisconnect(user);
366 if (Config->GetIOHook(user->port))
368 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
370 ServerInstance->SE->DelFd(user->fd);
374 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
375 // if they were an oper with +s.
376 if (user->registered == 7) {
377 purge_empty_chans(user);
378 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
380 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
384 if (iter != clientlist.end())
386 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
389 fd_ref_table[user->fd] = NULL;
390 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
392 local_users.erase(find(local_users.begin(),local_users.end(),user));
393 log(DEBUG,"Delete local user");
396 clientlist.erase(iter);
401 void kill_link_silent(userrec *user,const char* r)
403 user_hash::iterator iter = clientlist.find(user->nick);
407 strncpy(reason,r,MAXBUF);
409 if (strlen(reason)>MAXQUIT)
411 reason[MAXQUIT-1] = '\0';
414 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
415 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
416 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
418 user->FlushWriteBuf();
420 if (user->registered == 7) {
421 FOREACH_MOD OnUserQuit(user,reason);
422 WriteCommonExcept(user,"QUIT :%s",reason);
425 FOREACH_MOD OnUserDisconnect(user);
429 if (Config->GetIOHook(user->port))
431 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
433 ServerInstance->SE->DelFd(user->fd);
437 if (user->registered == 7) {
438 purge_empty_chans(user);
441 if (iter != clientlist.end())
443 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
446 fd_ref_table[user->fd] = NULL;
447 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
449 log(DEBUG,"Delete local user");
450 local_users.erase(find(local_users.begin(),local_users.end(),user));
453 clientlist.erase(iter);
459 /* adds or updates an entry in the whowas list */
460 void AddWhoWas(userrec* u)
462 whowas_hash::iterator iter = whowas.find(u->nick);
463 WhoWasUser *a = new WhoWasUser();
464 strlcpy(a->nick,u->nick,NICKMAX);
465 strlcpy(a->ident,u->ident,IDENTMAX);
466 strlcpy(a->dhost,u->dhost,160);
467 strlcpy(a->host,u->host,160);
468 strlcpy(a->fullname,u->fullname,MAXGECOS);
469 strlcpy(a->server,u->server,256);
470 a->signon = u->signon;
472 /* MAX_WHOWAS: max number of /WHOWAS items
473 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
474 * can be replaced by a newer one
477 if (iter == whowas.end())
479 if (whowas.size() >= (unsigned)WHOWAS_MAX)
481 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
483 // 3600 seconds in an hour ;)
484 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
486 // delete the old one
487 if (i->second) delete i->second;
488 // replace with new one
490 log(DEBUG,"added WHOWAS entry, purged an old record");
494 // no space left and user doesnt exist. Don't leave ram in use!
495 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
500 log(DEBUG,"added fresh WHOWAS entry");
506 log(DEBUG,"updated WHOWAS entry");
507 if (iter->second) delete iter->second;
512 /* add a client connection to the sockets list */
513 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
517 user_hash::iterator iter;
519 tempnick = ConvToStr(socket) + "-unknown";
520 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
522 iter = clientlist.find(tempnick);
525 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
526 // using one as a registered connection. As theyre per fd, we can also safely assume
527 // that we wont have collisions. Therefore, if the nick exists in the list, its only
528 // used by a dead socket, erase the iterator so that the new client may reclaim it.
529 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
530 // issue in earlier alphas/betas
531 if (iter != clientlist.end())
533 userrec* goner = iter->second;
535 clientlist.erase(iter);
539 * It is OK to access the value here this way since we know
540 * it exists, we just created it above.
542 * At NO other time should you access a value in a map or a
545 clientlist[tempnick] = new userrec();
547 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
549 clientlist[tempnick]->fd = socket;
550 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
551 strlcpy(clientlist[tempnick]->host, host,160);
552 strlcpy(clientlist[tempnick]->dhost, host,160);
553 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
554 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
555 clientlist[tempnick]->registered = 0;
556 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
557 clientlist[tempnick]->lastping = 1;
558 clientlist[tempnick]->port = port;
559 strlcpy(clientlist[tempnick]->ip,ip,16);
561 // set the registration timeout for this user
562 unsigned long class_regtimeout = 90;
564 long class_threshold = 5;
565 long class_sqmax = 262144; // 256kb
566 long class_rqmax = 4096; // 4k
568 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
570 if (match(clientlist[tempnick]->host,i->host.c_str()) && (i->type == CC_ALLOW))
572 class_regtimeout = (unsigned long)i->registration_timeout;
573 class_flood = i->flood;
574 clientlist[tempnick]->pingmax = i->pingtime;
575 class_threshold = i->threshold;
576 class_sqmax = i->sendqmax;
577 class_rqmax = i->recvqmax;
582 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
583 clientlist[tempnick]->timeout = TIME+class_regtimeout;
584 clientlist[tempnick]->flood = class_flood;
585 clientlist[tempnick]->threshold = class_threshold;
586 clientlist[tempnick]->sendqmax = class_sqmax;
587 clientlist[tempnick]->recvqmax = class_rqmax;
592 for (int i = 0; i < MAXCHANS; i++)
593 clientlist[tempnick]->chans.push_back(a);
595 if (clientlist.size() > Config->SoftLimit)
597 kill_link(clientlist[tempnick],"No more connections allowed");
601 if (clientlist.size() >= MAXCLIENTS)
603 kill_link(clientlist[tempnick],"No more connections allowed");
607 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
608 // its a pretty big but for the moment valid assumption:
609 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
610 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
611 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
612 // which for the time being is a physical impossibility (even the largest networks dont have more
613 // than about 10,000 users on ONE server!)
614 if ((unsigned)socket > 65534)
616 kill_link(clientlist[tempnick],"Server is full");
619 char* e = matches_exception(ip);
622 char* r = matches_zline(ip);
626 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
627 kill_link(clientlist[tempnick],reason);
631 fd_ref_table[socket] = clientlist[tempnick];
632 local_users.push_back(clientlist[tempnick]);
633 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
636 void FullConnectUser(userrec* user)
638 ServerInstance->stats->statsConnects++;
639 user->idle_lastmsg = TIME;
640 log(DEBUG,"ConnectUser: %s",user->nick);
642 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
644 kill_link(user,"Invalid password");
649 kill_link(user,"Unauthorised connection");
653 char match_against[MAXBUF];
654 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
655 char* e = matches_exception(match_against);
658 char* r = matches_gline(match_against);
662 snprintf(reason,MAXBUF,"G-Lined: %s",r);
663 kill_link_silent(user,reason);
666 r = matches_kline(user->host);
670 snprintf(reason,MAXBUF,"K-Lined: %s",r);
671 kill_link_silent(user,reason);
677 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
678 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
679 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
680 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
681 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
682 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
684 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
685 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
686 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
687 v << Config->Network;
688 std::string data005 = v.str();
689 FOREACH_MOD On005Numeric(data005);
690 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
691 // so i'd better split it :)
692 std::stringstream out(data005);
693 std::string token = "";
694 std::string line5 = "";
695 int token_counter = 0;
699 line5 = line5 + token + " ";
701 if ((token_counter >= 13) || (out.eof() == true))
703 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
710 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
711 // onto the network and produce 'fake direction'
712 FOREACH_MOD OnUserConnect(user);
713 FOREACH_MOD OnGlobalConnect(user);
714 user->registered = 7;
715 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
719 /* shows the message of the day, and any other on-logon stuff */
720 void ConnectUser(userrec *user)
722 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
723 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
725 FullConnectUser(user);
729 /* re-allocates a nick in the user_hash after they change nicknames,
730 * returns a pointer to the new user as it may have moved */
732 userrec* ReHashNick(char* Old, char* New)
734 //user_hash::iterator newnick;
735 user_hash::iterator oldnick = clientlist.find(Old);
737 log(DEBUG,"ReHashNick: %s %s",Old,New);
739 if (!strcasecmp(Old,New))
741 log(DEBUG,"old nick is new nick, skipping");
742 return oldnick->second;
745 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
747 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
749 userrec* olduser = oldnick->second;
750 clientlist[New] = olduser;
751 clientlist.erase(oldnick);
753 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
755 return clientlist[New];
758 void force_nickchange(userrec* user,const char* newnick)
765 FOREACH_RESULT(OnUserPreNick(user,newnick));
767 ServerInstance->stats->statsCollisions++;
768 kill_link(user,"Nickname collision");
771 if (matches_qline(newnick))
773 ServerInstance->stats->statsCollisions++;
774 kill_link(user,"Nickname collision");
782 strncpy(nick,newnick,MAXBUF);
784 if (user->registered == 7)
788 std::string cmd = "NICK";
789 ServerInstance->Parser->CallHandler(cmd,pars,1,user);