]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/modules/m_spanningtree/treesocket2.cpp
Its ok to allow remote map to non-opers now, found the real culprit
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket2.cpp
index d383e2394b6b73df13703dbe63717a394f284d28..67e235e0af80207b44af568540fa317351515ae9 100644 (file)
@@ -1 +1,713 @@
-/*       +------------------------------------+\r *       | Inspire Internet Relay Chat Daemon |\r *       +------------------------------------+\r *\r *  InspIRCd: (C) 2002-2007 InspIRCd Development Team\r * See: http://www.inspircd.org/wiki/index.php/Credits\r *\r * This program is free but copyrighted software; see\r *            the file COPYING for details.\r *\r * ---------------------------------------------------\r */\r\r#include "inspircd.h"\r#include "configreader.h"\r#include "users.h"\r#include "channels.h"\r#include "modules.h"\r#include "commands/cmd_whois.h"\r#include "commands/cmd_stats.h"\r#include "socket.h"\r#include "wildcard.h"\r#include "xline.h"\r#include "transport.h"\r#include "socketengine.h"\r\r#include "m_spanningtree/main.h"\r#include "m_spanningtree/utils.h"\r#include "m_spanningtree/treeserver.h"\r#include "m_spanningtree/link.h"\r#include "m_spanningtree/treesocket.h"\r#include "m_spanningtree/resolvers.h"\r#include "m_spanningtree/handshaketimer.h"\r\r/* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */\r\rstatic std::map<std::string, std::string> warned;       /* Server names that have had protocol violation warnings displayed for them */\r\rint TreeSocket::WriteLine(std::string line)\r{\r      Instance->Log(DEBUG, "S[%d] -> %s", this->GetFd(), line.c_str());\r      line.append("\r\n");\r   return this->Write(line);\r}\r\r\r/* Handle ERROR command */\rbool TreeSocket::Error(std::deque<std::string> &params)\r{\r     if (params.size() < 1)\r         return false;\r  this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());\r      /* we will return false to cause the socket to close. */\r       return false;\r}\r\rbool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> &params)\r{\r        if (params.empty())\r            return true;\r\r  if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))\r {\r              /* Pass it on, not for us */\r           Utils->DoOneToOne(prefix, "MODULES", params, params[0]);\r               return true;\r   }\r\r     char strbuf[MAXBUF];\r   std::deque<std::string> par;\r   par.push_back(prefix);\r par.push_back("");\r\r    userrec* source = this->Instance->FindNick(prefix);\r    if (!source)\r           return true;\r\r  for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)\r       {\r              Version V = Instance->modules[i]->GetVersion();\r                char modulename[MAXBUF];\r               char flagstate[MAXBUF];\r                *flagstate = 0;\r                if (V.Flags & VF_STATIC)\r                       strlcat(flagstate,", static",MAXBUF);\r          if (V.Flags & VF_VENDOR)\r                       strlcat(flagstate,", vendor",MAXBUF);\r          if (V.Flags & VF_COMMON)\r                       strlcat(flagstate,", common",MAXBUF);\r          if (V.Flags & VF_SERVICEPROVIDER)\r                      strlcat(flagstate,", service provider",MAXBUF);\r                if (!flagstate[0])\r                     strcpy(flagstate,"  <no flags>");\r              strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);\r             if (*source->oper)\r             {\r                      snprintf(strbuf, MAXBUF, "::%s 900 %s :0x%08lx %d.%d.%d.%d %s (%s)",Instance->Config->ServerName,source->nick,(long unsigned int)Instance->modules[i],V.Major,V.Minor,V.Revision,V.Build,ServerConfig::CleanFilename(modulename),flagstate+2);\r         }\r              else\r           {\r                      snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));\r         }\r              par[1] = strbuf;\r               Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);\r  }\r      snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);\r      par[1] = strbuf;\r       Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);\r  return true;\r}\r\r/** remote MOTD. leet, huh? */\rbool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> &params)\r{\r     if (params.size() > 0)\r {\r              if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))\r          {\r                      /* It's for our server */\r                      string_list results;\r                   userrec* source = this->Instance->FindNick(prefix);\r\r                   if (source)\r                    {\r                              std::deque<std::string> par;\r                           par.push_back(prefix);\r                         par.push_back("");\r\r                            if (!Instance->Config->MOTD.size())\r                            {\r                                      par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";\r                                  Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                                     return true;\r                           }\r\r                             par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";\r                          Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r\r                            for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)\r                               {\r                                      par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];\r                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                             }\r\r                             par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";\r                            Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                     }\r              }\r              else\r           {\r                      /* Pass it on */\r                       userrec* source = this->Instance->FindNick(prefix);\r                    if (source)\r                            Utils->DoOneToOne(prefix, "MOTD", params, params[0]);\r          }\r      }\r      return true;\r}\r\r/** remote ADMIN. leet, huh? */\rbool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> &params)\r{\r   if (params.size() > 0)\r {\r              if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))\r          {\r                      /* It's for our server */\r                      string_list results;\r                   userrec* source = this->Instance->FindNick(prefix);\r                    if (source)\r                    {\r                              std::deque<std::string> par;\r                           par.push_back(prefix);\r                         par.push_back("");\r                             par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;\r                                Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                             par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name     - "+Instance->Config->AdminName;\r                              Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                             par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;\r                              Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                             par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail   - "+Instance->Config->AdminEmail;\r                             Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                     }\r              }\r              else\r           {\r                      /* Pass it on */\r                       userrec* source = this->Instance->FindNick(prefix);\r                    if (source)\r                            Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);\r         }\r      }\r      return true;\r}\r\rbool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> &params)\r{\r   /* Get the reply to a STATS query if it matches this servername,\r        * and send it back as a load of PUSH queries\r   */\r    if (params.size() > 1)\r {\r              if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))\r          {\r                      /* It's for our server */\r                      string_list results;\r                   userrec* source = this->Instance->FindNick(prefix);\r                    if (source)\r                    {\r                              std::deque<std::string> par;\r                           par.push_back(prefix);\r                         par.push_back("");\r                             DoStats(this->Instance, *(params[0].c_str()), source, results);\r                                for (size_t i = 0; i < results.size(); i++)\r                            {\r                                      par[1] = "::" + results[i];\r                                    Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);\r                             }\r                      }\r              }\r              else\r           {\r                      /* Pass it on */\r                       userrec* source = this->Instance->FindNick(prefix);\r                    if (source)\r                            Utils->DoOneToOne(prefix, "STATS", params, params[1]);\r         }\r      }\r      return true;\r}\r\r\r/** Because the core won't let users or even SERVERS set +o,\r * we use the OPERTYPE command to do this.\r */\rbool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> &params)\r{\r   if (params.size() != 1)\r                return true;\r   std::string opertype = params[0];\r      userrec* u = this->Instance->FindNick(prefix);\r if (u)\r {\r              u->modes[UM_OPERATOR] = 1;\r             this->Instance->all_opers.push_back(u);\r                strlcpy(u->oper,opertype.c_str(),NICKMAX-1);\r           Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);\r               this->Instance->SNO->WriteToSnoMask('o',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server, u->nick,u->ident,u->host,irc::Spacify(opertype.c_str()));\r      }\r      return true;\r}\r\r/** Because Andy insists that services-compatible servers must\r * implement SVSNICK and SVSJOIN, that's exactly what we do :p\r */\rbool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> &params)\r{\r     if (params.size() < 3)\r         return true;\r\r  userrec* u = this->Instance->FindNick(params[0]);\r\r     if (u)\r {\r              Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);\r            if (IS_LOCAL(u))\r               {\r                      std::deque<std::string> par;\r                   par.push_back(params[1]);\r                      if (!u->ForceNickChange(params[1].c_str()))\r                    {\r                              userrec::QuitUser(this->Instance, u, "Nickname collision");\r                            return true;\r                   }\r                      u->age = atoi(params[2].c_str());\r              }\r      }\r      return true;\r}\r\rbool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> &params)\r{\r        if (params.size() < 1)\r         return true;\r\r  userrec* u = this->Instance->FindNick(prefix);\r\r        if (u)\r {\r              u->SetOperQuit(params[0]);\r             params[0] = ":" + params[0];\r           Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);\r   }\r      return true;\r}\r\rbool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> &params)\r{\r     if (params.size() < 2)\r         return true;\r\r  userrec* u = this->Instance->FindNick(params[0]);\r\r     if (u)\r {\r              /* only join if it's local, otherwise just pass it on! */\r              if (IS_LOCAL(u))\r                       chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());\r          Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);\r    }\r      return true;\r}\r\rbool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> &params)\r{\r    if (params.size() < 1)\r         return false;\r\r std::string servermask = params[0];\r\r   if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))\r  {\r              this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");\r             this->Instance->RehashServer();\r                Utils->ReadConfiguration(false);\r               InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);\r      }\r      Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);\r     return true;\r}\r\rbool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> &params)\r{        \r      if (params.size() != 2)\r                return true;\r\r  userrec* who = this->Instance->FindNick(params[0]);\r\r   if (who)\r       {\r              /* Prepend kill source, if we don't have one */          \r              if (*(params[1].c_str()) != '[')\r               {\r                      params[1] = "[" + prefix + "] Killed (" + params[1] +")";\r              }\r              std::string reason = params[1];\r                params[1] = ":" + params[1];\r           Utils->DoOneToAllButSender(prefix,"KILL",params,prefix);\r               // NOTE: This is safe with kill hiding on, as RemoteKill is only reached if we have a server prefix.\r           // in short this is not executed for USERS.\r            who->Write(":%s KILL %s :%s (%s)", prefix.c_str(), who->nick, prefix.c_str(), reason.c_str());\r         userrec::QuitUser(this->Instance,who,reason);\r  }\r      return true;\r}\r\rbool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> &params)\r{\r       if (params.size() < 1)\r         return true;\r\r  if (params.size() == 1)\r        {\r              TreeServer* ServerSource = Utils->FindServer(prefix);\r          if (ServerSource)\r              {\r                      ServerSource->SetPingFlag();\r                   ServerSource->rtt = Instance->Time() - ServerSource->LastPing;\r         }\r      }\r      else\r   {\r              std::string forwardto = params[1];\r             if (forwardto == this->Instance->Config->ServerName)\r           {\r                      /*\r                      * this is a PONG for us\r                        * if the prefix is a user, check theyre local, and if they are,\r                        * dump the PONG reply back to their fd. If its a server, do nowt.\r                      * Services might want to send these s->s, but we dont need to yet.\r                     */\r                    userrec* u = this->Instance->FindNick(prefix);\r                 if (u)\r                 {\r                              u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());\r                        }\r              }\r              else\r           {\r                      // not for us, pass it on :)\r                   Utils->DoOneToOne(prefix,"PONG",params,forwardto);\r             }\r      }\r\r     return true;\r}\r\rbool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> &params)\r{\r        if (params.size() < 2)\r         return true;\r   else if (params.size() < 3)\r            params.push_back("");\r  TreeServer* ServerSource = Utils->FindServer(prefix);\r  if (ServerSource)\r      {\r              Utils->SetRemoteBursting(ServerSource, false);\r\r                if (params[0] == "*")\r          {\r                      FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));\r                }\r              else if (*(params[0].c_str()) == '#')\r          {\r                      chanrec* c = this->Instance->FindChan(params[0]);\r                      if (c)\r                 {\r                              FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));\r                 }\r              }\r              else if (*(params[0].c_str()) != '#')\r          {\r                      userrec* u = this->Instance->FindNick(params[0]);\r                      if (u)\r                 {\r                              FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));\r                    }\r              }\r      }\r\r     params[2] = ":" + params[2];\r   Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);\r   return true;\r}\r\rbool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> &params)\r{\r   if (params.size() < 1)\r         return true;\r\r  TreeServer* ServerSource = Utils->FindServer(prefix);\r\r if (ServerSource)\r      {\r              ServerSource->SetVersion(params[0]);\r   }\r      params[0] = ":" + params[0];\r   Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);\r    return true;\r}\r\rbool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> &params)\r{\r      if (params.size() < 1)\r         return true;\r   userrec* u = this->Instance->FindNick(prefix);\r\r        if (u)\r {\r              u->ChangeDisplayedHost(params[0].c_str());\r             Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);\r   }\r      return true;\r}\r\rbool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> &params)\r{\r if (params.size() < 6)\r         return true;\r   bool propogate = false;\r        if (!this->bursting)\r           Utils->lines_to_apply = 0;\r     switch (*(params[0].c_str()))\r  {\r              case 'Z':\r                      propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());\r                     Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));\r                 if (propogate)\r                         Utils->lines_to_apply |= APPLY_ZLINES;\r         break;\r         case 'Q':\r                      propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());\r                     Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));\r                 if (propogate)\r                         Utils->lines_to_apply |= APPLY_QLINES;\r         break;\r         case 'E':\r                      propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());\r                     Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));\r         break;\r         case 'G':\r                      propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());\r                     Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));\r                 if (propogate)\r                         Utils->lines_to_apply |= APPLY_GLINES;\r         break;\r         case 'K':\r                      propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());\r                     if (propogate)\r                         Utils->lines_to_apply |= APPLY_KLINES;\r         break;\r         default:\r                       /* Just in case... */\r                  this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");\r                        propogate = false;\r             break;\r }\r      /* Send it on its way */\r       if (propogate)\r {\r              if (atoi(params[4].c_str()))\r           {\r                      time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();\r                      this->Instance->SNO->WriteToSnoMask('x',"%s Added %cLINE on %s to expire on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),Instance->TimeString(c_requires_crap).c_str(),params[5].c_str());\r          }\r              else\r           {\r                      this->Instance->SNO->WriteToSnoMask('x',"%s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());\r              }\r              params[5] = ":" + params[5];\r           Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);\r    }\r      if (!this->bursting)\r   {\r              Instance->XLines->apply_lines(Utils->lines_to_apply);\r          Utils->lines_to_apply = 0;\r     }\r      return true;\r}\r\rbool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> &params)\r{\r      if (params.size() < 1)\r         return true;\r   userrec* u = this->Instance->FindNick(prefix);\r if (u)\r {\r              u->ChangeName(params[0].c_str());\r              params[0] = ":" + params[0];\r           Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);\r   }\r      return true;\r}\r\rbool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> &params)\r{\r   if (params.size() < 1)\r         return true;\r   userrec* u = this->Instance->FindNick(prefix);\r if (u)\r {\r              // an incoming request\r         if (params.size() == 1)\r                {\r                      userrec* x = this->Instance->FindNick(params[0]);\r                      if ((x) && (IS_LOCAL(x)))\r                      {\r                              userrec* x = this->Instance->FindNick(params[0]);\r                              char signon[MAXBUF];\r                           char idle[MAXBUF];\r                             snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);\r                             snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));\r                           std::deque<std::string> par;\r                           par.push_back(prefix);\r                         par.push_back(signon);\r                         par.push_back(idle);\r                           // ours, we're done, pass it BACK\r                              Utils->DoOneToOne(params[0], "IDLE", par, u->server);\r                  }\r                      else\r                   {\r                              // not ours pass it on\r                         if (x)\r                                 Utils->DoOneToOne(prefix, "IDLE", params, x->server);\r                  }\r              }\r              else if (params.size() == 3)\r           {\r                      std::string who_did_the_whois = params[0];\r                     userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);\r                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))\r                    {\r                              // an incoming reply to a whois we sent out\r                            std::string nick_whoised = prefix;\r                             unsigned long signon = atoi(params[1].c_str());\r                                unsigned long idle = atoi(params[2].c_str());\r                          if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))\r                            {\r                                      do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());\r                               }\r                      }\r                      else\r                   {\r                              // not ours, pass it on\r                                if (who_to_send_to)\r                                    Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);\r                     }\r              }\r      }\r      return true;\r}\r\rbool TreeSocket::Push(const std::string &prefix, std::deque<std::string> &params)\r{\r    if (params.size() < 2)\r         return true;\r   userrec* u = this->Instance->FindNick(params[0]);\r      if (!u)\r                return true;\r   if (IS_LOCAL(u))\r       {\r              u->Write(params[1]);\r   }\r      else\r   {\r              // continue the raw onwards\r            params[1] = ":" + params[1];\r           Utils->DoOneToOne(prefix,"PUSH",params,u->server);\r     }\r      return true;\r}\r\rbool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> &params)\r{\r   if (!params.size() || !Utils->EnableTimeSync)\r          return true;\r\r  bool force = false;\r\r   if ((params.size() == 2) && (params[1] == "FORCE"))\r            force = true;\r\r time_t them = atoi(params[0].c_str());\r time_t us = Instance->Time(false);\r\r    time_t diff = them - us;\r\r      Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);\r\r        if (force || (them != us))\r     {\r              time_t old = Instance->SetTimeDelta(diff);\r             Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);\r    }\r\r     return true;\r}\r\rbool TreeSocket::Time(const std::string &prefix, std::deque<std::string> &params)\r{\r    // :source.server TIME remote.server sendernick\r        // :remote.server TIME source.server sendernick TS\r     if (params.size() == 2)\r        {\r              // someone querying our time?\r          if (this->Instance->Config->ServerName == params[0])\r           {\r                      userrec* u = this->Instance->FindNick(params[1]);\r                      if (u)\r                 {\r                              params.push_back(ConvToStr(Instance->Time(false)));\r                            params[0] = prefix;\r                            Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);\r                 }\r              }\r              else\r           {\r                      // not us, pass it on\r                  userrec* u = this->Instance->FindNick(params[1]);\r                      if (u)\r                         Utils->DoOneToOne(prefix,"TIME",params,params[0]);\r             }\r      }\r      else if (params.size() == 3)\r   {\r              // a response to a previous TIME\r               userrec* u = this->Instance->FindNick(params[1]);\r              if ((u) && (IS_LOCAL(u)))\r              {\r                      time_t rawtime = atol(params[2].c_str());\r                      struct tm * timeinfo;\r                  timeinfo = localtime(&rawtime);\r                        char tms[26];\r                  snprintf(tms,26,"%s",asctime(timeinfo));\r                       tms[24] = 0;\r                   u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);\r              }\r              else\r           {\r                      if (u)\r                         Utils->DoOneToOne(prefix,"TIME",params,u->server);\r             }\r      }\r      return true;\r}\r\rbool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> &params)\r{\r       if (params.size() < 1)\r         return true;\r   if (params.size() == 1)\r        {\r              std::string stufftobounce = params[0];\r         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);\r           return true;\r   }\r      else\r   {\r              std::string forwardto = params[1];\r             if (forwardto == this->Instance->Config->ServerName)\r           {\r                      // this is a ping for us, send back PONG to the requesting server\r                      params[1] = params[0];\r                 params[0] = forwardto;\r                 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);\r          }\r              else\r           {\r                      // not for us, pass it on :)\r                   Utils->DoOneToOne(prefix,"PING",params,forwardto);\r             }\r              return true;\r   }\r}\r\r/** TODO: This creates a total mess of output and needs to really use irc::modestacker.\r */\rbool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> &params)\r{\r   if (params.size() < 1)\r         return true;\r   chanrec* c = Instance->FindChan(params[0]);\r    if (c)\r {\r              for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)\r           {\r                      ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);\r                     if (mh)\r                                mh->RemoveMode(c);\r             }\r      }\r      return true;\r}\r\rbool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> &params)\r{\r    if (params.size() < 4)\r         return false;\r  std::string servername = params[0];\r    std::string password = params[1];\r      // hopcount is not used for a remote server, we calculate this ourselves\r       std::string description = params[3];\r   TreeServer* ParentOfThis = Utils->FindServer(prefix);\r  if (!ParentOfThis)\r     {\r              this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);\r              return false;\r  }\r      TreeServer* CheckDupe = Utils->FindServer(servername);\r if (CheckDupe)\r {\r              this->SendError("Server "+servername+" already exists!");\r              this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);\r             return false;\r  }\r      Link* lnk = Utils->FindLink(servername);\r       TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);\r     ParentOfThis->AddChild(Node);\r  params[3] = ":" + params[3];\r   Utils->SetRemoteBursting(Node, true);\r  Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);\r     this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");\r       return true;\r}\r\rbool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)\r{\r     if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))\r    {\r              /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!\r             * We can't allow this password as valid.\r               */\r            if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)\r                         return false;\r          else\r                   /* Straight string compare of hashes */\r                        return ours == theirs;\r }\r      else\r           /* Straight string compare of plaintext */\r             return ours == theirs;\r}\r\rbool TreeSocket::Outbound_Reply_Server(std::deque<std::string> &params)\r{\r    if (params.size() < 4)\r         return false;\r\r irc::string servername = params[0].c_str();\r    std::string sname = params[0];\r std::string password = params[1];\r      std::string description = params[3];\r   int hops = atoi(params[2].c_str());\r\r   this->InboundServerName = sname;\r       this->InboundDescription = description;\r\r       if (!sentcapab)\r                this->SendCapabilities();\r\r     if (hops)\r      {\r              this->SendError("Server too far away for authentication");\r             this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");\r             return false;\r  }\r\r     for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)\r      {\r              if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))\r              {\r                      TreeServer* CheckDupe = Utils->FindServer(sname);\r                      if (CheckDupe)\r                 {\r                              this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");\r                           this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());\r                           return false;\r                  }\r                      // Begin the sync here. this kickstarts the\r                    // other side, waiting in WAIT_AUTH_2 state,\r                   // into starting their burst, as it shows\r                      // that we're happy.\r                   this->LinkState = CONNECTED;\r                   // we should add the details of this server now\r                        // to the servers tree, as a child of the root\r                 // node.\r                       TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);\r                        Utils->TreeRoot->AddChild(Node);\r                       params[3] = ":" + params[3];\r                   Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);\r                  this->bursting = true;\r                 this->DoBurst(Node);\r                   return true;\r           }\r      }\r      this->SendError("Invalid credentials");\r        this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");\r      return false;\r}\r\rbool TreeSocket::Inbound_Server(std::deque<std::string> &params)\r{\r    if (params.size() < 4)\r         return false;\r  irc::string servername = params[0].c_str();\r    std::string sname = params[0];\r std::string password = params[1];\r      std::string description = params[3];\r   int hops = atoi(params[2].c_str());\r\r   this->InboundServerName = sname;\r       this->InboundDescription = description;\r\r       if (!sentcapab)\r                this->SendCapabilities();\r\r     if (hops)\r      {\r              this->SendError("Server too far away for authentication");\r             this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");\r             return false;\r  }\r\r     for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)\r      {\r              if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))\r                {\r                      /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */\r                 TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);\r                        if (CheckDupeSocket)\r                   {\r                              /* If we find one, we abort the link to prevent a race condition */\r                            this->SendError("Negotiation collision");\r                              this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");\r                                CheckDupeSocket->SendError("Negotiation collision");\r                           Instance->SE->DelFd(CheckDupeSocket);\r                          CheckDupeSocket->Close();\r                              delete CheckDupeSocket;\r                                return false;\r                  }\r                      /* Now check for fully initialized instances of the server */\r                  TreeServer* CheckDupe = Utils->FindServer(sname);\r                      if (CheckDupe)\r                 {\r                              this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");\r                           this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());\r                           return false;\r                  }\r                      this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");\r                        if (this->Hook)\r                        {\r                              std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();\r                          this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");\r                  }\r\r                     Utils->AddBurstingServer(sname,this);\r\r                 // this is good. Send our details: Our server name and description and hopcount of 0,\r                  // along with the sendpass from this block.\r                    this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);\r                       // move to the next state, we are now waiting for THEM.\r                        this->LinkState = WAIT_AUTH_2;\r                 return true;\r           }\r      }\r      this->SendError("Invalid credentials");\r        this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");\r      return false;\r}\r\rvoid TreeSocket::Split(const std::string &line, std::deque<std::string> &n)\r{\r n.clear();\r     irc::tokenstream tokens(line);\r std::string param;\r     while (tokens.GetToken(param))\r {\r              if (!param.empty())\r                    n.push_back(param);\r    }\r      return;\r}\r\rbool TreeSocket::ProcessLine(std::string &line)\r{\r   std::deque<std::string> params;\r        irc::string command;\r   std::string prefix;\r\r   line = line.substr(0, line.find_first_of("\r\n"));\r\r    if (line.empty())\r              return true;\r\r  Instance->Log(DEBUG, "S[%d] <- %s", this->GetFd(), line.c_str());\r\r     this->Split(line.c_str(),params);\r      \r       if (params.empty())\r            return true;\r   \r       if ((params[0][0] == ':') && (params.size() > 1))\r      {\r              prefix = params[0].substr(1);\r          params.pop_front();\r    }\r      command = params[0].c_str();\r   params.pop_front();\r    switch (this->LinkState)\r       {\r              TreeServer* Node;\r\r             case WAIT_AUTH_1:\r                      // Waiting for SERVER command from remote server. Server initiating\r                    // the connection sends the first SERVER command, listening server\r                     // replies with theirs if its happy, then if the initiator is happy,\r                   // it starts to send its net sync, which starts the merge, otherwise\r                   // it sends an ERROR.\r                  if (command == "PASS")\r                 {\r                              /* Silently ignored */\r                 }\r                      else if (command == "SERVER")\r                  {\r                              return this->Inbound_Server(params);\r                   }\r                      else if (command == "ERROR")\r                   {\r                              return this->Error(params);\r                    }\r                      else if (command == "USER")\r                    {\r                              this->SendError("Client connections to this port are prohibited.");\r                            return false;\r                  }\r                      else if (command == "CAPAB")\r                   {\r                              return this->Capab(params);\r                    }\r                      else if ((command == "U") || (command == "S"))\r                 {\r                              this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");\r                             return false;\r                  }\r                      else\r                   {\r                              irc::string error = "Invalid command in negotiation phase: " + command;\r                                this->SendError(assign(error));\r                                return false;\r                  }\r              break;\r         case WAIT_AUTH_2:\r                      // Waiting for start of other side's netmerge to say they liked our\r                    // password.\r                   if (command == "SERVER")\r                       {\r                              // cant do this, they sent it to us in the WAIT_AUTH_1 state!\r                          // silently ignore.\r                            return true;\r                   }\r                      else if ((command == "U") || (command == "S"))\r                 {\r                              this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");\r                             return false;\r                  }\r                      else if (command == "BURST")\r                   {\r                              if (params.size() && Utils->EnableTimeSync)\r                            {\r                                      bool we_have_delta = (Instance->Time(false) != Instance->Time(true));\r                                  time_t them = atoi(params[0].c_str());\r                                 time_t delta = them - Instance->Time(false);\r                                   if ((delta < -300) || (delta > 300))\r                                   {\r                                              Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than five minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));\r                                             SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");\r                                                return false;\r                                  }\r                                      else if ((delta < -30) || (delta > 30))\r                                        {\r                                              Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));\r                                        }\r\r                                     if (!Utils->MasterTime && !we_have_delta)\r                                      {\r                                              this->Instance->SetTimeDelta(delta);\r                                           // Send this new timestamp to any other servers\r                                                Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);\r                                     }\r                              }\r                              this->LinkState = CONNECTED;\r                           Link* lnk = Utils->FindLink(InboundServerName);\r                                Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);\r                            Utils->DelBurstingServer(this);\r                                Utils->TreeRoot->AddChild(Node);\r                               params.clear();\r                                params.push_back(InboundServerName);\r                           params.push_back("*");\r                         params.push_back("1");\r                         params.push_back(":"+InboundDescription);\r                              Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);\r                              this->bursting = true;\r                         this->DoBurst(Node);\r                   }\r                      else if (command == "ERROR")\r                   {\r                              return this->Error(params);\r                    }\r                      else if (command == "CAPAB")\r                   {\r                              return this->Capab(params);\r                    }\r\r             break;\r         case LISTENER:\r                 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");\r                  return false;\r          break;\r         case CONNECTING:\r                       if (command == "SERVER")\r                       {\r                              // another server we connected to, which was in WAIT_AUTH_1 state,\r                             // has just sent us their credentials. If we get this far, theyre\r                              // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.\r                          // if we're happy with this, we should send our netburst which\r                         // kickstarts the merge.\r                               return this->Outbound_Reply_Server(params);\r                    }\r                      else if (command == "ERROR")\r                   {\r                              return this->Error(params);\r                    }\r                      else if (command == "CAPAB")\r                   {\r                              return this->Capab(params);\r                    }\r              break;\r         case CONNECTED:\r                        // This is the 'authenticated' state, when all passwords\r                       // have been exchanged and anything past this point is taken\r                   // as gospel.\r\r                 if (!prefix.empty())\r                   {\r                              std::string direction = prefix;\r                                userrec* t = this->Instance->FindNick(prefix);\r                         if (t)\r                         {\r                                      direction = t->server;\r                         }\r                              TreeServer* route_back_again = Utils->BestRouteTo(direction);\r                          if ((!route_back_again) || (route_back_again->GetSocket() != this))\r                            {\r                                      if (route_back_again)\r                                          Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());\r                                   return true;\r                           }\r                              /* Fix by brain:\r                                * When there is activity on the socket, reset the ping counter so\r                              * that we're not wasting bandwidth pinging an active server.\r                           */\r                            route_back_again->SetNextPingTime(time(NULL) + 60);\r                            route_back_again->SetPingFlag();\r                       }\r                      else\r                   {\r                              prefix = this->GetName();\r                      }\r\r                     if ((command == "MODE") && (params.size() >= 2))\r                       {\r                              chanrec* channel = Instance->FindChan(params[0]);\r                              if (channel)\r                           {\r                                      userrec* x = Instance->FindNick(prefix);\r                                       if (x)\r                                 {\r                                              if (warned.find(x->server) == warned.end())\r                                            {\r                                                      Instance->Log(DEFAULT,"WARNING: I revceived modes '%s' from another server '%s'. This is not compliant with InspIRCd. Please check that server for bugs.", params[1].c_str(), x->server);\r                                                      Instance->SNO->WriteToSnoMask('d', "WARNING: The server %s is sending nonstandard modes: '%s MODE %s' where FMODE should be used, and may cause desyncs.", x->server, x->nick, params[1].c_str());\r                                                     warned[x->server] = x->nick;\r                                           }\r                                      }\r                              }\r                      }\r\r                     if (command == "SVSMODE")\r                      {\r                              /* Services expects us to implement\r                             * SVSMODE. In inspircd its the same as\r                                 * MODE anyway.\r                                 */\r                            command = "MODE";\r                      }\r                      std::string target;\r                    /* Yes, know, this is a mess. Its reasonably fast though as we're\r                       * working with std::string here.\r                       */\r                    if ((command == "NICK") && (params.size() >= 8))\r                       {\r                              return this->IntroduceClient(prefix,params);\r                   }\r                      else if (command == "FJOIN")\r                   {\r                              TreeServer* ServerSource = Utils->FindServer(prefix);\r                          if (ServerSource)\r                                      Utils->SetRemoteBursting(ServerSource, false);\r                         return this->ForceJoin(prefix,params);\r                 }\r                      else if (command == "STATS")\r                   {\r                              return this->Stats(prefix, params);\r                    }\r                      else if (command == "MOTD")\r                    {\r                              return this->Motd(prefix, params);\r                     }\r                      else if (command == "KILL" && Utils->IsServer(prefix))\r                 {\r                              return this->RemoteKill(prefix,params);\r                        }\r                      else if (command == "MODULES")\r                 {\r                              return this->Modules(prefix, params);\r                  }\r                      else if (command == "ADMIN")\r                   {\r                              return this->Admin(prefix, params);\r                    }\r                      else if (command == "SERVER")\r                  {\r                              return this->RemoteServer(prefix,params);\r                      }\r                      else if (command == "ERROR")\r                   {\r                              return this->Error(params);\r                    }\r                      else if (command == "OPERTYPE")\r                        {\r                              return this->OperType(prefix,params);\r                  }\r                      else if (command == "FMODE")\r                   {\r                              TreeServer* ServerSource = Utils->FindServer(prefix);\r                          if (ServerSource)\r                                      Utils->SetRemoteBursting(ServerSource, false);\r                         return this->ForceMode(prefix,params);\r                 }\r                      else if (command == "FTOPIC")\r                  {\r                              return this->ForceTopic(prefix,params);\r                        }\r                      else if (command == "REHASH")\r                  {\r                              return this->RemoteRehash(prefix,params);\r                      }\r                      else if (command == "METADATA")\r                        {\r                              return this->MetaData(prefix,params);\r                  }\r                      else if (command == "REMSTATUS")\r                       {\r                              return this->RemoveStatus(prefix,params);\r                      }\r                      else if (command == "PING")\r                    {\r                              if (prefix.empty())\r                                    prefix = this->GetName();\r                              /*\r                              * We just got a ping from a server that's bursting.\r                            * This can't be right, so set them to not bursting, and\r                                * apply their lines.\r                           */\r                            TreeServer* ServerSource = Utils->FindServer(prefix);\r                          if (ServerSource)\r                                      Utils->SetRemoteBursting(ServerSource, false);\r\r                                if (this->bursting)\r                            {\r                                      this->bursting = false;\r                                        Instance->XLines->apply_lines(Utils->lines_to_apply);\r                                  Utils->lines_to_apply = 0;\r                             }\r\r                             return this->LocalPing(prefix,params);\r                 }\r                      else if (command == "PONG")\r                    {\r                              if (prefix.empty())\r                                    prefix = this->GetName();\r                              /*\r                              * We just got a pong from a server that's bursting.\r                            * This can't be right, so set them to not bursting, and\r                                * apply their lines.\r                           */\r                            TreeServer* ServerSource = Utils->FindServer(prefix);\r                          if (ServerSource)\r                                      Utils->SetRemoteBursting(ServerSource, false);\r\r                                if (this->bursting)\r                            {\r                                      this->bursting = false;\r                                        Instance->XLines->apply_lines(Utils->lines_to_apply);\r                                  Utils->lines_to_apply = 0;\r                             }\r\r                             return this->LocalPong(prefix,params);\r                 }\r                      else if (command == "VERSION")\r                 {\r                              return this->ServerVersion(prefix,params);\r                     }\r                      else if (command == "FHOST")\r                   {\r                              return this->ChangeHost(prefix,params);\r                        }\r                      else if (command == "FNAME")\r                   {\r                              return this->ChangeName(prefix,params);\r                        }\r                      else if (command == "ADDLINE")\r                 {\r                              TreeServer* ServerSource = Utils->FindServer(prefix);\r                          if (ServerSource)\r                                      Utils->SetRemoteBursting(ServerSource, false);\r                         return this->AddLine(prefix,params);\r                   }\r                      else if (command == "SVSNICK")\r                 {\r                              if (prefix.empty())\r                            {\r                                      prefix = this->GetName();\r                              }\r                              return this->ForceNick(prefix,params);\r                 }\r                      else if (command == "OPERQUIT")\r                        {\r                              return this->OperQuit(prefix,params);\r                  }\r                      else if (command == "IDLE")\r                    {\r                              return this->Whois(prefix,params);\r                     }\r                      else if (command == "PUSH")\r                    {\r                              return this->Push(prefix,params);\r                      }\r                      else if (command == "TIMESET")\r                 {\r                              return this->HandleSetTime(prefix, params);\r                    }\r                      else if (command == "TIME")\r                    {\r                              return this->Time(prefix,params);\r                      }\r                      else if ((command == "KICK") && (Utils->IsServer(prefix)))\r                     {\r                              std::string sourceserv = this->myhost;\r                         if (params.size() == 3)\r                                {\r                                      userrec* user = this->Instance->FindNick(params[1]);\r                                   chanrec* chan = this->Instance->FindChan(params[0]);\r                                   if (user && chan)\r                                      {\r                                              if (!chan->ServerKickUser(user, params[2].c_str(), false))\r                                                     /* Yikes, the channels gone! */\r                                                        delete chan;\r                                   }\r                              }\r                              if (!this->InboundServerName.empty())\r                          {\r                                      sourceserv = this->InboundServerName;\r                          }\r                              return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);\r                   }\r                      else if (command == "SVSJOIN")\r                 {\r                              if (prefix.empty())\r                            {\r                                      prefix = this->GetName();\r                              }\r                              return this->ServiceJoin(prefix,params);\r                       }\r                      else if (command == "SQUIT")\r                   {\r                              if (params.size() == 2)\r                                {\r                                      this->Squit(Utils->FindServer(params[0]),params[1]);\r                           }\r                              return true;\r                   }\r                      else if (command == "OPERNOTICE")\r                      {\r                              std::string sourceserv = this->myhost;\r                         if (!this->InboundServerName.empty())\r                                  sourceserv = this->InboundServerName;\r                          if (params.size() >= 1)\r                                        Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);\r                             return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);\r                       }\r                      else if (command == "MODENOTICE")\r                      {\r                              std::string sourceserv = this->myhost;\r                         if (!this->InboundServerName.empty())\r                                  sourceserv = this->InboundServerName;\r                          if (params.size() >= 2)\r                                {\r                                      Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());\r                              }\r                              return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);\r                       }\r                      else if (command == "SNONOTICE")\r                       {\r                              std::string sourceserv = this->myhost;\r                         if (!this->InboundServerName.empty())\r                                  sourceserv = this->InboundServerName;\r                          if (params.size() >= 2)\r                                {\r                                      Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);\r                           }\r                              return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);\r                       }\r                      else if (command == "ENDBURST")\r                        {\r                              this->bursting = false;\r                                Instance->XLines->apply_lines(Utils->lines_to_apply);\r                          Utils->lines_to_apply = 0;\r                             std::string sourceserv = this->myhost;\r                         if (!this->InboundServerName.empty())\r                                  sourceserv = this->InboundServerName;\r                          this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());\r\r                           Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");\r                         rmode.Send(Instance);\r\r                         return true;\r                   }\r                      else\r                   {\r                              // not a special inter-server command.\r                         // Emulate the actual user doing the command,\r                          // this saves us having a huge ugly parser.\r                            userrec* who = this->Instance->FindNick(prefix);\r                               std::string sourceserv = this->myhost;\r                         if (!this->InboundServerName.empty())\r                          {\r                                      sourceserv = this->InboundServerName;\r                          }\r                              if ((!who) && (command == "MODE"))\r                             {\r                                      if (Utils->IsServer(prefix))\r                                   {\r                                              const char* modelist[127];\r                                             for (size_t i = 0; i < params.size(); i++)\r                                                     modelist[i] = params[i].c_str();\r                                               userrec* fake = new userrec(Instance);\r                                         fake->SetFd(FD_MAGIC_NUMBER);\r                                          this->Instance->SendMode(modelist, params.size(), fake);\r\r                                              delete fake;\r                                           /* Hot potato! pass it on! */\r                                          return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);\r                                   }\r                              }\r                              if (who)\r                               {\r                                      if ((command == "NICK") && (params.size() > 0))\r                                        {\r                                              /* On nick messages, check that the nick doesnt\r                                                 * already exist here. If it does, kill their copy,\r                                             * and our copy.\r                                                */\r                                            userrec* x = this->Instance->FindNick(params[0]);\r                                              if ((x) && (x != who))\r                                         {\r                                                      std::deque<std::string> p;\r                                                     p.push_back(params[0]);\r                                                        p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");\r                                                       Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);\r                                                       p.clear();\r                                                     p.push_back(prefix);\r                                                   p.push_back("Nickname collision");\r                                                     Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);\r                                                       userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");\r                                                        userrec* y = this->Instance->FindNick(prefix);\r                                                 if (y)\r                                                 {\r                                                              userrec::QuitUser(this->Instance,y,"Nickname collision");\r                                                      }\r                                                      return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);\r                                           }\r                                      }\r                                      // its a user\r                                  target = who->server;\r                                  const char* strparams[127];\r                                    for (unsigned int q = 0; q < params.size(); q++)\r                                       {\r                                              strparams[q] = params[q].c_str();\r                                      }\r                                      switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))\r                                    {\r                                              case CMD_INVALID:\r                                                      this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");\r                                                      return false;\r                                          break;\r                                         case CMD_FAILURE:\r                                                      return true;\r                                           break;\r                                         default:\r                                                       /* CMD_SUCCESS and CMD_USER_DELETED fall through here */\r                                               break;\r                                 }\r                              }\r                              else\r                           {\r                                      // its not a user. Its either a server, or somethings screwed up.\r                                      if (Utils->IsServer(prefix))\r                                           target = this->Instance->Config->ServerName;\r                                   else\r                                           return true;\r                           }\r                              return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);\r\r                  }\r                      return true;\r           break;\r }\r      return true;\r}\r\rstd::string TreeSocket::GetName()\r{\r    std::string sourceserv = this->myhost;\r if (!this->InboundServerName.empty())\r  {\r              sourceserv = this->InboundServerName;\r  }\r      return sourceserv;\r}\r\rvoid TreeSocket::OnTimeout()\r{\r   if (this->LinkState == CONNECTING)\r     {\r              this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");\r               Link* MyLink = Utils->FindLink(myhost);\r                if (MyLink)\r                    Utils->DoFailOver(MyLink);\r     }\r}\r\rvoid TreeSocket::OnClose()\r{\r      // Connection closed.\r  // If the connection is fully up (state CONNECTED)\r     // then propogate a netsplit to all peers.\r     std::string quitserver = this->myhost;\r if (!this->InboundServerName.empty())\r  {\r              quitserver = this->InboundServerName;\r  }\r      TreeServer* s = Utils->FindServer(quitserver);\r if (s)\r {\r              Squit(s,"Remote host closed the connection");\r  }\r\r     if (!quitserver.empty())\r       {\r              this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());\r          time_t server_uptime = Instance->Time() - this->age;    \r               if (server_uptime)\r                     Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());\r      }\r}\r\rint TreeSocket::OnIncomingConnection(int newsock, char* ip)\r{\r     /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,\r      * or discovering if this port is the server port, we don't allow connections from any\r  * IPs for which we don't have a link block.\r    */\r    bool found = false;\r\r   found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());\r      if (!found)\r    {\r              for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)\r                       if (irc::sockets::MatchCIDR(ip, (*i).c_str()))\r                         found = true;\r\r         if (!found)\r            {\r                      this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);\r                 close(newsock);\r                        return false;\r          }\r      }\r\r     TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);\r  s = s; /* Whinge whinge whinge, thats all GCC ever does. */\r    return true;\r}\r
\ No newline at end of file
+/*       +------------------------------------+
+ *       | Inspire Internet Relay Chat Daemon |
+ *       +------------------------------------+
+ *
+ *  InspIRCd: (C) 2002-2008 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.
+ *
+ * ---------------------------------------------------
+ */
+
+#include "inspircd.h"
+#include "commands/cmd_whois.h"
+#include "commands/cmd_stats.h"
+#include "socket.h"
+#include "wildcard.h"
+#include "xline.h"
+#include "transport.h"
+#include "socketengine.h"
+
+#include "m_spanningtree/main.h"
+#include "m_spanningtree/utils.h"
+#include "m_spanningtree/treeserver.h"
+#include "m_spanningtree/link.h"
+#include "m_spanningtree/treesocket.h"
+#include "m_spanningtree/resolvers.h"
+#include "m_spanningtree/handshaketimer.h"
+
+/* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
+
+void TreeSocket::WriteLine(std::string line)
+{
+       Instance->Logs->Log("m_spanningtree",DEBUG, "S[%d] O %s", this->GetFd(), line.c_str());
+       line.append("\r\n");
+       this->Write(line);
+}
+
+
+/* Handle ERROR command */
+bool TreeSocket::Error(std::deque<std::string> &params)
+{
+       if (params.size() < 1)
+               return false;
+       this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
+       /* we will return false to cause the socket to close. */
+       return false;
+}
+
+void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
+{
+       n.clear();
+       irc::tokenstream tokens(line);
+       std::string param;
+       while (tokens.GetToken(param))
+       {
+               n.push_back(param);
+       }
+       return;
+}
+
+bool TreeSocket::ProcessLine(std::string &line)
+{
+       std::deque<std::string> params;
+       irc::string command;
+       std::string prefix;
+
+       line = line.substr(0, line.find_first_of("\r\n"));
+
+       if (line.empty())
+               return true;
+
+       Instance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
+
+       this->Split(line.c_str(),params);
+       
+       if (params.empty())
+               return true;
+       
+       if ((params[0][0] == ':') && (params.size() > 1))
+       {
+               prefix = params[0].substr(1);
+               params.pop_front();
+               
+               if (prefix.empty())
+               {
+                       this->SendError("BUG (?) Empty prefix recieved.");
+                       return false;
+               }
+       }
+       
+       command = params[0].c_str();
+       params.pop_front();
+
+       switch (this->LinkState)
+       {
+               TreeServer* Node;
+
+               case WAIT_AUTH_1:
+                       /*
+                        * State WAIT_AUTH_1:
+                        *  Waiting for SERVER command from remote server. Server initiating
+                        *  the connection sends the first SERVER command, listening server
+                        *  replies with theirs if its happy, then if the initiator is happy,
+                        *  it starts to send its net sync, which starts the merge, otherwise
+                        *  it sends an ERROR.
+                        */
+                       if (command == "PASS")
+                       {
+                               /*
+                                * Ignore this silently. Some services packages insist on sending PASS, even
+                                * when it is not required (i.e. by us). We have to ignore this here, otherwise
+                                * as it's an unknown command (effectively), it will cause the connection to be
+                                * closed, which probably isn't what people want. -- w00t
+                                */
+                       }
+                       else if (command == "SERVER")
+                       {
+                               return this->Inbound_Server(params);
+                       }
+                       else if (command == "ERROR")
+                       {
+                               return this->Error(params);
+                       }
+                       else if (command == "USER")
+                       {
+                               this->SendError("Client connections to this port are prohibited.");
+                               return false;
+                       }
+                       else if (command == "CAPAB")
+                       {
+                               return this->Capab(params);
+                       }
+                       else
+                       {
+                               // XXX ...wtf.
+                               irc::string error = "Invalid command in negotiation phase: " + command;
+                               this->SendError(assign(error));
+                               return false;
+                       }
+               break;
+               case WAIT_AUTH_2:
+                       /*
+                        * State WAIT_AUTH_2:
+                        *  We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
+                        *  The other option at this stage of things, of course, is for them to close our connection thanks
+                        *  to invalid credentials.. -- w
+                        */
+                       if (command == "SERVER")
+                       {
+                               /*
+                                * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
+                                * Both of these aren't allowable, so block them here. -- w
+                                */
+                               this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
+                               return true;
+                       }
+                       else if (command == "BURST")
+                       {
+                               if (params.size())
+                               {
+                                       time_t them = atoi(params[0].c_str());
+                                       time_t delta = them - Instance->Time();
+                                       if ((delta < -600) || (delta > 600))
+                                       {
+                                               Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than five minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
+                                               SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
+                                               return false;
+                                       }
+                                       else if ((delta < -30) || (delta > 30))
+                                       {
+                                               Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
+                                       }
+                               }
+                               this->LinkState = CONNECTED;
+                               Link* lnk = Utils->FindLink(InboundServerName);
+
+                               Node = new TreeServer(this->Utils, this->Instance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
+
+                               if (Node->DuplicateID())
+                               {
+                                       this->SendError("Server ID "+InboundSID+" already exists on the network!");
+                                       this->Instance->SNO->WriteToSnoMask('l',"Server \2"+InboundServerName+"\2 being introduced from \2" + prefix + "\2 denied, server ID already exists on the network. Closing link.");
+                                       return false;
+                               }
+
+                               Utils->TreeRoot->AddChild(Node);
+                               params.clear();
+                               params.push_back(InboundServerName);
+                               params.push_back("*");
+                               params.push_back("1");
+                               params.push_back(InboundSID);
+                               params.push_back(":"+InboundDescription);
+                               Utils->DoOneToAllButSender(Instance->Config->GetSID(),"SERVER",params,InboundServerName);
+                               Node->bursting = true;
+                               this->DoBurst(Node);
+                       }
+                       else if (command == "ERROR")
+                       {
+                               return this->Error(params);
+                       }
+                       else if (command == "CAPAB")
+                       {
+                               return this->Capab(params);
+                       }
+
+               break;
+               case LISTENER:
+                       /*
+                        * This really shouldn't happen.
+                        */
+                       this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
+                       return false;
+               break;
+               case CONNECTING:
+                       /*
+                        * State CONNECTING:
+                        *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
+                        *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
+                        *  + our netburst, which will put them into CONNECTED state. -- w
+                        */
+                       if (command == "SERVER")
+                       {
+                               // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
+                               return this->Outbound_Reply_Server(params);
+                       }
+                       else if (command == "ERROR")
+                       {
+                               return this->Error(params);
+                       }
+                       else if (command == "CAPAB")
+                       {
+                               return this->Capab(params);
+                       }
+               break;
+               case CONNECTED:
+                       /*
+                       * State CONNECTED:
+                        *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
+                        *  Anything from here on should be accepted a little more reasonably.
+                        */
+                       if (!prefix.empty())
+                       {
+                               /*
+                                * Check for fake direction here, and drop any instances that are found.
+                                * What is fake direction? Imagine the following server setup:
+                                *    0AA <-> 0AB <-> 0AC
+                                * Fake direction would be 0AC sending a message to 0AB claiming to be from
+                                * 0AA, or something similar. Basically, a message taking a path that *cannot*
+                                * be correct.
+                                *
+                                * When would this be seen?
+                                * Well, hopefully never. It could be caused by race conditions, bugs, or
+                                * "miscreant" servers, though, so let's check anyway. -- w
+                                */
+                               std::string direction = prefix;
+
+                               User *t = this->Instance->FindUUID(prefix);
+                               if (t)
+                               {
+                                       direction = t->server;
+                               }
+
+                               TreeServer* route_back_again = Utils->BestRouteTo(direction);
+                               if ((!route_back_again) || (route_back_again->GetSocket() != this))
+                               {
+                                       if (route_back_again)
+                                               Instance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
+                                       return true;
+                               }
+                               /* Fix by brain:
+                                * When there is activity on the socket, reset the ping counter so
+                                * that we're not wasting bandwidth pinging an active server.
+                                */
+                               route_back_again->SetNextPingTime(Instance->Time() + Utils->PingFreq);
+                               route_back_again->SetPingFlag();
+                       }
+                       else
+                       {
+                               /*
+                                * Empty prefix from a server to server link:
+                                *  This is somewhat bad/naughty, so let's set the prefix
+                                *  to be the link that we got it from, so we don't break anything. -- w
+                                */
+                               TreeServer* n = Utils->FindServer(GetName());
+                               if (n)
+                                       prefix = n->GetID();
+                               else
+                                       prefix = GetName();
+                       }
+
+                       /*
+                        * First up, check for any malformed commands (e.g. MODE without a timestamp)
+                        * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
+                        */
+                       if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
+                               command = "MODE";
+
+                       if (command == "MODE")
+                       {
+                               if (params.size() >= 2)
+                               {
+                                       Channel* channel = Instance->FindChan(params[0]);
+                                       if (channel)
+                                       {
+                                               this->SendError("MODE may no longer be used on channels. Please use FMODE, with correct timestamp rules.");
+                                               return false;
+                                       }
+                               }
+                       }
+
+
+                       /*
+                        * Now, check for (and parse) commands as appropriate. -- w
+                        */     
+               
+                       /* Find the server that this command originated from, used in the handlers below */
+                       TreeServer *ServerSource = Utils->FindServer(prefix);
+
+                       /* Find the link we just got this from so we don't bounce it back incorrectly */
+                       std::string sourceserv = this->myhost;
+                       if (!this->InboundServerName.empty())
+                       {
+                               sourceserv = this->InboundServerName;
+                       }
+
+                       /*
+                        * XXX one of these days, this needs to be moved into class Commands.
+                        */
+                       if (command == "UID")
+                       {
+                               return this->ParseUID(prefix, params);
+                       }
+                       else if (command == "FJOIN")
+                       {
+                               return this->ForceJoin(prefix,params);
+                       }
+                       else if ((command == "NOTICE" || command == "PRIVMSG") && (Utils->IsServer(prefix)))
+                       {
+                               return this->ServerMessage(assign(command), prefix, params, sourceserv);
+                       }
+                       else if (command == "STATS")
+                       {
+                               return this->Stats(prefix, params);
+                       }
+                       else if (command == "MOTD")
+                       {
+                               return this->Motd(prefix, params);
+                       }
+                       else if (command == "KILL" && ServerSource)
+                       {
+                               // Kill from a server
+                               return this->RemoteKill(prefix,params);
+                       }
+                       else if (command == "MODULES")
+                       {
+                               return this->Modules(prefix, params);
+                       }
+                       else if (command == "ADMIN")
+                       {
+                               return this->Admin(prefix, params);
+                       }
+                       else if (command == "MAP")
+                       {
+                               User* user = Instance->FindNick(prefix);
+                               if (user)
+                               {
+                                       const char* ptrs[127];
+                                       for (size_t n = 0; (n < params.size()) && (n < 127); ++n)
+                                               ptrs[n] = params[n].c_str();
+                                       return Utils->Creator->HandleMap(ptrs, params.size(), user);
+                               }
+                       }
+                       else if (command == "SERVER")
+                       {
+                               return this->RemoteServer(prefix,params);
+                       }
+                       else if (command == "ERROR")
+                       {
+                               return this->Error(params);
+                       }
+                       else if (command == "OPERTYPE")
+                       {
+                               return this->OperType(prefix,params);
+                       }
+                       else if (command == "FMODE")
+                       {
+                               return this->ForceMode(prefix,params);
+                       }
+                       else if (command == "FTOPIC")
+                       {
+                               return this->ForceTopic(prefix,params);
+                       }
+                       else if (command == "REHASH")
+                       {
+                               return this->RemoteRehash(prefix,params);
+                       }
+                       else if (command == "METADATA")
+                       {
+                               return this->MetaData(prefix,params);
+                       }
+                       else if (command == "PING")
+                       {
+                               return this->LocalPing(prefix,params);
+                       }
+                       else if (command == "PONG")
+                       {
+                               return this->LocalPong(prefix,params);
+                       }
+                       else if (command == "VERSION")
+                       {
+                               return this->ServerVersion(prefix,params);
+                       }
+                       else if (command == "FHOST")
+                       {
+                               return this->ChangeHost(prefix,params);
+                       }
+                       else if (command == "FNAME")
+                       {
+                               return this->ChangeName(prefix,params);
+                       }
+                       else if (command == "ADDLINE")
+                       {
+                               return this->AddLine(prefix,params);
+                       }
+                       else if (command == "DELLINE")
+                       {
+                               return this->DelLine(prefix,params);
+                       }
+                       else if (command == "SVSNICK")
+                       {
+                               return this->ForceNick(prefix,params);
+                       }
+                       else if (command == "OPERQUIT")
+                       {
+                               return this->OperQuit(prefix,params);
+                       }
+                       else if (command == "IDLE")
+                       {
+                               return this->Whois(prefix,params);
+                       }
+                       else if (command == "PUSH")
+                       {
+                               return this->Push(prefix,params);
+                       }
+                       else if (command == "TIME")
+                       {
+                               return this->Time(prefix,params);
+                       }
+                       else if ((command == "KICK") && (Utils->IsServer(prefix)))
+                       {
+                               if (params.size() == 3)
+                               {
+                                       User* user = this->Instance->FindNick(params[1]);
+                                       Channel* chan = this->Instance->FindChan(params[0]);
+                                       if (user && chan)
+                                       {
+                                               if (!chan->ServerKickUser(user, params[2].c_str(), false))
+                                                       /* Yikes, the channels gone! */
+                                                       delete chan;
+                                       }
+                               }
+
+                               return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
+                       }
+                       else if (command == "SVSJOIN")
+                       {
+                               return this->ServiceJoin(prefix,params);
+                       }
+                       else if (command == "SVSPART")
+                       {
+                               return this->ServicePart(prefix,params);
+                       }
+                       else if (command == "SQUIT")
+                       {
+                               if (params.size() == 2)
+                               {
+                                       this->Squit(Utils->FindServer(params[0]),params[1]);
+                               }
+                               return true;
+                       }
+                       else if (command == "OPERNOTICE")
+                       {
+                               if (params.size() >= 1)
+                                       Instance->SNO->WriteToSnoMask('A', "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": " + params[0]);
+                               return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
+                       }
+                       else if (command == "MODENOTICE")
+                       {
+                               if (params.size() >= 2)
+                               {
+                                       if (ServerSource)
+                                               Instance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()), params[1].c_str());
+                               }
+                               return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
+                       }
+                       else if (command == "SNONOTICE")
+                       {
+                               if (params.size() >= 2)
+                               {
+                                       Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": "+ params[1]);
+                               }
+                               return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
+                       }
+                       else if (command == "BURST")
+                       {
+                               // Set prefix server as bursting
+                               if (!ServerSource)
+                               {
+                                       this->Instance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
+                                       return false;
+                               }
+                               
+                               ServerSource->bursting = true;
+                               return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
+                       }
+                       else if (command == "ENDBURST")
+                       {
+                               if (!ServerSource)
+                               {
+                                       this->Instance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
+                                       return false;
+                               }
+                               
+                               ServerSource->FinishBurst();
+                               return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
+                       }
+                       else if (command == "ENCAP")
+                       {
+                               return this->Encap(prefix, params);
+                       }
+                       else if (command == "MODE")
+                       {
+                               // Server-prefix MODE.
+                               const char* modelist[MAXPARAMETERS];
+                               for (size_t i = 0; i < params.size(); i++)
+                                       modelist[i] = params[i].c_str();
+
+                               /* We don't support this for channel mode changes any more! */
+                               if (params.size() >= 1)
+                               {
+                                       if (Instance->FindChan(params[0]))
+                                       {
+                                               this->SendError("Protocol violation by '"+(ServerSource ? ServerSource->GetName().c_str() : prefix)+"'! MODE for channel mode changes is not supported by the InspIRCd 1.2 protocol. You must use FMODE to preserve channel timestamps.");
+                                               return false;
+                                       }
+                               }
+                                       
+                               // Insert into the parser
+                               this->Instance->SendMode(modelist, params.size(), this->Instance->FakeClient);
+                               
+                               // Pass out to the network
+                               return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
+                       }
+                       else
+                       {
+                               /*
+                                * Not a special s2s command. Emulate the user doing it.
+                                * This saves us having a huge ugly command parser again.
+                                */
+                               User *who = this->Instance->FindUUID(prefix);
+
+                               if (!who)
+                               {
+                                       // this looks ugly because command is an irc::string
+                                       this->SendError("Command (" + std::string(command.c_str()) + ") from unknown prefix (" + prefix + ")! Dropping link.");
+                                       return false;
+                               }
+
+                               if (command == "NICK")
+                               {
+                                       if (params.size() != 2)
+                                       {
+                                               SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
+                                               return false;
+                                       }
+                                       /* Update timestamp on user when they change nicks */
+                                       who->age = atoi(params[1].c_str());
+
+                                       /*
+                                        * On nick messages, check that the nick doesnt already exist here.
+                                        * If it does, perform collision logic.
+                                        */
+                                       User* x = this->Instance->FindNickOnly(params[0]);
+                                       if ((x) && (x != who))
+                                       {
+                                               int collideret = 0;
+                                               /* x is local, who is remote */
+                                               collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
+                                               if (collideret != 1)
+                                               {
+                                                       /*
+                                                        * Remote client lost, or both lost, parsing this nickchange would be
+                                                        * pointless, as the incoming client's server will soon recieve SVSNICK to
+                                                        * change its nick to its UID. :) -- w00t
+                                                        */
+                                                       return true;
+                                               }
+                                       }
+                               }
+                                       
+                               // its a user
+                               const char* strparams[127];
+                               for (unsigned int q = 0; q < params.size(); q++)
+                               {
+                                       strparams[q] = params[q].c_str();
+                               }
+
+                               switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
+                               {
+                                       case CMD_INVALID:
+                                               // command is irc::string, hence ugliness
+                                               this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
+                                               return false;
+                                               break;
+                                       /*
+                                        * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
+                                        */
+                                       case CMD_FAILURE:
+                                               return true;
+                                               break;
+                                       default:
+                                               /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
+                                               break;
+                               }
+
+                               return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
+
+                       }
+                       return true;
+                       break; // end of state CONNECTED (phew).
+       }
+       return true;
+}
+
+std::string TreeSocket::GetName()
+{
+       std::string sourceserv = this->myhost;
+       if (!this->InboundServerName.empty())
+       {
+               sourceserv = this->InboundServerName;
+       }
+       return sourceserv;
+}
+
+void TreeSocket::OnTimeout()
+{
+       if (this->LinkState == CONNECTING)
+       {
+               Utils->Creator->RemoteMessage(NULL, "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
+               Link* MyLink = Utils->FindLink(myhost);
+               if (MyLink)
+                       Utils->DoFailOver(MyLink);
+       }
+}
+
+void TreeSocket::OnClose()
+{
+       // Test fix for big fuckup
+       if (this->LinkState != CONNECTED)
+               return;
+
+       // Connection closed.
+       // If the connection is fully up (state CONNECTED)
+       // then propogate a netsplit to all peers.
+       std::string quitserver = this->myhost;
+       if (!this->InboundServerName.empty())
+       {
+               quitserver = this->InboundServerName;
+       }
+       TreeServer* s = Utils->FindServer(quitserver);
+       if (s)
+       {
+               Squit(s,"Remote host closed the connection");
+       }
+
+       if (!quitserver.empty())
+       {
+               Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' failed.",quitserver.c_str());
+               time_t server_uptime = Instance->Time() - this->age;    
+               if (server_uptime)
+                       Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
+       }
+}
+
+int TreeSocket::OnIncomingConnection(int newsock, char* ip)
+{
+       /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
+        * or discovering if this port is the server port, we don't allow connections from any
+        * IPs for which we don't have a link block.
+        */
+       bool found = false;
+
+       found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
+       if (!found)
+       {
+               for (std::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)
+               {
+                       Utils->Creator->RemoteMessage(NULL,"Server connection from %s denied (no link blocks with that IP address)", ip);
+                       Instance->SE->Close(newsock);
+                       return false;
+               }
+       }
+
+       TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
+       s = s; /* Whinge whinge whinge, thats all GCC ever does. */
+       return true;
+}