1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 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 * ---------------------------------------------------
17 #include "inspircd_config.h"
18 #include "configreader.h"
20 #include "connection.h"
24 #include "inspstring.h"
26 #include "helperfuncs.h"
28 #include "socketengine.h"
33 #include "cull_list.h"
35 extern InspIRCd* ServerInstance;
36 extern int WHOWAS_STALE;
37 extern int WHOWAS_MAX;
38 extern std::vector<Module*> modules;
39 extern std::vector<ircd_module*> factory;
40 extern std::vector<InspSocket*> module_sockets;
42 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
44 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
45 extern ServerConfig *Config;
46 extern user_hash clientlist;
47 extern Server* MyServer;
48 extern std::vector<userrec*> local_users;
50 irc::whowas::whowas_users whowas;
51 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
52 std::vector<userrec*> all_opers;
54 typedef std::map<irc::string,char*> opertype_t;
55 typedef opertype_t operclass_t;
58 operclass_t operclass;
60 /* XXX: Used for speeding up WriteCommon operations */
61 unsigned long uniq_id = 0;
63 bool InitTypes(const char* tag)
65 for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
75 bool InitClasses(const char* tag)
77 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
87 bool DoType(const char* tag, char** entries, void** values, int* types)
89 char* TypeName = (char*)values[0];
90 char* Classes = (char*)values[1];
92 opertypes[TypeName] = strdup(Classes);
93 log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
97 bool DoClass(const char* tag, char** entries, void** values, int* types)
99 char* ClassName = (char*)values[0];
100 char* CommandList = (char*)values[1];
102 operclass[ClassName] = strdup(CommandList);
103 log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
107 bool DoneClassesAndTypes(const char* tag)
112 bool userrec::ProcessNoticeMasks(const char *sm)
128 if ((*c >= 'A') && (*c <= 'z'))
129 this->SetNoticeMask(*c, adding);
139 void userrec::StartDNSLookup()
141 log(DEBUG,"Commencing reverse lookup");
144 res_reverse = new UserResolver(this, this->GetIPString(), false);
145 MyServer->AddResolver(res_reverse);
147 catch (ModuleException& e)
149 log(DEBUG,"Error in resolver: %s",e.GetReason());
153 UserResolver::UserResolver(userrec* user, std::string to_resolve, bool forward) : Resolver(to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
156 this->bound_fd = user->fd;
159 void UserResolver::OnLookupComplete(const std::string &result)
161 if ((!this->fwd) && (fd_ref_table[this->bound_fd] == this->bound_user))
163 log(DEBUG,"Commencing forward lookup");
164 this->bound_user->stored_host = result;
167 bound_user->res_forward = new UserResolver(this->bound_user, result, true);
168 MyServer->AddResolver(bound_user->res_forward);
170 catch (ModuleException& e)
172 log(DEBUG,"Error in resolver: %s",e.GetReason());
175 else if ((this->fwd) && (fd_ref_table[this->bound_fd] == this->bound_user))
177 /* Both lookups completed */
178 if (this->bound_user->GetIPString() == result)
180 std::string hostname = this->bound_user->stored_host;
181 if (hostname.length() < 65)
183 /* Hostnames starting with : are not a good thing (tm) */
184 if (*(hostname.c_str()) == ':')
185 hostname = "0" + hostname;
187 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
188 this->bound_user->dns_done = true;
189 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
190 strlcpy(this->bound_user->host, hostname.c_str(),64);
194 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname is longer than the maximum of 64 characters, using your IP address (%s) instead.", this->bound_user->GetIPString());
199 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname does not match up with your IP address. Sorry, using your IP address (%s) instead.", this->bound_user->GetIPString());
204 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
206 if (fd_ref_table[this->bound_fd] == this->bound_user)
208 /* Error message here */
209 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
210 this->bound_user->dns_done = true;
215 bool userrec::IsNoticeMaskSet(unsigned char sm)
217 return (snomasks[sm-65]);
220 void userrec::SetNoticeMask(unsigned char sm, bool value)
222 snomasks[sm-65] = value;
225 const char* userrec::FormatNoticeMasks()
227 static char data[MAXBUF];
230 for (int n = 0; n < 64; n++)
233 data[offset++] = n+65;
242 bool userrec::IsModeSet(unsigned char m)
244 return (modes[m-65]);
247 void userrec::SetMode(unsigned char m, bool value)
252 const char* userrec::FormatModes()
254 static char data[MAXBUF];
256 for (int n = 0; n < 64; n++)
259 data[offset++] = n+65;
267 // the PROPER way to do it, AVOID bzero at *ALL* costs
268 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
269 server = (char*)FindServerNamePtr(Config->ServerName);
271 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
272 timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
273 haspassed = dns_done = false;
277 res_forward = res_reverse = NULL;
281 chans.resize(MAXCHANS);
282 memset(modes,0,sizeof(modes));
284 for (unsigned int n = 0; n < MAXCHANS; n++)
286 ucrec* x = new ucrec();
295 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
297 ucrec* x = (ucrec*)*n;
303 if (this->GetProtocolFamily() == AF_INET)
305 delete (sockaddr_in*)ip;
307 #ifdef SUPPORT_IP6LINKS
310 delete (sockaddr_in6*)ip;
316 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
317 void userrec::MakeHost(char* nhost)
319 /* This is much faster than snprintf */
321 for(char* n = ident; *n; n++)
324 for(char* n = host; *n; n++)
329 void userrec::CloseSocket()
331 shutdown(this->fd,2);
335 char* userrec::GetFullHost()
337 static char result[MAXBUF];
339 for(char* n = nick; *n; n++)
342 for(char* n = ident; *n; n++)
345 for(char* n = dhost; *n; n++)
351 char* userrec::MakeWildHost()
353 static char nresult[MAXBUF];
355 *t++ = '*'; *t++ = '!';
356 *t++ = '*'; *t++ = '@';
357 for(char* n = dhost; *n; n++)
363 int userrec::ReadData(void* buffer, size_t size)
367 return read(this->fd, buffer, size);
374 char* userrec::GetFullRealHost()
376 static char fresult[MAXBUF];
378 for(char* n = nick; *n; n++)
381 for(char* n = ident; *n; n++)
384 for(char* n = host; *n; n++)
390 bool userrec::IsInvited(irc::string &channel)
392 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
394 irc::string compare = i->channel;
396 if (compare == channel)
404 InvitedList* userrec::GetInviteList()
409 void userrec::InviteTo(irc::string &channel)
413 invites.push_back(i);
416 void userrec::RemoveInvite(irc::string &channel)
418 log(DEBUG,"Removing invites");
422 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
424 irc::string compare = i->channel;
426 if (compare == channel)
435 bool userrec::HasPermission(const std::string &command)
442 * users on remote servers can completely bypass all permissions based checks.
443 * This prevents desyncs when one server has different type/class tags to another.
444 * That having been said, this does open things up to the possibility of source changes
445 * allowing remote kills, etc - but if they have access to the src, they most likely have
446 * access to the conf - so it's an end to a means either way.
451 // are they even an oper at all?
454 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
455 if (iter_opertype != opertypes.end())
457 char* Classes = strdup(iter_opertype->second);
458 char* myclass = strtok_r(Classes," ",&savept);
461 operclass_t::iterator iter_operclass = operclass.find(myclass);
462 if (iter_operclass != operclass.end())
464 char* CommandList = strdup(iter_operclass->second);
465 mycmd = strtok_r(CommandList," ",&savept2);
468 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
474 mycmd = strtok_r(NULL," ",&savept2);
478 myclass = strtok_r(NULL," ",&savept);
487 bool userrec::AddBuffer(const std::string &a)
491 /* NB: std::string is arsey about \r and \n and tries to translate them
492 * somehow, so we CANNOT use std::string::find() here :(
494 for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
503 if (recvq.length() > (unsigned)this->recvqmax)
505 this->SetWriteError("RecvQ exceeded");
506 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
513 bool userrec::BufferIsReady()
515 return (recvq.find('\n') != std::string::npos);
518 void userrec::ClearBuffer()
523 std::string userrec::GetBuffer()
528 /* Strip any leading \r or \n off the string.
529 * Usually there are only one or two of these,
530 * so its is computationally cheap to do.
532 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
533 recvq.erase(recvq.begin());
535 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
537 /* Find the first complete line, return it as the
538 * result, and leave the recvq as whats left
542 std::string ret = std::string(recvq.begin(), x);
543 recvq.erase(recvq.begin(), x + 1);
550 void userrec::AddWriteBuf(const std::string &data)
552 if (*this->GetWriteError())
555 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
558 * Fix by brain - Set the error text BEFORE calling writeopers, because
559 * if we dont it'll recursively call here over and over again trying
560 * to repeatedly add the text to the sendq!
562 this->SetWriteError("SendQ exceeded");
563 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
567 if (data.length() > 512)
569 std::string newdata(data);
571 newdata.append("\r\n");
572 sendq.append(newdata);
580 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
581 void userrec::FlushWriteBuf()
583 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
585 const char* tb = this->sendq.c_str();
586 int n_sent = write(this->fd,tb,this->sendq.length());
590 this->SetWriteError(strerror(errno));
597 // update the user's stats counters
598 this->bytes_out += n_sent;
604 void userrec::SetWriteError(const std::string &error)
606 log(DEBUG,"SetWriteError: %s",error.c_str());
607 // don't try to set the error twice, its already set take the first string.
608 if (!this->WriteError.length())
610 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
611 this->WriteError = error;
615 const char* userrec::GetWriteError()
617 return this->WriteError.c_str();
620 void userrec::Oper(const std::string &opertype)
622 this->modes[UM_OPERATOR] = 1;
623 this->WriteServ("MODE %s :+o", this->nick);
624 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
625 log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
626 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
627 all_opers.push_back(this);
628 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
631 void userrec::UnOper()
636 this->modes[UM_OPERATOR] = 0;
637 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
641 log(DEBUG,"Oper removed from optimization list");
649 void userrec::QuitUser(userrec *user,const std::string &quitreason)
651 user_hash::iterator iter = clientlist.find(user->nick);
654 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
655 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
657 * I can't imagine this blowing up, so I'm commenting it out. We still check
658 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
660 * if (iter == clientlist.end())
663 std::string reason = quitreason;
665 if (reason.length() > MAXQUIT - 1)
666 reason.resize(MAXQUIT - 1);
669 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
671 if (user->registered == REG_ALL)
673 purge_empty_chans(user);
674 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
675 user->WriteCommonExcept("QUIT :%s",reason.c_str());
679 user->FlushWriteBuf();
681 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
685 if (Config->GetIOHook(user->GetPort()))
689 Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
691 catch (ModuleException& modexcept)
693 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
697 ServerInstance->SE->DelFd(user->fd);
702 * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
703 * if they were an oper with +s.
706 * In the current implementation, we only show local quits, as we only show local connects. With
707 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
709 if (user->registered == REG_ALL)
712 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
716 if (iter != clientlist.end())
718 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
721 fd_ref_table[user->fd] = NULL;
722 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
723 local_users.erase(find(local_users.begin(),local_users.end(),user));
725 clientlist.erase(iter);
735 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
737 this->host = strdup(user->host);
738 this->dhost = strdup(user->dhost);
739 this->ident = strdup(user->ident);
740 this->server = user->server;
741 this->gecos = strdup(user->fullname);
744 WhoWasGroup::~WhoWasGroup()
756 /* every hour, run this function which removes all entries over 3 days */
757 void MaintainWhoWas(time_t TIME)
759 for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
761 whowas_set* n = (whowas_set*)iter->second;
764 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
766 WhoWasGroup *a = *(n->begin());
768 n->erase(n->begin());
776 /* adds or updates an entry in the whowas list */
777 void userrec::AddToWhoWas()
779 irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
781 if (iter == whowas.end())
783 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
784 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
786 whowas[this->nick] = n;
790 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
792 if (group->size() > 10)
794 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
799 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
804 /* add a client connection to the sockets list */
805 void userrec::AddClient(int socket, int port, bool iscached, insp_inaddr ip)
807 std::string tempnick = ConvToStr(socket) + "-unknown";
808 user_hash::iterator iter = clientlist.find(tempnick);
809 const char *ipaddr = insp_ntoa(ip);
815 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
816 * using one as a registered connection. As they are per fd, we can also safely assume
817 * that we wont have collisions. Therefore, if the nick exists in the list, its only
818 * used by a dead socket, erase the iterator so that the new client may reclaim it.
819 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
820 * issue in earlier alphas/betas
822 if (iter != clientlist.end())
824 userrec* goner = iter->second;
826 clientlist.erase(iter);
829 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
831 _new = new userrec();
832 clientlist[tempnick] = _new;
834 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
836 _new->server = FindServerNamePtr(Config->ServerName);
837 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
838 strcpy(_new->ident, "unknown");
840 _new->registered = REG_NONE;
841 _new->signon = TIME + Config->dns_timeout;
844 log(DEBUG,"Setting socket addresses");
845 _new->SetSockAddr(AF_FAMILY, ipaddr, port);
846 log(DEBUG,"Socket addresses set.");
848 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
849 for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
850 _new->dhost[j] = _new->host[j] = *temp;
851 _new->dhost[j] = _new->host[j] = 0;
853 // set the registration timeout for this user
854 unsigned long class_regtimeout = 90;
856 long class_threshold = 5;
857 long class_sqmax = 262144; // 256kb
858 long class_rqmax = 4096; // 4k
860 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
862 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
864 class_regtimeout = (unsigned long)i->registration_timeout;
865 class_flood = i->flood;
866 _new->pingmax = i->pingtime;
867 class_threshold = i->threshold;
868 class_sqmax = i->sendqmax;
869 class_rqmax = i->recvqmax;
874 _new->nping = TIME + _new->pingmax + Config->dns_timeout;
875 _new->timeout = TIME+class_regtimeout;
876 _new->flood = class_flood;
877 _new->threshold = class_threshold;
878 _new->sendqmax = class_sqmax;
879 _new->recvqmax = class_rqmax;
881 fd_ref_table[socket] = _new;
882 local_users.push_back(_new);
884 if (local_users.size() > Config->SoftLimit)
886 userrec::QuitUser(_new,"No more connections allowed");
890 if (local_users.size() >= MAXCLIENTS)
892 userrec::QuitUser(_new,"No more connections allowed");
898 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
899 * its a pretty big but for the moment valid assumption:
900 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
901 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
902 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
903 * which for the time being is a physical impossibility (even the largest networks dont have more
904 * than about 10,000 users on ONE server!)
906 if ((unsigned)socket >= MAX_DESCRIPTORS)
908 userrec::QuitUser(_new,"Server is full");
911 char* e = matches_exception(ipaddr);
914 char* r = matches_zline(ipaddr);
918 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
919 userrec::QuitUser(_new,reason);
926 if (!ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
928 userrec::QuitUser(_new, "Internal error handling connection");
933 _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
936 long userrec::GlobalCloneCount()
941 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
943 /* We have to match ip's as strings - we don't know what protocol
944 * a remote user may be using
946 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
952 long userrec::LocalCloneCount()
955 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
959 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
960 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
961 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
962 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
965 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
966 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
967 if (s1->s_addr == s2->s_addr)
974 void userrec::FullConnect(CullList* Goners)
976 ServerInstance->stats->statsConnects++;
977 this->idle_lastmsg = TIME;
979 ConnectClass a = GetClass(this);
981 if (a.type == CC_DENY)
983 Goners->AddItem(this,"Unauthorised connection");
987 if ((*(a.pass.c_str())) && (!this->haspassed))
989 Goners->AddItem(this,"Invalid password");
993 if (this->LocalCloneCount() > a.maxlocal)
995 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
996 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
999 else if (this->GlobalCloneCount() > a.maxglobal)
1001 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1002 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1006 char match_against[MAXBUF];
1007 snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
1008 char* e = matches_exception(match_against);
1012 char* r = matches_gline(match_against);
1016 char reason[MAXBUF];
1017 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1018 Goners->AddItem(this, reason);
1022 r = matches_kline(match_against);
1026 char reason[MAXBUF];
1027 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1028 Goners->AddItem(this, reason);
1034 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",Config->Network);
1035 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, Config->Network, this->nick, this->ident, this->host);
1036 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,Config->ServerName,VERSION);
1037 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1038 this->WriteServ("004 %s %s %s %s %s %s", this->nick, Config->ServerName, VERSION, ServerInstance->ModeGrok->UserModeList().c_str(), ServerInstance->ModeGrok->ChannelModeList().c_str(), ServerInstance->ModeGrok->ParaModeList().c_str());
1040 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1041 // so i'd better split it :)
1042 std::stringstream out(Config->data005);
1043 std::string token = "";
1044 std::string line5 = "";
1045 int token_counter = 0;
1050 line5 = line5 + token + " ";
1053 if ((token_counter >= 13) || (out.eof() == true))
1055 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1064 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1065 * changes dont go out onto the network and produce 'fake direction'.
1067 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1068 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(this));
1069 this->registered = REG_ALL;
1070 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1073 /** userrec::UpdateNick()
1074 * re-allocates a nick in the user_hash after they change nicknames,
1075 * returns a pointer to the new user as it may have moved
1077 userrec* userrec::UpdateNickHash(const char* New)
1079 //user_hash::iterator newnick;
1080 user_hash::iterator oldnick = clientlist.find(this->nick);
1082 if (!strcasecmp(this->nick,New))
1083 return oldnick->second;
1085 if (oldnick == clientlist.end())
1086 return NULL; /* doesnt exist */
1088 userrec* olduser = oldnick->second;
1089 clientlist[New] = olduser;
1090 clientlist.erase(oldnick);
1091 return clientlist[New];
1094 bool userrec::ForceNickChange(const char* newnick)
1101 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1105 ServerInstance->stats->statsCollisions++;
1109 if (matches_qline(newnick))
1111 ServerInstance->stats->statsCollisions++;
1117 strlcpy(this->nick, newnick, NICKMAX - 1);
1119 if (this->registered == REG_ALL)
1121 const char* pars[1];
1123 std::string cmd = "NICK";
1124 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1129 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1131 switch (protocol_family)
1133 #ifdef SUPPORT_IP6LINKS
1136 log(DEBUG,"Set inet6 protocol address");
1137 sockaddr_in6* sin = new sockaddr_in6;
1138 sin->sin6_family = AF_INET6;
1139 sin->sin6_port = port;
1140 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1141 this->ip = (sockaddr*)sin;
1147 log(DEBUG,"Set inet4 protocol address");
1148 sockaddr_in* sin = new sockaddr_in;
1149 sin->sin_family = AF_INET;
1150 sin->sin_port = port;
1151 inet_pton(AF_INET, ip, &sin->sin_addr);
1152 this->ip = (sockaddr*)sin;
1156 log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1161 int userrec::GetPort()
1163 if (this->ip == NULL)
1166 switch (this->GetProtocolFamily())
1168 #ifdef SUPPORT_IP6LINKS
1171 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1172 return sin->sin6_port;
1178 sockaddr_in* sin = (sockaddr_in*)this->ip;
1179 return sin->sin_port;
1183 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1189 int userrec::GetProtocolFamily()
1191 if (this->ip == NULL)
1194 sockaddr_in* sin = (sockaddr_in*)this->ip;
1195 return sin->sin_family;
1198 const char* userrec::GetIPString()
1200 static char buf[1024];
1201 static char temp[1024];
1203 if (this->ip == NULL)
1206 switch (this->GetProtocolFamily())
1208 #ifdef SUPPORT_IP6LINKS
1211 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1212 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1213 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1216 strlcpy(&temp[1], buf, sizeof(temp));
1226 sockaddr_in* sin = (sockaddr_in*)this->ip;
1227 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1232 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1238 const char* userrec::GetIPString(char* buf)
1240 static char temp[1024];
1242 if (this->ip == NULL)
1248 switch (this->GetProtocolFamily())
1250 #ifdef SUPPORT_IP6LINKS
1253 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1254 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1255 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1258 strlcpy(&temp[1], buf, sizeof(temp));
1260 strlcpy(buf, temp, sizeof(temp));
1268 sockaddr_in* sin = (sockaddr_in*)this->ip;
1269 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1275 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1282 void userrec::Write(const std::string &text)
1284 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1287 std::string crlf = text;
1288 crlf.append("\r\n");
1290 if (Config->GetIOHook(this->GetPort()))
1294 Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, crlf.data(), crlf.length());
1296 catch (ModuleException& modexcept)
1298 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1303 this->AddWriteBuf(crlf);
1305 ServerInstance->stats->statsSent += crlf.length();
1310 void userrec::Write(const char *text, ...)
1313 char textbuffer[MAXBUF];
1315 va_start(argsPtr, text);
1316 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1319 this->Write(std::string(textbuffer));
1322 void userrec::WriteServ(const std::string& text)
1324 char textbuffer[MAXBUF];
1326 snprintf(textbuffer,MAXBUF,":%s %s",Config->ServerName,text.c_str());
1327 this->Write(std::string(textbuffer));
1331 * Same as Write(), except `text' is prefixed with `:server.name '.
1333 void userrec::WriteServ(const char* text, ...)
1336 char textbuffer[MAXBUF];
1338 va_start(argsPtr, text);
1339 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1342 this->WriteServ(std::string(textbuffer));
1346 void userrec::WriteFrom(userrec *user, const std::string &text)
1350 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1352 this->Write(std::string(tb));
1356 /* write text from an originating user to originating user */
1358 void userrec::WriteFrom(userrec *user, const char* text, ...)
1361 char textbuffer[MAXBUF];
1363 va_start(argsPtr, text);
1364 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1367 this->WriteFrom(user, std::string(textbuffer));
1371 /* write text to an destination user from a source user (e.g. user privmsg) */
1373 void userrec::WriteTo(userrec *dest, const char *data, ...)
1375 char textbuffer[MAXBUF];
1378 va_start(argsPtr, data);
1379 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1382 this->WriteTo(dest, std::string(textbuffer));
1385 void userrec::WriteTo(userrec *dest, const std::string &data)
1387 dest->WriteFrom(this, data);
1391 void userrec::WriteCommon(const char* text, ...)
1393 char textbuffer[MAXBUF];
1396 if (this->registered != REG_ALL)
1399 va_start(argsPtr, text);
1400 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1403 this->WriteCommon(std::string(textbuffer));
1406 void userrec::WriteCommon(const std::string &text)
1408 bool sent_to_at_least_one = false;
1410 if (this->registered != REG_ALL)
1415 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1420 CUList *ulist= n->channel->GetUsers();
1422 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1424 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1426 already_sent[i->second->fd] = uniq_id;
1427 i->second->WriteFrom(this, std::string(text));
1428 sent_to_at_least_one = true;
1435 * if the user was not in any channels, no users will receive the text. Make sure the user
1436 * receives their OWN message for WriteCommon
1438 if (!sent_to_at_least_one)
1440 this->WriteFrom(this,std::string(text));
1445 /* write a formatted string to all users who share at least one common
1446 * channel, NOT including the source user e.g. for use in QUIT
1449 void userrec::WriteCommonExcept(const char* text, ...)
1451 char textbuffer[MAXBUF];
1454 va_start(argsPtr, text);
1455 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1458 this->WriteCommonExcept(std::string(textbuffer));
1461 void userrec::WriteCommonExcept(const std::string &text)
1463 bool quit_munge = true;
1464 char oper_quit[MAXBUF];
1465 char textbuffer[MAXBUF];
1467 strlcpy(textbuffer, text.c_str(), MAXBUF);
1469 if (this->registered != REG_ALL)
1474 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1475 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1478 if (Config->HideSplits)
1480 char* check = textbuffer + 6;
1482 if (!strncasecmp(textbuffer, "QUIT :",6))
1484 std::stringstream split(check);
1485 std::string server_one;
1486 std::string server_two;
1488 split >> server_one;
1489 split >> server_two;
1491 if ((FindServerName(server_one)) && (FindServerName(server_two)))
1493 strlcpy(oper_quit,textbuffer,MAXQUIT);
1494 strlcpy(check,"*.net *.split",MAXQUIT);
1500 if ((Config->HideBans) && (!quit_munge))
1502 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1503 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1505 char* check = textbuffer + 13;
1506 strlcpy(oper_quit,textbuffer,MAXQUIT);
1507 *check = 0; // We don't need to strlcpy, we just chop it from the :
1512 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1517 CUList *ulist= n->channel->GetUsers();
1519 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1521 if (this != i->second)
1523 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1525 already_sent[i->second->fd] = uniq_id;
1527 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1529 i->second->WriteFrom(this, std::string(textbuffer));
1538 void userrec::WriteWallOps(const std::string &text)
1540 /* Does nothing if theyre not opered */
1541 if ((!*this->oper) && (IS_LOCAL(this)))
1544 std::string wallop = "WALLOPS :";
1545 wallop.append(text);
1547 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1550 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1551 this->WriteTo(t,wallop);
1555 void userrec::WriteWallOps(const char* text, ...)
1557 char textbuffer[MAXBUF];
1560 va_start(argsPtr, text);
1561 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1564 this->WriteWallOps(std::string(textbuffer));
1567 /* return 0 or 1 depending if users u and u2 share one or more common channels
1568 * (used by QUIT, NICK etc which arent channel specific notices)
1570 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1571 * the first users channels then the second users channels within the outer loop,
1572 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1573 * all possible iterations). However this new function instead checks against the
1574 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1575 * and saves us time as we already know what pointer value we are after.
1576 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1577 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1579 bool userrec::SharesChannelWith(userrec *other)
1581 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1585 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1587 /* Fetch the channel from the user */
1588 ucrec* user_channel = *i;
1590 if (user_channel->channel)
1592 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1593 * by replacing it with a map::find which *should* be more efficient
1595 if (user_channel->channel->HasUser(other))
1602 int userrec::CountChannels()
1605 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1611 bool userrec::ChangeName(const char* gecos)
1616 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1619 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1621 strlcpy(this->fullname,gecos,MAXGECOS+1);
1625 bool userrec::ChangeDisplayedHost(const char* host)
1630 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1633 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1635 strlcpy(this->dhost,host,63);
1638 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);