]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/users.cpp
Annotations
[user/henk/code/inspircd.git] / src / users.cpp
index 84bdbb9d6f8509d2b60f1a21c323a811beeea799..8c6711d64e6807ecca69a5597c24b551cd9a9236 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"
@@ -92,31 +85,47 @@ 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;
                        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()
@@ -138,26 +147,30 @@ UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_res
        Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
 {
        this->fwd = forward;
-       this->bound_fd = user->fd;
+       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;
                try
                {
-                       bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
-                       this->ServerInstance->AddResolver(bound_user->res_forward);
+                       /* 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);
+                               this->ServerInstance->AddResolver(bound_user->res_forward);
+                       }
                }
                catch (ModuleException& e)
                {
                        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)
@@ -165,14 +178,18 @@ void UserResolver::OnLookupComplete(const std::string &result)
                        std::string hostname = this->bound_user->stored_host;
                        if (hostname.length() < 65)
                        {
-                               /* Hostnames starting with : are not a good thing (tm) */
-                               if (*(hostname.c_str()) == ':')
-                                       hostname = "0" + hostname;
-
-                               this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
-                               this->bound_user->dns_done = true;
-                               strlcpy(this->bound_user->dhost, hostname.c_str(),64);
-                               strlcpy(this->bound_user->host, hostname.c_str(),64);
+                               /* Check we didnt time out */
+                               if (this->bound_user->registered != REG_ALL)
+                               {
+                                       /* Hostnames starting with : are not a good thing (tm) */
+                                       if (*(hostname.c_str()) == ':')
+                                               hostname = "0" + hostname;
+
+                                       this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
+                                       this->bound_user->dns_done = true;
+                                       strlcpy(this->bound_user->dhost, hostname.c_str(),64);
+                                       strlcpy(this->bound_user->host, hostname.c_str(),64);
+                               }
                        }
                        else
                        {
@@ -188,7 +205,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());
@@ -254,9 +271,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();
-       lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
-       timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
+       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;
+       fd = -1;
        recvq = "";
        sendq = "";
        WriteError = "";
@@ -266,6 +284,7 @@ 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++)
        {
@@ -469,31 +488,42 @@ bool userrec::HasPermission(const std::string &command)
        return false;
 }
 
-
-bool userrec::AddBuffer(const std::string &a)
+/** NOTE: We cannot pass a const reference to this method.
+ * The string is changed by the workings of the method,
+ * so that if we pass const ref, we end up copying it to
+ * something we can change anyway. Makes sense to just let
+ * the compiler do that copy for us.
+ */
+bool userrec::AddBuffer(std::string a)
 {
-       std::string b = "";
-
-       /* NB: std::string is arsey about \r and \n and tries to translate them
-        * somehow, so we CANNOT use std::string::find() here :(
-        */
-       for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
+       try
        {
-               if (*i != '\r')
-                       b += *i;
-       }
+               std::string::size_type i = a.rfind('\r');
+       
+               while (i != std::string::npos)
+               {
+                       a.erase(i, 1);
+                       i = a.rfind('\r');
+               }
 
-       if (b.length())
-               recvq.append(b);
+               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()
@@ -508,29 +538,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)
@@ -549,52 +588,80 @@ 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)
                {
-                       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++;
+                       const char* tb = this->sendq.c_str();
+                               int n_sent = write(this->fd,tb,this->sendq.length());
+                       if (n_sent == -1)
+                       {
+                               if (errno != EAGAIN)
+                                       this->SetWriteError(strerror(errno));
+                       }
+                       else
+                       {
+                               // advance the queue
+                               tb += n_sent;
+                               this->sendq = tb;
+                               // update the user's stats counters
+                               this->bytes_out += n_sent;
+                               this->cmds_out++;
+                       }
                }
        }
+
+       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()");
        }
 }
 
@@ -605,31 +672,47 @@ 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)
@@ -680,22 +763,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();
        }
 
@@ -704,7 +785,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));
                }
@@ -864,7 +944,6 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        _new->sendqmax = class_sqmax;
        _new->recvqmax = class_rqmax;
 
-       Instance->fd_ref_table[socket] = _new;
        Instance->local_users.push_back(_new);
 
        if (Instance->local_users.size() > Instance->Config->SoftLimit)
@@ -894,7 +973,7 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
                userrec::QuitUser(Instance, _new,"Server is full");
                return;
        }
