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 std::vector<Module*> modules;
37 extern std::vector<ircd_module*> factory;
38 extern std::vector<InspSocket*> module_sockets;
41 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
42 extern user_hash clientlist;
43 extern Server* MyServer;
44 extern std::vector<userrec*> local_users;
46 irc::whowas::whowas_users whowas;
47 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
48 std::vector<userrec*> all_opers;
50 typedef std::map<irc::string,char*> opertype_t;
51 typedef opertype_t operclass_t;
54 operclass_t operclass;
56 /* XXX: Used for speeding up WriteCommon operations */
57 unsigned long uniq_id = 0;
59 bool InitTypes(const char* tag)
61 for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
71 bool InitClasses(const char* tag)
73 for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
83 bool DoType(const char* tag, char** entries, void** values, int* types)
85 char* TypeName = (char*)values[0];
86 char* Classes = (char*)values[1];
88 opertypes[TypeName] = strdup(Classes);
89 log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
93 bool DoClass(const char* tag, char** entries, void** values, int* types)
95 char* ClassName = (char*)values[0];
96 char* CommandList = (char*)values[1];
98 operclass[ClassName] = strdup(CommandList);
99 log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
103 bool DoneClassesAndTypes(const char* tag)
108 bool userrec::ProcessNoticeMasks(const char *sm)
124 if ((*c >= 'A') && (*c <= 'z'))
125 this->SetNoticeMask(*c, adding);
135 void userrec::StartDNSLookup()
137 log(DEBUG,"Commencing reverse lookup");
140 res_reverse = new UserResolver(this, this->GetIPString(), false);
141 MyServer->AddResolver(res_reverse);
143 catch (ModuleException& e)
145 log(DEBUG,"Error in resolver: %s",e.GetReason());
149 UserResolver::UserResolver(userrec* user, std::string to_resolve, bool forward) : Resolver(to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
152 this->bound_fd = user->fd;
155 void UserResolver::OnLookupComplete(const std::string &result)
157 if ((!this->fwd) && (fd_ref_table[this->bound_fd] == this->bound_user))
159 log(DEBUG,"Commencing forward lookup");
160 this->bound_user->stored_host = result;
163 bound_user->res_forward = new UserResolver(this->bound_user, result, true);
164 MyServer->AddResolver(bound_user->res_forward);
166 catch (ModuleException& e)
168 log(DEBUG,"Error in resolver: %s",e.GetReason());
171 else if ((this->fwd) && (fd_ref_table[this->bound_fd] == this->bound_user))
173 /* Both lookups completed */
174 if (this->bound_user->GetIPString() == result)
176 std::string hostname = this->bound_user->stored_host;
177 if (hostname.length() < 65)
179 /* Hostnames starting with : are not a good thing (tm) */
180 if (*(hostname.c_str()) == ':')
181 hostname = "0" + hostname;
183 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
184 this->bound_user->dns_done = true;
185 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
186 strlcpy(this->bound_user->host, hostname.c_str(),64);
190 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());
195 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());
200 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
202 if (fd_ref_table[this->bound_fd] == this->bound_user)
204 /* Error message here */
205 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
206 this->bound_user->dns_done = true;
211 bool userrec::IsNoticeMaskSet(unsigned char sm)
213 return (snomasks[sm-65]);
216 void userrec::SetNoticeMask(unsigned char sm, bool value)
218 snomasks[sm-65] = value;
221 const char* userrec::FormatNoticeMasks()
223 static char data[MAXBUF];
226 for (int n = 0; n < 64; n++)
229 data[offset++] = n+65;
238 bool userrec::IsModeSet(unsigned char m)
240 return (modes[m-65]);
243 void userrec::SetMode(unsigned char m, bool value)
248 const char* userrec::FormatModes()
250 static char data[MAXBUF];
252 for (int n = 0; n < 64; n++)
255 data[offset++] = n+65;
263 // the PROPER way to do it, AVOID bzero at *ALL* costs
264 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
265 server = (char*)FindServerNamePtr(ServerInstance->Config->ServerName);
267 lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
268 timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
269 haspassed = dns_done = false;
273 res_forward = res_reverse = NULL;
277 chans.resize(MAXCHANS);
278 memset(modes,0,sizeof(modes));
280 for (unsigned int n = 0; n < MAXCHANS; n++)
282 ucrec* x = new ucrec();
291 for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
293 ucrec* x = (ucrec*)*n;
299 if (this->GetProtocolFamily() == AF_INET)
301 delete (sockaddr_in*)ip;
303 #ifdef SUPPORT_IP6LINKS
306 delete (sockaddr_in6*)ip;
312 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
313 void userrec::MakeHost(char* nhost)
315 /* This is much faster than snprintf */
317 for(char* n = ident; *n; n++)
320 for(char* n = host; *n; n++)
325 void userrec::CloseSocket()
327 shutdown(this->fd,2);
331 char* userrec::GetFullHost()
333 static char result[MAXBUF];
335 for(char* n = nick; *n; n++)
338 for(char* n = ident; *n; n++)
341 for(char* n = dhost; *n; n++)
347 char* userrec::MakeWildHost()
349 static char nresult[MAXBUF];
351 *t++ = '*'; *t++ = '!';
352 *t++ = '*'; *t++ = '@';
353 for(char* n = dhost; *n; n++)
359 int userrec::ReadData(void* buffer, size_t size)
363 return read(this->fd, buffer, size);
370 char* userrec::GetFullRealHost()
372 static char fresult[MAXBUF];
374 for(char* n = nick; *n; n++)
377 for(char* n = ident; *n; n++)
380 for(char* n = host; *n; n++)
386 bool userrec::IsInvited(irc::string &channel)
388 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
390 irc::string compare = i->channel;
392 if (compare == channel)
400 InvitedList* userrec::GetInviteList()
405 void userrec::InviteTo(irc::string &channel)
409 invites.push_back(i);
412 void userrec::RemoveInvite(irc::string &channel)
414 log(DEBUG,"Removing invites");
418 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
420 irc::string compare = i->channel;
422 if (compare == channel)
431 bool userrec::HasPermission(const std::string &command)
438 * users on remote servers can completely bypass all permissions based checks.
439 * This prevents desyncs when one server has different type/class tags to another.
440 * That having been said, this does open things up to the possibility of source changes
441 * allowing remote kills, etc - but if they have access to the src, they most likely have
442 * access to the conf - so it's an end to a means either way.
447 // are they even an oper at all?
450 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
451 if (iter_opertype != opertypes.end())
453 char* Classes = strdup(iter_opertype->second);
454 char* myclass = strtok_r(Classes," ",&savept);
457 operclass_t::iterator iter_operclass = operclass.find(myclass);
458 if (iter_operclass != operclass.end())
460 char* CommandList = strdup(iter_operclass->second);
461 mycmd = strtok_r(CommandList," ",&savept2);
464 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
470 mycmd = strtok_r(NULL," ",&savept2);
474 myclass = strtok_r(NULL," ",&savept);
483 bool userrec::AddBuffer(const std::string &a)
487 /* NB: std::string is arsey about \r and \n and tries to translate them
488 * somehow, so we CANNOT use std::string::find() here :(
490 for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
499 if (recvq.length() > (unsigned)this->recvqmax)
501 this->SetWriteError("RecvQ exceeded");
502 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
509 bool userrec::BufferIsReady()
511 return (recvq.find('\n') != std::string::npos);
514 void userrec::ClearBuffer()
519 std::string userrec::GetBuffer()
524 /* Strip any leading \r or \n off the string.
525 * Usually there are only one or two of these,
526 * so its is computationally cheap to do.
528 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
529 recvq.erase(recvq.begin());
531 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
533 /* Find the first complete line, return it as the
534 * result, and leave the recvq as whats left
538 std::string ret = std::string(recvq.begin(), x);
539 recvq.erase(recvq.begin(), x + 1);
546 void userrec::AddWriteBuf(const std::string &data)
548 if (*this->GetWriteError())
551 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
554 * Fix by brain - Set the error text BEFORE calling writeopers, because
555 * if we dont it'll recursively call here over and over again trying
556 * to repeatedly add the text to the sendq!
558 this->SetWriteError("SendQ exceeded");
559 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
563 if (data.length() > 512)
565 std::string newdata(data);
567 newdata.append("\r\n");
568 sendq.append(newdata);
576 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
577 void userrec::FlushWriteBuf()
579 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
581 const char* tb = this->sendq.c_str();
582 int n_sent = write(this->fd,tb,this->sendq.length());
586 this->SetWriteError(strerror(errno));
593 // update the user's stats counters
594 this->bytes_out += n_sent;
600 void userrec::SetWriteError(const std::string &error)
602 log(DEBUG,"SetWriteError: %s",error.c_str());
603 // don't try to set the error twice, its already set take the first string.
604 if (!this->WriteError.length())
606 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
607 this->WriteError = error;
611 const char* userrec::GetWriteError()
613 return this->WriteError.c_str();
616 void userrec::Oper(const std::string &opertype)
618 this->modes[UM_OPERATOR] = 1;
619 this->WriteServ("MODE %s :+o", this->nick);
620 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
621 log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
622 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
623 all_opers.push_back(this);
624 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
627 void userrec::UnOper()
632 this->modes[UM_OPERATOR] = 0;
633 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
637 log(DEBUG,"Oper removed from optimization list");
645 void userrec::QuitUser(userrec *user,const std::string &quitreason)
647 user_hash::iterator iter = clientlist.find(user->nick);
650 * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
651 * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
653 * I can't imagine this blowing up, so I'm commenting it out. We still check
654 * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
656 * if (iter == clientlist.end())
659 std::string reason = quitreason;
661 if (reason.length() > MAXQUIT - 1)
662 reason.resize(MAXQUIT - 1);
665 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
667 if (user->registered == REG_ALL)
669 purge_empty_chans(user);
670 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
671 user->WriteCommonExcept("QUIT :%s",reason.c_str());
675 user->FlushWriteBuf();
677 FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
681 if (ServerInstance->Config->GetIOHook(user->GetPort()))
685 ServerInstance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
687 catch (ModuleException& modexcept)
689 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
693 ServerInstance->SE->DelFd(user->fd);
698 * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
699 * if they were an oper with +s.
702 * In the current implementation, we only show local quits, as we only show local connects. With
703 * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
705 if (user->registered == REG_ALL)
708 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
712 if (iter != clientlist.end())
714 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
717 fd_ref_table[user->fd] = NULL;
718 if (find(local_users.begin(),local_users.end(),user) != local_users.end())
719 local_users.erase(find(local_users.begin(),local_users.end(),user));
721 clientlist.erase(iter);
731 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
733 this->host = strdup(user->host);
734 this->dhost = strdup(user->dhost);
735 this->ident = strdup(user->ident);
736 this->server = user->server;
737 this->gecos = strdup(user->fullname);
740 WhoWasGroup::~WhoWasGroup()
752 /* every hour, run this function which removes all entries over 3 days */
753 void MaintainWhoWas(time_t TIME)
755 for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
757 whowas_set* n = (whowas_set*)iter->second;
760 while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
762 WhoWasGroup *a = *(n->begin());
764 n->erase(n->begin());
772 /* adds or updates an entry in the whowas list */
773 void userrec::AddToWhoWas()
775 irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
777 if (iter == whowas.end())
779 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
780 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
782 whowas[this->nick] = n;
786 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
788 if (group->size() > 10)
790 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
795 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
800 /* add a client connection to the sockets list */
801 void userrec::AddClient(int socket, int port, bool iscached, insp_inaddr ip)
803 std::string tempnick = ConvToStr(socket) + "-unknown";
804 user_hash::iterator iter = clientlist.find(tempnick);
805 const char *ipaddr = insp_ntoa(ip);
811 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
812 * using one as a registered connection. As they are per fd, we can also safely assume
813 * that we wont have collisions. Therefore, if the nick exists in the list, its only
814 * used by a dead socket, erase the iterator so that the new client may reclaim it.
815 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
816 * issue in earlier alphas/betas
818 if (iter != clientlist.end())
820 userrec* goner = iter->second;
822 clientlist.erase(iter);
825 log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
827 _new = new userrec();
828 clientlist[tempnick] = _new;
830 strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
832 _new->server = FindServerNamePtr(ServerInstance->Config->ServerName);
833 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
834 strcpy(_new->ident, "unknown");
836 _new->registered = REG_NONE;
837 _new->signon = TIME + ServerInstance->Config->dns_timeout;
840 log(DEBUG,"Setting socket addresses");
841 _new->SetSockAddr(AF_FAMILY, ipaddr, port);
842 log(DEBUG,"Socket addresses set.");
844 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
845 for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
846 _new->dhost[j] = _new->host[j] = *temp;
847 _new->dhost[j] = _new->host[j] = 0;
849 // set the registration timeout for this user
850 unsigned long class_regtimeout = 90;
852 long class_threshold = 5;
853 long class_sqmax = 262144; // 256kb
854 long class_rqmax = 4096; // 4k
856 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
858 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
860 class_regtimeout = (unsigned long)i->registration_timeout;
861 class_flood = i->flood;
862 _new->pingmax = i->pingtime;
863 class_threshold = i->threshold;
864 class_sqmax = i->sendqmax;
865 class_rqmax = i->recvqmax;
870 _new->nping = TIME + _new->pingmax + ServerInstance->Config->dns_timeout;
871 _new->timeout = TIME+class_regtimeout;
872 _new->flood = class_flood;
873 _new->threshold = class_threshold;
874 _new->sendqmax = class_sqmax;
875 _new->recvqmax = class_rqmax;
877 fd_ref_table[socket] = _new;
878 local_users.push_back(_new);
880 if (local_users.size() > ServerInstance->Config->SoftLimit)
882 userrec::QuitUser(_new,"No more connections allowed");
886 if (local_users.size() >= MAXCLIENTS)
888 userrec::QuitUser(_new,"No more connections allowed");
894 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
895 * its a pretty big but for the moment valid assumption:
896 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
897 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
898 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
899 * which for the time being is a physical impossibility (even the largest networks dont have more
900 * than about 10,000 users on ONE server!)
902 if ((unsigned)socket >= MAX_DESCRIPTORS)
904 userrec::QuitUser(_new,"Server is full");
907 char* e = matches_exception(ipaddr);
910 char* r = matches_zline(ipaddr);
914 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
915 userrec::QuitUser(_new,reason);
922 if (!ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
924 userrec::QuitUser(_new, "Internal error handling connection");
929 _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
932 long userrec::GlobalCloneCount()
937 for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
939 /* We have to match ip's as strings - we don't know what protocol
940 * a remote user may be using
942 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
948 long userrec::LocalCloneCount()
951 for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
955 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
956 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
957 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
958 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
961 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
962 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
963 if (s1->s_addr == s2->s_addr)
970 void userrec::FullConnect(CullList* Goners)
972 ServerInstance->stats->statsConnects++;
973 this->idle_lastmsg = TIME;
975 ConnectClass a = GetClass(this);
977 if (a.type == CC_DENY)
979 Goners->AddItem(this,"Unauthorised connection");
983 if ((*(a.pass.c_str())) && (!this->haspassed))
985 Goners->AddItem(this,"Invalid password");
989 if (this->LocalCloneCount() > a.maxlocal)
991 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
992 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
995 else if (this->GlobalCloneCount() > a.maxglobal)
997 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
998 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1002 char match_against[MAXBUF];
1003 snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
1004 char* e = matches_exception(match_against);
1008 char* r = matches_gline(match_against);
1012 char reason[MAXBUF];
1013 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1014 Goners->AddItem(this, reason);
1018 r = matches_kline(match_against);
1022 char reason[MAXBUF];
1023 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1024 Goners->AddItem(this, reason);
1030 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1031 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1032 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1033 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1034 this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->ModeGrok->UserModeList().c_str(), ServerInstance->ModeGrok->ChannelModeList().c_str(), ServerInstance->ModeGrok->ParaModeList().c_str());
1036 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1037 // so i'd better split it :)
1038 std::stringstream out(ServerInstance->Config->data005);
1039 std::string token = "";
1040 std::string line5 = "";
1041 int token_counter = 0;
1046 line5 = line5 + token + " ";
1049 if ((token_counter >= 13) || (out.eof() == true))
1051 this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1060 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1061 * changes dont go out onto the network and produce 'fake direction'.
1063 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1064 FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(this));
1065 this->registered = REG_ALL;
1066 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1069 /** userrec::UpdateNick()
1070 * re-allocates a nick in the user_hash after they change nicknames,
1071 * returns a pointer to the new user as it may have moved
1073 userrec* userrec::UpdateNickHash(const char* New)
1075 //user_hash::iterator newnick;
1076 user_hash::iterator oldnick = clientlist.find(this->nick);
1078 if (!strcasecmp(this->nick,New))
1079 return oldnick->second;
1081 if (oldnick == clientlist.end())
1082 return NULL; /* doesnt exist */
1084 userrec* olduser = oldnick->second;
1085 clientlist[New] = olduser;
1086 clientlist.erase(oldnick);
1087 return clientlist[New];
1090 bool userrec::ForceNickChange(const char* newnick)
1097 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1101 ServerInstance->stats->statsCollisions++;
1105 if (matches_qline(newnick))
1107 ServerInstance->stats->statsCollisions++;
1113 strlcpy(this->nick, newnick, NICKMAX - 1);
1115 if (this->registered == REG_ALL)
1117 const char* pars[1];
1119 std::string cmd = "NICK";
1120 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1125 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1127 switch (protocol_family)
1129 #ifdef SUPPORT_IP6LINKS
1132 log(DEBUG,"Set inet6 protocol address");
1133 sockaddr_in6* sin = new sockaddr_in6;
1134 sin->sin6_family = AF_INET6;
1135 sin->sin6_port = port;
1136 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1137 this->ip = (sockaddr*)sin;
1143 log(DEBUG,"Set inet4 protocol address");
1144 sockaddr_in* sin = new sockaddr_in;
1145 sin->sin_family = AF_INET;
1146 sin->sin_port = port;
1147 inet_pton(AF_INET, ip, &sin->sin_addr);
1148 this->ip = (sockaddr*)sin;
1152 log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1157 int userrec::GetPort()
1159 if (this->ip == NULL)
1162 switch (this->GetProtocolFamily())
1164 #ifdef SUPPORT_IP6LINKS
1167 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1168 return sin->sin6_port;
1174 sockaddr_in* sin = (sockaddr_in*)this->ip;
1175 return sin->sin_port;
1179 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1185 int userrec::GetProtocolFamily()
1187 if (this->ip == NULL)
1190 sockaddr_in* sin = (sockaddr_in*)this->ip;
1191 return sin->sin_family;
1194 const char* userrec::GetIPString()
1196 static char buf[1024];
1197 static char temp[1024];
1199 if (this->ip == NULL)
1202 switch (this->GetProtocolFamily())
1204 #ifdef SUPPORT_IP6LINKS
1207 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1208 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1209 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1212 strlcpy(&temp[1], buf, sizeof(temp));
1222 sockaddr_in* sin = (sockaddr_in*)this->ip;
1223 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1228 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1234 const char* userrec::GetIPString(char* buf)
1236 static char temp[1024];
1238 if (this->ip == NULL)
1244 switch (this->GetProtocolFamily())
1246 #ifdef SUPPORT_IP6LINKS
1249 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1250 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1251 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1254 strlcpy(&temp[1], buf, sizeof(temp));
1256 strlcpy(buf, temp, sizeof(temp));
1264 sockaddr_in* sin = (sockaddr_in*)this->ip;
1265 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1271 log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1278 void userrec::Write(const std::string &text)
1280 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1283 std::string crlf = text;
1284 crlf.append("\r\n");
1286 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1290 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, crlf.data(), crlf.length());
1292 catch (ModuleException& modexcept)
1294 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1299 this->AddWriteBuf(crlf);
1301 ServerInstance->stats->statsSent += crlf.length();
1306 void userrec::Write(const char *text, ...)
1309 char textbuffer[MAXBUF];
1311 va_start(argsPtr, text);
1312 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1315 this->Write(std::string(textbuffer));
1318 void userrec::WriteServ(const std::string& text)
1320 char textbuffer[MAXBUF];
1322 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1323 this->Write(std::string(textbuffer));
1327 * Same as Write(), except `text' is prefixed with `:server.name '.
1329 void userrec::WriteServ(const char* text, ...)
1332 char textbuffer[MAXBUF];
1334 va_start(argsPtr, text);
1335 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1338 this->WriteServ(std::string(textbuffer));
1342 void userrec::WriteFrom(userrec *user, const std::string &text)
1346 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1348 this->Write(std::string(tb));
1352 /* write text from an originating user to originating user */
1354 void userrec::WriteFrom(userrec *user, const char* text, ...)
1357 char textbuffer[MAXBUF];
1359 va_start(argsPtr, text);
1360 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1363 this->WriteFrom(user, std::string(textbuffer));
1367 /* write text to an destination user from a source user (e.g. user privmsg) */
1369 void userrec::WriteTo(userrec *dest, const char *data, ...)
1371 char textbuffer[MAXBUF];
1374 va_start(argsPtr, data);
1375 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1378 this->WriteTo(dest, std::string(textbuffer));
1381 void userrec::WriteTo(userrec *dest, const std::string &data)
1383 dest->WriteFrom(this, data);
1387 void userrec::WriteCommon(const char* text, ...)
1389 char textbuffer[MAXBUF];
1392 if (this->registered != REG_ALL)
1395 va_start(argsPtr, text);
1396 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1399 this->WriteCommon(std::string(textbuffer));
1402 void userrec::WriteCommon(const std::string &text)
1404 bool sent_to_at_least_one = false;
1406 if (this->registered != REG_ALL)
1411 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1416 CUList *ulist= n->channel->GetUsers();
1418 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1420 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1422 already_sent[i->second->fd] = uniq_id;
1423 i->second->WriteFrom(this, std::string(text));
1424 sent_to_at_least_one = true;
1431 * if the user was not in any channels, no users will receive the text. Make sure the user
1432 * receives their OWN message for WriteCommon
1434 if (!sent_to_at_least_one)
1436 this->WriteFrom(this,std::string(text));
1441 /* write a formatted string to all users who share at least one common
1442 * channel, NOT including the source user e.g. for use in QUIT
1445 void userrec::WriteCommonExcept(const char* text, ...)
1447 char textbuffer[MAXBUF];
1450 va_start(argsPtr, text);
1451 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1454 this->WriteCommonExcept(std::string(textbuffer));
1457 void userrec::WriteCommonExcept(const std::string &text)
1459 bool quit_munge = true;
1460 char oper_quit[MAXBUF];
1461 char textbuffer[MAXBUF];
1463 strlcpy(textbuffer, text.c_str(), MAXBUF);
1465 if (this->registered != REG_ALL)
1470 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1471 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1474 if (ServerInstance->Config->HideSplits)
1476 char* check = textbuffer + 6;
1478 if (!strncasecmp(textbuffer, "QUIT :",6))
1480 std::stringstream split(check);
1481 std::string server_one;
1482 std::string server_two;
1484 split >> server_one;
1485 split >> server_two;
1487 if ((FindServerName(server_one)) && (FindServerName(server_two)))
1489 strlcpy(oper_quit,textbuffer,MAXQUIT);
1490 strlcpy(check,"*.net *.split",MAXQUIT);
1496 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1498 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1499 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1501 char* check = textbuffer + 13;
1502 strlcpy(oper_quit,textbuffer,MAXQUIT);
1503 *check = 0; // We don't need to strlcpy, we just chop it from the :
1508 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1513 CUList *ulist= n->channel->GetUsers();
1515 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1517 if (this != i->second)
1519 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1521 already_sent[i->second->fd] = uniq_id;
1523 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1525 i->second->WriteFrom(this, std::string(textbuffer));
1534 void userrec::WriteWallOps(const std::string &text)
1536 /* Does nothing if theyre not opered */
1537 if ((!*this->oper) && (IS_LOCAL(this)))
1540 std::string wallop = "WALLOPS :";
1541 wallop.append(text);
1543 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1546 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1547 this->WriteTo(t,wallop);
1551 void userrec::WriteWallOps(const char* text, ...)
1553 char textbuffer[MAXBUF];
1556 va_start(argsPtr, text);
1557 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1560 this->WriteWallOps(std::string(textbuffer));
1563 /* return 0 or 1 depending if users u and u2 share one or more common channels
1564 * (used by QUIT, NICK etc which arent channel specific notices)
1566 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1567 * the first users channels then the second users channels within the outer loop,
1568 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1569 * all possible iterations). However this new function instead checks against the
1570 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1571 * and saves us time as we already know what pointer value we are after.
1572 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1573 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1575 bool userrec::SharesChannelWith(userrec *other)
1577 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1581 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1583 /* Fetch the channel from the user */
1584 ucrec* user_channel = *i;
1586 if (user_channel->channel)
1588 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1589 * by replacing it with a map::find which *should* be more efficient
1591 if (user_channel->channel->HasUser(other))
1598 int userrec::CountChannels()
1601 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1607 bool userrec::ChangeName(const char* gecos)
1612 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1615 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1617 strlcpy(this->fullname,gecos,MAXGECOS+1);
1621 bool userrec::ChangeDisplayedHost(const char* host)
1626 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1629 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1631 strlcpy(this->dhost,host,63);
1634 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);