X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=src%2Fmodules%2Fm_spanningtree.cpp;h=871675ed6afc65d03c0ed822de801aa82ca9cf92;hb=be70931a50f23c68e055602facce5736775f3fab;hp=71761000bc793eb25e5df386a76d66bb01e9cd86;hpb=6ee5b09346cbae737493cc193443f17ff1450347;p=user%2Fhenk%2Fcode%2Finspircd.git diff --git a/src/modules/m_spanningtree.cpp b/src/modules/m_spanningtree.cpp index 71761000b..871675ed6 100644 --- a/src/modules/m_spanningtree.cpp +++ b/src/modules/m_spanningtree.cpp @@ -1,13 +1,10 @@ -/* +------------------------------------+ - * | Inspire Internet Relay Chat Daemon | - * +------------------------------------+ +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits * - * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev. - * E-mail: - * - * - * - * Written by Craig Edwards, Craig McLure, and others. * This program is free but copyrighted software; see * the file COPYING for details. * @@ -26,12 +23,18 @@ #include "inspircd.h" #include "wildcard.h" #include "xline.h" -#include "aes.h" +#include "transport.h" /** If you make a change which breaks the protocol, increment this. * If you completely change the protocol, completely change the number. + * + * IMPORTANT: If you make changes, document your changes here, without fail: + * http://www.inspircd.org/wiki/List_of_protocol_changes_between_versions + * + * Failure to document your protocol changes will result in a painfully + * painful death by pain. You have been warned. */ -const long ProtocolVersion = 1101; +const long ProtocolVersion = 1103; /* * The server list in InspIRCd is maintained as two structures @@ -74,12 +77,19 @@ class TreeServer; class TreeSocket; class Link; class ModuleSpanningTree; +class SpanningTreeUtilities; /* This hash_map holds the hash equivalent of the server * tree, used for rapid linear lookups. */ typedef nspace::hash_map, irc::StrHashComp> server_hash; +typedef std::map TreeServerList; + +/** A group of modules that implement InspSocketHook + * that we can use to hook our server to server connections. + */ +typedef std::map hookmodules; /** The Link class might as well be a struct, * but this is C++ and we don't believe in structs (!). @@ -97,11 +107,26 @@ class Link : public classbase std::string RecvPass; unsigned long AutoConnect; time_t NextConnectTime; - std::string EncryptionKey; bool HiddenFromStats; std::string FailOver; + std::string Hook; + int Timeout; }; +class HandshakeTimer : public InspTimer +{ + private: + InspIRCd* Instance; + TreeSocket* sock; + Link* lnk; + SpanningTreeUtilities* Utils; + int thefd; + public: + HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u); + virtual void Tick(time_t TIME); +}; + + /** Contains helper functions and variables for this module, * and keeps them out of the global namespace */ @@ -124,6 +149,9 @@ class SpanningTreeUtilities /** Announce TS changes to channels on merge */ bool AnnounceTSChange; + /** Synchronize timestamps between servers + */ + bool EnableTimeSync; /** Socket bindings for listening sockets */ std::vector Bindings; @@ -140,6 +168,9 @@ class SpanningTreeUtilities */ std::vector LinkBlocks; + hookmodules hooks; + std::vector hooknames; + /** Initialise utility class */ SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator); @@ -148,43 +179,43 @@ class SpanningTreeUtilities ~SpanningTreeUtilities(); /** Send a message from this server to one other local or remote */ - bool DoOneToOne(std::string prefix, std::string command, std::deque ¶ms, std::string target); + bool DoOneToOne(const std::string &prefix, const std::string &command, std::deque ¶ms, std::string target); /** Send a message from this server to all but one other, local or remote */ - bool DoOneToAllButSender(std::string prefix, std::string command, std::deque ¶ms, std::string omit); + bool DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque ¶ms, std::string omit); /** Send a message from this server to all but one other, local or remote */ bool DoOneToAllButSender(const char* prefix, const char* command, std::deque ¶ms, std::string omit); /** Send a message from this server to all others */ - bool DoOneToMany(std::string prefix, std::string command, std::deque ¶ms); + bool DoOneToMany(const std::string &prefix, const std::string &command, std::deque ¶ms); /** Send a message from this server to all others */ bool DoOneToMany(const char* prefix, const char* command, std::deque ¶ms); /** Send a message from this server to all others, without doing any processing on the command (e.g. send it as-is with colons and all) */ - bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque ¶ms); + bool DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque ¶ms); /** Read the spanningtree module's tags from the config file */ void ReadConfiguration(bool rebind); /** Add a server to the server list for GetListOfServersForChannel */ - void AddThisServer(TreeServer* server, std::deque &list); + void AddThisServer(TreeServer* server, TreeServerList &list); /** Compile a list of servers which contain members of channel c */ - void GetListOfServersForChannel(chanrec* c, std::deque &list); + void GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list); /** Find a server by name */ - TreeServer* FindServer(std::string ServerName); + TreeServer* FindServer(const std::string &ServerName); /** Find a route to a server by name */ - TreeServer* BestRouteTo(std::string ServerName); + TreeServer* BestRouteTo(const std::string &ServerName); /** Find a server by glob mask */ - TreeServer* FindServerMask(std::string ServerName); + TreeServer* FindServerMask(const std::string &ServerName); /** Returns true if this is a server name we recognise */ - bool IsServer(std::string ServerName); + bool IsServer(const std::string &ServerName); /** Attempt to connect to the failover link of link x */ void DoFailOver(Link* x); @@ -247,7 +278,8 @@ class TreeServer : public classbase { Parent = NULL; VersionString = ""; - UserCount = OperCount = 0; + UserCount = ServerInstance->UserCount(); + OperCount = ServerInstance->OperCount(); VersionString = ServerInstance->GetVersionString(); Route = NULL; Socket = NULL; /* Fix by brain */ @@ -325,7 +357,7 @@ class TreeServer : public classbase ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str()); const char* reason_s = reason.c_str(); std::vector time_to_die; - for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++) + for (user_hash::iterator n = ServerInstance->clientlist->begin(); n != ServerInstance->clientlist->end(); n++) { if (!strcmp(n->second->server, this->ServerName.c_str())) { @@ -438,7 +470,7 @@ class TreeServer : public classbase return Parent; } - void SetVersion(std::string Version) + void SetVersion(const std::string &Version) { VersionString = Version; } @@ -519,7 +551,7 @@ class TreeServer : public classbase * there are more than a few servers to deal with. * (read as: lots). */ -TreeServer* SpanningTreeUtilities::FindServer(std::string ServerName) +TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName) { server_hash::iterator iter; iter = serverlist.find(ServerName.c_str()); @@ -539,7 +571,7 @@ TreeServer* SpanningTreeUtilities::FindServer(std::string ServerName) * See the comments for the constructor of TreeServer * for more details. */ -TreeServer* SpanningTreeUtilities::BestRouteTo(std::string ServerName) +TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName) { if (ServerName.c_str() == TreeRoot->GetName()) return NULL; @@ -560,7 +592,7 @@ TreeServer* SpanningTreeUtilities::BestRouteTo(std::string ServerName) * and match each one until we get a hit. Yes its slow, * deal with it. */ -TreeServer* SpanningTreeUtilities::FindServerMask(std::string ServerName) +TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName) { for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++) { @@ -571,7 +603,7 @@ TreeServer* SpanningTreeUtilities::FindServerMask(std::string ServerName) } /* A convenient wrapper that returns true if a server exists */ -bool SpanningTreeUtilities::IsServer(std::string ServerName) +bool SpanningTreeUtilities::IsServer(const std::string &ServerName) { return (FindServer(ServerName) != NULL); } @@ -587,12 +619,22 @@ class cmd_rconnect : public command_t cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util) { this->source = "m_spanningtree.so"; - syntax = " "; + syntax = " "; } CmdResult Handle (const char** parameters, int pcnt, userrec *user) { - user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]); + if (IS_LOCAL(user)) + { + if (!Utils->FindServer(parameters[0])) + { + user->WriteServ("NOTICE %s :*** RCONNECT: Server \002%s\002 isn't connected to the network!", user->nick, parameters[0]); + return CMD_FAILURE; + } + + user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]); + } + /* Is this aimed at our server? */ if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0])) { @@ -602,11 +644,9 @@ class cmd_rconnect : public command_t para[0] = parameters[1]; std::string original_command = std::string("CONNECT ") + parameters[1]; Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command); - - return CMD_SUCCESS; } - - return CMD_FAILURE; + + return CMD_SUCCESS; } }; @@ -636,11 +676,10 @@ class TreeSocket : public InspSocket time_t NextPing; bool LastPingWasGood; bool bursting; - AES* ctx_in; - AES* ctx_out; unsigned int keylength; std::string ModuleList; std::map CapKeys; + Module* Hook; public: @@ -649,71 +688,68 @@ class TreeSocket : public InspSocket * most of the action, and append a few of our own values * to it. */ - TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime) - : InspSocket(SI, host, port, listening, maxtime), Utils(Util) + TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod = NULL) + : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod) { myhost = host; this->LinkState = LISTENER; - this->ctx_in = NULL; - this->ctx_out = NULL; + + Instance->Log(DEBUG, "HOOK = %08x", Hook); + + if (listening && Hook) + InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send(); } - TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName) - : InspSocket(SI, host, port, listening, maxtime), Utils(Util) + TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName, Module* HookMod = NULL) + : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod) { myhost = ServerName; this->LinkState = CONNECTING; - this->ctx_in = NULL; - this->ctx_out = NULL; + + if (Hook) + InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send(); } /** When a listening socket gives us a new file descriptor, * we must associate it with a socket without creating a new * connection. This constructor is used for this purpose. */ - TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip) - : InspSocket(SI, newfd, ip), Utils(Util) + TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod = NULL) + : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod) { this->LinkState = WAIT_AUTH_1; - this->ctx_in = NULL; - this->ctx_out = NULL; - this->SendCapabilities(); + + /* If we have a transport module hooked to the parent, hook the same module to this + * socket, and set a timer waiting for handshake before we send CAPAB etc. + */ + if (Hook) + { + InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send(); + Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils)); + } + else + { + /* Otherwise, theres no lower layer transport in plain TCP/IP, + * so just send the capabilities right now. + */ + this->SendCapabilities(); + } } - ~TreeSocket() + ServerState GetLinkState() { - if (ctx_in) - DELETE(ctx_in); - if (ctx_out) - DELETE(ctx_out); + return this->LinkState; } - void InitAES(std::string key,std::string SName) + Module* GetHook() { - if (key == "") - return; + return this->Hook; + } - ctx_in = new AES(); - ctx_out = new AES(); - Instance->Log(DEBUG,"Initialized AES key %s",key.c_str()); - // key must be 16, 24, 32 etc bytes (multiple of 8) - keylength = key.length(); - if (!(keylength == 16 || keylength == 24 || keylength == 32)) - { - this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!"); - Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!"); - } - else - { - if (this->GetState() != I_ERROR) - { - this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str()); - ctx_in->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\ - \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength); - ctx_out->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\ - \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength); - } - } + ~TreeSocket() + { + if (Hook) + InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send(); } /** When an outbound connection finishes connecting, we receive @@ -732,21 +768,21 @@ class TreeSocket : public InspSocket if (x->Name == this->myhost) { this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "" : this->GetIP())+"] started."); - this->SendCapabilities(); - if (x->EncryptionKey != "") + + if (Hook) { - if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32)) - { - this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled."); - } - else - { - this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName); - this->InitAES(x->EncryptionKey,x->Name.c_str()); - } + InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send(); + this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "" : this->GetIP())+"] using transport \2"+x->Hook+"\2"); } + else + this->SendCapabilities(); + /* found who we're supposed to be connecting to, send the neccessary gubbins. */ - this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc); + if (Hook) + Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils)); + else + this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc); + return true; } } @@ -899,7 +935,7 @@ class TreeSocket : public InspSocket return result; } - bool Capab(std::deque params) + bool Capab(const std::deque ¶ms) { if (params.size() < 1) { @@ -1052,10 +1088,13 @@ class TreeSocket : public InspSocket * does some validation first and passes on the SQUIT to all * other remaining servers. */ - void Squit(TreeServer* Current,std::string reason) + void Squit(TreeServer* Current, const std::string &reason) { if ((Current) && (Current != Utils->TreeRoot)) { + Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server"); + rmode.Send(Instance); + std::deque params; params.push_back(Current->GetName()); params.push_back(":"+reason); @@ -1084,13 +1123,13 @@ class TreeSocket : public InspSocket } /** FMODE command - server mode with timestamp checks */ - bool ForceMode(std::string source, std::deque ¶ms) + bool ForceMode(const std::string &source, std::deque ¶ms) { /* Chances are this is a 1.0 FMODE without TS */ if (params.size() < 3) { - this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server"); - return false; + /* No modes were in the command, probably a channel with no modes set on it */ + return true; } bool smode = false; @@ -1472,7 +1511,7 @@ class TreeSocket : public InspSocket } /** FTOPIC command */ - bool ForceTopic(std::string source, std::deque ¶ms) + bool ForceTopic(const std::string &source, std::deque ¶ms) { if (params.size() != 4) return true; @@ -1516,7 +1555,7 @@ class TreeSocket : public InspSocket } /** FJOIN, similar to TS6 SJOIN, but not quite. */ - bool ForceJoin(std::string source, std::deque ¶ms) + bool ForceJoin(const std::string &source, std::deque ¶ms) { /* 1.1 FJOIN works as follows: * @@ -1577,6 +1616,7 @@ class TreeSocket : public InspSocket userrec* who = NULL; /* User we are currently checking */ std::string channel = params[0]; /* Channel name, as a string */ time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */ + bool created = false; /* Try and find the channel */ chanrec* chan = this->Instance->FindChan(channel); @@ -1587,11 +1627,13 @@ class TreeSocket : public InspSocket /* default TS is a high value, which if we dont have this * channel will let the other side apply their modes. */ - time_t ourTS = time(NULL)+600; + time_t ourTS = Instance->Time(true)+600; /* Does this channel exist? if it does, get its REAL timestamp */ if (chan) ourTS = chan->age; + else + created = true; /* don't perform deops, and set TS to correct time after processing. */ /* In 1.1, if they have the newer channel, we immediately clear * all status modes from our users. We then accept their modes. @@ -1601,20 +1643,23 @@ class TreeSocket : public InspSocket */ if (ourTS > TS) { + Instance->Log(DEBUG,"************ WE LOST TS COMPARE, DEOPPING EVERYONE ********************* "); std::deque param_list; - if (chan) - chan->age = TS; - /* Lower the TS here */ if (Utils->AnnounceTSChange && chan) chan->WriteChannelWithServ(Instance->Config->ServerName, - "TS for %s changed from %lu to %lu", chan->name, ourTS, TS); + "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS); ourTS = TS; - param_list.push_back(channel); - /* Zap all the privilage modes on our side */ - this->RemoveStatus(Instance->Config->ServerName, param_list); + /* Zap all the privilage modes on our side, if the channel exists here */ + if (!created) + { + param_list.push_back(channel); + /* Do this first! */ + chan->age = TS; + this->RemoveStatus(Instance->Config->ServerName, param_list); + } } /* Put the final parameter of the FJOIN into a tokenstream ready to split it */ @@ -1787,6 +1832,20 @@ class TreeSocket : public InspSocket free(mode_users[f]); } + /* if we newly created the channel, set it's TS properly. */ + if (created) + { + /* find created channel .. */ + chan = this->Instance->FindChan(channel); + if (chan) + /* w00t said this shouldnt be needed but it is. + * This isnt strictly true, as chan can be NULL + * if a nick collision has occured and therefore + * the channel was never created. + */ + chan->age = TS; + } + /* All done. That wasnt so bad was it, you can wipe * the sweat from your forehead now. :-) */ @@ -1794,7 +1853,7 @@ class TreeSocket : public InspSocket } /** NICK command */ - bool IntroduceClient(std::string source, std::deque ¶ms) + bool IntroduceClient(const std::string &source, std::deque ¶ms) { if (params.size() < 8) return true; @@ -1807,19 +1866,12 @@ class TreeSocket : public InspSocket // 0 1 2 3 4 5 6 7 time_t age = atoi(params[0].c_str()); - /* This used to have a pretty craq'y loop doing the same thing, - * now we just let the STL do the hard work (more efficiently) - */ - std::string::size_type pos_after_plus = params[5].find_first_not_of('+'); - if (pos_after_plus != std::string::npos) - params[5] = params[5].substr(pos_after_plus); - const char* tempnick = params[1].c_str(); Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str()); - user_hash::iterator iter = this->Instance->clientlist.find(tempnick); + user_hash::iterator iter = this->Instance->clientlist->find(tempnick); - if (iter != this->Instance->clientlist.end()) + if (iter != this->Instance->clientlist->end()) { // nick collision Instance->Log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,params[4].c_str(),params[2].c_str(),(unsigned long)age,(unsigned long)iter->second->age); @@ -1829,7 +1881,7 @@ class TreeSocket : public InspSocket } userrec* _new = new userrec(this->Instance); - this->Instance->clientlist[tempnick] = _new; + (*(this->Instance->clientlist))[tempnick] = _new; _new->SetFd(FD_MAGIC_NUMBER); strlcpy(_new->nick, tempnick,NICKMAX-1); strlcpy(_new->host, params[2].c_str(),63); @@ -1840,8 +1892,25 @@ class TreeSocket : public InspSocket _new->registered = REG_ALL; _new->signon = age; + /* + * we need to remove the + from the modestring, so we can do our stuff + */ + std::string::size_type pos_after_plus = params[5].find_first_not_of('+'); + if (pos_after_plus != std::string::npos) + params[5] = params[5].substr(pos_after_plus); + + for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++) + { _new->modes[(*v)-65] = 1; + /* For each mode thats set, increase counter */ + ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER); + if (mh) + mh->ChangeCount(1); + } + + /* now we've done with modes processing, put the + back for remote servers */ + params[5] = "+" + params[5]; #ifdef SUPPORT_IP6LINKS if (params[6].find_first_of(":") != std::string::npos) @@ -1850,10 +1919,12 @@ class TreeSocket : public InspSocket #endif _new->SetSockAddr(AF_INET, params[6].c_str(), 0); + Instance->AddGlobalClone(_new); + this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString()); params[7] = ":" + params[7]; - Utils->DoOneToAllButSender(source,"NICK",params,source); + Utils->DoOneToAllButSender(source,"NICK", params, source); // Increment the Source Servers User Count.. TreeServer* SourceServer = Utils->FindServer(source); @@ -1874,6 +1945,8 @@ class TreeSocket : public InspSocket */ void SendFJoins(TreeServer* Current, chanrec* c) { + std::string buffer; + Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name); char list[MAXBUF]; std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age); @@ -1899,7 +1972,8 @@ class TreeSocket : public InspSocket if (curlen > (480-NICKMAX)) { - this->WriteLine(list); + buffer.append(list).append("\r\n"); + dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age); ptr = list + dlen; ptrlen = 0; @@ -1908,64 +1982,102 @@ class TreeSocket : public InspSocket } if (numusers) - this->WriteLine(list); + buffer.append(list).append("\r\n"); + + /* Sorry for the hax. Because newly created channels assume +nt, + * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes. + */ + bool inverted = false; + if (!c->IsModeSet('n')) + { + modes.append("-n"); + inverted = true; + } + if (!c->IsModeSet('t')) + { + modes.append("-t"); + inverted = true; + } + if (inverted) + { + modes.append("+"); + } - for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++) - { + for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++) + { modes.append("b"); - params.append(b->data).append(" "); - } - this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+c->ChanModes(true)+modes+" "+params); + params.append(" ").append(b->data); + + if (params.length() >= MAXMODES) + { + /* Wrap at MAXMODES */ + buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params).append("\r\n"); + modes = ""; + params = ""; + } + } + + buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true)); + + /* Only send these if there are any */ + if (!modes.empty()) + buffer.append("\r\n").append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params); + + this->WriteLine(buffer); } /** Send G, Q, Z and E lines */ void SendXLines(TreeServer* Current) { char data[MAXBUF]; + std::string buffer; std::string n = this->Instance->Config->ServerName; const char* sn = n.c_str(); - int iterations = 0; + /* Yes, these arent too nice looking, but they get the job done */ - for (std::vector::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } - for (std::vector::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } - for (std::vector::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } - for (std::vector::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } - for (std::vector::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } - for (std::vector::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } - for (std::vector::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } - for (std::vector::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++) + for (std::vector::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++) { - snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); - this->WriteLine(data); + snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason); + buffer.append(data); } + + if (!buffer.empty()) + this->WriteLine(buffer); } /** Send channel modes and topics */ @@ -1973,10 +2085,9 @@ class TreeSocket : public InspSocket { char data[MAXBUF]; std::deque list; - int iterations = 0; std::string n = this->Instance->Config->ServerName; const char* sn = n.c_str(); - for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++) + for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++) { SendFJoins(Current, c->second); if (*c->second->topic) @@ -1999,8 +2110,8 @@ class TreeSocket : public InspSocket { char data[MAXBUF]; std::deque list; - int iterations = 0; - for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++) + std::string dataline; + for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++) { if (u->second->registered == REG_ALL) { @@ -2008,11 +2119,13 @@ class TreeSocket : public InspSocket this->WriteLine(data); if (*u->second->oper) { - this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper)); + snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper); + this->WriteLine(data); } if (*u->second->awaymsg) { - this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg)); + snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg); + this->WriteLine(data); } FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this)); list.clear(); @@ -2032,7 +2145,7 @@ class TreeSocket : public InspSocket */ void DoBurst(TreeServer* s) { - std::string burst = "BURST "+ConvToStr(time(NULL)); + std::string burst = "BURST "+ConvToStr(Instance->Time(true)); std::string endburst = "ENDBURST"; // Because by the end of the netburst, it could be gone! std::string name = s->GetName(); @@ -2078,33 +2191,13 @@ class TreeSocket : public InspSocket * chance of the \r being near the end of the * string, not the start. */ - if (ret.rfind("\r") != std::string::npos) - ret = in_buffer.substr(0,in_buffer.rfind("\r")-1); + if (ret.find("\r") != std::string::npos) + ret = in_buffer.substr(0,in_buffer.find("\r")-1); /* Process this one, abort if it * didnt return true. */ - if (this->ctx_in) - { - char out[1024]; - char result[1024]; - memset(result,0,1024); - memset(out,0,1024); - /* ERROR + CAPAB is still allowed unencryped */ - if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB ")) - { - int nbytes = from64tobits(out, ret.c_str(), 1024); - if ((nbytes > 0) && (nbytes < 1024)) - { - ctx_in->Decrypt(out, result, nbytes, 0); - for (int t = 0; t < nbytes; t++) - if (result[t] == '\7') result[t] = 0; - ret = result; - } - } - } if (!this->ProcessLine(ret)) { - Instance->Log(DEBUG,"ProcessLine says no!"); return false; } } @@ -2119,22 +2212,6 @@ class TreeSocket : public InspSocket int WriteLine(std::string line) { Instance->Log(DEBUG,"OUT: %s",line.c_str()); - if (this->ctx_out) - { - char result[10240]; - char result64[10240]; - if (this->keylength) - { - // pad it to the key length - int n = this->keylength - (line.length() % this->keylength); - if (n) - line.append(n,'\7'); - } - unsigned int ll = line.length(); - ctx_out->Encrypt(line.c_str(), result, ll, 0); - to64frombits((unsigned char*)result64,(unsigned char*)result,ll); - line = result64; - } line.append("\r\n"); return this->Write(line); } @@ -2150,7 +2227,7 @@ class TreeSocket : public InspSocket } /** remote MOTD. leet, huh? */ - bool Motd(std::string prefix, std::deque ¶ms) + bool Motd(const std::string &prefix, std::deque ¶ms) { if (params.size() > 0) { @@ -2198,7 +2275,7 @@ class TreeSocket : public InspSocket } /** remote ADMIN. leet, huh? */ - bool Admin(std::string prefix, std::deque ¶ms) + bool Admin(const std::string &prefix, std::deque ¶ms) { if (params.size() > 0) { @@ -2238,7 +2315,7 @@ class TreeSocket : public InspSocket return true; } - bool Stats(std::string prefix, std::deque ¶ms) + bool Stats(const std::string &prefix, std::deque ¶ms) { /* Get the reply to a STATS query if it matches this servername, * and send it back as a load of PUSH queries @@ -2278,7 +2355,7 @@ class TreeSocket : public InspSocket /** Because the core won't let users or even SERVERS set +o, * we use the OPERTYPE command to do this. */ - bool OperType(std::string prefix, std::deque ¶ms) + bool OperType(const std::string &prefix, std::deque ¶ms) { if (params.size() != 1) { @@ -2290,8 +2367,11 @@ class TreeSocket : public InspSocket if (u) { u->modes[UM_OPERATOR] = 1; + this->Instance->all_opers.push_back(u); strlcpy(u->oper,opertype.c_str(),NICKMAX-1); Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server); + 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())); + } return true; } @@ -2299,7 +2379,7 @@ class TreeSocket : public InspSocket /** Because Andy insists that services-compatible servers must * implement SVSNICK and SVSJOIN, that's exactly what we do :p */ - bool ForceNick(std::string prefix, std::deque ¶ms) + bool ForceNick(const std::string &prefix, std::deque ¶ms) { if (params.size() < 3) return true; @@ -2327,7 +2407,55 @@ class TreeSocket : public InspSocket return true; } - bool ServiceJoin(std::string prefix, std::deque ¶ms) + /* + * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally, + * then let that server do the dirty work (squit it!). Example: + * A -> B -> C -> D: oper on A squits D, A routes to B, B routes to C, C notices D connected locally, kills it. -- w00t + */ + bool RemoteSquit(const std::string &prefix, std::deque ¶ms) + { + /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */ + if (params.size() < 2) + return true; + + TreeServer* s = Utils->FindServerMask(params[0]); + + if (s) + { + if (s == Utils->TreeRoot) + { + this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str()); + return true; + } + + TreeSocket* sock = s->GetSocket(); + + if (sock) + { + /* it's locally connected, KILL IT! */ + Instance->Log(DEBUG,"Splitting server %s",s->GetName().c_str()); + Instance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s: %s", params[0].c_str(), prefix.c_str(), params[1].c_str()); + sock->Squit(s,"Server quit by " + prefix + ": " + params[1]); + Instance->SE->DelFd(sock); + sock->Close(); + delete sock; + } + else + { + /* route the rsquit */ + params[1] = ":" + params[1]; + Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]); + } + } + else + { + /* mother fucker! it doesn't exist */ + } + + return true; + } + + bool ServiceJoin(const std::string &prefix, std::deque ¶ms) { if (params.size() < 2) return true; @@ -2336,13 +2464,15 @@ class TreeSocket : public InspSocket if (u) { - chanrec::JoinUser(this->Instance, u, params[1].c_str(), false); + /* only join if it's local, otherwise just pass it on! */ + if (IS_LOCAL(u)) + chanrec::JoinUser(this->Instance, u, params[1].c_str(), false); Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix); } return true; } - bool RemoteRehash(std::string prefix, std::deque ¶ms) + bool RemoteRehash(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return false; @@ -2351,7 +2481,7 @@ class TreeSocket : public InspSocket if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask)) { - this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002."); + this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002."); this->Instance->RehashServer(); Utils->ReadConfiguration(false); InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance); @@ -2360,7 +2490,7 @@ class TreeSocket : public InspSocket return true; } - bool RemoteKill(std::string prefix, std::deque ¶ms) + bool RemoteKill(const std::string &prefix, std::deque ¶ms) { if (params.size() != 2) return true; @@ -2390,7 +2520,7 @@ class TreeSocket : public InspSocket return true; } - bool LocalPong(std::string prefix, std::deque ¶ms) + bool LocalPong(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return true; @@ -2431,7 +2561,7 @@ class TreeSocket : public InspSocket return true; } - bool MetaData(std::string prefix, std::deque ¶ms) + bool MetaData(const std::string &prefix, std::deque ¶ms) { if (params.size() < 3) return true; @@ -2467,7 +2597,7 @@ class TreeSocket : public InspSocket return true; } - bool ServerVersion(std::string prefix, std::deque ¶ms) + bool ServerVersion(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return true; @@ -2483,7 +2613,7 @@ class TreeSocket : public InspSocket return true; } - bool ChangeHost(std::string prefix, std::deque ¶ms) + bool ChangeHost(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return true; @@ -2498,7 +2628,7 @@ class TreeSocket : public InspSocket return true; } - bool AddLine(std::string prefix, std::deque ¶ms) + bool AddLine(const std::string &prefix, std::deque ¶ms) { if (params.size() < 6) return true; @@ -2555,7 +2685,7 @@ class TreeSocket : public InspSocket return true; } - bool ChangeName(std::string prefix, std::deque ¶ms) + bool ChangeName(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return true; @@ -2571,7 +2701,7 @@ class TreeSocket : public InspSocket return true; } - bool Whois(std::string prefix, std::deque ¶ms) + bool Whois(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return true; @@ -2593,7 +2723,7 @@ class TreeSocket : public InspSocket char idle[MAXBUF]; snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon); - snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL))); + snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true))); std::deque par; par.push_back(prefix); par.push_back(signon); @@ -2630,7 +2760,7 @@ class TreeSocket : public InspSocket return true; } - bool Push(std::string prefix, std::deque ¶ms) + bool Push(const std::string &prefix, std::deque ¶ms) { if (params.size() < 2) return true; @@ -2653,7 +2783,46 @@ class TreeSocket : public InspSocket return true; } - bool Time(std::string prefix, std::deque ¶ms) + bool HandleSetTime(const std::string &prefix, std::deque ¶ms) + { + if (!params.size() || !Utils->EnableTimeSync) + return true; + + bool force = false; + + if ((params.size() == 2) && (params[1] == "FORCE")) + force = true; + + time_t rts = atoi(params[0].c_str()); + time_t us = Instance->Time(true); + + if (rts == us) + { + Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str()); + + Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix); + } + else if (force || (rts < us)) + { + int old = Instance->SetTimeDelta(rts - us); + Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old); + + Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix); + } + else + { + Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str()); + + std::deque oparams; + oparams.push_back(ConvToStr(us)); + + Utils->DoOneToMany(prefix, "TIMESET", oparams); + } + + return true; + } + + bool Time(const std::string &prefix, std::deque ¶ms) { // :source.server TIME remote.server sendernick // :remote.server TIME source.server sendernick TS @@ -2665,9 +2834,7 @@ class TreeSocket : public InspSocket userrec* u = this->Instance->FindNick(params[1]); if (u) { - char curtime[256]; - snprintf(curtime,256,"%lu",(unsigned long)time(NULL)); - params.push_back(curtime); + params.push_back(ConvToStr(Instance->Time(false))); params[0] = prefix; Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]); } @@ -2703,7 +2870,7 @@ class TreeSocket : public InspSocket return true; } - bool LocalPing(std::string prefix, std::deque ¶ms) + bool LocalPing(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return true; @@ -2733,7 +2900,7 @@ class TreeSocket : public InspSocket } } - bool RemoveStatus(std::string prefix, std::deque ¶ms) + bool RemoveStatus(const std::string &prefix, std::deque ¶ms) { if (params.size() < 1) return true; @@ -2791,7 +2958,7 @@ class TreeSocket : public InspSocket return true; } - bool RemoteServer(std::string prefix, std::deque ¶ms) + bool RemoteServer(const std::string &prefix, std::deque ¶ms) { if (params.size() < 4) return false; @@ -2900,17 +3067,14 @@ class TreeSocket : public InspSocket this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName()); return false; } - /* If the config says this link is encrypted, but the remote side - * hasnt bothered to send the AES command before SERVER, then we - * boot them off as we MUST have this connection encrypted. - */ - if ((x->EncryptionKey != "") && (!this->ctx_in)) + this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "" : this->GetIP())+"] ("+description+")"); + + if (this->Hook) { - this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused."); - this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES."); - return false; + std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send(); + this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "" : this->GetIP())+"] using transport \2"+name+"\2"); } - this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "" : this->GetIP())+"] ("+description+")"); + this->InboundServerName = sname; this->InboundDescription = description; // this is good. Send our details: Our server name and description and hopcount of 0, @@ -2926,7 +3090,7 @@ class TreeSocket : public InspSocket return false; } - void Split(std::string line, std::deque &n) + void Split(const std::string &line, std::deque &n) { n.clear(); irc::tokenstream tokens(line); @@ -2936,17 +3100,17 @@ class TreeSocket : public InspSocket return; } - bool ProcessLine(std::string line) + bool ProcessLine(std::string &line) { std::deque params; irc::string command; std::string prefix; + line = line.substr(0, line.find_first_of("\r\n")); + if (line.empty()) return true; - line = line.substr(0, line.find_first_of("\r\n")); - Instance->Log(DEBUG,"IN: %s", line.c_str()); this->Split(line.c_str(),params); @@ -2960,24 +3124,6 @@ class TreeSocket : public InspSocket command = params[0].c_str(); params.pop_front(); - if ((!this->ctx_in) && (command == "AES")) - { - std::string sserv = params[0]; - for (std::vector::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++) - { - if ((x->EncryptionKey != "") && (x->Name == sserv)) - { - this->InitAES(x->EncryptionKey,sserv); - } - } - - return true; - } - else if ((this->ctx_in) && (command == "AES")) - { - this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str()); - } - switch (this->LinkState) { TreeServer* Node; @@ -3038,20 +3184,40 @@ class TreeSocket : public InspSocket } else if (command == "BURST") { - if (params.size()) + if (params.size() && Utils->EnableTimeSync) { - /* If a time stamp is provided, try and check syncronization */ - time_t THEM = atoi(params[0].c_str()); - long delta = THEM-time(NULL); + /* If a time stamp is provided, apply synchronization */ + bool force = false; + time_t them = atoi(params[0].c_str()); + time_t us = Instance->Time(true); + int delta = them - us; + + if ((params.size() == 2) && (params[1] == "FORCE")) + force = true; + if ((delta < -600) || (delta > 600)) { this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta)); this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!"); return false; } - else if ((delta < -60) || (delta > 60)) + + if (us == them) + { + this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back"); + } + else if (force || (us > them)) { - this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta)); + this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us); + this->Instance->SetTimeDelta(them - us); + // Send this new timestamp to any other servers + Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params); + } + else + { + // Override the timestamp + this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them); + this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us)); } } this->LinkState = CONNECTED; @@ -3252,6 +3418,10 @@ class TreeSocket : public InspSocket } return this->ForceNick(prefix,params); } + else if (command == "RSQUIT") + { + return this->RemoteSquit(prefix, params); + } else if (command == "IDLE") { return this->Whois(prefix,params); @@ -3260,6 +3430,10 @@ class TreeSocket : public InspSocket { return this->Push(prefix,params); } + else if (command == "TIMESET") + { + return this->HandleSetTime(prefix, params); + } else if (command == "TIME") { return this->Time(prefix,params); @@ -3300,6 +3474,42 @@ class TreeSocket : public InspSocket } return true; } + else if (command == "OPERNOTICE") + { + std::string sourceserv = this->myhost; + + if (this->InboundServerName != "") + sourceserv = this->InboundServerName; + + if (params.size() >= 1) + Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]); + + return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params); + } + else if (command == "MODENOTICE") + { + std::string sourceserv = this->myhost; + if (this->InboundServerName != "") + sourceserv = this->InboundServerName; + if (params.size() >= 2) + { + Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str()); + } + + return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params); + } + else if (command == "SNONOTICE") + { + std::string sourceserv = this->myhost; + if (this->InboundServerName != "") + sourceserv = this->InboundServerName; + if (params.size() >= 2) + { + Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]); + } + + return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params); + } else if (command == "ENDBURST") { this->bursting = false; @@ -3310,6 +3520,10 @@ class TreeSocket : public InspSocket sourceserv = this->InboundServerName; } this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str()); + + Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server"); + rmode.Send(Instance); + return true; } else @@ -3323,6 +3537,25 @@ class TreeSocket : public InspSocket { sourceserv = this->InboundServerName; } + if ((!who) && (command == "MODE")) + { + if (Utils->IsServer(prefix)) + { + const char* modelist[127]; + for (size_t i = 0; i < params.size(); i++) + modelist[i] = params[i].c_str(); + + userrec* fake = new userrec(Instance); + fake->SetFd(FD_MAGIC_NUMBER); + + this->Instance->SendMode(modelist, params.size(), fake); + + delete fake; + + /* Hot potato! pass it on! */ + return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params); + } + } if (who) { if ((command == "NICK") && (params.size() > 0)) @@ -3430,7 +3663,9 @@ class TreeSocket : public InspSocket { Squit(s,"Remote host closed the connection"); } - this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str()); + + if (quitserver != "") + this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str()); } virtual int OnIncomingConnection(int newsock, char* ip) @@ -3455,7 +3690,9 @@ class TreeSocket : public InspSocket return false; } } - TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip); + + TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook); + s = s; /* Whinge whinge whinge, thats all GCC ever does. */ return true; } @@ -3477,12 +3714,12 @@ class ServernameResolver : public Resolver Link MyLink; SpanningTreeUtilities* Utils; public: - ServernameResolver(SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(Util) + ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(Util) { /* Nothing in here, folks */ } - void OnLookupComplete(const std::string &result) + void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) { /* Initiate the connection, now that we have an IP to use. * Passing a hostname directly to InspSocket causes it to @@ -3491,7 +3728,12 @@ class ServernameResolver : public Resolver TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str()); if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */ { - TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str()); + + if ((!MyLink.Hook.empty()) && (Utils->hooks.find(MyLink.Hook.c_str()) == Utils->hooks.end())) + return; + + TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str(), + MyLink.Hook.empty() ? NULL : Utils->hooks[MyLink.Hook.c_str()]); if (newsocket->GetFd() > -1) { /* We're all OK */ @@ -3522,11 +3764,11 @@ class SecurityIPResolver : public Resolver Link MyLink; SpanningTreeUtilities* Utils; public: - SecurityIPResolver(SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(U) + SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(U) { } - void OnLookupComplete(const std::string &result) + void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) { ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str()); Utils->ValidIPs.push_back(result); @@ -3541,8 +3783,29 @@ class SecurityIPResolver : public Resolver SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C) { Bindings.clear(); - this->ReadConfiguration(true); + this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc); + + modulelist* ml = ServerInstance->FindInterface("InspSocketHook"); + + /* Did we find any modules? */ + if (ml) + { + /* Yes, enumerate them all to find out the hook name */ + for (modulelist::iterator m = ml->begin(); m != ml->end(); m++) + { + /* Make a request to it for its name, its implementing + * InspSocketHook so we know its safe to do this + */ + std::string name = InspSocketNameRequest((Module*)Creator, *m).Send(); + /* Build a map of them */ + hooks[name.c_str()] = *m; + hooknames.push_back(name); + ServerInstance->Log(DEBUG, "Found InspSocketHook interface: '%s' -> '%08x'", name.c_str(), *m); + } + } + + this->ReadConfiguration(true); } SpanningTreeUtilities::~SpanningTreeUtilities() @@ -3570,25 +3833,34 @@ SpanningTreeUtilities::~SpanningTreeUtilities() delete TreeRoot; } -void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque &list) +void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list) { - for (unsigned int c = 0; c < list.size(); c++) - { - if (list[c] == server) - { - return; - } - } - list.push_back(server); + if (list.find(server) == list.end()) + list[server] = server; } /** returns a list of DIRECT servernames for a specific channel */ -void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque &list) +void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list) { - CUList *ulist = c->GetUsers(); + CUList *ulist; + switch (status) + { + case '@': + ulist = c->GetOppedUsers(); + break; + case '%': + ulist = c->GetHalfoppedUsers(); + break; + case '+': + ulist = c->GetVoicedUsers(); + break; + default: + ulist = c->GetUsers(); + break; + } for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++) { - if (i->second->GetFd() < 0) + if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end())) { TreeServer* best = this->BestRouteTo(i->second->server); if (best) @@ -3598,8 +3870,9 @@ void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque ¶ms) +bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque ¶ms) { + char pfx = 0; TreeServer* omitroute = this->BestRouteTo(omit); if ((command == "NOTICE") || (command == "PRIVMSG")) { @@ -3608,6 +3881,7 @@ bool SpanningTreeUtilities::DoOneToAllButSenderRaw(std::string data, std::string /* Prefixes */ if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+')) { + pfx = params[0][0]; params[0] = params[0].substr(1, params[0].length()-1); } if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$')) @@ -3634,15 +3908,18 @@ bool SpanningTreeUtilities::DoOneToAllButSenderRaw(std::string data, std::string else { chanrec* c = ServerInstance->FindChan(params[0]); - if (c) + userrec* u = ServerInstance->FindNick(prefix); + if (c && u) { - std::deque list; - GetListOfServersForChannel(c,list); - unsigned int lsize = list.size(); - for (unsigned int i = 0; i < lsize; i++) + CUList elist; + TreeServerList list; + FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist)); + GetListOfServersForChannel(c,list,pfx,elist); + + for (TreeServerList::iterator i = list.begin(); i != list.end(); i++) { - TreeSocket* Sock = list[i]->GetSocket(); - if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i])) + TreeSocket* Sock = i->second->GetSocket(); + if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second)) { Sock->WriteLine(data); } @@ -3666,7 +3943,7 @@ bool SpanningTreeUtilities::DoOneToAllButSenderRaw(std::string data, std::string return true; } -bool SpanningTreeUtilities::DoOneToAllButSender(std::string prefix, std::string command, std::deque ¶ms, std::string omit) +bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque ¶ms, std::string omit) { TreeServer* omitroute = this->BestRouteTo(omit); std::string FullLine = ":" + prefix + " " + command; @@ -3693,7 +3970,7 @@ bool SpanningTreeUtilities::DoOneToAllButSender(std::string prefix, std::string return true; } -bool SpanningTreeUtilities::DoOneToMany(std::string prefix, std::string command, std::deque ¶ms) +bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque ¶ms) { std::string FullLine = ":" + prefix + " " + command; unsigned int words = params.size(); @@ -3729,7 +4006,7 @@ bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* return this->DoOneToAllButSender(spfx, scmd, params, omit); } -bool SpanningTreeUtilities::DoOneToOne(std::string prefix, std::string command, std::deque ¶ms, std::string target) +bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque ¶ms, std::string target) { TreeServer* Route = this->BestRouteTo(target); if (Route) @@ -3763,33 +4040,46 @@ void SpanningTreeUtilities::ReadConfiguration(bool rebind) { std::string Type = Conf->ReadValue("bind","type",j); std::string IP = Conf->ReadValue("bind","address",j); - int Port = Conf->ReadInteger("bind","port",j,true); + std::string Port = Conf->ReadValue("bind","port",j); + std::string transport = Conf->ReadValue("bind","transport",j); if (Type == "servers") { - ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), Port); - if (IP == "*") - { - IP = ""; - } - TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(),Port,true,10); - if (listener->GetState() == I_LISTENING) + irc::portparser portrange(Port, false); + int portno = -1; + while ((portno = portrange.GetToken())) { - ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), Port); - Bindings.push_back(listener); - } - else - { - ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port); - listener->Close(); - DELETE(listener); + ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno); + if (IP == "*") + IP = ""; + + if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end())) + { + ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for port %s:%s - maybe you forgot to load it BEFORE m_spanningtree in your config file? - Skipping this port binding", + transport.c_str(), IP.c_str(), Port.c_str()); + break; + } + + TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]); + if (listener->GetState() == I_LISTENING) + { + ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno); + Bindings.push_back(listener); + } + else + { + ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno); + listener->Close(); + DELETE(listener); + } + ServerInstance->Log(DEBUG,"Done with this binding"); } - ServerInstance->Log(DEBUG,"Done with this binding"); } } } FlatLinks = Conf->ReadFlag("options","flatlinks",0); HideULines = Conf->ReadFlag("options","hideulines",0); AnnounceTSChange = Conf->ReadFlag("options","announcets",0); + EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0)); LinkBlocks.clear(); ValidIPs.clear(); for (int j =0; j < Conf->Enumerate("link"); j++) @@ -3803,8 +4093,18 @@ void SpanningTreeUtilities::ReadConfiguration(bool rebind) L.SendPass = Conf->ReadValue("link","sendpass",j); L.RecvPass = Conf->ReadValue("link","recvpass",j); L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true); - L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j); L.HiddenFromStats = Conf->ReadFlag("link","hidden",j); + L.Timeout = Conf->ReadInteger("link","timeout",j,true); + L.Hook = Conf->ReadValue("link", "transport", j); + + if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end())) + { + ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for link '%s' - maybe you forgot to load it BEFORE m_spanningtree in your config file? Skipping tag completely.", + L.Hook.c_str(), L.Name.c_str()); + continue; + + } + L.NextConnectTime = time(NULL) + L.AutoConnect; /* Bugfix by brain, do not allow people to enter bad configurations */ if (L.Name != ServerInstance->Config->ServerName) @@ -3822,8 +4122,9 @@ void SpanningTreeUtilities::ReadConfiguration(bool rebind) { try { - SecurityIPResolver* sr = new SecurityIPResolver(this, ServerInstance, L.IPAddr, L); - ServerInstance->AddResolver(sr); + bool cached; + SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached); + ServerInstance->AddResolver(sr, cached); } catch (ModuleException& e) { @@ -3866,7 +4167,45 @@ void SpanningTreeUtilities::ReadConfiguration(bool rebind) DELETE(Conf); } +/** To create a timer which recurs every second, we inherit from InspTimer. + * InspTimer is only one-shot however, so at the end of each Tick() we simply + * insert another of ourselves into the pending queue :) + */ +class TimeSyncTimer : public InspTimer +{ + private: + InspIRCd *Instance; + ModuleSpanningTree *Module; + public: + TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod); + virtual void Tick(time_t TIME); +}; +HandshakeTimer::HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u) : InspTimer(1, time(NULL)), Instance(Inst), sock(s), lnk(l), Utils(u) +{ + thefd = sock->GetFd(); +} + +void HandshakeTimer::Tick(time_t TIME) +{ + if (Instance->SE->GetRef(thefd) == sock) + { + if (sock->GetHook() && InspSocketHSCompleteRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send()) + { + Instance->Log(DEBUG,"Handshake timer activated, sending SERVER and/or CAPAB"); + InspSocketAttachCertRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send(); + sock->SendCapabilities(); + if (sock->GetLinkState() == CONNECTING) + { + sock->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+lnk->SendPass+" 0 :"+this->Instance->Config->ServerDesc); + } + } + else + { + Instance->Timers->AddTimer(new HandshakeTimer(Instance, sock, lnk, Utils)); + } + } +} class ModuleSpanningTree : public Module { @@ -3878,14 +4217,25 @@ class ModuleSpanningTree : public Module SpanningTreeUtilities* Utils; public: + TimeSyncTimer *SyncTimer; ModuleSpanningTree(InspIRCd* Me) : Module::Module(Me), max_local(0), max_global(0) { + ServerInstance->UseInterface("InspSocketHook"); + Utils = new SpanningTreeUtilities(Me, this); command_rconnect = new cmd_rconnect(ServerInstance, this, Utils); ServerInstance->AddCommand(command_rconnect); + + if (Utils->EnableTimeSync) + { + SyncTimer = new TimeSyncTimer(ServerInstance, this); + ServerInstance->Timers->AddTimer(SyncTimer); + } + else + SyncTimer = NULL; } void ShowLinks(TreeServer* Current, userrec* user, int hops) @@ -3942,14 +4292,33 @@ class ModuleSpanningTree : public Module if (n_users > max_global) max_global = n_users; - user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs()); + unsigned int ulined_count = 0; + unsigned int ulined_local_count = 0; + + /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden, + * locally and globally (locally means directly connected to us) + */ + if ((Utils->HideULines) && (!*user->oper)) + { + for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++) + { + if (ServerInstance->ULine(q->second->GetName().c_str())) + { + ulined_count++; + if (q->second->GetParent() == Utils->TreeRoot) + ulined_local_count++; + } + } + } + + user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),ulined_count ? this->CountServs() - ulined_count : this->CountServs()); if (ServerInstance->OperCount()) user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount()); if (ServerInstance->UnregisteredUserCount()) user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount()); if (ServerInstance->ChannelCount()) user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount()); - user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs()); + user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs()); user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local); user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global); return; @@ -3981,13 +4350,13 @@ class ModuleSpanningTree : public Module float percent; char text[80]; - if (ServerInstance->clientlist.size() == 0) { + if (ServerInstance->clientlist->size() == 0) { // If there are no users, WHO THE HELL DID THE /MAP?!?!?! percent = 0; } else { - percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100; + percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist->size()) * 100; } snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent); totusers += Current->GetUserCount(); @@ -4153,7 +4522,7 @@ class ModuleSpanningTree : public Module { if (s == Utils->TreeRoot) { - user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]); + user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]); return 1; } TreeSocket* sock = s->GetSocket(); @@ -4161,14 +4530,18 @@ class ModuleSpanningTree : public Module { ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str()); ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick); - sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host)); + sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost()); ServerInstance->SE->DelFd(sock); sock->Close(); delete sock; } else { - user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]); + /* route it */ + std::deque params; + params.push_back(parameters[0]); + params.push_back(std::string(":Server quit by ") + user->GetFullRealHost()); + Utils->DoOneToOne(user->nick, "RSQUIT", params, parameters[0]); } } else @@ -4261,7 +4634,11 @@ class ModuleSpanningTree : public Module /* Do we already have an IP? If so, no need to resolve it. */ if (insp_aton(x->IPAddr.c_str(), &binip) > 0) { - TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str()); + /* Gave a hook, but it wasnt one we know */ + if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end())) + return; + + TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str(), x->Hook.empty() ? NULL : Utils->hooks[x->Hook.c_str()]); if (newsocket->GetFd() > -1) { /* Handled automatically on success */ @@ -4277,8 +4654,9 @@ class ModuleSpanningTree : public Module { try { - ServernameResolver* snr = new ServernameResolver(Utils, ServerInstance,x->IPAddr, *x); - ServerInstance->AddResolver(snr); + bool cached; + ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached); + ServerInstance->AddResolver(snr, cached); } catch (ModuleException& e) { @@ -4329,24 +4707,7 @@ class ModuleSpanningTree : public Module user->WriteServ("351 %s :%s",user->nick,Version.c_str()); if (found == Utils->TreeRoot) { - std::stringstream out(ServerInstance->Config->data005); - std::string token = ""; - std::string line5 = ""; - int token_counter = 0; - - while (!out.eof()) - { - out >> token; - line5 = line5 + token + " "; - token_counter++; - - if ((token_counter >= 13) || (out.eof() == true)) - { - user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str()); - line5 = ""; - token_counter = 0; - } - } + ServerInstance->Config->Send005(user); } } else @@ -4380,14 +4741,22 @@ class ModuleSpanningTree : public Module return 1; } + void BroadcastTimeSync() + { + std::deque params; + params.push_back(ConvToStr(ServerInstance->Time(true))); + Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params); + } + virtual int OnStats(char statschar, userrec* user, string_list &results) { - if (statschar == 'c') + if ((statschar == 'c') || (statschar == 'n')) { for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++) { - results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s'); - results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str()); + results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].Hook.empty() ? "plaintext" : Utils->LinkBlocks[i].Hook)+" "+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s'); + if (statschar == 'c') + results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str()); } results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report"); ServerInstance->SNO->WriteToSnoMask('t',"Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,ServerInstance->Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host); @@ -4523,7 +4892,7 @@ class ModuleSpanningTree : public Module } } - virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status) + virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list) { if (target_type == TYPE_USER) { @@ -4547,12 +4916,12 @@ class ModuleSpanningTree : public Module std::string cname = c->name; if (status) cname = status + cname; - std::deque list; - Utils->GetListOfServersForChannel(c,list); - unsigned int ucount = list.size(); - for (unsigned int i = 0; i < ucount; i++) + TreeServerList list; + Utils->GetListOfServersForChannel(c,list,status,exempt_list); + + for (TreeServerList::iterator i = list.begin(); i != list.end(); i++) { - TreeSocket* Sock = list[i]->GetSocket(); + TreeSocket* Sock = i->second->GetSocket(); if (Sock) Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text); } @@ -4572,7 +4941,7 @@ class ModuleSpanningTree : public Module } } - virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status) + virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list) { if (target_type == TYPE_USER) { @@ -4598,12 +4967,12 @@ class ModuleSpanningTree : public Module std::string cname = c->name; if (status) cname = status + cname; - std::deque list; - Utils->GetListOfServersForChannel(c,list); - unsigned int ucount = list.size(); - for (unsigned int i = 0; i < ucount; i++) + TreeServerList list; + Utils->GetListOfServersForChannel(c,list,status,exempt_list); + + for (TreeServerList::iterator i = list.begin(); i != list.end(); i++) { - TreeSocket* Sock = list[i]->GetSocket(); + TreeSocket* Sock = i->second->GetSocket(); if (Sock) Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text); } @@ -4634,17 +5003,29 @@ class ModuleSpanningTree : public Module // Only do this for local users if (IS_LOCAL(user)) { - std::deque params; - params.clear(); - params.push_back(channel->name); - // set up their permissions and the channel TS with FJOIN. - // All users are FJOINed now, because a module may specify - // new joining permissions for the user. - params.clear(); - params.push_back(channel->name); - params.push_back(ConvToStr(channel->age)); - params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick)); - Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params); + if (channel->GetUserCounter() == 1) + { + std::deque params; + // set up their permissions and the channel TS with FJOIN. + // All users are FJOINed now, because a module may specify + // new joining permissions for the user. + params.push_back(channel->name); + params.push_back(ConvToStr(channel->age)); + params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick)); + Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params); + /* First user in, sync the modes for the channel */ + params.pop_back(); + /* This is safe, all inspircd servers default to +nt */ + params.push_back("+nt"); + Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params); + } + else + { + std::deque params; + params.push_back(channel->name); + params.push_back(ConvToStr(channel->age)); + Utils->DoOneToMany(user->nick,"JOIN",params); + } } } @@ -4762,21 +5143,22 @@ class ModuleSpanningTree : public Module Utils->DoOneToMany(source->nick,"KILL",params); } - virtual void OnRehash(const std::string ¶meter) + virtual void OnRehash(userrec* user, const std::string ¶meter) { if (parameter != "") { std::deque params; params.push_back(parameter); - Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params); + Utils->DoOneToMany(user ? user->nick : ServerInstance->Config->ServerName, "REHASH", params); // check for self if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter)) { - ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName); + ServerInstance->WriteOpers("*** Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName); ServerInstance->RehashServer(); } } Utils->ReadConfiguration(false); + InitializeDisabledCommands(ServerInstance->Config->DisabledCommands, ServerInstance); } // note: the protocol does not allow direct umode +o except @@ -4794,26 +5176,39 @@ class ModuleSpanningTree : public Module void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason) { - if (IS_LOCAL(source)) + if (!source) { - char type[8]; - snprintf(type,8,"%cLINE",linetype); - std::string stype = type; - if (adding) - { - char sduration[MAXBUF]; - snprintf(sduration,MAXBUF,"%ld",duration); - std::deque params; - params.push_back(host); - params.push_back(sduration); - params.push_back(":"+reason); - Utils->DoOneToMany(source->nick,stype,params); - } - else + /* Server-set lines */ + char data[MAXBUF]; + snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false), + (unsigned long)duration, reason.c_str()); + std::deque params; + params.push_back(data); + Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params); + } + else + { + if (IS_LOCAL(source)) { - std::deque params; - params.push_back(host); - Utils->DoOneToMany(source->nick,stype,params); + char type[8]; + snprintf(type,8,"%cLINE",linetype); + std::string stype = type; + if (adding) + { + char sduration[MAXBUF]; + snprintf(sduration,MAXBUF,"%ld",duration); + std::deque params; + params.push_back(host); + params.push_back(sduration); + params.push_back(":"+reason); + Utils->DoOneToMany(source->nick,stype,params); + } + else + { + std::deque params; + params.push_back(host); + Utils->DoOneToMany(source->nick,stype,params); + } } } } @@ -4929,16 +5324,16 @@ class ModuleSpanningTree : public Module userrec* u = (userrec*)target; s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata); } - else if (target_type == TYPE_OTHER) - { - s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata); - } else if (target_type == TYPE_CHANNEL) { chanrec* c = (chanrec*)target; s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata); } } + if (target_type == TYPE_OTHER) + { + s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata); + } } virtual void OnEvent(Event* event) @@ -4958,7 +5353,7 @@ class ModuleSpanningTree : public Module return; (*params)[1] = ":" + (*params)[1]; params->insert(params->begin() + 1,ServerInstance->Config->ServerName); - params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time())); + params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true))); Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params); } else if (event->GetEventID() == "send_mode") @@ -4983,6 +5378,46 @@ class ModuleSpanningTree : public Module params->insert(params->begin() + 1,ConvToStr(ourTS)); Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params); } + else if (event->GetEventID() == "send_mode_explicit") + { + if (params->size() < 2) + return; + Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params); + } + else if (event->GetEventID() == "send_opers") + { + if (params->size() < 1) + return; + (*params)[0] = ":" + (*params)[0]; + Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params); + } + else if (event->GetEventID() == "send_modeset") + { + if (params->size() < 2) + return; + (*params)[1] = ":" + (*params)[1]; + Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params); + } + else if (event->GetEventID() == "send_snoset") + { + if (params->size() < 2) + return; + (*params)[1] = ":" + (*params)[1]; + Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params); + } + else if (event->GetEventID() == "send_push") + { + if (params->size() < 2) + return; + + userrec *a = ServerInstance->FindNick((*params)[0]); + + if (!a) + return; + + (*params)[1] = ":" + (*params)[1]; + Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server); + } } virtual ~ModuleSpanningTree() @@ -4990,6 +5425,10 @@ class ModuleSpanningTree : public Module ServerInstance->Log(DEBUG,"Performing unload of spanningtree!"); /* This will also free the listeners */ delete Utils; + if (SyncTimer) + ServerInstance->Timers->DelTimer(SyncTimer); + + ServerInstance->DoneWithInterface("InspSocketHook"); } virtual Version GetVersion() @@ -5021,6 +5460,17 @@ class ModuleSpanningTree : public Module } }; +TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod) +{ +} + +void TimeSyncTimer::Tick(time_t TIME) +{ + Module->BroadcastTimeSync(); + Module->SyncTimer = new TimeSyncTimer(Instance, Module); + Instance->Timers->AddTimer(Module->SyncTimer); +} + void SpanningTreeUtilities::DoFailOver(Link* x) { if (x->FailOver.length()) @@ -5055,7 +5505,6 @@ Link* SpanningTreeUtilities::FindLink(const std::string& name) return NULL; } - class ModuleSpanningTreeFactory : public ModuleFactory { public: