]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/users.cpp
Remove unused debug
[user/henk/code/inspircd.git] / src / users.cpp
index 261ee491eda0d5e9c8fd2a1d4e619520a561a26f..ed979e337a29db2f5fa2183f6c26572604451b5d 100644 (file)
  * ---------------------------------------------------
  */
 
-#include "inspircd_config.h"
 #include "configreader.h"
 #include "channels.h"
-#include "connection.h"
 #include "users.h"
 #include "inspircd.h"
 #include <stdarg.h>
-#include "inspstring.h"
-#include "commands.h"
-
-#include "typedefs.h"
 #include "socketengine.h"
-#include "hashcomp.h"
 #include "wildcard.h"
 #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;
 }
@@ -92,31 +86,65 @@ bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
        return true;
 }
 
-bool userrec::ProcessNoticeMasks(const char *sm)
+std::string userrec::ProcessNoticeMasks(const char *sm)
 {
-       bool adding = true;
+       bool adding = true, oldadding = false;
        const char *c = sm;
+       std::string output;
+
+       ServerInstance->Log(DEBUG,"Process notice masks");
 
        while (c && *c)
        {
+               ServerInstance->Log(DEBUG,"Process notice mask %c",*c);
+               
                switch (*c)
                {
                        case '+':
                                adding = true;
-                               break;
+                       break;
                        case '-':
                                adding = false;
-                               break;
+                       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'))
-                                       this->SetNoticeMask(*c, adding);
-                               break;
+                               if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
+                               {
+                                       if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
+                                       {
+                                               if ((oldadding != adding) || (!output.length()))
+                                                       output += (adding ? '+' : '-');
+
+                                               this->SetNoticeMask(*c, adding);
+
+                                               output += *c;
+                                       }
+                               }
+                               oldadding = adding;
+                       break;
                }
 
                *c++;
        }
 
-       return true;
+       return output;
 }
 
 void userrec::StartDNSLookup()
@@ -125,7 +153,7 @@ 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)
@@ -134,16 +162,16 @@ void userrec::StartDNSLookup()
        }
 }
 
-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->bound_fd = user->fd;
+       this->fwd = (qt == DNS_QUERY_A || qt == DNS_QUERY_AAAA);
+       this->bound_fd = user->GetFd();
 }
 
 void UserResolver::OnLookupComplete(const std::string &result)
 {
-       if ((!this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
+       if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
        {
                ServerInstance->Log(DEBUG,"Commencing forward lookup");
                this->bound_user->stored_host = result;
@@ -152,7 +180,12 @@ 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);
                        }
                }
@@ -161,10 +194,12 @@ void UserResolver::OnLookupComplete(const std::string &result)
                        ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
                }
        }
-       else if ((this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
+       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)
@@ -196,7 +231,7 @@ void UserResolver::OnLookupComplete(const std::string &result)
 
 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
 {
-       if (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user)
+       if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
        {
                /* Error message here */
                this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
@@ -262,9 +297,11 @@ 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();
-       lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
-       timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
-       haspassed = dns_done = false;
+       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;
+       exempt = haspassed = dns_done = false;
+       fd = -1;
        recvq = "";
        sendq = "";
        WriteError = "";
@@ -274,13 +311,13 @@ userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
        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;
+               chans[n] = new ucrec();
+               chans[n]->channel = NULL;
+               chans[n]->uc_modes = 0;
        }
 }
 
@@ -294,6 +331,26 @@ userrec::~userrec()
 
        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;
@@ -307,9 +364,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++)
@@ -318,6 +375,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()
@@ -356,7 +428,7 @@ char* userrec::MakeWildHost()
 
 int userrec::ReadData(void* buffer, size_t size)
 {
-       if (this->fd > -1)
+       if (IS_LOCAL(this))
        {
                return read(this->fd, buffer, size);
        }
@@ -445,15 +517,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);
@@ -485,25 +557,34 @@ bool userrec::HasPermission(const std::string &command)
  */
 bool userrec::AddBuffer(std::string a)
 {
-       std::string::size_type i = a.rfind('\r');
-
-       while (i != std::string::npos)
+       try
        {
-               a.erase(i, 1);
-               i = a.rfind('\r');
-       }
+               std::string::size_type i = a.rfind('\r');
+       
+               while (i != std::string::npos)
+               {
+                       a.erase(i, 1);
+                       i = a.rfind('\r');
+               }
 
-       if (a.length())
-               recvq.append(a);
+               if (a.length())
+                       recvq.append(a);
+               
+               if (recvq.length() > (unsigned)this->recvqmax)
+               {
+                       this->SetWriteError("RecvQ exceeded");
+                       ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
+                       return false;
+               }
+       
+               return true;
+       }
 
