]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/modules/m_spanningtree.cpp
Added the send_push event to m_spanningtree (send raw text to a remote user)
[user/henk/code/inspircd.git] / src / modules / m_spanningtree.cpp
index 2592d2a8431d10dcc315b34db40515032381d101..7d034c17ce263f7986cb93d57f17af56223949c7 100644 (file)
@@ -16,8 +16,6 @@
 
 /* $ModDesc: Povides a spanning tree server link protocol */
 
-using namespace std;
-
 #include "configreader.h"
 #include "users.h"
 #include "channels.h"
@@ -28,7 +26,6 @@ using namespace std;
 #include "inspircd.h"
 #include "wildcard.h"
 #include "xline.h"
-#include "cull_list.h"
 #include "aes.h"
 
 /** If you make a change which breaks the protocol, increment this.
@@ -55,14 +52,7 @@ const long ProtocolVersion = 1101;
  * any O(n) lookups. If however, during a split or sync, we want
  * to apply an operation to a server, and any of its child objects
  * we can resort to recursion to walk the tree structure.
- */
-
-using irc::sockets::MatchCIDR;
-
-class ModuleSpanningTree;
-static ModuleSpanningTree* TreeProtocolModule;
-
-/** Any socket can have one of five states at any one time.
+ * Any socket can have one of five states at any one time.
  * The LISTENER state indicates a socket which is listening
  * for connections. It cannot receive data itself, only incoming
  * sockets.
@@ -82,15 +72,36 @@ enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
 /* Foward declarations */
 class TreeServer;
 class TreeSocket;
+class Link;
+class ModuleSpanningTree;
 
 /* This hash_map holds the hash equivalent of the server
  * tree, used for rapid linear lookups.
  */
 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
-server_hash serverlist;
 
-typedef nspace::hash_map<std::string, userrec*> uid_hash;
-typedef nspace::hash_map<std::string, char*> sid_hash;
+
+/** The Link class might as well be a struct,
+ * but this is C++ and we don't believe in structs (!).
+ * It holds the entire information of one <link>
+ * tag from the main config file. We maintain a list
+ * of them, and populate the list on rehash/load.
+ */
+class Link : public classbase
+{
+ public:
+       irc::string Name;
+       std::string IPAddr;
+       int Port;
+       std::string SendPass;
+       std::string RecvPass;
+       unsigned long AutoConnect;
+       time_t NextConnectTime;
+       std::string EncryptionKey;
+       bool HiddenFromStats;
+       std::string FailOver;
+       int Timeout;
+};
 
 /** Contains helper functions and variables for this module,
  * and keeps them out of the global namespace
@@ -98,84 +109,89 @@ typedef nspace::hash_map<std::string, char*> sid_hash;
 class SpanningTreeUtilities
 {
  private:
+       /** Creator server
+        */
        InspIRCd* ServerInstance;
  public:
-       bool FlatLinks; /* Flatten links and /MAP for non-opers */
-       bool HideULines; /* Hide U-Lined servers in /MAP and /LINKS */
-       bool AnnounceTSChange; /* Announce TS changes to channels on merge */
-       std::vector<TreeSocket*> Bindings; /* Socket bindings */
-       /* This variable represents the root of the server tree
-        * (for all intents and purposes, it's us)
+       /** Creator module
+        */
+       ModuleSpanningTree* Creator;
+       /** Flatten links and /MAP for non-opers
+        */
+       bool FlatLinks;
+       /** Hide U-Lined servers in /MAP and /LINKS
+        */
+       bool HideULines;
+       /** Announce TS changes to channels on merge
+        */
+       bool AnnounceTSChange;
+       /** Socket bindings for listening sockets
+        */
+       std::vector<TreeSocket*> Bindings;
+       /** This variable represents the root of the server tree
         */
        TreeServer *TreeRoot;
+       /** IPs allowed to link to us
+        */
+       std::vector<std::string> ValidIPs;
+       /** Hash of currently connected servers by name
+        */
+       server_hash serverlist;
+       /** Holds the data from the <link> tags in the conf
+        */
+       std::vector<Link> LinkBlocks;
 
-       SpanningTreeUtilities(InspIRCd* Instance);
+       /** Initialise utility class
+        */
+       SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator);
+       /** Destroy class and free listeners etc
+        */
        ~SpanningTreeUtilities();
-       bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target);
-       bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit);
+       /** Send a message from this server to one other local or remote
+        */
+       bool DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target);
+       /** Send a message from this server to all but one other, local or remote
+        */
+       bool DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string omit);
+       /** Send a message from this server to all but one other, local or remote
+        */
        bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit);
