1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
19 #include "configreader.h"
23 #include "commands/cmd_whois.h"
24 #include "commands/cmd_stats.h"
32 /** If you make a change which breaks the protocol, increment this.
33 * If you completely change the protocol, completely change the number.
35 * IMPORTANT: If you make changes, document your changes here, without fail:
36 * http://www.inspircd.org/wiki/List_of_protocol_changes_between_versions
38 * Failure to document your protocol changes will result in a painfully
39 * painful death by pain. You have been warned.
41 const long ProtocolVersion = 1102;
44 * The server list in InspIRCd is maintained as two structures
45 * which hold the data in different ways. Most of the time, we
46 * want to very quicky obtain three pieces of information:
48 * (1) The information on a server
49 * (2) The information on the server we must send data through
50 * to actually REACH the server we're after
51 * (3) Potentially, the child/parent objects of this server
53 * The InspIRCd spanning protocol provides easy access to these
54 * by storing the data firstly in a recursive structure, where
55 * each item references its parent item, and a dynamic list
56 * of child items, and another structure which stores the items
57 * hashed, linearly. This means that if we want to find a server
58 * by name quickly, we can look it up in the hash, avoiding
59 * any O(n) lookups. If however, during a split or sync, we want
60 * to apply an operation to a server, and any of its child objects
61 * we can resort to recursion to walk the tree structure.
62 * Any socket can have one of five states at any one time.
63 * The LISTENER state indicates a socket which is listening
64 * for connections. It cannot receive data itself, only incoming
66 * The CONNECTING state indicates an outbound socket which is
67 * waiting to be writeable.
68 * The WAIT_AUTH_1 state indicates the socket is outbound and
69 * has successfully connected, but has not yet sent and received
71 * The WAIT_AUTH_2 state indicates that the socket is inbound
72 * (allocated by a LISTENER) but has not yet sent and received
74 * The CONNECTED state represents a fully authorized, fully
77 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
79 /* Foward declarations */
83 class ModuleSpanningTree;
84 class SpanningTreeUtilities;
86 /* This hash_map holds the hash equivalent of the server
87 * tree, used for rapid linear lookups.
89 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
91 typedef std::map<TreeServer*,TreeServer*> TreeServerList;
93 /** A group of modules that implement InspSocketHook
94 * that we can use to hook our server to server connections.
96 typedef std::map<irc::string, Module*> hookmodules;
98 /** The Link class might as well be a struct,
99 * but this is C++ and we don't believe in structs (!).
100 * It holds the entire information of one <link>
101 * tag from the main config file. We maintain a list
102 * of them, and populate the list on rehash/load.
104 class Link : public classbase
110 std::string SendPass;
111 std::string RecvPass;
112 unsigned long AutoConnect;
113 time_t NextConnectTime;
114 std::string EncryptionKey;
115 bool HiddenFromStats;
116 std::string FailOver;
121 class HandshakeTimer : public InspTimer
127 SpanningTreeUtilities* Utils;
130 HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u);
131 virtual void Tick(time_t TIME);
135 /** Contains helper functions and variables for this module,
136 * and keeps them out of the global namespace
138 class SpanningTreeUtilities
143 InspIRCd* ServerInstance;
147 ModuleSpanningTree* Creator;
148 /** Flatten links and /MAP for non-opers
151 /** Hide U-Lined servers in /MAP and /LINKS
154 /** Announce TS changes to channels on merge
156 bool AnnounceTSChange;
157 /** Synchronize timestamps between servers
160 /** Socket bindings for listening sockets
162 std::vector<TreeSocket*> Bindings;
163 /** This variable represents the root of the server tree
165 TreeServer *TreeRoot;
166 /** IPs allowed to link to us
168 std::vector<std::string> ValidIPs;
169 /** Hash of currently connected servers by name
171 server_hash serverlist;
172 /** Holds the data from the <link> tags in the conf
174 std::vector<Link> LinkBlocks;
177 std::vector<std::string> hooknames;
179 /** Initialise utility class
181 SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator);
182 /** Destroy class and free listeners etc
184 ~SpanningTreeUtilities();
185 /** Send a message from this server to one other local or remote
187 bool DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target);
188 /** Send a message from this server to all but one other, local or remote
190 bool DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit);
191 /** Send a message from this server to all but one other, local or remote
193 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit);
194 /** Send a message from this server to all others
196 bool DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms);
197 /** Send a message from this server to all others
199 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms);
200 /** 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)
202 bool DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms);
203 /** Read the spanningtree module's tags from the config file
205 void ReadConfiguration(bool rebind);
206 /** Add a server to the server list for GetListOfServersForChannel
208 void AddThisServer(TreeServer* server, TreeServerList &list);
209 /** Compile a list of servers which contain members of channel c
211 void GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list);
212 /** Find a server by name
214 TreeServer* FindServer(const std::string &ServerName);
215 /** Find a route to a server by name
217 TreeServer* BestRouteTo(const std::string &ServerName);
218 /** Find a server by glob mask
220 TreeServer* FindServerMask(const std::string &ServerName);
221 /** Returns true if this is a server name we recognise
223 bool IsServer(const std::string &ServerName);
224 /** Attempt to connect to the failover link of link x
226 void DoFailOver(Link* x);
227 /** Find a link tag from a server name
229 Link* FindLink(const std::string& name);
233 /** Each server in the tree is represented by one class of
234 * type TreeServer. A locally connected TreeServer can
235 * have a class of type TreeSocket associated with it, for
236 * remote servers, the TreeSocket entry will be NULL.
237 * Each server also maintains a pointer to its parent
238 * (NULL if this server is ours, at the top of the tree)
239 * and a pointer to its "Route" (see the comments in the
240 * constructors below), and also a dynamic list of pointers
241 * to its children which can be iterated recursively
242 * if required. Creating or deleting objects of type
243 i* TreeServer automatically maintains the hash_map of
244 * TreeServer items, deleting and inserting them as they
245 * are created and destroyed.
247 class TreeServer : public classbase
249 InspIRCd* ServerInstance; /* Creator */
250 TreeServer* Parent; /* Parent entry */
251 TreeServer* Route; /* Route entry */
252 std::vector<TreeServer*> Children; /* List of child objects */
253 irc::string ServerName; /* Server's name */
254 std::string ServerDesc; /* Server's description */
255 std::string VersionString; /* Version string or empty string */
256 int UserCount; /* Not used in this version */
257 int OperCount; /* Not used in this version */
258 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
259 time_t NextPing; /* After this time, the server should be PINGed*/
260 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
261 SpanningTreeUtilities* Utils; /* Utility class */
265 /** We don't use this constructor. Its a dummy, and won't cause any insertion
266 * of the TreeServer into the hash_map. See below for the two we DO use.
268 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance) : ServerInstance(Instance), Utils(Util)
274 UserCount = OperCount = 0;
275 VersionString = ServerInstance->GetVersionString();
278 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
279 * represents our own server. Therefore, it has no route, no parent, and
280 * no socket associated with it. Its version string is our own local version.
282 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util)
286 UserCount = ServerInstance->UserCount();
287 OperCount = ServerInstance->OperCount();
288 VersionString = ServerInstance->GetVersionString();
290 Socket = NULL; /* Fix by brain */
294 /** When we create a new server, we call this constructor to initialize it.
295 * This constructor initializes the server's Route and Parent, and sets up
296 * its ping counters so that it will be pinged one minute from now.
298 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
299 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util)
302 UserCount = OperCount = 0;
303 this->SetNextPingTime(time(NULL) + 60);
306 /* find the 'route' for this server (e.g. the one directly connected
307 * to the local server, which we can use to reach it)
309 * In the following example, consider we have just added a TreeServer
310 * class for server G on our network, of which we are server A.
311 * To route traffic to G (marked with a *) we must send the data to
312 * B (marked with a +) so this algorithm initializes the 'Route'
313 * value to point at whichever server traffic must be routed through
314 * to get here. If we were to try this algorithm with server B,
315 * the Route pointer would point at its own object ('this').
325 * We only run this algorithm when a server is created, as
326 * the routes remain constant while ever the server exists, and
327 * do not need to be re-calculated.
331 if (Route == Utils->TreeRoot)
337 while (this->Route->GetParent() != Utils->TreeRoot)
339 this->Route = Route->GetParent();
343 /* Because recursive code is slow and takes a lot of resources,
344 * we store two representations of the server tree. The first
345 * is a recursive structure where each server references its
346 * children and its parent, which is used for netbursts and
347 * netsplits to dump the whole dataset to the other server,
348 * and the second is used for very fast lookups when routing
349 * messages and is instead a hash_map, where each item can
350 * be referenced by its server name. The AddHashEntry()
351 * call below automatically inserts each TreeServer class
352 * into the hash_map as it is created. There is a similar
353 * maintainance call in the destructor to tidy up deleted
357 this->AddHashEntry();
360 int QuitUsers(const std::string &reason)
362 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
363 const char* reason_s = reason.c_str();
364 std::vector<userrec*> time_to_die;
365 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
367 if (!strcmp(n->second->server, this->ServerName.c_str()))
369 time_to_die.push_back(n->second);
372 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
374 userrec* a = (userrec*)*n;
375 ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
377 userrec::QuitUser(ServerInstance,a,reason_s);
379 return time_to_die.size();
382 /** This method is used to add the structure to the
383 * hash_map for linear searches. It is only called
384 * by the constructors.
388 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
389 if (iter == Utils->serverlist.end())
390 Utils->serverlist[this->ServerName.c_str()] = this;
393 /** This method removes the reference to this object
394 * from the hash_map which is used for linear searches.
395 * It is only called by the default destructor.
399 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
400 if (iter != Utils->serverlist.end())
401 Utils->serverlist.erase(iter);
404 /** These accessors etc should be pretty self-
407 TreeServer* GetRoute()
412 std::string GetName()
414 return ServerName.c_str();
417 std::string GetDesc()
422 std::string GetVersion()
424 return VersionString;
427 void SetNextPingTime(time_t t)
430 LastPingWasGood = false;
433 time_t NextPingTime()
438 bool AnsweredLastPing()
440 return LastPingWasGood;
445 LastPingWasGood = true;
468 TreeSocket* GetSocket()
473 TreeServer* GetParent()
478 void SetVersion(const std::string &Version)
480 VersionString = Version;
483 unsigned int ChildCount()
485 return Children.size();
488 TreeServer* GetChild(unsigned int n)
490 if (n < Children.size())
492 /* Make sure they cant request
493 * an out-of-range object. After
494 * all we know what these programmer
495 * types are like *grin*.
505 void AddChild(TreeServer* Child)
507 Children.push_back(Child);
510 bool DelChild(TreeServer* Child)
512 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
523 /** Removes child nodes of this node, and of that node, etc etc.
524 * This is used during netsplits to automatically tidy up the
525 * server tree. It is slow, we don't use it for much else.
529 bool stillchildren = true;
530 while (stillchildren)
532 stillchildren = false;
533 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
535 TreeServer* s = (TreeServer*)*a;
539 stillchildren = true;
548 /* We'd better tidy up after ourselves, eh? */
549 this->DelHashEntry();
553 /** Yay for fast searches!
554 * This is hundreds of times faster than recursion
555 * or even scanning a linked list, especially when
556 * there are more than a few servers to deal with.
559 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
561 server_hash::iterator iter;
562 iter = serverlist.find(ServerName.c_str());
563 if (iter != serverlist.end())
573 /** Returns the locally connected server we must route a
574 * message through to reach server 'ServerName'. This
575 * only applies to one-to-one and not one-to-many routing.
576 * See the comments for the constructor of TreeServer
579 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
581 if (ServerName.c_str() == TreeRoot->GetName())
583 TreeServer* Found = FindServer(ServerName);
586 return Found->GetRoute();
594 /** Find the first server matching a given glob mask.
595 * Theres no find-using-glob method of hash_map [awwww :-(]
596 * so instead, we iterate over the list using an iterator
597 * and match each one until we get a hit. Yes its slow,
600 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
602 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
604 if (match(i->first.c_str(),ServerName.c_str()))
610 /* A convenient wrapper that returns true if a server exists */
611 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
613 return (FindServer(ServerName) != NULL);
619 class cmd_rconnect : public command_t
622 SpanningTreeUtilities* Utils;
624 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
626 this->source = "m_spanningtree.so";
627 syntax = "<remote-server-mask> <servermask>";
630 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
632 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
633 /* Is this aimed at our server? */
634 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
636 /* Yes, initiate the given connect */
637 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
639 para[0] = parameters[1];
640 std::string original_command = std::string("CONNECT ") + parameters[1];
641 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
652 /** Every SERVER connection inbound or outbound is represented by
653 * an object of type TreeSocket.
654 * TreeSockets, being inherited from InspSocket, can be tied into
655 * the core socket engine, and we cn therefore receive activity events
656 * for them, just like activex objects on speed. (yes really, that
657 * is a technical term!) Each of these which relates to a locally
658 * connected server is assocated with it, by hooking it onto a
659 * TreeSocket class using its constructor. In this way, we can
660 * maintain a list of servers, some of which are directly connected,
661 * some of which are not.
663 class TreeSocket : public InspSocket
665 SpanningTreeUtilities* Utils;
667 std::string in_buffer;
668 ServerState LinkState;
669 std::string InboundServerName;
670 std::string InboundDescription;
672 int num_lost_servers;
674 bool LastPingWasGood;
678 unsigned int keylength;
679 std::string ModuleList;
680 std::map<std::string,std::string> CapKeys;
685 /** Because most of the I/O gubbins are encapsulated within
686 * InspSocket, we just call the superclass constructor for
687 * most of the action, and append a few of our own values
690 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod = NULL)
691 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
694 this->LinkState = LISTENER;
696 this->ctx_out = NULL;
698 Instance->Log(DEBUG, "HOOK = %08x", Hook);
700 if (listening && Hook)
701 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
704 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName, Module* HookMod = NULL)
705 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
708 this->LinkState = CONNECTING;
710 this->ctx_out = NULL;
713 /** When a listening socket gives us a new file descriptor,
714 * we must associate it with a socket without creating a new
715 * connection. This constructor is used for this purpose.
717 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod = NULL)
718 : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
720 this->LinkState = WAIT_AUTH_1;
722 this->ctx_out = NULL;
724 Instance->Log(DEBUG, "HOOK = %08x", Hook);
728 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
729 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils));
733 ServerState GetLinkState()
735 return this->LinkState;
751 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
754 void InitAES(std::string key,std::string SName)
761 Instance->Log(DEBUG,"Initialized AES key %s",key.c_str());
762 // key must be 16, 24, 32 etc bytes (multiple of 8)
763 keylength = key.length();
764 if (!(keylength == 16 || keylength == 24 || keylength == 32))
766 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
767 Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
771 if (this->GetState() != I_ERROR)
773 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
774 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\
775 \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);
776 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\
777 \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);
782 /** When an outbound connection finishes connecting, we receive
783 * this event, and must send our SERVER string to the other
784 * side. If the other side is happy, as outlined in the server
785 * to server docs on the inspircd.org site, the other side
786 * will then send back its own server string.
788 virtual bool OnConnected()
790 if (this->LinkState == CONNECTING)
792 /* we do not need to change state here. */
793 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
795 if (x->Name == this->myhost)
797 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
800 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
802 this->SendCapabilities();
804 if (x->EncryptionKey != "")
806 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
808 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.");
812 this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
813 this->InitAES(x->EncryptionKey,x->Name.c_str());
816 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
818 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
820 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
826 /* There is a (remote) chance that between the /CONNECT and the connection
827 * being accepted, some muppet has removed the <link> block and rehashed.
828 * If that happens the connection hangs here until it's closed. Unlikely
829 * and rather harmless.
831 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
835 virtual void OnError(InspSocketError e)
837 /* We don't handle this method, because all our
838 * dirty work is done in OnClose() (see below)
839 * which is still called on error conditions too.
841 if (e == I_ERR_CONNECT)
843 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
844 Link* MyLink = Utils->FindLink(myhost);
846 Utils->DoFailOver(MyLink);
850 virtual int OnDisconnect()
852 /* For the same reason as above, we don't
853 * handle OnDisconnect()
858 /** Recursively send the server tree with distances as hops.
859 * This is used during network burst to inform the other server
860 * (and any of ITS servers too) of what servers we know about.
861 * If at any point any of these servers already exist on the other
862 * end, our connection may be terminated. The hopcounts given
863 * by this function are relative, this doesn't matter so long as
864 * they are all >1, as all the remote servers re-calculate them
865 * to be relative too, with themselves as hop 0.
867 void SendServers(TreeServer* Current, TreeServer* s, int hops)
870 for (unsigned int q = 0; q < Current->ChildCount(); q++)
872 TreeServer* recursive_server = Current->GetChild(q);
873 if (recursive_server != s)
875 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
876 this->WriteLine(command);
877 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
878 /* down to next level */
879 this->SendServers(recursive_server, s, hops+1);
884 std::string MyCapabilities()
886 std::vector<std::string> modlist;
887 std::string capabilities = "";
889 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
891 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
892 modlist.push_back(this->Instance->Config->module_names[i]);
894 sort(modlist.begin(),modlist.end());
895 for (unsigned int i = 0; i < modlist.size(); i++)
898 capabilities = capabilities + ",";
899 capabilities = capabilities + modlist[i];
904 void SendCapabilities()
906 irc::commasepstream modulelist(MyCapabilities());
908 this->WriteLine("CAPAB START");
910 /* Send module names, split at 509 length */
911 std::string item = "*";
912 std::string line = "CAPAB MODULES ";
913 while ((item = modulelist.GetToken()) != "")
915 if (line.length() + item.length() + 1 > 509)
917 this->WriteLine(line);
918 line = "CAPAB MODULES ";
921 if (line != "CAPAB MODULES ")
926 if (line != "CAPAB MODULES ")
927 this->WriteLine(line);
934 #ifdef SUPPORT_IP6LINKS
937 this->WriteLine("CAPAB CAPABILITIES :NICKMAX="+ConvToStr(NICKMAX)+" HALFOP="+ConvToStr(this->Instance->Config->AllowHalfop)+" CHANMAX="+ConvToStr(CHANMAX)+" MAXMODES="+ConvToStr(MAXMODES)+" IDENTMAX="+ConvToStr(IDENTMAX)+" MAXQUIT="+ConvToStr(MAXQUIT)+" MAXTOPIC="+ConvToStr(MAXTOPIC)+" MAXKICK="+ConvToStr(MAXKICK)+" MAXGECOS="+ConvToStr(MAXGECOS)+" MAXAWAY="+ConvToStr(MAXAWAY)+" IP6NATIVE="+ConvToStr(ip6)+" IP6SUPPORT="+ConvToStr(ip6support)+" PROTOCOL="+ConvToStr(ProtocolVersion));
939 this->WriteLine("CAPAB END");
942 /* Check a comma seperated list for an item */
943 bool HasItem(const std::string &list, const std::string &item)
945 irc::commasepstream seplist(list);
947 std::string item2 = "*";
948 while ((item2 = seplist.GetToken()) != "")
957 /* Isolate and return the elements that are different between two comma seperated lists */
958 std::string ListDifference(const std::string &one, const std::string &two)
960 irc::commasepstream list_one(one);
961 std::string item = "*";
962 std::string result = "";
963 while ((item = list_one.GetToken()) != "")
965 if (!HasItem(two, item))
974 bool Capab(const std::deque<std::string> ¶ms)
976 if (params.size() < 1)
978 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
982 if (params[0] == "START")
984 this->ModuleList = "";
985 this->CapKeys.clear();
987 else if (params[0] == "END")
989 std::string reason = "";
991 #ifdef SUPPORT_IP6LINKS
994 /* Compare ModuleList and check CapKeys...
995 * Maybe this could be tidier? -- Brain
997 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
999 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
1002 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
1006 diff = "this server:" + diff;
1008 if (diff.length() == 12)
1009 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
1011 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
1014 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
1015 reason = "We don't both support linking to IPV6 servers";
1017 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
1018 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
1020 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
1021 reason = "Maximum nickname lengths differ or remote nickname length not specified";
1023 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
1025 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
1027 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
1031 reason = "Protocol version not specified";
1035 if (((this->CapKeys.find("HALFOP") == this->CapKeys.end()) && (Instance->Config->AllowHalfop)) || ((this->CapKeys.find("HALFOP") != this->CapKeys.end()) && (this->CapKeys.find("HALFOP")->second != ConvToStr(Instance->Config->AllowHalfop))))
1036 reason = "We don't both have halfop support enabled/disabled identically";
1038 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
1039 reason = "Maximum ident lengths differ or remote ident length not specified";
1041 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
1042 reason = "Maximum channel lengths differ or remote channel length not specified";
1044 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
1045 reason = "Maximum modes per line differ or remote modes per line not specified";
1047 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
1048 reason = "Maximum quit lengths differ or remote quit length not specified";
1050 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
1051 reason = "Maximum topic lengths differ or remote topic length not specified";
1053 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
1054 reason = "Maximum kick lengths differ or remote kick length not specified";
1056 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
1057 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
1059 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
1060 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
1062 if (reason.length())
1064 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
1068 else if ((params[0] == "MODULES") && (params.size() == 2))
1070 if (!this->ModuleList.length())
1072 this->ModuleList.append(params[1]);
1076 this->ModuleList.append(",");
1077 this->ModuleList.append(params[1]);
1080 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
1082 irc::tokenstream capabs(params[1]);
1083 std::string item = "*";
1084 while ((item = capabs.GetToken()) != "")
1086 /* Process each key/value pair */
1087 std::string::size_type equals = item.rfind('=');
1088 if (equals != std::string::npos)
1090 std::string var = item.substr(0, equals);
1091 std::string value = item.substr(equals+1, item.length());
1092 this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
1093 CapKeys[var] = value;
1101 /** This function forces this server to quit, removing this server
1102 * and any users on it (and servers and users below that, etc etc).
1103 * It's very slow and pretty clunky, but luckily unless your network
1104 * is having a REAL bad hair day, this function shouldnt be called
1105 * too many times a month ;-)
1107 void SquitServer(std::string &from, TreeServer* Current)
1109 /* recursively squit the servers attached to 'Current'.
1110 * We're going backwards so we don't remove users
1111 * while we still need them ;)
1113 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1115 TreeServer* recursive_server = Current->GetChild(q);
1116 this->SquitServer(from,recursive_server);
1118 /* Now we've whacked the kids, whack self */
1120 num_lost_users += Current->QuitUsers(from);
1123 /** This is a wrapper function for SquitServer above, which
1124 * does some validation first and passes on the SQUIT to all
1125 * other remaining servers.
1127 void Squit(TreeServer* Current, const std::string &reason)
1129 if ((Current) && (Current != Utils->TreeRoot))
1131 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
1132 rmode.Send(Instance);
1134 std::deque<std::string> params;
1135 params.push_back(Current->GetName());
1136 params.push_back(":"+reason);
1137 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1138 if (Current->GetParent() == Utils->TreeRoot)
1140 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1144 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1146 num_lost_servers = 0;
1148 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1149 SquitServer(from, Current);
1151 Current->GetParent()->DelChild(Current);
1153 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1157 Instance->Log(DEFAULT,"Squit from unknown server");
1161 /** FMODE command - server mode with timestamp checks */
1162 bool ForceMode(const std::string &source, std::deque<std::string> ¶ms)
1164 /* Chances are this is a 1.0 FMODE without TS */
1165 if (params.size() < 3)
1167 /* No modes were in the command, probably a channel with no modes set on it */
1172 std::string sourceserv;
1174 /* Are we dealing with an FMODE from a user, or from a server? */
1175 userrec* who = this->Instance->FindNick(source);
1178 /* FMODE from a user, set sourceserv to the users server name */
1179 sourceserv = who->server;
1183 /* FMODE from a server, create a fake user to receive mode feedback */
1184 who = new userrec(this->Instance);
1185 who->SetFd(FD_MAGIC_NUMBER);
1186 smode = true; /* Setting this flag tells us we should free the userrec later */
1187 sourceserv = source; /* Set sourceserv to the actual source string */
1189 const char* modelist[64];
1192 memset(&modelist,0,sizeof(modelist));
1193 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1197 /* The timestamp is in this position.
1198 * We don't want to pass that up to the
1199 * server->client protocol!
1201 TS = atoi(params[q].c_str());
1205 /* Everything else is fine to append to the modelist */
1206 modelist[n++] = params[q].c_str();
1210 /* Extract the TS value of the object, either userrec or chanrec */
1211 userrec* dst = this->Instance->FindNick(params[0]);
1212 chanrec* chan = NULL;
1220 chan = this->Instance->FindChan(params[0]);
1226 /* Oops, channel doesnt exist! */
1230 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1235 Instance->Log(DEBUG,"Entering TS equality check");
1236 ModeHandler* mh = NULL;
1237 unsigned long paramptr = 3;
1238 std::string to_bounce = "";
1239 std::string to_keep = "";
1240 std::vector<std::string> params_to_keep;
1241 std::string params_to_bounce = "";
1243 char cur_change = 1;
1244 char old_change = 0;
1245 char old_bounce_change = 0;
1246 /* Merge modes, basically do special stuff to mode with params */
1247 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1260 /* We only care about whats being set,
1261 * not whats being unset
1263 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1265 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1267 /* We only want to do special things to
1268 * modes with parameters, we are going to rewrite
1272 adding ? cur_change = '+' : cur_change = '-';
1274 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1276 /* The mode is set here, check which we should keep */
1279 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1281 if (which_to_keep == true)
1283 /* Keep ours, bounce theirs:
1284 * Send back ours to them and
1285 * drop their mode changs
1287 adding ? cur_change = '+' : cur_change = '-';
1288 if (cur_change != old_bounce_change)
1289 to_bounce += cur_change;
1291 old_bounce_change = cur_change;
1293 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1294 params_to_bounce.append(" ").append(ret.second);
1298 /* Keep theirs: Accept their mode change,
1301 adding ? cur_change = '+' : cur_change = '-';
1302 if (cur_change != old_change)
1303 to_keep += cur_change;
1305 old_change = cur_change;
1307 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1308 params_to_keep.push_back(params[paramptr]);
1313 /* Mode isnt set here, we want it */
1314 adding ? cur_change = '+' : cur_change = '-';
1315 if (cur_change != old_change)
1316 to_keep += cur_change;
1318 old_change = cur_change;
1320 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1321 params_to_keep.push_back(params[paramptr]);
1328 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1332 adding ? cur_change = '+' : cur_change = '-';
1334 /* Just keep this, safe to merge with no checks
1335 * it has no parameters
1338 if (cur_change != old_change)
1339 to_keep += cur_change;
1341 old_change = cur_change;
1343 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1345 Instance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1346 params_to_keep.push_back(params[paramptr++]);
1353 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1357 /* Taking a mode away */
1358 adding ? cur_change = '+' : cur_change = '-';
1360 if (cur_change != old_change)
1361 to_keep += cur_change;
1363 old_change = cur_change;
1365 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1366 params_to_keep.push_back(params[paramptr++]);
1373 if (to_bounce.length())
1375 std::deque<std::string> newparams;
1376 newparams.push_back(params[0]);
1377 newparams.push_back(ConvToStr(ourTS));
1378 newparams.push_back(to_bounce+params_to_bounce);
1379 Instance->Log(DEBUG,"BOUNCE BACK: %s",(to_bounce+params_to_bounce).c_str());
1380 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1383 if (to_keep.length())
1387 modelist[0] = params[0].c_str();
1388 modelist[1] = to_keep.c_str();
1390 if (params_to_keep.size() > 0)
1392 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1394 Instance->Log(DEBUG,"KEEP Item %d of %d: %s", q, params_to_keep.size(), params_to_keep[q].c_str());
1395 modelist[n++] = params_to_keep[q].c_str();
1401 Instance->Log(DEBUG,"Send mode");
1402 this->Instance->SendMode(modelist, n, who);
1406 Instance->Log(DEBUG,"Send mode client");
1407 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1410 /* HOT POTATO! PASS IT ON! */
1411 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1415 /* U-lined servers always win regardless of their TS */
1416 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1418 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1419 * SHOULD accept it, if its clock is right.
1421 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1422 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1423 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1425 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1426 * writing the code. It took me a while to come up with this solution.
1428 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1431 std::deque<std::string> newparams; /* New parameter list we send back */
1432 newparams.push_back(params[0]); /* Target, user or channel */
1433 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1434 newparams.push_back(""); /* This contains the mode string. For now
1435 * it's empty, we fill it below.
1438 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1439 * set to avoid a desync here.
1441 std::string modebounce = "";
1444 ModeHandler* mh = NULL;
1445 char cur_change = 1;
1446 char old_change = 0;
1447 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1449 /* Iterate over all mode chars in the sent set */
1452 /* Adding or subtracting modes? */
1460 /* Find the mode handler for this mode */
1461 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1463 /* Got a mode handler?
1464 * This also prevents us bouncing modes we have no handler for.
1471 /* Does the mode require a parameter right now?
1472 * If it does, fetch it if we can
1474 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1477 /* Call the ModeSet method to determine if its set with the
1478 * given parameter here or not.
1480 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1482 /* XXX: Really. Dont ask.
1483 * Determine from if its set combined with what the current
1484 * 'state' is (adding or not) as to wether we should 'invert'
1485 * or 'reinforce' the mode change
1487 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1489 /* Quickly determine if we have 'flipped' from + to -,
1490 * or - to +, to prevent unneccessary +/- chars in the
1491 * output string that waste bandwidth
1493 if (cur_change != old_change)
1494 modebounce += cur_change;
1495 old_change = cur_change;
1497 /* Add the mode character to the output string */
1498 modebounce += mh->GetModeChar();
1500 /* We got a parameter back from ModeHandler::ModeSet,
1501 * are we supposed to be sending one out right now?
1503 if (ret.second.length())
1505 if (mh->GetNumParams(cur_change == '+') > 0)
1506 /* Yes we're supposed to be sending out
1507 * the parameter. Make sure it goes
1509 newparams.push_back(ret.second);
1517 /* Update the parameters for FMODE with the new 'bounced' string */
1518 newparams[2] = modebounce;
1519 /* Only send it back the way it came, no need to send it anywhere else */
1520 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1521 Instance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1525 Instance->Log(DEBUG,"Allow modes, TS lower for sender");
1526 /* The server was ulined, but something iffy is up with the TS.
1527 * Sound the alarm bells!
1529 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1531 this->Instance->WriteOpers("\2WARNING!\2 U-Lined server '%s' has bad TS for '%s' (accepted change): \2SYNC YOUR CLOCKS\2 to avoid this notice",sourceserv.c_str(),params[0].c_str());
1533 /* Allow the mode, route it to either server or user command handling */
1535 this->Instance->SendMode(modelist,n,who);
1537 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1539 /* HOT POTATO! PASS IT ON! */
1540 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1542 /* Are we supposed to free the userrec? */
1549 /** FTOPIC command */
1550 bool ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
1552 if (params.size() != 4)
1554 time_t ts = atoi(params[1].c_str());
1555 std::string nsource = source;
1557 chanrec* c = this->Instance->FindChan(params[0]);
1560 if ((ts >= c->topicset) || (!*c->topic))
1562 std::string oldtopic = c->topic;
1563 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1564 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1566 /* if the topic text is the same as the current topic,
1567 * dont bother to send the TOPIC command out, just silently
1568 * update the set time and set nick.
1570 if (oldtopic != params[3])
1572 userrec* user = this->Instance->FindNick(source);
1575 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1579 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1580 nsource = user->server;
1582 /* all done, send it on its way */
1583 params[3] = ":" + params[3];
1584 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1593 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1594 bool ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
1596 /* 1.1 FJOIN works as follows:
1598 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1599 * timestamp 'wins'. From this point on we will refer to this side as the
1600 * winner. The side with the higher timestamp loses, from this point on we
1601 * will call this side the loser or losing side. This should be familiar to
1602 * anyone who's dealt with dreamforge or TS6 before.
1604 * When two sides of a split heal and this occurs, the following things
1607 * If the timestamps are exactly equal, both sides merge their privilages
1608 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1609 * re-created during a split, this is safe to do.
1612 * If the timestamps are NOT equal, the losing side removes all privilage
1613 * modes from all of its users that currently exist in the channel, before
1614 * introducing new users into the channel which are listed in the FJOIN
1615 * command's parameters. This means, all modes +ohv, and privilages added
1616 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1617 * of the channel to match that of the winning side, and the modes of the
1618 * users of the winning side are merged in with the losing side. The loser
1619 * then sends out a set of FMODE commands which 'confirm' that it just
1620 * removed all privilage modes from its existing users, which allows for
1621 * services packages to still work correctly without needing to know the
1622 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1623 * a problem, and services packages must contain code which explicitly
1624 * behaves as TS6 does, removing ops from the losing side of a split where
1625 * neccessary within its internal records, as this state information is
1626 * not explicitly echoed out in that protocol.
1628 * The winning side on the other hand will ignore all user modes from the
1629 * losing side, so only its own modes get applied. Life is simple for those
1630 * who succeed at internets. :-)
1632 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1633 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1634 * you ask? Well, quite simply because we don't need to. They'll be sent
1635 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1636 * the losing side sends any modes for the channel which shouldnt win,
1637 * they wont as their timestamp will be too high :-)
1640 if (params.size() < 3)
1643 char first[MAXBUF]; /* The first parameter of the mode command */
1644 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1645 char* mode_users[127]; /* The values used by the mode command */
1646 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1647 mode_users[0] = first; /* Set this up to be our on-stack value */
1648 mode_users[1] = modestring; /* Same here as above */
1649 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1650 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1652 userrec* who = NULL; /* User we are currently checking */
1653 std::string channel = params[0]; /* Channel name, as a string */
1654 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1655 bool created = false;
1657 /* Try and find the channel */
1658 chanrec* chan = this->Instance->FindChan(channel);
1660 /* Initialize channel name in the mode parameters */
1661 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1663 /* default TS is a high value, which if we dont have this
1664 * channel will let the other side apply their modes.
1666 time_t ourTS = Instance->Time(true)+600;
1668 /* Does this channel exist? if it does, get its REAL timestamp */
1672 created = true; /* don't perform deops, and set TS to correct time after processing. */
1674 /* In 1.1, if they have the newer channel, we immediately clear
1675 * all status modes from our users. We then accept their modes.
1676 * If WE have the newer channel its the other side's job to do this.
1677 * Note that this causes the losing server to send out confirming
1682 std::deque<std::string> param_list;
1684 /* Lower the TS here */
1685 if (Utils->AnnounceTSChange && chan)
1686 chan->WriteChannelWithServ(Instance->Config->ServerName,
1687 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1689 param_list.push_back(channel);
1691 /* Zap all the privilage modes on our side, if the channel exists here */
1694 this->RemoveStatus(Instance->Config->ServerName, param_list);
1699 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1700 irc::tokenstream users(params[2]);
1701 std::string item = "*";
1703 /* do this first, so our mode reversals are correctly received by other servers
1704 * if there is a TS collision.
1706 params[2] = ":" + params[2];
1707 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1709 /* Now, process every 'prefixes,nick' pair */
1712 /* Find next user */
1713 item = users.GetToken();
1715 const char* usr = item.c_str();
1717 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1718 * (is this even possible?) */
1721 const char* permissions = usr;
1723 char* nm = new char[MAXBUF];
1726 /* Iterate through all the prefix values, convert them from prefixes
1727 * to mode letters, and append them to the mode sequence
1729 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1731 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1734 /* This is a valid prefix */
1736 *tnm++ = mh->GetModeChar();
1740 /* Not a valid prefix...
1741 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1743 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1744 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1751 /* Null terminate modes */
1753 /* Advance past the comma, to the nick */
1756 /* Check the user actually exists */
1757 who = this->Instance->FindNick(usr);
1760 /* Did they get any modes? How many times? */
1761 strlcat(modestring, nm, MAXBUF);
1762 for (int k = 0; k < ntimes; k++)
1763 mode_users[modectr++] = strdup(usr);
1765 /* Free temporary buffer used for mode sequence */
1768 /* Check that the user's 'direction' is correct
1769 * based on the server sending the FJOIN. We must
1770 * check each nickname in turn, because the origin of
1771 * the FJOIN may be different to the origin of the nicks
1772 * in the command itself.
1774 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1775 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1777 /* Oh dear oh dear. */
1778 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1781 /* Finally, we can actually place the user into the channel.
1782 * We're sure its right. Final answer, phone a friend.
1784 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1786 /* Have we already queued up MAXMODES modes with parameters
1787 * (+qaohv) ready to be sent to the server?
1789 if (modectr >= (MAXMODES-1))
1791 /* Only actually give the users any status if we lost
1792 * the FJOIN or drew (equal timestamps).
1793 * It isn't actually possible for ourTS to be > TS here,
1794 * only possible to actually have ourTS == TS, or
1795 * ourTS < TS, because if we lost, we already lowered
1796 * our TS above before we entered this loop. We only
1797 * check >= as a safety measure, in case someone stuffed
1798 * up. If someone DID stuff up, it was most likely me.
1799 * Note: I do not like baseball bats in the face...
1803 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1804 this->Instance->SendMode((const char**)mode_users,modectr,who);
1806 /* Something stuffed up, and for some reason, the timestamp is
1807 * NOT lowered right now and should be. Lower it. Usually this
1808 * code won't be executed, doubtless someone will remove it some
1813 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1819 /* Reset all this back to defaults, and
1820 * free any ram we have left allocated.
1822 strcpy(mode_users[1],"+");
1823 for (unsigned int f = 2; f < modectr; f++)
1824 free(mode_users[f]);
1830 /* Remember to free this */
1832 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1833 * We don't try to process the nickname here (that WOULD cause a segfault because
1834 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1835 * in case somehow we're desynched, so that other users which might be able to see
1836 * the nickname get their fair chance to process it.
1838 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1844 /* there werent enough modes built up to flush it during FJOIN,
1845 * or, there are a number left over. flush them out.
1847 if ((modectr > 2) && (who) && (chan))
1851 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1852 this->Instance->SendMode((const char**)mode_users,modectr,who);
1853 /* Yet again, we can't actually get a true value here, if everything else
1854 * is working as it should.
1858 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1864 /* Free anything we have left to free */
1865 for (unsigned int f = 2; f < modectr; f++)
1866 free(mode_users[f]);
1869 /* if we newly created the channel, set it's TS properly. */
1872 /* find created channel .. */
1873 chan = this->Instance->FindChan(channel);
1875 /* w00t said this shouldnt be needed but it is.
1876 * This isnt strictly true, as chan can be NULL
1877 * if a nick collision has occured and therefore
1878 * the channel was never created.
1883 /* All done. That wasnt so bad was it, you can wipe
1884 * the sweat from your forehead now. :-)
1890 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1892 if (params.size() < 8)
1894 if (params.size() > 8)
1896 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1899 // NICK age nick host dhost ident +modes ip :gecos
1901 time_t age = atoi(params[0].c_str());
1903 /* This used to have a pretty craq'y loop doing the same thing,
1904 * now we just let the STL do the hard work (more efficiently)
1906 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1907 if (pos_after_plus != std::string::npos)
1908 params[5] = params[5].substr(pos_after_plus);
1910 const char* tempnick = params[1].c_str();
1911 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1913 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1915 if (iter != this->Instance->clientlist.end())
1918 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);
1919 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1920 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1924 userrec* _new = new userrec(this->Instance);
1925 this->Instance->clientlist[tempnick] = _new;
1926 _new->SetFd(FD_MAGIC_NUMBER);
1927 strlcpy(_new->nick, tempnick,NICKMAX-1);
1928 strlcpy(_new->host, params[2].c_str(),63);
1929 strlcpy(_new->dhost, params[3].c_str(),63);
1930 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1931 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1932 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1933 _new->registered = REG_ALL;
1936 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1937 _new->modes[(*v)-65] = 1;
1939 #ifdef SUPPORT_IP6LINKS
1940 if (params[6].find_first_of(":") != std::string::npos)
1941 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1944 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1946 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1948 params[7] = ":" + params[7];
1949 Utils->DoOneToAllButSender(source,"NICK",params,source);
1951 // Increment the Source Servers User Count..
1952 TreeServer* SourceServer = Utils->FindServer(source);
1955 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1956 SourceServer->AddUserCount();
1959 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1964 /** Send one or more FJOINs for a channel of users.
1965 * If the length of a single line is more than 480-NICKMAX
1966 * in length, it is split over multiple lines.
1968 void SendFJoins(TreeServer* Current, chanrec* c)
1972 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1974 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1976 size_t dlen, curlen;
1977 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1979 char* ptr = list + dlen;
1981 CUList *ulist = c->GetUsers();
1982 std::string modes = "";
1983 std::string params = "";
1985 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1987 // The first parameter gets a : before it
1988 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1995 if (curlen > (480-NICKMAX))
1997 buffer.append(list).append("\r\n");
1999 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
2007 buffer.append(list).append("\r\n");
2009 /* Sorry for the hax. Because newly created channels assume +nt,
2010 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
2012 bool inverted = false;
2013 if (!c->IsModeSet('n'))
2018 if (!c->IsModeSet('t'))
2028 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
2031 params.append(" ").append(b->data);
2033 if (params.length() >= MAXMODES)
2035 /* Wrap at MAXMODES */
2036 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");
2042 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
2044 /* Only send these if there are any */
2046 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);
2048 this->WriteLine(buffer);
2051 /** Send G, Q, Z and E lines */
2052 void SendXLines(TreeServer* Current)
2056 std::string n = this->Instance->Config->ServerName;
2057 const char* sn = n.c_str();
2059 /* Yes, these arent too nice looking, but they get the job done */
2060 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
2062 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);
2063 buffer.append(data);
2065 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
2067 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);
2068 buffer.append(data);
2070 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
2072 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);
2073 buffer.append(data);
2075 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
2077 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);
2078 buffer.append(data);
2080 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
2082 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);
2083 buffer.append(data);
2085 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
2087 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);
2088 buffer.append(data);
2090 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
2092 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);
2093 buffer.append(data);
2095 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
2097 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);
2098 buffer.append(data);
2101 if (!buffer.empty())
2102 this->WriteLine(buffer);
2105 /** Send channel modes and topics */
2106 void SendChannelModes(TreeServer* Current)
2109 std::deque<std::string> list;
2111 std::string n = this->Instance->Config->ServerName;
2112 const char* sn = n.c_str();
2113 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2115 SendFJoins(Current, c->second);
2116 if (*c->second->topic)
2118 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2119 this->WriteLine(data);
2121 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2123 c->second->GetExtList(list);
2124 for (unsigned int j = 0; j < list.size(); j++)
2126 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2131 /** send all users and their oper state/modes */
2132 void SendUsers(TreeServer* Current)
2135 std::deque<std::string> list;
2136 std::string dataline;
2138 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2140 if (u->second->registered == REG_ALL)
2142 snprintf(data,MAXBUF,":%s NICK %lu %s %s %s %s +%s %s :%s",u->second->server,(unsigned long)u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->FormatModes(),u->second->GetIPString(),u->second->fullname);
2143 this->WriteLine(data);
2144 if (*u->second->oper)
2146 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2147 this->WriteLine(data);
2149 if (*u->second->awaymsg)
2151 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2152 this->WriteLine(data);
2154 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2156 u->second->GetExtList(list);
2157 for (unsigned int j = 0; j < list.size(); j++)
2159 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2165 /** This function is called when we want to send a netburst to a local
2166 * server. There is a set order we must do this, because for example
2167 * users require their servers to exist, and channels require their
2168 * users to exist. You get the idea.
2170 void DoBurst(TreeServer* s)
2172 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2173 std::string endburst = "ENDBURST";
2174 // Because by the end of the netburst, it could be gone!
2175 std::string name = s->GetName();
2176 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2177 this->WriteLine(burst);
2178 /* send our version string */
2179 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2180 /* Send server tree */
2181 this->SendServers(Utils->TreeRoot,s,1);
2182 /* Send users and their oper status */
2184 /* Send everything else (channel modes, xlines etc) */
2185 this->SendChannelModes(s);
2186 this->SendXLines(s);
2187 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2188 this->WriteLine(endburst);
2189 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2192 /** This function is called when we receive data from a remote
2193 * server. We buffer the data in a std::string (it doesnt stay
2194 * there for long), reading using InspSocket::Read() which can
2195 * read up to 16 kilobytes in one operation.
2197 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2198 * THE SOCKET OBJECT FOR US.
2200 virtual bool OnDataReady()
2202 char* data = this->Read();
2203 /* Check that the data read is a valid pointer and it has some content */
2206 this->in_buffer.append(data);
2207 /* While there is at least one new line in the buffer,
2208 * do something useful (we hope!) with it.
2210 while (in_buffer.find("\n") != std::string::npos)
2212 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2213 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2214 /* Use rfind here not find, as theres more
2215 * chance of the \r being near the end of the
2216 * string, not the start.
2218 if (ret.find("\r") != std::string::npos)
2219 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2220 /* Process this one, abort if it
2221 * didnt return true.
2227 memset(result,0,1024);
2229 /* ERROR + CAPAB is still allowed unencryped */
2230 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2232 int nbytes = from64tobits(out, ret.c_str(), 1024);
2233 if ((nbytes > 0) && (nbytes < 1024))
2235 ctx_in->Decrypt(out, result, nbytes, 0);
2236 for (int t = 0; t < nbytes; t++)
2238 if (result[t] == '\7')
2240 /* We only need to stick a \0 on the
2241 * first \7, the rest will be lost
2251 if (!this->ProcessLine(ret))
2258 /* EAGAIN returns an empty but non-NULL string, so this
2259 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2261 return (data && !*data);
2264 int WriteLine(std::string line)
2266 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2270 char result64[10240];
2271 if (this->keylength)
2273 // pad it to the key length
2274 int n = this->keylength - (line.length() % this->keylength);
2276 line.append(n,'\7');
2278 unsigned int ll = line.length();
2279 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2280 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2283 line.append("\r\n");
2284 return this->Write(line);
2287 /* Handle ERROR command */
2288 bool Error(std::deque<std::string> ¶ms)
2290 if (params.size() < 1)
2292 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2293 /* we will return false to cause the socket to close. */
2297 /** remote MOTD. leet, huh? */
2298 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2300 if (params.size() > 0)
2302 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2304 /* It's for our server */
2305 string_list results;
2306 userrec* source = this->Instance->FindNick(prefix);
2310 std::deque<std::string> par;
2311 par.push_back(prefix);
2314 if (!Instance->Config->MOTD.size())
2316 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2317 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2321 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2322 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2324 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2326 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2327 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2330 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2331 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2337 userrec* source = this->Instance->FindNick(prefix);
2339 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2345 /** remote ADMIN. leet, huh? */
2346 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2348 if (params.size() > 0)
2350 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2352 /* It's for our server */
2353 string_list results;
2354 userrec* source = this->Instance->FindNick(prefix);
2358 std::deque<std::string> par;
2359 par.push_back(prefix);
2362 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2363 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2365 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2366 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2368 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2369 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2371 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2372 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2378 userrec* source = this->Instance->FindNick(prefix);
2380 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2386 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2388 /* Get the reply to a STATS query if it matches this servername,
2389 * and send it back as a load of PUSH queries
2391 if (params.size() > 1)
2393 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2395 /* It's for our server */
2396 string_list results;
2397 userrec* source = this->Instance->FindNick(prefix);
2400 std::deque<std::string> par;
2401 par.push_back(prefix);
2403 DoStats(this->Instance, *(params[0].c_str()), source, results);
2404 for (size_t i = 0; i < results.size(); i++)
2406 par[1] = "::" + results[i];
2407 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2414 userrec* source = this->Instance->FindNick(prefix);
2416 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2423 /** Because the core won't let users or even SERVERS set +o,
2424 * we use the OPERTYPE command to do this.
2426 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2428 if (params.size() != 1)
2430 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2433 std::string opertype = params[0];
2434 userrec* u = this->Instance->FindNick(prefix);
2437 u->modes[UM_OPERATOR] = 1;
2438 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2439 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2444 /** Because Andy insists that services-compatible servers must
2445 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2447 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2449 if (params.size() < 3)
2452 userrec* u = this->Instance->FindNick(params[0]);
2456 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2459 std::deque<std::string> par;
2460 par.push_back(params[1]);
2461 /* This is not required as one is sent in OnUserPostNick below
2463 //Utils->DoOneToMany(u->nick,"NICK",par);
2464 if (!u->ForceNickChange(params[1].c_str()))
2466 userrec::QuitUser(this->Instance, u, "Nickname collision");
2469 u->age = atoi(params[2].c_str());
2476 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
2477 * then let that server do the dirty work (squit it!). Example:
2478 * 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
2480 bool RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
2482 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
2483 if (params.size() < 2)
2486 TreeServer* s = Utils->FindServerMask(params[0]);
2490 if (s == Utils->TreeRoot)
2492 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
2496 TreeSocket* sock = s->GetSocket();
2500 /* it's locally connected, KILL IT! */
2501 Instance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
2502 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());
2503 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
2504 Instance->SE->DelFd(sock);
2510 /* route the rsquit */
2511 params[1] = ":" + params[1];
2512 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
2517 /* mother fucker! it doesn't exist */
2523 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2525 if (params.size() < 2)
2528 userrec* u = this->Instance->FindNick(params[0]);
2532 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2533 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2538 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2540 if (params.size() < 1)
2543 std::string servermask = params[0];
2545 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2547 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2548 this->Instance->RehashServer();
2549 Utils->ReadConfiguration(false);
2550 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2552 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2556 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2558 if (params.size() != 2)
2561 std::string nick = params[0];
2562 userrec* u = this->Instance->FindNick(prefix);
2563 userrec* who = this->Instance->FindNick(nick);
2567 /* Prepend kill source, if we don't have one */
2568 std::string sourceserv = prefix;
2571 sourceserv = u->server;
2573 if (*(params[1].c_str()) != '[')
2575 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2577 std::string reason = params[1];
2578 params[1] = ":" + params[1];
2579 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2580 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2581 userrec::QuitUser(this->Instance,who,reason);
2586 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2588 if (params.size() < 1)
2591 if (params.size() == 1)
2593 TreeServer* ServerSource = Utils->FindServer(prefix);
2596 ServerSource->SetPingFlag();
2601 std::string forwardto = params[1];
2602 if (forwardto == this->Instance->Config->ServerName)
2605 * this is a PONG for us
2606 * if the prefix is a user, check theyre local, and if they are,
2607 * dump the PONG reply back to their fd. If its a server, do nowt.
2608 * Services might want to send these s->s, but we dont need to yet.
2610 userrec* u = this->Instance->FindNick(prefix);
2614 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2619 // not for us, pass it on :)
2620 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2627 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2629 if (params.size() < 3)
2632 TreeServer* ServerSource = Utils->FindServer(prefix);
2636 if (params[0] == "*")
2638 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2640 else if (*(params[0].c_str()) == '#')
2642 chanrec* c = this->Instance->FindChan(params[0]);
2645 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2648 else if (*(params[0].c_str()) != '#')
2650 userrec* u = this->Instance->FindNick(params[0]);
2653 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2658 params[2] = ":" + params[2];
2659 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2663 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2665 if (params.size() < 1)
2668 TreeServer* ServerSource = Utils->FindServer(prefix);
2672 ServerSource->SetVersion(params[0]);
2674 params[0] = ":" + params[0];
2675 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2679 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2681 if (params.size() < 1)
2684 userrec* u = this->Instance->FindNick(prefix);
2688 u->ChangeDisplayedHost(params[0].c_str());
2689 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2694 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2696 if (params.size() < 6)
2699 bool propogate = false;
2701 switch (*(params[0].c_str()))
2704 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2705 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2708 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2709 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2712 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2713 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2716 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2717 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2720 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2723 /* Just in case... */
2724 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2729 /* Send it on its way */
2732 if (atoi(params[4].c_str()))
2734 this->Instance->SNO->WriteToSnoMask('x',"%s Added %cLINE on %s to expire in %lu seconds (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),atoi(params[4].c_str()),params[5].c_str());
2738 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());
2740 params[5] = ":" + params[5];
2741 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2743 if (!this->bursting)
2745 Instance->Log(DEBUG,"Applying lines...");
2746 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2751 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2753 if (params.size() < 1)
2756 userrec* u = this->Instance->FindNick(prefix);
2760 u->ChangeName(params[0].c_str());
2761 params[0] = ":" + params[0];
2762 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2767 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2769 if (params.size() < 1)
2772 Instance->Log(DEBUG,"In IDLE command");
2773 userrec* u = this->Instance->FindNick(prefix);
2777 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2778 // an incoming request
2779 if (params.size() == 1)
2781 userrec* x = this->Instance->FindNick(params[0]);
2782 if ((x) && (IS_LOCAL(x)))
2784 userrec* x = this->Instance->FindNick(params[0]);
2785 char signon[MAXBUF];
2788 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2789 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2790 std::deque<std::string> par;
2791 par.push_back(prefix);
2792 par.push_back(signon);
2793 par.push_back(idle);
2794 // ours, we're done, pass it BACK
2795 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2799 // not ours pass it on
2800 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2803 else if (params.size() == 3)
2805 std::string who_did_the_whois = params[0];
2806 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2807 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2809 // an incoming reply to a whois we sent out
2810 std::string nick_whoised = prefix;
2811 unsigned long signon = atoi(params[1].c_str());
2812 unsigned long idle = atoi(params[2].c_str());
2813 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2814 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2818 // not ours, pass it on
2819 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2826 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2828 if (params.size() < 2)
2831 userrec* u = this->Instance->FindNick(params[0]);
2838 u->Write(params[1]);
2842 // continue the raw onwards
2843 params[1] = ":" + params[1];
2844 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2849 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2851 if (!params.size() || !Utils->EnableTimeSync)
2856 if ((params.size() == 2) && (params[1] == "FORCE"))
2859 time_t rts = atoi(params[0].c_str());
2860 time_t us = Instance->Time(true);
2864 Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2866 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2868 else if (force || (rts < us))
2870 int old = Instance->SetTimeDelta(rts - us);
2871 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2873 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2877 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2879 std::deque<std::string> oparams;
2880 oparams.push_back(ConvToStr(us));
2882 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2888 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2890 // :source.server TIME remote.server sendernick
2891 // :remote.server TIME source.server sendernick TS
2892 if (params.size() == 2)
2894 // someone querying our time?
2895 if (this->Instance->Config->ServerName == params[0])
2897 userrec* u = this->Instance->FindNick(params[1]);
2900 params.push_back(ConvToStr(Instance->Time(false)));
2902 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2907 // not us, pass it on
2908 userrec* u = this->Instance->FindNick(params[1]);
2910 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2913 else if (params.size() == 3)
2915 // a response to a previous TIME
2916 userrec* u = this->Instance->FindNick(params[1]);
2917 if ((u) && (IS_LOCAL(u)))
2919 time_t rawtime = atol(params[2].c_str());
2920 struct tm * timeinfo;
2921 timeinfo = localtime(&rawtime);
2923 snprintf(tms,26,"%s",asctime(timeinfo));
2925 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2930 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2936 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2938 if (params.size() < 1)
2941 if (params.size() == 1)
2943 std::string stufftobounce = params[0];
2944 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2949 std::string forwardto = params[1];
2950 if (forwardto == this->Instance->Config->ServerName)
2952 // this is a ping for us, send back PONG to the requesting server
2953 params[1] = params[0];
2954 params[0] = forwardto;
2955 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2959 // not for us, pass it on :)
2960 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2966 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2968 if (params.size() < 1)
2971 chanrec* c = Instance->FindChan(params[0]);
2975 irc::modestacker modestack(false);
2976 CUList *ulist = c->GetUsers();
2978 std::deque<std::string> stackresult;
2981 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2983 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2984 if (modesequence.length())
2986 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2987 irc::spacesepstream sep(modesequence);
2988 std::string modeletters = sep.GetToken();
2989 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2991 while (!modeletters.empty())
2993 char mletter = *(modeletters.begin());
2994 modestack.Push(mletter,sep.GetToken());
2995 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2996 modeletters.erase(modeletters.begin());
2997 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
3002 while (modestack.GetStackedLine(stackresult))
3004 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
3005 stackresult.push_front(ConvToStr(c->age));
3006 stackresult.push_front(c->name);
3007 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
3008 stackresult.erase(stackresult.begin() + 1);
3009 Instance->Log(DEBUG,"Stacked items:");
3010 for (size_t z = 0; z < stackresult.size(); z++)
3012 y[z] = stackresult[z].c_str();
3013 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
3015 userrec* n = new userrec(Instance);
3016 n->SetFd(FD_MAGIC_NUMBER);
3017 Instance->SendMode(y, stackresult.size(), n);
3024 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
3026 if (params.size() < 4)
3029 std::string servername = params[0];
3030 std::string password = params[1];
3031 // hopcount is not used for a remote server, we calculate this ourselves
3032 std::string description = params[3];
3033 TreeServer* ParentOfThis = Utils->FindServer(prefix);
3037 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
3040 TreeServer* CheckDupe = Utils->FindServer(servername);
3043 this->WriteLine("ERROR :Server "+servername+" already exists!");
3044 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
3047 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
3048 ParentOfThis->AddChild(Node);
3049 params[3] = ":" + params[3];
3050 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
3051 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
3055 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
3057 if (params.size() < 4)
3060 irc::string servername = params[0].c_str();
3061 std::string sname = params[0];
3062 std::string password = params[1];
3063 int hops = atoi(params[2].c_str());
3067 this->WriteLine("ERROR :Server too far away for authentication");
3068 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3071 std::string description = params[3];
3072 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3074 if ((x->Name == servername) && (x->RecvPass == password))
3076 TreeServer* CheckDupe = Utils->FindServer(sname);
3079 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3080 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3083 // Begin the sync here. this kickstarts the
3084 // other side, waiting in WAIT_AUTH_2 state,
3085 // into starting their burst, as it shows
3086 // that we're happy.
3087 this->LinkState = CONNECTED;
3088 // we should add the details of this server now
3089 // to the servers tree, as a child of the root
3091 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
3092 Utils->TreeRoot->AddChild(Node);
3093 params[3] = ":" + params[3];
3094 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
3095 this->bursting = true;
3096 this->DoBurst(Node);
3100 this->WriteLine("ERROR :Invalid credentials");
3101 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3105 bool Inbound_Server(std::deque<std::string> ¶ms)
3107 if (params.size() < 4)
3110 irc::string servername = params[0].c_str();
3111 std::string sname = params[0];
3112 std::string password = params[1];
3113 int hops = atoi(params[2].c_str());
3117 this->WriteLine("ERROR :Server too far away for authentication");
3118 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3121 std::string description = params[3];
3122 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3124 if ((x->Name == servername) && (x->RecvPass == password))
3126 TreeServer* CheckDupe = Utils->FindServer(sname);
3129 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3130 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3133 /* If the config says this link is encrypted, but the remote side
3134 * hasnt bothered to send the AES command before SERVER, then we
3135 * boot them off as we MUST have this connection encrypted.
3137 if ((x->EncryptionKey != "") && (!this->ctx_in))
3139 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
3140 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
3143 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
3144 this->InboundServerName = sname;
3145 this->InboundDescription = description;
3146 // this is good. Send our details: Our server name and description and hopcount of 0,
3147 // along with the sendpass from this block.
3148 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3149 // move to the next state, we are now waiting for THEM.
3150 this->LinkState = WAIT_AUTH_2;
3154 this->WriteLine("ERROR :Invalid credentials");
3155 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3159 void Split(const std::string &line, std::deque<std::string> &n)
3162 irc::tokenstream tokens(line);
3164 while ((param = tokens.GetToken()) != "")
3169 bool ProcessLine(std::string &line)
3171 std::deque<std::string> params;
3172 irc::string command;
3175 line = line.substr(0, line.find_first_of("\r\n"));
3180 Instance->Log(DEBUG,"IN: %s", line.c_str());
3182 this->Split(line.c_str(),params);
3184 if ((params[0][0] == ':') && (params.size() > 1))
3186 prefix = params[0].substr(1);
3190 command = params[0].c_str();
3193 if ((!this->ctx_in) && (command == "AES"))
3195 std::string sserv = params[0];
3196 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3198 if ((x->EncryptionKey != "") && (x->Name == sserv))
3200 this->InitAES(x->EncryptionKey,sserv);
3206 else if ((this->ctx_in) && (command == "AES"))
3208 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());
3211 switch (this->LinkState)
3216 // Waiting for SERVER command from remote server. Server initiating
3217 // the connection sends the first SERVER command, listening server
3218 // replies with theirs if its happy, then if the initiator is happy,
3219 // it starts to send its net sync, which starts the merge, otherwise
3220 // it sends an ERROR.
3221 if (command == "PASS")
3223 /* Silently ignored */
3225 else if (command == "SERVER")
3227 return this->Inbound_Server(params);
3229 else if (command == "ERROR")
3231 return this->Error(params);
3233 else if (command == "USER")
3235 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3238 else if (command == "CAPAB")
3240 return this->Capab(params);
3242 else if ((command == "U") || (command == "S"))
3244 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3249 std::string error("ERROR :Invalid command in negotiation phase: ");
3250 error.append(command.c_str());
3251 this->WriteLine(error);
3256 // Waiting for start of other side's netmerge to say they liked our
3258 if (command == "SERVER")
3260 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3264 else if ((command == "U") || (command == "S"))
3266 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3269 else if (command == "BURST")
3271 if (params.size() && Utils->EnableTimeSync)
3273 /* If a time stamp is provided, apply synchronization */
3275 time_t them = atoi(params[0].c_str());
3276 time_t us = Instance->Time(true);
3277 int delta = them - us;
3279 if ((params.size() == 2) && (params[1] == "FORCE"))
3282 if ((delta < -600) || (delta > 600))
3284 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));
3285 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3291 this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3293 else if (force || (us > them))
3295 this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3296 this->Instance->SetTimeDelta(them - us);
3297 // Send this new timestamp to any other servers
3298 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3302 // Override the timestamp
3303 this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3304 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3307 this->LinkState = CONNECTED;
3308 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3309 Utils->TreeRoot->AddChild(Node);
3311 params.push_back(InboundServerName);
3312 params.push_back("*");
3313 params.push_back("1");
3314 params.push_back(":"+InboundDescription);
3315 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3316 this->bursting = true;
3317 this->DoBurst(Node);
3319 else if (command == "ERROR")
3321 return this->Error(params);
3323 else if (command == "CAPAB")
3325 return this->Capab(params);
3330 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3334 if (command == "SERVER")
3336 // another server we connected to, which was in WAIT_AUTH_1 state,
3337 // has just sent us their credentials. If we get this far, theyre
3338 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3339 // if we're happy with this, we should send our netburst which
3340 // kickstarts the merge.
3341 return this->Outbound_Reply_Server(params);
3343 else if (command == "ERROR")
3345 return this->Error(params);
3349 // This is the 'authenticated' state, when all passwords
3350 // have been exchanged and anything past this point is taken
3355 std::string direction = prefix;
3356 userrec* t = this->Instance->FindNick(prefix);
3359 direction = t->server;
3361 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3362 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3364 if (route_back_again)
3365 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3370 * When there is activity on the socket, reset the ping counter so
3371 * that we're not wasting bandwidth pinging an active server.
3373 route_back_again->SetNextPingTime(time(NULL) + 60);
3374 route_back_again->SetPingFlag();
3377 if (command == "SVSMODE")
3379 /* Services expects us to implement
3380 * SVSMODE. In inspircd its the same as
3385 std::string target = "";
3386 /* Yes, know, this is a mess. Its reasonably fast though as we're
3387 * working with std::string here.
3389 if ((command == "NICK") && (params.size() > 1))
3391 return this->IntroduceClient(prefix,params);
3393 else if (command == "FJOIN")
3395 return this->ForceJoin(prefix,params);
3397 else if (command == "STATS")
3399 return this->Stats(prefix, params);
3401 else if (command == "MOTD")
3403 return this->Motd(prefix, params);
3405 else if (command == "ADMIN")
3407 return this->Admin(prefix, params);
3409 else if (command == "SERVER")
3411 return this->RemoteServer(prefix,params);
3413 else if (command == "ERROR")
3415 return this->Error(params);
3417 else if (command == "OPERTYPE")
3419 return this->OperType(prefix,params);
3421 else if (command == "FMODE")
3423 return this->ForceMode(prefix,params);
3425 else if (command == "KILL")
3427 return this->RemoteKill(prefix,params);
3429 else if (command == "FTOPIC")
3431 return this->ForceTopic(prefix,params);
3433 else if (command == "REHASH")
3435 return this->RemoteRehash(prefix,params);
3437 else if (command == "METADATA")
3439 return this->MetaData(prefix,params);
3441 else if (command == "REMSTATUS")
3443 return this->RemoveStatus(prefix,params);
3445 else if (command == "PING")
3448 * We just got a ping from a server that's bursting.
3449 * This can't be right, so set them to not bursting, and
3450 * apply their lines.
3454 this->bursting = false;
3455 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3459 prefix = this->GetName();
3461 return this->LocalPing(prefix,params);
3463 else if (command == "PONG")
3466 * We just got a pong from a server that's bursting.
3467 * This can't be right, so set them to not bursting, and
3468 * apply their lines.
3472 this->bursting = false;
3473 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3477 prefix = this->GetName();
3479 return this->LocalPong(prefix,params);
3481 else if (command == "VERSION")
3483 return this->ServerVersion(prefix,params);
3485 else if (command == "FHOST")
3487 return this->ChangeHost(prefix,params);
3489 else if (command == "FNAME")
3491 return this->ChangeName(prefix,params);
3493 else if (command == "ADDLINE")
3495 return this->AddLine(prefix,params);
3497 else if (command == "SVSNICK")
3501 prefix = this->GetName();
3503 return this->ForceNick(prefix,params);
3505 else if (command == "RSQUIT")
3507 return this->RemoteSquit(prefix, params);
3509 else if (command == "IDLE")
3511 return this->Whois(prefix,params);
3513 else if (command == "PUSH")
3515 return this->Push(prefix,params);
3517 else if (command == "TIMESET")
3519 return this->HandleSetTime(prefix, params);
3521 else if (command == "TIME")
3523 return this->Time(prefix,params);
3525 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3527 std::string sourceserv = this->myhost;
3528 if (params.size() == 3)
3530 userrec* user = this->Instance->FindNick(params[1]);
3531 chanrec* chan = this->Instance->FindChan(params[0]);
3534 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3535 /* Yikes, the channels gone! */
3539 if (this->InboundServerName != "")
3541 sourceserv = this->InboundServerName;
3543 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3545 else if (command == "SVSJOIN")
3549 prefix = this->GetName();
3551 return this->ServiceJoin(prefix,params);
3553 else if (command == "SQUIT")
3555 if (params.size() == 2)
3557 this->Squit(Utils->FindServer(params[0]),params[1]);
3561 else if (command == "OPERNOTICE")
3563 std::string sourceserv = this->myhost;
3565 if (this->InboundServerName != "")
3566 sourceserv = this->InboundServerName;
3568 if (params.size() >= 1)
3569 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3571 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3573 else if (command == "MODENOTICE")
3575 std::string sourceserv = this->myhost;
3576 if (this->InboundServerName != "")
3577 sourceserv = this->InboundServerName;
3578 if (params.size() >= 2)
3580 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3583 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3585 else if (command == "SNONOTICE")
3587 std::string sourceserv = this->myhost;
3588 if (this->InboundServerName != "")
3589 sourceserv = this->InboundServerName;
3590 if (params.size() >= 2)
3592 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3595 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3597 else if (command == "ENDBURST")
3599 this->bursting = false;
3600 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3601 std::string sourceserv = this->myhost;
3602 if (this->InboundServerName != "")
3604 sourceserv = this->InboundServerName;
3606 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3608 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3609 rmode.Send(Instance);
3615 // not a special inter-server command.
3616 // Emulate the actual user doing the command,
3617 // this saves us having a huge ugly parser.
3618 userrec* who = this->Instance->FindNick(prefix);
3619 std::string sourceserv = this->myhost;
3620 if (this->InboundServerName != "")
3622 sourceserv = this->InboundServerName;
3624 if ((!who) && (command == "MODE"))
3626 if (Utils->IsServer(prefix))
3628 const char* modelist[127];
3629 for (size_t i = 0; i < params.size(); i++)
3630 modelist[i] = params[i].c_str();
3632 userrec* fake = new userrec(Instance);
3633 fake->SetFd(FD_MAGIC_NUMBER);
3635 this->Instance->SendMode(modelist, params.size(), fake);
3639 /* Hot potato! pass it on! */
3640 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3645 if ((command == "NICK") && (params.size() > 0))
3647 /* On nick messages, check that the nick doesnt
3648 * already exist here. If it does, kill their copy,
3651 userrec* x = this->Instance->FindNick(params[0]);
3652 if ((x) && (x != who))
3654 std::deque<std::string> p;
3655 p.push_back(params[0]);
3656 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3657 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3659 p.push_back(prefix);
3660 p.push_back("Nickname collision");
3661 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3662 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3663 userrec* y = this->Instance->FindNick(prefix);
3666 userrec::QuitUser(this->Instance,y,"Nickname collision");
3668 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3672 target = who->server;
3673 const char* strparams[127];
3674 for (unsigned int q = 0; q < params.size(); q++)
3676 strparams[q] = params[q].c_str();
3678 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3681 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3688 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3694 // its not a user. Its either a server, or somethings screwed up.
3695 if (Utils->IsServer(prefix))
3697 target = this->Instance->Config->ServerName;
3701 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3705 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3714 virtual std::string GetName()
3716 std::string sourceserv = this->myhost;
3717 if (this->InboundServerName != "")
3719 sourceserv = this->InboundServerName;
3724 virtual void OnTimeout()
3726 if (this->LinkState == CONNECTING)
3728 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3729 Link* MyLink = Utils->FindLink(myhost);
3731 Utils->DoFailOver(MyLink);
3735 virtual void OnClose()
3737 // Connection closed.
3738 // If the connection is fully up (state CONNECTED)
3739 // then propogate a netsplit to all peers.
3740 std::string quitserver = this->myhost;
3741 if (this->InboundServerName != "")
3743 quitserver = this->InboundServerName;
3745 TreeServer* s = Utils->FindServer(quitserver);
3748 Squit(s,"Remote host closed the connection");
3751 if (quitserver != "")
3752 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3755 virtual int OnIncomingConnection(int newsock, char* ip)
3757 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3758 * or discovering if this port is the server port, we don't allow connections from any
3759 * IPs for which we don't have a link block.
3763 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3766 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3767 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3772 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3778 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
3780 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3785 /** This class is used to resolve server hostnames during /connect and autoconnect.
3786 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3787 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3788 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3789 * will have an IP address which we can then use to continue our connection.
3791 class ServernameResolver : public Resolver
3794 /** A copy of the Link tag info for what we're connecting to.
3795 * We take a copy, rather than using a pointer, just in case the
3796 * admin takes the tag away and rehashes while the domain is resolving.
3799 SpanningTreeUtilities* Utils;
3801 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3803 /* Nothing in here, folks */
3806 void OnLookupComplete(const std::string &result)
3808 /* Initiate the connection, now that we have an IP to use.
3809 * Passing a hostname directly to InspSocket causes it to
3810 * just bail and set its FD to -1.
3812 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3813 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3816 if ((!MyLink.Hook.empty()) && (Utils->hooks.find(MyLink.Hook.c_str()) == Utils->hooks.end()))
3819 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str(),
3820 MyLink.Hook.empty() ? NULL : Utils->hooks[MyLink.Hook.c_str()]);
3821 if (newsocket->GetFd() > -1)
3827 /* Something barfed, show the opers */
3828 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3830 Utils->DoFailOver(&MyLink);
3835 void OnError(ResolverError e, const std::string &errormessage)
3838 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3839 Utils->DoFailOver(&MyLink);
3843 /** Handle resolving of server IPs for the cache
3845 class SecurityIPResolver : public Resolver
3849 SpanningTreeUtilities* Utils;
3851 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3855 void OnLookupComplete(const std::string &result)
3857 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3858 Utils->ValidIPs.push_back(result);
3861 void OnError(ResolverError e, const std::string &errormessage)
3863 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3867 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3871 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3873 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
3875 /* Did we find any modules? */
3878 /* Yes, enumerate them all to find out the hook name */
3879 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
3881 /* Make a request to it for its name, its implementing
3882 * InspSocketHook so we know its safe to do this
3884 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
3885 /* Build a map of them */
3886 hooks[name.c_str()] = *m;
3887 hooknames.push_back(name);
3888 ServerInstance->Log(DEBUG, "Found InspSocketHook interface: '%s' -> '%08x'", name.c_str(), *m);
3892 this->ReadConfiguration(true);
3895 SpanningTreeUtilities::~SpanningTreeUtilities()
3897 for (unsigned int i = 0; i < Bindings.size(); i++)
3899 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3900 ServerInstance->SE->DelFd(Bindings[i]);
3901 Bindings[i]->Close();
3902 DELETE(Bindings[i]);
3904 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3905 while (TreeRoot->ChildCount())
3907 TreeServer* child_server = TreeRoot->GetChild(0);
3908 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3911 TreeSocket* sock = child_server->GetSocket();
3912 ServerInstance->SE->DelFd(sock);
3920 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
3922 if (list.find(server) == list.end())
3923 list[server] = server;
3926 /** returns a list of DIRECT servernames for a specific channel */
3927 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
3933 ulist = c->GetOppedUsers();
3936 ulist = c->GetHalfoppedUsers();
3939 ulist = c->GetVoicedUsers();
3942 ulist = c->GetUsers();
3945 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3947 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
3949 TreeServer* best = this->BestRouteTo(i->second->server);
3951 AddThisServer(best,list);
3957 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3960 TreeServer* omitroute = this->BestRouteTo(omit);
3961 if ((command == "NOTICE") || (command == "PRIVMSG"))
3963 if (params.size() >= 2)
3966 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3969 params[0] = params[0].substr(1, params[0].length()-1);
3971 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3973 // special routing for private messages/notices
3974 userrec* d = ServerInstance->FindNick(params[0]);
3977 std::deque<std::string> par;
3978 par.push_back(params[0]);
3979 par.push_back(":"+params[1]);
3980 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3984 else if (*(params[0].c_str()) == '$')
3986 std::deque<std::string> par;
3987 par.push_back(params[0]);
3988 par.push_back(":"+params[1]);
3989 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3994 chanrec* c = ServerInstance->FindChan(params[0]);
3995 userrec* u = ServerInstance->FindNick(prefix);
3999 TreeServerList list;
4000 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
4001 GetListOfServersForChannel(c,list,pfx,elist);
4003 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
4005 TreeSocket* Sock = i->second->GetSocket();
4006 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
4008 Sock->WriteLine(data);
4016 unsigned int items =this->TreeRoot->ChildCount();
4017 for (unsigned int x = 0; x < items; x++)
4019 TreeServer* Route = this->TreeRoot->GetChild(x);
4020 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
4022 TreeSocket* Sock = Route->GetSocket();
4024 Sock->WriteLine(data);
4030 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
4032 TreeServer* omitroute = this->BestRouteTo(omit);
4033 std::string FullLine = ":" + prefix + " " + command;
4034 unsigned int words = params.size();
4035 for (unsigned int x = 0; x < words; x++)
4037 FullLine = FullLine + " " + params[x];
4039 unsigned int items = this->TreeRoot->ChildCount();
4040 for (unsigned int x = 0; x < items; x++)
4042 TreeServer* Route = this->TreeRoot->GetChild(x);
4043 // Send the line IF:
4044 // The route has a socket (its a direct connection)
4045 // The route isnt the one to be omitted
4046 // The route isnt the path to the one to be omitted
4047 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
4049 TreeSocket* Sock = Route->GetSocket();
4051 Sock->WriteLine(FullLine);
4057 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
4059 std::string FullLine = ":" + prefix + " " + command;
4060 unsigned int words = params.size();
4061 for (unsigned int x = 0; x < words; x++)
4063 FullLine = FullLine + " " + params[x];
4065 unsigned int items = this->TreeRoot->ChildCount();
4066 for (unsigned int x = 0; x < items; x++)
4068 TreeServer* Route = this->TreeRoot->GetChild(x);
4069 if (Route && Route->GetSocket())
4071 TreeSocket* Sock = Route->GetSocket();
4073 Sock->WriteLine(FullLine);
4079 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
4081 std::string spfx = prefix;
4082 std::string scmd = command;
4083 return this->DoOneToMany(spfx, scmd, params);
4086 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
4088 std::string spfx = prefix;
4089 std::string scmd = command;
4090 return this->DoOneToAllButSender(spfx, scmd, params, omit);
4093 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
4095 TreeServer* Route = this->BestRouteTo(target);
4098 std::string FullLine = ":" + prefix + " " + command;
4099 unsigned int words = params.size();
4100 for (unsigned int x = 0; x < words; x++)
4102 FullLine = FullLine + " " + params[x];
4104 if (Route && Route->GetSocket())
4106 TreeSocket* Sock = Route->GetSocket();
4108 Sock->WriteLine(FullLine);
4118 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
4120 ConfigReader* Conf = new ConfigReader(ServerInstance);
4123 for (int j =0; j < Conf->Enumerate("bind"); j++)
4125 std::string Type = Conf->ReadValue("bind","type",j);
4126 std::string IP = Conf->ReadValue("bind","address",j);
4127 std::string Port = Conf->ReadValue("bind","port",j);
4128 std::string transport = Conf->ReadValue("bind","transport",j);
4129 if (Type == "servers")
4131 irc::portparser portrange(Port, false);
4133 while ((portno = portrange.GetToken()))
4135 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
4139 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
4141 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' - maybe you forgot to load it BEFORE m_spanningtree in your config file?",
4146 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
4147 if (listener->GetState() == I_LISTENING)
4149 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
4150 Bindings.push_back(listener);
4154 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
4158 ServerInstance->Log(DEBUG,"Done with this binding");
4163 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
4164 HideULines = Conf->ReadFlag("options","hideulines",0);
4165 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
4166 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
4169 for (int j =0; j < Conf->Enumerate("link"); j++)
4172 std::string Allow = Conf->ReadValue("link","allowmask",j);
4173 L.Name = (Conf->ReadValue("link","name",j)).c_str();
4174 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
4175 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
4176 L.Port = Conf->ReadInteger("link","port",j,true);
4177 L.SendPass = Conf->ReadValue("link","sendpass",j);
4178 L.RecvPass = Conf->ReadValue("link","recvpass",j);
4179 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
4180 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
4181 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
4182 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
4183 L.Hook = Conf->ReadValue("link", "transport", j);
4184 L.NextConnectTime = time(NULL) + L.AutoConnect;
4185 /* Bugfix by brain, do not allow people to enter bad configurations */
4186 if (L.Name != ServerInstance->Config->ServerName)
4188 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
4190 ValidIPs.push_back(L.IPAddr);
4193 ValidIPs.push_back(Allow);
4195 /* Needs resolving */
4197 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
4201 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
4202 ServerInstance->AddResolver(sr);
4204 catch (ModuleException& e)
4206 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4210 LinkBlocks.push_back(L);
4211 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4217 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4219 else if (L.RecvPass == "")
4221 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4223 else if (L.SendPass == "")
4225 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4227 else if (L.Name == "")
4229 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4233 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4239 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4245 /** To create a timer which recurs every second, we inherit from InspTimer.
4246 * InspTimer is only one-shot however, so at the end of each Tick() we simply
4247 * insert another of ourselves into the pending queue :)
4249 class TimeSyncTimer : public InspTimer
4253 ModuleSpanningTree *Module;
4255 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4256 virtual void Tick(time_t TIME);
4259 HandshakeTimer::HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u) : InspTimer(1, time(NULL)), Instance(Inst), sock(s), lnk(l), Utils(u)
4261 thefd = sock->GetFd();
4264 void HandshakeTimer::Tick(time_t TIME)
4266 if (Instance->SE->GetRef(thefd) == sock)
4268 if (sock->GetHook() && InspSocketHSCompleteRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send())
4270 InspSocketAttachCertRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send();
4271 sock->SendCapabilities();
4272 if (sock->GetLinkState() == CONNECTING)
4274 sock->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+lnk->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
4279 Instance->Timers->AddTimer(new HandshakeTimer(Instance, sock, lnk, Utils));
4284 class ModuleSpanningTree : public Module
4288 unsigned int max_local;
4289 unsigned int max_global;
4290 cmd_rconnect* command_rconnect;
4291 SpanningTreeUtilities* Utils;
4294 TimeSyncTimer *SyncTimer;
4296 ModuleSpanningTree(InspIRCd* Me)
4297 : Module::Module(Me), max_local(0), max_global(0)
4299 Utils = new SpanningTreeUtilities(Me, this);
4301 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4302 ServerInstance->AddCommand(command_rconnect);
4304 if (Utils->EnableTimeSync)
4306 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4307 ServerInstance->Timers->AddTimer(SyncTimer);
4313 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4315 std::string Parent = Utils->TreeRoot->GetName();
4316 if (Current->GetParent())
4318 Parent = Current->GetParent()->GetName();
4320 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4322 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4326 ShowLinks(Current->GetChild(q),user,hops+1);
4331 ShowLinks(Current->GetChild(q),user,hops+1);
4334 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4335 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4337 user->WriteServ("364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(Utils->FlatLinks && (!*user->oper)) ? ServerInstance->Config->ServerName : Parent.c_str(),(Utils->FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
4340 int CountLocalServs()
4342 return Utils->TreeRoot->ChildCount();
4347 return Utils->serverlist.size();
4350 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4352 ShowLinks(Utils->TreeRoot,user,0);
4353 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4357 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4359 unsigned int n_users = ServerInstance->UserCount();
4361 /* Only update these when someone wants to see them, more efficient */
4362 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4363 max_local = ServerInstance->LocalUserCount();
4364 if (n_users > max_global)
4365 max_global = n_users;
4367 unsigned int ulined_count = 0;
4368 unsigned int ulined_local_count = 0;
4370 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4371 * locally and globally (locally means directly connected to us)
4373 if ((Utils->HideULines) && (!*user->oper))
4375 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4377 if (ServerInstance->ULine(q->second->GetName().c_str()))
4380 if (q->second->GetParent() == Utils->TreeRoot)
4381 ulined_local_count++;
4386 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());
4387 if (ServerInstance->OperCount())
4388 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4389 if (ServerInstance->UnregisteredUserCount())
4390 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4391 if (ServerInstance->ChannelCount())
4392 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4393 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());
4394 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4395 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4399 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4401 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4405 for (int t = 0; t < depth; t++)
4407 matrix[line][t] = ' ';
4410 // For Aligning, we need to work out exactly how deep this thing is, and produce
4411 // a 'Spacer' String to compensate.
4414 memset(spacer,' ',40);
4415 if ((40 - Current->GetName().length() - depth) > 1) {
4416 spacer[40 - Current->GetName().length() - depth] = '\0';
4425 if (ServerInstance->clientlist.size() == 0) {
4426 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4431 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4433 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4434 totusers += Current->GetUserCount();
4436 strlcpy(&matrix[line][depth],text,80);
4438 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4440 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4444 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4449 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4455 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4459 /* Remote MOTD, the server is within the 1st parameter */
4460 std::deque<std::string> params;
4461 params.push_back(parameters[0]);
4463 /* Send it out remotely, generate no reply yet */
4464 TreeServer* s = Utils->FindServerMask(parameters[0]);
4467 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4471 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4478 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4482 /* Remote ADMIN, the server is within the 1st parameter */
4483 std::deque<std::string> params;
4484 params.push_back(parameters[0]);
4486 /* Send it out remotely, generate no reply yet */
4487 TreeServer* s = Utils->FindServerMask(parameters[0]);
4490 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4494 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4501 int HandleStats(const char** parameters, int pcnt, userrec* user)
4505 /* Remote STATS, the server is within the 2nd parameter */
4506 std::deque<std::string> params;
4507 params.push_back(parameters[0]);
4508 params.push_back(parameters[1]);
4509 /* Send it out remotely, generate no reply yet */
4510 TreeServer* s = Utils->FindServerMask(parameters[1]);
4513 params[1] = s->GetName();
4514 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4518 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4525 // Ok, prepare to be confused.
4526 // After much mulling over how to approach this, it struck me that
4527 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4528 // keeping track of a ton of ascii characters, and line by line
4529 // under recursion working out where to place them using multiplications
4530 // and divisons, we instead render the map onto a backplane of characters
4531 // (a character matrix), then draw the branches as a series of "L" shapes
4532 // from the nodes. This is not only friendlier on CPU it uses less stack.
4534 void HandleMap(const char** parameters, int pcnt, userrec* user)
4536 // This array represents a virtual screen which we will
4537 // "scratch" draw to, as the console device of an irc
4538 // client does not provide for a proper terminal.
4540 float totservers = 0;
4541 char matrix[128][80];
4542 for (unsigned int t = 0; t < 128; t++)
4544 matrix[t][0] = '\0';
4547 // The only recursive bit is called here.
4548 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4549 // Process each line one by one. The algorithm has a limit of
4550 // 128 servers (which is far more than a spanning tree should have
4551 // anyway, so we're ok). This limit can be raised simply by making
4552 // the character matrix deeper, 128 rows taking 10k of memory.
4553 for (int l = 1; l < line; l++)
4555 // scan across the line looking for the start of the
4556 // servername (the recursive part of the algorithm has placed
4557 // the servers at indented positions depending on what they
4559 int first_nonspace = 0;
4560 while (matrix[l][first_nonspace] == ' ')
4565 // Draw the `- (corner) section: this may be overwritten by
4566 // another L shape passing along the same vertical pane, becoming
4567 // a |- (branch) section instead.
4568 matrix[l][first_nonspace] = '-';
4569 matrix[l][first_nonspace-1] = '`';
4571 // Draw upwards until we hit the parent server, causing possibly
4572 // other corners (`-) to become branches (|-)
4573 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4575 matrix[l2][first_nonspace-1] = '|';
4579 // dump the whole lot to the user. This is the easy bit, honest.
4580 for (int t = 0; t < line; t++)
4582 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4584 float avg_users = totusers / totservers;
4585 user->WriteServ("270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
4586 user->WriteServ("007 %s :End of /MAP",user->nick);
4590 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4592 TreeServer* s = Utils->FindServerMask(parameters[0]);
4595 if (s == Utils->TreeRoot)
4597 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4600 TreeSocket* sock = s->GetSocket();
4603 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4604 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4605 sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost());
4606 ServerInstance->SE->DelFd(sock);
4613 std::deque<std::string> params;
4614 params.push_back(parameters[0]);
4615 params.push_back(std::string(":Server quit by ") + user->GetFullRealHost());
4616 Utils->DoOneToOne(user->nick, "RSQUIT", params, parameters[0]);
4621 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4626 int HandleTime(const char** parameters, int pcnt, userrec* user)
4628 if ((IS_LOCAL(user)) && (pcnt))
4630 TreeServer* found = Utils->FindServerMask(parameters[0]);
4633 // we dont' override for local server
4634 if (found == Utils->TreeRoot)
4637 std::deque<std::string> params;
4638 params.push_back(found->GetName());
4639 params.push_back(user->nick);
4640 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4644 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4650 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4652 if ((IS_LOCAL(user)) && (pcnt > 1))
4654 userrec* remote = ServerInstance->FindNick(parameters[1]);
4655 if ((remote) && (remote->GetFd() < 0))
4657 std::deque<std::string> params;
4658 params.push_back(parameters[1]);
4659 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4664 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4665 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4672 void DoPingChecks(time_t curtime)
4674 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4676 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4677 TreeSocket* sock = serv->GetSocket();
4680 if (curtime >= serv->NextPingTime())
4682 if (serv->AnsweredLastPing())
4684 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4685 serv->SetNextPingTime(curtime + 60);
4689 // they didnt answer, boot them
4690 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4691 sock->Squit(serv,"Ping timeout");
4692 ServerInstance->SE->DelFd(sock);
4702 void ConnectServer(Link* x)
4706 /* Do we already have an IP? If so, no need to resolve it. */
4707 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4709 /* Gave a hook, but it wasnt one we know */
4710 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
4713 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()]);
4714 if (newsocket->GetFd() > -1)
4716 /* Handled automatically on success */
4720 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4722 Utils->DoFailOver(x);
4729 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4730 ServerInstance->AddResolver(snr);
4732 catch (ModuleException& e)
4734 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4735 Utils->DoFailOver(x);
4740 void AutoConnectServers(time_t curtime)
4742 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4744 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4746 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4747 x->NextConnectTime = curtime + x->AutoConnect;
4748 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4749 if (x->FailOver.length())
4751 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4754 /* The failover for this server is currently a member of the network.
4755 * The failover probably succeeded, where the main link did not.
4756 * Don't try the main link until the failover is gone again.
4763 // an autoconnected server is not connected. Check if its time to connect it
4764 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4765 this->ConnectServer(&(*x));
4771 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4773 // we've already checked if pcnt > 0, so this is safe
4774 TreeServer* found = Utils->FindServerMask(parameters[0]);
4777 std::string Version = found->GetVersion();
4778 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4779 if (found == Utils->TreeRoot)
4781 std::stringstream out(ServerInstance->Config->data005);
4782 std::string token = "";
4783 std::string line5 = "";
4784 int token_counter = 0;
4789 line5 = line5 + token + " ";
4792 if ((token_counter >= 13) || (out.eof() == true))
4794 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4803 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4808 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4810 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4812 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4814 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4817 user->WriteServ("NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
4818 ConnectServer(&(*x));
4823 user->WriteServ("NOTICE %s :*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
4828 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4832 void BroadcastTimeSync()
4834 std::deque<std::string> params;
4835 params.push_back(ConvToStr(ServerInstance->Time(true)));
4836 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4839 virtual int OnStats(char statschar, userrec* user, string_list &results)
4841 if ((statschar == 'c') || (statschar == 'n'))
4843 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4845 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4846 if (statschar == 'c')
4847 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4849 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4850 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);
4856 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4858 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4862 if (command == "CONNECT")
4864 return this->HandleConnect(parameters,pcnt,user);
4866 else if (command == "STATS")
4868 return this->HandleStats(parameters,pcnt,user);
4870 else if (command == "MOTD")
4872 return this->HandleMotd(parameters,pcnt,user);
4874 else if (command == "ADMIN")
4876 return this->HandleAdmin(parameters,pcnt,user);
4878 else if (command == "SQUIT")
4880 return this->HandleSquit(parameters,pcnt,user);
4882 else if (command == "MAP")
4884 this->HandleMap(parameters,pcnt,user);
4887 else if ((command == "TIME") && (pcnt > 0))
4889 return this->HandleTime(parameters,pcnt,user);
4891 else if (command == "LUSERS")
4893 this->HandleLusers(parameters,pcnt,user);
4896 else if (command == "LINKS")
4898 this->HandleLinks(parameters,pcnt,user);
4901 else if (command == "WHOIS")
4906 return this->HandleRemoteWhois(parameters,pcnt,user);
4909 else if ((command == "VERSION") && (pcnt > 0))
4911 this->HandleVersion(parameters,pcnt,user);
4918 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4920 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4922 // this bit of code cleverly routes all module commands
4923 // to all remote severs *automatically* so that modules
4924 // can just handle commands locally, without having
4925 // to have any special provision in place for remote
4926 // commands and linking protocols.
4927 std::deque<std::string> params;
4929 for (int j = 0; j < pcnt; j++)
4931 if (strchr(parameters[j],' '))
4933 params.push_back(":" + std::string(parameters[j]));
4937 params.push_back(std::string(parameters[j]));
4940 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4941 Utils->DoOneToMany(user->nick,command,params);
4945 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4947 TreeServer* s = Utils->FindServer(servername);
4950 description = s->GetDesc();
4954 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4956 if (IS_LOCAL(source))
4958 std::deque<std::string> params;
4959 params.push_back(dest->nick);
4960 params.push_back(channel->name);
4961 Utils->DoOneToMany(source->nick,"INVITE",params);
4965 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4967 std::deque<std::string> params;
4968 params.push_back(chan->name);
4969 params.push_back(":"+topic);
4970 Utils->DoOneToMany(user->nick,"TOPIC",params);
4973 virtual void OnWallops(userrec* user, const std::string &text)
4977 std::deque<std::string> params;
4978 params.push_back(":"+text);
4979 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4983 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4985 if (target_type == TYPE_USER)
4987 userrec* d = (userrec*)dest;
4988 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4990 std::deque<std::string> params;
4992 params.push_back(d->nick);
4993 params.push_back(":"+text);
4994 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4997 else if (target_type == TYPE_CHANNEL)
5001 chanrec *c = (chanrec*)dest;
5004 std::string cname = c->name;
5006 cname = status + cname;
5007 TreeServerList list;
5008 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
5010 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
5012 TreeSocket* Sock = i->second->GetSocket();
5014 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
5019 else if (target_type == TYPE_SERVER)
5023 char* target = (char*)dest;
5024 std::deque<std::string> par;
5025 par.push_back(target);
5026 par.push_back(":"+text);
5027 Utils->DoOneToMany(user->nick,"NOTICE",par);
5032 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
5034 if (target_type == TYPE_USER)
5036 // route private messages which are targetted at clients only to the server
5037 // which needs to receive them
5038 userrec* d = (userrec*)dest;
5039 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
5041 std::deque<std::string> params;
5043 params.push_back(d->nick);
5044 params.push_back(":"+text);
5045 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
5048 else if (target_type == TYPE_CHANNEL)
5052 chanrec *c = (chanrec*)dest;
5055 std::string cname = c->name;
5057 cname = status + cname;
5058 TreeServerList list;
5059 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
5061 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
5063 TreeSocket* Sock = i->second->GetSocket();
5065 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
5070 else if (target_type == TYPE_SERVER)
5074 char* target = (char*)dest;
5075 std::deque<std::string> par;
5076 par.push_back(target);
5077 par.push_back(":"+text);
5078 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
5083 virtual void OnBackgroundTimer(time_t curtime)
5085 AutoConnectServers(curtime);
5086 DoPingChecks(curtime);
5089 virtual void OnUserJoin(userrec* user, chanrec* channel)
5091 // Only do this for local users
5094 std::deque<std::string> params;
5096 params.push_back(channel->name);
5097 // set up their permissions and the channel TS with FJOIN.
5098 // All users are FJOINed now, because a module may specify
5099 // new joining permissions for the user.
5101 params.push_back(channel->name);
5102 params.push_back(ConvToStr(channel->age));
5103 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
5104 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
5105 if (channel->GetUserCounter() == 1)
5107 /* First user in, sync the modes for the channel */
5109 /* This is safe, all inspircd servers default to +nt */
5110 params.push_back("+nt");
5111 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
5116 virtual void OnChangeHost(userrec* user, const std::string &newhost)
5118 // only occurs for local clients
5119 if (user->registered != REG_ALL)
5121 std::deque<std::string> params;
5122 params.push_back(newhost);
5123 Utils->DoOneToMany(user->nick,"FHOST",params);
5126 virtual void OnChangeName(userrec* user, const std::string &gecos)
5128 // only occurs for local clients
5129 if (user->registered != REG_ALL)
5131 std::deque<std::string> params;
5132 params.push_back(gecos);
5133 Utils->DoOneToMany(user->nick,"FNAME",params);
5136 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
5140 std::deque<std::string> params;
5141 params.push_back(channel->name);
5142 if (partmessage != "")
5143 params.push_back(":"+partmessage);
5144 Utils->DoOneToMany(user->nick,"PART",params);
5148 virtual void OnUserConnect(userrec* user)
5150 char agestr[MAXBUF];
5153 std::deque<std::string> params;
5154 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
5155 params.push_back(agestr);
5156 params.push_back(user->nick);
5157 params.push_back(user->host);
5158 params.push_back(user->dhost);
5159 params.push_back(user->ident);
5160 params.push_back("+"+std::string(user->FormatModes()));
5161 params.push_back(user->GetIPString());
5162 params.push_back(":"+std::string(user->fullname));
5163 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
5165 // User is Local, change needs to be reflected!
5166 TreeServer* SourceServer = Utils->FindServer(user->server);
5169 SourceServer->AddUserCount();
5175 virtual void OnUserQuit(userrec* user, const std::string &reason)
5177 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5179 std::deque<std::string> params;
5180 params.push_back(":"+reason);
5181 Utils->DoOneToMany(user->nick,"QUIT",params);
5183 // Regardless, We need to modify the user Counts..
5184 TreeServer* SourceServer = Utils->FindServer(user->server);
5187 SourceServer->DelUserCount();
5192 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
5196 std::deque<std::string> params;
5197 params.push_back(user->nick);
5198 Utils->DoOneToMany(oldnick,"NICK",params);
5202 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
5204 if ((source) && (IS_LOCAL(source)))
5206 std::deque<std::string> params;
5207 params.push_back(chan->name);
5208 params.push_back(user->nick);
5209 params.push_back(":"+reason);
5210 Utils->DoOneToMany(source->nick,"KICK",params);
5214 std::deque<std::string> params;
5215 params.push_back(chan->name);
5216 params.push_back(user->nick);
5217 params.push_back(":"+reason);
5218 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
5222 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
5224 std::deque<std::string> params;
5225 params.push_back(dest->nick);
5226 params.push_back(":"+reason);
5227 Utils->DoOneToMany(source->nick,"KILL",params);
5230 virtual void OnRehash(const std::string ¶meter)
5232 if (parameter != "")
5234 std::deque<std::string> params;
5235 params.push_back(parameter);
5236 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
5238 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5240 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
5241 ServerInstance->RehashServer();
5244 Utils->ReadConfiguration(false);
5247 // note: the protocol does not allow direct umode +o except
5248 // via NICK with 8 params. sending OPERTYPE infers +o modechange
5250 virtual void OnOper(userrec* user, const std::string &opertype)
5254 std::deque<std::string> params;
5255 params.push_back(opertype);
5256 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5260 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5264 /* Server-set lines */
5266 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5267 (unsigned long)duration, reason.c_str());
5268 std::deque<std::string> params;
5269 params.push_back(data);
5270 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5274 if (IS_LOCAL(source))
5277 snprintf(type,8,"%cLINE",linetype);
5278 std::string stype = type;
5281 char sduration[MAXBUF];
5282 snprintf(sduration,MAXBUF,"%ld",duration);
5283 std::deque<std::string> params;
5284 params.push_back(host);
5285 params.push_back(sduration);
5286 params.push_back(":"+reason);
5287 Utils->DoOneToMany(source->nick,stype,params);
5291 std::deque<std::string> params;
5292 params.push_back(host);
5293 Utils->DoOneToMany(source->nick,stype,params);
5299 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5301 OnLine(source,hostmask,true,'G',duration,reason);
5304 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5306 OnLine(source,ipmask,true,'Z',duration,reason);
5309 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5311 OnLine(source,nickmask,true,'Q',duration,reason);
5314 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5316 OnLine(source,hostmask,true,'E',duration,reason);
5319 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5321 OnLine(source,hostmask,false,'G',0,"");
5324 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5326 OnLine(source,ipmask,false,'Z',0,"");
5329 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5331 OnLine(source,nickmask,false,'Q',0,"");
5334 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5336 OnLine(source,hostmask,false,'E',0,"");
5339 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5341 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5343 if (target_type == TYPE_USER)
5345 userrec* u = (userrec*)dest;
5346 std::deque<std::string> params;
5347 params.push_back(u->nick);
5348 params.push_back(text);
5349 Utils->DoOneToMany(user->nick,"MODE",params);
5353 chanrec* c = (chanrec*)dest;
5354 std::deque<std::string> params;
5355 params.push_back(c->name);
5356 params.push_back(text);
5357 Utils->DoOneToMany(user->nick,"MODE",params);
5362 virtual void OnSetAway(userrec* user)
5366 std::deque<std::string> params;
5367 params.push_back(":"+std::string(user->awaymsg));
5368 Utils->DoOneToMany(user->nick,"AWAY",params);
5372 virtual void OnCancelAway(userrec* user)
5376 std::deque<std::string> params;
5378 Utils->DoOneToMany(user->nick,"AWAY",params);
5382 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5384 TreeSocket* s = (TreeSocket*)opaque;
5387 if (target_type == TYPE_USER)
5389 userrec* u = (userrec*)target;
5390 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5394 chanrec* c = (chanrec*)target;
5395 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5400 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5402 TreeSocket* s = (TreeSocket*)opaque;
5405 if (target_type == TYPE_USER)
5407 userrec* u = (userrec*)target;
5408 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5410 else if (target_type == TYPE_CHANNEL)
5412 chanrec* c = (chanrec*)target;
5413 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5416 if (target_type == TYPE_OTHER)
5418 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5422 virtual void OnEvent(Event* event)
5424 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5426 if (event->GetEventID() == "send_metadata")
5428 if (params->size() < 3)
5430 (*params)[2] = ":" + (*params)[2];
5431 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5433 else if (event->GetEventID() == "send_topic")
5435 if (params->size() < 2)
5437 (*params)[1] = ":" + (*params)[1];
5438 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5439 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5440 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5442 else if (event->GetEventID() == "send_mode")
5444 if (params->size() < 2)
5446 // Insert the TS value of the object, either userrec or chanrec
5448 userrec* a = ServerInstance->FindNick((*params)[0]);
5455 chanrec* a = ServerInstance->FindChan((*params)[0]);
5461 params->insert(params->begin() + 1,ConvToStr(ourTS));
5462 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5464 else if (event->GetEventID() == "send_mode_explicit")
5466 if (params->size() < 2)
5468 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5470 else if (event->GetEventID() == "send_opers")
5472 if (params->size() < 1)
5474 (*params)[0] = ":" + (*params)[0];
5475 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5477 else if (event->GetEventID() == "send_modeset")
5479 if (params->size() < 2)
5481 (*params)[1] = ":" + (*params)[1];
5482 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5484 else if (event->GetEventID() == "send_snoset")
5486 if (params->size() < 2)
5488 (*params)[1] = ":" + (*params)[1];
5489 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5491 else if (event->GetEventID() == "send_push")
5493 if (params->size() < 2)
5496 userrec *a = ServerInstance->FindNick((*params)[0]);
5501 (*params)[1] = ":" + (*params)[1];
5502 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5506 virtual ~ModuleSpanningTree()
5508 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5509 /* This will also free the listeners */
5512 ServerInstance->Timers->DelTimer(SyncTimer);
5515 virtual Version GetVersion()
5517 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5520 void Implements(char* List)
5522 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5523 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5524 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5525 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5526 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5527 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5528 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5531 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5532 * so that any activity it sees is FINAL, e.g. we arent going to send out
5533 * a NICK message before m_cloaking has finished putting the +x on the user,
5535 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5536 * the module call queue.
5538 Priority Prioritize()
5540 return PRIORITY_LAST;
5544 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5548 void TimeSyncTimer::Tick(time_t TIME)
5550 Module->BroadcastTimeSync();
5551 Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5552 Instance->Timers->AddTimer(Module->SyncTimer);
5555 void SpanningTreeUtilities::DoFailOver(Link* x)
5557 if (x->FailOver.length())
5559 if (x->FailOver == x->Name)
5561 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Name.c_str());
5564 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5567 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5568 Creator->ConnectServer(TryThisOne);
5572 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5577 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5579 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5581 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5589 class ModuleSpanningTreeFactory : public ModuleFactory
5592 ModuleSpanningTreeFactory()
5596 ~ModuleSpanningTreeFactory()
5600 virtual Module * CreateModule(InspIRCd* Me)
5602 return new ModuleSpanningTree(Me);
5608 extern "C" void * init_module( void )
5610 return new ModuleSpanningTreeFactory;