1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
19 #include "configreader.h"
23 #include "commands/cmd_whois.h"
24 #include "commands/cmd_stats.h"
32 /** If you make a change which breaks the protocol, increment this.
33 * If you completely change the protocol, completely change the number.
35 * IMPORTANT: If you make changes, document your changes here, without fail:
36 * http://www.inspircd.org/wiki/List_of_protocol_changes_between_versions
38 * Failure to document your protocol changes will result in a painfully
39 * painful death by pain. You have been warned.
41 const long ProtocolVersion = 1102;
44 * The server list in InspIRCd is maintained as two structures
45 * which hold the data in different ways. Most of the time, we
46 * want to very quicky obtain three pieces of information:
48 * (1) The information on a server
49 * (2) The information on the server we must send data through
50 * to actually REACH the server we're after
51 * (3) Potentially, the child/parent objects of this server
53 * The InspIRCd spanning protocol provides easy access to these
54 * by storing the data firstly in a recursive structure, where
55 * each item references its parent item, and a dynamic list
56 * of child items, and another structure which stores the items
57 * hashed, linearly. This means that if we want to find a server
58 * by name quickly, we can look it up in the hash, avoiding
59 * any O(n) lookups. If however, during a split or sync, we want
60 * to apply an operation to a server, and any of its child objects
61 * we can resort to recursion to walk the tree structure.
62 * Any socket can have one of five states at any one time.
63 * The LISTENER state indicates a socket which is listening
64 * for connections. It cannot receive data itself, only incoming
66 * The CONNECTING state indicates an outbound socket which is
67 * waiting to be writeable.
68 * The WAIT_AUTH_1 state indicates the socket is outbound and
69 * has successfully connected, but has not yet sent and received
71 * The WAIT_AUTH_2 state indicates that the socket is inbound
72 * (allocated by a LISTENER) but has not yet sent and received
74 * The CONNECTED state represents a fully authorized, fully
77 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
79 /* Foward declarations */
83 class ModuleSpanningTree;
85 /* This hash_map holds the hash equivalent of the server
86 * tree, used for rapid linear lookups.
88 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
90 typedef std::map<TreeServer*,TreeServer*> TreeServerList;
92 /** A group of modules that implement InspSocketHook
93 * that we can use to hook our server to server connections.
95 typedef std::map<irc::string, Module*> hookmodules;
97 /** The Link class might as well be a struct,
98 * but this is C++ and we don't believe in structs (!).
99 * It holds the entire information of one <link>
100 * tag from the main config file. We maintain a list
101 * of them, and populate the list on rehash/load.
103 class Link : public classbase
109 std::string SendPass;
110 std::string RecvPass;
111 unsigned long AutoConnect;
112 time_t NextConnectTime;
113 std::string EncryptionKey;
114 bool HiddenFromStats;
115 std::string FailOver;
120 /** Contains helper functions and variables for this module,
121 * and keeps them out of the global namespace
123 class SpanningTreeUtilities
128 InspIRCd* ServerInstance;
132 ModuleSpanningTree* Creator;
133 /** Flatten links and /MAP for non-opers
136 /** Hide U-Lined servers in /MAP and /LINKS
139 /** Announce TS changes to channels on merge
141 bool AnnounceTSChange;
142 /** Synchronize timestamps between servers
145 /** Socket bindings for listening sockets
147 std::vector<TreeSocket*> Bindings;
148 /** This variable represents the root of the server tree
150 TreeServer *TreeRoot;
151 /** IPs allowed to link to us
153 std::vector<std::string> ValidIPs;
154 /** Hash of currently connected servers by name
156 server_hash serverlist;
157 /** Holds the data from the <link> tags in the conf
159 std::vector<Link> LinkBlocks;
162 std::vector<std::string> hooknames;
164 /** Initialise utility class
166 SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator);
167 /** Destroy class and free listeners etc
169 ~SpanningTreeUtilities();
170 /** Send a message from this server to one other local or remote
172 bool DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target);
173 /** Send a message from this server to all but one other, local or remote
175 bool DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit);
176 /** Send a message from this server to all but one other, local or remote
178 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit);
179 /** Send a message from this server to all others
181 bool DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms);
182 /** Send a message from this server to all others
184 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms);
185 /** 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)
187 bool DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms);
188 /** Read the spanningtree module's tags from the config file
190 void ReadConfiguration(bool rebind);
191 /** Add a server to the server list for GetListOfServersForChannel
193 void AddThisServer(TreeServer* server, TreeServerList &list);
194 /** Compile a list of servers which contain members of channel c
196 void GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list);
197 /** Find a server by name
199 TreeServer* FindServer(const std::string &ServerName);
200 /** Find a route to a server by name
202 TreeServer* BestRouteTo(const std::string &ServerName);
203 /** Find a server by glob mask
205 TreeServer* FindServerMask(const std::string &ServerName);
206 /** Returns true if this is a server name we recognise
208 bool IsServer(const std::string &ServerName);
209 /** Attempt to connect to the failover link of link x
211 void DoFailOver(Link* x);
212 /** Find a link tag from a server name
214 Link* FindLink(const std::string& name);
218 /** Each server in the tree is represented by one class of
219 * type TreeServer. A locally connected TreeServer can
220 * have a class of type TreeSocket associated with it, for
221 * remote servers, the TreeSocket entry will be NULL.
222 * Each server also maintains a pointer to its parent
223 * (NULL if this server is ours, at the top of the tree)
224 * and a pointer to its "Route" (see the comments in the
225 * constructors below), and also a dynamic list of pointers
226 * to its children which can be iterated recursively
227 * if required. Creating or deleting objects of type
228 i* TreeServer automatically maintains the hash_map of
229 * TreeServer items, deleting and inserting them as they
230 * are created and destroyed.
232 class TreeServer : public classbase
234 InspIRCd* ServerInstance; /* Creator */
235 TreeServer* Parent; /* Parent entry */
236 TreeServer* Route; /* Route entry */
237 std::vector<TreeServer*> Children; /* List of child objects */
238 irc::string ServerName; /* Server's name */
239 std::string ServerDesc; /* Server's description */
240 std::string VersionString; /* Version string or empty string */
241 int UserCount; /* Not used in this version */
242 int OperCount; /* Not used in this version */
243 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
244 time_t NextPing; /* After this time, the server should be PINGed*/
245 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
246 SpanningTreeUtilities* Utils; /* Utility class */
250 /** We don't use this constructor. Its a dummy, and won't cause any insertion
251 * of the TreeServer into the hash_map. See below for the two we DO use.
253 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance) : ServerInstance(Instance), Utils(Util)
259 UserCount = OperCount = 0;
260 VersionString = ServerInstance->GetVersionString();
263 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
264 * represents our own server. Therefore, it has no route, no parent, and
265 * no socket associated with it. Its version string is our own local version.
267 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util)
271 UserCount = ServerInstance->UserCount();
272 OperCount = ServerInstance->OperCount();
273 VersionString = ServerInstance->GetVersionString();
275 Socket = NULL; /* Fix by brain */
279 /** When we create a new server, we call this constructor to initialize it.
280 * This constructor initializes the server's Route and Parent, and sets up
281 * its ping counters so that it will be pinged one minute from now.
283 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
284 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util)
287 UserCount = OperCount = 0;
288 this->SetNextPingTime(time(NULL) + 60);
291 /* find the 'route' for this server (e.g. the one directly connected
292 * to the local server, which we can use to reach it)
294 * In the following example, consider we have just added a TreeServer
295 * class for server G on our network, of which we are server A.
296 * To route traffic to G (marked with a *) we must send the data to
297 * B (marked with a +) so this algorithm initializes the 'Route'
298 * value to point at whichever server traffic must be routed through
299 * to get here. If we were to try this algorithm with server B,
300 * the Route pointer would point at its own object ('this').
310 * We only run this algorithm when a server is created, as
311 * the routes remain constant while ever the server exists, and
312 * do not need to be re-calculated.
316 if (Route == Utils->TreeRoot)
322 while (this->Route->GetParent() != Utils->TreeRoot)
324 this->Route = Route->GetParent();
328 /* Because recursive code is slow and takes a lot of resources,
329 * we store two representations of the server tree. The first
330 * is a recursive structure where each server references its
331 * children and its parent, which is used for netbursts and
332 * netsplits to dump the whole dataset to the other server,
333 * and the second is used for very fast lookups when routing
334 * messages and is instead a hash_map, where each item can
335 * be referenced by its server name. The AddHashEntry()
336 * call below automatically inserts each TreeServer class
337 * into the hash_map as it is created. There is a similar
338 * maintainance call in the destructor to tidy up deleted
342 this->AddHashEntry();
345 int QuitUsers(const std::string &reason)
347 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
348 const char* reason_s = reason.c_str();
349 std::vector<userrec*> time_to_die;
350 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
352 if (!strcmp(n->second->server, this->ServerName.c_str()))
354 time_to_die.push_back(n->second);
357 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
359 userrec* a = (userrec*)*n;
360 ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
362 userrec::QuitUser(ServerInstance,a,reason_s);
364 return time_to_die.size();
367 /** This method is used to add the structure to the
368 * hash_map for linear searches. It is only called
369 * by the constructors.
373 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
374 if (iter == Utils->serverlist.end())
375 Utils->serverlist[this->ServerName.c_str()] = this;
378 /** This method removes the reference to this object
379 * from the hash_map which is used for linear searches.
380 * It is only called by the default destructor.
384 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
385 if (iter != Utils->serverlist.end())
386 Utils->serverlist.erase(iter);
389 /** These accessors etc should be pretty self-
392 TreeServer* GetRoute()
397 std::string GetName()
399 return ServerName.c_str();
402 std::string GetDesc()
407 std::string GetVersion()
409 return VersionString;
412 void SetNextPingTime(time_t t)
415 LastPingWasGood = false;
418 time_t NextPingTime()
423 bool AnsweredLastPing()
425 return LastPingWasGood;
430 LastPingWasGood = true;
453 TreeSocket* GetSocket()
458 TreeServer* GetParent()
463 void SetVersion(const std::string &Version)
465 VersionString = Version;
468 unsigned int ChildCount()
470 return Children.size();
473 TreeServer* GetChild(unsigned int n)
475 if (n < Children.size())
477 /* Make sure they cant request
478 * an out-of-range object. After
479 * all we know what these programmer
480 * types are like *grin*.
490 void AddChild(TreeServer* Child)
492 Children.push_back(Child);
495 bool DelChild(TreeServer* Child)
497 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
508 /** Removes child nodes of this node, and of that node, etc etc.
509 * This is used during netsplits to automatically tidy up the
510 * server tree. It is slow, we don't use it for much else.
514 bool stillchildren = true;
515 while (stillchildren)
517 stillchildren = false;
518 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
520 TreeServer* s = (TreeServer*)*a;
524 stillchildren = true;
533 /* We'd better tidy up after ourselves, eh? */
534 this->DelHashEntry();
538 /** Yay for fast searches!
539 * This is hundreds of times faster than recursion
540 * or even scanning a linked list, especially when
541 * there are more than a few servers to deal with.
544 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
546 server_hash::iterator iter;
547 iter = serverlist.find(ServerName.c_str());
548 if (iter != serverlist.end())
558 /** Returns the locally connected server we must route a
559 * message through to reach server 'ServerName'. This
560 * only applies to one-to-one and not one-to-many routing.
561 * See the comments for the constructor of TreeServer
564 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
566 if (ServerName.c_str() == TreeRoot->GetName())
568 TreeServer* Found = FindServer(ServerName);
571 return Found->GetRoute();
579 /** Find the first server matching a given glob mask.
580 * Theres no find-using-glob method of hash_map [awwww :-(]
581 * so instead, we iterate over the list using an iterator
582 * and match each one until we get a hit. Yes its slow,
585 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
587 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
589 if (match(i->first.c_str(),ServerName.c_str()))
595 /* A convenient wrapper that returns true if a server exists */
596 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
598 return (FindServer(ServerName) != NULL);
604 class cmd_rconnect : public command_t
607 SpanningTreeUtilities* Utils;
609 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
611 this->source = "m_spanningtree.so";
612 syntax = "<remote-server-mask> <servermask>";
615 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
617 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
618 /* Is this aimed at our server? */
619 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
621 /* Yes, initiate the given connect */
622 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
624 para[0] = parameters[1];
625 std::string original_command = std::string("CONNECT ") + parameters[1];
626 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
637 /** Every SERVER connection inbound or outbound is represented by
638 * an object of type TreeSocket.
639 * TreeSockets, being inherited from InspSocket, can be tied into
640 * the core socket engine, and we cn therefore receive activity events
641 * for them, just like activex objects on speed. (yes really, that
642 * is a technical term!) Each of these which relates to a locally
643 * connected server is assocated with it, by hooking it onto a
644 * TreeSocket class using its constructor. In this way, we can
645 * maintain a list of servers, some of which are directly connected,
646 * some of which are not.
648 class TreeSocket : public InspSocket
650 SpanningTreeUtilities* Utils;
652 std::string in_buffer;
653 ServerState LinkState;
654 std::string InboundServerName;
655 std::string InboundDescription;
657 int num_lost_servers;
659 bool LastPingWasGood;
663 unsigned int keylength;
664 std::string ModuleList;
665 std::map<std::string,std::string> CapKeys;
670 /** Because most of the I/O gubbins are encapsulated within
671 * InspSocket, we just call the superclass constructor for
672 * most of the action, and append a few of our own values
675 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod = NULL)
676 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
679 this->LinkState = LISTENER;
681 this->ctx_out = NULL;
683 Instance->Log(DEBUG, "HOOK = %08x", Hook);
685 if (listening && Hook)
686 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
689 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName, Module* HookMod = NULL)
690 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
693 this->LinkState = CONNECTING;
695 this->ctx_out = NULL;
698 /** When a listening socket gives us a new file descriptor,
699 * we must associate it with a socket without creating a new
700 * connection. This constructor is used for this purpose.
702 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod = NULL)
703 : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
705 this->LinkState = WAIT_AUTH_1;
707 this->ctx_out = NULL;
709 Instance->Log(DEBUG, "HOOK = %08x", Hook);
712 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
714 //this->SendCapabilities();
725 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
728 void InitAES(std::string key,std::string SName)
735 Instance->Log(DEBUG,"Initialized AES key %s",key.c_str());
736 // key must be 16, 24, 32 etc bytes (multiple of 8)
737 keylength = key.length();
738 if (!(keylength == 16 || keylength == 24 || keylength == 32))
740 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
741 Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
745 if (this->GetState() != I_ERROR)
747 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
748 ctx_in->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
749 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
750 ctx_out->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
751 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
756 /** When an outbound connection finishes connecting, we receive
757 * this event, and must send our SERVER string to the other
758 * side. If the other side is happy, as outlined in the server
759 * to server docs on the inspircd.org site, the other side
760 * will then send back its own server string.
762 virtual bool OnConnected()
764 if (this->LinkState == CONNECTING)
766 /* we do not need to change state here. */
767 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
769 if (x->Name == this->myhost)
771 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
774 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
776 //this->SendCapabilities();
777 if (x->EncryptionKey != "")
779 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
781 this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
785 this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
786 this->InitAES(x->EncryptionKey,x->Name.c_str());
789 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
790 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 std::deque<std::string> param_list;
1653 /* Lower the TS here */
1654 if (Utils->AnnounceTSChange && chan)
1655 chan->WriteChannelWithServ(Instance->Config->ServerName,
1656 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1658 param_list.push_back(channel);
1660 /* Zap all the privilage modes on our side, if the channel exists here */
1663 this->RemoveStatus(Instance->Config->ServerName, param_list);
1668 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1669 irc::tokenstream users(params[2]);
1670 std::string item = "*";
1672 /* do this first, so our mode reversals are correctly received by other servers
1673 * if there is a TS collision.
1675 params[2] = ":" + params[2];
1676 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1678 /* Now, process every 'prefixes,nick' pair */
1681 /* Find next user */
1682 item = users.GetToken();
1684 const char* usr = item.c_str();
1686 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1687 * (is this even possible?) */
1690 const char* permissions = usr;
1692 char* nm = new char[MAXBUF];
1695 /* Iterate through all the prefix values, convert them from prefixes
1696 * to mode letters, and append them to the mode sequence
1698 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1700 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1703 /* This is a valid prefix */
1705 *tnm++ = mh->GetModeChar();
1709 /* Not a valid prefix...
1710 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1712 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1713 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1720 /* Null terminate modes */
1722 /* Advance past the comma, to the nick */
1725 /* Check the user actually exists */
1726 who = this->Instance->FindNick(usr);
1729 /* Did they get any modes? How many times? */
1730 strlcat(modestring, nm, MAXBUF);
1731 for (int k = 0; k < ntimes; k++)
1732 mode_users[modectr++] = strdup(usr);
1734 /* Free temporary buffer used for mode sequence */
1737 /* Check that the user's 'direction' is correct
1738 * based on the server sending the FJOIN. We must
1739 * check each nickname in turn, because the origin of
1740 * the FJOIN may be different to the origin of the nicks
1741 * in the command itself.
1743 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1744 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1746 /* Oh dear oh dear. */
1747 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1750 /* Finally, we can actually place the user into the channel.
1751 * We're sure its right. Final answer, phone a friend.
1753 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1755 /* Have we already queued up MAXMODES modes with parameters
1756 * (+qaohv) ready to be sent to the server?
1758 if (modectr >= (MAXMODES-1))
1760 /* Only actually give the users any status if we lost
1761 * the FJOIN or drew (equal timestamps).
1762 * It isn't actually possible for ourTS to be > TS here,
1763 * only possible to actually have ourTS == TS, or
1764 * ourTS < TS, because if we lost, we already lowered
1765 * our TS above before we entered this loop. We only
1766 * check >= as a safety measure, in case someone stuffed
1767 * up. If someone DID stuff up, it was most likely me.
1768 * Note: I do not like baseball bats in the face...
1772 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1773 this->Instance->SendMode((const char**)mode_users,modectr,who);
1775 /* Something stuffed up, and for some reason, the timestamp is
1776 * NOT lowered right now and should be. Lower it. Usually this
1777 * code won't be executed, doubtless someone will remove it some
1782 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1788 /* Reset all this back to defaults, and
1789 * free any ram we have left allocated.
1791 strcpy(mode_users[1],"+");
1792 for (unsigned int f = 2; f < modectr; f++)
1793 free(mode_users[f]);
1799 /* Remember to free this */
1801 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1802 * We don't try to process the nickname here (that WOULD cause a segfault because
1803 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1804 * in case somehow we're desynched, so that other users which might be able to see
1805 * the nickname get their fair chance to process it.
1807 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1813 /* there werent enough modes built up to flush it during FJOIN,
1814 * or, there are a number left over. flush them out.
1816 if ((modectr > 2) && (who) && (chan))
1820 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1821 this->Instance->SendMode((const char**)mode_users,modectr,who);
1822 /* Yet again, we can't actually get a true value here, if everything else
1823 * is working as it should.
1827 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1833 /* Free anything we have left to free */
1834 for (unsigned int f = 2; f < modectr; f++)
1835 free(mode_users[f]);
1838 /* if we newly created the channel, set it's TS properly. */
1841 /* find created channel .. */
1842 chan = this->Instance->FindChan(channel);
1844 /* w00t said this shouldnt be needed but it is.
1845 * This isnt strictly true, as chan can be NULL
1846 * if a nick collision has occured and therefore
1847 * the channel was never created.
1852 /* All done. That wasnt so bad was it, you can wipe
1853 * the sweat from your forehead now. :-)
1859 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1861 if (params.size() < 8)
1863 if (params.size() > 8)
1865 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1868 // NICK age nick host dhost ident +modes ip :gecos
1870 time_t age = atoi(params[0].c_str());
1872 /* This used to have a pretty craq'y loop doing the same thing,
1873 * now we just let the STL do the hard work (more efficiently)
1875 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1876 if (pos_after_plus != std::string::npos)
1877 params[5] = params[5].substr(pos_after_plus);
1879 const char* tempnick = params[1].c_str();
1880 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1882 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1884 if (iter != this->Instance->clientlist.end())
1887 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);
1888 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1889 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1893 userrec* _new = new userrec(this->Instance);
1894 this->Instance->clientlist[tempnick] = _new;
1895 _new->SetFd(FD_MAGIC_NUMBER);
1896 strlcpy(_new->nick, tempnick,NICKMAX-1);
1897 strlcpy(_new->host, params[2].c_str(),63);
1898 strlcpy(_new->dhost, params[3].c_str(),63);
1899 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1900 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1901 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1902 _new->registered = REG_ALL;
1905 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1906 _new->modes[(*v)-65] = 1;
1908 #ifdef SUPPORT_IP6LINKS
1909 if (params[6].find_first_of(":") != std::string::npos)
1910 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1913 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1915 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1917 params[7] = ":" + params[7];
1918 Utils->DoOneToAllButSender(source,"NICK",params,source);
1920 // Increment the Source Servers User Count..
1921 TreeServer* SourceServer = Utils->FindServer(source);
1924 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1925 SourceServer->AddUserCount();
1928 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1933 /** Send one or more FJOINs for a channel of users.
1934 * If the length of a single line is more than 480-NICKMAX
1935 * in length, it is split over multiple lines.
1937 void SendFJoins(TreeServer* Current, chanrec* c)
1941 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1943 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1945 size_t dlen, curlen;
1946 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1948 char* ptr = list + dlen;
1950 CUList *ulist = c->GetUsers();
1951 std::string modes = "";
1952 std::string params = "";
1954 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1956 // The first parameter gets a : before it
1957 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1964 if (curlen > (480-NICKMAX))
1966 buffer.append(list).append("\r\n");
1968 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1976 buffer.append(list).append("\r\n");
1978 /* Sorry for the hax. Because newly created channels assume +nt,
1979 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1981 bool inverted = false;
1982 if (!c->IsModeSet('n'))
1987 if (!c->IsModeSet('t'))
1997 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
2000 params.append(" ").append(b->data);
2002 if (params.length() >= MAXMODES)
2004 /* Wrap at MAXMODES */
2005 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");
2011 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
2013 /* Only send these if there are any */
2015 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);
2017 this->WriteLine(buffer);
2020 /** Send G, Q, Z and E lines */
2021 void SendXLines(TreeServer* Current)
2025 std::string n = this->Instance->Config->ServerName;
2026 const char* sn = n.c_str();
2028 /* Yes, these arent too nice looking, but they get the job done */
2029 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
2031 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);
2032 buffer.append(data);
2034 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
2036 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);
2037 buffer.append(data);
2039 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
2041 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);
2042 buffer.append(data);
2044 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
2046 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);
2047 buffer.append(data);
2049 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
2051 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);
2052 buffer.append(data);
2054 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
2056 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);
2057 buffer.append(data);
2059 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
2061 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);
2062 buffer.append(data);
2064 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
2066 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);
2067 buffer.append(data);
2070 if (!buffer.empty())
2071 this->WriteLine(buffer);
2074 /** Send channel modes and topics */
2075 void SendChannelModes(TreeServer* Current)
2078 std::deque<std::string> list;
2080 std::string n = this->Instance->Config->ServerName;
2081 const char* sn = n.c_str();
2082 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2084 SendFJoins(Current, c->second);
2085 if (*c->second->topic)
2087 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2088 this->WriteLine(data);
2090 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2092 c->second->GetExtList(list);
2093 for (unsigned int j = 0; j < list.size(); j++)
2095 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2100 /** send all users and their oper state/modes */
2101 void SendUsers(TreeServer* Current)
2104 std::deque<std::string> list;
2105 std::string dataline;
2107 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2109 if (u->second->registered == REG_ALL)
2111 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);
2112 this->WriteLine(data);
2113 if (*u->second->oper)
2115 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2116 this->WriteLine(data);
2118 if (*u->second->awaymsg)
2120 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2121 this->WriteLine(data);
2123 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2125 u->second->GetExtList(list);
2126 for (unsigned int j = 0; j < list.size(); j++)
2128 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2134 /** This function is called when we want to send a netburst to a local
2135 * server. There is a set order we must do this, because for example
2136 * users require their servers to exist, and channels require their
2137 * users to exist. You get the idea.
2139 void DoBurst(TreeServer* s)
2141 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2142 std::string endburst = "ENDBURST";
2143 // Because by the end of the netburst, it could be gone!
2144 std::string name = s->GetName();
2145 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2146 this->WriteLine(burst);
2147 /* send our version string */
2148 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2149 /* Send server tree */
2150 this->SendServers(Utils->TreeRoot,s,1);
2151 /* Send users and their oper status */
2153 /* Send everything else (channel modes, xlines etc) */
2154 this->SendChannelModes(s);
2155 this->SendXLines(s);
2156 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2157 this->WriteLine(endburst);
2158 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2161 /** This function is called when we receive data from a remote
2162 * server. We buffer the data in a std::string (it doesnt stay
2163 * there for long), reading using InspSocket::Read() which can
2164 * read up to 16 kilobytes in one operation.
2166 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2167 * THE SOCKET OBJECT FOR US.
2169 virtual bool OnDataReady()
2171 char* data = this->Read();
2172 /* Check that the data read is a valid pointer and it has some content */
2175 this->in_buffer.append(data);
2176 /* While there is at least one new line in the buffer,
2177 * do something useful (we hope!) with it.
2179 while (in_buffer.find("\n") != std::string::npos)
2181 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2182 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2183 /* Use rfind here not find, as theres more
2184 * chance of the \r being near the end of the
2185 * string, not the start.
2187 if (ret.find("\r") != std::string::npos)
2188 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2189 /* Process this one, abort if it
2190 * didnt return true.
2196 memset(result,0,1024);
2198 /* ERROR + CAPAB is still allowed unencryped */
2199 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2201 int nbytes = from64tobits(out, ret.c_str(), 1024);
2202 if ((nbytes > 0) && (nbytes < 1024))
2204 ctx_in->Decrypt(out, result, nbytes, 0);
2205 for (int t = 0; t < nbytes; t++)
2207 if (result[t] == '\7')
2209 /* We only need to stick a \0 on the
2210 * first \7, the rest will be lost
2220 if (!this->ProcessLine(ret))
2227 /* EAGAIN returns an empty but non-NULL string, so this
2228 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2230 return (data && !*data);
2233 int WriteLine(std::string line)
2235 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2239 char result64[10240];
2240 if (this->keylength)
2242 // pad it to the key length
2243 int n = this->keylength - (line.length() % this->keylength);
2245 line.append(n,'\7');
2247 unsigned int ll = line.length();
2248 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2249 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2252 line.append("\r\n");
2253 return this->Write(line);
2256 /* Handle ERROR command */
2257 bool Error(std::deque<std::string> ¶ms)
2259 if (params.size() < 1)
2261 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2262 /* we will return false to cause the socket to close. */
2266 /** remote MOTD. leet, huh? */
2267 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2269 if (params.size() > 0)
2271 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2273 /* It's for our server */
2274 string_list results;
2275 userrec* source = this->Instance->FindNick(prefix);
2279 std::deque<std::string> par;
2280 par.push_back(prefix);
2283 if (!Instance->Config->MOTD.size())
2285 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2286 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2290 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2291 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2293 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2295 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2296 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2299 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2300 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2306 userrec* source = this->Instance->FindNick(prefix);
2308 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2314 /** remote ADMIN. leet, huh? */
2315 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2317 if (params.size() > 0)
2319 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2321 /* It's for our server */
2322 string_list results;
2323 userrec* source = this->Instance->FindNick(prefix);
2327 std::deque<std::string> par;
2328 par.push_back(prefix);
2331 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2332 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2334 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2335 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2337 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2338 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2340 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2341 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2347 userrec* source = this->Instance->FindNick(prefix);
2349 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2355 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2357 /* Get the reply to a STATS query if it matches this servername,
2358 * and send it back as a load of PUSH queries
2360 if (params.size() > 1)
2362 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2364 /* It's for our server */
2365 string_list results;
2366 userrec* source = this->Instance->FindNick(prefix);
2369 std::deque<std::string> par;
2370 par.push_back(prefix);
2372 DoStats(this->Instance, *(params[0].c_str()), source, results);
2373 for (size_t i = 0; i < results.size(); i++)
2375 par[1] = "::" + results[i];
2376 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2383 userrec* source = this->Instance->FindNick(prefix);
2385 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2392 /** Because the core won't let users or even SERVERS set +o,
2393 * we use the OPERTYPE command to do this.
2395 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2397 if (params.size() != 1)
2399 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2402 std::string opertype = params[0];
2403 userrec* u = this->Instance->FindNick(prefix);
2406 u->modes[UM_OPERATOR] = 1;
2407 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2408 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2413 /** Because Andy insists that services-compatible servers must
2414 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2416 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2418 if (params.size() < 3)
2421 userrec* u = this->Instance->FindNick(params[0]);
2425 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2428 std::deque<std::string> par;
2429 par.push_back(params[1]);
2430 /* This is not required as one is sent in OnUserPostNick below
2432 //Utils->DoOneToMany(u->nick,"NICK",par);
2433 if (!u->ForceNickChange(params[1].c_str()))
2435 userrec::QuitUser(this->Instance, u, "Nickname collision");
2438 u->age = atoi(params[2].c_str());
2445 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
2446 * then let that server do the dirty work (squit it!). Example:
2447 * 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
2449 bool RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
2451 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
2452 if (params.size() < 2)
2455 TreeServer* s = Utils->FindServerMask(params[0]);
2459 if (s == Utils->TreeRoot)
2461 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
2465 TreeSocket* sock = s->GetSocket();
2469 /* it's locally connected, KILL IT! */
2470 Instance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
2471 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());
2472 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
2473 Instance->SE->DelFd(sock);
2479 /* route the rsquit */
2480 params[1] = ":" + params[1];
2481 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
2486 /* mother fucker! it doesn't exist */
2492 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2494 if (params.size() < 2)
2497 userrec* u = this->Instance->FindNick(params[0]);
2501 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2502 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2507 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2509 if (params.size() < 1)
2512 std::string servermask = params[0];
2514 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2516 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2517 this->Instance->RehashServer();
2518 Utils->ReadConfiguration(false);
2519 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2521 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2525 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2527 if (params.size() != 2)
2530 std::string nick = params[0];
2531 userrec* u = this->Instance->FindNick(prefix);
2532 userrec* who = this->Instance->FindNick(nick);
2536 /* Prepend kill source, if we don't have one */
2537 std::string sourceserv = prefix;
2540 sourceserv = u->server;
2542 if (*(params[1].c_str()) != '[')
2544 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2546 std::string reason = params[1];
2547 params[1] = ":" + params[1];
2548 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2549 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2550 userrec::QuitUser(this->Instance,who,reason);
2555 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2557 if (params.size() < 1)
2560 if (params.size() == 1)
2562 TreeServer* ServerSource = Utils->FindServer(prefix);
2565 ServerSource->SetPingFlag();
2570 std::string forwardto = params[1];
2571 if (forwardto == this->Instance->Config->ServerName)
2574 * this is a PONG for us
2575 * if the prefix is a user, check theyre local, and if they are,
2576 * dump the PONG reply back to their fd. If its a server, do nowt.
2577 * Services might want to send these s->s, but we dont need to yet.
2579 userrec* u = this->Instance->FindNick(prefix);
2583 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2588 // not for us, pass it on :)
2589 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2596 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2598 if (params.size() < 3)
2601 TreeServer* ServerSource = Utils->FindServer(prefix);
2605 if (params[0] == "*")
2607 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2609 else if (*(params[0].c_str()) == '#')
2611 chanrec* c = this->Instance->FindChan(params[0]);
2614 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2617 else if (*(params[0].c_str()) != '#')
2619 userrec* u = this->Instance->FindNick(params[0]);
2622 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2627 params[2] = ":" + params[2];
2628 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2632 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2634 if (params.size() < 1)
2637 TreeServer* ServerSource = Utils->FindServer(prefix);
2641 ServerSource->SetVersion(params[0]);
2643 params[0] = ":" + params[0];
2644 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2648 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2650 if (params.size() < 1)
2653 userrec* u = this->Instance->FindNick(prefix);
2657 u->ChangeDisplayedHost(params[0].c_str());
2658 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2663 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2665 if (params.size() < 6)
2668 bool propogate = false;
2670 switch (*(params[0].c_str()))
2673 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2674 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2677 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2678 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2681 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2682 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2685 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2686 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2689 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2692 /* Just in case... */
2693 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2698 /* Send it on its way */
2701 if (atoi(params[4].c_str()))
2703 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());
2707 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());
2709 params[5] = ":" + params[5];
2710 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2712 if (!this->bursting)
2714 Instance->Log(DEBUG,"Applying lines...");
2715 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2720 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2722 if (params.size() < 1)
2725 userrec* u = this->Instance->FindNick(prefix);
2729 u->ChangeName(params[0].c_str());
2730 params[0] = ":" + params[0];
2731 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2736 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2738 if (params.size() < 1)
2741 Instance->Log(DEBUG,"In IDLE command");
2742 userrec* u = this->Instance->FindNick(prefix);
2746 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2747 // an incoming request
2748 if (params.size() == 1)
2750 userrec* x = this->Instance->FindNick(params[0]);
2751 if ((x) && (IS_LOCAL(x)))
2753 userrec* x = this->Instance->FindNick(params[0]);
2754 char signon[MAXBUF];
2757 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2758 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2759 std::deque<std::string> par;
2760 par.push_back(prefix);
2761 par.push_back(signon);
2762 par.push_back(idle);
2763 // ours, we're done, pass it BACK
2764 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2768 // not ours pass it on
2769 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2772 else if (params.size() == 3)
2774 std::string who_did_the_whois = params[0];
2775 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2776 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2778 // an incoming reply to a whois we sent out
2779 std::string nick_whoised = prefix;
2780 unsigned long signon = atoi(params[1].c_str());
2781 unsigned long idle = atoi(params[2].c_str());
2782 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2783 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2787 // not ours, pass it on
2788 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2795 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2797 if (params.size() < 2)
2800 userrec* u = this->Instance->FindNick(params[0]);
2807 u->Write(params[1]);
2811 // continue the raw onwards
2812 params[1] = ":" + params[1];
2813 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2818 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2820 if (!params.size() || !Utils->EnableTimeSync)
2825 if ((params.size() == 2) && (params[1] == "FORCE"))
2828 time_t rts = atoi(params[0].c_str());
2829 time_t us = Instance->Time(true);
2833 Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2835 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2837 else if (force || (rts < us))
2839 int old = Instance->SetTimeDelta(rts - us);
2840 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2842 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2846 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2848 std::deque<std::string> oparams;
2849 oparams.push_back(ConvToStr(us));
2851 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2857 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2859 // :source.server TIME remote.server sendernick
2860 // :remote.server TIME source.server sendernick TS
2861 if (params.size() == 2)
2863 // someone querying our time?
2864 if (this->Instance->Config->ServerName == params[0])
2866 userrec* u = this->Instance->FindNick(params[1]);
2869 params.push_back(ConvToStr(Instance->Time(false)));
2871 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2876 // not us, pass it on
2877 userrec* u = this->Instance->FindNick(params[1]);
2879 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2882 else if (params.size() == 3)
2884 // a response to a previous TIME
2885 userrec* u = this->Instance->FindNick(params[1]);
2886 if ((u) && (IS_LOCAL(u)))
2888 time_t rawtime = atol(params[2].c_str());
2889 struct tm * timeinfo;
2890 timeinfo = localtime(&rawtime);
2892 snprintf(tms,26,"%s",asctime(timeinfo));
2894 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2899 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2905 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2907 if (params.size() < 1)
2910 if (params.size() == 1)
2912 std::string stufftobounce = params[0];
2913 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2918 std::string forwardto = params[1];
2919 if (forwardto == this->Instance->Config->ServerName)
2921 // this is a ping for us, send back PONG to the requesting server
2922 params[1] = params[0];
2923 params[0] = forwardto;
2924 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2928 // not for us, pass it on :)
2929 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2935 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2937 if (params.size() < 1)
2940 chanrec* c = Instance->FindChan(params[0]);
2944 irc::modestacker modestack(false);
2945 CUList *ulist = c->GetUsers();
2947 std::deque<std::string> stackresult;
2950 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2952 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2953 if (modesequence.length())
2955 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2956 irc::spacesepstream sep(modesequence);
2957 std::string modeletters = sep.GetToken();
2958 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2960 while (!modeletters.empty())
2962 char mletter = *(modeletters.begin());
2963 modestack.Push(mletter,sep.GetToken());
2964 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2965 modeletters.erase(modeletters.begin());
2966 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2971 while (modestack.GetStackedLine(stackresult))
2973 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2974 stackresult.push_front(ConvToStr(c->age));
2975 stackresult.push_front(c->name);
2976 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2977 stackresult.erase(stackresult.begin() + 1);
2978 Instance->Log(DEBUG,"Stacked items:");
2979 for (size_t z = 0; z < stackresult.size(); z++)
2981 y[z] = stackresult[z].c_str();
2982 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2984 userrec* n = new userrec(Instance);
2985 n->SetFd(FD_MAGIC_NUMBER);
2986 Instance->SendMode(y, stackresult.size(), n);
2993 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2995 if (params.size() < 4)
2998 std::string servername = params[0];
2999 std::string password = params[1];
3000 // hopcount is not used for a remote server, we calculate this ourselves
3001 std::string description = params[3];
3002 TreeServer* ParentOfThis = Utils->FindServer(prefix);
3006 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
3009 TreeServer* CheckDupe = Utils->FindServer(servername);
3012 this->WriteLine("ERROR :Server "+servername+" already exists!");
3013 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
3016 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
3017 ParentOfThis->AddChild(Node);
3018 params[3] = ":" + params[3];
3019 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
3020 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
3024 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
3026 if (params.size() < 4)
3029 irc::string servername = params[0].c_str();
3030 std::string sname = params[0];
3031 std::string password = params[1];
3032 int hops = atoi(params[2].c_str());
3036 this->WriteLine("ERROR :Server too far away for authentication");
3037 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3040 std::string description = params[3];
3041 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3043 if ((x->Name == servername) && (x->RecvPass == password))
3045 TreeServer* CheckDupe = Utils->FindServer(sname);
3048 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3049 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3052 // Begin the sync here. this kickstarts the
3053 // other side, waiting in WAIT_AUTH_2 state,
3054 // into starting their burst, as it shows
3055 // that we're happy.
3056 this->LinkState = CONNECTED;
3057 // we should add the details of this server now
3058 // to the servers tree, as a child of the root
3060 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
3061 Utils->TreeRoot->AddChild(Node);
3062 params[3] = ":" + params[3];
3063 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
3064 this->bursting = true;
3065 this->DoBurst(Node);
3069 this->WriteLine("ERROR :Invalid credentials");
3070 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3074 bool Inbound_Server(std::deque<std::string> ¶ms)
3076 if (params.size() < 4)
3079 irc::string servername = params[0].c_str();
3080 std::string sname = params[0];
3081 std::string password = params[1];
3082 int hops = atoi(params[2].c_str());
3086 this->WriteLine("ERROR :Server too far away for authentication");
3087 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3090 std::string description = params[3];
3091 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3093 if ((x->Name == servername) && (x->RecvPass == password))
3095 TreeServer* CheckDupe = Utils->FindServer(sname);
3098 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3099 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3102 /* If the config says this link is encrypted, but the remote side
3103 * hasnt bothered to send the AES command before SERVER, then we
3104 * boot them off as we MUST have this connection encrypted.
3106 if ((x->EncryptionKey != "") && (!this->ctx_in))
3108 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
3109 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
3112 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
3113 this->InboundServerName = sname;
3114 this->InboundDescription = description;
3115 // this is good. Send our details: Our server name and description and hopcount of 0,
3116 // along with the sendpass from this block.
3117 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3118 // move to the next state, we are now waiting for THEM.
3119 this->LinkState = WAIT_AUTH_2;
3123 this->WriteLine("ERROR :Invalid credentials");
3124 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3128 void Split(const std::string &line, std::deque<std::string> &n)
3131 irc::tokenstream tokens(line);
3133 while ((param = tokens.GetToken()) != "")
3138 bool ProcessLine(std::string &line)
3140 std::deque<std::string> params;
3141 irc::string command;
3144 line = line.substr(0, line.find_first_of("\r\n"));
3149 Instance->Log(DEBUG,"IN: %s", line.c_str());
3151 this->Split(line.c_str(),params);
3153 if ((params[0][0] == ':') && (params.size() > 1))
3155 prefix = params[0].substr(1);
3159 command = params[0].c_str();
3162 if ((!this->ctx_in) && (command == "AES"))
3164 std::string sserv = params[0];
3165 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3167 if ((x->EncryptionKey != "") && (x->Name == sserv))
3169 this->InitAES(x->EncryptionKey,sserv);
3175 else if ((this->ctx_in) && (command == "AES"))
3177 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
3180 switch (this->LinkState)
3185 // Waiting for SERVER command from remote server. Server initiating
3186 // the connection sends the first SERVER command, listening server
3187 // replies with theirs if its happy, then if the initiator is happy,
3188 // it starts to send its net sync, which starts the merge, otherwise
3189 // it sends an ERROR.
3190 if (command == "PASS")
3192 /* Silently ignored */
3194 else if (command == "SERVER")
3196 return this->Inbound_Server(params);
3198 else if (command == "ERROR")
3200 return this->Error(params);
3202 else if (command == "USER")
3204 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3207 else if (command == "CAPAB")
3209 return this->Capab(params);
3211 else if ((command == "U") || (command == "S"))
3213 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3218 std::string error("ERROR :Invalid command in negotiation phase: ");
3219 error.append(command.c_str());
3220 this->WriteLine(error);
3225 // Waiting for start of other side's netmerge to say they liked our
3227 if (command == "SERVER")
3229 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3233 else if ((command == "U") || (command == "S"))
3235 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3238 else if (command == "BURST")
3240 if (params.size() && Utils->EnableTimeSync)
3242 /* If a time stamp is provided, apply synchronization */
3244 time_t them = atoi(params[0].c_str());
3245 time_t us = Instance->Time(true);
3246 int delta = them - us;
3248 if ((params.size() == 2) && (params[1] == "FORCE"))
3251 if ((delta < -600) || (delta > 600))
3253 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));
3254 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3260 this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3262 else if (force || (us > them))
3264 this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3265 this->Instance->SetTimeDelta(them - us);
3266 // Send this new timestamp to any other servers
3267 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3271 // Override the timestamp
3272 this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3273 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3276 this->LinkState = CONNECTED;
3277 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3278 Utils->TreeRoot->AddChild(Node);
3280 params.push_back(InboundServerName);
3281 params.push_back("*");
3282 params.push_back("1");
3283 params.push_back(":"+InboundDescription);
3284 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3285 this->bursting = true;
3286 this->DoBurst(Node);
3288 else if (command == "ERROR")
3290 return this->Error(params);
3292 else if (command == "CAPAB")
3294 return this->Capab(params);
3299 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3303 if (command == "SERVER")
3305 // another server we connected to, which was in WAIT_AUTH_1 state,
3306 // has just sent us their credentials. If we get this far, theyre
3307 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3308 // if we're happy with this, we should send our netburst which
3309 // kickstarts the merge.
3310 return this->Outbound_Reply_Server(params);
3312 else if (command == "ERROR")
3314 return this->Error(params);
3318 // This is the 'authenticated' state, when all passwords
3319 // have been exchanged and anything past this point is taken
3324 std::string direction = prefix;
3325 userrec* t = this->Instance->FindNick(prefix);
3328 direction = t->server;
3330 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3331 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3333 if (route_back_again)
3334 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3339 * When there is activity on the socket, reset the ping counter so
3340 * that we're not wasting bandwidth pinging an active server.
3342 route_back_again->SetNextPingTime(time(NULL) + 60);
3343 route_back_again->SetPingFlag();
3346 if (command == "SVSMODE")
3348 /* Services expects us to implement
3349 * SVSMODE. In inspircd its the same as
3354 std::string target = "";
3355 /* Yes, know, this is a mess. Its reasonably fast though as we're
3356 * working with std::string here.
3358 if ((command == "NICK") && (params.size() > 1))
3360 return this->IntroduceClient(prefix,params);
3362 else if (command == "FJOIN")
3364 return this->ForceJoin(prefix,params);
3366 else if (command == "STATS")
3368 return this->Stats(prefix, params);
3370 else if (command == "MOTD")
3372 return this->Motd(prefix, params);
3374 else if (command == "ADMIN")
3376 return this->Admin(prefix, params);
3378 else if (command == "SERVER")
3380 return this->RemoteServer(prefix,params);
3382 else if (command == "ERROR")
3384 return this->Error(params);
3386 else if (command == "OPERTYPE")
3388 return this->OperType(prefix,params);
3390 else if (command == "FMODE")
3392 return this->ForceMode(prefix,params);
3394 else if (command == "KILL")
3396 return this->RemoteKill(prefix,params);
3398 else if (command == "FTOPIC")
3400 return this->ForceTopic(prefix,params);
3402 else if (command == "REHASH")
3404 return this->RemoteRehash(prefix,params);
3406 else if (command == "METADATA")
3408 return this->MetaData(prefix,params);
3410 else if (command == "REMSTATUS")
3412 return this->RemoveStatus(prefix,params);
3414 else if (command == "PING")
3417 * We just got a ping from a server that's bursting.
3418 * This can't be right, so set them to not bursting, and
3419 * apply their lines.
3423 this->bursting = false;
3424 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3428 prefix = this->GetName();
3430 return this->LocalPing(prefix,params);
3432 else if (command == "PONG")
3435 * We just got a pong from a server that's bursting.
3436 * This can't be right, so set them to not bursting, and
3437 * apply their lines.
3441 this->bursting = false;
3442 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3446 prefix = this->GetName();
3448 return this->LocalPong(prefix,params);
3450 else if (command == "VERSION")
3452 return this->ServerVersion(prefix,params);
3454 else if (command == "FHOST")
3456 return this->ChangeHost(prefix,params);
3458 else if (command == "FNAME")
3460 return this->ChangeName(prefix,params);
3462 else if (command == "ADDLINE")
3464 return this->AddLine(prefix,params);
3466 else if (command == "SVSNICK")
3470 prefix = this->GetName();
3472 return this->ForceNick(prefix,params);
3474 else if (command == "RSQUIT")
3476 return this->RemoteSquit(prefix, params);
3478 else if (command == "IDLE")
3480 return this->Whois(prefix,params);
3482 else if (command == "PUSH")
3484 return this->Push(prefix,params);
3486 else if (command == "TIMESET")
3488 return this->HandleSetTime(prefix, params);
3490 else if (command == "TIME")
3492 return this->Time(prefix,params);
3494 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3496 std::string sourceserv = this->myhost;
3497 if (params.size() == 3)
3499 userrec* user = this->Instance->FindNick(params[1]);
3500 chanrec* chan = this->Instance->FindChan(params[0]);
3503 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3504 /* Yikes, the channels gone! */
3508 if (this->InboundServerName != "")
3510 sourceserv = this->InboundServerName;
3512 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3514 else if (command == "SVSJOIN")
3518 prefix = this->GetName();
3520 return this->ServiceJoin(prefix,params);
3522 else if (command == "SQUIT")
3524 if (params.size() == 2)
3526 this->Squit(Utils->FindServer(params[0]),params[1]);
3530 else if (command == "OPERNOTICE")
3532 std::string sourceserv = this->myhost;
3534 if (this->InboundServerName != "")
3535 sourceserv = this->InboundServerName;
3537 if (params.size() >= 1)
3538 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3540 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3542 else if (command == "MODENOTICE")
3544 std::string sourceserv = this->myhost;
3545 if (this->InboundServerName != "")
3546 sourceserv = this->InboundServerName;
3547 if (params.size() >= 2)
3549 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3552 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3554 else if (command == "SNONOTICE")
3556 std::string sourceserv = this->myhost;
3557 if (this->InboundServerName != "")
3558 sourceserv = this->InboundServerName;
3559 if (params.size() >= 2)
3561 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3564 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3566 else if (command == "ENDBURST")
3568 this->bursting = false;
3569 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3570 std::string sourceserv = this->myhost;
3571 if (this->InboundServerName != "")
3573 sourceserv = this->InboundServerName;
3575 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3577 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3578 rmode.Send(Instance);
3584 // not a special inter-server command.
3585 // Emulate the actual user doing the command,
3586 // this saves us having a huge ugly parser.
3587 userrec* who = this->Instance->FindNick(prefix);
3588 std::string sourceserv = this->myhost;
3589 if (this->InboundServerName != "")
3591 sourceserv = this->InboundServerName;
3593 if ((!who) && (command == "MODE"))
3595 if (Utils->IsServer(prefix))
3597 const char* modelist[127];
3598 for (size_t i = 0; i < params.size(); i++)
3599 modelist[i] = params[i].c_str();
3601 userrec* fake = new userrec(Instance);
3602 fake->SetFd(FD_MAGIC_NUMBER);
3604 this->Instance->SendMode(modelist, params.size(), fake);
3608 /* Hot potato! pass it on! */
3609 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3614 if ((command == "NICK") && (params.size() > 0))
3616 /* On nick messages, check that the nick doesnt
3617 * already exist here. If it does, kill their copy,
3620 userrec* x = this->Instance->FindNick(params[0]);
3621 if ((x) && (x != who))
3623 std::deque<std::string> p;
3624 p.push_back(params[0]);
3625 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3626 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3628 p.push_back(prefix);
3629 p.push_back("Nickname collision");
3630 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3631 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3632 userrec* y = this->Instance->FindNick(prefix);
3635 userrec::QuitUser(this->Instance,y,"Nickname collision");
3637 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3641 target = who->server;
3642 const char* strparams[127];
3643 for (unsigned int q = 0; q < params.size(); q++)
3645 strparams[q] = params[q].c_str();
3647 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3650 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3657 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3663 // its not a user. Its either a server, or somethings screwed up.
3664 if (Utils->IsServer(prefix))
3666 target = this->Instance->Config->ServerName;
3670 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3674 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3683 virtual std::string GetName()
3685 std::string sourceserv = this->myhost;
3686 if (this->InboundServerName != "")
3688 sourceserv = this->InboundServerName;
3693 virtual void OnTimeout()
3695 if (this->LinkState == CONNECTING)
3697 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3698 Link* MyLink = Utils->FindLink(myhost);
3700 Utils->DoFailOver(MyLink);
3704 virtual void OnClose()
3706 // Connection closed.
3707 // If the connection is fully up (state CONNECTED)
3708 // then propogate a netsplit to all peers.
3709 std::string quitserver = this->myhost;
3710 if (this->InboundServerName != "")
3712 quitserver = this->InboundServerName;
3714 TreeServer* s = Utils->FindServer(quitserver);
3717 Squit(s,"Remote host closed the connection");
3720 if (quitserver != "")
3721 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3724 virtual int OnIncomingConnection(int newsock, char* ip)
3726 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3727 * or discovering if this port is the server port, we don't allow connections from any
3728 * IPs for which we don't have a link block.
3732 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3735 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3736 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3741 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3747 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
3749 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3754 /** This class is used to resolve server hostnames during /connect and autoconnect.
3755 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3756 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3757 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3758 * will have an IP address which we can then use to continue our connection.
3760 class ServernameResolver : public Resolver
3763 /** A copy of the Link tag info for what we're connecting to.
3764 * We take a copy, rather than using a pointer, just in case the
3765 * admin takes the tag away and rehashes while the domain is resolving.
3768 SpanningTreeUtilities* Utils;
3770 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3772 /* Nothing in here, folks */
3775 void OnLookupComplete(const std::string &result)
3777 /* Initiate the connection, now that we have an IP to use.
3778 * Passing a hostname directly to InspSocket causes it to
3779 * just bail and set its FD to -1.
3781 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3782 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3785 if ((!MyLink.Hook.empty()) && (Utils->hooks.find(MyLink.Hook.c_str()) == Utils->hooks.end()))
3788 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str(),
3789 MyLink.Hook.empty() ? NULL : Utils->hooks[MyLink.Hook.c_str()]);
3790 if (newsocket->GetFd() > -1)
3796 /* Something barfed, show the opers */
3797 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3799 Utils->DoFailOver(&MyLink);
3804 void OnError(ResolverError e, const std::string &errormessage)
3807 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3808 Utils->DoFailOver(&MyLink);
3812 /** Handle resolving of server IPs for the cache
3814 class SecurityIPResolver : public Resolver
3818 SpanningTreeUtilities* Utils;
3820 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3824 void OnLookupComplete(const std::string &result)
3826 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3827 Utils->ValidIPs.push_back(result);
3830 void OnError(ResolverError e, const std::string &errormessage)
3832 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3836 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3840 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3842 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
3844 /* Did we find any modules? */
3847 /* Yes, enumerate them all to find out the hook name */
3848 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
3850 /* Make a request to it for its name, its implementing
3851 * InspSocketHook so we know its safe to do this
3853 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
3854 /* Build a map of them */
3855 hooks[name.c_str()] = *m;
3856 hooknames.push_back(name);
3857 ServerInstance->Log(DEBUG, "Found InspSocketHook interface: '%s' -> '%08x'", name.c_str(), *m);
3861 this->ReadConfiguration(true);
3864 SpanningTreeUtilities::~SpanningTreeUtilities()
3866 for (unsigned int i = 0; i < Bindings.size(); i++)
3868 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3869 ServerInstance->SE->DelFd(Bindings[i]);
3870 Bindings[i]->Close();
3871 DELETE(Bindings[i]);
3873 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3874 while (TreeRoot->ChildCount())
3876 TreeServer* child_server = TreeRoot->GetChild(0);
3877 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3880 TreeSocket* sock = child_server->GetSocket();
3881 ServerInstance->SE->DelFd(sock);
3889 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
3891 if (list.find(server) == list.end())
3892 list[server] = server;
3895 /** returns a list of DIRECT servernames for a specific channel */
3896 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
3902 ulist = c->GetOppedUsers();
3905 ulist = c->GetHalfoppedUsers();
3908 ulist = c->GetVoicedUsers();
3911 ulist = c->GetUsers();
3914 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3916 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
3918 TreeServer* best = this->BestRouteTo(i->second->server);
3920 AddThisServer(best,list);
3926 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3929 TreeServer* omitroute = this->BestRouteTo(omit);
3930 if ((command == "NOTICE") || (command == "PRIVMSG"))
3932 if (params.size() >= 2)
3935 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3938 params[0] = params[0].substr(1, params[0].length()-1);
3940 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3942 // special routing for private messages/notices
3943 userrec* d = ServerInstance->FindNick(params[0]);
3946 std::deque<std::string> par;
3947 par.push_back(params[0]);
3948 par.push_back(":"+params[1]);
3949 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3953 else if (*(params[0].c_str()) == '$')
3955 std::deque<std::string> par;
3956 par.push_back(params[0]);
3957 par.push_back(":"+params[1]);
3958 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3963 chanrec* c = ServerInstance->FindChan(params[0]);
3964 userrec* u = ServerInstance->FindNick(prefix);
3968 TreeServerList list;
3969 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
3970 GetListOfServersForChannel(c,list,pfx,elist);
3972 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
3974 TreeSocket* Sock = i->second->GetSocket();
3975 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
3977 Sock->WriteLine(data);
3985 unsigned int items =this->TreeRoot->ChildCount();
3986 for (unsigned int x = 0; x < items; x++)
3988 TreeServer* Route = this->TreeRoot->GetChild(x);
3989 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3991 TreeSocket* Sock = Route->GetSocket();
3993 Sock->WriteLine(data);
3999 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
4001 TreeServer* omitroute = this->BestRouteTo(omit);
4002 std::string FullLine = ":" + prefix + " " + command;
4003 unsigned int words = params.size();
4004 for (unsigned int x = 0; x < words; x++)
4006 FullLine = FullLine + " " + params[x];
4008 unsigned int items = this->TreeRoot->ChildCount();
4009 for (unsigned int x = 0; x < items; x++)
4011 TreeServer* Route = this->TreeRoot->GetChild(x);
4012 // Send the line IF:
4013 // The route has a socket (its a direct connection)
4014 // The route isnt the one to be omitted
4015 // The route isnt the path to the one to be omitted
4016 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
4018 TreeSocket* Sock = Route->GetSocket();
4020 Sock->WriteLine(FullLine);
4026 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
4028 std::string FullLine = ":" + prefix + " " + command;
4029 unsigned int words = params.size();
4030 for (unsigned int x = 0; x < words; x++)
4032 FullLine = FullLine + " " + params[x];
4034 unsigned int items = this->TreeRoot->ChildCount();
4035 for (unsigned int x = 0; x < items; x++)
4037 TreeServer* Route = this->TreeRoot->GetChild(x);
4038 if (Route && Route->GetSocket())
4040 TreeSocket* Sock = Route->GetSocket();
4042 Sock->WriteLine(FullLine);
4048 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
4050 std::string spfx = prefix;
4051 std::string scmd = command;
4052 return this->DoOneToMany(spfx, scmd, params);
4055 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
4057 std::string spfx = prefix;
4058 std::string scmd = command;
4059 return this->DoOneToAllButSender(spfx, scmd, params, omit);
4062 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
4064 TreeServer* Route = this->BestRouteTo(target);
4067 std::string FullLine = ":" + prefix + " " + command;
4068 unsigned int words = params.size();
4069 for (unsigned int x = 0; x < words; x++)
4071 FullLine = FullLine + " " + params[x];
4073 if (Route && Route->GetSocket())
4075 TreeSocket* Sock = Route->GetSocket();
4077 Sock->WriteLine(FullLine);
4087 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
4089 ConfigReader* Conf = new ConfigReader(ServerInstance);
4092 for (int j =0; j < Conf->Enumerate("bind"); j++)
4094 std::string Type = Conf->ReadValue("bind","type",j);
4095 std::string IP = Conf->ReadValue("bind","address",j);
4096 std::string Port = Conf->ReadValue("bind","port",j);
4097 std::string transport = Conf->ReadValue("bind","transport",j);
4098 if (Type == "servers")
4100 irc::portparser portrange(Port, false);
4102 while ((portno = portrange.GetToken()))
4104 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
4108 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
4110 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' - maybe you forgot to load it BEFORE m_spanningtree in your config file?",
4115 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
4116 if (listener->GetState() == I_LISTENING)
4118 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
4119 Bindings.push_back(listener);
4123 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
4127 ServerInstance->Log(DEBUG,"Done with this binding");
4132 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
4133 HideULines = Conf->ReadFlag("options","hideulines",0);
4134 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
4135 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
4138 for (int j =0; j < Conf->Enumerate("link"); j++)
4141 std::string Allow = Conf->ReadValue("link","allowmask",j);
4142 L.Name = (Conf->ReadValue("link","name",j)).c_str();
4143 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
4144 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
4145 L.Port = Conf->ReadInteger("link","port",j,true);
4146 L.SendPass = Conf->ReadValue("link","sendpass",j);
4147 L.RecvPass = Conf->ReadValue("link","recvpass",j);
4148 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
4149 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
4150 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
4151 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
4152 L.Hook = Conf->ReadValue("link", "transport", j);
4153 L.NextConnectTime = time(NULL) + L.AutoConnect;
4154 /* Bugfix by brain, do not allow people to enter bad configurations */
4155 if (L.Name != ServerInstance->Config->ServerName)
4157 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
4159 ValidIPs.push_back(L.IPAddr);
4162 ValidIPs.push_back(Allow);
4164 /* Needs resolving */
4166 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
4170 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
4171 ServerInstance->AddResolver(sr);
4173 catch (ModuleException& e)
4175 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4179 LinkBlocks.push_back(L);
4180 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4186 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4188 else if (L.RecvPass == "")
4190 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4192 else if (L.SendPass == "")
4194 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4196 else if (L.Name == "")
4198 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4202 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4208 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4214 /** To create a timer which recurs every second, we inherit from InspTimer.
4215 * InspTimer is only one-shot however, so at the end of each Tick() we simply
4216 * insert another of ourselves into the pending queue :)
4218 class TimeSyncTimer : public InspTimer
4222 ModuleSpanningTree *Module;
4224 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4225 virtual void Tick(time_t TIME);
4228 class ModuleSpanningTree : public Module
4232 unsigned int max_local;
4233 unsigned int max_global;
4234 cmd_rconnect* command_rconnect;
4235 SpanningTreeUtilities* Utils;
4238 TimeSyncTimer *SyncTimer;
4240 ModuleSpanningTree(InspIRCd* Me)
4241 : Module::Module(Me), max_local(0), max_global(0)
4243 Utils = new SpanningTreeUtilities(Me, this);
4245 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4246 ServerInstance->AddCommand(command_rconnect);
4248 if (Utils->EnableTimeSync)
4250 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4251 ServerInstance->Timers->AddTimer(SyncTimer);
4257 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4259 std::string Parent = Utils->TreeRoot->GetName();
4260 if (Current->GetParent())
4262 Parent = Current->GetParent()->GetName();
4264 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4266 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4270 ShowLinks(Current->GetChild(q),user,hops+1);
4275 ShowLinks(Current->GetChild(q),user,hops+1);
4278 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4279 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4281 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());
4284 int CountLocalServs()
4286 return Utils->TreeRoot->ChildCount();
4291 return Utils->serverlist.size();
4294 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4296 ShowLinks(Utils->TreeRoot,user,0);
4297 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4301 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4303 unsigned int n_users = ServerInstance->UserCount();
4305 /* Only update these when someone wants to see them, more efficient */
4306 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4307 max_local = ServerInstance->LocalUserCount();
4308 if (n_users > max_global)
4309 max_global = n_users;
4311 unsigned int ulined_count = 0;
4312 unsigned int ulined_local_count = 0;
4314 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4315 * locally and globally (locally means directly connected to us)
4317 if ((Utils->HideULines) && (!*user->oper))
4319 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4321 if (ServerInstance->ULine(q->second->GetName().c_str()))
4324 if (q->second->GetParent() == Utils->TreeRoot)
4325 ulined_local_count++;
4330 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());
4331 if (ServerInstance->OperCount())
4332 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4333 if (ServerInstance->UnregisteredUserCount())
4334 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4335 if (ServerInstance->ChannelCount())
4336 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4337 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());
4338 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4339 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4343 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4345 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4349 for (int t = 0; t < depth; t++)
4351 matrix[line][t] = ' ';
4354 // For Aligning, we need to work out exactly how deep this thing is, and produce
4355 // a 'Spacer' String to compensate.
4358 memset(spacer,' ',40);
4359 if ((40 - Current->GetName().length() - depth) > 1) {
4360 spacer[40 - Current->GetName().length() - depth] = '\0';
4369 if (ServerInstance->clientlist.size() == 0) {
4370 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4375 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4377 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4378 totusers += Current->GetUserCount();
4380 strlcpy(&matrix[line][depth],text,80);
4382 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4384 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4388 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4393 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4399 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4403 /* Remote MOTD, the server is within the 1st parameter */
4404 std::deque<std::string> params;
4405 params.push_back(parameters[0]);
4407 /* Send it out remotely, generate no reply yet */
4408 TreeServer* s = Utils->FindServerMask(parameters[0]);
4411 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4415 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4422 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4426 /* Remote ADMIN, the server is within the 1st parameter */
4427 std::deque<std::string> params;
4428 params.push_back(parameters[0]);
4430 /* Send it out remotely, generate no reply yet */
4431 TreeServer* s = Utils->FindServerMask(parameters[0]);
4434 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4438 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4445 int HandleStats(const char** parameters, int pcnt, userrec* user)
4449 /* Remote STATS, the server is within the 2nd parameter */
4450 std::deque<std::string> params;
4451 params.push_back(parameters[0]);
4452 params.push_back(parameters[1]);
4453 /* Send it out remotely, generate no reply yet */
4454 TreeServer* s = Utils->FindServerMask(parameters[1]);
4457 params[1] = s->GetName();
4458 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4462 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4469 // Ok, prepare to be confused.
4470 // After much mulling over how to approach this, it struck me that
4471 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4472 // keeping track of a ton of ascii characters, and line by line
4473 // under recursion working out where to place them using multiplications
4474 // and divisons, we instead render the map onto a backplane of characters
4475 // (a character matrix), then draw the branches as a series of "L" shapes
4476 // from the nodes. This is not only friendlier on CPU it uses less stack.
4478 void HandleMap(const char** parameters, int pcnt, userrec* user)
4480 // This array represents a virtual screen which we will
4481 // "scratch" draw to, as the console device of an irc
4482 // client does not provide for a proper terminal.
4484 float totservers = 0;
4485 char matrix[128][80];
4486 for (unsigned int t = 0; t < 128; t++)
4488 matrix[t][0] = '\0';
4491 // The only recursive bit is called here.
4492 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4493 // Process each line one by one. The algorithm has a limit of
4494 // 128 servers (which is far more than a spanning tree should have
4495 // anyway, so we're ok). This limit can be raised simply by making
4496 // the character matrix deeper, 128 rows taking 10k of memory.
4497 for (int l = 1; l < line; l++)
4499 // scan across the line looking for the start of the
4500 // servername (the recursive part of the algorithm has placed
4501 // the servers at indented positions depending on what they
4503 int first_nonspace = 0;
4504 while (matrix[l][first_nonspace] == ' ')
4509 // Draw the `- (corner) section: this may be overwritten by
4510 // another L shape passing along the same vertical pane, becoming
4511 // a |- (branch) section instead.
4512 matrix[l][first_nonspace] = '-';
4513 matrix[l][first_nonspace-1] = '`';
4515 // Draw upwards until we hit the parent server, causing possibly
4516 // other corners (`-) to become branches (|-)
4517 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4519 matrix[l2][first_nonspace-1] = '|';
4523 // dump the whole lot to the user. This is the easy bit, honest.
4524 for (int t = 0; t < line; t++)
4526 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4528 float avg_users = totusers / totservers;
4529 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);
4530 user->WriteServ("007 %s :End of /MAP",user->nick);
4534 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4536 TreeServer* s = Utils->FindServerMask(parameters[0]);
4539 if (s == Utils->TreeRoot)
4541 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4544 TreeSocket* sock = s->GetSocket();
4547 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4548 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4549 sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost());
4550 ServerInstance->SE->DelFd(sock);
4557 std::deque<std::string> params;
4558 params.push_back(parameters[0]);
4559 params.push_back(std::string(":Server quit by ") + user->GetFullRealHost());
4560 Utils->DoOneToOne(user->nick, "RSQUIT", params, parameters[0]);
4565 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4570 int HandleTime(const char** parameters, int pcnt, userrec* user)
4572 if ((IS_LOCAL(user)) && (pcnt))
4574 TreeServer* found = Utils->FindServerMask(parameters[0]);
4577 // we dont' override for local server
4578 if (found == Utils->TreeRoot)
4581 std::deque<std::string> params;
4582 params.push_back(found->GetName());
4583 params.push_back(user->nick);
4584 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4588 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4594 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4596 if ((IS_LOCAL(user)) && (pcnt > 1))
4598 userrec* remote = ServerInstance->FindNick(parameters[1]);
4599 if ((remote) && (remote->GetFd() < 0))
4601 std::deque<std::string> params;
4602 params.push_back(parameters[1]);
4603 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4608 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4609 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4616 void DoPingChecks(time_t curtime)
4618 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4620 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4621 TreeSocket* sock = serv->GetSocket();
4624 if (curtime >= serv->NextPingTime())
4626 if (serv->AnsweredLastPing())
4628 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4629 serv->SetNextPingTime(curtime + 60);
4633 // they didnt answer, boot them
4634 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4635 sock->Squit(serv,"Ping timeout");
4636 ServerInstance->SE->DelFd(sock);
4646 void ConnectServer(Link* x)
4650 /* Do we already have an IP? If so, no need to resolve it. */
4651 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4653 /* Gave a hook, but it wasnt one we know */
4654 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
4657 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()]);
4658 if (newsocket->GetFd() > -1)
4660 /* Handled automatically on success */
4664 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4666 Utils->DoFailOver(x);
4673 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4674 ServerInstance->AddResolver(snr);
4676 catch (ModuleException& e)
4678 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4679 Utils->DoFailOver(x);
4684 void AutoConnectServers(time_t curtime)
4686 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4688 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4690 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4691 x->NextConnectTime = curtime + x->AutoConnect;
4692 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4693 if (x->FailOver.length())
4695 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4698 /* The failover for this server is currently a member of the network.
4699 * The failover probably succeeded, where the main link did not.
4700 * Don't try the main link until the failover is gone again.
4707 // an autoconnected server is not connected. Check if its time to connect it
4708 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4709 this->ConnectServer(&(*x));
4715 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4717 // we've already checked if pcnt > 0, so this is safe
4718 TreeServer* found = Utils->FindServerMask(parameters[0]);
4721 std::string Version = found->GetVersion();
4722 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4723 if (found == Utils->TreeRoot)
4725 std::stringstream out(ServerInstance->Config->data005);
4726 std::string token = "";
4727 std::string line5 = "";
4728 int token_counter = 0;
4733 line5 = line5 + token + " ";
4736 if ((token_counter >= 13) || (out.eof() == true))
4738 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4747 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4752 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4754 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4756 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4758 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4761 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);
4762 ConnectServer(&(*x));
4767 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());
4772 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4776 void BroadcastTimeSync()
4778 std::deque<std::string> params;
4779 params.push_back(ConvToStr(ServerInstance->Time(true)));
4780 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4783 virtual int OnStats(char statschar, userrec* user, string_list &results)
4785 if ((statschar == 'c') || (statschar == 'n'))
4787 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4789 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4790 if (statschar == 'c')
4791 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4793 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4794 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);
4800 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4802 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4806 if (command == "CONNECT")
4808 return this->HandleConnect(parameters,pcnt,user);
4810 else if (command == "STATS")
4812 return this->HandleStats(parameters,pcnt,user);
4814 else if (command == "MOTD")
4816 return this->HandleMotd(parameters,pcnt,user);
4818 else if (command == "ADMIN")
4820 return this->HandleAdmin(parameters,pcnt,user);
4822 else if (command == "SQUIT")
4824 return this->HandleSquit(parameters,pcnt,user);
4826 else if (command == "MAP")
4828 this->HandleMap(parameters,pcnt,user);
4831 else if ((command == "TIME") && (pcnt > 0))
4833 return this->HandleTime(parameters,pcnt,user);
4835 else if (command == "LUSERS")
4837 this->HandleLusers(parameters,pcnt,user);
4840 else if (command == "LINKS")
4842 this->HandleLinks(parameters,pcnt,user);
4845 else if (command == "WHOIS")
4850 return this->HandleRemoteWhois(parameters,pcnt,user);
4853 else if ((command == "VERSION") && (pcnt > 0))
4855 this->HandleVersion(parameters,pcnt,user);
4862 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4864 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4866 // this bit of code cleverly routes all module commands
4867 // to all remote severs *automatically* so that modules
4868 // can just handle commands locally, without having
4869 // to have any special provision in place for remote
4870 // commands and linking protocols.
4871 std::deque<std::string> params;
4873 for (int j = 0; j < pcnt; j++)
4875 if (strchr(parameters[j],' '))
4877 params.push_back(":" + std::string(parameters[j]));
4881 params.push_back(std::string(parameters[j]));
4884 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4885 Utils->DoOneToMany(user->nick,command,params);
4889 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4891 TreeServer* s = Utils->FindServer(servername);
4894 description = s->GetDesc();
4898 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4900 if (IS_LOCAL(source))
4902 std::deque<std::string> params;
4903 params.push_back(dest->nick);
4904 params.push_back(channel->name);
4905 Utils->DoOneToMany(source->nick,"INVITE",params);
4909 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4911 std::deque<std::string> params;
4912 params.push_back(chan->name);
4913 params.push_back(":"+topic);
4914 Utils->DoOneToMany(user->nick,"TOPIC",params);
4917 virtual void OnWallops(userrec* user, const std::string &text)
4921 std::deque<std::string> params;
4922 params.push_back(":"+text);
4923 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4927 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4929 if (target_type == TYPE_USER)
4931 userrec* d = (userrec*)dest;
4932 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4934 std::deque<std::string> params;
4936 params.push_back(d->nick);
4937 params.push_back(":"+text);
4938 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4941 else if (target_type == TYPE_CHANNEL)
4945 chanrec *c = (chanrec*)dest;
4948 std::string cname = c->name;
4950 cname = status + cname;
4951 TreeServerList list;
4952 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4954 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
4956 TreeSocket* Sock = i->second->GetSocket();
4958 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4963 else if (target_type == TYPE_SERVER)
4967 char* target = (char*)dest;
4968 std::deque<std::string> par;
4969 par.push_back(target);
4970 par.push_back(":"+text);
4971 Utils->DoOneToMany(user->nick,"NOTICE",par);
4976 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4978 if (target_type == TYPE_USER)
4980 // route private messages which are targetted at clients only to the server
4981 // which needs to receive them
4982 userrec* d = (userrec*)dest;
4983 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4985 std::deque<std::string> params;
4987 params.push_back(d->nick);
4988 params.push_back(":"+text);
4989 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4992 else if (target_type == TYPE_CHANNEL)
4996 chanrec *c = (chanrec*)dest;
4999 std::string cname = c->name;
5001 cname = status + cname;
5002 TreeServerList list;
5003 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
5005 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
5007 TreeSocket* Sock = i->second->GetSocket();
5009 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
5014 else if (target_type == TYPE_SERVER)
5018 char* target = (char*)dest;
5019 std::deque<std::string> par;
5020 par.push_back(target);
5021 par.push_back(":"+text);
5022 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
5027 virtual void OnBackgroundTimer(time_t curtime)
5029 AutoConnectServers(curtime);
5030 DoPingChecks(curtime);
5033 virtual void OnUserJoin(userrec* user, chanrec* channel)
5035 // Only do this for local users
5038 std::deque<std::string> params;
5040 params.push_back(channel->name);
5041 // set up their permissions and the channel TS with FJOIN.
5042 // All users are FJOINed now, because a module may specify
5043 // new joining permissions for the user.
5045 params.push_back(channel->name);
5046 params.push_back(ConvToStr(channel->age));
5047 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
5048 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
5049 if (channel->GetUserCounter() == 1)
5051 /* First user in, sync the modes for the channel */
5053 /* This is safe, all inspircd servers default to +nt */
5054 params.push_back("+nt");
5055 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
5060 virtual void OnChangeHost(userrec* user, const std::string &newhost)
5062 // only occurs for local clients
5063 if (user->registered != REG_ALL)
5065 std::deque<std::string> params;
5066 params.push_back(newhost);
5067 Utils->DoOneToMany(user->nick,"FHOST",params);
5070 virtual void OnChangeName(userrec* user, const std::string &gecos)
5072 // only occurs for local clients
5073 if (user->registered != REG_ALL)
5075 std::deque<std::string> params;
5076 params.push_back(gecos);
5077 Utils->DoOneToMany(user->nick,"FNAME",params);
5080 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
5084 std::deque<std::string> params;
5085 params.push_back(channel->name);
5086 if (partmessage != "")
5087 params.push_back(":"+partmessage);
5088 Utils->DoOneToMany(user->nick,"PART",params);
5092 virtual void OnUserConnect(userrec* user)
5094 char agestr[MAXBUF];
5097 std::deque<std::string> params;
5098 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
5099 params.push_back(agestr);
5100 params.push_back(user->nick);
5101 params.push_back(user->host);
5102 params.push_back(user->dhost);
5103 params.push_back(user->ident);
5104 params.push_back("+"+std::string(user->FormatModes()));
5105 params.push_back(user->GetIPString());
5106 params.push_back(":"+std::string(user->fullname));
5107 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
5109 // User is Local, change needs to be reflected!
5110 TreeServer* SourceServer = Utils->FindServer(user->server);
5113 SourceServer->AddUserCount();
5119 virtual void OnUserQuit(userrec* user, const std::string &reason)
5121 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5123 std::deque<std::string> params;
5124 params.push_back(":"+reason);
5125 Utils->DoOneToMany(user->nick,"QUIT",params);
5127 // Regardless, We need to modify the user Counts..
5128 TreeServer* SourceServer = Utils->FindServer(user->server);
5131 SourceServer->DelUserCount();
5136 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
5140 std::deque<std::string> params;
5141 params.push_back(user->nick);
5142 Utils->DoOneToMany(oldnick,"NICK",params);
5146 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
5148 if ((source) && (IS_LOCAL(source)))
5150 std::deque<std::string> params;
5151 params.push_back(chan->name);
5152 params.push_back(user->nick);
5153 params.push_back(":"+reason);
5154 Utils->DoOneToMany(source->nick,"KICK",params);
5158 std::deque<std::string> params;
5159 params.push_back(chan->name);
5160 params.push_back(user->nick);
5161 params.push_back(":"+reason);
5162 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
5166 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
5168 std::deque<std::string> params;
5169 params.push_back(dest->nick);
5170 params.push_back(":"+reason);
5171 Utils->DoOneToMany(source->nick,"KILL",params);
5174 virtual void OnRehash(const std::string ¶meter)
5176 if (parameter != "")
5178 std::deque<std::string> params;
5179 params.push_back(parameter);
5180 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
5182 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5184 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
5185 ServerInstance->RehashServer();
5188 Utils->ReadConfiguration(false);
5191 // note: the protocol does not allow direct umode +o except
5192 // via NICK with 8 params. sending OPERTYPE infers +o modechange
5194 virtual void OnOper(userrec* user, const std::string &opertype)
5198 std::deque<std::string> params;
5199 params.push_back(opertype);
5200 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5204 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5208 /* Server-set lines */
5210 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5211 (unsigned long)duration, reason.c_str());
5212 std::deque<std::string> params;
5213 params.push_back(data);
5214 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5218 if (IS_LOCAL(source))
5221 snprintf(type,8,"%cLINE",linetype);
5222 std::string stype = type;
5225 char sduration[MAXBUF];
5226 snprintf(sduration,MAXBUF,"%ld",duration);
5227 std::deque<std::string> params;
5228 params.push_back(host);
5229 params.push_back(sduration);
5230 params.push_back(":"+reason);
5231 Utils->DoOneToMany(source->nick,stype,params);
5235 std::deque<std::string> params;
5236 params.push_back(host);
5237 Utils->DoOneToMany(source->nick,stype,params);
5243 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5245 OnLine(source,hostmask,true,'G',duration,reason);
5248 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5250 OnLine(source,ipmask,true,'Z',duration,reason);
5253 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5255 OnLine(source,nickmask,true,'Q',duration,reason);
5258 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5260 OnLine(source,hostmask,true,'E',duration,reason);
5263 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5265 OnLine(source,hostmask,false,'G',0,"");
5268 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5270 OnLine(source,ipmask,false,'Z',0,"");
5273 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5275 OnLine(source,nickmask,false,'Q',0,"");
5278 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5280 OnLine(source,hostmask,false,'E',0,"");
5283 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5285 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5287 if (target_type == TYPE_USER)
5289 userrec* u = (userrec*)dest;
5290 std::deque<std::string> params;
5291 params.push_back(u->nick);
5292 params.push_back(text);
5293 Utils->DoOneToMany(user->nick,"MODE",params);
5297 chanrec* c = (chanrec*)dest;
5298 std::deque<std::string> params;
5299 params.push_back(c->name);
5300 params.push_back(text);
5301 Utils->DoOneToMany(user->nick,"MODE",params);
5306 virtual void OnSetAway(userrec* user)
5310 std::deque<std::string> params;
5311 params.push_back(":"+std::string(user->awaymsg));
5312 Utils->DoOneToMany(user->nick,"AWAY",params);
5316 virtual void OnCancelAway(userrec* user)
5320 std::deque<std::string> params;
5322 Utils->DoOneToMany(user->nick,"AWAY",params);
5326 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5328 TreeSocket* s = (TreeSocket*)opaque;
5331 if (target_type == TYPE_USER)
5333 userrec* u = (userrec*)target;
5334 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5338 chanrec* c = (chanrec*)target;
5339 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5344 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5346 TreeSocket* s = (TreeSocket*)opaque;
5349 if (target_type == TYPE_USER)
5351 userrec* u = (userrec*)target;
5352 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5354 else if (target_type == TYPE_CHANNEL)
5356 chanrec* c = (chanrec*)target;
5357 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5360 if (target_type == TYPE_OTHER)
5362 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5366 virtual void OnEvent(Event* event)
5368 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5370 if (event->GetEventID() == "send_metadata")
5372 if (params->size() < 3)
5374 (*params)[2] = ":" + (*params)[2];
5375 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5377 else if (event->GetEventID() == "send_topic")
5379 if (params->size() < 2)
5381 (*params)[1] = ":" + (*params)[1];
5382 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5383 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5384 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5386 else if (event->GetEventID() == "send_mode")
5388 if (params->size() < 2)
5390 // Insert the TS value of the object, either userrec or chanrec
5392 userrec* a = ServerInstance->FindNick((*params)[0]);
5399 chanrec* a = ServerInstance->FindChan((*params)[0]);
5405 params->insert(params->begin() + 1,ConvToStr(ourTS));
5406 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5408 else if (event->GetEventID() == "send_mode_explicit")
5410 if (params->size() < 2)
5412 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5414 else if (event->GetEventID() == "send_opers")
5416 if (params->size() < 1)
5418 (*params)[0] = ":" + (*params)[0];
5419 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5421 else if (event->GetEventID() == "send_modeset")
5423 if (params->size() < 2)
5425 (*params)[1] = ":" + (*params)[1];
5426 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5428 else if (event->GetEventID() == "send_snoset")
5430 if (params->size() < 2)
5432 (*params)[1] = ":" + (*params)[1];
5433 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5435 else if (event->GetEventID() == "send_push")
5437 if (params->size() < 2)
5440 userrec *a = ServerInstance->FindNick((*params)[0]);
5445 (*params)[1] = ":" + (*params)[1];
5446 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5450 virtual ~ModuleSpanningTree()
5452 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5453 /* This will also free the listeners */
5456 ServerInstance->Timers->DelTimer(SyncTimer);
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()), Instance(Inst), Module(Mod)
5492 void TimeSyncTimer::Tick(time_t TIME)
5494 Module->BroadcastTimeSync();
5495 Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5496 Instance->Timers->AddTimer(Module->SyncTimer);
5499 void SpanningTreeUtilities::DoFailOver(Link* x)
5501 if (x->FailOver.length())
5503 if (x->FailOver == x->Name)
5505 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());
5508 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5511 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5512 Creator->ConnectServer(TryThisOne);
5516 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5521 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5523 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5525 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5533 class ModuleSpanningTreeFactory : public ModuleFactory
5536 ModuleSpanningTreeFactory()
5540 ~ModuleSpanningTreeFactory()
5544 virtual Module * CreateModule(InspIRCd* Me)
5546 return new ModuleSpanningTree(Me);
5552 extern "C" void * init_module( void )
5554 return new ModuleSpanningTreeFactory;