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 SocketEngine* SE;
49 extern userrec* fd_ref_table[65536];
50 extern serverstats* stats;
51 extern ServerConfig *Config;
52 extern user_hash clientlist;
53 extern whowas_hash whowas;
54 extern Module* IOHookModule;
55 std::vector<userrec*> local_users;
57 std::vector<userrec*> all_opers;
59 template<typename T> inline string ConvToStr(const T &in)
62 if (!(tmp << in)) return string();
68 // the PROPER way to do it, AVOID bzero at *ALL* costs
70 strcpy(ip,"127.0.0.1");
77 server = (char*)FindServerNamePtr(Config->ServerName);
82 fd = lastping = signon = idle_lastmsg = nping = registered = 0;
83 flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
96 void userrec::CloseSocket()
102 char* userrec::GetFullHost()
104 static char result[MAXBUF];
105 snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
109 int userrec::ReadData(void* buffer, size_t size)
113 return read(this->fd, buffer, size);
119 char* userrec::GetFullRealHost()
121 static char fresult[MAXBUF];
122 snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
126 bool userrec::IsInvited(irc::string &channel)
128 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
130 irc::string compare = i->channel;
131 if (compare == channel)
139 InvitedList* userrec::GetInviteList()
144 void userrec::InviteTo(irc::string &channel)
148 invites.push_back(i);
151 void userrec::RemoveInvite(irc::string &channel)
153 log(DEBUG,"Removing invites");
156 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
158 irc::string compare = i->channel;
159 if (compare == channel)
168 bool userrec::HasPermission(std::string &command)
170 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
175 // users on u-lined servers can completely bypass
176 // all permissions based checks.
178 // of course, if this is sent to a remote server and this
179 // server is not ulined there, then that other server
180 // silently drops the command.
181 if (is_uline(this->server))
184 // are they even an oper at all?
185 if (strchr(this->modes,'o'))
187 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
189 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
190 if (!strcmp(TypeName,this->oper))
192 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
193 char* myclass = strtok_r(Classes," ",&savept);
196 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
198 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
199 if (!strcmp(ClassName,myclass))
201 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
202 mycmd = strtok_r(CommandList," ",&savept2);
205 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
209 mycmd = strtok_r(NULL," ",&savept2);
213 myclass = strtok_r(NULL," ",&savept);
222 bool userrec::AddBuffer(std::string a)
225 for (unsigned int i = 0; i < a.length(); i++)
226 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
228 std::stringstream stream(recvq);
230 recvq = stream.str();
232 // count the size of the first line in the buffer.
233 while (i < recvq.length())
235 if (recvq[i++] == '\n')
238 if (recvq.length() > (unsigned)this->recvqmax)
240 this->SetWriteError("RecvQ exceeded");
241 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
243 // return false if we've had more than 600 characters WITHOUT
244 // a carriage return (this is BAD, drop the socket)
248 bool userrec::BufferIsReady()
250 for (unsigned int i = 0; i < recvq.length(); i++)
251 if (recvq[i] == '\n')
256 void userrec::ClearBuffer()
261 std::string userrec::GetBuffer()
265 char* line = (char*)recvq.c_str();
266 std::string ret = "";
267 while ((*line != '\n') && (strlen(line)))
272 if ((*line == '\n') || (*line == '\r'))
278 void userrec::AddWriteBuf(std::string data)
280 if (this->GetWriteError() != "")
282 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
284 /* Fix by brain - Set the error text BEFORE calling writeopers, because
285 * if we dont it'll recursively call here over and over again trying
286 * to repeatedly add the text to the sendq!
288 this->SetWriteError("SendQ exceeded");
289 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
292 std::stringstream stream;
293 stream << sendq << data;
294 sendq = stream.str();
297 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
298 void userrec::FlushWriteBuf()
302 char* tb = (char*)this->sendq.c_str();
303 int n_sent = write(this->fd,tb,this->sendq.length());
306 this->SetWriteError(strerror(errno));
313 // update the user's stats counters
314 this->bytes_out += n_sent;
320 void userrec::SetWriteError(std::string error)
322 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
323 // don't try to set the error twice, its already set take the first string.
324 if (this->WriteError == "")
325 this->WriteError = error;
328 std::string userrec::GetWriteError()
330 return this->WriteError;
333 void AddOper(userrec* user)
335 log(DEBUG,"Oper added to optimization list");
336 all_opers.push_back(user);
339 void DeleteOper(userrec* user)
341 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
345 log(DEBUG,"Oper removed from optimization list");
352 void kill_link(userrec *user,const char* r)
354 user_hash::iterator iter = clientlist.find(user->nick);
358 strncpy(reason,r,MAXBUF);
360 if (strlen(reason)>MAXQUIT)
362 reason[MAXQUIT-1] = '\0';
365 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
366 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
367 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
369 if (user->registered == 7) {
370 FOREACH_MOD OnUserQuit(user,reason);
371 WriteCommonExcept(user,"QUIT :%s",reason);
374 user->FlushWriteBuf();
376 FOREACH_MOD OnUserDisconnect(user);
382 IOHookModule->OnRawSocketClose(user->fd);
388 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
389 // if they were an oper with +s.
390 if (user->registered == 7) {
391 purge_empty_chans(user);
392 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
394 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
398 if (iter != clientlist.end())
400 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
403 fd_ref_table[user->fd] = NULL;
404 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
406 local_users.erase(find(local_users.begin(),local_users.end(),user));
407 log(DEBUG,"Delete local user");
410 clientlist.erase(iter);
415 void kill_link_silent(userrec *user,const char* r)
417 user_hash::iterator iter = clientlist.find(user->nick);
421 strncpy(reason,r,MAXBUF);
423 if (strlen(reason)>MAXQUIT)
425 reason[MAXQUIT-1] = '\0';
428 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
429 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
430 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
432 user->FlushWriteBuf();
434 if (user->registered == 7) {
435 FOREACH_MOD OnUserQuit(user,reason);
436 WriteCommonExcept(user,"QUIT :%s",reason);
439 FOREACH_MOD OnUserDisconnect(user);
445 IOHookModule->OnRawSocketClose(user->fd);
451 if (user->registered == 7) {
452 purge_empty_chans(user);
455 if (iter != clientlist.end())
457 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
460 fd_ref_table[user->fd] = NULL;
461 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
463 log(DEBUG,"Delete local user");
464 local_users.erase(find(local_users.begin(),local_users.end(),user));
467 clientlist.erase(iter);
473 /* adds or updates an entry in the whowas list */
474 void AddWhoWas(userrec* u)
476 whowas_hash::iterator iter = whowas.find(u->nick);
477 WhoWasUser *a = new WhoWasUser();
478 strlcpy(a->nick,u->nick,NICKMAX);
479 strlcpy(a->ident,u->ident,IDENTMAX);
480 strlcpy(a->dhost,u->dhost,160);
481 strlcpy(a->host,u->host,160);
482 strlcpy(a->fullname,u->fullname,MAXGECOS);
483 strlcpy(a->server,u->server,256);
484 a->signon = u->signon;
486 /* MAX_WHOWAS: max number of /WHOWAS items
487 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
488 * can be replaced by a newer one
491 if (iter == whowas.end())
493 if (whowas.size() >= (unsigned)WHOWAS_MAX)
495 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
497 // 3600 seconds in an hour ;)
498 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
500 // delete the old one
501 if (i->second) delete i->second;
502 // replace with new one
504 log(DEBUG,"added WHOWAS entry, purged an old record");
508 // no space left and user doesnt exist. Don't leave ram in use!
509 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
514 log(DEBUG,"added fresh WHOWAS entry");
520 log(DEBUG,"updated WHOWAS entry");
521 if (iter->second) delete iter->second;
526 /* add a client connection to the sockets list */
527 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
531 user_hash::iterator iter;
533 tempnick = ConvToStr(socket) + "-unknown";
534 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
536 iter = clientlist.find(tempnick);
539 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
540 // using one as a registered connection. As theyre per fd, we can also safely assume
541 // that we wont have collisions. Therefore, if the nick exists in the list, its only
542 // used by a dead socket, erase the iterator so that the new client may reclaim it.
543 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
544 // issue in earlier alphas/betas
545 if (iter != clientlist.end())
547 userrec* goner = iter->second;
549 clientlist.erase(iter);
553 * It is OK to access the value here this way since we know
554 * it exists, we just created it above.
556 * At NO other time should you access a value in a map or a
559 clientlist[tempnick] = new userrec();
562 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
564 clientlist[tempnick]->fd = socket;
565 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
566 strlcpy(clientlist[tempnick]->host, host,160);
567 strlcpy(clientlist[tempnick]->dhost, host,160);
568 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
569 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
570 clientlist[tempnick]->registered = 0;
571 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
572 clientlist[tempnick]->lastping = 1;
573 clientlist[tempnick]->port = port;
574 strlcpy(clientlist[tempnick]->ip,ip,16);
576 // set the registration timeout for this user
577 unsigned long class_regtimeout = 90;
579 long class_threshold = 5;
580 long class_sqmax = 262144; // 256kb
581 long class_rqmax = 4096; // 4k
583 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
585 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
587 class_regtimeout = (unsigned long)i->registration_timeout;
588 class_flood = i->flood;
589 clientlist[tempnick]->pingmax = i->pingtime;
590 class_threshold = i->threshold;
591 class_sqmax = i->sendqmax;
592 class_rqmax = i->recvqmax;
597 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
598 clientlist[tempnick]->timeout = TIME+class_regtimeout;
599 clientlist[tempnick]->flood = class_flood;
600 clientlist[tempnick]->threshold = class_threshold;
601 clientlist[tempnick]->sendqmax = class_sqmax;
602 clientlist[tempnick]->recvqmax = class_rqmax;
607 for (int i = 0; i < MAXCHANS; i++)
608 clientlist[tempnick]->chans.push_back(a);
610 if (clientlist.size() > Config->SoftLimit)
612 kill_link(clientlist[tempnick],"No more connections allowed");
616 if (clientlist.size() >= MAXCLIENTS)
618 kill_link(clientlist[tempnick],"No more connections allowed");
622 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
623 // its a pretty big but for the moment valid assumption:
624 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
625 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
626 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
627 // which for the time being is a physical impossibility (even the largest networks dont have more
628 // than about 10,000 users on ONE server!)
629 if ((unsigned)socket > 65534)
631 kill_link(clientlist[tempnick],"Server is full");
634 char* e = matches_exception(ip);
637 char* r = matches_zline(ip);
641 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
642 kill_link(clientlist[tempnick],reason);
646 fd_ref_table[socket] = clientlist[tempnick];
647 local_users.push_back(clientlist[tempnick]);
648 SE->AddFd(socket,true,X_ESTAB_CLIENT);
651 void FullConnectUser(userrec* user)
653 stats->statsConnects++;
654 user->idle_lastmsg = TIME;
655 log(DEBUG,"ConnectUser: %s",user->nick);
657 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
659 kill_link(user,"Invalid password");
664 kill_link(user,"Unauthorised connection");
668 char match_against[MAXBUF];
669 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
670 char* e = matches_exception(match_against);
673 char* r = matches_gline(match_against);
677 snprintf(reason,MAXBUF,"G-Lined: %s",r);
678 kill_link_silent(user,reason);
681 r = matches_kline(user->host);
685 snprintf(reason,MAXBUF,"K-Lined: %s",r);
686 kill_link_silent(user,reason);
692 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
693 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
694 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
695 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
696 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
697 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
699 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
700 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
701 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
702 v << Config->Network;
703 std::string data005 = v.str();
704 FOREACH_MOD On005Numeric(data005);
705 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
706 // so i'd better split it :)
707 std::stringstream out(data005);
708 std::string token = "";
709 std::string line5 = "";
710 int token_counter = 0;
714 line5 = line5 + token + " ";
716 if ((token_counter >= 13) || (out.eof() == true))
718 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
725 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
726 // onto the network and produce 'fake direction'
727 FOREACH_MOD OnUserConnect(user);
728 FOREACH_MOD OnGlobalConnect(user);
729 user->registered = 7;
730 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
734 /* shows the message of the day, and any other on-logon stuff */
735 void ConnectUser(userrec *user)
737 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
738 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
740 FullConnectUser(user);
744 /* re-allocates a nick in the user_hash after they change nicknames,
745 * returns a pointer to the new user as it may have moved */
747 userrec* ReHashNick(char* Old, char* New)
749 //user_hash::iterator newnick;
750 user_hash::iterator oldnick = clientlist.find(Old);
752 log(DEBUG,"ReHashNick: %s %s",Old,New);
754 if (!strcasecmp(Old,New))
756 log(DEBUG,"old nick is new nick, skipping");
757 return oldnick->second;
760 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
762 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
764 userrec* olduser = oldnick->second;
765 clientlist[New] = olduser;
766 clientlist.erase(oldnick);
768 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
770 return clientlist[New];
773 void force_nickchange(userrec* user,const char* newnick)
780 FOREACH_RESULT(OnUserPreNick(user,newnick));
782 stats->statsCollisions++;
783 kill_link(user,"Nickname collision");
786 if (matches_qline(newnick))
788 stats->statsCollisions++;
789 kill_link(user,"Nickname collision");
797 strncpy(nick,newnick,MAXBUF);
799 if (user->registered == 7)
803 handle_nick(pars,1,user);