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 "commands/cmd_whowas.h"
24 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
26 /* XXX: Used for speeding up WriteCommon operations */
27 unsigned long uniq_id = 0;
29 bool InitTypes(ServerConfig* conf, const char* tag)
31 if (conf->opertypes.size())
33 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
40 conf->opertypes.clear();
44 bool InitClasses(ServerConfig* conf, const char* tag)
46 if (conf->operclass.size())
48 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
55 conf->operclass.clear();
59 bool DoType(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
61 const char* TypeName = values[0].GetString();
62 const char* Classes = values[1].GetString();
64 conf->opertypes[TypeName] = strdup(Classes);
68 bool DoClass(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
70 const char* ClassName = values[0].GetString();
71 const char* CommandList = values[1].GetString();
73 conf->operclass[ClassName] = strdup(CommandList);
77 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
82 std::string userrec::ProcessNoticeMasks(const char *sm)
84 bool adding = true, oldadding = false;
99 for (unsigned char d = 'A'; d <= 'z'; d++)
101 if (ServerInstance->SNO->IsEnabled(d))
103 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
105 if ((oldadding != adding) || (!output.length()))
106 output += (adding ? '+' : '-');
108 this->SetNoticeMask(d, adding);
117 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
119 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
121 if ((oldadding != adding) || (!output.length()))
122 output += (adding ? '+' : '-');
124 this->SetNoticeMask(*c, adding);
139 void userrec::StartDNSLookup()
144 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), DNS_QUERY_REVERSE, cached);
145 this->ServerInstance->AddResolver(res_reverse, cached);
147 catch (CoreException& e)
149 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
153 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, QueryType qt, bool &cache) :
154 Resolver(Instance, to_resolve, qt, cache), bound_user(user)
156 this->fwd = (qt == DNS_QUERY_A || qt == DNS_QUERY_AAAA);
157 this->bound_fd = user->GetFd();
160 void UserResolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
162 if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
164 this->bound_user->stored_host = result;
167 /* Check we didnt time out */
168 if (this->bound_user->registered != REG_ALL)
172 const char *ip = this->bound_user->GetIPString();
173 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, (strstr(ip,"0::ffff:") == ip ? DNS_QUERY_A : DNS_QUERY_AAAA), cached);
175 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, DNS_QUERY_A, cached);
177 this->ServerInstance->AddResolver(bound_user->res_forward, cached);
180 catch (CoreException& e)
182 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
185 else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
187 /* Both lookups completed */
188 std::string result2 = "0::ffff:";
189 result2.append(result);
190 if (this->bound_user->GetIPString() == result || this->bound_user->GetIPString() == result2)
192 std::string hostname = this->bound_user->stored_host;
193 if (hostname.length() < 65)
195 /* Check we didnt time out */
196 if (this->bound_user->registered != REG_ALL)
198 /* Hostnames starting with : are not a good thing (tm) */
199 if (*(hostname.c_str()) == ':')
200 hostname = "0" + hostname;
202 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)%s", hostname.c_str(), (cached ? " -- cached" : ""));
203 this->bound_user->dns_done = true;
204 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
205 strlcpy(this->bound_user->host, hostname.c_str(),64);
206 /* Invalidate cache */
207 this->bound_user->InvalidateCache();
212 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());
217 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());
222 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
224 if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
226 /* Error message here */
227 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());
228 this->bound_user->dns_done = true;
233 bool userrec::IsNoticeMaskSet(unsigned char sm)
235 return (snomasks[sm-65]);
238 void userrec::SetNoticeMask(unsigned char sm, bool value)
240 snomasks[sm-65] = value;
243 const char* userrec::FormatNoticeMasks()
245 static char data[MAXBUF];
248 for (int n = 0; n < 64; n++)
251 data[offset++] = n+65;
260 bool userrec::IsModeSet(unsigned char m)
262 return (modes[m-65]);
265 void userrec::SetMode(unsigned char m, bool value)
270 const char* userrec::FormatModes()
272 static char data[MAXBUF];
274 for (int n = 0; n < 64; n++)
277 data[offset++] = n+65;
283 void userrec::DecrementModes()
285 for (int n = 0; n < 64; n++)
289 ModeHandler* mh = ServerInstance->Modes->FindMode(n+65, MODETYPE_USER);
296 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
298 // the PROPER way to do it, AVOID bzero at *ALL* costs
299 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
300 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
301 reset_due = ServerInstance->Time();
302 age = ServerInstance->Time(true);
303 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
304 ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
305 exempt = haspassed = dns_done = false;
310 res_forward = res_reverse = NULL;
314 memset(modes,0,sizeof(modes));
315 memset(snomasks,0,sizeof(snomasks));
316 /* Invalidate cache */
317 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
322 this->InvalidateCache();
323 this->DecrementModes();
326 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
327 if (x != ServerInstance->local_clones.end())
332 ServerInstance->local_clones.erase(x);
336 clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
337 if (y != ServerInstance->global_clones.end())
342 ServerInstance->global_clones.erase(y);
346 if (this->GetProtocolFamily() == AF_INET)
348 delete (sockaddr_in*)ip;
350 #ifdef SUPPORT_IP6LINKS
353 delete (sockaddr_in6*)ip;
359 char* userrec::MakeHost()
361 if (this->cached_makehost)
362 return this->cached_makehost;
365 /* This is much faster than snprintf */
367 for(char* n = ident; *n; n++)
370 for(char* n = host; *n; n++)
374 this->cached_makehost = strdup(nhost);
376 return this->cached_makehost;
379 char* userrec::MakeHostIP()
381 if (this->cached_hostip)
382 return this->cached_hostip;
385 /* This is much faster than snprintf */
387 for(char* n = ident; *n; n++)
390 for(const char* n = this->GetIPString(); *n; n++)
394 this->cached_hostip = strdup(ihost);
396 return this->cached_hostip;
399 void userrec::CloseSocket()
401 shutdown(this->fd,2);
405 char* userrec::GetFullHost()
407 if (this->cached_fullhost)
408 return this->cached_fullhost;
412 for(char* n = nick; *n; n++)
415 for(char* n = ident; *n; n++)
418 for(char* n = dhost; *n; n++)
422 this->cached_fullhost = strdup(result);
424 return this->cached_fullhost;
427 char* userrec::MakeWildHost()
429 static char nresult[MAXBUF];
431 *t++ = '*'; *t++ = '!';
432 *t++ = '*'; *t++ = '@';
433 for(char* n = dhost; *n; n++)
439 int userrec::ReadData(void* buffer, size_t size)
443 return read(this->fd, buffer, size);
450 char* userrec::GetFullRealHost()
452 if (this->cached_fullrealhost)
453 return this->cached_fullrealhost;
455 char fresult[MAXBUF];
457 for(char* n = nick; *n; n++)
460 for(char* n = ident; *n; n++)
463 for(char* n = host; *n; n++)
467 this->cached_fullrealhost = strdup(fresult);
469 return this->cached_fullrealhost;
472 bool userrec::IsInvited(const irc::string &channel)
474 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
484 InvitedList* userrec::GetInviteList()
489 void userrec::InviteTo(const irc::string &channel)
491 invites.push_back(channel);
494 void userrec::RemoveInvite(const irc::string &channel)
496 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
506 bool userrec::HasPermission(const std::string &command)
513 * users on remote servers can completely bypass all permissions based checks.
514 * This prevents desyncs when one server has different type/class tags to another.
515 * That having been said, this does open things up to the possibility of source changes
516 * allowing remote kills, etc - but if they have access to the src, they most likely have
517 * access to the conf - so it's an end to a means either way.
522 // are they even an oper at all?
525 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
526 if (iter_opertype != ServerInstance->Config->opertypes.end())
528 char* Classes = strdup(iter_opertype->second);
529 char* myclass = strtok_r(Classes," ",&savept);
532 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
533 if (iter_operclass != ServerInstance->Config->operclass.end())
535 char* CommandList = strdup(iter_operclass->second);
536 mycmd = strtok_r(CommandList," ",&savept2);
539 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
545 mycmd = strtok_r(NULL," ",&savept2);
549 myclass = strtok_r(NULL," ",&savept);
557 /** NOTE: We cannot pass a const reference to this method.
558 * The string is changed by the workings of the method,
559 * so that if we pass const ref, we end up copying it to
560 * something we can change anyway. Makes sense to just let
561 * the compiler do that copy for us.
563 bool userrec::AddBuffer(std::string a)
567 std::string::size_type i = a.rfind('\r');
569 while (i != std::string::npos)
578 if (recvq.length() > (unsigned)this->recvqmax)
580 this->SetWriteError("RecvQ exceeded");
581 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
590 ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
595 bool userrec::BufferIsReady()
597 return (recvq.find('\n') != std::string::npos);
600 void userrec::ClearBuffer()
605 std::string userrec::GetBuffer()
612 /* Strip any leading \r or \n off the string.
613 * Usually there are only one or two of these,
614 * so its is computationally cheap to do.
616 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
617 recvq.erase(recvq.begin());
619 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
621 /* Find the first complete line, return it as the
622 * result, and leave the recvq as whats left
626 std::string ret = std::string(recvq.begin(), x);
627 recvq.erase(recvq.begin(), x + 1);
636 ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
641 void userrec::AddWriteBuf(const std::string &data)
643 if (*this->GetWriteError())
646 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
649 * Fix by brain - Set the error text BEFORE calling writeopers, because
650 * if we dont it'll recursively call here over and over again trying
651 * to repeatedly add the text to the sendq!
653 this->SetWriteError("SendQ exceeded");
654 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
660 if (data.length() > 512)
661 sendq.append(data.substr(0,510)).append("\r\n");
667 this->SetWriteError("SendQ exceeded");
668 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
672 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
673 void userrec::FlushWriteBuf()
677 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
681 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
683 int old_sendq_length = sendq.length();
684 int n_sent = write(this->fd, this->sendq.data(), this->sendq.length());
689 /* The socket buffer is full. This isnt fatal,
692 this->ServerInstance->SE->WantWrite(this);
696 /* Fatal error, set write error and bail
698 this->SetWriteError(strerror(errno));
704 /* advance the queue */
706 this->sendq = this->sendq.substr(n_sent);
707 /* update the user's stats counters */
708 this->bytes_out += n_sent;
710 if (n_sent != old_sendq_length)
711 this->ServerInstance->SE->WantWrite(this);
718 ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
722 void userrec::SetWriteError(const std::string &error)
726 // don't try to set the error twice, its already set take the first string.
727 if (this->WriteError.empty())
728 this->WriteError = error;
733 ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
737 const char* userrec::GetWriteError()
739 return this->WriteError.c_str();
742 void userrec::Oper(const std::string &opertype)
746 this->modes[UM_OPERATOR] = 1;
747 this->WriteServ("MODE %s :+o", this->nick);
748 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
749 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
750 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
751 ServerInstance->all_opers.push_back(this);
752 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
757 ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
761 void userrec::UnOper()
768 this->modes[UM_OPERATOR] = 0;
769 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
773 ServerInstance->all_opers.erase(a);
782 ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
786 void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
788 Instance->GlobalCulls.AddItem(user, quitreason.c_str());
792 /* adds or updates an entry in the whowas list */
793 void userrec::AddToWhoWas()
795 command_t* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
798 std::deque<classbase*> params;
799 params.push_back(this);
800 whowas_command->HandleInternal(WHOWAS_ADD, params);
804 /* add a client connection to the sockets list */
805 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, int socketfamily, sockaddr* ip)
807 std::string tempnick = ConvToStr(socket) + "-unknown";
808 user_hash::iterator iter = Instance->clientlist->find(tempnick);
811 if (socketfamily = AF_INET6)
812 inet_ntop(AF_INET6, &((const sockaddr_in6*)ip)->sin6_addr, ipaddr, sizeof(ipaddr));
814 inet_ntop(AF_INET, &((const sockaddr_in*)ip)->sin_addr, ipaddr, sizeof(ipaddr));
816 inet_ntop(AF_INET, &((const sockaddr_in*)ip)->sin_addr, ipaddr, sizeof(ipaddr));
821 Instance->unregistered_count++;
825 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
826 * using one as a registered connection. As they are per fd, we can also safely assume
827 * that we wont have collisions. Therefore, if the nick exists in the list, its only
828 * used by a dead socket, erase the iterator so that the new client may reclaim it.
829 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
830 * issue in earlier alphas/betas
832 if (iter != Instance->clientlist->end())
834 userrec* goner = iter->second;
836 Instance->clientlist->erase(iter);
839 New = new userrec(Instance);
840 (*(Instance->clientlist))[tempnick] = New;
842 strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
844 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
845 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
846 strcpy(New->ident, "unknown");
848 New->registered = REG_NONE;
849 New->signon = Instance->Time() + Instance->Config->dns_timeout;
852 New->SetSockAddr(AF_FAMILY, ipaddr, port);
854 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
855 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
856 New->dhost[j] = New->host[j] = *temp;
857 New->dhost[j] = New->host[j] = 0;
859 Instance->AddLocalClone(New);
860 Instance->AddGlobalClone(New);
862 ConnectClass* i = New->GetClass();
864 if ((!i) || (i->GetType() == CC_DENY))
866 userrec::QuitUser(Instance, New,"Unauthorised connection");
870 New->pingmax = i->GetPingTime();
871 New->nping = Instance->Time() + i->GetPingTime() + Instance->Config->dns_timeout;
872 New->timeout = Instance->Time() + i->GetRegTimeout();
873 New->flood = i->GetFlood();
874 New->threshold = i->GetThreshold();
875 New->sendqmax = i->GetSendqMax();
876 New->recvqmax = i->GetRecvqMax();
878 Instance->local_users.push_back(New);
880 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
882 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
883 userrec::QuitUser(Instance, New,"No more connections allowed");
889 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
890 * its a pretty big but for the moment valid assumption:
891 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
892 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
893 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
894 * which for the time being is a physical impossibility (even the largest networks dont have more
895 * than about 10,000 users on ONE server!)
897 if ((unsigned int)socket >= MAX_DESCRIPTORS)
899 userrec::QuitUser(Instance, New, "Server is full");
903 New->exempt = (Instance->XLines->matches_exception(New) != NULL);
906 ZLine* r = Instance->XLines->matches_zline(ipaddr);
910 snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
911 userrec::QuitUser(Instance, New, reason);
918 if (!Instance->SE->AddFd(New))
920 userrec::QuitUser(Instance, New, "Internal error handling connection");
925 /* NOTE: even if dns lookups are *off*, we still need to display this.
926 * BOPM and other stuff requires it.
928 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
931 unsigned long userrec::GlobalCloneCount()
933 clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
934 if (x != ServerInstance->global_clones.end())
940 unsigned long userrec::LocalCloneCount()
942 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
943 if (x != ServerInstance->local_clones.end())
949 void userrec::FullConnect()
951 ServerInstance->stats->statsConnects++;
952 this->idle_lastmsg = ServerInstance->Time();
954 ConnectClass* a = this->GetClass();
956 if ((!a) || (a->GetType() == CC_DENY))
958 ServerInstance->GlobalCulls.AddItem(this,"Unauthorised connection");
962 if ((!a->GetPass().empty()) && (!this->haspassed))
964 ServerInstance->GlobalCulls.AddItem(this,"Invalid password");
968 if (this->LocalCloneCount() > a->GetMaxLocal())
970 ServerInstance->GlobalCulls.AddItem(this, "No more connections allowed from your host via this connect class (local)");
971 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
974 else if (this->GlobalCloneCount() > a->GetMaxGlobal())
976 ServerInstance->GlobalCulls.AddItem(this, "No more connections allowed from your host via this connect class (global)");
977 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a->GetMaxGlobal(), this->GetIPString());
983 GLine* r = ServerInstance->XLines->matches_gline(this);
988 snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
989 ServerInstance->GlobalCulls.AddItem(this, reason);
993 KLine* n = ServerInstance->XLines->matches_kline(this);
998 snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
999 ServerInstance->GlobalCulls.AddItem(this, reason);
1005 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1006 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1007 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1008 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1009 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());
1011 ServerInstance->Config->Send005(this);
1015 /* Now registered */
1016 if (ServerInstance->unregistered_count)
1017 ServerInstance->unregistered_count--;
1020 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1021 * changes dont go out onto the network and produce 'fake direction'.
1023 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1025 this->registered = REG_ALL;
1027 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1029 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1032 /** userrec::UpdateNick()
1033 * re-allocates a nick in the user_hash after they change nicknames,
1034 * returns a pointer to the new user as it may have moved
1036 userrec* userrec::UpdateNickHash(const char* New)
1040 //user_hash::iterator newnick;
1041 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1043 if (!strcasecmp(this->nick,New))
1044 return oldnick->second;
1046 if (oldnick == ServerInstance->clientlist->end())
1047 return NULL; /* doesnt exist */
1049 userrec* olduser = oldnick->second;
1050 (*(ServerInstance->clientlist))[New] = olduser;
1051 ServerInstance->clientlist->erase(oldnick);
1057 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1062 void userrec::InvalidateCache()
1064 /* Invalidate cache */
1065 if (cached_fullhost)
1066 free(cached_fullhost);
1068 free(cached_hostip);
1069 if (cached_makehost)
1070 free(cached_makehost);
1071 if (cached_fullrealhost)
1072 free(cached_fullrealhost);
1073 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1076 bool userrec::ForceNickChange(const char* newnick)
1082 this->InvalidateCache();
1084 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1088 ServerInstance->stats->statsCollisions++;
1092 if (ServerInstance->XLines->matches_qline(newnick))
1094 ServerInstance->stats->statsCollisions++;
1098 if (this->registered == REG_ALL)
1100 const char* pars[1];
1102 std::string cmd = "NICK";
1103 return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1110 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1115 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1117 switch (protocol_family)
1119 #ifdef SUPPORT_IP6LINKS
1122 sockaddr_in6* sin = new sockaddr_in6;
1123 sin->sin6_family = AF_INET6;
1124 sin->sin6_port = port;
1125 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1126 this->ip = (sockaddr*)sin;
1132 sockaddr_in* sin = new sockaddr_in;
1133 sin->sin_family = AF_INET;
1134 sin->sin_port = port;
1135 inet_pton(AF_INET, ip, &sin->sin_addr);
1136 this->ip = (sockaddr*)sin;
1140 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1145 int userrec::GetPort()
1147 if (this->ip == NULL)
1150 switch (this->GetProtocolFamily())
1152 #ifdef SUPPORT_IP6LINKS
1155 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1156 return sin->sin6_port;
1162 sockaddr_in* sin = (sockaddr_in*)this->ip;
1163 return sin->sin_port;
1172 int userrec::GetProtocolFamily()
1174 if (this->ip == NULL)
1177 sockaddr_in* sin = (sockaddr_in*)this->ip;
1178 return sin->sin_family;
1181 const char* userrec::GetIPString()
1183 static char buf[1024];
1185 if (this->ip == NULL)
1188 switch (this->GetProtocolFamily())
1190 #ifdef SUPPORT_IP6LINKS
1193 static char temp[1024];
1195 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1196 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1197 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1200 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1210 sockaddr_in* sin = (sockaddr_in*)this->ip;
1211 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1221 const char* userrec::GetIPString(char* buf)
1223 if (this->ip == NULL)
1229 switch (this->GetProtocolFamily())
1231 #ifdef SUPPORT_IP6LINKS
1234 static char temp[1024];
1236 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1237 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1238 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1241 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1243 strlcpy(buf, temp, sizeof(temp));
1251 sockaddr_in* sin = (sockaddr_in*)this->ip;
1252 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1263 /** NOTE: We cannot pass a const reference to this method.
1264 * The string is changed by the workings of the method,
1265 * so that if we pass const ref, we end up copying it to
1266 * something we can change anyway. Makes sense to just let
1267 * the compiler do that copy for us.
1269 void userrec::Write(std::string text)
1271 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1276 /* ServerInstance->Log(DEBUG,"<- %s", text.c_str());
1277 * WARNING: The above debug line is VERY loud, do NOT
1278 * enable it till we have a good way of filtering it
1279 * out of the logs (e.g. 1.2 would be good).
1281 text.append("\r\n");
1285 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1289 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1293 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1295 catch (CoreException& modexcept)
1297 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1302 this->AddWriteBuf(text);
1304 ServerInstance->stats->statsSent += text.length();
1305 this->ServerInstance->SE->WantWrite(this);
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",ServerInstance->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)
1410 bool sent_to_at_least_one = false;
1413 if (this->registered != REG_ALL)
1418 /* We dont want to be doing this n times, just once */
1419 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1420 std::string out = tb;
1422 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1424 CUList* ulist = v->first->GetUsers();
1425 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1427 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1429 already_sent[i->second->fd] = uniq_id;
1430 i->second->Write(out);
1431 sent_to_at_least_one = true;
1437 * if the user was not in any channels, no users will receive the text. Make sure the user
1438 * receives their OWN message for WriteCommon
1440 if (!sent_to_at_least_one)
1442 this->Write(std::string(tb));
1448 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1453 /* write a formatted string to all users who share at least one common
1454 * channel, NOT including the source user e.g. for use in QUIT
1457 void userrec::WriteCommonExcept(const char* text, ...)
1459 char textbuffer[MAXBUF];
1462 va_start(argsPtr, text);
1463 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1466 this->WriteCommonExcept(std::string(textbuffer));
1469 void userrec::WriteCommonExcept(const std::string &text)
1471 bool quit_munge = false;
1472 char oper_quit[MAXBUF];
1473 char textbuffer[MAXBUF];
1479 strlcpy(textbuffer, text.c_str(), MAXBUF);
1481 if (this->registered != REG_ALL)
1486 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),textbuffer);
1488 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1489 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1492 if (ServerInstance->Config->HideSplits)
1494 char* check = textbuffer + 6;
1496 if (!strncasecmp(textbuffer, "QUIT :",6))
1498 std::stringstream split(check);
1499 std::string server_one;
1500 std::string server_two;
1502 split >> server_one;
1503 split >> server_two;
1505 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1507 strlcpy(oper_quit,textbuffer,MAXQUIT);
1508 strlcpy(check,"*.net *.split",MAXQUIT);
1510 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1516 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1518 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1519 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1521 char* check = textbuffer + 13;
1522 strlcpy(oper_quit,textbuffer,MAXQUIT);
1523 *check = 0; // We don't need to strlcpy, we just chop it from the :
1525 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1532 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1534 CUList *ulist = v->first->GetUsers();
1535 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1537 if (this != i->second)
1539 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1541 already_sent[i->second->fd] = uniq_id;
1543 i->second->Write(*i->second->oper ? out2 : out1);
1545 i->second->Write(out1);
1553 void userrec::WriteWallOps(const std::string &text)
1555 /* Does nothing if theyre not opered */
1556 if ((!*this->oper) && (IS_LOCAL(this)))
1559 std::string wallop = "WALLOPS :";
1563 wallop.append(text);
1567 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1571 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1574 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1575 this->WriteTo(t,wallop);
1579 void userrec::WriteWallOps(const char* text, ...)
1581 char textbuffer[MAXBUF];
1584 va_start(argsPtr, text);
1585 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1588 this->WriteWallOps(std::string(textbuffer));
1591 /* return 0 or 1 depending if users u and u2 share one or more common channels
1592 * (used by QUIT, NICK etc which arent channel specific notices)
1594 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1595 * the first users channels then the second users channels within the outer loop,
1596 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1597 * all possible iterations). However this new function instead checks against the
1598 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1599 * and saves us time as we already know what pointer value we are after.
1600 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1601 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1603 bool userrec::SharesChannelWith(userrec *other)
1605 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1609 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1611 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1612 * by replacing it with a map::find which *should* be more efficient
1614 if (i->first->HasUser(other))
1620 bool userrec::ChangeName(const char* gecos)
1622 if (!strcmp(gecos, this->fullname))
1628 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1631 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1633 strlcpy(this->fullname,gecos,MAXGECOS+1);
1638 bool userrec::ChangeDisplayedHost(const char* host)
1640 if (!strcmp(host, this->dhost))
1646 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1649 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1651 if (this->ServerInstance->Config->CycleHosts)
1652 this->WriteCommonExcept("QUIT :Changing hosts");
1654 /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
1655 strlcpy(this->dhost,host,64);
1657 this->InvalidateCache();
1659 if (this->ServerInstance->Config->CycleHosts)
1661 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1663 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1664 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1666 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1671 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1676 bool userrec::ChangeIdent(const char* newident)
1678 if (!strcmp(newident, this->ident))
1681 if (this->ServerInstance->Config->CycleHosts)
1682 this->WriteCommonExcept("%s","QUIT :Changing ident");
1684 strlcpy(this->ident, newident, IDENTMAX+2);
1686 this->InvalidateCache();
1688 if (this->ServerInstance->Config->CycleHosts)
1690 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1692 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1693 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1695 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1702 void userrec::NoticeAll(char* text, ...)
1704 char textbuffer[MAXBUF];
1705 char formatbuffer[MAXBUF];
1708 va_start(argsPtr, text);
1709 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1712 snprintf(formatbuffer,MAXBUF,":%s NOTICE $* :%s", this->GetFullHost(), textbuffer);
1713 std::string fmt = formatbuffer;
1715 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1722 std::string userrec::ChannelList(userrec* source)
1727 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1729 /* If the target is the same as the sender, let them see all their channels.
1730 * If the channel is NOT private/secret OR the user shares a common channel
1731 * If the user is an oper, and the <options:operspywhois> option is set.
1733 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
1735 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1742 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1747 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1750 std::ostringstream prefix;
1751 std::string::size_type start, pos, length;
1755 prefix << this->nick << " " << dest->nick << " :";
1756 line = prefix.str();
1757 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1759 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1761 length = (pos == std::string::npos) ? cl.length() : pos;
1763 if (line.length() + namelen + length - start > 510)
1765 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1766 line = prefix.str();
1769 if(pos == std::string::npos)
1771 line.append(cl.substr(start, length - start));
1776 line.append(cl.substr(start, length - start + 1));
1782 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1788 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1793 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1794 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1795 * then their ip will be taken as 'priority' anyway, so for example,
1796 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1798 ConnectClass* userrec::GetClass()
1800 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1802 if ((match(this->GetIPString(),i->GetHost().c_str(),true)) || (match(this->host,i->GetHost().c_str())))
1808 void userrec::PurgeEmptyChannels()
1810 std::vector<chanrec*> to_delete;
1812 // firstly decrement the count on each channel
1813 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1815 f->first->RemoveAllPrefixes(this);
1816 if (f->first->DelUser(this) == 0)
1818 /* No users left in here, mark it for deletion */
1821 to_delete.push_back(f->first);
1825 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1830 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1832 chanrec* thischan = *n;
1833 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1834 if (i2 != ServerInstance->chanlist->end())
1836 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1838 ServerInstance->chanlist->erase(i2);
1839 this->chans.erase(*n);
1846 void userrec::ShowMOTD()
1848 if (!ServerInstance->Config->MOTD.size())
1850 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1853 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1855 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1856 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1858 this->WriteServ("376 %s :End of message of the day.", this->nick);
1861 void userrec::ShowRULES()
1863 if (!ServerInstance->Config->RULES.size())
1865 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1868 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1870 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1871 this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
1873 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1876 void userrec::HandleEvent(EventType et, int errornum)
1878 /* WARNING: May delete this user! */
1879 int thisfd = this->GetFd();
1886 ServerInstance->ProcessUser(this);
1889 this->FlushWriteBuf();
1892 /** This should be safe, but dont DARE do anything after it -- Brain */
1893 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1899 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
1902 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1903 if ((ServerInstance->SE->GetRef(thisfd) == this))
1905 if (!WriteError.empty())
1907 userrec::QuitUser(ServerInstance, this, GetWriteError());