]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/users.cpp
Fix server prefix on JOIN.
[user/henk/code/inspircd.git] / src / users.cpp
index 184eef8efce619e9f92be34ccd42209882ff89a3..4a77b450f2422304cbebdcb9dd434595129c9831 100644 (file)
@@ -2,14 +2,11 @@
  *       | Inspire Internet Relay Chat Daemon |
  *       +------------------------------------+
  *
- *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
- *                    E-mail:
- *             <brain@chatspike.net>
- *               <Craig@chatspike.net>
- *     
- * Written by Craig Edwards, Craig McLure, and others.
+ *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
+ * See: http://www.inspircd.org/wiki/index.php/Credits
+ *
  * This program is free but copyrighted software; see
- *         the file COPYING for details.
+ *            the file COPYING for details.
  *
  * ---------------------------------------------------
  */
@@ -61,20 +58,20 @@ bool InitClasses(ServerConfig* conf, const char* tag)
        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();
        
        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();
        
        conf->operclass[ClassName] = strdup(CommandList);
        conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
@@ -156,7 +153,7 @@ void userrec::StartDNSLookup()
                res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), DNS_QUERY_REVERSE);
                this->ServerInstance->AddResolver(res_reverse);
        }
-       catch (ModuleException& e)
+       catch (CoreException& e)
        {
                ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
        }
@@ -189,7 +186,7 @@ void UserResolver::OnLookupComplete(const std::string &result)
                                this->ServerInstance->AddResolver(bound_user->res_forward);
                        }
                }
-               catch (ModuleException& e)
+               catch (CoreException& e)
                {
                        ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
                }
@@ -300,7 +297,7 @@ userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
        age = ServerInstance->Time(true);
        lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
        ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
-       haspassed = dns_done = false;
+       exempt = haspassed = dns_done = false;
        fd = -1;
        recvq = "";
        sendq = "";
@@ -309,28 +306,34 @@ userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
        ip = NULL;
        chans.clear();
        invites.clear();
-       chans.resize(MAXCHANS);
        memset(modes,0,sizeof(modes));
        memset(snomasks,0,sizeof(snomasks));