-       if (recvq.length() > (unsigned)this->recvqmax)
+       catch (...)
        {
-               this->SetWriteError("RecvQ exceeded");
-               ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
+               ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
                return false;
        }
-
-       return true;
 }
 
 bool userrec::BufferIsReady()
@@ -518,29 +599,38 @@ void userrec::ClearBuffer()
 
 std::string userrec::GetBuffer()
 {
-       if (!recvq.length())
-               return "";
-
-       /* Strip any leading \r or \n off the string.
-        * Usually there are only one or two of these,
-        * so its is computationally cheap to do.
-        */
-       while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
-               recvq.erase(recvq.begin());
-
-       for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
+       try
        {
-               /* Find the first complete line, return it as the
-                * result, and leave the recvq as whats left
+               if (!recvq.length())
+                       return "";
+       
+               /* Strip any leading \r or \n off the string.
+                * Usually there are only one or two of these,
+                * so its is computationally cheap to do.
                 */
-               if (*x == '\n')
+               while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
+                       recvq.erase(recvq.begin());
+       
+               for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
                {
-                       std::string ret = std::string(recvq.begin(), x);
-                       recvq.erase(recvq.begin(), x + 1);
-                       return ret;
+                       /* Find the first complete line, return it as the
+                        * result, and leave the recvq as whats left
+                        */
+                       if (*x == '\n')
+                       {
+                               std::string ret = std::string(recvq.begin(), x);
+                               recvq.erase(recvq.begin(), x + 1);
+                               return ret;
+                       }
                }
+               return "";
+       }
+
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
+               return "";
        }
-       return "";
 }
 
 void userrec::AddWriteBuf(const std::string &data)
@@ -559,52 +649,95 @@ void userrec::AddWriteBuf(const std::string &data)
                ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
                return;
        }
-       
-       if (data.length() > 512)
+
+       try 
        {
-               std::string newdata(data);
-               newdata.resize(510);
-               newdata.append("\r\n");
-               sendq.append(newdata);
+               if (data.length() > 512)
+               {
+                       std::string newdata(data);
+                       newdata.resize(510);
+                       newdata.append("\r\n");
+                       sendq.append(newdata);
+               }
+               else
+               {
+                       sendq.append(data);
+               }
        }
-       else
+       catch (...)
        {
-               sendq.append(data);
+               this->SetWriteError("SendQ exceeded");
+               ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
        }
 }
 
 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
 void userrec::FlushWriteBuf()
 {
-       if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
+       try
        {
-               const char* tb = this->sendq.c_str();
-               int n_sent = write(this->fd,tb,this->sendq.length());
-               if (n_sent == -1)
+               if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
                {
-                       if (errno != EAGAIN)
-                               this->SetWriteError(strerror(errno));
+                       sendq = "";
                }
-               else
+               if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
                {
-                       // advance the queue
-                       tb += n_sent;
-                       this->sendq = tb;
-                       // update the user's stats counters
-                       this->bytes_out += n_sent;
-                       this->cmds_out++;
+                       int old_sendq_length = sendq.length();
+                       const char* tb = this->sendq.c_str();
+                       int n_sent = write(this->fd,tb,this->sendq.length());
+                       if (n_sent == -1)
+                       {
+                               if (errno == EAGAIN)
+                               {
+                                       ServerInstance->Log(DEBUG,"EAGAIN, want write");
+                                       this->ServerInstance->SE->WantWrite(this);
+                               }
+                               else
+                               {
+                                       this->QuitUser(ServerInstance, this, strerror(errno));
+                                       return;
+                               }
+                       }
+                       else
+                       {
+                               /*ServerInstance->Log(DEBUG,"Wrote: %d of %d: %s", n_sent, old_sendq_length, sendq.substr(0, n_sent).c_str());*/
+                               // advance the queue
+                               tb += n_sent;
+                               this->sendq = tb;
+                               // 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);
+                               }
+                       }
                }
        }
