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 std::vector<userrec*> local_users;
56 std::vector<userrec*> all_opers;
58 template<typename T> inline string ConvToStr(const T &in)
61 if (!(tmp << in)) return string();
67 // the PROPER way to do it, AVOID bzero at *ALL* costs
69 strcpy(ip,"127.0.0.1");
76 server = (char*)FindServerNamePtr(Config->ServerName);
81 fd = lastping = signon = idle_lastmsg = nping = registered = 0;
82 flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
95 void userrec::CloseSocket()
101 char* userrec::GetFullHost()
103 static char result[MAXBUF];
104 snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
108 int userrec::ReadData(void* buffer, size_t size)
112 return read(this->fd, buffer, size);
118 char* userrec::GetFullRealHost()
120 static char fresult[MAXBUF];
121 snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
125 bool userrec::IsInvited(irc::string &channel)
127 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
129 irc::string compare = i->channel;
130 if (compare == channel)
138 InvitedList* userrec::GetInviteList()
143 void userrec::InviteTo(irc::string &channel)
147 invites.push_back(i);
150 void userrec::RemoveInvite(irc::string &channel)
152 log(DEBUG,"Removing invites");
155 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
157 irc::string compare = i->channel;
158 if (compare == channel)
167 bool userrec::HasPermission(std::string &command)
169 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
174 // users on u-lined servers can completely bypass
175 // all permissions based checks.
177 // of course, if this is sent to a remote server and this
178 // server is not ulined there, then that other server
179 // silently drops the command.
180 if (is_uline(this->server))
183 // are they even an oper at all?
184 if (strchr(this->modes,'o'))
186 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
188 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
189 if (!strcmp(TypeName,this->oper))
191 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
192 char* myclass = strtok_r(Classes," ",&savept);
195 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
197 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
198 if (!strcmp(ClassName,myclass))
200 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
201 mycmd = strtok_r(CommandList," ",&savept2);
204 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
208 mycmd = strtok_r(NULL," ",&savept2);
212 myclass = strtok_r(NULL," ",&savept);
221 bool userrec::AddBuffer(std::string a)
224 for (unsigned int i = 0; i < a.length(); i++)
225 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
227 std::stringstream stream(recvq);
229 recvq = stream.str();
231 // count the size of the first line in the buffer.
232 while (i < recvq.length())
234 if (recvq[i++] == '\n')
237 if (recvq.length() > (unsigned)this->recvqmax)
239 this->SetWriteError("RecvQ exceeded");
240 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
242 // return false if we've had more than 600 characters WITHOUT
243 // a carriage return (this is BAD, drop the socket)
247 bool userrec::BufferIsReady()
249 for (unsigned int i = 0; i < recvq.length(); i++)
250 if (recvq[i] == '\n')
255 void userrec::ClearBuffer()
260 std::string userrec::GetBuffer()
264 char* line = (char*)recvq.c_str();
265 std::string ret = "";
266 while ((*line != '\n') && (strlen(line)))
271 if ((*line == '\n') || (*line == '\r'))
277 void userrec::AddWriteBuf(std::string data)
279 if (this->GetWriteError() != "")
281 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
283 /* Fix by brain - Set the error text BEFORE calling writeopers, because
284 * if we dont it'll recursively call here over and over again trying
285 * to repeatedly add the text to the sendq!
287 this->SetWriteError("SendQ exceeded");
288 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
291 std::stringstream stream;
292 stream << sendq << data;
293 sendq = stream.str();
296 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
297 void userrec::FlushWriteBuf()
301 char* tb = (char*)this->sendq.c_str();
302 int n_sent = write(this->fd,tb,this->sendq.length());
305 this->SetWriteError(strerror(errno));
312 // update the user's stats counters
313 this->bytes_out += n_sent;
319 void userrec::SetWriteError(std::string error)
321 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
322 // don't try to set the error twice, its already set take the first string.
323 if (this->WriteError == "")
324 this->WriteError = error;
327 std::string userrec::GetWriteError()
329 return this->WriteError;
332 void AddOper(userrec* user)
334 log(DEBUG,"Oper added to optimization list");
335 all_opers.push_back(user);
338 void DeleteOper(userrec* user)
340 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
344 log(DEBUG,"Oper removed from optimization list");
351 void kill_link(userrec *user,const char* r)
353 user_hash::iterator iter = clientlist.find(user->nick);
357 strncpy(reason,r,MAXBUF);
359 if (strlen(reason)>MAXQUIT)
361 reason[MAXQUIT-1] = '\0';
364 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
365 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
366 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
368 if (user->registered == 7) {
369 FOREACH_MOD OnUserQuit(user,reason);
370 WriteCommonExcept(user,"QUIT :%s",reason);
373 user->FlushWriteBuf();
375 FOREACH_MOD OnUserDisconnect(user);
379 FOREACH_MOD OnRawSocketClose(user->fd);
384 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
385 // if they were an oper with +s.
386 if (user->registered == 7) {
387 purge_empty_chans(user);
388 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
390 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
394 if (iter != clientlist.end())
396 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
399 fd_ref_table[user->fd] = NULL;
400 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
402 local_users.erase(find(local_users.begin(),local_users.end(),user));
403 log(DEBUG,"Delete local user");
406 clientlist.erase(iter);
411 void kill_link_silent(userrec *user,const char* r)
413 user_hash::iterator iter = clientlist.find(user->nick);
417 strncpy(reason,r,MAXBUF);
419 if (strlen(reason)>MAXQUIT)
421 reason[MAXQUIT-1] = '\0';
424 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
425 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
426 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
428 user->FlushWriteBuf();
430 if (user->registered == 7) {
431 FOREACH_MOD OnUserQuit(user,reason);
432 WriteCommonExcept(user,"QUIT :%s",reason);
435 FOREACH_MOD OnUserDisconnect(user);
439 FOREACH_MOD OnRawSocketClose(user->fd);
444 if (user->registered == 7) {
445 purge_empty_chans(user);
448 if (iter != clientlist.end())
450 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
453 fd_ref_table[user->fd] = NULL;
454 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
456 log(DEBUG,"Delete local user");
457 local_users.erase(find(local_users.begin(),local_users.end(),user));
460 clientlist.erase(iter);
466 /* adds or updates an entry in the whowas list */
467 void AddWhoWas(userrec* u)
469 whowas_hash::iterator iter = whowas.find(u->nick);
470 WhoWasUser *a = new WhoWasUser();
471 strlcpy(a->nick,u->nick,NICKMAX);
472 strlcpy(a->ident,u->ident,IDENTMAX);
473 strlcpy(a->dhost,u->dhost,160);
474 strlcpy(a->host,u->host,160);
475 strlcpy(a->fullname,u->fullname,MAXGECOS);
476 strlcpy(a->server,u->server,256);
477 a->signon = u->signon;
479 /* MAX_WHOWAS: max number of /WHOWAS items
480 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
481 * can be replaced by a newer one
484 if (iter == whowas.end())
486 if (whowas.size() >= (unsigned)WHOWAS_MAX)
488 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
490 // 3600 seconds in an hour ;)
491 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
493 // delete the old one
494 if (i->second) delete i->second;
495 // replace with new one
497 log(DEBUG,"added WHOWAS entry, purged an old record");
501 // no space left and user doesnt exist. Don't leave ram in use!
502 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
507 log(DEBUG,"added fresh WHOWAS entry");
513 log(DEBUG,"updated WHOWAS entry");
514 if (iter->second) delete iter->second;
519 /* add a client connection to the sockets list */
520 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
524 user_hash::iterator iter;
526 tempnick = ConvToStr(socket) + "-unknown";
527 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
529 iter = clientlist.find(tempnick);
532 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
533 // using one as a registered connection. As theyre per fd, we can also safely assume
534 // that we wont have collisions. Therefore, if the nick exists in the list, its only
535 // used by a dead socket, erase the iterator so that the new client may reclaim it.
536 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
537 // issue in earlier alphas/betas
538 if (iter != clientlist.end())
540 userrec* goner = iter->second;
542 clientlist.erase(iter);
546 * It is OK to access the value here this way since we know
547 * it exists, we just created it above.
549 * At NO other time should you access a value in a map or a
552 clientlist[tempnick] = new userrec();
555 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
557 clientlist[tempnick]->fd = socket;
558 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
559 strlcpy(clientlist[tempnick]->host, host,160);
560 strlcpy(clientlist[tempnick]->dhost, host,160);
561 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
562 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
563 clientlist[tempnick]->registered = 0;
564 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
565 clientlist[tempnick]->lastping = 1;
566 clientlist[tempnick]->port = port;
567 strlcpy(clientlist[tempnick]->ip,ip,16);
569 // set the registration timeout for this user
570 unsigned long class_regtimeout = 90;
572 long class_threshold = 5;
573 long class_sqmax = 262144; // 256kb
574 long class_rqmax = 4096; // 4k
576 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
578 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
580 class_regtimeout = (unsigned long)i->registration_timeout;
581 class_flood = i->flood;
582 clientlist[tempnick]->pingmax = i->pingtime;
583 class_threshold = i->threshold;
584 class_sqmax = i->sendqmax;
585 class_rqmax = i->recvqmax;
590 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
591 clientlist[tempnick]->timeout = TIME+class_regtimeout;
592 clientlist[tempnick]->flood = class_flood;
593 clientlist[tempnick]->threshold = class_threshold;
594 clientlist[tempnick]->sendqmax = class_sqmax;
595 clientlist[tempnick]->recvqmax = class_rqmax;
600 for (int i = 0; i < MAXCHANS; i++)
601 clientlist[tempnick]->chans.push_back(a);
603 if (clientlist.size() > Config->SoftLimit)
605 kill_link(clientlist[tempnick],"No more connections allowed");
609 if (clientlist.size() >= MAXCLIENTS)
611 kill_link(clientlist[tempnick],"No more connections allowed");
615 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
616 // its a pretty big but for the moment valid assumption:
617 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
618 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
619 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
620 // which for the time being is a physical impossibility (even the largest networks dont have more
621 // than about 10,000 users on ONE server!)
622 if ((unsigned)socket > 65534)
624 kill_link(clientlist[tempnick],"Server is full");
627 char* e = matches_exception(ip);
630 char* r = matches_zline(ip);
634 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
635 kill_link(clientlist[tempnick],reason);
639 fd_ref_table[socket] = clientlist[tempnick];
640 local_users.push_back(clientlist[tempnick]);
641 SE->AddFd(socket,true,X_ESTAB_CLIENT);
644 void FullConnectUser(userrec* user)
646 stats->statsConnects++;
647 user->idle_lastmsg = TIME;
648 log(DEBUG,"ConnectUser: %s",user->nick);
650 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
652 kill_link(user,"Invalid password");
657 kill_link(user,"Unauthorised connection");
661 char match_against[MAXBUF];
662 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
663 char* e = matches_exception(match_against);
666 char* r = matches_gline(match_against);
670 snprintf(reason,MAXBUF,"G-Lined: %s",r);
671 kill_link_silent(user,reason);
674 r = matches_kline(user->host);
678 snprintf(reason,MAXBUF,"K-Lined: %s",r);
679 kill_link_silent(user,reason);
685 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
686 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
687 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
688 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
689 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
690 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
692 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
693 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
694 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
695 v << Config->Network;
696 std::string data005 = v.str();
697 FOREACH_MOD On005Numeric(data005);
698 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
699 // so i'd better split it :)
700 std::stringstream out(data005);
701 std::string token = "";
702 std::string line5 = "";
703 int token_counter = 0;
707 line5 = line5 + token + " ";
709 if ((token_counter >= 13) || (out.eof() == true))
711 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
718 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
719 // onto the network and produce 'fake direction'
720 FOREACH_MOD OnUserConnect(user);
721 FOREACH_MOD OnGlobalConnect(user);
722 user->registered = 7;
723 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
727 /* shows the message of the day, and any other on-logon stuff */
728 void ConnectUser(userrec *user)
730 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
731 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
733 FullConnectUser(user);
737 /* re-allocates a nick in the user_hash after they change nicknames,
738 * returns a pointer to the new user as it may have moved */
740 userrec* ReHashNick(char* Old, char* New)
742 //user_hash::iterator newnick;
743 user_hash::iterator oldnick = clientlist.find(Old);
745 log(DEBUG,"ReHashNick: %s %s",Old,New);
747 if (!strcasecmp(Old,New))
749 log(DEBUG,"old nick is new nick, skipping");
750 return oldnick->second;
753 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
755 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
757 userrec* olduser = oldnick->second;
758 clientlist[New] = olduser;
759 clientlist.erase(oldnick);
761 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
763 return clientlist[New];
766 void force_nickchange(userrec* user,const char* newnick)
773 FOREACH_RESULT(OnUserPreNick(user,newnick));
775 stats->statsCollisions++;
776 kill_link(user,"Nickname collision");
779 if (matches_qline(newnick))
781 stats->statsCollisions++;
782 kill_link(user,"Nickname collision");
790 strncpy(nick,newnick,MAXBUF);
792 if (user->registered == 7)
796 handle_nick(pars,1,user);