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"
31 /** If you make a change which breaks the protocol, increment this.
32 * If you completely change the protocol, completely change the number.
34 const long ProtocolVersion = 1101;
37 * The server list in InspIRCd is maintained as two structures
38 * which hold the data in different ways. Most of the time, we
39 * want to very quicky obtain three pieces of information:
41 * (1) The information on a server
42 * (2) The information on the server we must send data through
43 * to actually REACH the server we're after
44 * (3) Potentially, the child/parent objects of this server
46 * The InspIRCd spanning protocol provides easy access to these
47 * by storing the data firstly in a recursive structure, where
48 * each item references its parent item, and a dynamic list
49 * of child items, and another structure which stores the items
50 * hashed, linearly. This means that if we want to find a server
51 * by name quickly, we can look it up in the hash, avoiding
52 * any O(n) lookups. If however, during a split or sync, we want
53 * to apply an operation to a server, and any of its child objects
54 * we can resort to recursion to walk the tree structure.
55 * Any socket can have one of five states at any one time.
56 * The LISTENER state indicates a socket which is listening
57 * for connections. It cannot receive data itself, only incoming
59 * The CONNECTING state indicates an outbound socket which is
60 * waiting to be writeable.
61 * The WAIT_AUTH_1 state indicates the socket is outbound and
62 * has successfully connected, but has not yet sent and received
64 * The WAIT_AUTH_2 state indicates that the socket is inbound
65 * (allocated by a LISTENER) but has not yet sent and received
67 * The CONNECTED state represents a fully authorized, fully
70 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
72 /* Foward declarations */
76 class ModuleSpanningTree;
78 /* This hash_map holds the hash equivalent of the server
79 * tree, used for rapid linear lookups.
81 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
84 /** The Link class might as well be a struct,
85 * but this is C++ and we don't believe in structs (!).
86 * It holds the entire information of one <link>
87 * tag from the main config file. We maintain a list
88 * of them, and populate the list on rehash/load.
90 class Link : public classbase
98 unsigned long AutoConnect;
99 time_t NextConnectTime;
100 std::string EncryptionKey;
101 bool HiddenFromStats;
102 std::string FailOver;
106 /** Contains helper functions and variables for this module,
107 * and keeps them out of the global namespace
109 class SpanningTreeUtilities
114 InspIRCd* ServerInstance;
118 ModuleSpanningTree* Creator;
119 /** Flatten links and /MAP for non-opers
122 /** Hide U-Lined servers in /MAP and /LINKS
125 /** Announce TS changes to channels on merge
127 bool AnnounceTSChange;
128 /** Synchronize timestamps between servers
131 /** Socket bindings for listening sockets
133 std::vector<TreeSocket*> Bindings;
134 /** This variable represents the root of the server tree
136 TreeServer *TreeRoot;
137 /** IPs allowed to link to us
139 std::vector<std::string> ValidIPs;
140 /** Hash of currently connected servers by name
142 server_hash serverlist;
143 /** Holds the data from the <link> tags in the conf
145 std::vector<Link> LinkBlocks;
147 /** Initialise utility class
149 SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator);
150 /** Destroy class and free listeners etc
152 ~SpanningTreeUtilities();
153 /** Send a message from this server to one other local or remote
155 bool DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target);
156 /** Send a message from this server to all but one other, local or remote
158 bool DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit);
159 /** Send a message from this server to all but one other, local or remote
161 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit);
162 /** Send a message from this server to all others
164 bool DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms);
165 /** Send a message from this server to all others
167 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms);
168 /** 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)
170 bool DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms);
171 /** Read the spanningtree module's tags from the config file
173 void ReadConfiguration(bool rebind);
174 /** Add a server to the server list for GetListOfServersForChannel
176 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list);
177 /** Compile a list of servers which contain members of channel c
179 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list);
180 /** Find a server by name
182 TreeServer* FindServer(const std::string &ServerName);
183 /** Find a route to a server by name
185 TreeServer* BestRouteTo(const std::string &ServerName);
186 /** Find a server by glob mask
188 TreeServer* FindServerMask(const std::string &ServerName);
189 /** Returns true if this is a server name we recognise
191 bool IsServer(const std::string &ServerName);
192 /** Attempt to connect to the failover link of link x
194 void DoFailOver(Link* x);
195 /** Find a link tag from a server name
197 Link* FindLink(const std::string& name);
201 /** Each server in the tree is represented by one class of
202 * type TreeServer. A locally connected TreeServer can
203 * have a class of type TreeSocket associated with it, for
204 * remote servers, the TreeSocket entry will be NULL.
205 * Each server also maintains a pointer to its parent
206 * (NULL if this server is ours, at the top of the tree)
207 * and a pointer to its "Route" (see the comments in the
208 * constructors below), and also a dynamic list of pointers
209 * to its children which can be iterated recursively
210 * if required. Creating or deleting objects of type
211 i* TreeServer automatically maintains the hash_map of
212 * TreeServer items, deleting and inserting them as they
213 * are created and destroyed.
215 class TreeServer : public classbase
217 InspIRCd* ServerInstance; /* Creator */
218 TreeServer* Parent; /* Parent entry */
219 TreeServer* Route; /* Route entry */
220 std::vector<TreeServer*> Children; /* List of child objects */
221 irc::string ServerName; /* Server's name */
222 std::string ServerDesc; /* Server's description */
223 std::string VersionString; /* Version string or empty string */
224 int UserCount; /* Not used in this version */
225 int OperCount; /* Not used in this version */
226 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
227 time_t NextPing; /* After this time, the server should be PINGed*/
228 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
229 SpanningTreeUtilities* Utils; /* Utility class */
233 /** We don't use this constructor. Its a dummy, and won't cause any insertion
234 * of the TreeServer into the hash_map. See below for the two we DO use.
236 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance) : ServerInstance(Instance), Utils(Util)
242 UserCount = OperCount = 0;
243 VersionString = ServerInstance->GetVersionString();
246 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
247 * represents our own server. Therefore, it has no route, no parent, and
248 * no socket associated with it. Its version string is our own local version.
250 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util)
254 UserCount = ServerInstance->UserCount();
255 OperCount = ServerInstance->OperCount();
256 VersionString = ServerInstance->GetVersionString();
258 Socket = NULL; /* Fix by brain */
262 /** When we create a new server, we call this constructor to initialize it.
263 * This constructor initializes the server's Route and Parent, and sets up
264 * its ping counters so that it will be pinged one minute from now.
266 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
267 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util)
270 UserCount = OperCount = 0;
271 this->SetNextPingTime(time(NULL) + 60);
274 /* find the 'route' for this server (e.g. the one directly connected
275 * to the local server, which we can use to reach it)
277 * In the following example, consider we have just added a TreeServer
278 * class for server G on our network, of which we are server A.
279 * To route traffic to G (marked with a *) we must send the data to
280 * B (marked with a +) so this algorithm initializes the 'Route'
281 * value to point at whichever server traffic must be routed through
282 * to get here. If we were to try this algorithm with server B,
283 * the Route pointer would point at its own object ('this').
293 * We only run this algorithm when a server is created, as
294 * the routes remain constant while ever the server exists, and
295 * do not need to be re-calculated.
299 if (Route == Utils->TreeRoot)
305 while (this->Route->GetParent() != Utils->TreeRoot)
307 this->Route = Route->GetParent();
311 /* Because recursive code is slow and takes a lot of resources,
312 * we store two representations of the server tree. The first
313 * is a recursive structure where each server references its
314 * children and its parent, which is used for netbursts and
315 * netsplits to dump the whole dataset to the other server,
316 * and the second is used for very fast lookups when routing
317 * messages and is instead a hash_map, where each item can
318 * be referenced by its server name. The AddHashEntry()
319 * call below automatically inserts each TreeServer class
320 * into the hash_map as it is created. There is a similar
321 * maintainance call in the destructor to tidy up deleted
325 this->AddHashEntry();
328 int QuitUsers(const std::string &reason)
330 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
331 const char* reason_s = reason.c_str();
332 std::vector<userrec*> time_to_die;
333 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
335 if (!strcmp(n->second->server, this->ServerName.c_str()))
337 time_to_die.push_back(n->second);
340 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
342 userrec* a = (userrec*)*n;
343 ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
345 userrec::QuitUser(ServerInstance,a,reason_s);
347 return time_to_die.size();
350 /** This method is used to add the structure to the
351 * hash_map for linear searches. It is only called
352 * by the constructors.
356 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
357 if (iter == Utils->serverlist.end())
358 Utils->serverlist[this->ServerName.c_str()] = this;
361 /** This method removes the reference to this object
362 * from the hash_map which is used for linear searches.
363 * It is only called by the default destructor.
367 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
368 if (iter != Utils->serverlist.end())
369 Utils->serverlist.erase(iter);
372 /** These accessors etc should be pretty self-
375 TreeServer* GetRoute()
380 std::string GetName()
382 return ServerName.c_str();
385 std::string GetDesc()
390 std::string GetVersion()
392 return VersionString;
395 void SetNextPingTime(time_t t)
398 LastPingWasGood = false;
401 time_t NextPingTime()
406 bool AnsweredLastPing()
408 return LastPingWasGood;
413 LastPingWasGood = true;
436 TreeSocket* GetSocket()
441 TreeServer* GetParent()
446 void SetVersion(const std::string &Version)
448 VersionString = Version;
451 unsigned int ChildCount()
453 return Children.size();
456 TreeServer* GetChild(unsigned int n)
458 if (n < Children.size())
460 /* Make sure they cant request
461 * an out-of-range object. After
462 * all we know what these programmer
463 * types are like *grin*.
473 void AddChild(TreeServer* Child)
475 Children.push_back(Child);
478 bool DelChild(TreeServer* Child)
480 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
491 /** Removes child nodes of this node, and of that node, etc etc.
492 * This is used during netsplits to automatically tidy up the
493 * server tree. It is slow, we don't use it for much else.
497 bool stillchildren = true;
498 while (stillchildren)
500 stillchildren = false;
501 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
503 TreeServer* s = (TreeServer*)*a;
507 stillchildren = true;
516 /* We'd better tidy up after ourselves, eh? */
517 this->DelHashEntry();
521 /** Yay for fast searches!
522 * This is hundreds of times faster than recursion
523 * or even scanning a linked list, especially when
524 * there are more than a few servers to deal with.
527 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
529 server_hash::iterator iter;
530 iter = serverlist.find(ServerName.c_str());
531 if (iter != serverlist.end())
541 /** Returns the locally connected server we must route a
542 * message through to reach server 'ServerName'. This
543 * only applies to one-to-one and not one-to-many routing.
544 * See the comments for the constructor of TreeServer
547 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
549 if (ServerName.c_str() == TreeRoot->GetName())
551 TreeServer* Found = FindServer(ServerName);
554 return Found->GetRoute();
562 /** Find the first server matching a given glob mask.
563 * Theres no find-using-glob method of hash_map [awwww :-(]
564 * so instead, we iterate over the list using an iterator
565 * and match each one until we get a hit. Yes its slow,
568 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
570 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
572 if (match(i->first.c_str(),ServerName.c_str()))
578 /* A convenient wrapper that returns true if a server exists */
579 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
581 return (FindServer(ServerName) != NULL);
587 class cmd_rconnect : public command_t
590 SpanningTreeUtilities* Utils;
592 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
594 this->source = "m_spanningtree.so";
595 syntax = "<remote-server-mask> <servermask>";
598 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
600 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
601 /* Is this aimed at our server? */
602 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
604 /* Yes, initiate the given connect */
605 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
607 para[0] = parameters[1];
608 std::string original_command = std::string("CONNECT ") + parameters[1];
609 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
620 /** Every SERVER connection inbound or outbound is represented by
621 * an object of type TreeSocket.
622 * TreeSockets, being inherited from InspSocket, can be tied into
623 * the core socket engine, and we cn therefore receive activity events
624 * for them, just like activex objects on speed. (yes really, that
625 * is a technical term!) Each of these which relates to a locally
626 * connected server is assocated with it, by hooking it onto a
627 * TreeSocket class using its constructor. In this way, we can
628 * maintain a list of servers, some of which are directly connected,
629 * some of which are not.
631 class TreeSocket : public InspSocket
633 SpanningTreeUtilities* Utils;
635 std::string in_buffer;
636 ServerState LinkState;
637 std::string InboundServerName;
638 std::string InboundDescription;
640 int num_lost_servers;
642 bool LastPingWasGood;
646 unsigned int keylength;
647 std::string ModuleList;
648 std::map<std::string,std::string> CapKeys;
652 /** Because most of the I/O gubbins are encapsulated within
653 * InspSocket, we just call the superclass constructor for
654 * most of the action, and append a few of our own values
657 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
658 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
661 this->LinkState = LISTENER;
663 this->ctx_out = NULL;
666 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
667 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
670 this->LinkState = CONNECTING;
672 this->ctx_out = NULL;
675 /** When a listening socket gives us a new file descriptor,
676 * we must associate it with a socket without creating a new
677 * connection. This constructor is used for this purpose.
679 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip)
680 : InspSocket(SI, newfd, ip), Utils(Util)
682 this->LinkState = WAIT_AUTH_1;
684 this->ctx_out = NULL;
685 this->SendCapabilities();
696 void InitAES(std::string key,std::string SName)
703 Instance->Log(DEBUG,"Initialized AES key %s",key.c_str());
704 // key must be 16, 24, 32 etc bytes (multiple of 8)
705 keylength = key.length();
706 if (!(keylength == 16 || keylength == 24 || keylength == 32))
708 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
709 Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
713 if (this->GetState() != I_ERROR)
715 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
716 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\
717 \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);
718 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\
719 \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);
724 /** When an outbound connection finishes connecting, we receive
725 * this event, and must send our SERVER string to the other
726 * side. If the other side is happy, as outlined in the server
727 * to server docs on the inspircd.org site, the other side
728 * will then send back its own server string.
730 virtual bool OnConnected()
732 if (this->LinkState == CONNECTING)
734 /* we do not need to change state here. */
735 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
737 if (x->Name == this->myhost)
739 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
740 this->SendCapabilities();
741 if (x->EncryptionKey != "")
743 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
745 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.");
749 this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
750 this->InitAES(x->EncryptionKey,x->Name.c_str());
753 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
754 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
759 /* There is a (remote) chance that between the /CONNECT and the connection
760 * being accepted, some muppet has removed the <link> block and rehashed.
761 * If that happens the connection hangs here until it's closed. Unlikely
762 * and rather harmless.
764 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
768 virtual void OnError(InspSocketError e)
770 /* We don't handle this method, because all our
771 * dirty work is done in OnClose() (see below)
772 * which is still called on error conditions too.
774 if (e == I_ERR_CONNECT)
776 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
777 Link* MyLink = Utils->FindLink(myhost);
779 Utils->DoFailOver(MyLink);
783 virtual int OnDisconnect()
785 /* For the same reason as above, we don't
786 * handle OnDisconnect()
791 /** Recursively send the server tree with distances as hops.
792 * This is used during network burst to inform the other server
793 * (and any of ITS servers too) of what servers we know about.
794 * If at any point any of these servers already exist on the other
795 * end, our connection may be terminated. The hopcounts given
796 * by this function are relative, this doesn't matter so long as
797 * they are all >1, as all the remote servers re-calculate them
798 * to be relative too, with themselves as hop 0.
800 void SendServers(TreeServer* Current, TreeServer* s, int hops)
803 for (unsigned int q = 0; q < Current->ChildCount(); q++)
805 TreeServer* recursive_server = Current->GetChild(q);
806 if (recursive_server != s)
808 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
809 this->WriteLine(command);
810 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
811 /* down to next level */
812 this->SendServers(recursive_server, s, hops+1);
817 std::string MyCapabilities()
819 std::vector<std::string> modlist;
820 std::string capabilities = "";
822 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
824 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
825 modlist.push_back(this->Instance->Config->module_names[i]);
827 sort(modlist.begin(),modlist.end());
828 for (unsigned int i = 0; i < modlist.size(); i++)
831 capabilities = capabilities + ",";
832 capabilities = capabilities + modlist[i];
837 void SendCapabilities()
839 irc::commasepstream modulelist(MyCapabilities());
841 this->WriteLine("CAPAB START");
843 /* Send module names, split at 509 length */
844 std::string item = "*";
845 std::string line = "CAPAB MODULES ";
846 while ((item = modulelist.GetToken()) != "")
848 if (line.length() + item.length() + 1 > 509)
850 this->WriteLine(line);
851 line = "CAPAB MODULES ";
854 if (line != "CAPAB MODULES ")
859 if (line != "CAPAB MODULES ")
860 this->WriteLine(line);
867 #ifdef SUPPORT_IP6LINKS
870 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));
872 this->WriteLine("CAPAB END");
875 /* Check a comma seperated list for an item */
876 bool HasItem(const std::string &list, const std::string &item)
878 irc::commasepstream seplist(list);
880 std::string item2 = "*";
881 while ((item2 = seplist.GetToken()) != "")
890 /* Isolate and return the elements that are different between two comma seperated lists */
891 std::string ListDifference(const std::string &one, const std::string &two)
893 irc::commasepstream list_one(one);
894 std::string item = "*";
895 std::string result = "";
896 while ((item = list_one.GetToken()) != "")
898 if (!HasItem(two, item))
907 bool Capab(const std::deque<std::string> ¶ms)
909 if (params.size() < 1)
911 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
915 if (params[0] == "START")
917 this->ModuleList = "";
918 this->CapKeys.clear();
920 else if (params[0] == "END")
922 std::string reason = "";
924 #ifdef SUPPORT_IP6LINKS
927 /* Compare ModuleList and check CapKeys...
928 * Maybe this could be tidier? -- Brain
930 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
932 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
935 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
939 diff = "this server:" + diff;
941 if (diff.length() == 12)
942 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
944 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
947 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
948 reason = "We don't both support linking to IPV6 servers";
950 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
951 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
953 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
954 reason = "Maximum nickname lengths differ or remote nickname length not specified";
956 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
958 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
960 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
964 reason = "Protocol version not specified";
968 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))))
969 reason = "We don't both have halfop support enabled/disabled identically";
971 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
972 reason = "Maximum ident lengths differ or remote ident length not specified";
974 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
975 reason = "Maximum channel lengths differ or remote channel length not specified";
977 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
978 reason = "Maximum modes per line differ or remote modes per line not specified";
980 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
981 reason = "Maximum quit lengths differ or remote quit length not specified";
983 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
984 reason = "Maximum topic lengths differ or remote topic length not specified";
986 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
987 reason = "Maximum kick lengths differ or remote kick length not specified";
989 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
990 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
992 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
993 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
997 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
1001 else if ((params[0] == "MODULES") && (params.size() == 2))
1003 if (!this->ModuleList.length())
1005 this->ModuleList.append(params[1]);
1009 this->ModuleList.append(",");
1010 this->ModuleList.append(params[1]);
1013 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
1015 irc::tokenstream capabs(params[1]);
1016 std::string item = "*";
1017 while ((item = capabs.GetToken()) != "")
1019 /* Process each key/value pair */
1020 std::string::size_type equals = item.rfind('=');
1021 if (equals != std::string::npos)
1023 std::string var = item.substr(0, equals);
1024 std::string value = item.substr(equals+1, item.length());
1025 this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
1026 CapKeys[var] = value;
1034 /** This function forces this server to quit, removing this server
1035 * and any users on it (and servers and users below that, etc etc).
1036 * It's very slow and pretty clunky, but luckily unless your network
1037 * is having a REAL bad hair day, this function shouldnt be called
1038 * too many times a month ;-)
1040 void SquitServer(std::string &from, TreeServer* Current)
1042 /* recursively squit the servers attached to 'Current'.
1043 * We're going backwards so we don't remove users
1044 * while we still need them ;)
1046 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1048 TreeServer* recursive_server = Current->GetChild(q);
1049 this->SquitServer(from,recursive_server);
1051 /* Now we've whacked the kids, whack self */
1053 num_lost_users += Current->QuitUsers(from);
1056 /** This is a wrapper function for SquitServer above, which
1057 * does some validation first and passes on the SQUIT to all
1058 * other remaining servers.
1060 void Squit(TreeServer* Current, const std::string &reason)
1062 if ((Current) && (Current != Utils->TreeRoot))
1064 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
1065 rmode.Send(Instance);
1067 std::deque<std::string> params;
1068 params.push_back(Current->GetName());
1069 params.push_back(":"+reason);
1070 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1071 if (Current->GetParent() == Utils->TreeRoot)
1073 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1077 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1079 num_lost_servers = 0;
1081 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1082 SquitServer(from, Current);
1084 Current->GetParent()->DelChild(Current);
1086 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1090 Instance->Log(DEFAULT,"Squit from unknown server");
1094 /** FMODE command - server mode with timestamp checks */
1095 bool ForceMode(const std::string &source, std::deque<std::string> ¶ms)
1097 /* Chances are this is a 1.0 FMODE without TS */
1098 if (params.size() < 3)
1100 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
1105 std::string sourceserv;
1107 /* Are we dealing with an FMODE from a user, or from a server? */
1108 userrec* who = this->Instance->FindNick(source);
1111 /* FMODE from a user, set sourceserv to the users server name */
1112 sourceserv = who->server;
1116 /* FMODE from a server, create a fake user to receive mode feedback */
1117 who = new userrec(this->Instance);
1118 who->SetFd(FD_MAGIC_NUMBER);
1119 smode = true; /* Setting this flag tells us we should free the userrec later */
1120 sourceserv = source; /* Set sourceserv to the actual source string */
1122 const char* modelist[64];
1125 memset(&modelist,0,sizeof(modelist));
1126 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1130 /* The timestamp is in this position.
1131 * We don't want to pass that up to the
1132 * server->client protocol!
1134 TS = atoi(params[q].c_str());
1138 /* Everything else is fine to append to the modelist */
1139 modelist[n++] = params[q].c_str();
1143 /* Extract the TS value of the object, either userrec or chanrec */
1144 userrec* dst = this->Instance->FindNick(params[0]);
1145 chanrec* chan = NULL;
1153 chan = this->Instance->FindChan(params[0]);
1159 /* Oops, channel doesnt exist! */
1163 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1168 Instance->Log(DEBUG,"Entering TS equality check");
1169 ModeHandler* mh = NULL;
1170 unsigned long paramptr = 3;
1171 std::string to_bounce = "";
1172 std::string to_keep = "";
1173 std::vector<std::string> params_to_keep;
1174 std::string params_to_bounce = "";
1176 char cur_change = 1;
1177 char old_change = 0;
1178 char old_bounce_change = 0;
1179 /* Merge modes, basically do special stuff to mode with params */
1180 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1193 /* We only care about whats being set,
1194 * not whats being unset
1196 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1198 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1200 /* We only want to do special things to
1201 * modes with parameters, we are going to rewrite
1205 adding ? cur_change = '+' : cur_change = '-';
1207 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1209 /* The mode is set here, check which we should keep */
1212 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1214 if (which_to_keep == true)
1216 /* Keep ours, bounce theirs:
1217 * Send back ours to them and
1218 * drop their mode changs
1220 adding ? cur_change = '+' : cur_change = '-';
1221 if (cur_change != old_bounce_change)
1222 to_bounce += cur_change;
1224 old_bounce_change = cur_change;
1226 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1227 params_to_bounce.append(" ").append(ret.second);
1231 /* Keep theirs: Accept their mode change,
1234 adding ? cur_change = '+' : cur_change = '-';
1235 if (cur_change != old_change)
1236 to_keep += cur_change;
1238 old_change = cur_change;
1240 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1241 params_to_keep.push_back(params[paramptr]);
1246 /* Mode isnt set here, we want it */
1247 adding ? cur_change = '+' : cur_change = '-';
1248 if (cur_change != old_change)
1249 to_keep += cur_change;
1251 old_change = cur_change;
1253 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1254 params_to_keep.push_back(params[paramptr]);
1261 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1265 adding ? cur_change = '+' : cur_change = '-';
1267 /* Just keep this, safe to merge with no checks
1268 * it has no parameters
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()))
1278 Instance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1279 params_to_keep.push_back(params[paramptr++]);
1286 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1290 /* Taking a mode away */
1291 adding ? cur_change = '+' : cur_change = '-';
1293 if (cur_change != old_change)
1294 to_keep += cur_change;
1296 old_change = cur_change;
1298 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1299 params_to_keep.push_back(params[paramptr++]);
1306 if (to_bounce.length())
1308 std::deque<std::string> newparams;
1309 newparams.push_back(params[0]);
1310 newparams.push_back(ConvToStr(ourTS));
1311 newparams.push_back(to_bounce+params_to_bounce);
1312 Instance->Log(DEBUG,"BOUNCE BACK: %s",(to_bounce+params_to_bounce).c_str());
1313 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1316 if (to_keep.length())
1320 modelist[0] = params[0].c_str();
1321 modelist[1] = to_keep.c_str();
1323 if (params_to_keep.size() > 0)
1325 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1327 Instance->Log(DEBUG,"KEEP Item %d of %d: %s", q, params_to_keep.size(), params_to_keep[q].c_str());
1328 modelist[n++] = params_to_keep[q].c_str();
1334 Instance->Log(DEBUG,"Send mode");
1335 this->Instance->SendMode(modelist, n, who);
1339 Instance->Log(DEBUG,"Send mode client");
1340 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1343 /* HOT POTATO! PASS IT ON! */
1344 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1348 /* U-lined servers always win regardless of their TS */
1349 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1351 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1352 * SHOULD accept it, if its clock is right.
1354 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1355 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1356 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1358 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1359 * writing the code. It took me a while to come up with this solution.
1361 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1364 std::deque<std::string> newparams; /* New parameter list we send back */
1365 newparams.push_back(params[0]); /* Target, user or channel */
1366 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1367 newparams.push_back(""); /* This contains the mode string. For now
1368 * it's empty, we fill it below.
1371 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1372 * set to avoid a desync here.
1374 std::string modebounce = "";
1377 ModeHandler* mh = NULL;
1378 char cur_change = 1;
1379 char old_change = 0;
1380 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1382 /* Iterate over all mode chars in the sent set */
1385 /* Adding or subtracting modes? */
1393 /* Find the mode handler for this mode */
1394 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1396 /* Got a mode handler?
1397 * This also prevents us bouncing modes we have no handler for.
1404 /* Does the mode require a parameter right now?
1405 * If it does, fetch it if we can
1407 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1410 /* Call the ModeSet method to determine if its set with the
1411 * given parameter here or not.
1413 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1415 /* XXX: Really. Dont ask.
1416 * Determine from if its set combined with what the current
1417 * 'state' is (adding or not) as to wether we should 'invert'
1418 * or 'reinforce' the mode change
1420 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1422 /* Quickly determine if we have 'flipped' from + to -,
1423 * or - to +, to prevent unneccessary +/- chars in the
1424 * output string that waste bandwidth
1426 if (cur_change != old_change)
1427 modebounce += cur_change;
1428 old_change = cur_change;
1430 /* Add the mode character to the output string */
1431 modebounce += mh->GetModeChar();
1433 /* We got a parameter back from ModeHandler::ModeSet,
1434 * are we supposed to be sending one out right now?
1436 if (ret.second.length())
1438 if (mh->GetNumParams(cur_change == '+') > 0)
1439 /* Yes we're supposed to be sending out
1440 * the parameter. Make sure it goes
1442 newparams.push_back(ret.second);
1450 /* Update the parameters for FMODE with the new 'bounced' string */
1451 newparams[2] = modebounce;
1452 /* Only send it back the way it came, no need to send it anywhere else */
1453 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1454 Instance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1458 Instance->Log(DEBUG,"Allow modes, TS lower for sender");
1459 /* The server was ulined, but something iffy is up with the TS.
1460 * Sound the alarm bells!
1462 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1464 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());
1466 /* Allow the mode, route it to either server or user command handling */
1468 this->Instance->SendMode(modelist,n,who);
1470 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1472 /* HOT POTATO! PASS IT ON! */
1473 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1475 /* Are we supposed to free the userrec? */
1482 /** FTOPIC command */
1483 bool ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
1485 if (params.size() != 4)
1487 time_t ts = atoi(params[1].c_str());
1488 std::string nsource = source;
1490 chanrec* c = this->Instance->FindChan(params[0]);
1493 if ((ts >= c->topicset) || (!*c->topic))
1495 std::string oldtopic = c->topic;
1496 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1497 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1499 /* if the topic text is the same as the current topic,
1500 * dont bother to send the TOPIC command out, just silently
1501 * update the set time and set nick.
1503 if (oldtopic != params[3])
1505 userrec* user = this->Instance->FindNick(source);
1508 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1512 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1513 nsource = user->server;
1515 /* all done, send it on its way */
1516 params[3] = ":" + params[3];
1517 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1526 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1527 bool ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
1529 /* 1.1 FJOIN works as follows:
1531 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1532 * timestamp 'wins'. From this point on we will refer to this side as the
1533 * winner. The side with the higher timestamp loses, from this point on we
1534 * will call this side the loser or losing side. This should be familiar to
1535 * anyone who's dealt with dreamforge or TS6 before.
1537 * When two sides of a split heal and this occurs, the following things
1540 * If the timestamps are exactly equal, both sides merge their privilages
1541 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1542 * re-created during a split, this is safe to do.
1545 * If the timestamps are NOT equal, the losing side removes all privilage
1546 * modes from all of its users that currently exist in the channel, before
1547 * introducing new users into the channel which are listed in the FJOIN
1548 * command's parameters. This means, all modes +ohv, and privilages added
1549 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1550 * of the channel to match that of the winning side, and the modes of the
1551 * users of the winning side are merged in with the losing side. The loser
1552 * then sends out a set of FMODE commands which 'confirm' that it just
1553 * removed all privilage modes from its existing users, which allows for
1554 * services packages to still work correctly without needing to know the
1555 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1556 * a problem, and services packages must contain code which explicitly
1557 * behaves as TS6 does, removing ops from the losing side of a split where
1558 * neccessary within its internal records, as this state information is
1559 * not explicitly echoed out in that protocol.
1561 * The winning side on the other hand will ignore all user modes from the
1562 * losing side, so only its own modes get applied. Life is simple for those
1563 * who succeed at internets. :-)
1565 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1566 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1567 * you ask? Well, quite simply because we don't need to. They'll be sent
1568 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1569 * the losing side sends any modes for the channel which shouldnt win,
1570 * they wont as their timestamp will be too high :-)
1573 if (params.size() < 3)
1576 char first[MAXBUF]; /* The first parameter of the mode command */
1577 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1578 char* mode_users[127]; /* The values used by the mode command */
1579 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1580 mode_users[0] = first; /* Set this up to be our on-stack value */
1581 mode_users[1] = modestring; /* Same here as above */
1582 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1583 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1585 userrec* who = NULL; /* User we are currently checking */
1586 std::string channel = params[0]; /* Channel name, as a string */
1587 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1589 /* Try and find the channel */
1590 chanrec* chan = this->Instance->FindChan(channel);
1592 /* Initialize channel name in the mode parameters */
1593 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1595 /* default TS is a high value, which if we dont have this
1596 * channel will let the other side apply their modes.
1598 time_t ourTS = Instance->Time(true)+600;
1600 /* Does this channel exist? if it does, get its REAL timestamp */
1604 /* In 1.1, if they have the newer channel, we immediately clear
1605 * all status modes from our users. We then accept their modes.
1606 * If WE have the newer channel its the other side's job to do this.
1607 * Note that this causes the losing server to send out confirming
1612 std::deque<std::string> param_list;
1617 /* Lower the TS here */
1618 if (Utils->AnnounceTSChange && chan)
1619 chan->WriteChannelWithServ(Instance->Config->ServerName,
1620 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1623 param_list.push_back(channel);
1624 /* Zap all the privilage modes on our side */
1625 this->RemoveStatus(Instance->Config->ServerName, param_list);
1628 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1629 irc::tokenstream users(params[2]);
1630 std::string item = "*";
1632 /* do this first, so our mode reversals are correctly received by other servers
1633 * if there is a TS collision.
1635 params[2] = ":" + params[2];
1636 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1638 /* Now, process every 'prefixes,nick' pair */
1641 /* Find next user */
1642 item = users.GetToken();
1644 const char* usr = item.c_str();
1646 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1647 * (is this even possible?) */
1650 const char* permissions = usr;
1652 char* nm = new char[MAXBUF];
1655 /* Iterate through all the prefix values, convert them from prefixes
1656 * to mode letters, and append them to the mode sequence
1658 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1660 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1663 /* This is a valid prefix */
1665 *tnm++ = mh->GetModeChar();
1669 /* Not a valid prefix...
1670 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1672 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1673 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1680 /* Null terminate modes */
1682 /* Advance past the comma, to the nick */
1685 /* Check the user actually exists */
1686 who = this->Instance->FindNick(usr);
1689 /* Did they get any modes? How many times? */
1690 strlcat(modestring, nm, MAXBUF);
1691 for (int k = 0; k < ntimes; k++)
1692 mode_users[modectr++] = strdup(usr);
1694 /* Free temporary buffer used for mode sequence */
1697 /* Check that the user's 'direction' is correct
1698 * based on the server sending the FJOIN. We must
1699 * check each nickname in turn, because the origin of
1700 * the FJOIN may be different to the origin of the nicks
1701 * in the command itself.
1703 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1704 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1706 /* Oh dear oh dear. */
1707 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1710 /* Finally, we can actually place the user into the channel.
1711 * We're sure its right. Final answer, phone a friend.
1713 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1715 /* Have we already queued up MAXMODES modes with parameters
1716 * (+qaohv) ready to be sent to the server?
1718 if (modectr >= (MAXMODES-1))
1720 /* Only actually give the users any status if we lost
1721 * the FJOIN or drew (equal timestamps).
1722 * It isn't actually possible for ourTS to be > TS here,
1723 * only possible to actually have ourTS == TS, or
1724 * ourTS < TS, because if we lost, we already lowered
1725 * our TS above before we entered this loop. We only
1726 * check >= as a safety measure, in case someone stuffed
1727 * up. If someone DID stuff up, it was most likely me.
1728 * Note: I do not like baseball bats in the face...
1732 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1733 this->Instance->SendMode((const char**)mode_users,modectr,who);
1735 /* Something stuffed up, and for some reason, the timestamp is
1736 * NOT lowered right now and should be. Lower it. Usually this
1737 * code won't be executed, doubtless someone will remove it some
1742 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1748 /* Reset all this back to defaults, and
1749 * free any ram we have left allocated.
1751 strcpy(mode_users[1],"+");
1752 for (unsigned int f = 2; f < modectr; f++)
1753 free(mode_users[f]);
1759 /* Remember to free this */
1761 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1762 * We don't try to process the nickname here (that WOULD cause a segfault because
1763 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1764 * in case somehow we're desynched, so that other users which might be able to see
1765 * the nickname get their fair chance to process it.
1767 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1773 /* there werent enough modes built up to flush it during FJOIN,
1774 * or, there are a number left over. flush them out.
1776 if ((modectr > 2) && (who) && (chan))
1780 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1781 this->Instance->SendMode((const char**)mode_users,modectr,who);
1782 /* Yet again, we can't actually get a true value here, if everything else
1783 * is working as it should.
1787 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1793 /* Free anything we have left to free */
1794 for (unsigned int f = 2; f < modectr; f++)
1795 free(mode_users[f]);
1798 /* All done. That wasnt so bad was it, you can wipe
1799 * the sweat from your forehead now. :-)
1805 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1807 if (params.size() < 8)
1809 if (params.size() > 8)
1811 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1814 // NICK age nick host dhost ident +modes ip :gecos
1816 time_t age = atoi(params[0].c_str());
1818 /* This used to have a pretty craq'y loop doing the same thing,
1819 * now we just let the STL do the hard work (more efficiently)
1821 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1822 if (pos_after_plus != std::string::npos)
1823 params[5] = params[5].substr(pos_after_plus);
1825 const char* tempnick = params[1].c_str();
1826 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1828 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1830 if (iter != this->Instance->clientlist.end())
1833 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);
1834 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1835 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1839 userrec* _new = new userrec(this->Instance);
1840 this->Instance->clientlist[tempnick] = _new;
1841 _new->SetFd(FD_MAGIC_NUMBER);
1842 strlcpy(_new->nick, tempnick,NICKMAX-1);
1843 strlcpy(_new->host, params[2].c_str(),63);
1844 strlcpy(_new->dhost, params[3].c_str(),63);
1845 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1846 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1847 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1848 _new->registered = REG_ALL;
1851 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1852 _new->modes[(*v)-65] = 1;
1854 #ifdef SUPPORT_IP6LINKS
1855 if (params[6].find_first_of(":") != std::string::npos)
1856 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1859 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1861 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1863 params[7] = ":" + params[7];
1864 Utils->DoOneToAllButSender(source,"NICK",params,source);
1866 // Increment the Source Servers User Count..
1867 TreeServer* SourceServer = Utils->FindServer(source);
1870 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1871 SourceServer->AddUserCount();
1874 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1879 /** Send one or more FJOINs for a channel of users.
1880 * If the length of a single line is more than 480-NICKMAX
1881 * in length, it is split over multiple lines.
1883 void SendFJoins(TreeServer* Current, chanrec* c)
1887 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1889 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1891 size_t dlen, curlen;
1892 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1894 char* ptr = list + dlen;
1896 CUList *ulist = c->GetUsers();
1897 std::string modes = "";
1898 std::string params = "";
1900 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1902 // The first parameter gets a : before it
1903 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1910 if (curlen > (480-NICKMAX))
1912 buffer.append(list).append("\r\n");
1914 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1922 buffer.append(list).append("\r\n");
1924 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1927 params.append(" ").append(b->data);
1929 if (params.length() >= MAXMODES)
1931 /* Wrap at MAXMODES */
1932 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");
1938 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1940 /* Only send these if there are any */
1942 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);
1944 this->WriteLine(buffer);
1947 /** Send G, Q, Z and E lines */
1948 void SendXLines(TreeServer* Current)
1952 std::string n = this->Instance->Config->ServerName;
1953 const char* sn = n.c_str();
1955 /* Yes, these arent too nice looking, but they get the job done */
1956 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1958 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);
1959 buffer.append(data);
1961 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1963 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);
1964 buffer.append(data);
1966 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1968 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);
1969 buffer.append(data);
1971 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1973 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);
1974 buffer.append(data);
1976 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
1978 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);
1979 buffer.append(data);
1981 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
1983 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);
1984 buffer.append(data);
1986 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
1988 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);
1989 buffer.append(data);
1991 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
1993 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);
1994 buffer.append(data);
1997 if (!buffer.empty())
1998 this->WriteLine(buffer);
2001 /** Send channel modes and topics */
2002 void SendChannelModes(TreeServer* Current)
2005 std::deque<std::string> list;
2007 std::string n = this->Instance->Config->ServerName;
2008 const char* sn = n.c_str();
2009 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2011 SendFJoins(Current, c->second);
2012 if (*c->second->topic)
2014 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2015 this->WriteLine(data);
2017 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2019 c->second->GetExtList(list);
2020 for (unsigned int j = 0; j < list.size(); j++)
2022 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2027 /** send all users and their oper state/modes */
2028 void SendUsers(TreeServer* Current)
2031 std::deque<std::string> list;
2032 std::string dataline;
2034 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2036 if (u->second->registered == REG_ALL)
2038 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);
2039 this->WriteLine(data);
2040 if (*u->second->oper)
2042 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2043 this->WriteLine(data);
2045 if (*u->second->awaymsg)
2047 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2048 this->WriteLine(data);
2050 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2052 u->second->GetExtList(list);
2053 for (unsigned int j = 0; j < list.size(); j++)
2055 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2061 /** This function is called when we want to send a netburst to a local
2062 * server. There is a set order we must do this, because for example
2063 * users require their servers to exist, and channels require their
2064 * users to exist. You get the idea.
2066 void DoBurst(TreeServer* s)
2068 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2069 std::string endburst = "ENDBURST";
2070 // Because by the end of the netburst, it could be gone!
2071 std::string name = s->GetName();
2072 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2073 this->WriteLine(burst);
2074 /* send our version string */
2075 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2076 /* Send server tree */
2077 this->SendServers(Utils->TreeRoot,s,1);
2078 /* Send users and their oper status */
2080 /* Send everything else (channel modes, xlines etc) */
2081 this->SendChannelModes(s);
2082 this->SendXLines(s);
2083 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2084 this->WriteLine(endburst);
2085 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2088 /** This function is called when we receive data from a remote
2089 * server. We buffer the data in a std::string (it doesnt stay
2090 * there for long), reading using InspSocket::Read() which can
2091 * read up to 16 kilobytes in one operation.
2093 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2094 * THE SOCKET OBJECT FOR US.
2096 virtual bool OnDataReady()
2098 char* data = this->Read();
2099 /* Check that the data read is a valid pointer and it has some content */
2102 this->in_buffer.append(data);
2103 /* While there is at least one new line in the buffer,
2104 * do something useful (we hope!) with it.
2106 while (in_buffer.find("\n") != std::string::npos)
2108 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2109 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2110 /* Use rfind here not find, as theres more
2111 * chance of the \r being near the end of the
2112 * string, not the start.
2114 if (ret.find("\r") != std::string::npos)
2115 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2116 /* Process this one, abort if it
2117 * didnt return true.
2123 memset(result,0,1024);
2125 /* ERROR + CAPAB is still allowed unencryped */
2126 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2128 int nbytes = from64tobits(out, ret.c_str(), 1024);
2129 if ((nbytes > 0) && (nbytes < 1024))
2131 ctx_in->Decrypt(out, result, nbytes, 0);
2132 for (int t = 0; t < nbytes; t++)
2134 if (result[t] == '\7')
2136 /* We only need to stick a \0 on the
2137 * first \7, the rest will be lost
2147 if (!this->ProcessLine(ret))
2154 /* EAGAIN returns an empty but non-NULL string, so this
2155 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2157 return (data && !*data);
2160 int WriteLine(std::string line)
2162 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2166 char result64[10240];
2167 if (this->keylength)
2169 // pad it to the key length
2170 int n = this->keylength - (line.length() % this->keylength);
2172 line.append(n,'\7');
2174 unsigned int ll = line.length();
2175 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2176 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2179 line.append("\r\n");
2180 return this->Write(line);
2183 /* Handle ERROR command */
2184 bool Error(std::deque<std::string> ¶ms)
2186 if (params.size() < 1)
2188 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2189 /* we will return false to cause the socket to close. */
2193 /** remote MOTD. leet, huh? */
2194 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2196 if (params.size() > 0)
2198 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2200 /* It's for our server */
2201 string_list results;
2202 userrec* source = this->Instance->FindNick(prefix);
2206 std::deque<std::string> par;
2207 par.push_back(prefix);
2210 if (!Instance->Config->MOTD.size())
2212 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2213 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2217 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2218 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2220 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2222 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2223 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2226 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2227 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2233 userrec* source = this->Instance->FindNick(prefix);
2235 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2241 /** remote ADMIN. leet, huh? */
2242 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2244 if (params.size() > 0)
2246 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2248 /* It's for our server */
2249 string_list results;
2250 userrec* source = this->Instance->FindNick(prefix);
2254 std::deque<std::string> par;
2255 par.push_back(prefix);
2258 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2259 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2261 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2262 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2264 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2265 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2267 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2268 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2274 userrec* source = this->Instance->FindNick(prefix);
2276 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2282 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2284 /* Get the reply to a STATS query if it matches this servername,
2285 * and send it back as a load of PUSH queries
2287 if (params.size() > 1)
2289 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2291 /* It's for our server */
2292 string_list results;
2293 userrec* source = this->Instance->FindNick(prefix);
2296 std::deque<std::string> par;
2297 par.push_back(prefix);
2299 DoStats(this->Instance, *(params[0].c_str()), source, results);
2300 for (size_t i = 0; i < results.size(); i++)
2302 par[1] = "::" + results[i];
2303 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2310 userrec* source = this->Instance->FindNick(prefix);
2312 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2319 /** Because the core won't let users or even SERVERS set +o,
2320 * we use the OPERTYPE command to do this.
2322 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2324 if (params.size() != 1)
2326 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2329 std::string opertype = params[0];
2330 userrec* u = this->Instance->FindNick(prefix);
2333 u->modes[UM_OPERATOR] = 1;
2334 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2335 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2340 /** Because Andy insists that services-compatible servers must
2341 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2343 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2345 if (params.size() < 3)
2348 userrec* u = this->Instance->FindNick(params[0]);
2352 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2355 std::deque<std::string> par;
2356 par.push_back(params[1]);
2357 /* This is not required as one is sent in OnUserPostNick below
2359 //Utils->DoOneToMany(u->nick,"NICK",par);
2360 if (!u->ForceNickChange(params[1].c_str()))
2362 userrec::QuitUser(this->Instance, u, "Nickname collision");
2365 u->age = atoi(params[2].c_str());
2371 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2373 if (params.size() < 2)
2376 userrec* u = this->Instance->FindNick(params[0]);
2380 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2381 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2386 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2388 if (params.size() < 1)
2391 std::string servermask = params[0];
2393 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2395 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2396 this->Instance->RehashServer();
2397 Utils->ReadConfiguration(false);
2398 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2400 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2404 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2406 if (params.size() != 2)
2409 std::string nick = params[0];
2410 userrec* u = this->Instance->FindNick(prefix);
2411 userrec* who = this->Instance->FindNick(nick);
2415 /* Prepend kill source, if we don't have one */
2416 std::string sourceserv = prefix;
2419 sourceserv = u->server;
2421 if (*(params[1].c_str()) != '[')
2423 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2425 std::string reason = params[1];
2426 params[1] = ":" + params[1];
2427 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2428 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2429 userrec::QuitUser(this->Instance,who,reason);
2434 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2436 if (params.size() < 1)
2439 if (params.size() == 1)
2441 TreeServer* ServerSource = Utils->FindServer(prefix);
2444 ServerSource->SetPingFlag();
2449 std::string forwardto = params[1];
2450 if (forwardto == this->Instance->Config->ServerName)
2453 * this is a PONG for us
2454 * if the prefix is a user, check theyre local, and if they are,
2455 * dump the PONG reply back to their fd. If its a server, do nowt.
2456 * Services might want to send these s->s, but we dont need to yet.
2458 userrec* u = this->Instance->FindNick(prefix);
2462 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2467 // not for us, pass it on :)
2468 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2475 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2477 if (params.size() < 3)
2480 TreeServer* ServerSource = Utils->FindServer(prefix);
2484 if (params[0] == "*")
2486 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2488 else if (*(params[0].c_str()) == '#')
2490 chanrec* c = this->Instance->FindChan(params[0]);
2493 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2496 else if (*(params[0].c_str()) != '#')
2498 userrec* u = this->Instance->FindNick(params[0]);
2501 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2506 params[2] = ":" + params[2];
2507 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2511 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2513 if (params.size() < 1)
2516 TreeServer* ServerSource = Utils->FindServer(prefix);
2520 ServerSource->SetVersion(params[0]);
2522 params[0] = ":" + params[0];
2523 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2527 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2529 if (params.size() < 1)
2532 userrec* u = this->Instance->FindNick(prefix);
2536 u->ChangeDisplayedHost(params[0].c_str());
2537 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2542 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2544 if (params.size() < 6)
2547 bool propogate = false;
2549 switch (*(params[0].c_str()))
2552 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2553 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2556 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2557 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2560 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2561 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2564 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2565 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2568 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2571 /* Just in case... */
2572 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2577 /* Send it on its way */
2580 if (atoi(params[4].c_str()))
2582 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());
2586 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());
2588 params[5] = ":" + params[5];
2589 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2591 if (!this->bursting)
2593 Instance->Log(DEBUG,"Applying lines...");
2594 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2599 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2601 if (params.size() < 1)
2604 userrec* u = this->Instance->FindNick(prefix);
2608 u->ChangeName(params[0].c_str());
2609 params[0] = ":" + params[0];
2610 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2615 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2617 if (params.size() < 1)
2620 Instance->Log(DEBUG,"In IDLE command");
2621 userrec* u = this->Instance->FindNick(prefix);
2625 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2626 // an incoming request
2627 if (params.size() == 1)
2629 userrec* x = this->Instance->FindNick(params[0]);
2630 if ((x) && (IS_LOCAL(x)))
2632 userrec* x = this->Instance->FindNick(params[0]);
2633 char signon[MAXBUF];
2636 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2637 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2638 std::deque<std::string> par;
2639 par.push_back(prefix);
2640 par.push_back(signon);
2641 par.push_back(idle);
2642 // ours, we're done, pass it BACK
2643 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2647 // not ours pass it on
2648 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2651 else if (params.size() == 3)
2653 std::string who_did_the_whois = params[0];
2654 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2655 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2657 // an incoming reply to a whois we sent out
2658 std::string nick_whoised = prefix;
2659 unsigned long signon = atoi(params[1].c_str());
2660 unsigned long idle = atoi(params[2].c_str());
2661 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2662 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2666 // not ours, pass it on
2667 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2674 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2676 if (params.size() < 2)
2679 userrec* u = this->Instance->FindNick(params[0]);
2686 u->Write(params[1]);
2690 // continue the raw onwards
2691 params[1] = ":" + params[1];
2692 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2697 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2699 if (!params.size() || !Utils->EnableTimeSync)
2704 if ((params.size() == 2) && (params[1] == "FORCE"))
2707 time_t rts = atoi(params[0].c_str());
2708 time_t us = Instance->Time(true);
2712 Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2714 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2716 else if (force || (rts < us))
2718 int old = Instance->SetTimeDelta(rts - us);
2719 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2721 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2725 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2727 std::deque<std::string> oparams;
2728 oparams.push_back(ConvToStr(us));
2730 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2736 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2738 // :source.server TIME remote.server sendernick
2739 // :remote.server TIME source.server sendernick TS
2740 if (params.size() == 2)
2742 // someone querying our time?
2743 if (this->Instance->Config->ServerName == params[0])
2745 userrec* u = this->Instance->FindNick(params[1]);
2748 params.push_back(ConvToStr(Instance->Time(false)));
2750 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2755 // not us, pass it on
2756 userrec* u = this->Instance->FindNick(params[1]);
2758 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2761 else if (params.size() == 3)
2763 // a response to a previous TIME
2764 userrec* u = this->Instance->FindNick(params[1]);
2765 if ((u) && (IS_LOCAL(u)))
2767 time_t rawtime = atol(params[2].c_str());
2768 struct tm * timeinfo;
2769 timeinfo = localtime(&rawtime);
2771 snprintf(tms,26,"%s",asctime(timeinfo));
2773 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2778 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2784 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2786 if (params.size() < 1)
2789 if (params.size() == 1)
2791 std::string stufftobounce = params[0];
2792 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2797 std::string forwardto = params[1];
2798 if (forwardto == this->Instance->Config->ServerName)
2800 // this is a ping for us, send back PONG to the requesting server
2801 params[1] = params[0];
2802 params[0] = forwardto;
2803 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2807 // not for us, pass it on :)
2808 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2814 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2816 if (params.size() < 1)
2819 chanrec* c = Instance->FindChan(params[0]);
2823 irc::modestacker modestack(false);
2824 CUList *ulist = c->GetUsers();
2826 std::deque<std::string> stackresult;
2829 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2831 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2832 if (modesequence.length())
2834 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2835 irc::spacesepstream sep(modesequence);
2836 std::string modeletters = sep.GetToken();
2837 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2839 while (!modeletters.empty())
2841 char mletter = *(modeletters.begin());
2842 modestack.Push(mletter,sep.GetToken());
2843 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2844 modeletters.erase(modeletters.begin());
2845 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2850 while (modestack.GetStackedLine(stackresult))
2852 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2853 stackresult.push_front(ConvToStr(c->age));
2854 stackresult.push_front(c->name);
2855 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2856 stackresult.erase(stackresult.begin() + 1);
2857 Instance->Log(DEBUG,"Stacked items:");
2858 for (size_t z = 0; z < stackresult.size(); z++)
2860 y[z] = stackresult[z].c_str();
2861 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2863 userrec* n = new userrec(Instance);
2864 n->SetFd(FD_MAGIC_NUMBER);
2865 Instance->SendMode(y, stackresult.size(), n);
2872 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2874 if (params.size() < 4)
2877 std::string servername = params[0];
2878 std::string password = params[1];
2879 // hopcount is not used for a remote server, we calculate this ourselves
2880 std::string description = params[3];
2881 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2885 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2888 TreeServer* CheckDupe = Utils->FindServer(servername);
2891 this->WriteLine("ERROR :Server "+servername+" already exists!");
2892 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2895 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2896 ParentOfThis->AddChild(Node);
2897 params[3] = ":" + params[3];
2898 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2899 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2903 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2905 if (params.size() < 4)
2908 irc::string servername = params[0].c_str();
2909 std::string sname = params[0];
2910 std::string password = params[1];
2911 int hops = atoi(params[2].c_str());
2915 this->WriteLine("ERROR :Server too far away for authentication");
2916 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2919 std::string description = params[3];
2920 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2922 if ((x->Name == servername) && (x->RecvPass == password))
2924 TreeServer* CheckDupe = Utils->FindServer(sname);
2927 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2928 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2931 // Begin the sync here. this kickstarts the
2932 // other side, waiting in WAIT_AUTH_2 state,
2933 // into starting their burst, as it shows
2934 // that we're happy.
2935 this->LinkState = CONNECTED;
2936 // we should add the details of this server now
2937 // to the servers tree, as a child of the root
2939 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2940 Utils->TreeRoot->AddChild(Node);
2941 params[3] = ":" + params[3];
2942 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2943 this->bursting = true;
2944 this->DoBurst(Node);
2948 this->WriteLine("ERROR :Invalid credentials");
2949 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2953 bool Inbound_Server(std::deque<std::string> ¶ms)
2955 if (params.size() < 4)
2958 irc::string servername = params[0].c_str();
2959 std::string sname = params[0];
2960 std::string password = params[1];
2961 int hops = atoi(params[2].c_str());
2965 this->WriteLine("ERROR :Server too far away for authentication");
2966 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2969 std::string description = params[3];
2970 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2972 if ((x->Name == servername) && (x->RecvPass == password))
2974 TreeServer* CheckDupe = Utils->FindServer(sname);
2977 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2978 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2981 /* If the config says this link is encrypted, but the remote side
2982 * hasnt bothered to send the AES command before SERVER, then we
2983 * boot them off as we MUST have this connection encrypted.
2985 if ((x->EncryptionKey != "") && (!this->ctx_in))
2987 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2988 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2991 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2992 this->InboundServerName = sname;
2993 this->InboundDescription = description;
2994 // this is good. Send our details: Our server name and description and hopcount of 0,
2995 // along with the sendpass from this block.
2996 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2997 // move to the next state, we are now waiting for THEM.
2998 this->LinkState = WAIT_AUTH_2;
3002 this->WriteLine("ERROR :Invalid credentials");
3003 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3007 void Split(const std::string &line, std::deque<std::string> &n)
3010 irc::tokenstream tokens(line);
3012 while ((param = tokens.GetToken()) != "")
3017 bool ProcessLine(std::string &line)
3019 std::deque<std::string> params;
3020 irc::string command;
3026 line = line.substr(0, line.find_first_of("\r\n"));
3028 Instance->Log(DEBUG,"IN: %s", line.c_str());
3030 this->Split(line.c_str(),params);
3032 if ((params[0][0] == ':') && (params.size() > 1))
3034 prefix = params[0].substr(1);
3038 command = params[0].c_str();
3041 if ((!this->ctx_in) && (command == "AES"))
3043 std::string sserv = params[0];
3044 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3046 if ((x->EncryptionKey != "") && (x->Name == sserv))
3048 this->InitAES(x->EncryptionKey,sserv);
3054 else if ((this->ctx_in) && (command == "AES"))
3056 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());
3059 switch (this->LinkState)
3064 // Waiting for SERVER command from remote server. Server initiating
3065 // the connection sends the first SERVER command, listening server
3066 // replies with theirs if its happy, then if the initiator is happy,
3067 // it starts to send its net sync, which starts the merge, otherwise
3068 // it sends an ERROR.
3069 if (command == "PASS")
3071 /* Silently ignored */
3073 else if (command == "SERVER")
3075 return this->Inbound_Server(params);
3077 else if (command == "ERROR")
3079 return this->Error(params);
3081 else if (command == "USER")
3083 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3086 else if (command == "CAPAB")
3088 return this->Capab(params);
3090 else if ((command == "U") || (command == "S"))
3092 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3097 std::string error("ERROR :Invalid command in negotiation phase: ");
3098 error.append(command.c_str());
3099 this->WriteLine(error);
3104 // Waiting for start of other side's netmerge to say they liked our
3106 if (command == "SERVER")
3108 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3112 else if ((command == "U") || (command == "S"))
3114 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3117 else if (command == "BURST")
3119 if (params.size() && Utils->EnableTimeSync)
3121 /* If a time stamp is provided, apply synchronization */
3123 time_t them = atoi(params[0].c_str());
3124 time_t us = Instance->Time(true);
3125 int delta = them - us;
3127 if ((params.size() == 2) && (params[1] == "FORCE"))
3130 if ((delta < -600) || (delta > 600))
3132 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));
3133 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3139 this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3141 else if (force || (us > them))
3143 this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3144 this->Instance->SetTimeDelta(them - us);
3145 // Send this new timestamp to any other servers
3146 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3150 // Override the timestamp
3151 this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3152 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3155 this->LinkState = CONNECTED;
3156 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3157 Utils->TreeRoot->AddChild(Node);
3159 params.push_back(InboundServerName);
3160 params.push_back("*");
3161 params.push_back("1");
3162 params.push_back(":"+InboundDescription);
3163 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3164 this->bursting = true;
3165 this->DoBurst(Node);
3167 else if (command == "ERROR")
3169 return this->Error(params);
3171 else if (command == "CAPAB")
3173 return this->Capab(params);
3178 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3182 if (command == "SERVER")
3184 // another server we connected to, which was in WAIT_AUTH_1 state,
3185 // has just sent us their credentials. If we get this far, theyre
3186 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3187 // if we're happy with this, we should send our netburst which
3188 // kickstarts the merge.
3189 return this->Outbound_Reply_Server(params);
3191 else if (command == "ERROR")
3193 return this->Error(params);
3197 // This is the 'authenticated' state, when all passwords
3198 // have been exchanged and anything past this point is taken
3203 std::string direction = prefix;
3204 userrec* t = this->Instance->FindNick(prefix);
3207 direction = t->server;
3209 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3210 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3212 if (route_back_again)
3213 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3218 * When there is activity on the socket, reset the ping counter so
3219 * that we're not wasting bandwidth pinging an active server.
3221 route_back_again->SetNextPingTime(time(NULL) + 60);
3222 route_back_again->SetPingFlag();
3225 if (command == "SVSMODE")
3227 /* Services expects us to implement
3228 * SVSMODE. In inspircd its the same as
3233 std::string target = "";
3234 /* Yes, know, this is a mess. Its reasonably fast though as we're
3235 * working with std::string here.
3237 if ((command == "NICK") && (params.size() > 1))
3239 return this->IntroduceClient(prefix,params);
3241 else if (command == "FJOIN")
3243 return this->ForceJoin(prefix,params);
3245 else if (command == "STATS")
3247 return this->Stats(prefix, params);
3249 else if (command == "MOTD")
3251 return this->Motd(prefix, params);
3253 else if (command == "ADMIN")
3255 return this->Admin(prefix, params);
3257 else if (command == "SERVER")
3259 return this->RemoteServer(prefix,params);
3261 else if (command == "ERROR")
3263 return this->Error(params);
3265 else if (command == "OPERTYPE")
3267 return this->OperType(prefix,params);
3269 else if (command == "FMODE")
3271 return this->ForceMode(prefix,params);
3273 else if (command == "KILL")
3275 return this->RemoteKill(prefix,params);
3277 else if (command == "FTOPIC")
3279 return this->ForceTopic(prefix,params);
3281 else if (command == "REHASH")
3283 return this->RemoteRehash(prefix,params);
3285 else if (command == "METADATA")
3287 return this->MetaData(prefix,params);
3289 else if (command == "REMSTATUS")
3291 return this->RemoveStatus(prefix,params);
3293 else if (command == "PING")
3296 * We just got a ping from a server that's bursting.
3297 * This can't be right, so set them to not bursting, and
3298 * apply their lines.
3302 this->bursting = false;
3303 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3307 prefix = this->GetName();
3309 return this->LocalPing(prefix,params);
3311 else if (command == "PONG")
3314 * We just got a pong from a server that's bursting.
3315 * This can't be right, so set them to not bursting, and
3316 * apply their lines.
3320 this->bursting = false;
3321 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3325 prefix = this->GetName();
3327 return this->LocalPong(prefix,params);
3329 else if (command == "VERSION")
3331 return this->ServerVersion(prefix,params);
3333 else if (command == "FHOST")
3335 return this->ChangeHost(prefix,params);
3337 else if (command == "FNAME")
3339 return this->ChangeName(prefix,params);
3341 else if (command == "ADDLINE")
3343 return this->AddLine(prefix,params);
3345 else if (command == "SVSNICK")
3349 prefix = this->GetName();
3351 return this->ForceNick(prefix,params);
3353 else if (command == "IDLE")
3355 return this->Whois(prefix,params);
3357 else if (command == "PUSH")
3359 return this->Push(prefix,params);
3361 else if (command == "TIMESET")
3363 return this->HandleSetTime(prefix, params);
3365 else if (command == "TIME")
3367 return this->Time(prefix,params);
3369 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3371 std::string sourceserv = this->myhost;
3372 if (params.size() == 3)
3374 userrec* user = this->Instance->FindNick(params[1]);
3375 chanrec* chan = this->Instance->FindChan(params[0]);
3378 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3379 /* Yikes, the channels gone! */
3383 if (this->InboundServerName != "")
3385 sourceserv = this->InboundServerName;
3387 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3389 else if (command == "SVSJOIN")
3393 prefix = this->GetName();
3395 return this->ServiceJoin(prefix,params);
3397 else if (command == "SQUIT")
3399 if (params.size() == 2)
3401 this->Squit(Utils->FindServer(params[0]),params[1]);
3405 else if (command == "ENDBURST")
3407 this->bursting = false;
3408 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3409 std::string sourceserv = this->myhost;
3410 if (this->InboundServerName != "")
3412 sourceserv = this->InboundServerName;
3414 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3416 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3417 rmode.Send(Instance);
3423 // not a special inter-server command.
3424 // Emulate the actual user doing the command,
3425 // this saves us having a huge ugly parser.
3426 userrec* who = this->Instance->FindNick(prefix);
3427 std::string sourceserv = this->myhost;
3428 if (this->InboundServerName != "")
3430 sourceserv = this->InboundServerName;
3434 if ((command == "NICK") && (params.size() > 0))
3436 /* On nick messages, check that the nick doesnt
3437 * already exist here. If it does, kill their copy,
3440 userrec* x = this->Instance->FindNick(params[0]);
3441 if ((x) && (x != who))
3443 std::deque<std::string> p;
3444 p.push_back(params[0]);
3445 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3446 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3448 p.push_back(prefix);
3449 p.push_back("Nickname collision");
3450 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3451 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3452 userrec* y = this->Instance->FindNick(prefix);
3455 userrec::QuitUser(this->Instance,y,"Nickname collision");
3457 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3461 target = who->server;
3462 const char* strparams[127];
3463 for (unsigned int q = 0; q < params.size(); q++)
3465 strparams[q] = params[q].c_str();
3467 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3470 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3477 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3483 // its not a user. Its either a server, or somethings screwed up.
3484 if (Utils->IsServer(prefix))
3486 target = this->Instance->Config->ServerName;
3490 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3494 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3503 virtual std::string GetName()
3505 std::string sourceserv = this->myhost;
3506 if (this->InboundServerName != "")
3508 sourceserv = this->InboundServerName;
3513 virtual void OnTimeout()
3515 if (this->LinkState == CONNECTING)
3517 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3518 Link* MyLink = Utils->FindLink(myhost);
3520 Utils->DoFailOver(MyLink);
3524 virtual void OnClose()
3526 // Connection closed.
3527 // If the connection is fully up (state CONNECTED)
3528 // then propogate a netsplit to all peers.
3529 std::string quitserver = this->myhost;
3530 if (this->InboundServerName != "")
3532 quitserver = this->InboundServerName;
3534 TreeServer* s = Utils->FindServer(quitserver);
3537 Squit(s,"Remote host closed the connection");
3540 if (quitserver != "")
3541 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3544 virtual int OnIncomingConnection(int newsock, char* ip)
3546 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3547 * or discovering if this port is the server port, we don't allow connections from any
3548 * IPs for which we don't have a link block.
3552 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3555 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3556 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3561 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3566 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3567 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3572 /** This class is used to resolve server hostnames during /connect and autoconnect.
3573 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3574 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3575 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3576 * will have an IP address which we can then use to continue our connection.
3578 class ServernameResolver : public Resolver
3581 /** A copy of the Link tag info for what we're connecting to.
3582 * We take a copy, rather than using a pointer, just in case the
3583 * admin takes the tag away and rehashes while the domain is resolving.
3586 SpanningTreeUtilities* Utils;
3588 ServernameResolver(SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(Util)
3590 /* Nothing in here, folks */
3593 void OnLookupComplete(const std::string &result)
3595 /* Initiate the connection, now that we have an IP to use.
3596 * Passing a hostname directly to InspSocket causes it to
3597 * just bail and set its FD to -1.
3599 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3600 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3602 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
3603 if (newsocket->GetFd() > -1)
3609 /* Something barfed, show the opers */
3610 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3612 Utils->DoFailOver(&MyLink);
3617 void OnError(ResolverError e, const std::string &errormessage)
3620 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3621 Utils->DoFailOver(&MyLink);
3625 /** Handle resolving of server IPs for the cache
3627 class SecurityIPResolver : public Resolver
3631 SpanningTreeUtilities* Utils;
3633 SecurityIPResolver(SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(U)
3637 void OnLookupComplete(const std::string &result)
3639 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3640 Utils->ValidIPs.push_back(result);
3643 void OnError(ResolverError e, const std::string &errormessage)
3645 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3649 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3652 this->ReadConfiguration(true);
3653 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3656 SpanningTreeUtilities::~SpanningTreeUtilities()
3658 for (unsigned int i = 0; i < Bindings.size(); i++)
3660 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3661 ServerInstance->SE->DelFd(Bindings[i]);
3662 Bindings[i]->Close();
3663 DELETE(Bindings[i]);
3665 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3666 while (TreeRoot->ChildCount())
3668 TreeServer* child_server = TreeRoot->GetChild(0);
3669 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3672 TreeSocket* sock = child_server->GetSocket();
3673 ServerInstance->SE->DelFd(sock);
3681 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3683 for (unsigned int c = 0; c < list.size(); c++)
3685 if (list[c] == server)
3690 list.push_back(server);
3693 /** returns a list of DIRECT servernames for a specific channel */
3694 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3696 CUList *ulist = c->GetUsers();
3697 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3699 if (i->second->GetFd() < 0)
3701 TreeServer* best = this->BestRouteTo(i->second->server);
3703 AddThisServer(best,list);
3709 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3711 TreeServer* omitroute = this->BestRouteTo(omit);
3712 if ((command == "NOTICE") || (command == "PRIVMSG"))
3714 if (params.size() >= 2)
3717 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3719 params[0] = params[0].substr(1, params[0].length()-1);
3721 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3723 // special routing for private messages/notices
3724 userrec* d = ServerInstance->FindNick(params[0]);
3727 std::deque<std::string> par;
3728 par.push_back(params[0]);
3729 par.push_back(":"+params[1]);
3730 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3734 else if (*(params[0].c_str()) == '$')
3736 std::deque<std::string> par;
3737 par.push_back(params[0]);
3738 par.push_back(":"+params[1]);
3739 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3744 chanrec* c = ServerInstance->FindChan(params[0]);
3747 std::deque<TreeServer*> list;
3748 GetListOfServersForChannel(c,list);
3749 unsigned int lsize = list.size();
3750 for (unsigned int i = 0; i < lsize; i++)
3752 TreeSocket* Sock = list[i]->GetSocket();
3753 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3755 Sock->WriteLine(data);
3763 unsigned int items =this->TreeRoot->ChildCount();
3764 for (unsigned int x = 0; x < items; x++)
3766 TreeServer* Route = this->TreeRoot->GetChild(x);
3767 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3769 TreeSocket* Sock = Route->GetSocket();
3771 Sock->WriteLine(data);
3777 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
3779 TreeServer* omitroute = this->BestRouteTo(omit);
3780 std::string FullLine = ":" + prefix + " " + command;
3781 unsigned int words = params.size();
3782 for (unsigned int x = 0; x < words; x++)
3784 FullLine = FullLine + " " + params[x];
3786 unsigned int items = this->TreeRoot->ChildCount();
3787 for (unsigned int x = 0; x < items; x++)
3789 TreeServer* Route = this->TreeRoot->GetChild(x);
3790 // Send the line IF:
3791 // The route has a socket (its a direct connection)
3792 // The route isnt the one to be omitted
3793 // The route isnt the path to the one to be omitted
3794 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3796 TreeSocket* Sock = Route->GetSocket();
3798 Sock->WriteLine(FullLine);
3804 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
3806 std::string FullLine = ":" + prefix + " " + command;
3807 unsigned int words = params.size();
3808 for (unsigned int x = 0; x < words; x++)
3810 FullLine = FullLine + " " + params[x];
3812 unsigned int items = this->TreeRoot->ChildCount();
3813 for (unsigned int x = 0; x < items; x++)
3815 TreeServer* Route = this->TreeRoot->GetChild(x);
3816 if (Route && Route->GetSocket())
3818 TreeSocket* Sock = Route->GetSocket();
3820 Sock->WriteLine(FullLine);
3826 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3828 std::string spfx = prefix;
3829 std::string scmd = command;
3830 return this->DoOneToMany(spfx, scmd, params);
3833 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3835 std::string spfx = prefix;
3836 std::string scmd = command;
3837 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3840 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
3842 TreeServer* Route = this->BestRouteTo(target);
3845 std::string FullLine = ":" + prefix + " " + command;
3846 unsigned int words = params.size();
3847 for (unsigned int x = 0; x < words; x++)
3849 FullLine = FullLine + " " + params[x];
3851 if (Route && Route->GetSocket())
3853 TreeSocket* Sock = Route->GetSocket();
3855 Sock->WriteLine(FullLine);
3865 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3867 ConfigReader* Conf = new ConfigReader(ServerInstance);
3870 for (int j =0; j < Conf->Enumerate("bind"); j++)
3872 std::string Type = Conf->ReadValue("bind","type",j);
3873 std::string IP = Conf->ReadValue("bind","address",j);
3874 int Port = Conf->ReadInteger("bind","port",j,true);
3875 if (Type == "servers")
3877 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), Port);
3882 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(),Port,true,10);
3883 if (listener->GetState() == I_LISTENING)
3885 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), Port);
3886 Bindings.push_back(listener);
3890 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3894 ServerInstance->Log(DEBUG,"Done with this binding");
3898 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3899 HideULines = Conf->ReadFlag("options","hideulines",0);
3900 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3901 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3904 for (int j =0; j < Conf->Enumerate("link"); j++)
3907 std::string Allow = Conf->ReadValue("link","allowmask",j);
3908 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3909 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3910 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3911 L.Port = Conf->ReadInteger("link","port",j,true);
3912 L.SendPass = Conf->ReadValue("link","sendpass",j);
3913 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3914 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3915 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
3916 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3917 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
3918 L.NextConnectTime = time(NULL) + L.AutoConnect;
3919 /* Bugfix by brain, do not allow people to enter bad configurations */
3920 if (L.Name != ServerInstance->Config->ServerName)
3922 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3924 ValidIPs.push_back(L.IPAddr);
3927 ValidIPs.push_back(Allow);
3929 /* Needs resolving */
3931 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3935 SecurityIPResolver* sr = new SecurityIPResolver(this, ServerInstance, L.IPAddr, L);
3936 ServerInstance->AddResolver(sr);
3938 catch (ModuleException& e)
3940 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
3944 LinkBlocks.push_back(L);
3945 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3951 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3953 else if (L.RecvPass == "")
3955 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3957 else if (L.SendPass == "")
3959 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3961 else if (L.Name == "")
3963 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
3967 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3973 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
3979 /** To create a timer which recurs every second, we inherit from InspTimer.
3980 * InspTimer is only one-shot however, so at the end of each Tick() we simply
3981 * insert another of ourselves into the pending queue :)
3983 class TimeSyncTimer : public InspTimer
3987 ModuleSpanningTree *Module;
3989 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
3990 virtual void Tick(time_t TIME);
3993 class ModuleSpanningTree : public Module
3997 unsigned int max_local;
3998 unsigned int max_global;
3999 cmd_rconnect* command_rconnect;
4000 SpanningTreeUtilities* Utils;
4003 TimeSyncTimer *SyncTimer;
4005 ModuleSpanningTree(InspIRCd* Me)
4006 : Module::Module(Me), max_local(0), max_global(0)
4008 Utils = new SpanningTreeUtilities(Me, this);
4010 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4011 ServerInstance->AddCommand(command_rconnect);
4013 if (Utils->EnableTimeSync)
4015 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4016 ServerInstance->Timers->AddTimer(SyncTimer);
4022 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4024 std::string Parent = Utils->TreeRoot->GetName();
4025 if (Current->GetParent())
4027 Parent = Current->GetParent()->GetName();
4029 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4031 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4035 ShowLinks(Current->GetChild(q),user,hops+1);
4040 ShowLinks(Current->GetChild(q),user,hops+1);
4043 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4044 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4046 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());
4049 int CountLocalServs()
4051 return Utils->TreeRoot->ChildCount();
4056 return Utils->serverlist.size();
4059 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4061 ShowLinks(Utils->TreeRoot,user,0);
4062 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4066 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4068 unsigned int n_users = ServerInstance->UserCount();
4070 /* Only update these when someone wants to see them, more efficient */
4071 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4072 max_local = ServerInstance->LocalUserCount();
4073 if (n_users > max_global)
4074 max_global = n_users;
4076 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs());
4077 if (ServerInstance->OperCount())
4078 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4079 if (ServerInstance->UnregisteredUserCount())
4080 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4081 if (ServerInstance->ChannelCount())
4082 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4083 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs());
4084 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4085 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4089 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4091 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4095 for (int t = 0; t < depth; t++)
4097 matrix[line][t] = ' ';
4100 // For Aligning, we need to work out exactly how deep this thing is, and produce
4101 // a 'Spacer' String to compensate.
4104 memset(spacer,' ',40);
4105 if ((40 - Current->GetName().length() - depth) > 1) {
4106 spacer[40 - Current->GetName().length() - depth] = '\0';
4115 if (ServerInstance->clientlist.size() == 0) {
4116 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4121 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4123 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4124 totusers += Current->GetUserCount();
4126 strlcpy(&matrix[line][depth],text,80);
4128 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4130 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4134 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4139 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4145 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4149 /* Remote MOTD, the server is within the 1st parameter */
4150 std::deque<std::string> params;
4151 params.push_back(parameters[0]);
4153 /* Send it out remotely, generate no reply yet */
4154 TreeServer* s = Utils->FindServerMask(parameters[0]);
4157 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4161 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4168 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4172 /* Remote ADMIN, the server is within the 1st parameter */
4173 std::deque<std::string> params;
4174 params.push_back(parameters[0]);
4176 /* Send it out remotely, generate no reply yet */
4177 TreeServer* s = Utils->FindServerMask(parameters[0]);
4180 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4184 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4191 int HandleStats(const char** parameters, int pcnt, userrec* user)
4195 /* Remote STATS, the server is within the 2nd parameter */
4196 std::deque<std::string> params;
4197 params.push_back(parameters[0]);
4198 params.push_back(parameters[1]);
4199 /* Send it out remotely, generate no reply yet */
4200 TreeServer* s = Utils->FindServerMask(parameters[1]);
4203 params[1] = s->GetName();
4204 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4208 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4215 // Ok, prepare to be confused.
4216 // After much mulling over how to approach this, it struck me that
4217 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4218 // keeping track of a ton of ascii characters, and line by line
4219 // under recursion working out where to place them using multiplications
4220 // and divisons, we instead render the map onto a backplane of characters
4221 // (a character matrix), then draw the branches as a series of "L" shapes
4222 // from the nodes. This is not only friendlier on CPU it uses less stack.
4224 void HandleMap(const char** parameters, int pcnt, userrec* user)
4226 // This array represents a virtual screen which we will
4227 // "scratch" draw to, as the console device of an irc
4228 // client does not provide for a proper terminal.
4230 float totservers = 0;
4231 char matrix[128][80];
4232 for (unsigned int t = 0; t < 128; t++)
4234 matrix[t][0] = '\0';
4237 // The only recursive bit is called here.
4238 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4239 // Process each line one by one. The algorithm has a limit of
4240 // 128 servers (which is far more than a spanning tree should have
4241 // anyway, so we're ok). This limit can be raised simply by making
4242 // the character matrix deeper, 128 rows taking 10k of memory.
4243 for (int l = 1; l < line; l++)
4245 // scan across the line looking for the start of the
4246 // servername (the recursive part of the algorithm has placed
4247 // the servers at indented positions depending on what they
4249 int first_nonspace = 0;
4250 while (matrix[l][first_nonspace] == ' ')
4255 // Draw the `- (corner) section: this may be overwritten by
4256 // another L shape passing along the same vertical pane, becoming
4257 // a |- (branch) section instead.
4258 matrix[l][first_nonspace] = '-';
4259 matrix[l][first_nonspace-1] = '`';
4261 // Draw upwards until we hit the parent server, causing possibly
4262 // other corners (`-) to become branches (|-)
4263 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4265 matrix[l2][first_nonspace-1] = '|';
4269 // dump the whole lot to the user. This is the easy bit, honest.
4270 for (int t = 0; t < line; t++)
4272 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4274 float avg_users = totusers / totservers;
4275 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);
4276 user->WriteServ("007 %s :End of /MAP",user->nick);
4280 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4282 TreeServer* s = Utils->FindServerMask(parameters[0]);
4285 if (s == Utils->TreeRoot)
4287 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4290 TreeSocket* sock = s->GetSocket();
4293 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4294 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4295 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4296 ServerInstance->SE->DelFd(sock);
4302 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4307 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4312 int HandleTime(const char** parameters, int pcnt, userrec* user)
4314 if ((IS_LOCAL(user)) && (pcnt))
4316 TreeServer* found = Utils->FindServerMask(parameters[0]);
4319 // we dont' override for local server
4320 if (found == Utils->TreeRoot)
4323 std::deque<std::string> params;
4324 params.push_back(found->GetName());
4325 params.push_back(user->nick);
4326 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4330 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4336 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4338 if ((IS_LOCAL(user)) && (pcnt > 1))
4340 userrec* remote = ServerInstance->FindNick(parameters[1]);
4341 if ((remote) && (remote->GetFd() < 0))
4343 std::deque<std::string> params;
4344 params.push_back(parameters[1]);
4345 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4350 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4351 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4358 void DoPingChecks(time_t curtime)
4360 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4362 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4363 TreeSocket* sock = serv->GetSocket();
4366 if (curtime >= serv->NextPingTime())
4368 if (serv->AnsweredLastPing())
4370 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4371 serv->SetNextPingTime(curtime + 60);
4375 // they didnt answer, boot them
4376 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4377 sock->Squit(serv,"Ping timeout");
4378 ServerInstance->SE->DelFd(sock);
4388 void ConnectServer(Link* x)
4392 /* Do we already have an IP? If so, no need to resolve it. */
4393 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4395 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
4396 if (newsocket->GetFd() > -1)
4398 /* Handled automatically on success */
4402 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4404 Utils->DoFailOver(x);
4411 ServernameResolver* snr = new ServernameResolver(Utils, ServerInstance,x->IPAddr, *x);
4412 ServerInstance->AddResolver(snr);
4414 catch (ModuleException& e)
4416 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4417 Utils->DoFailOver(x);
4422 void AutoConnectServers(time_t curtime)
4424 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4426 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4428 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4429 x->NextConnectTime = curtime + x->AutoConnect;
4430 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4431 if (x->FailOver.length())
4433 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4436 /* The failover for this server is currently a member of the network.
4437 * The failover probably succeeded, where the main link did not.
4438 * Don't try the main link until the failover is gone again.
4445 // an autoconnected server is not connected. Check if its time to connect it
4446 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4447 this->ConnectServer(&(*x));
4453 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4455 // we've already checked if pcnt > 0, so this is safe
4456 TreeServer* found = Utils->FindServerMask(parameters[0]);
4459 std::string Version = found->GetVersion();
4460 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4461 if (found == Utils->TreeRoot)
4463 std::stringstream out(ServerInstance->Config->data005);
4464 std::string token = "";
4465 std::string line5 = "";
4466 int token_counter = 0;
4471 line5 = line5 + token + " ";
4474 if ((token_counter >= 13) || (out.eof() == true))
4476 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4485 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4490 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4492 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4494 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4496 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4499 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);
4500 ConnectServer(&(*x));
4505 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());
4510 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4514 void BroadcastTimeSync()
4516 std::deque<std::string> params;
4517 params.push_back(ConvToStr(ServerInstance->Time(true)));
4518 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4521 virtual int OnStats(char statschar, userrec* user, string_list &results)
4523 if (statschar == 'c')
4525 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4527 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(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');
4528 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4530 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4531 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);
4537 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4539 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4543 if (command == "CONNECT")
4545 return this->HandleConnect(parameters,pcnt,user);
4547 else if (command == "STATS")
4549 return this->HandleStats(parameters,pcnt,user);
4551 else if (command == "MOTD")
4553 return this->HandleMotd(parameters,pcnt,user);
4555 else if (command == "ADMIN")
4557 return this->HandleAdmin(parameters,pcnt,user);
4559 else if (command == "SQUIT")
4561 return this->HandleSquit(parameters,pcnt,user);
4563 else if (command == "MAP")
4565 this->HandleMap(parameters,pcnt,user);
4568 else if ((command == "TIME") && (pcnt > 0))
4570 return this->HandleTime(parameters,pcnt,user);
4572 else if (command == "LUSERS")
4574 this->HandleLusers(parameters,pcnt,user);
4577 else if (command == "LINKS")
4579 this->HandleLinks(parameters,pcnt,user);
4582 else if (command == "WHOIS")
4587 return this->HandleRemoteWhois(parameters,pcnt,user);
4590 else if ((command == "VERSION") && (pcnt > 0))
4592 this->HandleVersion(parameters,pcnt,user);
4599 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4601 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4603 // this bit of code cleverly routes all module commands
4604 // to all remote severs *automatically* so that modules
4605 // can just handle commands locally, without having
4606 // to have any special provision in place for remote
4607 // commands and linking protocols.
4608 std::deque<std::string> params;
4610 for (int j = 0; j < pcnt; j++)
4612 if (strchr(parameters[j],' '))
4614 params.push_back(":" + std::string(parameters[j]));
4618 params.push_back(std::string(parameters[j]));
4621 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4622 Utils->DoOneToMany(user->nick,command,params);
4626 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4628 TreeServer* s = Utils->FindServer(servername);
4631 description = s->GetDesc();
4635 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4637 if (IS_LOCAL(source))
4639 std::deque<std::string> params;
4640 params.push_back(dest->nick);
4641 params.push_back(channel->name);
4642 Utils->DoOneToMany(source->nick,"INVITE",params);
4646 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4648 std::deque<std::string> params;
4649 params.push_back(chan->name);
4650 params.push_back(":"+topic);
4651 Utils->DoOneToMany(user->nick,"TOPIC",params);
4654 virtual void OnWallops(userrec* user, const std::string &text)
4658 std::deque<std::string> params;
4659 params.push_back(":"+text);
4660 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4664 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4666 if (target_type == TYPE_USER)
4668 userrec* d = (userrec*)dest;
4669 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4671 std::deque<std::string> params;
4673 params.push_back(d->nick);
4674 params.push_back(":"+text);
4675 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4678 else if (target_type == TYPE_CHANNEL)
4682 chanrec *c = (chanrec*)dest;
4685 std::string cname = c->name;
4687 cname = status + cname;
4688 std::deque<TreeServer*> list;
4689 Utils->GetListOfServersForChannel(c,list);
4690 unsigned int ucount = list.size();
4691 for (unsigned int i = 0; i < ucount; i++)
4693 TreeSocket* Sock = list[i]->GetSocket();
4695 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4700 else if (target_type == TYPE_SERVER)
4704 char* target = (char*)dest;
4705 std::deque<std::string> par;
4706 par.push_back(target);
4707 par.push_back(":"+text);
4708 Utils->DoOneToMany(user->nick,"NOTICE",par);
4713 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4715 if (target_type == TYPE_USER)
4717 // route private messages which are targetted at clients only to the server
4718 // which needs to receive them
4719 userrec* d = (userrec*)dest;
4720 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4722 std::deque<std::string> params;
4724 params.push_back(d->nick);
4725 params.push_back(":"+text);
4726 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4729 else if (target_type == TYPE_CHANNEL)
4733 chanrec *c = (chanrec*)dest;
4736 std::string cname = c->name;
4738 cname = status + cname;
4739 std::deque<TreeServer*> list;
4740 Utils->GetListOfServersForChannel(c,list);
4741 unsigned int ucount = list.size();
4742 for (unsigned int i = 0; i < ucount; i++)
4744 TreeSocket* Sock = list[i]->GetSocket();
4746 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4751 else if (target_type == TYPE_SERVER)
4755 char* target = (char*)dest;
4756 std::deque<std::string> par;
4757 par.push_back(target);
4758 par.push_back(":"+text);
4759 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4764 virtual void OnBackgroundTimer(time_t curtime)
4766 AutoConnectServers(curtime);
4767 DoPingChecks(curtime);
4770 virtual void OnUserJoin(userrec* user, chanrec* channel)
4772 // Only do this for local users
4775 std::deque<std::string> params;
4777 params.push_back(channel->name);
4778 // set up their permissions and the channel TS with FJOIN.
4779 // All users are FJOINed now, because a module may specify
4780 // new joining permissions for the user.
4782 params.push_back(channel->name);
4783 params.push_back(ConvToStr(channel->age));
4784 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4785 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4789 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4791 // only occurs for local clients
4792 if (user->registered != REG_ALL)
4794 std::deque<std::string> params;
4795 params.push_back(newhost);
4796 Utils->DoOneToMany(user->nick,"FHOST",params);
4799 virtual void OnChangeName(userrec* user, const std::string &gecos)
4801 // only occurs for local clients
4802 if (user->registered != REG_ALL)
4804 std::deque<std::string> params;
4805 params.push_back(gecos);
4806 Utils->DoOneToMany(user->nick,"FNAME",params);
4809 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4813 std::deque<std::string> params;
4814 params.push_back(channel->name);
4815 if (partmessage != "")
4816 params.push_back(":"+partmessage);
4817 Utils->DoOneToMany(user->nick,"PART",params);
4821 virtual void OnUserConnect(userrec* user)
4823 char agestr[MAXBUF];
4826 std::deque<std::string> params;
4827 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4828 params.push_back(agestr);
4829 params.push_back(user->nick);
4830 params.push_back(user->host);
4831 params.push_back(user->dhost);
4832 params.push_back(user->ident);
4833 params.push_back("+"+std::string(user->FormatModes()));
4834 params.push_back(user->GetIPString());
4835 params.push_back(":"+std::string(user->fullname));
4836 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4838 // User is Local, change needs to be reflected!
4839 TreeServer* SourceServer = Utils->FindServer(user->server);
4842 SourceServer->AddUserCount();
4848 virtual void OnUserQuit(userrec* user, const std::string &reason)
4850 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4852 std::deque<std::string> params;
4853 params.push_back(":"+reason);
4854 Utils->DoOneToMany(user->nick,"QUIT",params);
4856 // Regardless, We need to modify the user Counts..
4857 TreeServer* SourceServer = Utils->FindServer(user->server);
4860 SourceServer->DelUserCount();
4865 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4869 std::deque<std::string> params;
4870 params.push_back(user->nick);
4871 Utils->DoOneToMany(oldnick,"NICK",params);
4875 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4877 if ((source) && (IS_LOCAL(source)))
4879 std::deque<std::string> params;
4880 params.push_back(chan->name);
4881 params.push_back(user->nick);
4882 params.push_back(":"+reason);
4883 Utils->DoOneToMany(source->nick,"KICK",params);
4887 std::deque<std::string> params;
4888 params.push_back(chan->name);
4889 params.push_back(user->nick);
4890 params.push_back(":"+reason);
4891 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4895 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4897 std::deque<std::string> params;
4898 params.push_back(dest->nick);
4899 params.push_back(":"+reason);
4900 Utils->DoOneToMany(source->nick,"KILL",params);
4903 virtual void OnRehash(const std::string ¶meter)
4905 if (parameter != "")
4907 std::deque<std::string> params;
4908 params.push_back(parameter);
4909 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4911 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4913 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4914 ServerInstance->RehashServer();
4917 Utils->ReadConfiguration(false);
4920 // note: the protocol does not allow direct umode +o except
4921 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4923 virtual void OnOper(userrec* user, const std::string &opertype)
4927 std::deque<std::string> params;
4928 params.push_back(opertype);
4929 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
4933 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4937 /* Server-set lines */
4939 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, ServerInstance->Time(false), duration, reason.c_str());
4940 std::deque<std::string> params;
4941 params.push_back(data);
4942 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
4946 if (IS_LOCAL(source))
4949 snprintf(type,8,"%cLINE",linetype);
4950 std::string stype = type;
4953 char sduration[MAXBUF];
4954 snprintf(sduration,MAXBUF,"%ld",duration);
4955 std::deque<std::string> params;
4956 params.push_back(host);
4957 params.push_back(sduration);
4958 params.push_back(":"+reason);
4959 Utils->DoOneToMany(source->nick,stype,params);
4963 std::deque<std::string> params;
4964 params.push_back(host);
4965 Utils->DoOneToMany(source->nick,stype,params);
4971 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4973 OnLine(source,hostmask,true,'G',duration,reason);
4976 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4978 OnLine(source,ipmask,true,'Z',duration,reason);
4981 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4983 OnLine(source,nickmask,true,'Q',duration,reason);
4986 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4988 OnLine(source,hostmask,true,'E',duration,reason);
4991 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4993 OnLine(source,hostmask,false,'G',0,"");
4996 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4998 OnLine(source,ipmask,false,'Z',0,"");
5001 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5003 OnLine(source,nickmask,false,'Q',0,"");
5006 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5008 OnLine(source,hostmask,false,'E',0,"");
5011 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5013 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5015 if (target_type == TYPE_USER)
5017 userrec* u = (userrec*)dest;
5018 std::deque<std::string> params;
5019 params.push_back(u->nick);
5020 params.push_back(text);
5021 Utils->DoOneToMany(user->nick,"MODE",params);
5025 chanrec* c = (chanrec*)dest;
5026 std::deque<std::string> params;
5027 params.push_back(c->name);
5028 params.push_back(text);
5029 Utils->DoOneToMany(user->nick,"MODE",params);
5034 virtual void OnSetAway(userrec* user)
5038 std::deque<std::string> params;
5039 params.push_back(":"+std::string(user->awaymsg));
5040 Utils->DoOneToMany(user->nick,"AWAY",params);
5044 virtual void OnCancelAway(userrec* user)
5048 std::deque<std::string> params;
5050 Utils->DoOneToMany(user->nick,"AWAY",params);
5054 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5056 TreeSocket* s = (TreeSocket*)opaque;
5059 if (target_type == TYPE_USER)
5061 userrec* u = (userrec*)target;
5062 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5066 chanrec* c = (chanrec*)target;
5067 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5072 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5074 TreeSocket* s = (TreeSocket*)opaque;
5077 if (target_type == TYPE_USER)
5079 userrec* u = (userrec*)target;
5080 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5082 else if (target_type == TYPE_OTHER)
5084 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5086 else if (target_type == TYPE_CHANNEL)
5088 chanrec* c = (chanrec*)target;
5089 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5094 virtual void OnEvent(Event* event)
5096 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5098 if (event->GetEventID() == "send_metadata")
5100 if (params->size() < 3)
5102 (*params)[2] = ":" + (*params)[2];
5103 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5105 else if (event->GetEventID() == "send_topic")
5107 if (params->size() < 2)
5109 (*params)[1] = ":" + (*params)[1];
5110 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5111 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5112 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5114 else if (event->GetEventID() == "send_mode")
5116 if (params->size() < 2)
5118 // Insert the TS value of the object, either userrec or chanrec
5120 userrec* a = ServerInstance->FindNick((*params)[0]);
5127 chanrec* a = ServerInstance->FindChan((*params)[0]);
5133 params->insert(params->begin() + 1,ConvToStr(ourTS));
5134 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5136 else if (event->GetEventID() == "send_push")
5138 if (params->size() < 2)
5141 userrec *a = ServerInstance->FindNick((*params)[0]);
5146 (*params)[1] = ":" + (*params)[1];
5147 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5151 virtual ~ModuleSpanningTree()
5153 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5154 /* This will also free the listeners */
5157 ServerInstance->Timers->DelTimer(SyncTimer);
5160 virtual Version GetVersion()
5162 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5165 void Implements(char* List)
5167 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5168 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5169 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5170 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5171 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5172 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5173 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5176 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5177 * so that any activity it sees is FINAL, e.g. we arent going to send out
5178 * a NICK message before m_cloaking has finished putting the +x on the user,
5180 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5181 * the module call queue.
5183 Priority Prioritize()
5185 return PRIORITY_LAST;
5189 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5193 void TimeSyncTimer::Tick(time_t TIME)
5195 Module->BroadcastTimeSync();
5196 Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5197 Instance->Timers->AddTimer(Module->SyncTimer);
5200 void SpanningTreeUtilities::DoFailOver(Link* x)
5202 if (x->FailOver.length())
5204 if (x->FailOver == x->Name)
5206 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());
5209 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5212 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5213 Creator->ConnectServer(TryThisOne);
5217 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5222 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5224 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5226 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5234 class ModuleSpanningTreeFactory : public ModuleFactory
5237 ModuleSpanningTreeFactory()
5241 ~ModuleSpanningTreeFactory()
5245 virtual Module * CreateModule(InspIRCd* Me)
5247 return new ModuleSpanningTree(Me);
5253 extern "C" void * init_module( void )
5255 return new ModuleSpanningTreeFactory;