+
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
+       }
 }
 
 void userrec::SetWriteError(const std::string &error)
 {
-       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())
+       try
        {
-               ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
-               this->WriteError = error;
+               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())
+               {
+                       ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
+                       this->WriteError = error;
+               }
+       }
+
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
        }
 }
 
@@ -615,47 +748,52 @@ const char* userrec::GetWriteError()
 
 void userrec::Oper(const std::string &opertype)
 {
-       this->modes[UM_OPERATOR] = 1;
-       this->WriteServ("MODE %s :+o", this->nick);
-       FOREACH_MOD(I_OnOper, OnOper(this, opertype));
-       ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
-       strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
-       ServerInstance->all_opers.push_back(this);
-       FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
+       try
+       {
+               this->modes[UM_OPERATOR] = 1;
+               this->WriteServ("MODE %s :+o", this->nick);
+               FOREACH_MOD(I_OnOper, OnOper(this, opertype));
+               ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
+               strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
+               ServerInstance->all_opers.push_back(this);
+               FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
+       }
+
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
+       }
 }
 
 void userrec::UnOper()
 {
-       if (*this->oper)
+       try
        {
-               *this->oper = 0;
-               this->modes[UM_OPERATOR] = 0;
-               for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
+               if (*this->oper)
                {
-                       if (*a == this)
+                       *this->oper = 0;
+                       this->modes[UM_OPERATOR] = 0;
+                       for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
                        {
-                               ServerInstance->Log(DEBUG,"Oper removed from optimization list");
-                               ServerInstance->all_opers.erase(a);
-                               return;
+                               if (*a == this)
+                               {
+                                       ServerInstance->Log(DEBUG,"Oper removed from optimization list");
+                                       ServerInstance->all_opers.erase(a);
+                                       return;
+                               }
                        }
                }
        }
+
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
+       }
 }
 
-void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quitreason)
+void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
 {
        user_hash::iterator iter = Instance->clientlist.find(user->nick);
-
-/*
- * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
- * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
- *
- * I can't imagine this blowing up, so I'm commenting it out. We still check
- * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
- *
- *     if (iter == clientlist.end())
- *             return;
- */
        std::string reason = quitreason;
 
        if (reason.length() > MAXQUIT - 1)
@@ -671,9 +809,6 @@ void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quit
                user->WriteCommonExcept("QUIT :%s",reason.c_str());
        }
 
-       if (IS_LOCAL(user))
-               user->FlushWriteBuf();
-
        FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
 
        if (IS_LOCAL(user))
@@ -690,22 +825,20 @@ void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quit
                        }
                }
                
-               Instance->SE->DelFd(user->fd);
+               Instance->SE->DelFd(user);
                user->CloseSocket();
        }
 
        /*
-        * this must come before the ServerInstance->WriteOpers so that it doesnt try to fill their buffer with anything
-        * if they were an oper with +s.
-        *
-        * XXX -
-        * In the current implementation, we only show local quits, as we only show local connects. With 
-        * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
+        * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
+        * if they were an oper with +sn +qQ.
         */
        if (user->registered == REG_ALL)
        {
                if (IS_LOCAL(user))
-                       Instance->WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
+                       Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
+               else
+                       Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
                user->AddToWhoWas();
        }
 
@@ -714,7 +847,6 @@ void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quit
                Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
                if (IS_LOCAL(user))
                {
-                       Instance->fd_ref_table[user->fd] = NULL;
                        if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
                                Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
                }
@@ -749,15 +881,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);
@@ -766,27 +898,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;
+       }
+
+       irc::whowas::whowas_users::iterator iter = ServerInstance->whowas.find(this->nick);
+
+       ServerInstance->Log(DEBUG,"Add to whowas lists");
 
-       if (iter == whowas.end())
+       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();
@@ -803,7 +1007,7 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        std::string tempnick = ConvToStr(socket) + "-unknown";
        user_hash::iterator iter = Instance->clientlist.find(tempnick);
        const char *ipaddr = insp_ntoa(ip);
