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 extern ServerConfig* Config;
35 std::vector<userrec*> all_opers;
39 // the PROPER way to do it, AVOID bzero at *ALL* costs
41 strcpy(ip,"127.0.0.1");
48 server = (char*)FindServerNamePtr(Config->ServerName);
53 fd = lastping = signon = idle_lastmsg = nping = registered = 0;
54 flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
67 void userrec::CloseSocket()
73 char* userrec::GetFullHost()
75 static char result[MAXBUF];
76 snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
80 int userrec::ReadData(void* buffer, size_t size)
84 return read(this->fd, buffer, size);
90 char* userrec::GetFullRealHost()
92 static char fresult[MAXBUF];
93 snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
97 bool userrec::IsInvited(irc::string &channel)
99 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
103 irc::string compare = i->channel;
104 if (compare == channel)
113 InvitedList* userrec::GetInviteList()
118 void userrec::InviteTo(irc::string &channel)
122 invites.push_back(i);
125 void userrec::RemoveInvite(std::string &channel)
127 log(DEBUG,"Removing invites");
130 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
134 irc::string compare = i->channel;
135 if (compare == channel)
145 bool userrec::HasPermission(std::string &command)
147 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
152 // users on u-lined servers can completely bypass
153 // all permissions based checks.
155 // of course, if this is sent to a remote server and this
156 // server is not ulined there, then that other server
157 // silently drops the command.
158 if (is_uline(this->server))
161 // are they even an oper at all?
162 if (strchr(this->modes,'o'))
164 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
166 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
167 if (!strcmp(TypeName,this->oper))
169 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
170 char* myclass = strtok_r(Classes," ",&savept);
173 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
175 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
176 if (!strcmp(ClassName,myclass))
178 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
179 mycmd = strtok_r(CommandList," ",&savept2);
182 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
186 mycmd = strtok_r(NULL," ",&savept2);
190 myclass = strtok_r(NULL," ",&savept);
199 bool userrec::AddBuffer(std::string a)
202 for (unsigned int i = 0; i < a.length(); i++)
203 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
205 std::stringstream stream(recvq);
207 recvq = stream.str();
209 // count the size of the first line in the buffer.
210 while (i < recvq.length())
212 if (recvq[i++] == '\n')
215 if (recvq.length() > (unsigned)this->recvqmax)
217 this->SetWriteError("RecvQ exceeded");
218 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
220 // return false if we've had more than 600 characters WITHOUT
221 // a carriage return (this is BAD, drop the socket)
225 bool userrec::BufferIsReady()
227 for (unsigned int i = 0; i < recvq.length(); i++)
228 if (recvq[i] == '\n')
233 void userrec::ClearBuffer()
238 std::string userrec::GetBuffer()
242 char* line = (char*)recvq.c_str();
243 std::string ret = "";
244 while ((*line != '\n') && (strlen(line)))
249 if ((*line == '\n') || (*line == '\r'))
255 void userrec::AddWriteBuf(std::string data)
257 if (this->GetWriteError() != "")
259 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
261 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
262 this->SetWriteError("SendQ exceeded");
265 std::stringstream stream;
266 stream << sendq << data;
267 sendq = stream.str();
270 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
271 void userrec::FlushWriteBuf()
275 char* tb = (char*)this->sendq.c_str();
276 int n_sent = write(this->fd,tb,this->sendq.length());
279 this->SetWriteError(strerror(errno));
286 // update the user's stats counters
287 this->bytes_out += n_sent;
293 void userrec::SetWriteError(std::string error)
295 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
296 // don't try to set the error twice, its already set take the first string.
297 if (this->WriteError == "")
298 this->WriteError = error;
301 std::string userrec::GetWriteError()
303 return this->WriteError;
306 void AddOper(userrec* user)
308 log(DEBUG,"Oper added to optimization list");
309 all_opers.push_back(user);
312 void DeleteOper(userrec* user)
314 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
318 log(DEBUG,"Oper removed from optimization list");
325 void kill_link(userrec *user,const char* r)
327 user_hash::iterator iter = clientlist.find(user->nick);
331 strncpy(reason,r,MAXBUF);
333 if (strlen(reason)>MAXQUIT)
335 reason[MAXQUIT-1] = '\0';
338 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
339 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
340 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
342 if (user->registered == 7) {
343 FOREACH_MOD OnUserQuit(user,reason);
344 WriteCommonExcept(user,"QUIT :%s",reason);
347 user->FlushWriteBuf();
349 FOREACH_MOD OnUserDisconnect(user);
353 FOREACH_MOD OnRawSocketClose(user->fd);
358 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
359 // if they were an oper with +s.
360 if (user->registered == 7) {
361 purge_empty_chans(user);
362 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
364 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
368 if (iter != clientlist.end())
370 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
372 fd_ref_table[user->fd] = NULL;
373 clientlist.erase(iter);
378 void kill_link_silent(userrec *user,const char* r)
380 user_hash::iterator iter = clientlist.find(user->nick);
384 strncpy(reason,r,MAXBUF);
386 if (strlen(reason)>MAXQUIT)
388 reason[MAXQUIT-1] = '\0';
391 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
392 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
393 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
395 user->FlushWriteBuf();
397 if (user->registered == 7) {
398 FOREACH_MOD OnUserQuit(user,reason);
399 WriteCommonExcept(user,"QUIT :%s",reason);
402 FOREACH_MOD OnUserDisconnect(user);
406 FOREACH_MOD OnRawSocketClose(user->fd);
411 if (user->registered == 7) {
412 purge_empty_chans(user);
415 if (iter != clientlist.end())
417 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
419 fd_ref_table[user->fd] = NULL;
420 clientlist.erase(iter);
426 /* adds or updates an entry in the whowas list */
427 void AddWhoWas(userrec* u)
429 whowas_hash::iterator iter = whowas.find(u->nick);
430 WhoWasUser *a = new WhoWasUser();
431 strlcpy(a->nick,u->nick,NICKMAX);
432 strlcpy(a->ident,u->ident,IDENTMAX);
433 strlcpy(a->dhost,u->dhost,160);
434 strlcpy(a->host,u->host,160);
435 strlcpy(a->fullname,u->fullname,MAXGECOS);
436 strlcpy(a->server,u->server,256);
437 a->signon = u->signon;
439 /* MAX_WHOWAS: max number of /WHOWAS items
440 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
441 * can be replaced by a newer one
444 if (iter == whowas.end())
446 if (whowas.size() >= (unsigned)WHOWAS_MAX)
448 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
450 // 3600 seconds in an hour ;)
451 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
453 // delete the old one
454 if (i->second) delete i->second;
455 // replace with new one
457 log(DEBUG,"added WHOWAS entry, purged an old record");
461 // no space left and user doesnt exist. Don't leave ram in use!
462 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
467 log(DEBUG,"added fresh WHOWAS entry");
473 log(DEBUG,"updated WHOWAS entry");
474 if (iter->second) delete iter->second;
479 /* add a client connection to the sockets list */
480 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
484 user_hash::iterator iter;
486 tempnick = ConvToStr(socket) + "-unknown";
487 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
489 iter = clientlist.find(tempnick);
492 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
493 // using one as a registered connection. As theyre per fd, we can also safely assume
494 // that we wont have collisions. Therefore, if the nick exists in the list, its only
495 // used by a dead socket, erase the iterator so that the new client may reclaim it.
496 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
497 // issue in earlier alphas/betas
498 if (iter != clientlist.end())
500 userrec* goner = iter->second;
502 clientlist.erase(iter);
506 * It is OK to access the value here this way since we know
507 * it exists, we just created it above.
509 * At NO other time should you access a value in a map or a
512 clientlist[tempnick] = new userrec();
515 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
517 clientlist[tempnick]->fd = socket;
518 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
519 strlcpy(clientlist[tempnick]->host, host,160);
520 strlcpy(clientlist[tempnick]->dhost, host,160);
521 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
522 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
523 clientlist[tempnick]->registered = 0;
524 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
525 clientlist[tempnick]->lastping = 1;
526 clientlist[tempnick]->port = port;
527 strlcpy(clientlist[tempnick]->ip,ip,16);
529 // set the registration timeout for this user
530 unsigned long class_regtimeout = 90;
532 long class_threshold = 5;
533 long class_sqmax = 262144; // 256kb
534 long class_rqmax = 4096; // 4k
536 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
538 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
540 class_regtimeout = (unsigned long)i->registration_timeout;
541 class_flood = i->flood;
542 clientlist[tempnick]->pingmax = i->pingtime;
543 class_threshold = i->threshold;
544 class_sqmax = i->sendqmax;
545 class_rqmax = i->recvqmax;
550 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
551 clientlist[tempnick]->timeout = TIME+class_regtimeout;
552 clientlist[tempnick]->flood = class_flood;
553 clientlist[tempnick]->threshold = class_threshold;
554 clientlist[tempnick]->sendqmax = class_sqmax;
555 clientlist[tempnick]->recvqmax = class_rqmax;
560 for (int i = 0; i < MAXCHANS; i++)
561 clientlist[tempnick]->chans.push_back(a);
563 if (clientlist.size() > Config->SoftLimit)
565 kill_link(clientlist[tempnick],"No more connections allowed");
569 if (clientlist.size() >= MAXCLIENTS)
571 kill_link(clientlist[tempnick],"No more connections allowed");
575 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
576 // its a pretty big but for the moment valid assumption:
577 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
578 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
579 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
580 // which for the time being is a physical impossibility (even the largest networks dont have more
581 // than about 10,000 users on ONE server!)
582 if ((unsigned)socket > 65534)
584 kill_link(clientlist[tempnick],"Server is full");
587 char* e = matches_exception(ip);
590 char* r = matches_zline(ip);
594 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
595 kill_link(clientlist[tempnick],reason);
599 fd_ref_table[socket] = clientlist[tempnick];
600 SE->AddFd(socket,true,X_ESTAB_CLIENT);
603 void FullConnectUser(userrec* user)
605 stats->statsConnects++;
606 user->idle_lastmsg = TIME;
607 log(DEBUG,"ConnectUser: %s",user->nick);
609 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
611 kill_link(user,"Invalid password");
616 kill_link(user,"Unauthorised connection");
620 char match_against[MAXBUF];
621 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
622 char* e = matches_exception(match_against);
625 char* r = matches_gline(match_against);
629 snprintf(reason,MAXBUF,"G-Lined: %s",r);
630 kill_link_silent(user,reason);
633 r = matches_kline(user->host);
637 snprintf(reason,MAXBUF,"K-Lined: %s",r);
638 kill_link_silent(user,reason);
644 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
645 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
646 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
647 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
648 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
649 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
651 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
652 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
653 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
654 v << Config->Network;
655 std::string data005 = v.str();
656 FOREACH_MOD On005Numeric(data005);
657 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
658 // so i'd better split it :)
659 std::stringstream out(data005);
660 std::string token = "";
661 std::string line5 = "";
662 int token_counter = 0;
666 line5 = line5 + token + " ";
668 if ((token_counter >= 13) || (out.eof() == true))
670 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
677 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
678 // onto the network and produce 'fake direction'
679 FOREACH_MOD OnUserConnect(user);
680 FOREACH_MOD OnGlobalConnect(user);
681 user->registered = 7;
682 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
686 /* shows the message of the day, and any other on-logon stuff */
687 void ConnectUser(userrec *user)
689 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
690 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
692 FullConnectUser(user);