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++)
101 irc::string compare = i->channel;
102 if (compare == channel)
110 InvitedList* userrec::GetInviteList()
115 void userrec::InviteTo(irc::string &channel)
119 invites.push_back(i);
122 void userrec::RemoveInvite(irc::string &channel)
124 log(DEBUG,"Removing invites");
127 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
131 irc::string compare = i->channel;
132 if (compare == channel)
142 bool userrec::HasPermission(std::string &command)
144 char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
149 // users on u-lined servers can completely bypass
150 // all permissions based checks.
152 // of course, if this is sent to a remote server and this
153 // server is not ulined there, then that other server
154 // silently drops the command.
155 if (is_uline(this->server))
158 // are they even an oper at all?
159 if (strchr(this->modes,'o'))
161 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
163 Config->ConfValue("type","name",j,TypeName,&Config->config_f);
164 if (!strcmp(TypeName,this->oper))
166 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
167 char* myclass = strtok_r(Classes," ",&savept);
170 for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
172 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
173 if (!strcmp(ClassName,myclass))
175 Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
176 mycmd = strtok_r(CommandList," ",&savept2);
179 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
183 mycmd = strtok_r(NULL," ",&savept2);
187 myclass = strtok_r(NULL," ",&savept);
196 bool userrec::AddBuffer(std::string a)
199 for (unsigned int i = 0; i < a.length(); i++)
200 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
202 std::stringstream stream(recvq);
204 recvq = stream.str();
206 // count the size of the first line in the buffer.
207 while (i < recvq.length())
209 if (recvq[i++] == '\n')
212 if (recvq.length() > (unsigned)this->recvqmax)
214 this->SetWriteError("RecvQ exceeded");
215 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
217 // return false if we've had more than 600 characters WITHOUT
218 // a carriage return (this is BAD, drop the socket)
222 bool userrec::BufferIsReady()
224 for (unsigned int i = 0; i < recvq.length(); i++)
225 if (recvq[i] == '\n')
230 void userrec::ClearBuffer()
235 std::string userrec::GetBuffer()
239 char* line = (char*)recvq.c_str();
240 std::string ret = "";
241 while ((*line != '\n') && (strlen(line)))
246 if ((*line == '\n') || (*line == '\r'))
252 void userrec::AddWriteBuf(std::string data)
254 if (this->GetWriteError() != "")
256 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
258 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
259 this->SetWriteError("SendQ exceeded");
262 std::stringstream stream;
263 stream << sendq << data;
264 sendq = stream.str();
267 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
268 void userrec::FlushWriteBuf()
272 char* tb = (char*)this->sendq.c_str();
273 int n_sent = write(this->fd,tb,this->sendq.length());
276 this->SetWriteError(strerror(errno));
283 // update the user's stats counters
284 this->bytes_out += n_sent;
290 void userrec::SetWriteError(std::string error)
292 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
293 // don't try to set the error twice, its already set take the first string.
294 if (this->WriteError == "")
295 this->WriteError = error;
298 std::string userrec::GetWriteError()
300 return this->WriteError;
303 void AddOper(userrec* user)
305 log(DEBUG,"Oper added to optimization list");
306 all_opers.push_back(user);
309 void DeleteOper(userrec* user)
311 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
315 log(DEBUG,"Oper removed from optimization list");
322 void kill_link(userrec *user,const char* r)
324 user_hash::iterator iter = clientlist.find(user->nick);
328 strncpy(reason,r,MAXBUF);
330 if (strlen(reason)>MAXQUIT)
332 reason[MAXQUIT-1] = '\0';
335 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
336 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
337 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
339 if (user->registered == 7) {
340 FOREACH_MOD OnUserQuit(user,reason);
341 WriteCommonExcept(user,"QUIT :%s",reason);
344 user->FlushWriteBuf();
346 FOREACH_MOD OnUserDisconnect(user);
350 FOREACH_MOD OnRawSocketClose(user->fd);
355 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
356 // if they were an oper with +s.
357 if (user->registered == 7) {
358 purge_empty_chans(user);
359 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
361 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
365 if (iter != clientlist.end())
367 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
369 fd_ref_table[user->fd] = NULL;
370 clientlist.erase(iter);
375 void kill_link_silent(userrec *user,const char* r)
377 user_hash::iterator iter = clientlist.find(user->nick);
381 strncpy(reason,r,MAXBUF);
383 if (strlen(reason)>MAXQUIT)
385 reason[MAXQUIT-1] = '\0';
388 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
389 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
390 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
392 user->FlushWriteBuf();
394 if (user->registered == 7) {
395 FOREACH_MOD OnUserQuit(user,reason);
396 WriteCommonExcept(user,"QUIT :%s",reason);
399 FOREACH_MOD OnUserDisconnect(user);
403 FOREACH_MOD OnRawSocketClose(user->fd);
408 if (user->registered == 7) {
409 purge_empty_chans(user);
412 if (iter != clientlist.end())
414 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
416 fd_ref_table[user->fd] = NULL;
417 clientlist.erase(iter);
423 /* adds or updates an entry in the whowas list */
424 void AddWhoWas(userrec* u)
426 whowas_hash::iterator iter = whowas.find(u->nick);
427 WhoWasUser *a = new WhoWasUser();
428 strlcpy(a->nick,u->nick,NICKMAX);
429 strlcpy(a->ident,u->ident,IDENTMAX);
430 strlcpy(a->dhost,u->dhost,160);
431 strlcpy(a->host,u->host,160);
432 strlcpy(a->fullname,u->fullname,MAXGECOS);
433 strlcpy(a->server,u->server,256);
434 a->signon = u->signon;
436 /* MAX_WHOWAS: max number of /WHOWAS items
437 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
438 * can be replaced by a newer one
441 if (iter == whowas.end())
443 if (whowas.size() >= (unsigned)WHOWAS_MAX)
445 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
447 // 3600 seconds in an hour ;)
448 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
450 // delete the old one
451 if (i->second) delete i->second;
452 // replace with new one
454 log(DEBUG,"added WHOWAS entry, purged an old record");
458 // no space left and user doesnt exist. Don't leave ram in use!
459 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
464 log(DEBUG,"added fresh WHOWAS entry");
470 log(DEBUG,"updated WHOWAS entry");
471 if (iter->second) delete iter->second;
476 /* add a client connection to the sockets list */
477 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
481 user_hash::iterator iter;
483 tempnick = ConvToStr(socket) + "-unknown";
484 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
486 iter = clientlist.find(tempnick);
489 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
490 // using one as a registered connection. As theyre per fd, we can also safely assume
491 // that we wont have collisions. Therefore, if the nick exists in the list, its only
492 // used by a dead socket, erase the iterator so that the new client may reclaim it.
493 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
494 // issue in earlier alphas/betas
495 if (iter != clientlist.end())
497 userrec* goner = iter->second;
499 clientlist.erase(iter);
503 * It is OK to access the value here this way since we know
504 * it exists, we just created it above.
506 * At NO other time should you access a value in a map or a
509 clientlist[tempnick] = new userrec();
512 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
514 clientlist[tempnick]->fd = socket;
515 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
516 strlcpy(clientlist[tempnick]->host, host,160);
517 strlcpy(clientlist[tempnick]->dhost, host,160);
518 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
519 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
520 clientlist[tempnick]->registered = 0;
521 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
522 clientlist[tempnick]->lastping = 1;
523 clientlist[tempnick]->port = port;
524 strlcpy(clientlist[tempnick]->ip,ip,16);
526 // set the registration timeout for this user
527 unsigned long class_regtimeout = 90;
529 long class_threshold = 5;
530 long class_sqmax = 262144; // 256kb
531 long class_rqmax = 4096; // 4k
533 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
535 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
537 class_regtimeout = (unsigned long)i->registration_timeout;
538 class_flood = i->flood;
539 clientlist[tempnick]->pingmax = i->pingtime;
540 class_threshold = i->threshold;
541 class_sqmax = i->sendqmax;
542 class_rqmax = i->recvqmax;
547 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
548 clientlist[tempnick]->timeout = TIME+class_regtimeout;
549 clientlist[tempnick]->flood = class_flood;
550 clientlist[tempnick]->threshold = class_threshold;
551 clientlist[tempnick]->sendqmax = class_sqmax;
552 clientlist[tempnick]->recvqmax = class_rqmax;
557 for (int i = 0; i < MAXCHANS; i++)
558 clientlist[tempnick]->chans.push_back(a);
560 if (clientlist.size() > Config->SoftLimit)
562 kill_link(clientlist[tempnick],"No more connections allowed");
566 if (clientlist.size() >= MAXCLIENTS)
568 kill_link(clientlist[tempnick],"No more connections allowed");
572 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
573 // its a pretty big but for the moment valid assumption:
574 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
575 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
576 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
577 // which for the time being is a physical impossibility (even the largest networks dont have more
578 // than about 10,000 users on ONE server!)
579 if ((unsigned)socket > 65534)
581 kill_link(clientlist[tempnick],"Server is full");
584 char* e = matches_exception(ip);
587 char* r = matches_zline(ip);
591 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
592 kill_link(clientlist[tempnick],reason);
596 fd_ref_table[socket] = clientlist[tempnick];
597 SE->AddFd(socket,true,X_ESTAB_CLIENT);
600 void FullConnectUser(userrec* user)
602 stats->statsConnects++;
603 user->idle_lastmsg = TIME;
604 log(DEBUG,"ConnectUser: %s",user->nick);
606 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
608 kill_link(user,"Invalid password");
613 kill_link(user,"Unauthorised connection");
617 char match_against[MAXBUF];
618 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
619 char* e = matches_exception(match_against);
622 char* r = matches_gline(match_against);
626 snprintf(reason,MAXBUF,"G-Lined: %s",r);
627 kill_link_silent(user,reason);
630 r = matches_kline(user->host);
634 snprintf(reason,MAXBUF,"K-Lined: %s",r);
635 kill_link_silent(user,reason);
641 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
642 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
643 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
644 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
645 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
646 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
648 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
649 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
650 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
651 v << Config->Network;
652 std::string data005 = v.str();
653 FOREACH_MOD On005Numeric(data005);
654 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
655 // so i'd better split it :)
656 std::stringstream out(data005);
657 std::string token = "";
658 std::string line5 = "";
659 int token_counter = 0;
663 line5 = line5 + token + " ";
665 if ((token_counter >= 13) || (out.eof() == true))
667 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
674 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
675 // onto the network and produce 'fake direction'
676 FOREACH_MOD OnUserConnect(user);
677 FOREACH_MOD OnGlobalConnect(user);
678 user->registered = 7;
679 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
683 /* shows the message of the day, and any other on-logon stuff */
684 void ConnectUser(userrec *user)
686 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
687 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
689 FullConnectUser(user);