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 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
67 strcpy(ip,"127.0.0.1");
74 server = (char*)FindServerNamePtr(Config->ServerName);
79 fd = lastping = signon = idle_lastmsg = nping = registered = 0;
80 flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
93 void userrec::CloseSocket()
99 char* userrec::GetFullHost()
101 static char result[MAXBUF];
102 snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
106 int userrec::ReadData(void* buffer, size_t size)
110 return read(this->fd, buffer, size);
116 char* userrec::GetFullRealHost()
118 static char fresult[MAXBUF];
119 snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
123 bool userrec::IsInvited(irc::string &channel)
125 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
127 irc::string compare = i->channel;
128 if (compare == channel)
136 InvitedList* userrec::GetInviteList()
141 void userrec::InviteTo(irc::string &channel)
145 invites.push_back(i);
148 void userrec::RemoveInvite(irc::string &channel)
150 log(DEBUG,"Removing invites");
153 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
155 irc::string compare = i->channel;
156 if (compare == channel)
165 bool userrec::HasPermission(std::string &command)
167 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
172 // users on u-lined servers can completely bypass
173 // all permissions based checks.
175 // of course, if this is sent to a remote server and this
176 // server is not ulined there, then that other server
177 // silently drops the command.
178 if (is_uline(this->server))
181 // are they even an oper at all?
182 if (strchr(this->modes,'o'))
184 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
186 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
187 if (!strcmp(TypeName,this->oper))
189 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
190 char* myclass = strtok_r(Classes," ",&savept);
193 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
195 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
196 if (!strcmp(ClassName,myclass))
198 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
199 mycmd = strtok_r(CommandList," ",&savept2);
202 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
206 mycmd = strtok_r(NULL," ",&savept2);
210 myclass = strtok_r(NULL," ",&savept);
219 bool userrec::AddBuffer(std::string a)
222 for (unsigned int i = 0; i < a.length(); i++)
223 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
225 std::stringstream stream(recvq);
227 recvq = stream.str();
229 // count the size of the first line in the buffer.
230 while (i < recvq.length())
232 if (recvq[i++] == '\n')
235 if (recvq.length() > (unsigned)this->recvqmax)
237 this->SetWriteError("RecvQ exceeded");
238 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
240 // return false if we've had more than 600 characters WITHOUT
241 // a carriage return (this is BAD, drop the socket)
245 bool userrec::BufferIsReady()
247 for (unsigned int i = 0; i < recvq.length(); i++)
248 if (recvq[i] == '\n')
253 void userrec::ClearBuffer()
258 std::string userrec::GetBuffer()
262 char* line = (char*)recvq.c_str();
263 std::string ret = "";
264 while ((*line != '\n') && (strlen(line)))
269 if ((*line == '\n') || (*line == '\r'))
275 void userrec::AddWriteBuf(std::string data)
277 if (this->GetWriteError() != "")
279 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
281 /* Fix by brain - Set the error text BEFORE calling writeopers, because
282 * if we dont it'll recursively call here over and over again trying
283 * to repeatedly add the text to the sendq!
285 this->SetWriteError("SendQ exceeded");
286 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
289 std::stringstream stream;
290 stream << sendq << data;
291 sendq = stream.str();
294 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
295 void userrec::FlushWriteBuf()
299 char* tb = (char*)this->sendq.c_str();
300 int n_sent = write(this->fd,tb,this->sendq.length());
303 this->SetWriteError(strerror(errno));
310 // update the user's stats counters
311 this->bytes_out += n_sent;
317 void userrec::SetWriteError(std::string error)
319 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
320 // don't try to set the error twice, its already set take the first string.
321 if (this->WriteError == "")
322 this->WriteError = error;
325 std::string userrec::GetWriteError()
327 return this->WriteError;
330 void AddOper(userrec* user)
332 log(DEBUG,"Oper added to optimization list");
333 all_opers.push_back(user);
336 void DeleteOper(userrec* user)
338 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
342 log(DEBUG,"Oper removed from optimization list");
349 void kill_link(userrec *user,const char* r)
351 user_hash::iterator iter = clientlist.find(user->nick);
355 strncpy(reason,r,MAXBUF);
357 if (strlen(reason)>MAXQUIT)
359 reason[MAXQUIT-1] = '\0';
362 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
363 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
364 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
366 if (user->registered == 7) {
367 FOREACH_MOD OnUserQuit(user,reason);
368 WriteCommonExcept(user,"QUIT :%s",reason);
371 user->FlushWriteBuf();
373 FOREACH_MOD OnUserDisconnect(user);
377 if (Config->GetIOHook(user->port))
379 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
381 ServerInstance->SE->DelFd(user->fd);
385 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
386 // if they were an oper with +s.
387 if (user->registered == 7) {
388 purge_empty_chans(user);
389 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
391 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
395 if (iter != clientlist.end())
397 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
400 fd_ref_table[user->fd] = NULL;
401 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
403 local_users.erase(find(local_users.begin(),local_users.end(),user));
404 log(DEBUG,"Delete local user");
407 clientlist.erase(iter);
412 void kill_link_silent(userrec *user,const char* r)
414 user_hash::iterator iter = clientlist.find(user->nick);
418 strncpy(reason,r,MAXBUF);
420 if (strlen(reason)>MAXQUIT)
422 reason[MAXQUIT-1] = '\0';
425 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
426 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
427 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
429 user->FlushWriteBuf();
431 if (user->registered == 7) {
432 FOREACH_MOD OnUserQuit(user,reason);
433 WriteCommonExcept(user,"QUIT :%s",reason);
436 FOREACH_MOD OnUserDisconnect(user);
440 if (Config->GetIOHook(user->port))
442 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
444 ServerInstance->SE->DelFd(user->fd);
448 if (user->registered == 7) {
449 purge_empty_chans(user);
452 if (iter != clientlist.end())
454 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
457 fd_ref_table[user->fd] = NULL;
458 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
460 log(DEBUG,"Delete local user");
461 local_users.erase(find(local_users.begin(),local_users.end(),user));
464 clientlist.erase(iter);
470 /* adds or updates an entry in the whowas list */
471 void AddWhoWas(userrec* u)
473 whowas_hash::iterator iter = whowas.find(u->nick);
474 WhoWasUser *a = new WhoWasUser();
475 strlcpy(a->nick,u->nick,NICKMAX);
476 strlcpy(a->ident,u->ident,IDENTMAX);
477 strlcpy(a->dhost,u->dhost,160);
478 strlcpy(a->host,u->host,160);
479 strlcpy(a->fullname,u->fullname,MAXGECOS);
480 strlcpy(a->server,u->server,256);
481 a->signon = u->signon;
483 /* MAX_WHOWAS: max number of /WHOWAS items
484 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
485 * can be replaced by a newer one
488 if (iter == whowas.end())
490 if (whowas.size() >= (unsigned)WHOWAS_MAX)
492 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
494 // 3600 seconds in an hour ;)
495 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
497 // delete the old one
498 if (i->second) delete i->second;
499 // replace with new one
501 log(DEBUG,"added WHOWAS entry, purged an old record");
505 // no space left and user doesnt exist. Don't leave ram in use!
506 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
511 log(DEBUG,"added fresh WHOWAS entry");
517 log(DEBUG,"updated WHOWAS entry");
518 if (iter->second) delete iter->second;
523 /* add a client connection to the sockets list */
524 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
528 user_hash::iterator iter;
530 tempnick = ConvToStr(socket) + "-unknown";
531 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
533 iter = clientlist.find(tempnick);
536 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
537 // using one as a registered connection. As theyre per fd, we can also safely assume
538 // that we wont have collisions. Therefore, if the nick exists in the list, its only
539 // used by a dead socket, erase the iterator so that the new client may reclaim it.
540 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
541 // issue in earlier alphas/betas
542 if (iter != clientlist.end())
544 userrec* goner = iter->second;
546 clientlist.erase(iter);
550 * It is OK to access the value here this way since we know
551 * it exists, we just created it above.
553 * At NO other time should you access a value in a map or a
556 clientlist[tempnick] = new userrec();
558 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
560 clientlist[tempnick]->fd = socket;
561 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
562 strlcpy(clientlist[tempnick]->host, host,160);
563 strlcpy(clientlist[tempnick]->dhost, host,160);
564 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
565 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
566 clientlist[tempnick]->registered = 0;
567 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
568 clientlist[tempnick]->lastping = 1;
569 clientlist[tempnick]->port = port;
570 strlcpy(clientlist[tempnick]->ip,ip,16);
572 // set the registration timeout for this user
573 unsigned long class_regtimeout = 90;
575 long class_threshold = 5;
576 long class_sqmax = 262144; // 256kb
577 long class_rqmax = 4096; // 4k
579 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
581 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
583 class_regtimeout = (unsigned long)i->registration_timeout;
584 class_flood = i->flood;
585 clientlist[tempnick]->pingmax = i->pingtime;
586 class_threshold = i->threshold;
587 class_sqmax = i->sendqmax;
588 class_rqmax = i->recvqmax;
593 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
594 clientlist[tempnick]->timeout = TIME+class_regtimeout;
595 clientlist[tempnick]->flood = class_flood;
596 clientlist[tempnick]->threshold = class_threshold;
597 clientlist[tempnick]->sendqmax = class_sqmax;
598 clientlist[tempnick]->recvqmax = class_rqmax;
603 for (int i = 0; i < MAXCHANS; i++)
604 clientlist[tempnick]->chans.push_back(a);
606 if (clientlist.size() > Config->SoftLimit)
608 kill_link(clientlist[tempnick],"No more connections allowed");
612 if (clientlist.size() >= MAXCLIENTS)
614 kill_link(clientlist[tempnick],"No more connections allowed");
618 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
619 // its a pretty big but for the moment valid assumption:
620 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
621 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
622 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
623 // which for the time being is a physical impossibility (even the largest networks dont have more
624 // than about 10,000 users on ONE server!)
625 if ((unsigned)socket > 65534)
627 kill_link(clientlist[tempnick],"Server is full");
630 char* e = matches_exception(ip);
633 char* r = matches_zline(ip);
637 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
638 kill_link(clientlist[tempnick],reason);
642 fd_ref_table[socket] = clientlist[tempnick];
643 local_users.push_back(clientlist[tempnick]);
644 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
647 void FullConnectUser(userrec* user)
649 ServerInstance->stats->statsConnects++;
650 user->idle_lastmsg = TIME;
651 log(DEBUG,"ConnectUser: %s",user->nick);
653 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
655 kill_link(user,"Invalid password");
660 kill_link(user,"Unauthorised connection");
664 char match_against[MAXBUF];
665 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
666 char* e = matches_exception(match_against);
669 char* r = matches_gline(match_against);
673 snprintf(reason,MAXBUF,"G-Lined: %s",r);
674 kill_link_silent(user,reason);
677 r = matches_kline(user->host);
681 snprintf(reason,MAXBUF,"K-Lined: %s",r);
682 kill_link_silent(user,reason);
688 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
689 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
690 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
691 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
692 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
693 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
695 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
696 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
697 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
698 v << Config->Network;
699 std::string data005 = v.str();
700 FOREACH_MOD On005Numeric(data005);
701 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
702 // so i'd better split it :)
703 std::stringstream out(data005);
704 std::string token = "";
705 std::string line5 = "";
706 int token_counter = 0;
710 line5 = line5 + token + " ";
712 if ((token_counter >= 13) || (out.eof() == true))
714 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
721 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
722 // onto the network and produce 'fake direction'
723 FOREACH_MOD OnUserConnect(user);
724 FOREACH_MOD OnGlobalConnect(user);
725 user->registered = 7;
726 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
730 /* shows the message of the day, and any other on-logon stuff */
731 void ConnectUser(userrec *user)
733 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
734 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
736 FullConnectUser(user);
740 /* re-allocates a nick in the user_hash after they change nicknames,
741 * returns a pointer to the new user as it may have moved */
743 userrec* ReHashNick(char* Old, char* New)
745 //user_hash::iterator newnick;
746 user_hash::iterator oldnick = clientlist.find(Old);
748 log(DEBUG,"ReHashNick: %s %s",Old,New);
750 if (!strcasecmp(Old,New))
752 log(DEBUG,"old nick is new nick, skipping");
753 return oldnick->second;
756 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
758 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
760 userrec* olduser = oldnick->second;
761 clientlist[New] = olduser;
762 clientlist.erase(oldnick);
764 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
766 return clientlist[New];
769 void force_nickchange(userrec* user,const char* newnick)
776 FOREACH_RESULT(OnUserPreNick(user,newnick));
778 ServerInstance->stats->statsCollisions++;
779 kill_link(user,"Nickname collision");
782 if (matches_qline(newnick))
784 ServerInstance->stats->statsCollisions++;
785 kill_link(user,"Nickname collision");
793 strncpy(nick,newnick,MAXBUF);
795 if (user->registered == 7)
799 std::string cmd = "NICK";
800 ServerInstance->Parser->CallHandler(cmd,pars,1,user);