-       userrec* _new;
+       userrec* New;
        int j = 0;
 
        /*
@@ -823,29 +1027,30 @@ 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;
-       strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
 
-       _new->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
+       New = new userrec(Instance);
+       Instance->clientlist[tempnick] = New;
+       New->fd = socket;
+       strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
+
+       New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
        /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
-       strcpy(_new->ident, "unknown");
+       strcpy(New->ident, "unknown");
 
-       _new->registered = REG_NONE;
-       _new->signon = Instance->Time() + Instance->Config->dns_timeout;
-       _new->lastping = 1;
+       New->registered = REG_NONE;
+       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.");
+       New->SetSockAddr(AF_FAMILY, ipaddr, port);
 
        /* 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;
-                       
+       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;
@@ -859,7 +1064,7 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
                {
                        class_regtimeout = (unsigned long)i->registration_timeout;
                        class_flood = i->flood;
-                       _new->pingmax = i->pingtime;
+                       New->pingmax = i->pingtime;
                        class_threshold = i->threshold;
                        class_sqmax = i->sendqmax;
                        class_rqmax = i->recvqmax;
@@ -867,25 +1072,19 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
                }
        }
 
-       _new->nping = Instance->Time() + _new->pingmax + Instance->Config->dns_timeout;
-       _new->timeout = Instance->Time() + class_regtimeout;
-       _new->flood = class_flood;
-       _new->threshold = class_threshold;
-       _new->sendqmax = class_sqmax;
-       _new->recvqmax = class_rqmax;
-
-       Instance->fd_ref_table[socket] = _new;
-       Instance->local_users.push_back(_new);
+       New->nping = Instance->Time() + New->pingmax + Instance->Config->dns_timeout;
+       New->timeout = Instance->Time() + class_regtimeout;
+       New->flood = class_flood;
+       New->threshold = class_threshold;
+       New->sendqmax = class_sqmax;
+       New->recvqmax = class_rqmax;
 
-       if (Instance->local_users.size() > Instance->Config->SoftLimit)
-       {
-               userrec::QuitUser(Instance, _new,"No more connections allowed");
-               return;
-       }
+       Instance->local_users.push_back(New);
 
-       if (Instance->local_users.size() >= MAXCLIENTS)
+       if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
        {
-               userrec::QuitUser(Instance, _new,"No more connections allowed");
+               Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
+               userrec::QuitUser(Instance, New,"No more connections allowed");
                return;
        }
 
@@ -899,72 +1098,56 @@ 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");
+               userrec::QuitUser(Instance, New, "Server is full");
                return;
        }
-       char* e = Instance->XLines->matches_exception(ipaddr);
-       if (!e)
+
+       New->exempt = (Instance->XLines->matches_exception(New) != NULL);
+       if (!New->exempt)
        {
-               char* r = Instance->XLines->matches_zline(ipaddr);
+               ZLine* r = Instance->XLines->matches_zline(ipaddr);
                if (r)
                {
                        char reason[MAXBUF];
-                       snprintf(reason,MAXBUF,"Z-Lined: %s",r);
-                       userrec::QuitUser(Instance, _new,reason);
+                       snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
+                       userrec::QuitUser(Instance, New, reason);
                        return;
                }
        }
 
        if (socket > -1)
        {
-               if (!Instance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
+               if (!Instance->SE->AddFd(New))
                {
-                       userrec::QuitUser(Instance, _new, "Internal error handling connection");
+                       userrec::QuitUser(Instance, New, "Internal error handling connection");
                        return;
                }
        }
 
-       _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
+       /* 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[1024];
-       char u2[1024];
-       long x = 0;
-       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 (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
-                               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)
@@ -999,28 +1182,24 @@ void userrec::FullConnect(CullList* Goners)
                return;
        }
 
-       char match_against[MAXBUF];
-       snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
-       char* e = ServerInstance->XLines->matches_exception(match_against);
-
-       if (!e)
+       if (!this->exempt)
        {
-               char* r = ServerInstance->XLines->matches_gline(match_against);
+               GLine* r = ServerInstance->XLines->matches_gline(this);
                
                if (r)
                {
                        char reason[MAXBUF];
-                       snprintf(reason,MAXBUF,"G-Lined: %s",r);
+                       snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
                        Goners->AddItem(this, reason);
                        return;
                }
                
-               r = ServerInstance->XLines->matches_kline(match_against);
+               KLine* n = ServerInstance->XLines->matches_kline(this);
                
-               if (r)
+               if (n)
                {
                        char reason[MAXBUF];
-                       snprintf(reason,MAXBUF,"K-Lined: %s",r);
+                       snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
                        Goners->AddItem(this, reason);
                        return;
                }
@@ -1061,9 +1240,12 @@ 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_OnGlobalConnect,OnGlobalConnect(this));
+
        this->registered = REG_ALL;
-       ServerInstance->WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
+
+       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());
 }
 
 /** userrec::UpdateNick()
@@ -1072,54 +1254,65 @@ void userrec::FullConnect(CullList* Goners)
  */
 userrec* userrec::UpdateNickHash(const char* New)
 {
-       //user_hash::iterator newnick;
-       user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
+       try
+       {
+               //user_hash::iterator newnick;
+               user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
 
-       if (!strcasecmp(this->nick,New))
-               return oldnick->second;
+               if (!strcasecmp(this->nick,New))
+                       return oldnick->second;
 
-       if (oldnick == ServerInstance->clientlist.end())
-               return NULL; /* doesnt exist */
+               if (oldnick == ServerInstance->clientlist.end())
+                       return NULL; /* doesnt exist */
 
-       userrec* olduser = oldnick->second;
-       ServerInstance->clientlist[New] = olduser;
-       ServerInstance->clientlist.erase(oldnick);
-       return ServerInstance->clientlist[New];
+               userrec* olduser = oldnick->second;
+               ServerInstance->clientlist[New] = olduser;
+               ServerInstance->clientlist.erase(oldnick);
+               return ServerInstance->clientlist[New];
+       }
+
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
+               return NULL;
+       }
 }
 
 bool userrec::ForceNickChange(const char* newnick)
 {
-       char nick[MAXBUF];
-       int MOD_RESULT = 0;
-
-       *nick = 0;
-
-       FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
-       
-       if (MOD_RESULT)
+       try
        {
-               ServerInstance->stats->statsCollisions++;
-               return false;
-       }
+               int MOD_RESULT = 0;
        
-       if (ServerInstance->XLines->matches_qline(newnick))
-       {
-               ServerInstance->stats->statsCollisions++;
+               FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
+
+               if (MOD_RESULT)
+               {
+                       ServerInstance->stats->statsCollisions++;
+                       return false;
+               }
+       
+               if (ServerInstance->XLines->matches_qline(newnick))
+               {
+                       ServerInstance->stats->statsCollisions++;
+                       return false;
+               }
+
+               if (this->registered == REG_ALL)
+               {
+                       const char* pars[1];
+                       pars[0] = newnick;
+                       std::string cmd = "NICK";
+                       return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
+               }
                return false;
        }
 
-       if (newnick)
-       {
-               strlcpy(this->nick, newnick, NICKMAX - 1);
-       }
-       if (this->registered == REG_ALL)
+       catch (...)
        {
-               const char* pars[1];
-               pars[0] = nick;
-               std::string cmd = "NICK";
-               ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
+               ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
+               return false;
        }
-       return true;
 }
 
 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
