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;
55 std::vector<userrec*> all_opers;
57 template<typename T> inline string ConvToStr(const T &in)
60 if (!(tmp << in)) return string();
66 // the PROPER way to do it, AVOID bzero at *ALL* costs
68 strcpy(ip,"127.0.0.1");
75 server = (char*)FindServerNamePtr(Config->ServerName);
80 fd = lastping = signon = idle_lastmsg = nping = registered = 0;
81 flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
94 void userrec::CloseSocket()
100 char* userrec::GetFullHost()
102 static char result[MAXBUF];
103 snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
107 int userrec::ReadData(void* buffer, size_t size)
111 return read(this->fd, buffer, size);
117 char* userrec::GetFullRealHost()
119 static char fresult[MAXBUF];
120 snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
124 bool userrec::IsInvited(irc::string &channel)
126 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
128 irc::string compare = i->channel;
129 if (compare == channel)
137 InvitedList* userrec::GetInviteList()
142 void userrec::InviteTo(irc::string &channel)
146 invites.push_back(i);
149 void userrec::RemoveInvite(irc::string &channel)
151 log(DEBUG,"Removing invites");
154 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
156 irc::string compare = i->channel;
157 if (compare == channel)
166 bool userrec::HasPermission(std::string &command)
168 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
173 // users on u-lined servers can completely bypass
174 // all permissions based checks.
176 // of course, if this is sent to a remote server and this
177 // server is not ulined there, then that other server
178 // silently drops the command.
179 if (is_uline(this->server))
182 // are they even an oper at all?
183 if (strchr(this->modes,'o'))
185 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
187 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
188 if (!strcmp(TypeName,this->oper))
190 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
191 char* myclass = strtok_r(Classes," ",&savept);
194 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
196 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
197 if (!strcmp(ClassName,myclass))
199 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
200 mycmd = strtok_r(CommandList," ",&savept2);
203 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
207 mycmd = strtok_r(NULL," ",&savept2);
211 myclass = strtok_r(NULL," ",&savept);
220 bool userrec::AddBuffer(std::string a)
223 for (unsigned int i = 0; i < a.length(); i++)
224 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
226 std::stringstream stream(recvq);
228 recvq = stream.str();
230 // count the size of the first line in the buffer.
231 while (i < recvq.length())
233 if (recvq[i++] == '\n')
236 if (recvq.length() > (unsigned)this->recvqmax)
238 this->SetWriteError("RecvQ exceeded");
239 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
241 // return false if we've had more than 600 characters WITHOUT
242 // a carriage return (this is BAD, drop the socket)
246 bool userrec::BufferIsReady()
248 for (unsigned int i = 0; i < recvq.length(); i++)
249 if (recvq[i] == '\n')
254 void userrec::ClearBuffer()
259 std::string userrec::GetBuffer()
263 char* line = (char*)recvq.c_str();
264 std::string ret = "";
265 while ((*line != '\n') && (strlen(line)))
270 if ((*line == '\n') || (*line == '\r'))
276 void userrec::AddWriteBuf(std::string data)
278 if (this->GetWriteError() != "")
280 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
282 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
283 this->SetWriteError("SendQ exceeded");
286 std::stringstream stream;
287 stream << sendq << data;
288 sendq = stream.str();
291 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
292 void userrec::FlushWriteBuf()
296 char* tb = (char*)this->sendq.c_str();
297 int n_sent = write(this->fd,tb,this->sendq.length());
300 this->SetWriteError(strerror(errno));
307 // update the user's stats counters
308 this->bytes_out += n_sent;
314 void userrec::SetWriteError(std::string error)
316 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
317 // don't try to set the error twice, its already set take the first string.
318 if (this->WriteError == "")
319 this->WriteError = error;
322 std::string userrec::GetWriteError()
324 return this->WriteError;
327 void AddOper(userrec* user)
329 log(DEBUG,"Oper added to optimization list");
330 all_opers.push_back(user);
333 void DeleteOper(userrec* user)
335 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
339 log(DEBUG,"Oper removed from optimization list");
346 void kill_link(userrec *user,const char* r)
348 user_hash::iterator iter = clientlist.find(user->nick);
352 strncpy(reason,r,MAXBUF);
354 if (strlen(reason)>MAXQUIT)
356 reason[MAXQUIT-1] = '\0';
359 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
360 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
361 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
363 if (user->registered == 7) {
364 FOREACH_MOD OnUserQuit(user,reason);
365 WriteCommonExcept(user,"QUIT :%s",reason);
368 user->FlushWriteBuf();
370 FOREACH_MOD OnUserDisconnect(user);
374 FOREACH_MOD OnRawSocketClose(user->fd);
379 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
380 // if they were an oper with +s.
381 if (user->registered == 7) {
382 purge_empty_chans(user);
383 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
385 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
389 if (iter != clientlist.end())
391 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
393 fd_ref_table[user->fd] = NULL;
394 clientlist.erase(iter);
399 void kill_link_silent(userrec *user,const char* r)
401 user_hash::iterator iter = clientlist.find(user->nick);
405 strncpy(reason,r,MAXBUF);
407 if (strlen(reason)>MAXQUIT)
409 reason[MAXQUIT-1] = '\0';
412 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
413 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
414 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
416 user->FlushWriteBuf();
418 if (user->registered == 7) {
419 FOREACH_MOD OnUserQuit(user,reason);
420 WriteCommonExcept(user,"QUIT :%s",reason);
423 FOREACH_MOD OnUserDisconnect(user);
427 FOREACH_MOD OnRawSocketClose(user->fd);
432 if (user->registered == 7) {
433 purge_empty_chans(user);
436 if (iter != clientlist.end())
438 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
440 fd_ref_table[user->fd] = NULL;
441 clientlist.erase(iter);
447 /* adds or updates an entry in the whowas list */
448 void AddWhoWas(userrec* u)
450 whowas_hash::iterator iter = whowas.find(u->nick);
451 WhoWasUser *a = new WhoWasUser();
452 strlcpy(a->nick,u->nick,NICKMAX);
453 strlcpy(a->ident,u->ident,IDENTMAX);
454 strlcpy(a->dhost,u->dhost,160);
455 strlcpy(a->host,u->host,160);
456 strlcpy(a->fullname,u->fullname,MAXGECOS);
457 strlcpy(a->server,u->server,256);
458 a->signon = u->signon;
460 /* MAX_WHOWAS: max number of /WHOWAS items
461 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
462 * can be replaced by a newer one
465 if (iter == whowas.end())
467 if (whowas.size() >= (unsigned)WHOWAS_MAX)
469 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
471 // 3600 seconds in an hour ;)
472 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
474 // delete the old one
475 if (i->second) delete i->second;
476 // replace with new one
478 log(DEBUG,"added WHOWAS entry, purged an old record");
482 // no space left and user doesnt exist. Don't leave ram in use!
483 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
488 log(DEBUG,"added fresh WHOWAS entry");
494 log(DEBUG,"updated WHOWAS entry");
495 if (iter->second) delete iter->second;
500 /* add a client connection to the sockets list */
501 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
505 user_hash::iterator iter;
507 tempnick = ConvToStr(socket) + "-unknown";
508 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
510 iter = clientlist.find(tempnick);
513 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
514 // using one as a registered connection. As theyre per fd, we can also safely assume
515 // that we wont have collisions. Therefore, if the nick exists in the list, its only
516 // used by a dead socket, erase the iterator so that the new client may reclaim it.
517 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
518 // issue in earlier alphas/betas
519 if (iter != clientlist.end())
521 userrec* goner = iter->second;
523 clientlist.erase(iter);
527 * It is OK to access the value here this way since we know
528 * it exists, we just created it above.
530 * At NO other time should you access a value in a map or a
533 clientlist[tempnick] = new userrec();
536 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
538 clientlist[tempnick]->fd = socket;
539 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
540 strlcpy(clientlist[tempnick]->host, host,160);
541 strlcpy(clientlist[tempnick]->dhost, host,160);
542 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
543 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
544 clientlist[tempnick]->registered = 0;
545 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
546 clientlist[tempnick]->lastping = 1;
547 clientlist[tempnick]->port = port;
548 strlcpy(clientlist[tempnick]->ip,ip,16);
550 // set the registration timeout for this user
551 unsigned long class_regtimeout = 90;
553 long class_threshold = 5;
554 long class_sqmax = 262144; // 256kb
555 long class_rqmax = 4096; // 4k
557 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
559 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
561 class_regtimeout = (unsigned long)i->registration_timeout;
562 class_flood = i->flood;
563 clientlist[tempnick]->pingmax = i->pingtime;
564 class_threshold = i->threshold;
565 class_sqmax = i->sendqmax;
566 class_rqmax = i->recvqmax;
571 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
572 clientlist[tempnick]->timeout = TIME+class_regtimeout;
573 clientlist[tempnick]->flood = class_flood;
574 clientlist[tempnick]->threshold = class_threshold;
575 clientlist[tempnick]->sendqmax = class_sqmax;
576 clientlist[tempnick]->recvqmax = class_rqmax;
581 for (int i = 0; i < MAXCHANS; i++)
582 clientlist[tempnick]->chans.push_back(a);
584 if (clientlist.size() > Config->SoftLimit)
586 kill_link(clientlist[tempnick],"No more connections allowed");
590 if (clientlist.size() >= MAXCLIENTS)
592 kill_link(clientlist[tempnick],"No more connections allowed");
596 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
597 // its a pretty big but for the moment valid assumption:
598 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
599 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
600 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
601 // which for the time being is a physical impossibility (even the largest networks dont have more
602 // than about 10,000 users on ONE server!)
603 if ((unsigned)socket > 65534)
605 kill_link(clientlist[tempnick],"Server is full");
608 char* e = matches_exception(ip);
611 char* r = matches_zline(ip);
615 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
616 kill_link(clientlist[tempnick],reason);
620 fd_ref_table[socket] = clientlist[tempnick];
621 SE->AddFd(socket,true,X_ESTAB_CLIENT);
624 void FullConnectUser(userrec* user)
626 stats->statsConnects++;
627 user->idle_lastmsg = TIME;
628 log(DEBUG,"ConnectUser: %s",user->nick);
630 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
632 kill_link(user,"Invalid password");
637 kill_link(user,"Unauthorised connection");
641 char match_against[MAXBUF];
642 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
643 char* e = matches_exception(match_against);
646 char* r = matches_gline(match_against);
650 snprintf(reason,MAXBUF,"G-Lined: %s",r);
651 kill_link_silent(user,reason);
654 r = matches_kline(user->host);
658 snprintf(reason,MAXBUF,"K-Lined: %s",r);
659 kill_link_silent(user,reason);
665 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
666 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
667 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
668 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
669 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
670 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
672 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
673 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
674 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
675 v << Config->Network;
676 std::string data005 = v.str();
677 FOREACH_MOD On005Numeric(data005);
678 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
679 // so i'd better split it :)
680 std::stringstream out(data005);
681 std::string token = "";
682 std::string line5 = "";
683 int token_counter = 0;
687 line5 = line5 + token + " ";
689 if ((token_counter >= 13) || (out.eof() == true))
691 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
698 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
699 // onto the network and produce 'fake direction'
700 FOREACH_MOD OnUserConnect(user);
701 FOREACH_MOD OnGlobalConnect(user);
702 user->registered = 7;
703 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
707 /* shows the message of the day, and any other on-logon stuff */
708 void ConnectUser(userrec *user)
710 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
711 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
713 FullConnectUser(user);
717 /* re-allocates a nick in the user_hash after they change nicknames,
718 * returns a pointer to the new user as it may have moved */
720 userrec* ReHashNick(char* Old, char* New)
722 //user_hash::iterator newnick;
723 user_hash::iterator oldnick = clientlist.find(Old);
725 log(DEBUG,"ReHashNick: %s %s",Old,New);
727 if (!strcasecmp(Old,New))
729 log(DEBUG,"old nick is new nick, skipping");
730 return oldnick->second;
733 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
735 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
737 userrec* olduser = oldnick->second;
738 clientlist[New] = olduser;
739 clientlist.erase(oldnick);
741 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
743 return clientlist[New];
746 void force_nickchange(userrec* user,const char* newnick)
753 FOREACH_RESULT(OnUserPreNick(user,newnick));
755 stats->statsCollisions++;
756 kill_link(user,"Nickname collision");
759 if (matches_qline(newnick))
761 stats->statsCollisions++;
762 kill_link(user,"Nickname collision");
770 strncpy(nick,newnick,MAXBUF);
772 if (user->registered == 7)
776 handle_nick(pars,1,user);