-       bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params);
+       /** Send a message from this server to all others
+        */
+       bool DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params);
+       /** Send a message from this server to all others
+        */
        bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params);
-       bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params);
+       /** Send a message from this server to all others, without doing any processing on the command (e.g. send it as-is with colons and all)
+        */
+       bool DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> &params);
+       /** Read the spanningtree module's tags from the config file
+        */
        void ReadConfiguration(bool rebind);
+       /** Add a server to the server list for GetListOfServersForChannel
+        */
        void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list);
+       /** Compile a list of servers which contain members of channel c
+        */
        void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list);
-       TreeServer* FindServer(std::string ServerName);
-       TreeServer* BestRouteTo(std::string ServerName);
-       TreeServer* FindServerMask(std::string ServerName);
-       bool IsServer(std::string ServerName);
-};
-
-
-std::vector<std::string> ValidIPs;
-
-/** This will be used in a future version of InspIRCd for UID support
- */
-class UserManager : public classbase
-{
-       uid_hash uids;
-       sid_hash sids;
- public:
-       UserManager()
-       {
-               uids.clear();
-               sids.clear();
-       }
-
-       std::string UserToUID(userrec* user)
-       {
-               return "";
-       }
-
-       std::string UIDToUser(const std::string &UID)
-       {
-               return "";
-       }
-
-       std::string CreateAndAdd(userrec* user)
-       {
-               return "";
-       }
-
-       std::string CreateAndAdd(const std::string &servername)
-       {
-               return "";
-       }
-
-       std::string ServerToSID(const std::string &servername)
-       {
-               return "";
-       }
-
-       std::string SIDToServer(const std::string &SID)
-       {
-               return "";
-       }
-
-       userrec* FindByID(const std::string &UID)
-       {
-               return NULL;
-       }
+       /** Find a server by name
+        */
+       TreeServer* FindServer(const std::string &ServerName);
+       /** Find a route to a server by name
+        */
+       TreeServer* BestRouteTo(const std::string &ServerName);
+       /** Find a server by glob mask
+        */
+       TreeServer* FindServerMask(const std::string &ServerName);
+       /** Returns true if this is a server name we recognise
+        */
+       bool IsServer(const std::string &ServerName);
+       /** Attempt to connect to the failover link of link x
+        */
+       void DoFailOver(Link* x);
+       /** Find a link tag from a server name
+        */
+       Link* FindLink(const std::string& name);
 };
 
 