-       
-       for (unsigned int n = 0; n < MAXCHANS; n++)
-       {
-               chans[n] = new ucrec();
-               chans[n]->channel = NULL;
-               chans[n]->uc_modes = 0;
-       }
 }
 
 userrec::~userrec()
 {
-       for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
-       {
-               ucrec* x = (ucrec*)*n;
-               delete x;
-       }
-
        if (ip)
        {
+               clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
+               if (x != ServerInstance->local_clones.end())
+               {
+                       x->second--;
+                       if (!x->second)
+                       {
+                               ServerInstance->local_clones.erase(x);
+                       }
+               }
+       
+               clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
+               if (y != ServerInstance->global_clones.end())
+               {
+                       y->second--;
+                       if (!y->second)
+                       {
+                               ServerInstance->global_clones.erase(y);
+                       }
+               }
+
                if (this->GetProtocolFamily() == AF_INET)
                {
                        delete (sockaddr_in*)ip;
@@ -433,13 +436,11 @@ char* userrec::GetFullRealHost()
        return fresult;
 }
 
-bool userrec::IsInvited(irc::string &channel)
+bool userrec::IsInvited(const irc::string &channel)
 {
        for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
        {
-               irc::string compare = i->channel;
-               
-               if (compare == channel)
+               if (channel == *i)
                {
                        return true;
                }
@@ -452,30 +453,22 @@ InvitedList* userrec::GetInviteList()
        return &invites;
 }
 
-void userrec::InviteTo(irc::string &channel)
+void userrec::InviteTo(const irc::string &channel)
 {
-       Invited i;
-       i.channel = channel;
-       invites.push_back(i);
+       invites.push_back(channel);
 }
 
-void userrec::RemoveInvite(irc::string &channel)
+void userrec::RemoveInvite(const irc::string &channel)
 {
        ServerInstance->Log(DEBUG,"Removing invites");
-       
-       if (invites.size())
+       for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
        {
-               for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
+               if (channel == *i)
                {
-                       irc::string compare = i->channel;
-                       
-                       if (compare == channel)
-                       {
-                               invites.erase(i);
-                               return;
-                               }
-                       }
-               }
+                       invites.erase(i);
+                       return;
+               }
+       }
 }
 
 bool userrec::HasPermission(const std::string &command)
@@ -633,16 +626,9 @@ void userrec::AddWriteBuf(const std::string &data)
        try 
        {
                if (data.length() > 512)
-               {
-                       std::string newdata(data);
-                       newdata.resize(510);
-                       newdata.append("\r\n");
-                       sendq.append(newdata);
-               }
+                       sendq.append(data.substr(0,510)).append("\r\n");
                else
-               {
                        sendq.append(data);
-               }
        }
        catch (...)
        {
@@ -663,25 +649,31 @@ void userrec::FlushWriteBuf()
                if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
                {
                        int old_sendq_length = sendq.length();
-                       const char* tb = this->sendq.c_str();
-                       int n_sent = write(this->fd,tb,this->sendq.length());
+                       int n_sent = write(this->fd, this->sendq.data(), this->sendq.length());
                        if (n_sent == -1)
                        {
                                if (errno == EAGAIN)
                                {
+                                       /* The socket buffer is full. This isnt fatal,
+                                        * try again later.
+                                        */
                                        ServerInstance->Log(DEBUG,"EAGAIN, want write");
                                        this->ServerInstance->SE->WantWrite(this);
                                }
                                else
+                               {
+                                       /* Fatal error, set write error and bail
+                                        */
                                        this->SetWriteError(strerror(errno));
+                                       return;
+                               }
                        }
                        else
                        {
-                               /*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
+                               /* advance the queue */
+                               if (n_sent)
+                                       this->sendq = this->sendq.substr(n_sent);
+                               /* update the user's stats counters */
                                this->bytes_out += n_sent;
                                this->cmds_out++;
                                if (n_sent != old_sendq_length)
@@ -703,9 +695,8 @@ void userrec::SetWriteError(const std::string &error)
 {
        try
        {
-               ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
                // don't try to set the error twice, its already set take the first string.
-               if (!this->WriteError.length())
+               if (this->WriteError.empty())
                {
                        ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
                        this->WriteError = error;
@@ -777,18 +768,19 @@ void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &qui
                reason.resize(MAXQUIT - 1);
        
        if (IS_LOCAL(user))
+       {
                user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
+               if ((!user->sendq.empty()) && (!(*user->GetWriteError())))
+                       user->FlushWriteBuf();
+       }
 
        if (user->registered == REG_ALL)
        {
                user->PurgeEmptyChannels();
-               FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
                user->WriteCommonExcept("QUIT :%s",reason.c_str());
+               FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
        }
 
-       if (IS_LOCAL(user))
-               user->FlushWriteBuf();
-
        FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
 
        if (IS_LOCAL(user))
@@ -799,9 +791,9 @@ void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &qui
                        {
                                Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
                        }
-                       catch (ModuleException& modexcept)
+                       catch (CoreException& modexcept)
                        {
-                               Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
+                               Instance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
                        }
                }
                
@@ -888,7 +880,8 @@ namespace irc
 
                        int groupcount = ServerInstance->whowas.size();
                        /* iterate whowas_fifo oldest first */
-                       for (whowas_users_fifo::iterator iter = ServerInstance->whowas_fifo.begin(); iter != ServerInstance->whowas_fifo.end(); iter++)
+                       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
@@ -907,7 +900,10 @@ namespace irc
                                                }
                                        }
                                        ServerInstance->whowas.erase(iter->second);
-                                       ServerInstance->whowas_fifo.erase(iter->first);
+                                       /* 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 */
@@ -1003,7 +999,7 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        }
 
        Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
-       
+
        New = new userrec(Instance);
        Instance->clientlist[tempnick] = New;
        New->fd = socket;
@@ -1017,16 +1013,15 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        New->signon = Instance->Time() + Instance->Config->dns_timeout;
        New->lastping = 1;
 
-       Instance->Log(DEBUG,"Setting socket addresses");
        New->SetSockAddr(AF_FAMILY, ipaddr, port);
-       Instance->Log(DEBUG,"Socket addresses set.");
 
        /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
        for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
                New->dhost[j] = New->host[j] = *temp;
        New->dhost[j] = New->host[j] = 0;
-       
-       Instance->Log(DEBUG,"Hosts set.");
+
+       Instance->AddLocalClone(New);
+       Instance->AddGlobalClone(New);
 
        // set the registration timeout for this user
        unsigned long class_regtimeout = 90;
@@ -1035,8 +1030,6 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        long class_sqmax = 262144;      // 256kb
        long class_rqmax = 4096;        // 4k
 
-       Instance->Log(DEBUG,"Class stuff set.");
-
        for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
        {
                if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
@@ -1051,8 +1044,6 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
                }
        }
 
-       Instance->Log(DEBUG,"nping etc set.");
-
        New->nping = Instance->Time() + New->pingmax + Instance->Config->dns_timeout;
        New->timeout = Instance->Time() + class_regtimeout;
        New->flood = class_flood;
@@ -1060,20 +1051,15 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
        New->sendqmax = class_sqmax;
        New->recvqmax = class_rqmax;
 
-       Instance->Log(DEBUG,"Push back to local users.");
        Instance->local_users.push_back(New);
 
-       Instance->Log(DEBUG,"Check softlimit: %d %d %d",Instance->local_users.size(), Instance->Config->SoftLimit, MAXCLIENTS);
        if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
        {
-               Instance->Log(DEBUG,"Check softlimit failed");
                Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
                userrec::QuitUser(Instance, New,"No more connections allowed");
                return;
        }
 
-       Instance->Log(DEBUG,"Softlimit passed.");
-
        /*
         * XXX -
         * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
@@ -1090,78 +1076,50 @@ void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached,
                return;
        }
 
-       Instance->Log(DEBUG,"socket < MAX_DESCRIPTORS passed.");
-
-       ELine* e = Instance->XLines->matches_exception(New);
-       if (!e)
+       New->exempt = (Instance->XLines->matches_exception(New) != NULL);
+       if (!New->exempt)
        {
-               Instance->Log(DEBUG,"Doesnt match eline.");
                ZLine* r = Instance->XLines->matches_zline(ipaddr);
                if (r)
                {
-                       Instance->Log(DEBUG,"Matches zline.");
                        char reason[MAXBUF];
                        snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
                        userrec::QuitUser(Instance, New, reason);
                        return;
                }
-               Instance->Log(DEBUG,"Doesnt match zline.");
        }
 
-       Instance->Log(DEBUG,"Check before AddFd.");
-
        if (socket > -1)
        {
-               Instance->Log(DEBUG,"Adding fd.");
                if (!Instance->SE->AddFd(New))
                {
-                       Instance->Log(DEBUG,"Oops, fd already exists");
                        userrec::QuitUser(Instance, New, "Internal error handling connection");
                        return;
                }
        }
 
+       /* 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 u2[128];
-       long x = 0;
-       strlcpy(u2, this->GetIPString(), 64);
-
-       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(), u2) == 0)
-                       x++;
-       }
-
-       return x;
+       clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
+       if (x != ServerInstance->global_clones.end())
+               return x->second;
+       else
+               return 0;
 }
 
 long userrec::LocalCloneCount()
 {
-       long x = 0;
-       for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
-       {
-               userrec* comp = *a;
-#ifdef IPV6
-               /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
-               in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
-               in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
-               if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
-                       x++;
-#else
-               in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
-               in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
-               if (s1->s_addr == s2->s_addr)
-                       x++;
-#endif
-       }
-       return x;
+       clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
+       if (x != ServerInstance->local_clones.end())
+               return x->second;
+       else
+               return 0;
 }
 
 void userrec::FullConnect(CullList* Goners)
@@ -1196,9 +1154,7 @@ void userrec::FullConnect(CullList* Goners)
                return;
        }
 
-       ELine* e = ServerInstance->XLines->matches_exception(this);
-
-       if (!e)
+       if (!this->exempt)
        {
                GLine* r = ServerInstance->XLines->matches_gline(this);
                
@@ -1228,27 +1184,8 @@ void userrec::FullConnect(CullList* Goners)
        this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
        this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
 
-       // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
-       // so i'd better split it :)
-       std::stringstream out(ServerInstance->Config->data005);
-       std::string token = "";
-       std::string line5 = "";
-       int token_counter = 0;
-       
-       while (!out.eof())
-       {
-               out >> token;
-               line5 = line5 + token + " ";
-               token_counter++;
-               
-               if ((token_counter >= 13) || (out.eof() == true))
-               {
-                       this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
-                       line5 = "";
-                       token_counter = 0;
-               }
-       }
-       
+       ServerInstance->Config->Send005(this);
+
        this->ShowMOTD();
 
        /*
@@ -1385,7 +1322,6 @@ int userrec::GetPort()
                }
                break;
                default:
-                       ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
                break;
        }
        return 0;
@@ -1435,7 +1371,6 @@ const char* userrec::GetIPString()
                }
                break;
                default:
-                       ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
                break;
        }
        return "";
@@ -1478,7 +1413,6 @@ const char* userrec::GetIPString(char* buf)
                break;
 
                default:
-                       ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
                break;
        }
        return "";
@@ -1511,9 +1445,9 @@ void userrec::Write(std::string text)
                {
                        ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
                }
-               catch (ModuleException& modexcept)
+               catch (CoreException& modexcept)
                {
-                       ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
+                       ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
                }
        }
        else
@@ -1633,21 +1567,16 @@ void userrec::WriteCommon(const std::string &text)
        
                uniq_id++;
        
-               for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
+               for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
                {
-                       ucrec *n = *v;
-                       if (n->channel)
+                       CUList* ulist = v->first->GetUsers();
+                       for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
                        {
-                               CUList *ulist= n->channel->GetUsers();
-               
-                               for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
+                               if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
                                {
-                                       if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
-                                       {
-                                               already_sent[i->second->fd] = uniq_id;
-                                               i->second->WriteFrom(this, std::string(text));
-                                               sent_to_at_least_one = true;
-                                       }
+                                       already_sent[i->second->fd] = uniq_id;
+                                       i->second->WriteFrom(this, std::string(text));
+                                       sent_to_at_least_one = true;
                                }
                        }
                }
@@ -1736,25 +1665,20 @@ void userrec::WriteCommonExcept(const std::string &text)
                }
        }
 
-       for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
+       for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
        {
-               ucrec* n = *v;
-               if (n->channel)
+               CUList *ulist = v->first->GetUsers();
+               for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
                {
-                       CUList *ulist= n->channel->GetUsers();
-
-                       for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
+                       if (this != i->second)
                        {
-                               if (this != i->second)
+                               if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
                                {
-                                       if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
-                                       {
-                                               already_sent[i->second->fd] = uniq_id;
-                                               if (quit_munge)
-                                                       i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
-                                               else
-                                                       i->second->WriteFrom(this, std::string(textbuffer));
-                                       }
+                                       already_sent[i->second->fd] = uniq_id;
+                                       if (quit_munge)
+                                               i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
+                                       else
+                                               i->second->WriteFrom(this, std::string(textbuffer));
                                }
                        }
                }
@@ -1818,33 +1742,17 @@ bool userrec::SharesChannelWith(userrec *other)
                return false;
 
        /* Outer loop */
-       for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+       for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
        {
-               /* Fetch the channel from the user */
-               ucrec* user_channel = *i;
-
-               if (user_channel->channel)
-               {
-                       /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
-                        * by replacing it with a map::find which *should* be more efficient
-                        */
-                       if (user_channel->channel->HasUser(other))
-                               return true;
-               }
+               /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
+                * by replacing it with a map::find which *should* be more efficient
+                */
+               if (i->first->HasUser(other))
+                       return true;
        }
        return false;
 }
 
-int userrec::CountChannels()
-{
-       return ChannelCount;
-}
-
-void userrec::ModChannelCount(int n)
-{
-       ChannelCount += n;
-}
-
 bool userrec::ChangeName(const char* gecos)
 {
        if (!strcmp(gecos, this->fullname))
@@ -1876,22 +1784,19 @@ bool userrec::ChangeDisplayedHost(const char* host)
                FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
        }
        if (this->ServerInstance->Config->CycleHosts)
-               this->WriteCommonExcept("%s","QUIT :Changing hosts");
+               this->WriteCommonExcept("QUIT :Changing hosts");
 
        /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
        strlcpy(this->dhost,host,64);
 
        if (this->ServerInstance->Config->CycleHosts)
        {
-               for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+               for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
                {
-                       if ((*i)->channel)
-                       {
-                               (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
-                               std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
-                               if (n.length() > 0)
-                                       (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
-                       }
+                       i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
+                       std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
+                       if (n.length() > 0)
+                               i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
                }
        }
 
@@ -1913,15 +1818,12 @@ bool userrec::ChangeIdent(const char* newident)
 
        if (this->ServerInstance->Config->CycleHosts)
        {
-               for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+               for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
                {
-                       if ((*i)->channel)
-                       {
-                               (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
-                               std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
-                               if (n.length() > 0)
-                                       (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
-                       }
+                       i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
+                       std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
+                       if (n.length() > 0)
+                               i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
                }
        }
 
@@ -1953,20 +1855,15 @@ std::string userrec::ChannelList(userrec* source)
        try
        {
                std::string list;
-               for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
+               for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
                {
-                       ucrec* rec = *i;
-       
-                       if(rec->channel && rec->channel->name)
+                       /* If the target is the same as the sender, let them see all their channels.
+                        * If the channel is NOT private/secret OR the user shares a common channel
+                        * If the user is an oper, and the <options:operspywhois> option is set.
+                        */
+                       if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
                        {
-                               /* If the target is the same as the sender, let them see all their channels.
-                                * If the channel is NOT private/secret OR the user shares a common channel
-                                * If the user is an oper, and the <options:operspywhois> option is set.
-                                */
-                               if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
-                               {
-                                       list.append(rec->channel->GetPrefixChar(this)).append(rec->channel->name).append(" ");
-                               }
+                               list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
                        }
                }
                return list;
@@ -1996,7 +1893,7 @@ void userrec::SplitChanList(userrec* dest, const std::string &cl)
        
                        if (line.length() + namelen + length - start > 510)
                        {
-                               this->Write(line);
+                               ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
                                line = prefix.str();
                        }
        
@@ -2045,24 +1942,19 @@ void userrec::PurgeEmptyChannels()
        std::vector<chanrec*> to_delete;
 
        // firstly decrement the count on each channel
-       for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
+       for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
        {
-               ucrec* uc = *f;
-               if (uc->channel)
+               f->first->RemoveAllPrefixes(this);
+               if (f->first->DelUser(this) == 0)
                {
-                       uc->channel->RemoveAllPrefixes(this);
-                       if (uc->channel->DelUser(this) == 0)
+                       /* No users left in here, mark it for deletion */
+                       try
                        {
-                               /* No users left in here, mark it for deletion */
-                               try
-                               {
-                                       to_delete.push_back(uc->channel);
-                               }
-                               catch (...)
-                               {
-                                       ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
-                               }
-                               uc->channel = NULL;
+                               to_delete.push_back(f->first);
+                       }
+                       catch (...)
+                       {
+                               ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
                        }
                }
        }
@@ -2091,8 +1983,8 @@ void userrec::ShowMOTD()
        }
        this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
 
-       for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
-               this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
+       for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
+               this->WriteServ("372 %s :- %s",this->nick,i->c_str());
 
        this->WriteServ("376 %s :End of message of the day.", this->nick);
 }
@@ -2106,8 +1998,8 @@ void userrec::ShowRULES()
        }
        this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
 
-       for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
-               this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
+       for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
+               this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
 
        this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
 }
@@ -2121,11 +2013,13 @@ void userrec::HandleEvent(EventType et, int errornum)
                {
                        case EVENT_READ:
                                ServerInstance->ProcessUser(this);
+
                        break;
                        case EVENT_WRITE:
                                this->FlushWriteBuf();
                        break;
                        case EVENT_ERROR:
+                               /** This should be safe, but dont DARE do anything after it -- Brain */
                                this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
                        break;
                }
@@ -2134,4 +2028,11 @@ void userrec::HandleEvent(EventType et, int errornum)
        {
                ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
        }
+
+       /* If the user has raised an error whilst being processed, quit them now we're safe to */
+       if (!WriteError.empty())
+       {
+               userrec::QuitUser(ServerInstance, this, GetWriteError());
+       }
 }
+