-       char* e = Instance->XLines->matches_exception(ipaddr);
+       char* e = Instance->XLines->matches_exception(_new);
        if (!e)
        {
                char* r = Instance->XLines->matches_zline(ipaddr);
@@ -909,7 +988,7 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
 
        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");
                        return;
@@ -921,8 +1000,8 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
 
 long userrec::GlobalCloneCount()
 {
-       char u1[1024];
-       char u2[1024];
+       char u1[1024] = {0};
+       char u2[1024] = {0};
        long x = 0;
        for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
        {
@@ -989,13 +1068,11 @@ 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);
+       char* e = ServerInstance->XLines->matches_exception(this);
 
        if (!e)
        {
-               char* r = ServerInstance->XLines->matches_gline(match_against);
+               char* r = ServerInstance->XLines->matches_gline(this);
                
                if (r)
                {
@@ -1005,7 +1082,7 @@ void userrec::FullConnect(CullList* Goners)
                        return;
                }
                
-               r = ServerInstance->XLines->matches_kline(match_against);
+               r = ServerInstance->XLines->matches_kline(this);
                
                if (r)
                {
@@ -1051,9 +1128,9 @@ 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));
+       FOREACH_MOD(I_OnPostConnect,OnPostConnect(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());
+       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()
@@ -1062,54 +1139,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)
@@ -1184,7 +1272,6 @@ int userrec::GetProtocolFamily()
 const char* userrec::GetIPString()
 {
        static char buf[1024];
-       static char temp[1024];
 
        if (this->ip == NULL)
                return "";
@@ -1194,6 +1281,8 @@ 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) */
@@ -1223,8 +1312,6 @@ const char* userrec::GetIPString()
 
 const char* userrec::GetIPString(char* buf)
 {
-       static char temp[1024];
-
        if (this->ip == NULL)
        {
                *buf = 0;
@@ -1236,6 +1323,8 @@ 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) */
@@ -1264,20 +1353,32 @@ const char* userrec::GetIPString(char* buf)
        return "";
 }
 
-
-void userrec::Write(const std::string &text)
+/** NOTE: We cannot pass a const reference to this method.
+ * The string is changed by the workings of the method,
+ * so that if we pass const ref, we end up copying it to
+ * something we can change anyway. Makes sense to just let
+ * the compiler do that copy for us.
+ */
+void userrec::Write(std::string text)
 {
        if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
                return;
 
-       std::string crlf = text;
-       crlf.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()))
        {
                try
                {
-                       ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, crlf.data(), crlf.length());
+                       ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
                }
                catch (ModuleException& modexcept)
                {
@@ -1286,9 +1387,9 @@ void userrec::Write(const std::string &text)
        }
        else
        {
-               this->AddWriteBuf(crlf);
+               this->AddWriteBuf(text);
        }
-       ServerInstance->stats->statsSent += crlf.length();
+       ServerInstance->stats->statsSent += text.length();
 }
 
 /** Write()
@@ -1391,39 +1492,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()");
        }
 }
 
@@ -1446,7 +1555,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];
 
@@ -1528,7 +1637,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++)
        {
@@ -1587,15 +1705,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;
@@ -1610,6 +1732,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;
@@ -1618,14 +1743,58 @@ bool userrec::ChangeDisplayedHost(const char* host)
                        return false;
                FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
        }
+       if (this->ServerInstance->Config->CycleHosts)
+               this->WriteCommonExcept("%s","QUIT :Changing hosts");
+
        strlcpy(this->dhost,host,63);
 
+       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);
 
        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];
@@ -1648,24 +1817,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)
@@ -1674,33 +1851,41 @@ 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 << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
+               line = prefix.str();
+       
+               for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
                {
-                       line += cl.substr(start, length - start);
-                       break;
+                       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)
+                       {
+                               line.append(cl.substr(start, length - start));
+                               break;
+                       }
+                       else
+                       {
+                               line.append(cl.substr(start, length - start + 1));
+                       }
                }
-               else
+       
+               if (line.length())
                {
-                       line += cl.substr(start, length - start + 1);
+                       this->Write(line);
                }
        }
 
-       if (line.length())
+       catch (...)
        {
-               this->Write(line);
+               ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
        }
 }
 
@@ -1731,10 +1916,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;
                        }
                }
@@ -1785,3 +1978,16 @@ void userrec::ShowRULES()
        this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
 }
 
+void userrec::HandleEvent(EventType et)
+{
+       /* WARNING: May delete this user! */
+       try
+       {
+               ServerInstance->ProcessUser(this);
+       }
+       catch (...)
+       {
+               ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
+       }
+}
+