]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/users.cpp
Fix server prefix on JOIN.
[user/henk/code/inspircd.git] / src / users.cpp
index bb6b71782cdf454f6955ccfbca34db0ef05b7265..4a77b450f2422304cbebdcb9dd434595129c9831 100644 (file)
@@ -2,14 +2,11 @@
  *       | Inspire Internet Relay Chat Daemon |
  *       +------------------------------------+
  *
- *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
- *                    E-mail:
- *             <brain@chatspike.net>
- *               <Craig@chatspike.net>
- *     
- * Written by Craig Edwards, Craig McLure, and others.
+ *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
+ * See: http://www.inspircd.org/wiki/index.php/Credits
+ *
  * This program is free but copyrighted software; see
- *         the file COPYING for details.
+ *            the file COPYING for details.
  *
  * ---------------------------------------------------
  */
 #include "xline.h"
 #include "cull_list.h"
 
-irc::whowas::whowas_users whowas;
 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
 
-typedef std::map<irc::string,char*> opertype_t;
-typedef opertype_t operclass_t;
-
-opertype_t opertypes;
-operclass_t operclass;
-
 /* XXX: Used for speeding up WriteCommon operations */
 unsigned long uniq_id = 0;
 
 bool InitTypes(ServerConfig* conf, const char* tag)
 {
-       for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
+       if (conf->opertypes.size())
        {
-               if (n->second)
-                       delete[] n->second;
+               conf->GetInstance()->Log(DEBUG,"Currently %d items to clear",conf->opertypes.size());
+               for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
+               {
+                       conf->GetInstance()->Log(DEBUG,"Clear item");
+                       if (n->second)
+                               delete[] n->second;
+               }
        }
        
-       opertypes.clear();
+       conf->opertypes.clear();
        return true;
 }
 
 bool InitClasses(ServerConfig* conf, const char* tag)
 {
-       for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
+       if (conf->operclass.size())
        {
-               if (n->second)
-                       delete[] n->second;
+               for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
+               {
+                       if (n->second)
+                               delete[] n->second;
+               }
        }
        
-       operclass.clear();
+       conf->operclass.clear();
        return true;
 }
 
-bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
+bool DoType(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
 {
-       char* TypeName = (char*)values[0];
-       char* Classes = (char*)values[1];
+       const char* TypeName = values[0].GetString();
+       const char* Classes = values[1].GetString();
        
-       opertypes[TypeName] = strdup(Classes);
+       conf->opertypes[TypeName] = strdup(Classes);
        conf->GetInstance()->Log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
        return true;
 }
 
-bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
+bool DoClass(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
 {
-       char* ClassName = (char*)values[0];
-       char* CommandList = (char*)values[1];
+       const char* ClassName = values[0].GetString();
+       const char* CommandList = values[1].GetString();
        
-       operclass[ClassName] = strdup(CommandList);
+       conf->operclass[ClassName] = strdup(CommandList);
        conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
        return true;
 }
@@ -105,6 +103,24 @@ std::string userrec::ProcessNoticeMasks(const char *sm)
                        case '-':
                                adding = false;
                        break;
+                       case '*':
+                               for (unsigned char d = 'A'; d <= 'z'; d++)
+                               {
+                                       if (ServerInstance->SNO->IsEnabled(d))
+                                       {
+                                               if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
+                                               {
+                                                       if ((oldadding != adding) || (!output.length()))
+                                                               output += (adding ? '+' : '-');
+
+                                                       this->SetNoticeMask(d, adding);
+
+                                                       output += d;
+                                               }
+                                       }
+                                       oldadding = adding;
+                               }
+                       break;
                        default:
                                if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
                                {
@@ -134,19 +150,19 @@ void userrec::StartDNSLookup()
        try
        {
                ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
-               res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
+               res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), DNS_QUERY_REVERSE);
                this->ServerInstance->AddResolver(res_reverse);
        }
-       catch (ModuleException& e)
+       catch (CoreException& e)
        {
                ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
        }
 }
 
-UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
-       Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
+UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, QueryType qt) :
+       Resolver(Instance, to_resolve, qt), bound_user(user)
 {
-       this->fwd = forward;
+       this->fwd = (qt == DNS_QUERY_A || qt == DNS_QUERY_AAAA);
        this->bound_fd = user->GetFd();
 }
 
@@ -161,11 +177,16 @@ void UserResolver::OnLookupComplete(const std::string &result)
                        /* Check we didnt time out */
                        if (this->bound_user->registered != REG_ALL)
                        {
-                               bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
+#ifdef IPV6
+                               const char *ip = this->bound_user->GetIPString();
+                               bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, (strstr(ip,"0::ffff:") == ip ? DNS_QUERY_A : DNS_QUERY_AAAA));
+#else
+                               bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, DNS_QUERY_A);
+#endif
                                this->ServerInstance->AddResolver(bound_user->res_forward);
                        }
                }
-               catch (ModuleException& e)
+               catch (CoreException& e)
                {
                        ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
                }
@@ -173,7 +194,9 @@ void UserResolver::OnLookupComplete(const std::string &result)
        else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
        {
                /* Both lookups completed */
-               if (this->bound_user->GetIPString() == result)
+               std::string result2 = "0::ffff:";
+               result2.append(result);
+               if (this->bound_user->GetIPString() == result || this->bound_user->GetIPString() == result2)
                {
                        std::string hostname = this->bound_user->stored_host;
                        if (hostname.length() < 65)
@@ -271,9 +294,10 @@ userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
        *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
        server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
        reset_due = ServerInstance->Time();
+       age = ServerInstance->Time(true);
        lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
        ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
-       haspassed = dns_done = false;
+       exempt = haspassed = dns_done = false;
        fd = -1;
        recvq = "";
        sendq = "";
@@ -282,29 +306,34 @@ userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
        ip = NULL;
        chans.clear();
        invites.clear();
-       chans.resize(MAXCHANS);
        memset(modes,0,sizeof(modes));
        memset(snomasks,0,sizeof(snomasks));
-       
-       for (unsigned int n = 0; n < MAXCHANS; n++)
-       {
-               ucrec* x = new ucrec();
-               chans[n] = x;
-               x->channel = NULL;
-               x->uc_modes = 0;
-       }
 }
 
 userrec::~userrec()
 {
-       for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
-       {
-               ucrec* x = (ucrec*)*n;
-               delete x;
-       }
-
        if (ip)
        {
+               clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
+               if (x != ServerInstance->local_clones.end())
+               {
+                       x->second--;
+                       if (!x->second)
+                       {
+                               ServerInstance->local_clones.erase(x);
+                       }
+               }
+       
+               clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
+               if (y != ServerInstance->global_clones.end())
+               {
+                       y->second--;
+                       if (!y->second)
+                       {
+                               ServerInstance->global_clones.erase(y);
+                       }
+               }
+
                if (this->GetProtocolFamily() == AF_INET)
                {
                        delete (sockaddr_in*)ip;
@@ -318,9 +347,9 @@ userrec::~userrec()
        }
 }
 
-/* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
-void userrec::MakeHost(char* nhost)
+char* userrec::MakeHost()
 {
+       static char nhost[MAXBUF];
        /* This is much faster than snprintf */
        char* t = nhost;
        for(char* n = ident; *n; n++)
@@ -329,6 +358,21 @@ void userrec::MakeHost(char* nhost)
        for(char* n = host; *n; n++)
                *t++ = *n;
        *t = 0;
+       return nhost;
+}
+
+char* userrec::MakeHostIP()
+{
+       static char ihost[MAXBUF];
+       /* This is much faster than snprintf */
+       char* t = ihost;
+       for(char* n = ident; *n; n++)
+               *t++ = *n;
+       *t++ = '@';
+       for(const char* n = this->GetIPString(); *n; n++)
+               *t++ = *n;
+       *t = 0;
+       return ihost;
 }
 
 void userrec::CloseSocket()
@@ -392,13 +436,11 @@ char* userrec::GetFullRealHost()
        return fresult;
 }
 
