1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #include "configreader.h"
19 #include "socketengine.h"
22 #include "cull_list.h"
23 #include "commands/cmd_whowas.h"
25 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
27 /* XXX: Used for speeding up WriteCommon operations */
28 unsigned long uniq_id = 0;
30 bool InitTypes(ServerConfig* conf, const char* tag)
32 if (conf->opertypes.size())
34 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
41 conf->opertypes.clear();
45 bool InitClasses(ServerConfig* conf, const char* tag)
47 if (conf->operclass.size())
49 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
56 conf->operclass.clear();
60 bool DoType(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
62 const char* TypeName = values[0].GetString();
63 const char* Classes = values[1].GetString();
65 conf->opertypes[TypeName] = strdup(Classes);
69 bool DoClass(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
71 const char* ClassName = values[0].GetString();
72 const char* CommandList = values[1].GetString();
74 conf->operclass[ClassName] = strdup(CommandList);
78 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
83 std::string userrec::ProcessNoticeMasks(const char *sm)
85 bool adding = true, oldadding = false;
100 for (unsigned char d = 'A'; d <= 'z'; d++)
102 if (ServerInstance->SNO->IsEnabled(d))
104 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
106 if ((oldadding != adding) || (!output.length()))
107 output += (adding ? '+' : '-');
109 this->SetNoticeMask(d, adding);
118 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
120 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
122 if ((oldadding != adding) || (!output.length()))
123 output += (adding ? '+' : '-');
125 this->SetNoticeMask(*c, adding);
140 void userrec::StartDNSLookup()
145 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), DNS_QUERY_REVERSE, cached);
146 this->ServerInstance->AddResolver(res_reverse, cached);
148 catch (CoreException& e)
150 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
154 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, QueryType qt, bool &cache) :
155 Resolver(Instance, to_resolve, qt, cache), bound_user(user)
157 this->fwd = (qt == DNS_QUERY_A || qt == DNS_QUERY_AAAA);
158 this->bound_fd = user->GetFd();
161 void UserResolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
163 if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
165 this->bound_user->stored_host = result;
168 /* Check we didnt time out */
169 if (this->bound_user->registered != REG_ALL)
173 const char *ip = this->bound_user->GetIPString();
174 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, (strstr(ip,"0::ffff:") == ip ? DNS_QUERY_A : DNS_QUERY_AAAA), cached);
176 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, DNS_QUERY_A, cached);
178 this->ServerInstance->AddResolver(bound_user->res_forward, cached);
181 catch (CoreException& e)
183 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
186 else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
188 /* Both lookups completed */
189 std::string result2 = "0::ffff:";
190 result2.append(result);
191 if (this->bound_user->GetIPString() == result || this->bound_user->GetIPString() == result2)
193 std::string hostname = this->bound_user->stored_host;
194 if (hostname.length() < 65)
196 /* Check we didnt time out */
197 if (this->bound_user->registered != REG_ALL)
199 /* Hostnames starting with : are not a good thing (tm) */
200 if (*(hostname.c_str()) == ':')
201 hostname = "0" + hostname;
203 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)%s", hostname.c_str(), (cached ? " -- cached" : ""));
204 this->bound_user->dns_done = true;
205 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
206 strlcpy(this->bound_user->host, hostname.c_str(),64);
207 /* Invalidate cache */
208 this->bound_user->InvalidateCache();
213 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());
218 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());
223 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
225 if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
227 /* Error message here */
228 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname: %s; using your IP address (%s) instead.", errormessage.c_str(), this->bound_user->GetIPString());
229 this->bound_user->dns_done = true;
234 bool userrec::IsNoticeMaskSet(unsigned char sm)
236 return (snomasks[sm-65]);
239 void userrec::SetNoticeMask(unsigned char sm, bool value)
241 snomasks[sm-65] = value;
244 const char* userrec::FormatNoticeMasks()
246 static char data[MAXBUF];
249 for (int n = 0; n < 64; n++)
252 data[offset++] = n+65;
261 bool userrec::IsModeSet(unsigned char m)
263 return (modes[m-65]);
266 void userrec::SetMode(unsigned char m, bool value)
271 const char* userrec::FormatModes()
273 static char data[MAXBUF];
275 for (int n = 0; n < 64; n++)
278 data[offset++] = n+65;
284 void userrec::DecrementModes()
286 for (int n = 0; n < 64; n++)
290 ModeHandler* mh = ServerInstance->Modes->FindMode(n+65, MODETYPE_USER);
297 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
299 // the PROPER way to do it, AVOID bzero at *ALL* costs
300 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
301 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
302 reset_due = ServerInstance->Time();
303 age = ServerInstance->Time(true);
304 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
305 ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
306 exempt = haspassed = dns_done = false;
311 res_forward = res_reverse = NULL;
315 memset(modes,0,sizeof(modes));
316 memset(snomasks,0,sizeof(snomasks));
317 /* Invalidate cache */
318 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
323 this->InvalidateCache();
324 this->DecrementModes();
327 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
328 if (x != ServerInstance->local_clones.end())
333 ServerInstance->local_clones.erase(x);
337 clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
338 if (y != ServerInstance->global_clones.end())
343 ServerInstance->global_clones.erase(y);
347 if (this->GetProtocolFamily() == AF_INET)
349 delete (sockaddr_in*)ip;
351 #ifdef SUPPORT_IP6LINKS
354 delete (sockaddr_in6*)ip;
360 char* userrec::MakeHost()
362 if (this->cached_makehost)
363 return this->cached_makehost;
366 /* This is much faster than snprintf */
368 for(char* n = ident; *n; n++)
371 for(char* n = host; *n; n++)
375 this->cached_makehost = strdup(nhost);
377 return this->cached_makehost;
380 char* userrec::MakeHostIP()
382 if (this->cached_hostip)
383 return this->cached_hostip;
386 /* This is much faster than snprintf */
388 for(char* n = ident; *n; n++)
391 for(const char* n = this->GetIPString(); *n; n++)
395 this->cached_hostip = strdup(ihost);
397 return this->cached_hostip;
400 void userrec::CloseSocket()
402 shutdown(this->fd,2);
406 char* userrec::GetFullHost()
408 if (this->cached_fullhost)
409 return this->cached_fullhost;
413 for(char* n = nick; *n; n++)
416 for(char* n = ident; *n; n++)
419 for(char* n = dhost; *n; n++)
423 this->cached_fullhost = strdup(result);
425 return this->cached_fullhost;
428 char* userrec::MakeWildHost()
430 static char nresult[MAXBUF];
432 *t++ = '*'; *t++ = '!';
433 *t++ = '*'; *t++ = '@';
434 for(char* n = dhost; *n; n++)
440 int userrec::ReadData(void* buffer, size_t size)
444 return read(this->fd, buffer, size);
451 char* userrec::GetFullRealHost()
453 if (this->cached_fullrealhost)
454 return this->cached_fullrealhost;
456 char fresult[MAXBUF];
458 for(char* n = nick; *n; n++)
461 for(char* n = ident; *n; n++)
464 for(char* n = host; *n; n++)
468 this->cached_fullrealhost = strdup(fresult);
470 return this->cached_fullrealhost;
473 bool userrec::IsInvited(const irc::string &channel)
475 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
485 InvitedList* userrec::GetInviteList()
490 void userrec::InviteTo(const irc::string &channel)
492 invites.push_back(channel);
495 void userrec::RemoveInvite(const irc::string &channel)
497 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
507 bool userrec::HasPermission(const std::string &command)
514 * users on remote servers can completely bypass all permissions based checks.
515 * This prevents desyncs when one server has different type/class tags to another.
516 * That having been said, this does open things up to the possibility of source changes
517 * allowing remote kills, etc - but if they have access to the src, they most likely have
518 * access to the conf - so it's an end to a means either way.
523 // are they even an oper at all?
526 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
527 if (iter_opertype != ServerInstance->Config->opertypes.end())
529 char* Classes = strdup(iter_opertype->second);
530 char* myclass = strtok_r(Classes," ",&savept);
533 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
534 if (iter_operclass != ServerInstance->Config->operclass.end())
536 char* CommandList = strdup(iter_operclass->second);
537 mycmd = strtok_r(CommandList," ",&savept2);
540 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
546 mycmd = strtok_r(NULL," ",&savept2);
550 myclass = strtok_r(NULL," ",&savept);
558 /** NOTE: We cannot pass a const reference to this method.
559 * The string is changed by the workings of the method,
560 * so that if we pass const ref, we end up copying it to
561 * something we can change anyway. Makes sense to just let
562 * the compiler do that copy for us.
564 bool userrec::AddBuffer(std::string a)
568 std::string::size_type i = a.rfind('\r');
570 while (i != std::string::npos)
579 if (recvq.length() > (unsigned)this->recvqmax)
581 this->SetWriteError("RecvQ exceeded");
582 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
591 ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
596 bool userrec::BufferIsReady()
598 return (recvq.find('\n') != std::string::npos);
601 void userrec::ClearBuffer()
606 std::string userrec::GetBuffer()
613 /* Strip any leading \r or \n off the string.
614 * Usually there are only one or two of these,
615 * so its is computationally cheap to do.
617 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
618 recvq.erase(recvq.begin());
620 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
622 /* Find the first complete line, return it as the
623 * result, and leave the recvq as whats left
627 std::string ret = std::string(recvq.begin(), x);
628 recvq.erase(recvq.begin(), x + 1);
637 ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
642 void userrec::AddWriteBuf(const std::string &data)
644 if (*this->GetWriteError())
647 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
650 * Fix by brain - Set the error text BEFORE calling writeopers, because
651 * if we dont it'll recursively call here over and over again trying
652 * to repeatedly add the text to the sendq!
654 this->SetWriteError("SendQ exceeded");
655 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
661 if (data.length() > 512)
662 sendq.append(data.substr(0,510)).append("\r\n");
668 this->SetWriteError("SendQ exceeded");
669 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
673 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
674 void userrec::FlushWriteBuf()
678 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
682 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
684 int old_sendq_length = sendq.length();
685 int n_sent = write(this->fd, this->sendq.data(), this->sendq.length());
690 /* The socket buffer is full. This isnt fatal,
693 this->ServerInstance->SE->WantWrite(this);
697 /* Fatal error, set write error and bail
699 this->SetWriteError(strerror(errno));
705 /* advance the queue */
707 this->sendq = this->sendq.substr(n_sent);
708 /* update the user's stats counters */
709 this->bytes_out += n_sent;
711 if (n_sent != old_sendq_length)
712 this->ServerInstance->SE->WantWrite(this);
719 ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
723 void userrec::SetWriteError(const std::string &error)
727 // don't try to set the error twice, its already set take the first string.
728 if (this->WriteError.empty())
729 this->WriteError = error;
734 ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
738 const char* userrec::GetWriteError()
740 return this->WriteError.c_str();
743 void userrec::Oper(const std::string &opertype)
747 this->modes[UM_OPERATOR] = 1;
748 this->WriteServ("MODE %s :+o", this->nick);
749 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
750 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
751 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
752 ServerInstance->all_opers.push_back(this);
753 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
758 ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
762 void userrec::UnOper()
769 this->modes[UM_OPERATOR] = 0;
770 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
774 ServerInstance->all_opers.erase(a);
783 ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
787 void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
789 user_hash::iterator iter = Instance->clientlist->find(user->nick);
790 std::string reason = quitreason;
792 if (reason.length() > MAXQUIT - 1)
793 reason.resize(MAXQUIT - 1);
795 if (user->registered != REG_ALL)
796 if (Instance->unregistered_count)
797 Instance->unregistered_count--;
801 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
802 if ((!user->sendq.empty()) && (!(*user->GetWriteError())))
803 user->FlushWriteBuf();
806 if (user->registered == REG_ALL)
808 user->PurgeEmptyChannels();
809 user->WriteCommonExcept("QUIT :%s",reason.c_str());
810 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
813 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
817 if (Instance->Config->GetIOHook(user->GetPort()))
821 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
823 catch (CoreException& modexcept)
825 Instance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
829 Instance->SE->DelFd(user);
834 * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
835 * if they were an oper with +sn +qQ.
837 if (user->registered == REG_ALL)
840 Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
842 Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
846 if (iter != Instance->clientlist->end())
850 std::vector<userrec*>::iterator x = find(Instance->local_users.begin(),Instance->local_users.end(),user);
851 if (x != Instance->local_users.end())
852 Instance->local_users.erase(x);
854 Instance->clientlist->erase(iter);
860 /* adds or updates an entry in the whowas list */
861 void userrec::AddToWhoWas()
863 command_t* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
866 std::deque<classbase*> params;
867 params.push_back(this);
868 whowas_command->HandleInternal(WHOWAS_ADD, params);
872 /* add a client connection to the sockets list */
873 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
875 std::string tempnick = ConvToStr(socket) + "-unknown";
876 user_hash::iterator iter = Instance->clientlist->find(tempnick);
877 const char *ipaddr = insp_ntoa(ip);
881 Instance->unregistered_count++;
885 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
886 * using one as a registered connection. As they are per fd, we can also safely assume
887 * that we wont have collisions. Therefore, if the nick exists in the list, its only
888 * used by a dead socket, erase the iterator so that the new client may reclaim it.
889 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
890 * issue in earlier alphas/betas
892 if (iter != Instance->clientlist->end())
894 userrec* goner = iter->second;
896 Instance->clientlist->erase(iter);
899 New = new userrec(Instance);
900 (*(Instance->clientlist))[tempnick] = New;
902 strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
904 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
905 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
906 strcpy(New->ident, "unknown");
908 New->registered = REG_NONE;
909 New->signon = Instance->Time() + Instance->Config->dns_timeout;
912 New->SetSockAddr(AF_FAMILY, ipaddr, port);
914 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
915 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
916 New->dhost[j] = New->host[j] = *temp;
917 New->dhost[j] = New->host[j] = 0;
919 Instance->AddLocalClone(New);
920 Instance->AddGlobalClone(New);
922 ConnectClass* i = New->GetClass();
924 if ((!i) || (i->GetType() == CC_DENY))
926 userrec::QuitUser(Instance, New,"Unauthorised connection");
930 New->pingmax = i->GetPingTime();
931 New->nping = Instance->Time() + i->GetPingTime() + Instance->Config->dns_timeout;
932 New->timeout = Instance->Time() + i->GetRegTimeout();
933 New->flood = i->GetFlood();
934 New->threshold = i->GetThreshold();
935 New->sendqmax = i->GetSendqMax();
936 New->recvqmax = i->GetRecvqMax();
938 Instance->local_users.push_back(New);
940 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
942 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
943 userrec::QuitUser(Instance, New,"No more connections allowed");
949 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
950 * its a pretty big but for the moment valid assumption:
951 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
952 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
953 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
954 * which for the time being is a physical impossibility (even the largest networks dont have more
955 * than about 10,000 users on ONE server!)
957 if ((unsigned int)socket >= MAX_DESCRIPTORS)
959 userrec::QuitUser(Instance, New, "Server is full");
963 New->exempt = (Instance->XLines->matches_exception(New) != NULL);
966 ZLine* r = Instance->XLines->matches_zline(ipaddr);
970 snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
971 userrec::QuitUser(Instance, New, reason);
978 if (!Instance->SE->AddFd(New))
980 userrec::QuitUser(Instance, New, "Internal error handling connection");
985 /* NOTE: even if dns lookups are *off*, we still need to display this.
986 * BOPM and other stuff requires it.
988 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
991 unsigned long userrec::GlobalCloneCount()
993 clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
994 if (x != ServerInstance->global_clones.end())
1000 unsigned long userrec::LocalCloneCount()
1002 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
1003 if (x != ServerInstance->local_clones.end())
1009 void userrec::FullConnect(CullList* Goners)
1011 ServerInstance->stats->statsConnects++;
1012 this->idle_lastmsg = ServerInstance->Time();
1014 ConnectClass* a = this->GetClass();
1016 if ((!a) || (a->GetType() == CC_DENY))
1018 Goners->AddItem(this,"Unauthorised connection");
1022 if ((!a->GetPass().empty()) && (!this->haspassed))
1024 Goners->AddItem(this,"Invalid password");
1028 if (this->LocalCloneCount() > a->GetMaxLocal())
1030 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1031 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
1034 else if (this->GlobalCloneCount() > a->GetMaxGlobal())
1036 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1037 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a->GetMaxGlobal(), this->GetIPString());
1043 GLine* r = ServerInstance->XLines->matches_gline(this);
1047 char reason[MAXBUF];
1048 snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
1049 Goners->AddItem(this, reason);
1053 KLine* n = ServerInstance->XLines->matches_kline(this);
1057 char reason[MAXBUF];
1058 snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
1059 Goners->AddItem(this, reason);
1065 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1066 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1067 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1068 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1069 this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
1071 ServerInstance->Config->Send005(this);
1075 /* Now registered */
1076 if (ServerInstance->unregistered_count)
1077 ServerInstance->unregistered_count--;
1080 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1081 * changes dont go out onto the network and produce 'fake direction'.
1083 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1085 this->registered = REG_ALL;
1087 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1089 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1092 /** userrec::UpdateNick()
1093 * re-allocates a nick in the user_hash after they change nicknames,
1094 * returns a pointer to the new user as it may have moved
1096 userrec* userrec::UpdateNickHash(const char* New)
1100 //user_hash::iterator newnick;
1101 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1103 if (!strcasecmp(this->nick,New))
1104 return oldnick->second;
1106 if (oldnick == ServerInstance->clientlist->end())
1107 return NULL; /* doesnt exist */
1109 userrec* olduser = oldnick->second;
1110 (*(ServerInstance->clientlist))[New] = olduser;
1111 ServerInstance->clientlist->erase(oldnick);
1117 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1122 void userrec::InvalidateCache()
1124 /* Invalidate cache */
1125 if (cached_fullhost)
1126 free(cached_fullhost);
1128 free(cached_hostip);
1129 if (cached_makehost)
1130 free(cached_makehost);
1131 if (cached_fullrealhost)
1132 free(cached_fullrealhost);
1133 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1136 bool userrec::ForceNickChange(const char* newnick)
1142 this->InvalidateCache();
1144 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1148 ServerInstance->stats->statsCollisions++;
1152 if (ServerInstance->XLines->matches_qline(newnick))
1154 ServerInstance->stats->statsCollisions++;
1158 if (this->registered == REG_ALL)
1160 const char* pars[1];
1162 std::string cmd = "NICK";
1163 return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1170 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1175 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1177 switch (protocol_family)
1179 #ifdef SUPPORT_IP6LINKS
1182 sockaddr_in6* sin = new sockaddr_in6;
1183 sin->sin6_family = AF_INET6;
1184 sin->sin6_port = port;
1185 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1186 this->ip = (sockaddr*)sin;
1192 sockaddr_in* sin = new sockaddr_in;
1193 sin->sin_family = AF_INET;
1194 sin->sin_port = port;
1195 inet_pton(AF_INET, ip, &sin->sin_addr);
1196 this->ip = (sockaddr*)sin;
1200 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1205 int userrec::GetPort()
1207 if (this->ip == NULL)
1210 switch (this->GetProtocolFamily())
1212 #ifdef SUPPORT_IP6LINKS
1215 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1216 return sin->sin6_port;
1222 sockaddr_in* sin = (sockaddr_in*)this->ip;
1223 return sin->sin_port;
1232 int userrec::GetProtocolFamily()
1234 if (this->ip == NULL)
1237 sockaddr_in* sin = (sockaddr_in*)this->ip;
1238 return sin->sin_family;
1241 const char* userrec::GetIPString()
1243 static char buf[1024];
1245 if (this->ip == NULL)
1248 switch (this->GetProtocolFamily())
1250 #ifdef SUPPORT_IP6LINKS
1253 static char temp[1024];
1255 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1256 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1257 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1260 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1270 sockaddr_in* sin = (sockaddr_in*)this->ip;
1271 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1281 const char* userrec::GetIPString(char* buf)
1283 if (this->ip == NULL)
1289 switch (this->GetProtocolFamily())
1291 #ifdef SUPPORT_IP6LINKS
1294 static char temp[1024];
1296 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1297 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1298 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1301 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1303 strlcpy(buf, temp, sizeof(temp));
1311 sockaddr_in* sin = (sockaddr_in*)this->ip;
1312 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1323 /** NOTE: We cannot pass a const reference to this method.
1324 * The string is changed by the workings of the method,
1325 * so that if we pass const ref, we end up copying it to
1326 * something we can change anyway. Makes sense to just let
1327 * the compiler do that copy for us.
1329 void userrec::Write(std::string text)
1331 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1336 /* ServerInstance->Log(DEBUG,"<- %s", text.c_str());
1337 * WARNING: The above debug line is VERY loud, do NOT
1338 * enable it till we have a good way of filtering it
1339 * out of the logs (e.g. 1.2 would be good).
1341 text.append("\r\n");
1345 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1349 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1353 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1355 catch (CoreException& modexcept)
1357 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1362 this->AddWriteBuf(text);
1364 ServerInstance->stats->statsSent += text.length();
1365 this->ServerInstance->SE->WantWrite(this);
1370 void userrec::Write(const char *text, ...)
1373 char textbuffer[MAXBUF];
1375 va_start(argsPtr, text);
1376 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1379 this->Write(std::string(textbuffer));
1382 void userrec::WriteServ(const std::string& text)
1384 char textbuffer[MAXBUF];
1386 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1387 this->Write(std::string(textbuffer));
1391 * Same as Write(), except `text' is prefixed with `:server.name '.
1393 void userrec::WriteServ(const char* text, ...)
1396 char textbuffer[MAXBUF];
1398 va_start(argsPtr, text);
1399 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1402 this->WriteServ(std::string(textbuffer));
1406 void userrec::WriteFrom(userrec *user, const std::string &text)
1410 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1412 this->Write(std::string(tb));
1416 /* write text from an originating user to originating user */
1418 void userrec::WriteFrom(userrec *user, const char* text, ...)
1421 char textbuffer[MAXBUF];
1423 va_start(argsPtr, text);
1424 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1427 this->WriteFrom(user, std::string(textbuffer));
1431 /* write text to an destination user from a source user (e.g. user privmsg) */
1433 void userrec::WriteTo(userrec *dest, const char *data, ...)
1435 char textbuffer[MAXBUF];
1438 va_start(argsPtr, data);
1439 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1442 this->WriteTo(dest, std::string(textbuffer));
1445 void userrec::WriteTo(userrec *dest, const std::string &data)
1447 dest->WriteFrom(this, data);
1451 void userrec::WriteCommon(const char* text, ...)
1453 char textbuffer[MAXBUF];
1456 if (this->registered != REG_ALL)
1459 va_start(argsPtr, text);
1460 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1463 this->WriteCommon(std::string(textbuffer));
1466 void userrec::WriteCommon(const std::string &text)
1470 bool sent_to_at_least_one = false;
1473 if (this->registered != REG_ALL)
1478 /* We dont want to be doing this n times, just once */
1479 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1480 std::string out = tb;
1482 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1484 CUList* ulist = v->first->GetUsers();
1485 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1487 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1489 already_sent[i->second->fd] = uniq_id;
1490 i->second->Write(out);
1491 sent_to_at_least_one = true;
1497 * if the user was not in any channels, no users will receive the text. Make sure the user
1498 * receives their OWN message for WriteCommon
1500 if (!sent_to_at_least_one)
1502 this->Write(std::string(tb));
1508 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1513 /* write a formatted string to all users who share at least one common
1514 * channel, NOT including the source user e.g. for use in QUIT
1517 void userrec::WriteCommonExcept(const char* text, ...)
1519 char textbuffer[MAXBUF];
1522 va_start(argsPtr, text);
1523 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1526 this->WriteCommonExcept(std::string(textbuffer));
1529 void userrec::WriteCommonExcept(const std::string &text)
1531 bool quit_munge = false;
1532 char oper_quit[MAXBUF];
1533 char textbuffer[MAXBUF];
1539 strlcpy(textbuffer, text.c_str(), MAXBUF);
1541 if (this->registered != REG_ALL)
1546 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),textbuffer);
1548 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1549 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1552 if (ServerInstance->Config->HideSplits)
1554 char* check = textbuffer + 6;
1556 if (!strncasecmp(textbuffer, "QUIT :",6))
1558 std::stringstream split(check);
1559 std::string server_one;
1560 std::string server_two;
1562 split >> server_one;
1563 split >> server_two;
1565 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1567 strlcpy(oper_quit,textbuffer,MAXQUIT);
1568 strlcpy(check,"*.net *.split",MAXQUIT);
1570 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1576 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1578 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1579 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1581 char* check = textbuffer + 13;
1582 strlcpy(oper_quit,textbuffer,MAXQUIT);
1583 *check = 0; // We don't need to strlcpy, we just chop it from the :
1585 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1592 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1594 CUList *ulist = v->first->GetUsers();
1595 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1597 if (this != i->second)
1599 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1601 already_sent[i->second->fd] = uniq_id;
1603 i->second->Write(*i->second->oper ? out2 : out1);
1605 i->second->Write(out1);
1613 void userrec::WriteWallOps(const std::string &text)
1615 /* Does nothing if theyre not opered */
1616 if ((!*this->oper) && (IS_LOCAL(this)))
1619 std::string wallop = "WALLOPS :";
1623 wallop.append(text);
1627 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1631 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1634 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1635 this->WriteTo(t,wallop);
1639 void userrec::WriteWallOps(const char* text, ...)
1641 char textbuffer[MAXBUF];
1644 va_start(argsPtr, text);
1645 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1648 this->WriteWallOps(std::string(textbuffer));
1651 /* return 0 or 1 depending if users u and u2 share one or more common channels
1652 * (used by QUIT, NICK etc which arent channel specific notices)
1654 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1655 * the first users channels then the second users channels within the outer loop,
1656 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1657 * all possible iterations). However this new function instead checks against the
1658 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1659 * and saves us time as we already know what pointer value we are after.
1660 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1661 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1663 bool userrec::SharesChannelWith(userrec *other)
1665 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1669 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1671 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1672 * by replacing it with a map::find which *should* be more efficient
1674 if (i->first->HasUser(other))
1680 bool userrec::ChangeName(const char* gecos)
1682 if (!strcmp(gecos, this->fullname))
1688 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1691 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1693 strlcpy(this->fullname,gecos,MAXGECOS+1);
1698 bool userrec::ChangeDisplayedHost(const char* host)
1700 if (!strcmp(host, this->dhost))
1706 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1709 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1711 if (this->ServerInstance->Config->CycleHosts)
1712 this->WriteCommonExcept("QUIT :Changing hosts");
1714 /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
1715 strlcpy(this->dhost,host,64);
1717 this->InvalidateCache();
1719 if (this->ServerInstance->Config->CycleHosts)
1721 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1723 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1724 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1726 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1731 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1736 bool userrec::ChangeIdent(const char* newident)
1738 if (!strcmp(newident, this->ident))
1741 if (this->ServerInstance->Config->CycleHosts)
1742 this->WriteCommonExcept("%s","QUIT :Changing ident");
1744 strlcpy(this->ident, newident, IDENTMAX+2);
1746 this->InvalidateCache();
1748 if (this->ServerInstance->Config->CycleHosts)
1750 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1752 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1753 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1755 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1762 void userrec::NoticeAll(char* text, ...)
1764 char textbuffer[MAXBUF];
1765 char formatbuffer[MAXBUF];
1768 va_start(argsPtr, text);
1769 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1772 snprintf(formatbuffer,MAXBUF,":%s NOTICE $* :%s", this->GetFullHost(), textbuffer);
1773 std::string fmt = formatbuffer;
1775 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1782 std::string userrec::ChannelList(userrec* source)
1787 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1789 /* If the target is the same as the sender, let them see all their channels.
1790 * If the channel is NOT private/secret OR the user shares a common channel
1791 * If the user is an oper, and the <options:operspywhois> option is set.
1793 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
1795 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1802 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1807 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1810 std::ostringstream prefix;
1811 std::string::size_type start, pos, length;
1815 prefix << this->nick << " " << dest->nick << " :";
1816 line = prefix.str();
1817 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1819 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1821 length = (pos == std::string::npos) ? cl.length() : pos;
1823 if (line.length() + namelen + length - start > 510)
1825 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1826 line = prefix.str();
1829 if(pos == std::string::npos)
1831 line.append(cl.substr(start, length - start));
1836 line.append(cl.substr(start, length - start + 1));
1842 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1848 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1853 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1854 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1855 * then their ip will be taken as 'priority' anyway, so for example,
1856 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1858 ConnectClass* userrec::GetClass()
1860 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1862 if ((match(this->GetIPString(),i->GetHost().c_str(),true)) || (match(this->host,i->GetHost().c_str())))
1868 void userrec::PurgeEmptyChannels()
1870 std::vector<chanrec*> to_delete;
1872 // firstly decrement the count on each channel
1873 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1875 f->first->RemoveAllPrefixes(this);
1876 if (f->first->DelUser(this) == 0)
1878 /* No users left in here, mark it for deletion */
1881 to_delete.push_back(f->first);
1885 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1890 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1892 chanrec* thischan = *n;
1893 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1894 if (i2 != ServerInstance->chanlist->end())
1896 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1898 ServerInstance->chanlist->erase(i2);
1899 this->chans.erase(*n);
1906 void userrec::ShowMOTD()
1908 if (!ServerInstance->Config->MOTD.size())
1910 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1913 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1915 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1916 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1918 this->WriteServ("376 %s :End of message of the day.", this->nick);
1921 void userrec::ShowRULES()
1923 if (!ServerInstance->Config->RULES.size())
1925 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1928 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1930 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1931 this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
1933 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1936 void userrec::HandleEvent(EventType et, int errornum)
1938 /* WARNING: May delete this user! */
1939 int thisfd = this->GetFd();
1946 ServerInstance->ProcessUser(this);
1949 this->FlushWriteBuf();
1952 /** This should be safe, but dont DARE do anything after it -- Brain */
1953 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1959 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
1962 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1963 if ((ServerInstance->SE->GetRef(thisfd) == this))
1965 if (!WriteError.empty())
1967 userrec::QuitUser(ServerInstance, this, GetWriteError());