@@ -1194,7 +1387,6 @@ int userrec::GetProtocolFamily()
 const char* userrec::GetIPString()
 {
        static char buf[1024];
-       static char temp[1024];
 
        if (this->ip == NULL)
                return "";
@@ -1204,12 +1396,14 @@ const char* userrec::GetIPString()
 #ifdef SUPPORT_IP6LINKS
                case AF_INET6:
                {
+                       static char temp[1024];
+               
                        sockaddr_in6* sin = (sockaddr_in6*)this->ip;
                        inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(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';
                                return temp;
                        }
@@ -1233,8 +1427,6 @@ const char* userrec::GetIPString()
 
 const char* userrec::GetIPString(char* buf)
 {
-       static char temp[1024];
-
        if (this->ip == NULL)
        {
                *buf = 0;
@@ -1246,12 +1438,14 @@ const char* userrec::GetIPString(char* buf)
 #ifdef SUPPORT_IP6LINKS
                case AF_INET6:
                {
+                       static char temp[1024];
+               
                        sockaddr_in6* sin = (sockaddr_in6*)this->ip;
                        inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(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));
                        }
@@ -1285,7 +1479,15 @@ void userrec::Write(std::string text)
        if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
                return;
 
-       text.append("\r\n");
+       try
+       {
+               text.append("\r\n");
+       }
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
+               return;
+       }
 
        if (ServerInstance->Config->GetIOHook(this->GetPort()))
        {
@@ -1303,6 +1505,7 @@ void userrec::Write(std::string text)
                this->AddWriteBuf(text);
        }
        ServerInstance->stats->statsSent += text.length();
+       this->ServerInstance->SE->WantWrite(this);
 }
 
 /** Write()
@@ -1405,39 +1608,47 @@ void userrec::WriteCommon(const char* text, ...)
 
 void userrec::WriteCommon(const std::string &text)
 {
-       bool sent_to_at_least_one = false;
-
-       if (this->registered != REG_ALL)
-               return;
-
-       uniq_id++;
-
-       for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
+       try
        {
-               ucrec *n = *v;
-               if (n->channel)
+               bool sent_to_at_least_one = false;
+       
+               if (this->registered != REG_ALL)
+                       return;
+       
+               uniq_id++;
+       
+               for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
                {
-                       CUList *ulist= n->channel->GetUsers();
-
-                       for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
+                       ucrec *n = *v;
+                       if (n->channel)
                        {
-                               if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
+                               CUList *ulist= n->channel->GetUsers();
+               
+                               for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
                                {
-                                       already_sent[i->second->fd] = uniq_id;
-                                       i->second->WriteFrom(this, std::string(text));
-                                       sent_to_at_least_one = true;
+                                       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;
+                                       }
                                }
                        }
                }
+       
+               /*
+                * if the user was not in any channels, no users will receive the text. Make sure the user
+                * receives their OWN message for WriteCommon
+                */
+               if (!sent_to_at_least_one)
+               {
+                       this->WriteFrom(this,std::string(text));
+               }
        }
 