-bool userrec::IsInvited(irc::string &channel)
+bool userrec::IsInvited(const irc::string &channel)
 {
        for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
        {
-               irc::string compare = i->channel;
-               
-               if (compare == channel)
+               if (channel == *i)
                {
                        return true;
                }
@@ -411,30 +453,22 @@ InvitedList* userrec::GetInviteList()
        return &invites;
 }
 
-void userrec::InviteTo(irc::string &channel)
+void userrec::InviteTo(const irc::string &channel)
 {
-       Invited i;
-       i.channel = channel;
-       invites.push_back(i);
+       invites.push_back(channel);
 }
 
-void userrec::RemoveInvite(irc::string &channel)
+void userrec::RemoveInvite(const irc::string &channel)
 {
        ServerInstance->Log(DEBUG,"Removing invites");
-       
-       if (invites.size())
+       for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
        {
-               for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
+               if (channel == *i)
                {
-                       irc::string compare = i->channel;
-                       
-                       if (compare == channel)
-                       {
-                               invites.erase(i);
-                               return;
-                               }
-                       }
-               }
+                       invites.erase(i);
+                       return;
+               }
+       }
 }
 
 bool userrec::HasPermission(const std::string &command)
@@ -456,15 +490,15 @@ bool userrec::HasPermission(const std::string &command)
        // are they even an oper at all?
        if (*this->oper)
        {
-               opertype_t::iterator iter_opertype = opertypes.find(this->oper);
-               if (iter_opertype != opertypes.end())
+               opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
+               if (iter_opertype != ServerInstance->Config->opertypes.end())
                {
                        char* Classes = strdup(iter_opertype->second);
                        char* myclass = strtok_r(Classes," ",&savept);
                        while (myclass)
                        {
-                               operclass_t::iterator iter_operclass = operclass.find(myclass);
-                               if (iter_operclass != operclass.end())
+                               operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
+                               if (iter_operclass != ServerInstance->Config->operclass.end())
                                {
                                        char* CommandList = strdup(iter_operclass->second);
                                        mycmd = strtok_r(CommandList," ",&savept2);
@@ -592,16 +626,9 @@ void userrec::AddWriteBuf(const std::string &data)
        try 
        {
                if (data.length() > 512)
-               {
-                       std::string newdata(data);
-                       newdata.resize(510);
-                       newdata.append("\r\n");
-                       sendq.append(newdata);
-               }
+                       sendq.append(data.substr(0,510)).append("\r\n");
                else
-               {
                        sendq.append(data);
-               }
        }
        catch (...)
        {
@@ -615,27 +642,45 @@ void userrec::FlushWriteBuf()
 {
        try
        {
-               if (this->fd == FD_MAGIC_NUMBER)
+               if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
                {
                        sendq = "";
                }
                if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
                {
-                       const char* tb = this->sendq.c_str();
-                       int n_sent = write(this->fd,tb,this->sendq.length());
+                       int old_sendq_length = sendq.length();
+                       int n_sent = write(this->fd, this->sendq.data(), this->sendq.length());
                        if (n_sent == -1)
                        {
-                               if (errno != EAGAIN)
+                               if (errno == EAGAIN)
+                               {
+                                       /* The socket buffer is full. This isnt fatal,
+                                        * try again later.
+                                        */
+                                       ServerInstance->Log(DEBUG,"EAGAIN, want write");
+                                       this->ServerInstance->SE->WantWrite(this);
+                               }
+                               else
+                               {
+                                       /* Fatal error, set write error and bail
+                                        */
                                        this->SetWriteError(strerror(errno));
+                                       return;
+                               }
                        }
                        else
                        {
-                               // advance the queue
-                               tb += n_sent;
-                               this->sendq = tb;
-                               // update the user's stats counters
+                               /* advance the queue */
+                               if (n_sent)
+                                       this->sendq = this->sendq.substr(n_sent);
+                               /* update the user's stats counters */
                                this->bytes_out += n_sent;
                                this->cmds_out++;
+                               if (n_sent != old_sendq_length)
+                               {
+                                       ServerInstance->Log(DEBUG,"Not all written, want write");
+                                       this->ServerInstance->SE->WantWrite(this);
+                               }
                        }
                }
        }
@@ -650,9 +695,8 @@ void userrec::SetWriteError(const std::string &error)
 {
        try
        {
-               ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
                // don't try to set the error twice, its already set take the first string.
-               if (!this->WriteError.length())
+               if (this->WriteError.empty())
                {
                        ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
                        this->WriteError = error;
@@ -724,18 +768,19 @@ void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &qui
                reason.resize(MAXQUIT - 1);
        
        if (IS_LOCAL(user))
+       {
                user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
+               if ((!user->sendq.empty()) && (!(*user->GetWriteError())))
+                       user->FlushWriteBuf();
+       }
 
        if (user->registered == REG_ALL)
        {
                user->PurgeEmptyChannels();
-               FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
                user->WriteCommonExcept("QUIT :%s",reason.c_str());
+               FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
        }
 
-       if (IS_LOCAL(user))
-               user->FlushWriteBuf();
-
        FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
 
        if (IS_LOCAL(user))
@@ -746,9 +791,9 @@ void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &qui
                        {
                                Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
                        }
-                       catch (ModuleException& modexcept)
+                       catch (CoreException& modexcept)
                        {
-                               Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
+                               Instance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
                        }
                }
                
@@ -808,15 +853,15 @@ namespace irc
                                free(gecos);
                }
 
-               /* every hour, run this function which removes all entries over 3 days */
-               void MaintainWhoWas(time_t t)
+               /* every hour, run this function which removes all entries older than Config->WhoWasMaxKeep */
+               void MaintainWhoWas(InspIRCd* ServerInstance, time_t t)
                {
-                       for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
+                       for (whowas_users::iterator iter = ServerInstance->whowas.begin(); iter != ServerInstance->whowas.end(); iter++)
                        {
                                whowas_set* n = (whowas_set*)iter->second;
                                if (n->size())
                                {
-                                       while ((n->begin() != n->end()) && ((*n->begin())->signon < t - 259200)) // 3 days
+                                       while ((n->begin() != n->end()) && ((*n->begin())->signon < t - ServerInstance->Config->WhoWasMaxKeep))
                                        {
                                                WhoWasGroup *a = *(n->begin());
                                                DELETE(a);
@@ -825,27 +870,99 @@ namespace irc
                                }
                        }
                }
+               /* on rehash, refactor maps according to new conf values */
+               void PruneWhoWas(InspIRCd* ServerInstance, time_t t)
+               {
+                       /* config values */
+                       int groupsize = ServerInstance->Config->WhoWasGroupSize;
+                       int maxgroups = ServerInstance->Config->WhoWasMaxGroups;
+                       int maxkeep =   ServerInstance->Config->WhoWasMaxKeep;
+
+                       int groupcount = ServerInstance->whowas.size();
+                       /* iterate whowas_fifo oldest first */
+                       whowas_users_fifo::iterator iter, safeiter;
+                       for (iter = ServerInstance->whowas_fifo.begin(); iter != ServerInstance->whowas_fifo.end(); iter++)
+                       {
+                               /** prune all groups that has expired due to new maxkeep time and
+                                *  also any group number higher than new maxgroups. The oldest are
+                                *  removed first due to iteration over whowas_fifo 
+                                */
+                               if (groupcount > maxgroups || iter->first < t - maxkeep)
+                               {
+                                       whowas_set* n = (whowas_set*)ServerInstance->whowas.find(iter->second)->second;
+                                       if (n->size())
+                                       {
+                                               while (n->begin() != n->end())
+                                               {
+                                                       WhoWasGroup *a = *(n->begin());
+                                                       DELETE(a);
+                                                       n->erase(n->begin());
+                                               }
+                                       }
+                                       ServerInstance->whowas.erase(iter->second);
+                                       /* use a safe iter copy for erase and set the orig iter old valid ref by decrementing it */
+                                       safeiter = iter;
+                                       --iter;
+                                       ServerInstance->whowas_fifo.erase(safeiter);
+                               }
+                               else {
+                                       /* also trim individual groupsizes in case groupsize should have been lowered */
+                                       whowas_set* n = (whowas_set*)ServerInstance->whowas.find(iter->second)->second;
+                                       if (n->size())
+                                       {
+                                               int nickcount = n->size();
+                                               while (n->begin() != n->end() && nickcount > groupsize)
+                                               {
+                                                       WhoWasGroup *a = *(n->begin());
+                                                       DELETE(a);
+                                                       n->erase(n->begin());
+                                                       nickcount--;
+                                               }
+                                       }
+                               }
+                               groupcount--;
+                       }
+               }
        };
 };
 
 /* adds or updates an entry in the whowas list */
 void userrec::AddToWhoWas()
 {
-       irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
+       /* if whowas disabled */
+       if (ServerInstance->Config->WhoWasGroupSize == 0 || ServerInstance->Config->WhoWasMaxGroups == 0)
+       {
+               return;
+       }
 
-       if (iter == whowas.end())
+       irc::whowas::whowas_users::iterator iter = ServerInstance->whowas.find(this->nick);
+
+       ServerInstance->Log(DEBUG,"Add to whowas lists");
+
+       if (iter == ServerInstance->whowas.end())
        {
+               ServerInstance->Log(DEBUG,"Adding new whowas set for %s",this->nick);
                irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
                irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
                n->push_back(a);
-               whowas[this->nick] = n;
+               ServerInstance->whowas[this->nick] = n;
+               ServerInstance->whowas_fifo[ServerInstance->Time()] = this->nick;
+               if ((int)(ServerInstance->whowas.size()) > ServerInstance->Config->WhoWasMaxGroups)
+               {
+                       ServerInstance->Log(DEBUG,"Maxgroups of %d reached deleting oldest group '%s'",ServerInstance->Config->WhoWasMaxGroups, ServerInstance->whowas_fifo.begin()->second.c_str());
+                       ServerInstance->whowas.erase(ServerInstance->whowas_fifo.begin()->second);
+                       ServerInstance->whowas_fifo.erase(ServerInstance->whowas_fifo.begin());
+               }
        }
        else
        {
                irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
 
-               if (group->size() > 10)
+               ServerInstance->Log(DEBUG,"Using existing whowas group for %s",this->nick);
+
+               if ((int)(group->size()) >= ServerInstance->Config->WhoWasGroupSize)
                {
+                       ServerInstance->Log(DEBUG,"Trimming existing group '%s' to %d entries",this->nick, ServerInstance->Config->WhoWasGroupSize);
                        irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
                        DELETE(a);
                        group->pop_front();
@@ -882,7 +999,7 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        }
 
        Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
-       
+
        New = new userrec(Instance);
        Instance->clientlist[tempnick] = New;
        New->fd = socket;
@@ -896,15 +1013,16 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        New->signon = Instance->Time() + Instance->Config->dns_timeout;
        New->lastping = 1;
 
-       Instance->Log(DEBUG,"Setting socket addresses");
        New->SetSockAddr(AF_FAMILY, ipaddr, port);
-       Instance->Log(DEBUG,"Socket addresses set.");
 
        /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
        for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
                New->dhost[j] = New->host[j] = *temp;
        New->dhost[j] = New->host[j] = 0;
-                       
+
+       Instance->AddLocalClone(New);
+       Instance->AddGlobalClone(New);
+
        // set the registration timeout for this user
        unsigned long class_regtimeout = 90;
        int class_flood = 0;
@@ -937,6 +1055,7 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
 
        if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
        {
+               Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
                userrec::QuitUser(Instance, New,"No more connections allowed");
                return;
        }
@@ -951,13 +1070,14 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
         * which for the time being is a physical impossibility (even the largest networks dont have more
         * than about 10,000 users on ONE server!)
         */
-       if ((unsigned)socket >= MAX_DESCRIPTORS)
+       if ((unsigned int)socket >= MAX_DESCRIPTORS)
        {
                userrec::QuitUser(Instance, New, "Server is full");
                return;
        }
-       ELine* e = Instance->XLines->matches_exception(New);
-       if (!e)
+
+       New->exempt = (Instance->XLines->matches_exception(New) != NULL);
+       if (!New->exempt)
        {
                ZLine* r = Instance->XLines->matches_zline(ipaddr);
                if (r)
@@ -978,49 +1098,28 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
                }
        }
 
+       /* NOTE: even if dns lookups are *off*, we still need to display this.
+        * BOPM and other stuff requires it.
+        */
        New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
 }
 
 long userrec::GlobalCloneCount()
 {
-       char u1[128] = {0};
-       char u2[128] = {0};
-       long x = 0;
-       
-       this->GetIPString(u2);
-       
-       for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
-       {
-               /* We have to match ip's as strings - we don't know what protocol
-                * a remote user may be using
-                */
-               if (strcmp(a->second->GetIPString(u1), u2) == 0)
-                       x++;
-       }
-       
-       return x;
+       clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
+       if (x != ServerInstance->global_clones.end())
+               return x->second;
+       else
+               return 0;
 }
 
 long userrec::LocalCloneCount()
 {
-       long x = 0;
-       for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
-       {
-               userrec* comp = *a;
-#ifdef IPV6
-               /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
-               in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
-               in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
-               if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
-                       x++;
-#else
-               in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
-               in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
-               if (s1->s_addr == s2->s_addr)
-                       x++;
-#endif
-       }
-       return x;
+       clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
+       if (x != ServerInstance->local_clones.end())
+               return x->second;
+       else
+               return 0;
 }
 
 void userrec::FullConnect(CullList* Goners)
@@ -1055,9 +1154,7 @@ void userrec::FullConnect(CullList* Goners)
                return;
        }
 
-       ELine* e = ServerInstance->XLines->matches_exception(this);
-
-       if (!e)
+       if (!this->exempt)
        {
                GLine* r = ServerInstance->XLines->matches_gline(this);
                
@@ -1087,27 +1184,8 @@ void userrec::FullConnect(CullList* Goners)
        this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
        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());
 
-       // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
-       // so i'd better split it :)
-       std::stringstream out(ServerInstance->Config->data005);
-       std::string token = "";
-       std::string line5 = "";
-       int token_counter = 0;
-       
-       while (!out.eof())
-       {
-               out >> token;
-               line5 = line5 + token + " ";
-               token_counter++;
-               
-               if ((token_counter >= 13) || (out.eof() == true))
-               {
-                       this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
-                       line5 = "";
-                       token_counter = 0;
-               }
-       }
-       
+       ServerInstance->Config->Send005(this);
+
        this->ShowMOTD();
 
        /*
@@ -1115,8 +1193,11 @@ void userrec::FullConnect(CullList* Goners)
         * changes dont go out onto the network and produce 'fake direction'.
         */
        FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
-       FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
+
        this->registered = REG_ALL;
+
+       FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
+
        ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
 }
 
@@ -1241,7 +1322,6 @@ int userrec::GetPort()
                }
                break;
                default:
-                       ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
                break;
        }
        return 0;
@@ -1275,7 +1355,7 @@ const char* userrec::GetIPString()
                        /* IP addresses starting with a : on irc are a Bad Thing (tm) */
                        if (*buf == ':')
                        {
-                               strlcpy(&temp[1], buf, sizeof(temp));
+                               strlcpy(&temp[1], buf, sizeof(temp) - 1);
                                *temp = '0';
                                return temp;
                        }
@@ -1291,7 +1371,6 @@ const char* userrec::GetIPString()
                }
                break;
                default:
-                       ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
                break;
        }
        return "";