@@ -196,7 +212,6 @@ class UserManager : public classbase
 class TreeServer : public classbase
 {
        InspIRCd* ServerInstance;               /* Creator */
-       SpanningTreeUtilities* Utils;           /* Utility class */
        TreeServer* Parent;                     /* Parent entry */
        TreeServer* Route;                      /* Route entry */
        std::vector<TreeServer*> Children;      /* List of child objects */
@@ -208,13 +223,14 @@ class TreeServer : public classbase
        TreeSocket* Socket;                     /* For directly connected servers this points at the socket object */
        time_t NextPing;                        /* After this time, the server should be PINGed*/
        bool LastPingWasGood;                   /* True if the server responded to the last PING with a PONG */
+       SpanningTreeUtilities* Utils;           /* Utility class */
        
  public:
 
        /** We don't use this constructor. Its a dummy, and won't cause any insertion
         * of the TreeServer into the hash_map. See below for the two we DO use.
         */
-       TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance) : ServerInstance(Instance)
+       TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance) : ServerInstance(Instance), Utils(Util)
        {
                Parent = NULL;
                ServerName = "";
@@ -228,11 +244,12 @@ class TreeServer : public classbase
         * represents our own server. Therefore, it has no route, no parent, and
         * no socket associated with it. Its version string is our own local version.
         */
-       TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc)
+       TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util)
        {
                Parent = NULL;
                VersionString = "";
-               UserCount = OperCount = 0;
+               UserCount = ServerInstance->UserCount();
+               OperCount = ServerInstance->OperCount();
                VersionString = ServerInstance->GetVersionString();
                Route = NULL;
                Socket = NULL; /* Fix by brain */
@@ -243,8 +260,8 @@ class TreeServer : public classbase
         * This constructor initializes the server's Route and Parent, and sets up
         * its ping counters so that it will be pinged one minute from now.
         */
-       TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
-               : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
+       TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
+               : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util)
        {
                VersionString = "";
                UserCount = OperCount = 0;
@@ -333,10 +350,9 @@ class TreeServer : public classbase
         */
        void AddHashEntry()
        {
-               server_hash::iterator iter;
-               iter = serverlist.find(this->ServerName.c_str());
-               if (iter == serverlist.end())
-                       serverlist[this->ServerName.c_str()] = this;
+               server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
+               if (iter == Utils->serverlist.end())
+                       Utils->serverlist[this->ServerName.c_str()] = this;
        }
 
        /** This method removes the reference to this object
@@ -345,10 +361,9 @@ class TreeServer : public classbase
         */
        void DelHashEntry()
        {
-               server_hash::iterator iter;
-               iter = serverlist.find(this->ServerName.c_str());
-               if (iter != serverlist.end())
-                       serverlist.erase(iter);
+               server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
+               if (iter != Utils->serverlist.end())
+                       Utils->serverlist.erase(iter);
        }
 
        /** These accessors etc should be pretty self-
@@ -425,7 +440,7 @@ class TreeServer : public classbase
                return Parent;
        }
 
-       void SetVersion(std::string Version)
+       void SetVersion(const std::string &Version)
        {
                VersionString = Version;
        }
@@ -500,45 +515,13 @@ class TreeServer : public classbase
        }
 };
 
-/** The Link class might as well be a struct,
- * but this is C++ and we don't believe in structs (!).
- * It holds the entire information of one <link>
- * tag from the main config file. We maintain a list
- * of them, and populate the list on rehash/load.
- */
-class Link : public classbase
-{
- public:
-       irc::string Name;
-       std::string IPAddr;
-       int Port;
-       std::string SendPass;
-       std::string RecvPass;
-       unsigned long AutoConnect;
-       time_t NextConnectTime;
-       std::string EncryptionKey;
-       bool HiddenFromStats;
-       irc::string FailOver;
-};
-
-void DoFailOver(Link* x);
-Link* FindLink(const std::string& name);
-
-/* The usual stuff for inspircd modules,
- * plus the vector of Link classes which we
- * use to store the <link> tags from the config
- * file.
- */
-ConfigReader *Conf;
-std::vector<Link> LinkBlocks;
-
 /** Yay for fast searches!
  * This is hundreds of times faster than recursion
  * or even scanning a linked list, especially when
  * there are more than a few servers to deal with.
  * (read as: lots).
  */
-TreeServer* SpanningTreeUtilities::FindServer(std::string ServerName)
+TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
 {
        server_hash::iterator iter;
        iter = serverlist.find(ServerName.c_str());
@@ -558,7 +541,7 @@ TreeServer* SpanningTreeUtilities::FindServer(std::string ServerName)
  * See the comments for the constructor of TreeServer
  * for more details.
  */
-TreeServer* SpanningTreeUtilities::BestRouteTo(std::string ServerName)
+TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
 {
        if (ServerName.c_str() == TreeRoot->GetName())
                return NULL;
@@ -579,7 +562,7 @@ TreeServer* SpanningTreeUtilities::BestRouteTo(std::string ServerName)
  * and match each one until we get a hit. Yes its slow,
  * deal with it.
  */
-TreeServer* SpanningTreeUtilities::FindServerMask(std::string ServerName)
+TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
 {
        for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
        {
@@ -590,7 +573,7 @@ TreeServer* SpanningTreeUtilities::FindServerMask(std::string ServerName)
 }
 
 /* A convenient wrapper that returns true if a server exists */
-bool SpanningTreeUtilities::IsServer(std::string ServerName)
+bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
 {
        return (FindServer(ServerName) != NULL);
 }
@@ -746,7 +729,7 @@ class TreeSocket : public InspSocket
                if (this->LinkState == CONNECTING)
                {
                        /* we do not need to change state here. */
-                       for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
+                       for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
                        {
                                if (x->Name == this->myhost)
                                {
@@ -788,9 +771,9 @@ class TreeSocket : public InspSocket
                if (e == I_ERR_CONNECT)
                {
                        this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
-                       Link* MyLink = FindLink(myhost);
+                       Link* MyLink = Utils->FindLink(myhost);
                        if (MyLink)
-                               DoFailOver(MyLink);
+                               Utils->DoFailOver(MyLink);
                }
        }
 
@@ -918,7 +901,7 @@ class TreeSocket : public InspSocket
                return result;
        }
 
-       bool Capab(std::deque<std::string> params)
+       bool Capab(const std::deque<std::string> &params)
        {
                if (params.size() < 1)
                {
@@ -1071,10 +1054,13 @@ class TreeSocket : public InspSocket
         * does some validation first and passes on the SQUIT to all
         * other remaining servers.
         */
-       void Squit(TreeServer* Current,std::string reason)
+       void Squit(TreeServer* Current, const std::string &reason)
        {
                if ((Current) && (Current != Utils->TreeRoot))
                {
+                       Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
+                       rmode.Send(Instance);
+
                        std::deque<std::string> params;
                        params.push_back(Current->GetName());
                        params.push_back(":"+reason);
@@ -1103,7 +1089,7 @@ class TreeSocket : public InspSocket
        }
 
        /** FMODE command - server mode with timestamp checks */
-       bool ForceMode(std::string source, std::deque<std::string> &params)
+       bool ForceMode(const std::string &source, std::deque<std::string> &params)
        {
                /* Chances are this is a 1.0 FMODE without TS */
                if (params.size() < 3)
@@ -1491,7 +1477,7 @@ class TreeSocket : public InspSocket
        }
 
        /** FTOPIC command */
-       bool ForceTopic(std::string source, std::deque<std::string> &params)
+       bool ForceTopic(const std::string &source, std::deque<std::string> &params)
        {
                if (params.size() != 4)
                        return true;
@@ -1535,7 +1521,7 @@ class TreeSocket : public InspSocket
        }
 
        /** FJOIN, similar to TS6 SJOIN, but not quite. */
-       bool ForceJoin(std::string source, std::deque<std::string> &params)
+       bool ForceJoin(const std::string &source, std::deque<std::string> &params)
        {
                /* 1.1 FJOIN works as follows:
                 *
@@ -1628,7 +1614,7 @@ class TreeSocket : public InspSocket
                        /* Lower the TS here */
                        if (Utils->AnnounceTSChange && chan)
                                chan->WriteChannelWithServ(Instance->Config->ServerName,
-                               "TS for %s changed from %lu to %lu", chan->name, ourTS, TS);
+                               "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
                        ourTS = TS;
 
                        param_list.push_back(channel);
@@ -1813,7 +1799,7 @@ class TreeSocket : public InspSocket
        }
 
        /** NICK command */
-       bool IntroduceClient(std::string source, std::deque<std::string> &params)
+       bool IntroduceClient(const std::string &source, std::deque<std::string> &params)
        {
                if (params.size() < 8)
                        return true;
@@ -1893,6 +1879,8 @@ class TreeSocket : public InspSocket
         */
        void SendFJoins(TreeServer* Current, chanrec* c)
        {
+               std::string buffer;
+
                Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
                char list[MAXBUF];
                std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
@@ -1903,8 +1891,6 @@ class TreeSocket : public InspSocket
                char* ptr = list + dlen;
 
                CUList *ulist = c->GetUsers();
-               std::vector<userrec*> specific_halfop;
-               std::vector<userrec*> specific_voice;
                std::string modes = "";
                std::string params = "";
 
@@ -1920,7 +1906,8 @@ class TreeSocket : public InspSocket
 
                        if (curlen > (480-NICKMAX))
                        {
-                               this->WriteLine(list);
+                               buffer.append(list).append("\r\n");
+
                                dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
                                ptr = list + dlen;
                                ptrlen = 0;
@@ -1929,64 +1916,83 @@ class TreeSocket : public InspSocket
                }
 
                if (numusers)
-                       this->WriteLine(list);
+                       buffer.append(list).append("\r\n");
 
-                for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
-                {
+               for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
+               {
                        modes.append("b");
-                       params.append(b->data).append(" ");
-                }
-               this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+c->ChanModes(true)+modes+" "+params);
+                       params.append(" ").append(b->data);
+
+                       if (params.length() >= MAXMODES)
+                       {
+                               /* Wrap at MAXMODES */
+                               buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params).append("\r\n");
+                               modes = "";
+                               params = "";
+                       }
+               }
+
+               buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
+
+               /* Only send these if there are any */
+               if (!modes.empty())
+                       buffer.append("\r\n").append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
+
+               this->WriteLine(buffer);
        }
 
        /** Send G, Q, Z and E lines */
        void SendXLines(TreeServer* Current)
        {
                char data[MAXBUF];
+               std::string buffer;
                std::string n = this->Instance->Config->ServerName;
                const char* sn = n.c_str();
                int iterations = 0;
                /* Yes, these arent too nice looking, but they get the job done */
                for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
                for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
                for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s\r\n",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
                for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s\r\n",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
                for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
                for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
                for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s\r\n",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
                for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
                {
-                       snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
-                       this->WriteLine(data);
+                       snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s\r\n",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
+                       buffer.append(data);
                }
+
+               if (!buffer.empty())
+                       this->WriteLine(buffer);
        }
 
        /** Send channel modes and topics */
@@ -2005,12 +2011,12 @@ class TreeSocket : public InspSocket
                                snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
                                this->WriteLine(data);
                        }
-                       FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
+                       FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
                        list.clear();
                        c->second->GetExtList(list);
                        for (unsigned int j = 0; j < list.size(); j++)
                        {
-                               FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
+                               FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
                        }
                }
        }
@@ -2020,6 +2026,7 @@ class TreeSocket : public InspSocket
        {
                char data[MAXBUF];
                std::deque<std::string> list;
+               std::string dataline;
                int iterations = 0;
                for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
                {
@@ -2029,18 +2036,20 @@ class TreeSocket : public InspSocket
                                this->WriteLine(data);
                                if (*u->second->oper)
                                {
-                                       this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
+                                       snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
+                                       this->WriteLine(data);
                                }
                                if (*u->second->awaymsg)
                                {
-                                       this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
+                                       snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
+                                       this->WriteLine(data);
                                }
-                               FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
+                               FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
                                list.clear();
                                u->second->GetExtList(list);
                                for (unsigned int j = 0; j < list.size(); j++)
                                {
-                                       FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
+                                       FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
                                }
                        }
                }
@@ -2068,7 +2077,7 @@ class TreeSocket : public InspSocket
                /* Send everything else (channel modes, xlines etc) */
                this->SendChannelModes(s);
                this->SendXLines(s);            
-               FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
+               FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
                this->WriteLine(endburst);
                this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
        }
@@ -2095,6 +2104,10 @@ class TreeSocket : public InspSocket
                        {
                                std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
                                in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
+                               /* Use rfind here not find, as theres more
+                                * chance of the \r being near the end of the
+                                * string, not the start.
+                                */
                                if (ret.find("\r") != std::string::npos)
                                        ret = in_buffer.substr(0,in_buffer.find("\r")-1);
                                /* Process this one, abort if it
@@ -2114,14 +2127,22 @@ class TreeSocket : public InspSocket
                                                {
                                                        ctx_in->Decrypt(out, result, nbytes, 0);
                                                        for (int t = 0; t < nbytes; t++)
-                                                               if (result[t] == '\7') result[t] = 0;
+                                                       {
+                                                               if (result[t] == '\7')
+                                                               {
+                                                                       /* We only need to stick a \0 on the
+                                                                        * first \7, the rest will be lost
+                                                                        */
+                                                                       result[t] = 0;
+                                                                       break;
+                                                               }
+                                                       }
                                                        ret = result;
                                                }
                                        }
                                }
                                if (!this->ProcessLine(ret))
                                {
-                                       Instance->Log(DEBUG,"ProcessLine says no!");
                                        return false;
                                }
                        }