-       /*
-        * if the user was not in any channels, no users will receive the text. Make sure the user
-        * receives their OWN message for WriteCommon
-        */
-       if (!sent_to_at_least_one)
+       catch (...)
        {
-               this->WriteFrom(this,std::string(text));
+               ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
        }
 }
 
@@ -1460,7 +1671,7 @@ void userrec::WriteCommonExcept(const char* text, ...)
 
 void userrec::WriteCommonExcept(const std::string &text)
 {
-       bool quit_munge = true;
+       bool quit_munge = false;
        char oper_quit[MAXBUF];
        char textbuffer[MAXBUF];
 
@@ -1542,7 +1753,16 @@ void userrec::WriteWallOps(const std::string &text)
                return;
 
        std::string wallop = "WALLOPS :";
-       wallop.append(text);
+
+       try
+       {
+               wallop.append(text);
+       }
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
+               return;
+       }
 
        for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
        {
@@ -1601,15 +1821,19 @@ bool userrec::SharesChannelWith(userrec *other)
 
 int userrec::CountChannels()
 {
-       int z = 0;
-       for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
-               if ((*i)->channel)
-                       z++;
-       return z;
+       return ChannelCount;
+}
+
+void userrec::ModChannelCount(int n)
+{
+       ChannelCount += n;
 }
 
 bool userrec::ChangeName(const char* gecos)
 {
+       if (!strcmp(gecos, this->fullname))
+               return true;
+
        if (IS_LOCAL(this))
        {
                int MOD_RESULT = 0;
@@ -1624,6 +1848,9 @@ bool userrec::ChangeName(const char* gecos)
 
 bool userrec::ChangeDisplayedHost(const char* host)
 {
+       if (!strcmp(host, this->dhost))
+               return true;
+
        if (IS_LOCAL(this))
        {
                int MOD_RESULT = 0;
@@ -1632,7 +1859,25 @@ bool userrec::ChangeDisplayedHost(const char* host)
                        return false;
                FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
        }
-       strlcpy(this->dhost,host,63);
+       if (this->ServerInstance->Config->CycleHosts)
+               this->WriteCommonExcept("QUIT :Changing hosts");
+
+       /* 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++)
+               {
+                       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());
+                       }
+               }
+       }
 
        if (IS_LOCAL(this))
                this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
@@ -1640,6 +1885,33 @@ bool userrec::ChangeDisplayedHost(const char* host)
        return true;
 }
 
+bool userrec::ChangeIdent(const char* newident)
+{
+       if (!strcmp(newident, this->ident))
+               return true;
+
+       if (this->ServerInstance->Config->CycleHosts)
+               this->WriteCommonExcept("%s","QUIT :Changing ident");
+
+       strlcpy(this->ident, newident, IDENTMAX+2);
+
+       if (this->ServerInstance->Config->CycleHosts)
+       {
+               for (std::vector<ucrec*>::const_iterator 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());
+                       }
+               }
+       }
+
+       return true;
+}
+
 void userrec::NoticeAll(char* text, ...)
 {
        char textbuffer[MAXBUF];
@@ -1662,24 +1934,32 @@ void userrec::NoticeAll(char* text, ...)
 
 std::string userrec::ChannelList(userrec* source)
 {
-       std::string list;
-       for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+       try
        {
-               ucrec* rec = *i;
-
-               if(rec->channel && rec->channel->name)
+               std::string list;
+               for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
                {
-                       /* 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))))
+                       ucrec* rec = *i;
+       
+                       if(rec->channel && rec->channel->name)
                        {
-                               list.append(rec->channel->GetStatusChar(this)).append(rec->channel->name).append(" ");
+                               /* 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(" ");
+                               }
                        }
                }
+               return list;
+       }
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
+               return "";
        }
-       return list;
 }
 
 void userrec::SplitChanList(userrec* dest, const std::string &cl)
@@ -1688,33 +1968,42 @@ void userrec::SplitChanList(userrec* dest, const std::string &cl)
        std::ostringstream prefix;
        std::string::size_type start, pos, length;
 
-       prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
-       line = prefix.str();
-
-       for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
+       try
        {
-               length = (pos == std::string::npos) ? cl.length() : pos;
-
-               if (line.length() + length - start > 510)
-               {
-                       this->Write(line);
-                       line = prefix.str();
-               }
-
-               if(pos == std::string::npos)
+               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)
                {
-                       line.append(cl.substr(start, length - start));
-                       break;
+                       length = (pos == std::string::npos) ? cl.length() : pos;
+       
+                       if (line.length() + namelen + length - start > 510)
+                       {
+                               ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
+                               line = prefix.str();
+                       }
+       
+                       if(pos == std::string::npos)
+                       {
+                               line.append(cl.substr(start, length - start));
+                               break;
+                       }
+                       else
+                       {
+                               line.append(cl.substr(start, length - start + 1));
+                       }
                }
-               else
+       
+               if (line.length())
                {
-                       line.append(cl.substr(start, length - start + 1));
+                       ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
                }
        }
 
-       if (line.length())
+       catch (...)
        {
-               this->Write(line);
+               ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
        }
 }
 
@@ -1745,10 +2034,18 @@ void userrec::PurgeEmptyChannels()
                ucrec* uc = *f;
                if (uc->channel)
                {
+                       uc->channel->RemoveAllPrefixes(this);
                        if (uc->channel->DelUser(this) == 0)
                        {
                                /* No users left in here, mark it for deletion */
-                               to_delete.push_back(uc->channel);
+                               try
+                               {
+                                       to_delete.push_back(uc->channel);
+                               }
+                               catch (...)
+                               {
+                                       ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
+                               }
                                uc->channel = NULL;
                        }
                }
@@ -1799,3 +2096,27 @@ void userrec::ShowRULES()
        this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
 }
 
+void userrec::HandleEvent(EventType et, int errornum)
+{
+       /* WARNING: May delete this user! */
+       try
+       {
+               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 */
+                               userrec::QuitUser(ServerInstance, this, errornum ? strerror(errornum) : "EOF from client");
+                       break;
+               }
+       }
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
+       }
+}