@@ -1317,7 +1396,7 @@ const char* userrec::GetIPString(char* buf)
                        /* IP addresses starting with a : on irc are a Bad Thing (tm) */
                        if (*buf == ':')
                        {
-                               strlcpy(&temp[1], buf, sizeof(temp));
+                               strlcpy(&temp[1], buf, sizeof(temp) - 1);
                                *temp = '0';
                                strlcpy(buf, temp, sizeof(temp));
                        }
@@ -1334,7 +1413,6 @@ const char* userrec::GetIPString(char* buf)
                break;
 
                default:
-                       ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
                break;
        }
        return "";
@@ -1367,9 +1445,9 @@ void userrec::Write(std::string text)
                {
                        ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
                }
-               catch (ModuleException& modexcept)
+               catch (CoreException& modexcept)
                {
-                       ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
+                       ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
                }
        }
        else
@@ -1377,6 +1455,7 @@ void userrec::Write(std::string text)
                this->AddWriteBuf(text);
        }
        ServerInstance->stats->statsSent += text.length();
+       this->ServerInstance->SE->WantWrite(this);
 }
 
 /** Write()
@@ -1488,21 +1567,16 @@ void userrec::WriteCommon(const std::string &text)
        
                uniq_id++;
        
-               for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
+               for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
                {
-                       ucrec *n = *v;
-                       if (n->channel)
+                       CUList* ulist = v->first->GetUsers();
+                       for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
                        {
-                               CUList *ulist= n->channel->GetUsers();
-               
-                               for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
+                               if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
                                {
-                                       if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
-                                       {
-                                               already_sent[i->second->fd] = uniq_id;
-                                               i->second->WriteFrom(this, std::string(text));
-                                               sent_to_at_least_one = true;
-                                       }
+                                       already_sent[i->second->fd] = uniq_id;
+                                       i->second->WriteFrom(this, std::string(text));
+                                       sent_to_at_least_one = true;
                                }
                        }
                }
@@ -1591,25 +1665,20 @@ void userrec::WriteCommonExcept(const std::string &text)
                }
        }
 
-       for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
+       for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
        {
-               ucrec* n = *v;
-               if (n->channel)
+               CUList *ulist = v->first->GetUsers();
+               for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
                {
-                       CUList *ulist= n->channel->GetUsers();
-
-                       for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
+                       if (this != i->second)
                        {
-                               if (this != i->second)
+                               if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
                                {
-                                       if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
-                                       {
-                                               already_sent[i->second->fd] = uniq_id;
-                                               if (quit_munge)
-                                                       i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
-                                               else
-                                                       i->second->WriteFrom(this, std::string(textbuffer));
-                                       }
+                                       already_sent[i->second->fd] = uniq_id;
+                                       if (quit_munge)
+                                               i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
+                                       else
+                                               i->second->WriteFrom(this, std::string(textbuffer));
                                }
                        }
                }
@@ -1673,33 +1742,17 @@ bool userrec::SharesChannelWith(userrec *other)
                return false;
 
        /* Outer loop */
