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();
559 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
561 clientlist[tempnick]->fd = socket;
562 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
563 strlcpy(clientlist[tempnick]->host, host,160);
564 strlcpy(clientlist[tempnick]->dhost, host,160);
565 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
566 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
567 clientlist[tempnick]->registered = 0;
568 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
569 clientlist[tempnick]->lastping = 1;
570 clientlist[tempnick]->port = port;
571 strlcpy(clientlist[tempnick]->ip,ip,16);
573 // set the registration timeout for this user
574 unsigned long class_regtimeout = 90;
576 long class_threshold = 5;
577 long class_sqmax = 262144; // 256kb
578 long class_rqmax = 4096; // 4k
580 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
582 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
584 class_regtimeout = (unsigned long)i->registration_timeout;
585 class_flood = i->flood;
586 clientlist[tempnick]->pingmax = i->pingtime;
587 class_threshold = i->threshold;
588 class_sqmax = i->sendqmax;
589 class_rqmax = i->recvqmax;
594 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
595 clientlist[tempnick]->timeout = TIME+class_regtimeout;
596 clientlist[tempnick]->flood = class_flood;
597 clientlist[tempnick]->threshold = class_threshold;
598 clientlist[tempnick]->sendqmax = class_sqmax;
599 clientlist[tempnick]->recvqmax = class_rqmax;
604 for (int i = 0; i < MAXCHANS; i++)
605 clientlist[tempnick]->chans.push_back(a);
607 if (clientlist.size() > Config->SoftLimit)
609 kill_link(clientlist[tempnick],"No more connections allowed");
613 if (clientlist.size() >= MAXCLIENTS)
615 kill_link(clientlist[tempnick],"No more connections allowed");
619 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
620 // its a pretty big but for the moment valid assumption:
621 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
622 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
623 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
624 // which for the time being is a physical impossibility (even the largest networks dont have more
625 // than about 10,000 users on ONE server!)
626 if ((unsigned)socket > 65534)
628 kill_link(clientlist[tempnick],"Server is full");
631 char* e = matches_exception(ip);
634 char* r = matches_zline(ip);
638 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
639 kill_link(clientlist[tempnick],reason);
643 fd_ref_table[socket] = clientlist[tempnick];
644 local_users.push_back(clientlist[tempnick]);
645 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
648 void FullConnectUser(userrec* user)
650 ServerInstance->stats->statsConnects++;
651 user->idle_lastmsg = TIME;
652 log(DEBUG,"ConnectUser: %s",user->nick);
654 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
656 kill_link(user,"Invalid password");
661 kill_link(user,"Unauthorised connection");
665 char match_against[MAXBUF];
666 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
667 char* e = matches_exception(match_against);
670 char* r = matches_gline(match_against);
674 snprintf(reason,MAXBUF,"G-Lined: %s",r);
675 kill_link_silent(user,reason);
678 r = matches_kline(user->host);
682 snprintf(reason,MAXBUF,"K-Lined: %s",r);
683 kill_link_silent(user,reason);
689 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
690 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
691 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
692 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
693 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
694 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
696 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
697 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
698 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
699 v << Config->Network;
700 std::string data005 = v.str();
701 FOREACH_MOD On005Numeric(data005);
702 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
703 // so i'd better split it :)
704 std::stringstream out(data005);
705 std::string token = "";
706 std::string line5 = "";
707 int token_counter = 0;
711 line5 = line5 + token + " ";
713 if ((token_counter >= 13) || (out.eof() == true))
715 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
722 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
723 // onto the network and produce 'fake direction'
724 FOREACH_MOD OnUserConnect(user);
725 FOREACH_MOD OnGlobalConnect(user);
726 user->registered = 7;
727 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
731 /* shows the message of the day, and any other on-logon stuff */
732 void ConnectUser(userrec *user)
734 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
735 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
737 FullConnectUser(user);
741 /* re-allocates a nick in the user_hash after they change nicknames,
742 * returns a pointer to the new user as it may have moved */
744 userrec* ReHashNick(char* Old, char* New)
746 //user_hash::iterator newnick;
747 user_hash::iterator oldnick = clientlist.find(Old);
749 log(DEBUG,"ReHashNick: %s %s",Old,New);
751 if (!strcasecmp(Old,New))
753 log(DEBUG,"old nick is new nick, skipping");
754 return oldnick->second;
757 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
759 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
761 userrec* olduser = oldnick->second;
762 clientlist[New] = olduser;
763 clientlist.erase(oldnick);
765 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
767 return clientlist[New];
770 void force_nickchange(userrec* user,const char* newnick)
777 FOREACH_RESULT(OnUserPreNick(user,newnick));
779 ServerInstance->stats->statsCollisions++;
780 kill_link(user,"Nickname collision");
783 if (matches_qline(newnick))
785 ServerInstance->stats->statsCollisions++;
786 kill_link(user,"Nickname collision");
794 strncpy(nick,newnick,MAXBUF);
796 if (user->registered == 7)
800 std::string cmd = "NICK";
801 ServerInstance->Parser->CallHandler(cmd,pars,1,user);