1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $ModDesc: Povides a spanning tree server link protocol */
16 #include "configreader.h"
20 #include "commands/cmd_whois.h"
21 #include "commands/cmd_stats.h"
26 #include "transport.h"
28 /** If you make a change which breaks the protocol, increment this.
29 * If you completely change the protocol, completely change the number.
31 * IMPORTANT: If you make changes, document your changes here, without fail:
32 * http://www.inspircd.org/wiki/List_of_protocol_changes_between_versions
34 * Failure to document your protocol changes will result in a painfully
35 * painful death by pain. You have been warned.
37 const long ProtocolVersion = 1103;
40 * The server list in InspIRCd is maintained as two structures
41 * which hold the data in different ways. Most of the time, we
42 * want to very quicky obtain three pieces of information:
44 * (1) The information on a server
45 * (2) The information on the server we must send data through
46 * to actually REACH the server we're after
47 * (3) Potentially, the child/parent objects of this server
49 * The InspIRCd spanning protocol provides easy access to these
50 * by storing the data firstly in a recursive structure, where
51 * each item references its parent item, and a dynamic list
52 * of child items, and another structure which stores the items
53 * hashed, linearly. This means that if we want to find a server
54 * by name quickly, we can look it up in the hash, avoiding
55 * any O(n) lookups. If however, during a split or sync, we want
56 * to apply an operation to a server, and any of its child objects
57 * we can resort to recursion to walk the tree structure.
58 * Any socket can have one of five states at any one time.
59 * The LISTENER state indicates a socket which is listening
60 * for connections. It cannot receive data itself, only incoming
62 * The CONNECTING state indicates an outbound socket which is
63 * waiting to be writeable.
64 * The WAIT_AUTH_1 state indicates the socket is outbound and
65 * has successfully connected, but has not yet sent and received
67 * The WAIT_AUTH_2 state indicates that the socket is inbound
68 * (allocated by a LISTENER) but has not yet sent and received
70 * The CONNECTED state represents a fully authorized, fully
73 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
75 /* Foward declarations */
79 class ModuleSpanningTree;
80 class SpanningTreeUtilities;
82 /* This hash_map holds the hash equivalent of the server
83 * tree, used for rapid linear lookups.
85 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
87 typedef std::map<TreeServer*,TreeServer*> TreeServerList;
89 /** A group of modules that implement InspSocketHook
90 * that we can use to hook our server to server connections.
92 typedef std::map<irc::string, Module*> hookmodules;
94 /** The Link class might as well be a struct,
95 * but this is C++ and we don't believe in structs (!).
96 * It holds the entire information of one <link>
97 * tag from the main config file. We maintain a list
98 * of them, and populate the list on rehash/load.
100 class Link : public classbase
106 std::string SendPass;
107 std::string RecvPass;
108 unsigned long AutoConnect;
109 time_t NextConnectTime;
110 bool HiddenFromStats;
111 std::string FailOver;
116 class HandshakeTimer : public InspTimer
122 SpanningTreeUtilities* Utils;
125 HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u);
126 virtual void Tick(time_t TIME);
130 /** Contains helper functions and variables for this module,
131 * and keeps them out of the global namespace
133 class SpanningTreeUtilities
138 InspIRCd* ServerInstance;
142 ModuleSpanningTree* Creator;
143 /** Flatten links and /MAP for non-opers
146 /** Hide U-Lined servers in /MAP and /LINKS
149 /** Announce TS changes to channels on merge
151 bool AnnounceTSChange;
152 /** Synchronize timestamps between servers
155 /** Socket bindings for listening sockets
157 std::vector<TreeSocket*> Bindings;
158 /** This variable represents the root of the server tree
160 TreeServer *TreeRoot;
161 /** IPs allowed to link to us
163 std::vector<std::string> ValidIPs;
164 /** Hash of currently connected servers by name
166 server_hash serverlist;
167 /** Holds the data from the <link> tags in the conf
169 std::vector<Link> LinkBlocks;
170 /** Holds a bitmask of queued xline types waiting to be applied.
171 * Will be a mask containing values APPLY_GLINES, APPLY_KLINES,
172 * APPLY_QLINES and APPLY_ZLINES.
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> <target-server-mask>";
630 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
634 if (!Utils->FindServer(parameters[0]))
636 user->WriteServ("NOTICE %s :*** RCONNECT: Server \002%s\002 isn't connected to the network!", user->nick, parameters[0]);
640 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
643 /* Is this aimed at our server? */
644 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
646 /* Yes, initiate the given connect */
647 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
649 para[0] = parameters[1];
650 std::string original_command = std::string("CONNECT ") + parameters[1];
651 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
660 /** Every SERVER connection inbound or outbound is represented by
661 * an object of type TreeSocket.
662 * TreeSockets, being inherited from InspSocket, can be tied into
663 * the core socket engine, and we cn therefore receive activity events
664 * for them, just like activex objects on speed. (yes really, that
665 * is a technical term!) Each of these which relates to a locally
666 * connected server is assocated with it, by hooking it onto a
667 * TreeSocket class using its constructor. In this way, we can
668 * maintain a list of servers, some of which are directly connected,
669 * some of which are not.
671 class TreeSocket : public InspSocket
673 SpanningTreeUtilities* Utils;
675 std::string in_buffer;
676 ServerState LinkState;
677 std::string InboundServerName;
678 std::string InboundDescription;
680 int num_lost_servers;
682 bool LastPingWasGood;
684 unsigned int keylength;
685 std::string ModuleList;
686 std::map<std::string,std::string> CapKeys;
691 /** Because most of the I/O gubbins are encapsulated within
692 * InspSocket, we just call the superclass constructor for
693 * most of the action, and append a few of our own values
696 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod = NULL)
697 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
700 this->LinkState = LISTENER;
702 Instance->Log(DEBUG, "HOOK = %08x", Hook);
704 if (listening && Hook)
705 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
708 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName, Module* HookMod = NULL)
709 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
712 this->LinkState = CONNECTING;
715 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
718 /** When a listening socket gives us a new file descriptor,
719 * we must associate it with a socket without creating a new
720 * connection. This constructor is used for this purpose.
722 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod = NULL)
723 : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
725 this->LinkState = WAIT_AUTH_1;
727 /* If we have a transport module hooked to the parent, hook the same module to this
728 * socket, and set a timer waiting for handshake before we send CAPAB etc.
732 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
733 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils));
737 /* Otherwise, theres no lower layer transport in plain TCP/IP,
738 * so just send the capabilities right now.
740 this->SendCapabilities();
744 ServerState GetLinkState()
746 return this->LinkState;
757 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
760 /** When an outbound connection finishes connecting, we receive
761 * this event, and must send our SERVER string to the other
762 * side. If the other side is happy, as outlined in the server
763 * to server docs on the inspircd.org site, the other side
764 * will then send back its own server string.
766 virtual bool OnConnected()
768 if (this->LinkState == CONNECTING)
770 /* we do not need to change state here. */
771 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
773 if (x->Name == this->myhost)
775 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
779 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
780 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+x->Hook+"\2");
783 this->SendCapabilities();
785 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
787 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
789 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
795 /* There is a (remote) chance that between the /CONNECT and the connection
796 * being accepted, some muppet has removed the <link> block and rehashed.
797 * If that happens the connection hangs here until it's closed. Unlikely
798 * and rather harmless.
800 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
804 virtual void OnError(InspSocketError e)
806 /* We don't handle this method, because all our
807 * dirty work is done in OnClose() (see below)
808 * which is still called on error conditions too.
810 if (e == I_ERR_CONNECT)
812 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
813 Link* MyLink = Utils->FindLink(myhost);
815 Utils->DoFailOver(MyLink);
819 virtual int OnDisconnect()
821 /* For the same reason as above, we don't
822 * handle OnDisconnect()
827 /** Recursively send the server tree with distances as hops.
828 * This is used during network burst to inform the other server
829 * (and any of ITS servers too) of what servers we know about.
830 * If at any point any of these servers already exist on the other
831 * end, our connection may be terminated. The hopcounts given
832 * by this function are relative, this doesn't matter so long as
833 * they are all >1, as all the remote servers re-calculate them
834 * to be relative too, with themselves as hop 0.
836 void SendServers(TreeServer* Current, TreeServer* s, int hops)
839 for (unsigned int q = 0; q < Current->ChildCount(); q++)
841 TreeServer* recursive_server = Current->GetChild(q);
842 if (recursive_server != s)
844 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
845 this->WriteLine(command);
846 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
847 /* down to next level */
848 this->SendServers(recursive_server, s, hops+1);
853 std::string MyCapabilities()
855 std::vector<std::string> modlist;
856 std::string capabilities = "";
858 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
860 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
861 modlist.push_back(this->Instance->Config->module_names[i]);
863 sort(modlist.begin(),modlist.end());
864 for (unsigned int i = 0; i < modlist.size(); i++)
867 capabilities = capabilities + ",";
868 capabilities = capabilities + modlist[i];
873 void SendCapabilities()
875 irc::commasepstream modulelist(MyCapabilities());
877 this->WriteLine("CAPAB START");
879 /* Send module names, split at 509 length */
880 std::string item = "*";
881 std::string line = "CAPAB MODULES ";
882 while ((item = modulelist.GetToken()) != "")
884 if (line.length() + item.length() + 1 > 509)
886 this->WriteLine(line);
887 line = "CAPAB MODULES ";
890 if (line != "CAPAB MODULES ")
895 if (line != "CAPAB MODULES ")
896 this->WriteLine(line);
903 #ifdef SUPPORT_IP6LINKS
906 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));
908 this->WriteLine("CAPAB END");
911 /* Check a comma seperated list for an item */
912 bool HasItem(const std::string &list, const std::string &item)
914 irc::commasepstream seplist(list);
916 std::string item2 = "*";
917 while ((item2 = seplist.GetToken()) != "")
926 /* Isolate and return the elements that are different between two comma seperated lists */
927 std::string ListDifference(const std::string &one, const std::string &two)
929 irc::commasepstream list_one(one);
930 std::string item = "*";
931 std::string result = "";
932 while ((item = list_one.GetToken()) != "")
934 if (!HasItem(two, item))
943 bool Capab(const std::deque<std::string> ¶ms)
945 if (params.size() < 1)
947 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
951 if (params[0] == "START")
953 this->ModuleList = "";
954 this->CapKeys.clear();
956 else if (params[0] == "END")
958 std::string reason = "";
960 #ifdef SUPPORT_IP6LINKS
963 /* Compare ModuleList and check CapKeys...
964 * Maybe this could be tidier? -- Brain
966 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
968 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
971 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
975 diff = "this server:" + diff;
977 if (diff.length() == 12)
978 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
980 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
983 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
984 reason = "We don't both support linking to IPV6 servers";
986 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
987 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
989 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
990 reason = "Maximum nickname lengths differ or remote nickname length not specified";
992 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
994 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
996 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
1000 reason = "Protocol version not specified";
1004 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))))
1005 reason = "We don't both have halfop support enabled/disabled identically";
1007 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
1008 reason = "Maximum ident lengths differ or remote ident length not specified";
1010 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
1011 reason = "Maximum channel lengths differ or remote channel length not specified";
1013 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
1014 reason = "Maximum modes per line differ or remote modes per line not specified";
1016 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
1017 reason = "Maximum quit lengths differ or remote quit length not specified";
1019 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
1020 reason = "Maximum topic lengths differ or remote topic length not specified";
1022 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
1023 reason = "Maximum kick lengths differ or remote kick length not specified";
1025 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
1026 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
1028 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
1029 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
1031 if (reason.length())
1033 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
1037 else if ((params[0] == "MODULES") && (params.size() == 2))
1039 if (!this->ModuleList.length())
1041 this->ModuleList.append(params[1]);
1045 this->ModuleList.append(",");
1046 this->ModuleList.append(params[1]);
1049 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
1051 irc::tokenstream capabs(params[1]);
1052 std::string item = "*";
1053 while ((item = capabs.GetToken()) != "")
1055 /* Process each key/value pair */
1056 std::string::size_type equals = item.rfind('=');
1057 if (equals != std::string::npos)
1059 std::string var = item.substr(0, equals);
1060 std::string value = item.substr(equals+1, item.length());
1061 this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
1062 CapKeys[var] = value;
1070 /** This function forces this server to quit, removing this server
1071 * and any users on it (and servers and users below that, etc etc).
1072 * It's very slow and pretty clunky, but luckily unless your network
1073 * is having a REAL bad hair day, this function shouldnt be called
1074 * too many times a month ;-)
1076 void SquitServer(std::string &from, TreeServer* Current)
1078 /* recursively squit the servers attached to 'Current'.
1079 * We're going backwards so we don't remove users
1080 * while we still need them ;)
1082 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1084 TreeServer* recursive_server = Current->GetChild(q);
1085 this->SquitServer(from,recursive_server);
1087 /* Now we've whacked the kids, whack self */
1089 num_lost_users += Current->QuitUsers(from);
1092 /** This is a wrapper function for SquitServer above, which
1093 * does some validation first and passes on the SQUIT to all
1094 * other remaining servers.
1096 void Squit(TreeServer* Current, const std::string &reason)
1098 if ((Current) && (Current != Utils->TreeRoot))
1100 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
1101 rmode.Send(Instance);
1103 std::deque<std::string> params;
1104 params.push_back(Current->GetName());
1105 params.push_back(":"+reason);
1106 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1107 if (Current->GetParent() == Utils->TreeRoot)
1109 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1113 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1115 num_lost_servers = 0;
1117 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1118 SquitServer(from, Current);
1120 Current->GetParent()->DelChild(Current);
1122 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1126 Instance->Log(DEFAULT,"Squit from unknown server");
1130 /** FMODE command - server mode with timestamp checks */
1131 bool ForceMode(const std::string &source, std::deque<std::string> ¶ms)
1133 /* Chances are this is a 1.0 FMODE without TS */
1134 if (params.size() < 3)
1136 /* No modes were in the command, probably a channel with no modes set on it */
1141 std::string sourceserv;
1143 /* Are we dealing with an FMODE from a user, or from a server? */
1144 userrec* who = this->Instance->FindNick(source);
1147 /* FMODE from a user, set sourceserv to the users server name */
1148 sourceserv = who->server;
1152 /* FMODE from a server, create a fake user to receive mode feedback */
1153 who = new userrec(this->Instance);
1154 who->SetFd(FD_MAGIC_NUMBER);
1155 smode = true; /* Setting this flag tells us we should free the userrec later */
1156 sourceserv = source; /* Set sourceserv to the actual source string */
1158 const char* modelist[64];
1161 memset(&modelist,0,sizeof(modelist));
1162 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1166 /* The timestamp is in this position.
1167 * We don't want to pass that up to the
1168 * server->client protocol!
1170 TS = atoi(params[q].c_str());
1174 /* Everything else is fine to append to the modelist */
1175 modelist[n++] = params[q].c_str();
1179 /* Extract the TS value of the object, either userrec or chanrec */
1180 userrec* dst = this->Instance->FindNick(params[0]);
1181 chanrec* chan = NULL;
1189 chan = this->Instance->FindChan(params[0]);
1195 /* Oops, channel doesnt exist! */
1199 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1204 Instance->Log(DEBUG,"Entering TS equality check");
1205 ModeHandler* mh = NULL;
1206 unsigned long paramptr = 3;
1207 std::string to_bounce = "";
1208 std::string to_keep = "";
1209 std::vector<std::string> params_to_keep;
1210 std::string params_to_bounce = "";
1212 char cur_change = 1;
1213 char old_change = 0;
1214 char old_bounce_change = 0;
1215 /* Merge modes, basically do special stuff to mode with params */
1216 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1229 /* We only care about whats being set,
1230 * not whats being unset
1232 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1234 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1236 /* We only want to do special things to
1237 * modes with parameters, we are going to rewrite
1241 adding ? cur_change = '+' : cur_change = '-';
1243 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1245 /* The mode is set here, check which we should keep */
1248 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1250 if (which_to_keep == true)
1252 /* Keep ours, bounce theirs:
1253 * Send back ours to them and
1254 * drop their mode changs
1256 adding ? cur_change = '+' : cur_change = '-';
1257 if (cur_change != old_bounce_change)
1258 to_bounce += cur_change;
1260 old_bounce_change = cur_change;
1262 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1263 params_to_bounce.append(" ").append(ret.second);
1267 /* Keep theirs: Accept their mode change,
1270 adding ? cur_change = '+' : cur_change = '-';
1271 if (cur_change != old_change)
1272 to_keep += cur_change;
1274 old_change = cur_change;
1276 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1277 params_to_keep.push_back(params[paramptr]);
1282 /* Mode isnt set here, we want it */
1283 adding ? cur_change = '+' : cur_change = '-';
1284 if (cur_change != old_change)
1285 to_keep += cur_change;
1287 old_change = cur_change;
1289 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1290 params_to_keep.push_back(params[paramptr]);
1297 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1301 adding ? cur_change = '+' : cur_change = '-';
1303 /* Just keep this, safe to merge with no checks
1304 * it has no parameters
1307 if (cur_change != old_change)
1308 to_keep += cur_change;
1310 old_change = cur_change;
1312 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1314 Instance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1315 params_to_keep.push_back(params[paramptr++]);
1322 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1326 /* Taking a mode away */
1327 adding ? cur_change = '+' : cur_change = '-';
1329 if (cur_change != old_change)
1330 to_keep += cur_change;
1332 old_change = cur_change;
1334 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1335 params_to_keep.push_back(params[paramptr++]);
1342 if (to_bounce.length())
1344 std::deque<std::string> newparams;
1345 newparams.push_back(params[0]);
1346 newparams.push_back(ConvToStr(ourTS));
1347 newparams.push_back(to_bounce+params_to_bounce);
1348 Instance->Log(DEBUG,"BOUNCE BACK: %s",(to_bounce+params_to_bounce).c_str());
1349 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1352 if (to_keep.length())
1356 modelist[0] = params[0].c_str();
1357 modelist[1] = to_keep.c_str();
1359 if (params_to_keep.size() > 0)
1361 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1363 Instance->Log(DEBUG,"KEEP Item %d of %d: %s", q, params_to_keep.size(), params_to_keep[q].c_str());
1364 modelist[n++] = params_to_keep[q].c_str();
1370 Instance->Log(DEBUG,"Send mode");
1371 this->Instance->SendMode(modelist, n, who);
1375 Instance->Log(DEBUG,"Send mode client");
1376 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1379 /* HOT POTATO! PASS IT ON! */
1380 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1384 /* U-lined servers always win regardless of their TS */
1385 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1387 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1388 * SHOULD accept it, if its clock is right.
1390 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1391 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1392 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1394 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1395 * writing the code. It took me a while to come up with this solution.
1397 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1400 std::deque<std::string> newparams; /* New parameter list we send back */
1401 newparams.push_back(params[0]); /* Target, user or channel */
1402 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1403 newparams.push_back(""); /* This contains the mode string. For now
1404 * it's empty, we fill it below.
1407 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1408 * set to avoid a desync here.
1410 std::string modebounce = "";
1413 ModeHandler* mh = NULL;
1414 char cur_change = 1;
1415 char old_change = 0;
1416 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1418 /* Iterate over all mode chars in the sent set */
1421 /* Adding or subtracting modes? */
1429 /* Find the mode handler for this mode */
1430 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1432 /* Got a mode handler?
1433 * This also prevents us bouncing modes we have no handler for.
1440 /* Does the mode require a parameter right now?
1441 * If it does, fetch it if we can
1443 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1446 /* Call the ModeSet method to determine if its set with the
1447 * given parameter here or not.
1449 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1451 /* XXX: Really. Dont ask.
1452 * Determine from if its set combined with what the current
1453 * 'state' is (adding or not) as to wether we should 'invert'
1454 * or 'reinforce' the mode change
1456 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1458 /* Quickly determine if we have 'flipped' from + to -,
1459 * or - to +, to prevent unneccessary +/- chars in the
1460 * output string that waste bandwidth
1462 if (cur_change != old_change)
1463 modebounce += cur_change;
1464 old_change = cur_change;
1466 /* Add the mode character to the output string */
1467 modebounce += mh->GetModeChar();
1469 /* We got a parameter back from ModeHandler::ModeSet,
1470 * are we supposed to be sending one out right now?
1472 if (ret.second.length())
1474 if (mh->GetNumParams(cur_change == '+') > 0)
1475 /* Yes we're supposed to be sending out
1476 * the parameter. Make sure it goes
1478 newparams.push_back(ret.second);
1486 /* Update the parameters for FMODE with the new 'bounced' string */
1487 newparams[2] = modebounce;
1488 /* Only send it back the way it came, no need to send it anywhere else */
1489 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1490 Instance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1494 Instance->Log(DEBUG,"Allow modes, TS lower for sender");
1495 /* The server was ulined, but something iffy is up with the TS.
1496 * Sound the alarm bells!
1498 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1500 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());
1502 /* Allow the mode, route it to either server or user command handling */
1504 this->Instance->SendMode(modelist,n,who);
1506 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1508 /* HOT POTATO! PASS IT ON! */
1509 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1511 /* Are we supposed to free the userrec? */
1518 /** FTOPIC command */
1519 bool ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
1521 if (params.size() != 4)
1523 time_t ts = atoi(params[1].c_str());
1524 std::string nsource = source;
1526 chanrec* c = this->Instance->FindChan(params[0]);
1529 if ((ts >= c->topicset) || (!*c->topic))
1531 std::string oldtopic = c->topic;
1532 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1533 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1535 /* if the topic text is the same as the current topic,
1536 * dont bother to send the TOPIC command out, just silently
1537 * update the set time and set nick.
1539 if (oldtopic != params[3])
1541 userrec* user = this->Instance->FindNick(source);
1544 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1548 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1549 nsource = user->server;
1551 /* all done, send it on its way */
1552 params[3] = ":" + params[3];
1553 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1562 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1563 bool ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
1565 /* 1.1 FJOIN works as follows:
1567 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1568 * timestamp 'wins'. From this point on we will refer to this side as the
1569 * winner. The side with the higher timestamp loses, from this point on we
1570 * will call this side the loser or losing side. This should be familiar to
1571 * anyone who's dealt with dreamforge or TS6 before.
1573 * When two sides of a split heal and this occurs, the following things
1576 * If the timestamps are exactly equal, both sides merge their privilages
1577 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1578 * re-created during a split, this is safe to do.
1581 * If the timestamps are NOT equal, the losing side removes all privilage
1582 * modes from all of its users that currently exist in the channel, before
1583 * introducing new users into the channel which are listed in the FJOIN
1584 * command's parameters. This means, all modes +ohv, and privilages added
1585 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1586 * of the channel to match that of the winning side, and the modes of the
1587 * users of the winning side are merged in with the losing side. The loser
1588 * then sends out a set of FMODE commands which 'confirm' that it just
1589 * removed all privilage modes from its existing users, which allows for
1590 * services packages to still work correctly without needing to know the
1591 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1592 * a problem, and services packages must contain code which explicitly
1593 * behaves as TS6 does, removing ops from the losing side of a split where
1594 * neccessary within its internal records, as this state information is
1595 * not explicitly echoed out in that protocol.
1597 * The winning side on the other hand will ignore all user modes from the
1598 * losing side, so only its own modes get applied. Life is simple for those
1599 * who succeed at internets. :-)
1601 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1602 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1603 * you ask? Well, quite simply because we don't need to. They'll be sent
1604 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1605 * the losing side sends any modes for the channel which shouldnt win,
1606 * they wont as their timestamp will be too high :-)
1609 if (params.size() < 3)
1612 char first[MAXBUF]; /* The first parameter of the mode command */
1613 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1614 char* mode_users[127]; /* The values used by the mode command */
1615 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1616 mode_users[0] = first; /* Set this up to be our on-stack value */
1617 mode_users[1] = modestring; /* Same here as above */
1618 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1619 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1621 userrec* who = NULL; /* User we are currently checking */
1622 std::string channel = params[0]; /* Channel name, as a string */
1623 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1624 bool created = false;
1626 /* Try and find the channel */
1627 chanrec* chan = this->Instance->FindChan(channel);
1629 /* Initialize channel name in the mode parameters */
1630 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1632 /* default TS is a high value, which if we dont have this
1633 * channel will let the other side apply their modes.
1635 time_t ourTS = Instance->Time(true)+600;
1637 /* Does this channel exist? if it does, get its REAL timestamp */
1641 created = true; /* don't perform deops, and set TS to correct time after processing. */
1643 /* In 1.1, if they have the newer channel, we immediately clear
1644 * all status modes from our users. We then accept their modes.
1645 * If WE have the newer channel its the other side's job to do this.
1646 * Note that this causes the losing server to send out confirming
1651 Instance->Log(DEBUG,"************ WE LOST TS COMPARE, DEOPPING EVERYONE ********************* ");
1652 std::deque<std::string> param_list;
1654 /* Lower the TS here */
1655 if (Utils->AnnounceTSChange && chan)
1656 chan->WriteChannelWithServ(Instance->Config->ServerName,
1657 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1660 /* Zap all the privilage modes on our side, if the channel exists here */
1663 param_list.push_back(channel);
1664 /* Do this first! */
1666 this->RemoveStatus(Instance->Config->ServerName, param_list);
1670 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1671 irc::tokenstream users(params[2]);
1672 std::string item = "*";
1674 /* do this first, so our mode reversals are correctly received by other servers
1675 * if there is a TS collision.
1677 params[2] = ":" + params[2];
1678 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1680 /* Now, process every 'prefixes,nick' pair */
1683 /* Find next user */
1684 item = users.GetToken();
1686 const char* usr = item.c_str();
1688 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1689 * (is this even possible?) */
1692 const char* permissions = usr;
1694 char* nm = new char[MAXBUF];
1697 /* Iterate through all the prefix values, convert them from prefixes
1698 * to mode letters, and append them to the mode sequence
1700 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1702 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1705 /* This is a valid prefix */
1707 *tnm++ = mh->GetModeChar();
1711 /* Not a valid prefix...
1712 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1714 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1715 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1722 /* Null terminate modes */
1724 /* Advance past the comma, to the nick */
1727 /* Check the user actually exists */
1728 who = this->Instance->FindNick(usr);
1731 /* Did they get any modes? How many times? */
1732 strlcat(modestring, nm, MAXBUF);
1733 for (int k = 0; k < ntimes; k++)
1734 mode_users[modectr++] = strdup(usr);
1736 /* Free temporary buffer used for mode sequence */
1739 /* Check that the user's 'direction' is correct
1740 * based on the server sending the FJOIN. We must
1741 * check each nickname in turn, because the origin of
1742 * the FJOIN may be different to the origin of the nicks
1743 * in the command itself.
1745 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1746 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1748 /* Oh dear oh dear. */
1749 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1752 /* Finally, we can actually place the user into the channel.
1753 * We're sure its right. Final answer, phone a friend.
1755 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1757 /* Have we already queued up MAXMODES modes with parameters
1758 * (+qaohv) ready to be sent to the server?
1760 if (modectr >= (MAXMODES-1))
1762 /* Only actually give the users any status if we lost
1763 * the FJOIN or drew (equal timestamps).
1764 * It isn't actually possible for ourTS to be > TS here,
1765 * only possible to actually have ourTS == TS, or
1766 * ourTS < TS, because if we lost, we already lowered
1767 * our TS above before we entered this loop. We only
1768 * check >= as a safety measure, in case someone stuffed
1769 * up. If someone DID stuff up, it was most likely me.
1770 * Note: I do not like baseball bats in the face...
1774 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1775 this->Instance->SendMode((const char**)mode_users,modectr,who);
1777 /* Something stuffed up, and for some reason, the timestamp is
1778 * NOT lowered right now and should be. Lower it. Usually this
1779 * code won't be executed, doubtless someone will remove it some
1784 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1790 /* Reset all this back to defaults, and
1791 * free any ram we have left allocated.
1793 strcpy(mode_users[1],"+");
1794 for (unsigned int f = 2; f < modectr; f++)
1795 free(mode_users[f]);
1801 /* Remember to free this */
1803 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1804 * We don't try to process the nickname here (that WOULD cause a segfault because
1805 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1806 * in case somehow we're desynched, so that other users which might be able to see
1807 * the nickname get their fair chance to process it.
1809 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1815 /* there werent enough modes built up to flush it during FJOIN,
1816 * or, there are a number left over. flush them out.
1818 if ((modectr > 2) && (who) && (chan))
1822 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1823 this->Instance->SendMode((const char**)mode_users,modectr,who);
1824 /* Yet again, we can't actually get a true value here, if everything else
1825 * is working as it should.
1829 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1835 /* Free anything we have left to free */
1836 for (unsigned int f = 2; f < modectr; f++)
1837 free(mode_users[f]);
1840 /* if we newly created the channel, set it's TS properly. */
1843 /* find created channel .. */
1844 chan = this->Instance->FindChan(channel);
1846 /* w00t said this shouldnt be needed but it is.
1847 * This isnt strictly true, as chan can be NULL
1848 * if a nick collision has occured and therefore
1849 * the channel was never created.
1854 /* All done. That wasnt so bad was it, you can wipe
1855 * the sweat from your forehead now. :-)
1861 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1863 if (params.size() < 8)
1865 if (params.size() > 8)
1867 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1870 // NICK age nick host dhost ident +modes ip :gecos
1872 time_t age = atoi(params[0].c_str());
1874 const char* tempnick = params[1].c_str();
1875 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1877 user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
1879 if (iter != this->Instance->clientlist->end())
1882 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);
1883 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1884 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1888 userrec* _new = new userrec(this->Instance);
1889 (*(this->Instance->clientlist))[tempnick] = _new;
1890 _new->SetFd(FD_MAGIC_NUMBER);
1891 strlcpy(_new->nick, tempnick,NICKMAX-1);
1892 strlcpy(_new->host, params[2].c_str(),63);
1893 strlcpy(_new->dhost, params[3].c_str(),63);
1894 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1895 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1896 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1897 _new->registered = REG_ALL;
1901 * we need to remove the + from the modestring, so we can do our stuff
1903 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1904 if (pos_after_plus != std::string::npos)
1905 params[5] = params[5].substr(pos_after_plus);
1908 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1910 _new->modes[(*v)-65] = 1;
1911 /* For each mode thats set, increase counter */
1912 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
1917 /* now we've done with modes processing, put the + back for remote servers */
1918 params[5] = "+" + params[5];
1920 #ifdef SUPPORT_IP6LINKS
1921 if (params[6].find_first_of(":") != std::string::npos)
1922 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1925 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1927 Instance->AddGlobalClone(_new);
1929 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1931 params[7] = ":" + params[7];
1932 Utils->DoOneToAllButSender(source,"NICK", params, source);
1934 // Increment the Source Servers User Count..
1935 TreeServer* SourceServer = Utils->FindServer(source);
1938 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1939 SourceServer->AddUserCount();
1942 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1947 /** Send one or more FJOINs for a channel of users.
1948 * If the length of a single line is more than 480-NICKMAX
1949 * in length, it is split over multiple lines.
1951 void SendFJoins(TreeServer* Current, chanrec* c)
1955 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1957 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1959 size_t dlen, curlen;
1960 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1962 char* ptr = list + dlen;
1964 CUList *ulist = c->GetUsers();
1965 std::string modes = "";
1966 std::string params = "";
1968 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1970 // The first parameter gets a : before it
1971 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1978 if (curlen > (480-NICKMAX))
1980 buffer.append(list).append("\r\n");
1982 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1990 buffer.append(list).append("\r\n");
1992 /* Sorry for the hax. Because newly created channels assume +nt,
1993 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1995 bool inverted = false;
1996 if (!c->IsModeSet('n'))
2001 if (!c->IsModeSet('t'))
2011 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
2014 params.append(" ").append(b->data);
2016 if (params.length() >= MAXMODES)
2018 /* Wrap at MAXMODES */
2019 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");
2025 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
2027 /* Only send these if there are any */
2029 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);
2031 this->WriteLine(buffer);
2034 /** Send G, Q, Z and E lines */
2035 void SendXLines(TreeServer* Current)
2039 std::string n = this->Instance->Config->ServerName;
2040 const char* sn = n.c_str();
2042 /* Yes, these arent too nice looking, but they get the job done */
2043 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
2045 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);
2046 buffer.append(data);
2048 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
2050 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);
2051 buffer.append(data);
2053 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
2055 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);
2056 buffer.append(data);
2058 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
2060 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);
2061 buffer.append(data);
2063 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
2065 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);
2066 buffer.append(data);
2068 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
2070 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);
2071 buffer.append(data);
2073 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
2075 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);
2076 buffer.append(data);
2078 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
2080 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);
2081 buffer.append(data);
2084 if (!buffer.empty())
2085 this->WriteLine(buffer);
2088 /** Send channel modes and topics */
2089 void SendChannelModes(TreeServer* Current)
2092 std::deque<std::string> list;
2093 std::string n = this->Instance->Config->ServerName;
2094 const char* sn = n.c_str();
2095 for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
2097 SendFJoins(Current, c->second);
2098 if (*c->second->topic)
2100 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2101 this->WriteLine(data);
2103 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2105 c->second->GetExtList(list);
2106 for (unsigned int j = 0; j < list.size(); j++)
2108 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2113 /** send all users and their oper state/modes */
2114 void SendUsers(TreeServer* Current)
2117 std::deque<std::string> list;
2118 std::string dataline;
2119 for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
2121 if (u->second->registered == REG_ALL)
2123 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);
2124 this->WriteLine(data);
2125 if (*u->second->oper)
2127 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2128 this->WriteLine(data);
2130 if (*u->second->awaymsg)
2132 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2133 this->WriteLine(data);
2135 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2137 u->second->GetExtList(list);
2138 for (unsigned int j = 0; j < list.size(); j++)
2140 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2146 /** This function is called when we want to send a netburst to a local
2147 * server. There is a set order we must do this, because for example
2148 * users require their servers to exist, and channels require their
2149 * users to exist. You get the idea.
2151 void DoBurst(TreeServer* s)
2153 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2154 std::string endburst = "ENDBURST";
2155 // Because by the end of the netburst, it could be gone!
2156 std::string name = s->GetName();
2157 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2158 this->WriteLine(burst);
2159 /* send our version string */
2160 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2161 /* Send server tree */
2162 this->SendServers(Utils->TreeRoot,s,1);
2163 /* Send users and their oper status */
2165 /* Send everything else (channel modes, xlines etc) */
2166 this->SendChannelModes(s);
2167 this->SendXLines(s);
2168 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2169 this->WriteLine(endburst);
2170 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2173 /** This function is called when we receive data from a remote
2174 * server. We buffer the data in a std::string (it doesnt stay
2175 * there for long), reading using InspSocket::Read() which can
2176 * read up to 16 kilobytes in one operation.
2178 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2179 * THE SOCKET OBJECT FOR US.
2181 virtual bool OnDataReady()
2183 char* data = this->Read();
2184 /* Check that the data read is a valid pointer and it has some content */
2187 this->in_buffer.append(data);
2188 /* While there is at least one new line in the buffer,
2189 * do something useful (we hope!) with it.
2191 while (in_buffer.find("\n") != std::string::npos)
2193 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2194 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2195 /* Use rfind here not find, as theres more
2196 * chance of the \r being near the end of the
2197 * string, not the start.
2199 if (ret.find("\r") != std::string::npos)
2200 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2201 /* Process this one, abort if it
2202 * didnt return true.
2204 if (!this->ProcessLine(ret))
2211 /* EAGAIN returns an empty but non-NULL string, so this
2212 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2214 return (data && !*data);
2217 int WriteLine(std::string line)
2219 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2220 line.append("\r\n");
2221 return this->Write(line);
2224 /* Handle ERROR command */
2225 bool Error(std::deque<std::string> ¶ms)
2227 if (params.size() < 1)
2229 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2230 /* we will return false to cause the socket to close. */
2234 /** remote MOTD. leet, huh? */
2235 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2237 if (params.size() > 0)
2239 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2241 /* It's for our server */
2242 string_list results;
2243 userrec* source = this->Instance->FindNick(prefix);
2247 std::deque<std::string> par;
2248 par.push_back(prefix);
2251 if (!Instance->Config->MOTD.size())
2253 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2254 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2258 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2259 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2261 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2263 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2264 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2267 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2268 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2274 userrec* source = this->Instance->FindNick(prefix);
2276 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2282 /** remote ADMIN. leet, huh? */
2283 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2285 if (params.size() > 0)
2287 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2289 /* It's for our server */
2290 string_list results;
2291 userrec* source = this->Instance->FindNick(prefix);
2295 std::deque<std::string> par;
2296 par.push_back(prefix);
2299 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2300 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2302 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2303 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2305 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2306 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2308 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2309 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2315 userrec* source = this->Instance->FindNick(prefix);
2317 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2323 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2325 /* Get the reply to a STATS query if it matches this servername,
2326 * and send it back as a load of PUSH queries
2328 if (params.size() > 1)
2330 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2332 /* It's for our server */
2333 string_list results;
2334 userrec* source = this->Instance->FindNick(prefix);
2337 std::deque<std::string> par;
2338 par.push_back(prefix);
2340 DoStats(this->Instance, *(params[0].c_str()), source, results);
2341 for (size_t i = 0; i < results.size(); i++)
2343 par[1] = "::" + results[i];
2344 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2351 userrec* source = this->Instance->FindNick(prefix);
2353 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2360 /** Because the core won't let users or even SERVERS set +o,
2361 * we use the OPERTYPE command to do this.
2363 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2365 if (params.size() != 1)
2367 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2370 std::string opertype = params[0];
2371 userrec* u = this->Instance->FindNick(prefix);
2374 u->modes[UM_OPERATOR] = 1;
2375 this->Instance->all_opers.push_back(u);
2376 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2377 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2378 this->Instance->SNO->WriteToSnoMask('o',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server, u->nick,u->ident,u->host,irc::Spacify(opertype.c_str()));
2384 /** Because Andy insists that services-compatible servers must
2385 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2387 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2389 if (params.size() < 3)
2392 userrec* u = this->Instance->FindNick(params[0]);
2396 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2399 std::deque<std::string> par;
2400 par.push_back(params[1]);
2401 /* This is not required as one is sent in OnUserPostNick below
2403 //Utils->DoOneToMany(u->nick,"NICK",par);
2404 if (!u->ForceNickChange(params[1].c_str()))
2406 userrec::QuitUser(this->Instance, u, "Nickname collision");
2409 u->age = atoi(params[2].c_str());
2416 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
2417 * then let that server do the dirty work (squit it!). Example:
2418 * 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
2420 bool RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
2422 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
2423 if (params.size() < 2)
2426 TreeServer* s = Utils->FindServerMask(params[0]);
2430 if (s == Utils->TreeRoot)
2432 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
2436 TreeSocket* sock = s->GetSocket();
2440 /* it's locally connected, KILL IT! */
2441 Instance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
2442 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());
2443 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
2444 Instance->SE->DelFd(sock);
2450 /* route the rsquit */
2451 params[1] = ":" + params[1];
2452 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
2457 /* mother fucker! it doesn't exist */
2463 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2465 if (params.size() < 2)
2468 userrec* u = this->Instance->FindNick(params[0]);
2472 /* only join if it's local, otherwise just pass it on! */
2474 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2475 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2480 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2482 if (params.size() < 1)
2485 std::string servermask = params[0];
2487 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2489 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
2490 this->Instance->RehashServer();
2491 Utils->ReadConfiguration(false);
2492 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2494 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2498 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2500 if (params.size() != 2)
2503 std::string nick = params[0];
2504 userrec* u = this->Instance->FindNick(prefix);
2505 userrec* who = this->Instance->FindNick(nick);
2509 /* Prepend kill source, if we don't have one */
2510 std::string sourceserv = prefix;
2513 sourceserv = u->server;
2515 if (*(params[1].c_str()) != '[')
2517 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2519 std::string reason = params[1];
2520 params[1] = ":" + params[1];
2521 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2522 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2523 userrec::QuitUser(this->Instance,who,reason);
2528 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2530 if (params.size() < 1)
2533 if (params.size() == 1)
2535 TreeServer* ServerSource = Utils->FindServer(prefix);
2538 ServerSource->SetPingFlag();
2543 std::string forwardto = params[1];
2544 if (forwardto == this->Instance->Config->ServerName)
2547 * this is a PONG for us
2548 * if the prefix is a user, check theyre local, and if they are,
2549 * dump the PONG reply back to their fd. If its a server, do nowt.
2550 * Services might want to send these s->s, but we dont need to yet.
2552 userrec* u = this->Instance->FindNick(prefix);
2556 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2561 // not for us, pass it on :)
2562 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2569 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2571 if (params.size() < 3)
2574 TreeServer* ServerSource = Utils->FindServer(prefix);
2578 if (params[0] == "*")
2580 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2582 else if (*(params[0].c_str()) == '#')
2584 chanrec* c = this->Instance->FindChan(params[0]);
2587 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2590 else if (*(params[0].c_str()) != '#')
2592 userrec* u = this->Instance->FindNick(params[0]);
2595 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2600 params[2] = ":" + params[2];
2601 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2605 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2607 if (params.size() < 1)
2610 TreeServer* ServerSource = Utils->FindServer(prefix);
2614 ServerSource->SetVersion(params[0]);
2616 params[0] = ":" + params[0];
2617 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2621 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2623 if (params.size() < 1)
2626 userrec* u = this->Instance->FindNick(prefix);
2630 u->ChangeDisplayedHost(params[0].c_str());
2631 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2636 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2638 if (params.size() < 6)
2641 bool propogate = false;
2643 if (!this->bursting)
2644 Utils->lines_to_apply = 0;
2646 switch (*(params[0].c_str()))
2649 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2650 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2652 Utils->lines_to_apply |= APPLY_ZLINES;
2655 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2656 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2658 Utils->lines_to_apply |= APPLY_QLINES;
2661 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2662 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2665 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2666 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2668 Utils->lines_to_apply |= APPLY_GLINES;
2671 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2673 Utils->lines_to_apply |= APPLY_KLINES;
2676 /* Just in case... */
2677 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2682 /* Send it on its way */
2685 if (atoi(params[4].c_str()))
2687 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());
2691 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());
2693 params[5] = ":" + params[5];
2694 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2696 if (!this->bursting)
2698 Instance->Log(DEBUG,"Applying lines with mask %d...", Utils->lines_to_apply);
2699 Instance->XLines->apply_lines(Utils->lines_to_apply);
2700 Utils->lines_to_apply = 0;
2705 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2707 if (params.size() < 1)
2710 userrec* u = this->Instance->FindNick(prefix);
2714 u->ChangeName(params[0].c_str());
2715 params[0] = ":" + params[0];
2716 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2721 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2723 if (params.size() < 1)
2726 Instance->Log(DEBUG,"In IDLE command");
2727 userrec* u = this->Instance->FindNick(prefix);
2731 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2732 // an incoming request
2733 if (params.size() == 1)
2735 userrec* x = this->Instance->FindNick(params[0]);
2736 if ((x) && (IS_LOCAL(x)))
2738 userrec* x = this->Instance->FindNick(params[0]);
2739 char signon[MAXBUF];
2742 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2743 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2744 std::deque<std::string> par;
2745 par.push_back(prefix);
2746 par.push_back(signon);
2747 par.push_back(idle);
2748 // ours, we're done, pass it BACK
2749 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2753 // not ours pass it on
2754 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2757 else if (params.size() == 3)
2759 std::string who_did_the_whois = params[0];
2760 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2761 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2763 // an incoming reply to a whois we sent out
2764 std::string nick_whoised = prefix;
2765 unsigned long signon = atoi(params[1].c_str());
2766 unsigned long idle = atoi(params[2].c_str());
2767 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2768 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2772 // not ours, pass it on
2773 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2780 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2782 if (params.size() < 2)
2785 userrec* u = this->Instance->FindNick(params[0]);
2792 u->Write(params[1]);
2796 // continue the raw onwards
2797 params[1] = ":" + params[1];
2798 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2803 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2805 if (!params.size() || !Utils->EnableTimeSync)
2810 if ((params.size() == 2) && (params[1] == "FORCE"))
2813 time_t rts = atoi(params[0].c_str());
2814 time_t us = Instance->Time(true);
2818 Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2820 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2822 else if (force || (rts < us))
2824 int old = Instance->SetTimeDelta(rts - us);
2825 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2827 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2831 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2833 std::deque<std::string> oparams;
2834 oparams.push_back(ConvToStr(us));
2836 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2842 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2844 // :source.server TIME remote.server sendernick
2845 // :remote.server TIME source.server sendernick TS
2846 if (params.size() == 2)
2848 // someone querying our time?
2849 if (this->Instance->Config->ServerName == params[0])
2851 userrec* u = this->Instance->FindNick(params[1]);
2854 params.push_back(ConvToStr(Instance->Time(false)));
2856 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2861 // not us, pass it on
2862 userrec* u = this->Instance->FindNick(params[1]);
2864 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2867 else if (params.size() == 3)
2869 // a response to a previous TIME
2870 userrec* u = this->Instance->FindNick(params[1]);
2871 if ((u) && (IS_LOCAL(u)))
2873 time_t rawtime = atol(params[2].c_str());
2874 struct tm * timeinfo;
2875 timeinfo = localtime(&rawtime);
2877 snprintf(tms,26,"%s",asctime(timeinfo));
2879 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2884 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2890 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2892 if (params.size() < 1)
2895 if (params.size() == 1)
2897 std::string stufftobounce = params[0];
2898 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2903 std::string forwardto = params[1];
2904 if (forwardto == this->Instance->Config->ServerName)
2906 // this is a ping for us, send back PONG to the requesting server
2907 params[1] = params[0];
2908 params[0] = forwardto;
2909 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2913 // not for us, pass it on :)
2914 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2920 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2922 if (params.size() < 1)
2925 chanrec* c = Instance->FindChan(params[0]);
2929 irc::modestacker modestack(false);
2930 CUList *ulist = c->GetUsers();
2932 std::deque<std::string> stackresult;
2935 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2937 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2938 if (modesequence.length())
2940 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2941 irc::spacesepstream sep(modesequence);
2942 std::string modeletters = sep.GetToken();
2943 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2945 while (!modeletters.empty())
2947 char mletter = *(modeletters.begin());
2948 modestack.Push(mletter,sep.GetToken());
2949 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2950 modeletters.erase(modeletters.begin());
2951 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2956 while (modestack.GetStackedLine(stackresult))
2958 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2959 stackresult.push_front(ConvToStr(c->age));
2960 stackresult.push_front(c->name);
2961 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2962 stackresult.erase(stackresult.begin() + 1);
2963 Instance->Log(DEBUG,"Stacked items:");
2964 for (size_t z = 0; z < stackresult.size(); z++)
2966 y[z] = stackresult[z].c_str();
2967 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2969 userrec* n = new userrec(Instance);
2970 n->SetFd(FD_MAGIC_NUMBER);
2971 Instance->SendMode(y, stackresult.size(), n);
2978 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2980 if (params.size() < 4)
2983 std::string servername = params[0];
2984 std::string password = params[1];
2985 // hopcount is not used for a remote server, we calculate this ourselves
2986 std::string description = params[3];
2987 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2991 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2994 TreeServer* CheckDupe = Utils->FindServer(servername);
2997 this->WriteLine("ERROR :Server "+servername+" already exists!");
2998 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
3001 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
3002 ParentOfThis->AddChild(Node);
3003 params[3] = ":" + params[3];
3004 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
3005 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
3009 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
3011 if (params.size() < 4)
3014 irc::string servername = params[0].c_str();
3015 std::string sname = params[0];
3016 std::string password = params[1];
3017 int hops = atoi(params[2].c_str());
3021 this->WriteLine("ERROR :Server too far away for authentication");
3022 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3025 std::string description = params[3];
3026 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3028 if ((x->Name == servername) && (x->RecvPass == password))
3030 TreeServer* CheckDupe = Utils->FindServer(sname);
3033 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3034 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3037 // Begin the sync here. this kickstarts the
3038 // other side, waiting in WAIT_AUTH_2 state,
3039 // into starting their burst, as it shows
3040 // that we're happy.
3041 this->LinkState = CONNECTED;
3042 // we should add the details of this server now
3043 // to the servers tree, as a child of the root
3045 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
3046 Utils->TreeRoot->AddChild(Node);
3047 params[3] = ":" + params[3];
3048 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
3049 this->bursting = true;
3050 this->DoBurst(Node);
3054 this->WriteLine("ERROR :Invalid credentials");
3055 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3059 bool Inbound_Server(std::deque<std::string> ¶ms)
3061 if (params.size() < 4)
3064 irc::string servername = params[0].c_str();
3065 std::string sname = params[0];
3066 std::string password = params[1];
3067 int hops = atoi(params[2].c_str());
3071 this->WriteLine("ERROR :Server too far away for authentication");
3072 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3075 std::string description = params[3];
3076 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3078 if ((x->Name == servername) && (x->RecvPass == password))
3080 TreeServer* CheckDupe = Utils->FindServer(sname);
3083 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3084 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3087 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
3091 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
3092 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
3095 this->InboundServerName = sname;
3096 this->InboundDescription = description;
3097 // this is good. Send our details: Our server name and description and hopcount of 0,
3098 // along with the sendpass from this block.
3099 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3100 // move to the next state, we are now waiting for THEM.
3101 this->LinkState = WAIT_AUTH_2;
3105 this->WriteLine("ERROR :Invalid credentials");
3106 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3110 void Split(const std::string &line, std::deque<std::string> &n)
3113 irc::tokenstream tokens(line);
3115 while ((param = tokens.GetToken()) != "")
3120 bool ProcessLine(std::string &line)
3122 std::deque<std::string> params;
3123 irc::string command;
3126 line = line.substr(0, line.find_first_of("\r\n"));
3131 Instance->Log(DEBUG,"IN: %s", line.c_str());
3133 this->Split(line.c_str(),params);
3135 if ((params[0][0] == ':') && (params.size() > 1))
3137 prefix = params[0].substr(1);
3141 command = params[0].c_str();
3144 switch (this->LinkState)
3149 // Waiting for SERVER command from remote server. Server initiating
3150 // the connection sends the first SERVER command, listening server
3151 // replies with theirs if its happy, then if the initiator is happy,
3152 // it starts to send its net sync, which starts the merge, otherwise
3153 // it sends an ERROR.
3154 if (command == "PASS")
3156 /* Silently ignored */
3158 else if (command == "SERVER")
3160 return this->Inbound_Server(params);
3162 else if (command == "ERROR")
3164 return this->Error(params);
3166 else if (command == "USER")
3168 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3171 else if (command == "CAPAB")
3173 return this->Capab(params);
3175 else if ((command == "U") || (command == "S"))
3177 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3182 std::string error("ERROR :Invalid command in negotiation phase: ");
3183 error.append(command.c_str());
3184 this->WriteLine(error);
3189 // Waiting for start of other side's netmerge to say they liked our
3191 if (command == "SERVER")
3193 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3197 else if ((command == "U") || (command == "S"))
3199 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3202 else if (command == "BURST")
3204 if (params.size() && Utils->EnableTimeSync)
3206 /* If a time stamp is provided, apply synchronization */
3208 time_t them = atoi(params[0].c_str());
3209 time_t us = Instance->Time(true);
3210 int delta = them - us;
3212 if ((params.size() == 2) && (params[1] == "FORCE"))
3215 if ((delta < -600) || (delta > 600))
3217 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));
3218 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3224 this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3226 else if (force || (us > them))
3228 this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3229 this->Instance->SetTimeDelta(them - us);
3230 // Send this new timestamp to any other servers
3231 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3235 // Override the timestamp
3236 this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3237 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3240 this->LinkState = CONNECTED;
3241 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3242 Utils->TreeRoot->AddChild(Node);
3244 params.push_back(InboundServerName);
3245 params.push_back("*");
3246 params.push_back("1");
3247 params.push_back(":"+InboundDescription);
3248 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3249 this->bursting = true;
3250 this->DoBurst(Node);
3252 else if (command == "ERROR")
3254 return this->Error(params);
3256 else if (command == "CAPAB")
3258 return this->Capab(params);
3263 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3267 if (command == "SERVER")
3269 // another server we connected to, which was in WAIT_AUTH_1 state,
3270 // has just sent us their credentials. If we get this far, theyre
3271 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3272 // if we're happy with this, we should send our netburst which
3273 // kickstarts the merge.
3274 return this->Outbound_Reply_Server(params);
3276 else if (command == "ERROR")
3278 return this->Error(params);
3282 // This is the 'authenticated' state, when all passwords
3283 // have been exchanged and anything past this point is taken
3288 std::string direction = prefix;
3289 userrec* t = this->Instance->FindNick(prefix);
3292 direction = t->server;
3294 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3295 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3297 if (route_back_again)
3298 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3303 * When there is activity on the socket, reset the ping counter so
3304 * that we're not wasting bandwidth pinging an active server.
3306 route_back_again->SetNextPingTime(time(NULL) + 60);
3307 route_back_again->SetPingFlag();
3310 if (command == "SVSMODE")
3312 /* Services expects us to implement
3313 * SVSMODE. In inspircd its the same as
3318 std::string target = "";
3319 /* Yes, know, this is a mess. Its reasonably fast though as we're
3320 * working with std::string here.
3322 if ((command == "NICK") && (params.size() > 1))
3324 return this->IntroduceClient(prefix,params);
3326 else if (command == "FJOIN")
3328 return this->ForceJoin(prefix,params);
3330 else if (command == "STATS")
3332 return this->Stats(prefix, params);
3334 else if (command == "MOTD")
3336 return this->Motd(prefix, params);
3338 else if (command == "ADMIN")
3340 return this->Admin(prefix, params);
3342 else if (command == "SERVER")
3344 return this->RemoteServer(prefix,params);
3346 else if (command == "ERROR")
3348 return this->Error(params);
3350 else if (command == "OPERTYPE")
3352 return this->OperType(prefix,params);
3354 else if (command == "FMODE")
3356 return this->ForceMode(prefix,params);
3358 else if (command == "KILL")
3360 return this->RemoteKill(prefix,params);
3362 else if (command == "FTOPIC")
3364 return this->ForceTopic(prefix,params);
3366 else if (command == "REHASH")
3368 return this->RemoteRehash(prefix,params);
3370 else if (command == "METADATA")
3372 return this->MetaData(prefix,params);
3374 else if (command == "REMSTATUS")
3376 return this->RemoveStatus(prefix,params);
3378 else if (command == "PING")
3381 * We just got a ping from a server that's bursting.
3382 * This can't be right, so set them to not bursting, and
3383 * apply their lines.
3387 this->bursting = false;
3388 Instance->Log(DEBUG,"Applying lines with mask %d...", Utils->lines_to_apply);
3389 Instance->XLines->apply_lines(Utils->lines_to_apply);
3390 Utils->lines_to_apply = 0;
3394 prefix = this->GetName();
3396 return this->LocalPing(prefix,params);
3398 else if (command == "PONG")
3401 * We just got a pong from a server that's bursting.
3402 * This can't be right, so set them to not bursting, and
3403 * apply their lines.
3407 this->bursting = false;
3408 Instance->Log(DEBUG,"Applying lines with mask %d...", Utils->lines_to_apply);
3409 Instance->XLines->apply_lines(Utils->lines_to_apply);
3410 Utils->lines_to_apply = 0;
3414 prefix = this->GetName();
3416 return this->LocalPong(prefix,params);
3418 else if (command == "VERSION")
3420 return this->ServerVersion(prefix,params);
3422 else if (command == "FHOST")
3424 return this->ChangeHost(prefix,params);
3426 else if (command == "FNAME")
3428 return this->ChangeName(prefix,params);
3430 else if (command == "ADDLINE")
3432 return this->AddLine(prefix,params);
3434 else if (command == "SVSNICK")
3438 prefix = this->GetName();
3440 return this->ForceNick(prefix,params);
3442 else if (command == "RSQUIT")
3444 return this->RemoteSquit(prefix, params);
3446 else if (command == "IDLE")
3448 return this->Whois(prefix,params);
3450 else if (command == "PUSH")
3452 return this->Push(prefix,params);
3454 else if (command == "TIMESET")
3456 return this->HandleSetTime(prefix, params);
3458 else if (command == "TIME")
3460 return this->Time(prefix,params);
3462 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3464 std::string sourceserv = this->myhost;
3465 if (params.size() == 3)
3467 userrec* user = this->Instance->FindNick(params[1]);
3468 chanrec* chan = this->Instance->FindChan(params[0]);
3471 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3472 /* Yikes, the channels gone! */
3476 if (this->InboundServerName != "")
3478 sourceserv = this->InboundServerName;
3480 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3482 else if (command == "SVSJOIN")
3486 prefix = this->GetName();
3488 return this->ServiceJoin(prefix,params);
3490 else if (command == "SQUIT")
3492 if (params.size() == 2)
3494 this->Squit(Utils->FindServer(params[0]),params[1]);
3498 else if (command == "OPERNOTICE")
3500 std::string sourceserv = this->myhost;
3502 if (this->InboundServerName != "")
3503 sourceserv = this->InboundServerName;
3505 if (params.size() >= 1)
3506 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3508 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3510 else if (command == "MODENOTICE")
3512 std::string sourceserv = this->myhost;
3513 if (this->InboundServerName != "")
3514 sourceserv = this->InboundServerName;
3515 if (params.size() >= 2)
3517 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3520 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3522 else if (command == "SNONOTICE")
3524 std::string sourceserv = this->myhost;
3525 if (this->InboundServerName != "")
3526 sourceserv = this->InboundServerName;
3527 if (params.size() >= 2)
3529 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3532 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3534 else if (command == "ENDBURST")
3536 this->bursting = false;
3537 Instance->Log(DEBUG,"Applying lines with mask %d...", Utils->lines_to_apply);
3538 Instance->XLines->apply_lines(Utils->lines_to_apply);
3539 Utils->lines_to_apply = 0;
3540 std::string sourceserv = this->myhost;
3541 if (this->InboundServerName != "")
3543 sourceserv = this->InboundServerName;
3545 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3547 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3548 rmode.Send(Instance);
3554 // not a special inter-server command.
3555 // Emulate the actual user doing the command,
3556 // this saves us having a huge ugly parser.
3557 userrec* who = this->Instance->FindNick(prefix);
3558 std::string sourceserv = this->myhost;
3559 if (this->InboundServerName != "")
3561 sourceserv = this->InboundServerName;
3563 if ((!who) && (command == "MODE"))
3565 if (Utils->IsServer(prefix))
3567 const char* modelist[127];
3568 for (size_t i = 0; i < params.size(); i++)
3569 modelist[i] = params[i].c_str();
3571 userrec* fake = new userrec(Instance);
3572 fake->SetFd(FD_MAGIC_NUMBER);
3574 this->Instance->SendMode(modelist, params.size(), fake);
3578 /* Hot potato! pass it on! */
3579 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3584 if ((command == "NICK") && (params.size() > 0))
3586 /* On nick messages, check that the nick doesnt
3587 * already exist here. If it does, kill their copy,
3590 userrec* x = this->Instance->FindNick(params[0]);
3591 if ((x) && (x != who))
3593 std::deque<std::string> p;
3594 p.push_back(params[0]);
3595 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3596 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3598 p.push_back(prefix);
3599 p.push_back("Nickname collision");
3600 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3601 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3602 userrec* y = this->Instance->FindNick(prefix);
3605 userrec::QuitUser(this->Instance,y,"Nickname collision");
3607 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3611 target = who->server;
3612 const char* strparams[127];
3613 for (unsigned int q = 0; q < params.size(); q++)
3615 strparams[q] = params[q].c_str();
3617 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3620 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3627 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3633 // its not a user. Its either a server, or somethings screwed up.
3634 if (Utils->IsServer(prefix))
3636 target = this->Instance->Config->ServerName;
3640 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3644 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3653 virtual std::string GetName()
3655 std::string sourceserv = this->myhost;
3656 if (this->InboundServerName != "")
3658 sourceserv = this->InboundServerName;
3663 virtual void OnTimeout()
3665 if (this->LinkState == CONNECTING)
3667 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3668 Link* MyLink = Utils->FindLink(myhost);
3670 Utils->DoFailOver(MyLink);
3674 virtual void OnClose()
3676 // Connection closed.
3677 // If the connection is fully up (state CONNECTED)
3678 // then propogate a netsplit to all peers.
3679 std::string quitserver = this->myhost;
3680 if (this->InboundServerName != "")
3682 quitserver = this->InboundServerName;
3684 TreeServer* s = Utils->FindServer(quitserver);
3687 Squit(s,"Remote host closed the connection");
3690 if (quitserver != "")
3691 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3694 virtual int OnIncomingConnection(int newsock, char* ip)
3696 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3697 * or discovering if this port is the server port, we don't allow connections from any
3698 * IPs for which we don't have a link block.
3702 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3705 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3706 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3711 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3717 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
3719 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3724 /** This class is used to resolve server hostnames during /connect and autoconnect.
3725 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3726 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3727 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3728 * will have an IP address which we can then use to continue our connection.
3730 class ServernameResolver : public Resolver
3733 /** A copy of the Link tag info for what we're connecting to.
3734 * We take a copy, rather than using a pointer, just in case the
3735 * admin takes the tag away and rehashes while the domain is resolving.
3738 SpanningTreeUtilities* Utils;
3740 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(Util)
3742 /* Nothing in here, folks */
3745 void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
3747 /* Initiate the connection, now that we have an IP to use.
3748 * Passing a hostname directly to InspSocket causes it to
3749 * just bail and set its FD to -1.
3751 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3752 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3755 if ((!MyLink.Hook.empty()) && (Utils->hooks.find(MyLink.Hook.c_str()) == Utils->hooks.end()))
3758 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str(),
3759 MyLink.Hook.empty() ? NULL : Utils->hooks[MyLink.Hook.c_str()]);
3760 if (newsocket->GetFd() > -1)
3766 /* Something barfed, show the opers */
3767 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3769 Utils->DoFailOver(&MyLink);
3774 void OnError(ResolverError e, const std::string &errormessage)
3777 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3778 Utils->DoFailOver(&MyLink);
3782 /** Handle resolving of server IPs for the cache
3784 class SecurityIPResolver : public Resolver
3788 SpanningTreeUtilities* Utils;
3790 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(U)
3794 void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
3796 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3797 Utils->ValidIPs.push_back(result);
3800 void OnError(ResolverError e, const std::string &errormessage)
3802 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3806 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3812 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3814 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
3816 /* Did we find any modules? */
3819 /* Yes, enumerate them all to find out the hook name */
3820 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
3822 /* Make a request to it for its name, its implementing
3823 * InspSocketHook so we know its safe to do this
3825 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
3826 /* Build a map of them */
3827 hooks[name.c_str()] = *m;
3828 hooknames.push_back(name);
3829 ServerInstance->Log(DEBUG, "Found InspSocketHook interface: '%s' -> '%08x'", name.c_str(), *m);
3833 this->ReadConfiguration(true);
3836 SpanningTreeUtilities::~SpanningTreeUtilities()
3838 for (unsigned int i = 0; i < Bindings.size(); i++)
3840 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3841 ServerInstance->SE->DelFd(Bindings[i]);
3842 Bindings[i]->Close();
3843 DELETE(Bindings[i]);
3845 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3846 while (TreeRoot->ChildCount())
3848 TreeServer* child_server = TreeRoot->GetChild(0);
3849 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3852 TreeSocket* sock = child_server->GetSocket();
3853 ServerInstance->SE->DelFd(sock);
3861 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
3863 if (list.find(server) == list.end())
3864 list[server] = server;
3867 /** returns a list of DIRECT servernames for a specific channel */
3868 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
3874 ulist = c->GetOppedUsers();
3877 ulist = c->GetHalfoppedUsers();
3880 ulist = c->GetVoicedUsers();
3883 ulist = c->GetUsers();
3886 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3888 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
3890 TreeServer* best = this->BestRouteTo(i->second->server);
3892 AddThisServer(best,list);
3898 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3901 TreeServer* omitroute = this->BestRouteTo(omit);
3902 if ((command == "NOTICE") || (command == "PRIVMSG"))
3904 if (params.size() >= 2)
3907 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3910 params[0] = params[0].substr(1, params[0].length()-1);
3912 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3914 // special routing for private messages/notices
3915 userrec* d = ServerInstance->FindNick(params[0]);
3918 std::deque<std::string> par;
3919 par.push_back(params[0]);
3920 par.push_back(":"+params[1]);
3921 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3925 else if (*(params[0].c_str()) == '$')
3927 std::deque<std::string> par;
3928 par.push_back(params[0]);
3929 par.push_back(":"+params[1]);
3930 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3935 chanrec* c = ServerInstance->FindChan(params[0]);
3936 userrec* u = ServerInstance->FindNick(prefix);
3940 TreeServerList list;
3941 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
3942 GetListOfServersForChannel(c,list,pfx,elist);
3944 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
3946 TreeSocket* Sock = i->second->GetSocket();
3947 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
3949 Sock->WriteLine(data);
3957 unsigned int items =this->TreeRoot->ChildCount();
3958 for (unsigned int x = 0; x < items; x++)
3960 TreeServer* Route = this->TreeRoot->GetChild(x);
3961 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3963 TreeSocket* Sock = Route->GetSocket();
3965 Sock->WriteLine(data);
3971 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
3973 TreeServer* omitroute = this->BestRouteTo(omit);
3974 std::string FullLine = ":" + prefix + " " + command;
3975 unsigned int words = params.size();
3976 for (unsigned int x = 0; x < words; x++)
3978 FullLine = FullLine + " " + params[x];
3980 unsigned int items = this->TreeRoot->ChildCount();
3981 for (unsigned int x = 0; x < items; x++)
3983 TreeServer* Route = this->TreeRoot->GetChild(x);
3984 // Send the line IF:
3985 // The route has a socket (its a direct connection)
3986 // The route isnt the one to be omitted
3987 // The route isnt the path to the one to be omitted
3988 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3990 TreeSocket* Sock = Route->GetSocket();
3992 Sock->WriteLine(FullLine);
3998 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
4000 std::string FullLine = ":" + prefix + " " + command;
4001 unsigned int words = params.size();
4002 for (unsigned int x = 0; x < words; x++)
4004 FullLine = FullLine + " " + params[x];
4006 unsigned int items = this->TreeRoot->ChildCount();
4007 for (unsigned int x = 0; x < items; x++)
4009 TreeServer* Route = this->TreeRoot->GetChild(x);
4010 if (Route && Route->GetSocket())
4012 TreeSocket* Sock = Route->GetSocket();
4014 Sock->WriteLine(FullLine);
4020 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
4022 std::string spfx = prefix;
4023 std::string scmd = command;
4024 return this->DoOneToMany(spfx, scmd, params);
4027 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
4029 std::string spfx = prefix;
4030 std::string scmd = command;
4031 return this->DoOneToAllButSender(spfx, scmd, params, omit);
4034 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
4036 TreeServer* Route = this->BestRouteTo(target);
4039 std::string FullLine = ":" + prefix + " " + command;
4040 unsigned int words = params.size();
4041 for (unsigned int x = 0; x < words; x++)
4043 FullLine = FullLine + " " + params[x];
4045 if (Route && Route->GetSocket())
4047 TreeSocket* Sock = Route->GetSocket();
4049 Sock->WriteLine(FullLine);
4059 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
4061 ConfigReader* Conf = new ConfigReader(ServerInstance);
4064 for (int j =0; j < Conf->Enumerate("bind"); j++)
4066 std::string Type = Conf->ReadValue("bind","type",j);
4067 std::string IP = Conf->ReadValue("bind","address",j);
4068 std::string Port = Conf->ReadValue("bind","port",j);
4069 std::string transport = Conf->ReadValue("bind","transport",j);
4070 if (Type == "servers")
4072 irc::portparser portrange(Port, false);
4074 while ((portno = portrange.GetToken()))
4076 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
4080 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
4082 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for port %s:%s - maybe you forgot to load it BEFORE m_spanningtree in your config file? - Skipping this port binding",
4083 transport.c_str(), IP.c_str(), Port.c_str());
4087 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
4088 if (listener->GetState() == I_LISTENING)
4090 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
4091 Bindings.push_back(listener);
4095 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
4099 ServerInstance->Log(DEBUG,"Done with this binding");
4104 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
4105 HideULines = Conf->ReadFlag("options","hideulines",0);
4106 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
4107 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
4110 for (int j =0; j < Conf->Enumerate("link"); j++)
4113 std::string Allow = Conf->ReadValue("link","allowmask",j);
4114 L.Name = (Conf->ReadValue("link","name",j)).c_str();
4115 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
4116 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
4117 L.Port = Conf->ReadInteger("link","port",j,true);
4118 L.SendPass = Conf->ReadValue("link","sendpass",j);
4119 L.RecvPass = Conf->ReadValue("link","recvpass",j);
4120 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
4121 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
4122 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
4123 L.Hook = Conf->ReadValue("link", "transport", j);
4125 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
4127 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for link '%s' - maybe you forgot to load it BEFORE m_spanningtree in your config file? Skipping <link> tag completely.",
4128 L.Hook.c_str(), L.Name.c_str());
4133 L.NextConnectTime = time(NULL) + L.AutoConnect;
4134 /* Bugfix by brain, do not allow people to enter bad configurations */
4135 if (L.Name != ServerInstance->Config->ServerName)
4137 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
4139 ValidIPs.push_back(L.IPAddr);
4142 ValidIPs.push_back(Allow);
4144 /* Needs resolving */
4146 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
4151 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached);
4152 ServerInstance->AddResolver(sr, cached);
4154 catch (ModuleException& e)
4156 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4160 LinkBlocks.push_back(L);
4161 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4167 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4169 else if (L.RecvPass == "")
4171 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4173 else if (L.SendPass == "")
4175 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4177 else if (L.Name == "")
4179 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4183 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4189 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4195 /** To create a timer which recurs every second, we inherit from InspTimer.
4196 * InspTimer is only one-shot however, so at the end of each Tick() we simply
4197 * insert another of ourselves into the pending queue :)
4199 class TimeSyncTimer : public InspTimer
4203 ModuleSpanningTree *Module;
4205 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4206 virtual void Tick(time_t TIME);
4209 HandshakeTimer::HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u) : InspTimer(1, time(NULL)), Instance(Inst), sock(s), lnk(l), Utils(u)
4211 thefd = sock->GetFd();
4214 void HandshakeTimer::Tick(time_t TIME)
4216 if (Instance->SE->GetRef(thefd) == sock)
4218 if (sock->GetHook() && InspSocketHSCompleteRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send())
4220 Instance->Log(DEBUG,"Handshake timer activated, sending SERVER and/or CAPAB");
4221 InspSocketAttachCertRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send();
4222 sock->SendCapabilities();
4223 if (sock->GetLinkState() == CONNECTING)
4225 sock->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+lnk->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
4230 Instance->Timers->AddTimer(new HandshakeTimer(Instance, sock, lnk, Utils));
4235 class ModuleSpanningTree : public Module
4239 unsigned int max_local;
4240 unsigned int max_global;
4241 cmd_rconnect* command_rconnect;
4242 SpanningTreeUtilities* Utils;
4245 TimeSyncTimer *SyncTimer;
4247 ModuleSpanningTree(InspIRCd* Me)
4248 : Module::Module(Me), max_local(0), max_global(0)
4250 ServerInstance->UseInterface("InspSocketHook");
4252 Utils = new SpanningTreeUtilities(Me, this);
4254 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4255 ServerInstance->AddCommand(command_rconnect);
4257 if (Utils->EnableTimeSync)
4259 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4260 ServerInstance->Timers->AddTimer(SyncTimer);
4266 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4268 std::string Parent = Utils->TreeRoot->GetName();
4269 if (Current->GetParent())
4271 Parent = Current->GetParent()->GetName();
4273 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4275 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4279 ShowLinks(Current->GetChild(q),user,hops+1);
4284 ShowLinks(Current->GetChild(q),user,hops+1);
4287 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4288 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4290 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());
4293 int CountLocalServs()
4295 return Utils->TreeRoot->ChildCount();
4300 return Utils->serverlist.size();
4303 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4305 ShowLinks(Utils->TreeRoot,user,0);
4306 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4310 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4312 unsigned int n_users = ServerInstance->UserCount();
4314 /* Only update these when someone wants to see them, more efficient */
4315 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4316 max_local = ServerInstance->LocalUserCount();
4317 if (n_users > max_global)
4318 max_global = n_users;
4320 unsigned int ulined_count = 0;
4321 unsigned int ulined_local_count = 0;
4323 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4324 * locally and globally (locally means directly connected to us)
4326 if ((Utils->HideULines) && (!*user->oper))
4328 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4330 if (ServerInstance->ULine(q->second->GetName().c_str()))
4333 if (q->second->GetParent() == Utils->TreeRoot)
4334 ulined_local_count++;
4339 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());
4340 if (ServerInstance->OperCount())
4341 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4342 if (ServerInstance->UnregisteredUserCount())
4343 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4344 if (ServerInstance->ChannelCount())
4345 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4346 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());
4347 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4348 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4352 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4354 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4358 for (int t = 0; t < depth; t++)
4360 matrix[line][t] = ' ';
4363 // For Aligning, we need to work out exactly how deep this thing is, and produce
4364 // a 'Spacer' String to compensate.
4367 memset(spacer,' ',40);
4368 if ((40 - Current->GetName().length() - depth) > 1) {
4369 spacer[40 - Current->GetName().length() - depth] = '\0';
4378 if (ServerInstance->clientlist->size() == 0) {
4379 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4384 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist->size()) * 100;
4386 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4387 totusers += Current->GetUserCount();
4389 strlcpy(&matrix[line][depth],text,80);
4391 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4393 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4397 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4402 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4408 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4412 /* Remote MOTD, the server is within the 1st parameter */
4413 std::deque<std::string> params;
4414 params.push_back(parameters[0]);
4416 /* Send it out remotely, generate no reply yet */
4417 TreeServer* s = Utils->FindServerMask(parameters[0]);
4420 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4424 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4431 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4435 /* Remote ADMIN, the server is within the 1st parameter */
4436 std::deque<std::string> params;
4437 params.push_back(parameters[0]);
4439 /* Send it out remotely, generate no reply yet */
4440 TreeServer* s = Utils->FindServerMask(parameters[0]);
4443 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4447 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4454 int HandleStats(const char** parameters, int pcnt, userrec* user)
4458 /* Remote STATS, the server is within the 2nd parameter */
4459 std::deque<std::string> params;
4460 params.push_back(parameters[0]);
4461 params.push_back(parameters[1]);
4462 /* Send it out remotely, generate no reply yet */
4463 TreeServer* s = Utils->FindServerMask(parameters[1]);
4466 params[1] = s->GetName();
4467 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4471 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4478 // Ok, prepare to be confused.
4479 // After much mulling over how to approach this, it struck me that
4480 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4481 // keeping track of a ton of ascii characters, and line by line
4482 // under recursion working out where to place them using multiplications
4483 // and divisons, we instead render the map onto a backplane of characters
4484 // (a character matrix), then draw the branches as a series of "L" shapes
4485 // from the nodes. This is not only friendlier on CPU it uses less stack.
4487 void HandleMap(const char** parameters, int pcnt, userrec* user)
4489 // This array represents a virtual screen which we will
4490 // "scratch" draw to, as the console device of an irc
4491 // client does not provide for a proper terminal.
4493 float totservers = 0;
4494 char matrix[128][80];
4495 for (unsigned int t = 0; t < 128; t++)
4497 matrix[t][0] = '\0';
4500 // The only recursive bit is called here.
4501 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4502 // Process each line one by one. The algorithm has a limit of
4503 // 128 servers (which is far more than a spanning tree should have
4504 // anyway, so we're ok). This limit can be raised simply by making
4505 // the character matrix deeper, 128 rows taking 10k of memory.
4506 for (int l = 1; l < line; l++)
4508 // scan across the line looking for the start of the
4509 // servername (the recursive part of the algorithm has placed
4510 // the servers at indented positions depending on what they
4512 int first_nonspace = 0;
4513 while (matrix[l][first_nonspace] == ' ')
4518 // Draw the `- (corner) section: this may be overwritten by
4519 // another L shape passing along the same vertical pane, becoming
4520 // a |- (branch) section instead.
4521 matrix[l][first_nonspace] = '-';
4522 matrix[l][first_nonspace-1] = '`';
4524 // Draw upwards until we hit the parent server, causing possibly
4525 // other corners (`-) to become branches (|-)
4526 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4528 matrix[l2][first_nonspace-1] = '|';
4532 // dump the whole lot to the user. This is the easy bit, honest.
4533 for (int t = 0; t < line; t++)
4535 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4537 float avg_users = totusers / totservers;
4538 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);
4539 user->WriteServ("007 %s :End of /MAP",user->nick);
4543 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4545 TreeServer* s = Utils->FindServerMask(parameters[0]);
4548 if (s == Utils->TreeRoot)
4550 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4553 TreeSocket* sock = s->GetSocket();
4556 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4557 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4558 sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost());
4559 ServerInstance->SE->DelFd(sock);
4566 std::deque<std::string> params;
4567 params.push_back(parameters[0]);
4568 params.push_back(std::string(":Server quit by ") + user->GetFullRealHost());
4569 Utils->DoOneToOne(user->nick, "RSQUIT", params, parameters[0]);
4574 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4579 int HandleTime(const char** parameters, int pcnt, userrec* user)
4581 if ((IS_LOCAL(user)) && (pcnt))
4583 TreeServer* found = Utils->FindServerMask(parameters[0]);
4586 // we dont' override for local server
4587 if (found == Utils->TreeRoot)
4590 std::deque<std::string> params;
4591 params.push_back(found->GetName());
4592 params.push_back(user->nick);
4593 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4597 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4603 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4605 if ((IS_LOCAL(user)) && (pcnt > 1))
4607 userrec* remote = ServerInstance->FindNick(parameters[1]);
4608 if ((remote) && (remote->GetFd() < 0))
4610 std::deque<std::string> params;
4611 params.push_back(parameters[1]);
4612 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4617 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4618 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4625 void DoPingChecks(time_t curtime)
4627 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4629 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4630 TreeSocket* sock = serv->GetSocket();
4633 if (curtime >= serv->NextPingTime())
4635 if (serv->AnsweredLastPing())
4637 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4638 serv->SetNextPingTime(curtime + 60);
4642 // they didnt answer, boot them
4643 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4644 sock->Squit(serv,"Ping timeout");
4645 ServerInstance->SE->DelFd(sock);
4655 void ConnectServer(Link* x)
4659 /* Do we already have an IP? If so, no need to resolve it. */
4660 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4662 /* Gave a hook, but it wasnt one we know */
4663 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
4666 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()]);
4667 if (newsocket->GetFd() > -1)
4669 /* Handled automatically on success */
4673 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4675 Utils->DoFailOver(x);
4683 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached);
4684 ServerInstance->AddResolver(snr, cached);
4686 catch (ModuleException& e)
4688 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4689 Utils->DoFailOver(x);
4694 void AutoConnectServers(time_t curtime)
4696 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4698 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4700 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4701 x->NextConnectTime = curtime + x->AutoConnect;
4702 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4703 if (x->FailOver.length())
4705 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4708 /* The failover for this server is currently a member of the network.
4709 * The failover probably succeeded, where the main link did not.
4710 * Don't try the main link until the failover is gone again.
4717 // an autoconnected server is not connected. Check if its time to connect it
4718 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4719 this->ConnectServer(&(*x));
4725 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4727 // we've already checked if pcnt > 0, so this is safe
4728 TreeServer* found = Utils->FindServerMask(parameters[0]);
4731 std::string Version = found->GetVersion();
4732 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4733 if (found == Utils->TreeRoot)
4735 ServerInstance->Config->Send005(user);
4740 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4745 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4747 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4749 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4751 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4754 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);
4755 ConnectServer(&(*x));
4760 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());
4765 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4769 void BroadcastTimeSync()
4771 std::deque<std::string> params;
4772 params.push_back(ConvToStr(ServerInstance->Time(true)));
4773 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4776 virtual int OnStats(char statschar, userrec* user, string_list &results)
4778 if ((statschar == 'c') || (statschar == 'n'))
4780 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4782 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].Hook.empty() ? "plaintext" : Utils->LinkBlocks[i].Hook)+" "+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4783 if (statschar == 'c')
4784 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4786 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4787 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);
4793 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4795 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4799 if (command == "CONNECT")
4801 return this->HandleConnect(parameters,pcnt,user);
4803 else if (command == "STATS")
4805 return this->HandleStats(parameters,pcnt,user);
4807 else if (command == "MOTD")
4809 return this->HandleMotd(parameters,pcnt,user);
4811 else if (command == "ADMIN")
4813 return this->HandleAdmin(parameters,pcnt,user);
4815 else if (command == "SQUIT")
4817 return this->HandleSquit(parameters,pcnt,user);
4819 else if (command == "MAP")
4821 this->HandleMap(parameters,pcnt,user);
4824 else if ((command == "TIME") && (pcnt > 0))
4826 return this->HandleTime(parameters,pcnt,user);
4828 else if (command == "LUSERS")
4830 this->HandleLusers(parameters,pcnt,user);
4833 else if (command == "LINKS")
4835 this->HandleLinks(parameters,pcnt,user);
4838 else if (command == "WHOIS")
4843 return this->HandleRemoteWhois(parameters,pcnt,user);
4846 else if ((command == "VERSION") && (pcnt > 0))
4848 this->HandleVersion(parameters,pcnt,user);
4855 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4857 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4859 // this bit of code cleverly routes all module commands
4860 // to all remote severs *automatically* so that modules
4861 // can just handle commands locally, without having
4862 // to have any special provision in place for remote
4863 // commands and linking protocols.
4864 std::deque<std::string> params;
4866 for (int j = 0; j < pcnt; j++)
4868 if (strchr(parameters[j],' '))
4870 params.push_back(":" + std::string(parameters[j]));
4874 params.push_back(std::string(parameters[j]));
4877 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4878 Utils->DoOneToMany(user->nick,command,params);
4882 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4884 TreeServer* s = Utils->FindServer(servername);
4887 description = s->GetDesc();
4891 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4893 if (IS_LOCAL(source))
4895 std::deque<std::string> params;
4896 params.push_back(dest->nick);
4897 params.push_back(channel->name);
4898 Utils->DoOneToMany(source->nick,"INVITE",params);
4902 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4904 std::deque<std::string> params;
4905 params.push_back(chan->name);
4906 params.push_back(":"+topic);
4907 Utils->DoOneToMany(user->nick,"TOPIC",params);
4910 virtual void OnWallops(userrec* user, const std::string &text)
4914 std::deque<std::string> params;
4915 params.push_back(":"+text);
4916 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4920 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4922 if (target_type == TYPE_USER)
4924 userrec* d = (userrec*)dest;
4925 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4927 std::deque<std::string> params;
4929 params.push_back(d->nick);
4930 params.push_back(":"+text);
4931 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4934 else if (target_type == TYPE_CHANNEL)
4938 chanrec *c = (chanrec*)dest;
4941 std::string cname = c->name;
4943 cname = status + cname;
4944 TreeServerList list;
4945 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4947 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
4949 TreeSocket* Sock = i->second->GetSocket();
4951 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4956 else if (target_type == TYPE_SERVER)
4960 char* target = (char*)dest;
4961 std::deque<std::string> par;
4962 par.push_back(target);
4963 par.push_back(":"+text);
4964 Utils->DoOneToMany(user->nick,"NOTICE",par);
4969 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4971 if (target_type == TYPE_USER)
4973 // route private messages which are targetted at clients only to the server
4974 // which needs to receive them
4975 userrec* d = (userrec*)dest;
4976 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4978 std::deque<std::string> params;
4980 params.push_back(d->nick);
4981 params.push_back(":"+text);
4982 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4985 else if (target_type == TYPE_CHANNEL)
4989 chanrec *c = (chanrec*)dest;
4992 std::string cname = c->name;
4994 cname = status + cname;
4995 TreeServerList list;
4996 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4998 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
5000 TreeSocket* Sock = i->second->GetSocket();
5002 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
5007 else if (target_type == TYPE_SERVER)
5011 char* target = (char*)dest;
5012 std::deque<std::string> par;
5013 par.push_back(target);
5014 par.push_back(":"+text);
5015 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
5020 virtual void OnBackgroundTimer(time_t curtime)
5022 AutoConnectServers(curtime);
5023 DoPingChecks(curtime);
5026 virtual void OnUserJoin(userrec* user, chanrec* channel)
5028 // Only do this for local users
5031 if (channel->GetUserCounter() == 1)
5033 std::deque<std::string> params;
5034 // set up their permissions and the channel TS with FJOIN.
5035 // All users are FJOINed now, because a module may specify
5036 // new joining permissions for the user.
5037 params.push_back(channel->name);
5038 params.push_back(ConvToStr(channel->age));
5039 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
5040 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
5041 /* First user in, sync the modes for the channel */
5043 /* This is safe, all inspircd servers default to +nt */
5044 params.push_back("+nt");
5045 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
5049 std::deque<std::string> params;
5050 params.push_back(channel->name);
5051 params.push_back(ConvToStr(channel->age));
5052 Utils->DoOneToMany(user->nick,"JOIN",params);
5057 virtual void OnChangeHost(userrec* user, const std::string &newhost)
5059 // only occurs for local clients
5060 if (user->registered != REG_ALL)
5062 std::deque<std::string> params;
5063 params.push_back(newhost);
5064 Utils->DoOneToMany(user->nick,"FHOST",params);
5067 virtual void OnChangeName(userrec* user, const std::string &gecos)
5069 // only occurs for local clients
5070 if (user->registered != REG_ALL)
5072 std::deque<std::string> params;
5073 params.push_back(gecos);
5074 Utils->DoOneToMany(user->nick,"FNAME",params);
5077 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
5081 std::deque<std::string> params;
5082 params.push_back(channel->name);
5083 if (partmessage != "")
5084 params.push_back(":"+partmessage);
5085 Utils->DoOneToMany(user->nick,"PART",params);
5089 virtual void OnUserConnect(userrec* user)
5091 char agestr[MAXBUF];
5094 std::deque<std::string> params;
5095 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
5096 params.push_back(agestr);
5097 params.push_back(user->nick);
5098 params.push_back(user->host);
5099 params.push_back(user->dhost);
5100 params.push_back(user->ident);
5101 params.push_back("+"+std::string(user->FormatModes()));
5102 params.push_back(user->GetIPString());
5103 params.push_back(":"+std::string(user->fullname));
5104 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
5106 // User is Local, change needs to be reflected!
5107 TreeServer* SourceServer = Utils->FindServer(user->server);
5110 SourceServer->AddUserCount();
5116 virtual void OnUserQuit(userrec* user, const std::string &reason)
5118 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5120 std::deque<std::string> params;
5121 params.push_back(":"+reason);
5122 Utils->DoOneToMany(user->nick,"QUIT",params);
5124 // Regardless, We need to modify the user Counts..
5125 TreeServer* SourceServer = Utils->FindServer(user->server);
5128 SourceServer->DelUserCount();
5133 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
5137 std::deque<std::string> params;
5138 params.push_back(user->nick);
5139 Utils->DoOneToMany(oldnick,"NICK",params);
5143 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
5145 if ((source) && (IS_LOCAL(source)))
5147 std::deque<std::string> params;
5148 params.push_back(chan->name);
5149 params.push_back(user->nick);
5150 params.push_back(":"+reason);
5151 Utils->DoOneToMany(source->nick,"KICK",params);
5155 std::deque<std::string> params;
5156 params.push_back(chan->name);
5157 params.push_back(user->nick);
5158 params.push_back(":"+reason);
5159 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
5163 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
5165 std::deque<std::string> params;
5166 params.push_back(dest->nick);
5167 params.push_back(":"+reason);
5168 Utils->DoOneToMany(source->nick,"KILL",params);
5171 virtual void OnRehash(userrec* user, const std::string ¶meter)
5173 if (parameter != "")
5175 std::deque<std::string> params;
5176 params.push_back(parameter);
5177 Utils->DoOneToMany(user ? user->nick : ServerInstance->Config->ServerName, "REHASH", params);
5179 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5181 ServerInstance->WriteOpers("*** Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName);
5182 ServerInstance->RehashServer();
5185 Utils->ReadConfiguration(false);
5186 InitializeDisabledCommands(ServerInstance->Config->DisabledCommands, ServerInstance);
5189 // note: the protocol does not allow direct umode +o except
5190 // via NICK with 8 params. sending OPERTYPE infers +o modechange
5192 virtual void OnOper(userrec* user, const std::string &opertype)
5196 std::deque<std::string> params;
5197 params.push_back(opertype);
5198 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5202 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5206 /* Server-set lines */
5208 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5209 (unsigned long)duration, reason.c_str());
5210 std::deque<std::string> params;
5211 params.push_back(data);
5212 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5216 if (IS_LOCAL(source))
5219 snprintf(type,8,"%cLINE",linetype);
5220 std::string stype = type;
5223 char sduration[MAXBUF];
5224 snprintf(sduration,MAXBUF,"%ld",duration);
5225 std::deque<std::string> params;
5226 params.push_back(host);
5227 params.push_back(sduration);
5228 params.push_back(":"+reason);
5229 Utils->DoOneToMany(source->nick,stype,params);
5233 std::deque<std::string> params;
5234 params.push_back(host);
5235 Utils->DoOneToMany(source->nick,stype,params);
5241 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5243 OnLine(source,hostmask,true,'G',duration,reason);
5246 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5248 OnLine(source,ipmask,true,'Z',duration,reason);
5251 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5253 OnLine(source,nickmask,true,'Q',duration,reason);
5256 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5258 OnLine(source,hostmask,true,'E',duration,reason);
5261 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5263 OnLine(source,hostmask,false,'G',0,"");
5266 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5268 OnLine(source,ipmask,false,'Z',0,"");
5271 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5273 OnLine(source,nickmask,false,'Q',0,"");
5276 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5278 OnLine(source,hostmask,false,'E',0,"");
5281 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5283 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5285 if (target_type == TYPE_USER)
5287 userrec* u = (userrec*)dest;
5288 std::deque<std::string> params;
5289 params.push_back(u->nick);
5290 params.push_back(text);
5291 Utils->DoOneToMany(user->nick,"MODE",params);
5295 chanrec* c = (chanrec*)dest;
5296 std::deque<std::string> params;
5297 params.push_back(c->name);
5298 params.push_back(text);
5299 Utils->DoOneToMany(user->nick,"MODE",params);
5304 virtual void OnSetAway(userrec* user)
5308 std::deque<std::string> params;
5309 params.push_back(":"+std::string(user->awaymsg));
5310 Utils->DoOneToMany(user->nick,"AWAY",params);
5314 virtual void OnCancelAway(userrec* user)
5318 std::deque<std::string> params;
5320 Utils->DoOneToMany(user->nick,"AWAY",params);
5324 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5326 TreeSocket* s = (TreeSocket*)opaque;
5329 if (target_type == TYPE_USER)
5331 userrec* u = (userrec*)target;
5332 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5336 chanrec* c = (chanrec*)target;
5337 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5342 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5344 TreeSocket* s = (TreeSocket*)opaque;
5347 if (target_type == TYPE_USER)
5349 userrec* u = (userrec*)target;
5350 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5352 else if (target_type == TYPE_CHANNEL)
5354 chanrec* c = (chanrec*)target;
5355 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5358 if (target_type == TYPE_OTHER)
5360 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5364 virtual void OnEvent(Event* event)
5366 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5368 if (event->GetEventID() == "send_metadata")
5370 if (params->size() < 3)
5372 (*params)[2] = ":" + (*params)[2];
5373 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5375 else if (event->GetEventID() == "send_topic")
5377 if (params->size() < 2)
5379 (*params)[1] = ":" + (*params)[1];
5380 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5381 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5382 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5384 else if (event->GetEventID() == "send_mode")
5386 if (params->size() < 2)
5388 // Insert the TS value of the object, either userrec or chanrec
5390 userrec* a = ServerInstance->FindNick((*params)[0]);
5397 chanrec* a = ServerInstance->FindChan((*params)[0]);
5403 params->insert(params->begin() + 1,ConvToStr(ourTS));
5404 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5406 else if (event->GetEventID() == "send_mode_explicit")
5408 if (params->size() < 2)
5410 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5412 else if (event->GetEventID() == "send_opers")
5414 if (params->size() < 1)
5416 (*params)[0] = ":" + (*params)[0];
5417 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5419 else if (event->GetEventID() == "send_modeset")
5421 if (params->size() < 2)
5423 (*params)[1] = ":" + (*params)[1];
5424 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5426 else if (event->GetEventID() == "send_snoset")
5428 if (params->size() < 2)
5430 (*params)[1] = ":" + (*params)[1];
5431 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5433 else if (event->GetEventID() == "send_push")
5435 if (params->size() < 2)
5438 userrec *a = ServerInstance->FindNick((*params)[0]);
5443 (*params)[1] = ":" + (*params)[1];
5444 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5448 virtual ~ModuleSpanningTree()
5450 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5451 /* This will also free the listeners */
5454 ServerInstance->Timers->DelTimer(SyncTimer);
5456 ServerInstance->DoneWithInterface("InspSocketHook");
5459 virtual Version GetVersion()
5461 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5464 void Implements(char* List)
5466 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5467 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5468 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5469 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5470 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5471 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5472 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5475 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5476 * so that any activity it sees is FINAL, e.g. we arent going to send out
5477 * a NICK message before m_cloaking has finished putting the +x on the user,
5479 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5480 * the module call queue.
5482 Priority Prioritize()
5484 return PRIORITY_LAST;
5488 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time(), true), Instance(Inst), Module(Mod)
5492 void TimeSyncTimer::Tick(time_t TIME)
5494 Module->BroadcastTimeSync();
5497 void SpanningTreeUtilities::DoFailOver(Link* x)
5499 if (x->FailOver.length())
5501 if (x->FailOver == x->Name)
5503 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());
5506 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5509 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5510 Creator->ConnectServer(TryThisOne);
5514 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5519 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5521 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5523 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5531 class ModuleSpanningTreeFactory : public ModuleFactory
5534 ModuleSpanningTreeFactory()
5538 ~ModuleSpanningTreeFactory()
5542 virtual Module * CreateModule(InspIRCd* Me)
5544 return new ModuleSpanningTree(Me);
5550 extern "C" void * init_module( void )
5552 return new ModuleSpanningTreeFactory;