@@ -2152,7 +2173,8 @@ class TreeSocket : public InspSocket
                        to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
                        line = result64;
                }
-               return this->Write(line + "\r\n");
+               line.append("\r\n");
+               return this->Write(line);
        }
 
        /* Handle ERROR command */
@@ -2166,7 +2188,7 @@ class TreeSocket : public InspSocket
        }
 
        /** remote MOTD. leet, huh? */
-       bool Motd(std::string prefix, std::deque<std::string> &params)
+       bool Motd(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() > 0)
                {
@@ -2214,7 +2236,7 @@ class TreeSocket : public InspSocket
        }
 
        /** remote ADMIN. leet, huh? */
-       bool Admin(std::string prefix, std::deque<std::string> &params)
+       bool Admin(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() > 0)
                {
@@ -2254,7 +2276,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool Stats(std::string prefix, std::deque<std::string> &params)
+       bool Stats(const std::string &prefix, std::deque<std::string> &params)
        {
                /* Get the reply to a STATS query if it matches this servername,
                 * and send it back as a load of PUSH queries
@@ -2294,7 +2316,7 @@ class TreeSocket : public InspSocket
        /** Because the core won't let users or even SERVERS set +o,
         * we use the OPERTYPE command to do this.
         */
-       bool OperType(std::string prefix, std::deque<std::string> &params)
+       bool OperType(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() != 1)
                {
@@ -2315,7 +2337,7 @@ class TreeSocket : public InspSocket
        /** Because Andy insists that services-compatible servers must
         * implement SVSNICK and SVSJOIN, that's exactly what we do :p
         */
-       bool ForceNick(std::string prefix, std::deque<std::string> &params)
+       bool ForceNick(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 3)
                        return true;
@@ -2343,7 +2365,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
+       bool ServiceJoin(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 2)
                        return true;
@@ -2358,7 +2380,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
+       bool RemoteRehash(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return false;
@@ -2376,7 +2398,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool RemoteKill(std::string prefix, std::deque<std::string> &params)
+       bool RemoteKill(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() != 2)
                        return true;
@@ -2406,7 +2428,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool LocalPong(std::string prefix, std::deque<std::string> &params)
+       bool LocalPong(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return true;
@@ -2447,7 +2469,7 @@ class TreeSocket : public InspSocket
                return true;
        }
        
-       bool MetaData(std::string prefix, std::deque<std::string> &params)
+       bool MetaData(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 3)
                        return true;
@@ -2483,7 +2505,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool ServerVersion(std::string prefix, std::deque<std::string> &params)
+       bool ServerVersion(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return true;
@@ -2499,7 +2521,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool ChangeHost(std::string prefix, std::deque<std::string> &params)
+       bool ChangeHost(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return true;
@@ -2514,7 +2536,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool AddLine(std::string prefix, std::deque<std::string> &params)
+       bool AddLine(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 6)
                        return true;
@@ -2571,7 +2593,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool ChangeName(std::string prefix, std::deque<std::string> &params)
+       bool ChangeName(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return true;
@@ -2587,7 +2609,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool Whois(std::string prefix, std::deque<std::string> &params)
+       bool Whois(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return true;
@@ -2646,7 +2668,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool Push(std::string prefix, std::deque<std::string> &params)
+       bool Push(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 2)
                        return true;
@@ -2669,7 +2691,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool Time(std::string prefix, std::deque<std::string> &params)
+       bool Time(const std::string &prefix, std::deque<std::string> &params)
        {
                // :source.server TIME remote.server sendernick
                // :remote.server TIME source.server sendernick TS
@@ -2719,7 +2741,7 @@ class TreeSocket : public InspSocket
                return true;
        }
        
-       bool LocalPing(std::string prefix, std::deque<std::string> &params)
+       bool LocalPing(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return true;
@@ -2749,7 +2771,7 @@ class TreeSocket : public InspSocket
                }
        }
 
-       bool RemoveStatus(std::string prefix, std::deque<std::string> &params)
+       bool RemoveStatus(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 1)
                        return true;
@@ -2807,7 +2829,7 @@ class TreeSocket : public InspSocket
                return true;
        }
 
-       bool RemoteServer(std::string prefix, std::deque<std::string> &params)
+       bool RemoteServer(const std::string &prefix, std::deque<std::string> &params)
        {
                if (params.size() < 4)
                        return false;
@@ -2855,7 +2877,7 @@ class TreeSocket : public InspSocket
                        return false;
                }
                std::string description = params[3];
-               for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
+               for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
                {
                        if ((x->Name == servername) && (x->RecvPass == password))
                        {
@@ -2905,7 +2927,7 @@ class TreeSocket : public InspSocket
                        return false;
                }
                std::string description = params[3];
-               for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
+               for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
                {
                        if ((x->Name == servername) && (x->RecvPass == password))
                        {
@@ -2942,7 +2964,7 @@ class TreeSocket : public InspSocket
                return false;
        }
 
-       void Split(std::string line, std::deque<std::string> &n)
+       void Split(const std::string &line, std::deque<std::string> &n)
        {
                n.clear();
                irc::tokenstream tokens(line);
@@ -2952,7 +2974,7 @@ class TreeSocket : public InspSocket
                return;
        }
 
-       bool ProcessLine(std::string line)
+       bool ProcessLine(std::string &line)
        {
                std::deque<std::string> params;
                irc::string command;
@@ -2979,7 +3001,7 @@ class TreeSocket : public InspSocket
                if ((!this->ctx_in) && (command == "AES"))
                {
                        std::string sserv = params[0];
-                       for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
+                       for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
                        {
                                if ((x->EncryptionKey != "") && (x->Name == sserv))
                                {
@@ -3326,6 +3348,10 @@ class TreeSocket : public InspSocket
                                                sourceserv = this->InboundServerName;
                                        }
                                        this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
+
+                                       Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
+                                       rmode.Send(Instance);
+
                                        return true;
                                }
                                else
@@ -3425,9 +3451,9 @@ class TreeSocket : public InspSocket
                if (this->LinkState == CONNECTING)
                {
                        this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
-                       Link* MyLink = FindLink(myhost);
+                       Link* MyLink = Utils->FindLink(myhost);
                        if (MyLink)
-                               DoFailOver(MyLink);
+                               Utils->DoFailOver(MyLink);
                }
        }
 
@@ -3446,7 +3472,9 @@ class TreeSocket : public InspSocket
                {
                        Squit(s,"Remote host closed the connection");
                }
-               this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
+
+               if (quitserver != "")
+                       this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
        }
 
        virtual int OnIncomingConnection(int newsock, char* ip)
@@ -3457,11 +3485,11 @@ class TreeSocket : public InspSocket
                 */
                bool found = false;
 
-               found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
+               found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
                if (!found)
                {
-                       for (vector<std::string>::iterator i = ValidIPs.begin(); i != ValidIPs.end(); i++)
-                               if (MatchCIDR(ip, (*i).c_str()))
+                       for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
+                               if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
                                        found = true;
 
                        if (!found)
@@ -3507,7 +3535,7 @@ class ServernameResolver : public Resolver
                TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
                if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
                {
-                       TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str());
+                       TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
                        if (newsocket->GetFd() > -1)
                        {
                                /* We're all OK */
@@ -3517,7 +3545,7 @@ class ServernameResolver : public Resolver
                                /* Something barfed, show the opers */
                                ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
                                delete newsocket;
-                               DoFailOver(&MyLink);
+                               Utils->DoFailOver(&MyLink);
                        }
                }
        }
@@ -3526,7 +3554,7 @@ class ServernameResolver : public Resolver
        {
                /* Ooops! */
                ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
-               DoFailOver(&MyLink);
+               Utils->DoFailOver(&MyLink);
        }
 };
 
@@ -3536,15 +3564,16 @@ class SecurityIPResolver : public Resolver
 {
  private:
        Link MyLink;
+       SpanningTreeUtilities* Utils;
  public:
-       SecurityIPResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
+       SecurityIPResolver(SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(U)
        {
        }
 
        void OnLookupComplete(const std::string &result)
        {
                ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
-               ValidIPs.push_back(result);
+               Utils->ValidIPs.push_back(result);
        }
 
        void OnError(ResolverError e, const std::string &errormessage)
@@ -3553,11 +3582,11 @@ class SecurityIPResolver : public Resolver
        }
 };
 
-SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance) : ServerInstance(Instance)
+SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
 {
        Bindings.clear();
-       this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
        this->ReadConfiguration(true);
+       this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
 }
 
 SpanningTreeUtilities::~SpanningTreeUtilities()
@@ -3582,6 +3611,7 @@ SpanningTreeUtilities::~SpanningTreeUtilities()
                        DELETE(sock);
                }
        }
+       delete TreeRoot;
 }
 
 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
@@ -3612,7 +3642,7 @@ void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<Tr
        return;
 }
 
-bool SpanningTreeUtilities::DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params)
+bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> &params)
 {
        TreeServer* omitroute = this->BestRouteTo(omit);
        if ((command == "NOTICE") || (command == "PRIVMSG"))
@@ -3680,7 +3710,7 @@ bool SpanningTreeUtilities::DoOneToAllButSenderRaw(std::string data, std::string
        return true;
 }
 
-bool SpanningTreeUtilities::DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
+bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string omit)
 {
        TreeServer* omitroute = this->BestRouteTo(omit);
        std::string FullLine = ":" + prefix + " " + command;
@@ -3707,7 +3737,7 @@ bool SpanningTreeUtilities::DoOneToAllButSender(std::string prefix, std::string
        return true;
 }
 
-bool SpanningTreeUtilities::DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
+bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params)
 {
        std::string FullLine = ":" + prefix + " " + command;
        unsigned int words = params.size();
@@ -3743,7 +3773,7 @@ bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char*
        return this->DoOneToAllButSender(spfx, scmd, params, omit);
 }
        
-bool SpanningTreeUtilities::DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
+bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target)
 {
        TreeServer* Route = this->BestRouteTo(target);
        if (Route)
@@ -3770,7 +3800,7 @@ bool SpanningTreeUtilities::DoOneToOne(std::string prefix, std::string command,
 
 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
 {
-       Conf = new ConfigReader(ServerInstance);
+       ConfigReader* Conf = new ConfigReader(ServerInstance);
        if (rebind)
        {
                for (int j =0; j < Conf->Enumerate("bind"); j++)
@@ -3819,6 +3849,7 @@ void SpanningTreeUtilities::ReadConfiguration(bool rebind)
                L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
                L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
                L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
+               L.Timeout = Conf->ReadInteger("link","timeout",j,true);
                L.NextConnectTime = time(NULL) + L.AutoConnect;
                /* Bugfix by brain, do not allow people to enter bad configurations */
                if (L.Name != ServerInstance->Config->ServerName)
@@ -3836,7 +3867,7 @@ void SpanningTreeUtilities::ReadConfiguration(bool rebind)
                                {
                                        try
                                        {
-                                               SecurityIPResolver* sr = new SecurityIPResolver(ServerInstance, L.IPAddr, L);
+                                               SecurityIPResolver* sr = new SecurityIPResolver(this, ServerInstance, L.IPAddr, L);
                                                ServerInstance->AddResolver(sr);
                                        }
                                        catch (ModuleException& e)
@@ -3896,7 +3927,7 @@ class ModuleSpanningTree : public Module
        ModuleSpanningTree(InspIRCd* Me)
                : Module::Module(Me), max_local(0), max_global(0)
        {
-               Utils = new SpanningTreeUtilities(Me);
+               Utils = new SpanningTreeUtilities(Me, this);
 
                command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
                ServerInstance->AddCommand(command_rconnect);
@@ -3936,7 +3967,7 @@ class ModuleSpanningTree : public Module
 
        int CountServs()
        {
-               return serverlist.size();
+               return Utils->serverlist.size();
        }
 
        void HandleLinks(const char** parameters, int pcnt, userrec* user)
@@ -4275,7 +4306,7 @@ class ModuleSpanningTree : public Module
                /* Do we already have an IP? If so, no need to resolve it. */
                if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
                {
-                       TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str());
+                       TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
                        if (newsocket->GetFd() > -1)
                        {
                                /* Handled automatically on success */
@@ -4284,7 +4315,7 @@ class ModuleSpanningTree : public Module
                        {
                                ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
                                delete newsocket;
-                               this->DoFailOver(x);
+                               Utils->DoFailOver(x);
                        }
                }
                else
@@ -4297,48 +4328,14 @@ class ModuleSpanningTree : public Module
                        catch (ModuleException& e)
                        {
                                ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
-                               this->DoFailOver(x);
-                       }
-               }
-       }
-
-       void DoFailOver(Link* x)
-       {
-               if (x->FailOver.length())
-               {
-                       if (x->FailOver == x->Name)
-                       {
-                               ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Name.c_str());
-                               return;
-                       }
-                       Link* TryThisOne = this->FindLink(x->FailOver.c_str());
-                       if (TryThisOne)
-                       {
-                               ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
-                               ConnectServer(TryThisOne);
-                       }
-                       else
-                       {
-                               ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
+                               Utils->DoFailOver(x);
                        }
                }
        }
 
-       Link* FindLink(const std::string& name)
-       {
-               for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
-               {
-                       if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
-                       {
-                               return &(*x);
-                       }
-               }
-               return NULL;
-       }
-
        void AutoConnectServers(time_t curtime)
        {
-               for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
+               for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
                {
                        if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
                        {
@@ -4406,7 +4403,7 @@ class ModuleSpanningTree : public Module
        
        int HandleConnect(const char** parameters, int pcnt, userrec* user)
        {
-               for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
+               for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
                {
                        if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
                        {
@@ -4432,10 +4429,10 @@ class ModuleSpanningTree : public Module
        {
                if (statschar == 'c')
                {
-                       for (unsigned int i = 0; i < LinkBlocks.size(); i++)
+                       for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
                        {
-                               results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr)+" * "+LinkBlocks[i].Name.c_str()+" "+ConvToStr(LinkBlocks[i].Port)+" "+(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
-                               results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
+                               results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
+                               results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
                        }
                        results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
                        ServerInstance->SNO->WriteToSnoMask('t',"Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,ServerInstance->Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
@@ -5031,6 +5028,19 @@ class ModuleSpanningTree : public Module
                        params->insert(params->begin() + 1,ConvToStr(ourTS));
                        Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
                }
+               else if (event->GetEventID() == "send_push")
+               {
+                       if (params->size() < 2)
+                               return;
+                       
+                       userrec *a = ServerInstance->FindNick((*params)[0]);
+                       
+                       if (!a)
+                               return;
+                       
+                       (*params)[1] = ":" + (*params)[1];
+                       Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
+               }
        }
 
        virtual ~ModuleSpanningTree()
@@ -5069,16 +5079,41 @@ class ModuleSpanningTree : public Module
        }
 };
 
-void DoFailOver(Link* x)
+void SpanningTreeUtilities::DoFailOver(Link* x)
 {
-       TreeProtocolModule->DoFailOver(x);
+       if (x->FailOver.length())
+       {
+               if (x->FailOver == x->Name)
+               {
+                       ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Name.c_str());
+                       return;
+               }
+               Link* TryThisOne = this->FindLink(x->FailOver.c_str());
+               if (TryThisOne)
+               {
+                       ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
+                       Creator->ConnectServer(TryThisOne);
+               }
+               else
+               {
+                       ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
+               }
+       }
 }
 
-Link* FindLink(const std::string& name)
+Link* SpanningTreeUtilities::FindLink(const std::string& name)
 {
-       return TreeProtocolModule->FindLink(name);
+       for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
+       {
+               if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
+               {
+                       return &(*x);
+               }
+       }
+       return NULL;
 }
 
+
 class ModuleSpanningTreeFactory : public ModuleFactory
 {
  public:
@@ -5092,8 +5127,7 @@ class ModuleSpanningTreeFactory : public ModuleFactory
        
        virtual Module * CreateModule(InspIRCd* Me)
        {
-               TreeProtocolModule = new ModuleSpanningTree(Me);
-               return TreeProtocolModule;
+               return new ModuleSpanningTree(Me);
        }
        
 };