-       for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+       for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
        {
-               /* Fetch the channel from the user */
-               ucrec* user_channel = *i;
-
-               if (user_channel->channel)
-               {
-                       /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
-                        * by replacing it with a map::find which *should* be more efficient
-                        */
-                       if (user_channel->channel->HasUser(other))
-                               return true;
-               }
+               /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
+                * by replacing it with a map::find which *should* be more efficient
+                */
+               if (i->first->HasUser(other))
+                       return true;
        }
        return false;
 }
 
-int userrec::CountChannels()
-{
-       return ChannelCount;
-}
-
-void userrec::ModChannelCount(int n)
-{
-       ChannelCount += n;
-}
-
 bool userrec::ChangeName(const char* gecos)
 {
        if (!strcmp(gecos, this->fullname))
@@ -1731,21 +1784,19 @@ bool userrec::ChangeDisplayedHost(const char* host)
                FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
        }
        if (this->ServerInstance->Config->CycleHosts)
-               this->WriteCommonExcept("%s","QUIT :Changing hosts");
+               this->WriteCommonExcept("QUIT :Changing hosts");
 
-       strlcpy(this->dhost,host,63);
+       /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
+       strlcpy(this->dhost,host,64);
 
        if (this->ServerInstance->Config->CycleHosts)
        {
-               for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+               for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
                {
-                       if ((*i)->channel)
-                       {
-                               (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
-                               std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
-                               if (n.length() > 0)
-                                       (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
-                       }
+                       i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
+                       std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
+                       if (n.length() > 0)
+                               i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
                }
        }
 
@@ -1767,15 +1818,12 @@ bool userrec::ChangeIdent(const char* newident)
 
        if (this->ServerInstance->Config->CycleHosts)
        {
-               for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+               for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
                {
-                       if ((*i)->channel)
-                       {
-                               (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
-                               std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
-                               if (n.length() > 0)
-                                       (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
-                       }
+                       i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
+                       std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
+                       if (n.length() > 0)
+                               i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
                }
        }
 
@@ -1807,20 +1855,15 @@ std::string userrec::ChannelList(userrec* source)
        try
        {
                std::string list;
-               for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+               for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
                {
-                       ucrec* rec = *i;
-       
-                       if(rec->channel && rec->channel->name)
+                       /* If the target is the same as the sender, let them see all their channels.
+                        * If the channel is NOT private/secret OR the user shares a common channel
+                        * If the user is an oper, and the <options:operspywhois> option is set.
+                        */
+                       if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
                        {
-                               /* If the target is the same as the sender, let them see all their channels.
-                                * If the channel is NOT private/secret OR the user shares a common channel
-                                * If the user is an oper, and the <options:operspywhois> option is set.
-                                */
-                               if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
-                               {
-                                       list.append(rec->channel->GetPrefixChar(this)).append(rec->channel->name).append(" ");
-                               }
+                               list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
                        }
                }
                return list;
@@ -1840,16 +1883,17 @@ void userrec::SplitChanList(userrec* dest, const std::string &cl)
 
        try
        {
-               prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
+               prefix << this->nick << " " << dest->nick << " :";
                line = prefix.str();
+               int namelen = strlen(ServerInstance->Config->ServerName) + 6;
        
                for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
                {
                        length = (pos == std::string::npos) ? cl.length() : pos;
        
-                       if (line.length() + length - start > 510)
+                       if (line.length() + namelen + length - start > 510)
                        {
-                               this->Write(line);
+                               ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
                                line = prefix.str();
                        }
        
@@ -1866,7 +1910,7 @@ void userrec::SplitChanList(userrec* dest, const std::string &cl)
        
                if (line.length())
                {
-                       this->Write(line);
+                       ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
                }
        }
 
@@ -1898,24 +1942,19 @@ void userrec::PurgeEmptyChannels()
        std::vector<chanrec*> to_delete;
 
        // firstly decrement the count on each channel
-       for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
+       for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
        {
-               ucrec* uc = *f;
-               if (uc->channel)
+               f->first->RemoveAllPrefixes(this);
+               if (f->first->DelUser(this) == 0)
                {
-                       uc->channel->RemoveAllPrefixes(this);
-                       if (uc->channel->DelUser(this) == 0)
+                       /* No users left in here, mark it for deletion */
+                       try
                        {
-                               /* No users left in here, mark it for deletion */
-                               try
-                               {
-                                       to_delete.push_back(uc->channel);
-                               }
-                               catch (...)
-                               {
-                                       ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
-                               }
-                               uc->channel = NULL;
+                               to_delete.push_back(f->first);
+                       }
+                       catch (...)
+                       {
+                               ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
                        }
                }
        }
@@ -1944,8 +1983,8 @@ void userrec::ShowMOTD()
        }
        this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
 
-       for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
-               this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
+       for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
+               this->WriteServ("372 %s :- %s",this->nick,i->c_str());
 
        this->WriteServ("376 %s :End of message of the day.", this->nick);
 }
@@ -1959,22 +1998,41 @@ void userrec::ShowRULES()
        }
        this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
 
-       for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
-               this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
+       for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
+               this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
 
        this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
 }
 
-void userrec::HandleEvent(EventType et)
+void userrec::HandleEvent(EventType et, int errornum)
 {
        /* WARNING: May delete this user! */
        try
        {
-               ServerInstance->ProcessUser(this);
+               switch (et)
+               {
+                       case EVENT_READ:
+                               ServerInstance->ProcessUser(this);
+
+                       break;
+                       case EVENT_WRITE:
+                               this->FlushWriteBuf();
+                       break;
+                       case EVENT_ERROR:
+                               /** This should be safe, but dont DARE do anything after it -- Brain */
+                               this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
+                       break;
+               }
        }
        catch (...)
        {
                ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
        }
+
+       /* If the user has raised an error whilst being processed, quit them now we're safe to */
+       if (!WriteError.empty())
+       {
+               userrec::QuitUser(ServerInstance, this, GetWriteError());
+       }
 }