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 * IMPORTANT: If you make changes, document your changes here, without fail:
35 * http://www.inspircd.org/wiki/List_of_protocol_changes_between_versions
37 * Failure to document your protocol changes will result in a painfully
38 * painful death by pain. You have been warned.
40 const long ProtocolVersion = 1102;
43 * The server list in InspIRCd is maintained as two structures
44 * which hold the data in different ways. Most of the time, we
45 * want to very quicky obtain three pieces of information:
47 * (1) The information on a server
48 * (2) The information on the server we must send data through
49 * to actually REACH the server we're after
50 * (3) Potentially, the child/parent objects of this server
52 * The InspIRCd spanning protocol provides easy access to these
53 * by storing the data firstly in a recursive structure, where
54 * each item references its parent item, and a dynamic list
55 * of child items, and another structure which stores the items
56 * hashed, linearly. This means that if we want to find a server
57 * by name quickly, we can look it up in the hash, avoiding
58 * any O(n) lookups. If however, during a split or sync, we want
59 * to apply an operation to a server, and any of its child objects
60 * we can resort to recursion to walk the tree structure.
61 * Any socket can have one of five states at any one time.
62 * The LISTENER state indicates a socket which is listening
63 * for connections. It cannot receive data itself, only incoming
65 * The CONNECTING state indicates an outbound socket which is
66 * waiting to be writeable.
67 * The WAIT_AUTH_1 state indicates the socket is outbound and
68 * has successfully connected, but has not yet sent and received
70 * The WAIT_AUTH_2 state indicates that the socket is inbound
71 * (allocated by a LISTENER) but has not yet sent and received
73 * The CONNECTED state represents a fully authorized, fully
76 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
78 /* Foward declarations */
82 class ModuleSpanningTree;
84 /* This hash_map holds the hash equivalent of the server
85 * tree, used for rapid linear lookups.
87 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
90 /** The Link class might as well be a struct,
91 * but this is C++ and we don't believe in structs (!).
92 * It holds the entire information of one <link>
93 * tag from the main config file. We maintain a list
94 * of them, and populate the list on rehash/load.
96 class Link : public classbase
102 std::string SendPass;
103 std::string RecvPass;
104 unsigned long AutoConnect;
105 time_t NextConnectTime;
106 std::string EncryptionKey;
107 bool HiddenFromStats;
108 std::string FailOver;
112 /** Contains helper functions and variables for this module,
113 * and keeps them out of the global namespace
115 class SpanningTreeUtilities
120 InspIRCd* ServerInstance;
124 ModuleSpanningTree* Creator;
125 /** Flatten links and /MAP for non-opers
128 /** Hide U-Lined servers in /MAP and /LINKS
131 /** Announce TS changes to channels on merge
133 bool AnnounceTSChange;
134 /** Synchronize timestamps between servers
137 /** Socket bindings for listening sockets
139 std::vector<TreeSocket*> Bindings;
140 /** This variable represents the root of the server tree
142 TreeServer *TreeRoot;
143 /** IPs allowed to link to us
145 std::vector<std::string> ValidIPs;
146 /** Hash of currently connected servers by name
148 server_hash serverlist;
149 /** Holds the data from the <link> tags in the conf
151 std::vector<Link> LinkBlocks;
153 /** Initialise utility class
155 SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator);
156 /** Destroy class and free listeners etc
158 ~SpanningTreeUtilities();
159 /** Send a message from this server to one other local or remote
161 bool DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target);
162 /** Send a message from this server to all but one other, local or remote
164 bool DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit);
165 /** Send a message from this server to all but one other, local or remote
167 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit);
168 /** Send a message from this server to all others
170 bool DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms);
171 /** Send a message from this server to all others
173 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms);
174 /** 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)
176 bool DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms);
177 /** Read the spanningtree module's tags from the config file
179 void ReadConfiguration(bool rebind);
180 /** Add a server to the server list for GetListOfServersForChannel
182 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list);
183 /** Compile a list of servers which contain members of channel c
185 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list);
186 /** Find a server by name
188 TreeServer* FindServer(const std::string &ServerName);
189 /** Find a route to a server by name
191 TreeServer* BestRouteTo(const std::string &ServerName);
192 /** Find a server by glob mask
194 TreeServer* FindServerMask(const std::string &ServerName);
195 /** Returns true if this is a server name we recognise
197 bool IsServer(const std::string &ServerName);
198 /** Attempt to connect to the failover link of link x
200 void DoFailOver(Link* x);
201 /** Find a link tag from a server name
203 Link* FindLink(const std::string& name);
207 /** Each server in the tree is represented by one class of
208 * type TreeServer. A locally connected TreeServer can
209 * have a class of type TreeSocket associated with it, for
210 * remote servers, the TreeSocket entry will be NULL.
211 * Each server also maintains a pointer to its parent
212 * (NULL if this server is ours, at the top of the tree)
213 * and a pointer to its "Route" (see the comments in the
214 * constructors below), and also a dynamic list of pointers
215 * to its children which can be iterated recursively
216 * if required. Creating or deleting objects of type
217 i* TreeServer automatically maintains the hash_map of
218 * TreeServer items, deleting and inserting them as they
219 * are created and destroyed.
221 class TreeServer : public classbase
223 InspIRCd* ServerInstance; /* Creator */
224 TreeServer* Parent; /* Parent entry */
225 TreeServer* Route; /* Route entry */
226 std::vector<TreeServer*> Children; /* List of child objects */
227 irc::string ServerName; /* Server's name */
228 std::string ServerDesc; /* Server's description */
229 std::string VersionString; /* Version string or empty string */
230 int UserCount; /* Not used in this version */
231 int OperCount; /* Not used in this version */
232 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
233 time_t NextPing; /* After this time, the server should be PINGed*/
234 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
235 SpanningTreeUtilities* Utils; /* Utility class */
239 /** We don't use this constructor. Its a dummy, and won't cause any insertion
240 * of the TreeServer into the hash_map. See below for the two we DO use.
242 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance) : ServerInstance(Instance), Utils(Util)
248 UserCount = OperCount = 0;
249 VersionString = ServerInstance->GetVersionString();
252 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
253 * represents our own server. Therefore, it has no route, no parent, and
254 * no socket associated with it. Its version string is our own local version.
256 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util)
260 UserCount = ServerInstance->UserCount();
261 OperCount = ServerInstance->OperCount();
262 VersionString = ServerInstance->GetVersionString();
264 Socket = NULL; /* Fix by brain */
268 /** When we create a new server, we call this constructor to initialize it.
269 * This constructor initializes the server's Route and Parent, and sets up
270 * its ping counters so that it will be pinged one minute from now.
272 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
273 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util)
276 UserCount = OperCount = 0;
277 this->SetNextPingTime(time(NULL) + 60);
280 /* find the 'route' for this server (e.g. the one directly connected
281 * to the local server, which we can use to reach it)
283 * In the following example, consider we have just added a TreeServer
284 * class for server G on our network, of which we are server A.
285 * To route traffic to G (marked with a *) we must send the data to
286 * B (marked with a +) so this algorithm initializes the 'Route'
287 * value to point at whichever server traffic must be routed through
288 * to get here. If we were to try this algorithm with server B,
289 * the Route pointer would point at its own object ('this').
299 * We only run this algorithm when a server is created, as
300 * the routes remain constant while ever the server exists, and
301 * do not need to be re-calculated.
305 if (Route == Utils->TreeRoot)
311 while (this->Route->GetParent() != Utils->TreeRoot)
313 this->Route = Route->GetParent();
317 /* Because recursive code is slow and takes a lot of resources,
318 * we store two representations of the server tree. The first
319 * is a recursive structure where each server references its
320 * children and its parent, which is used for netbursts and
321 * netsplits to dump the whole dataset to the other server,
322 * and the second is used for very fast lookups when routing
323 * messages and is instead a hash_map, where each item can
324 * be referenced by its server name. The AddHashEntry()
325 * call below automatically inserts each TreeServer class
326 * into the hash_map as it is created. There is a similar
327 * maintainance call in the destructor to tidy up deleted
331 this->AddHashEntry();
334 int QuitUsers(const std::string &reason)
336 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
337 const char* reason_s = reason.c_str();
338 std::vector<userrec*> time_to_die;
339 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
341 if (!strcmp(n->second->server, this->ServerName.c_str()))
343 time_to_die.push_back(n->second);
346 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
348 userrec* a = (userrec*)*n;
349 ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
351 userrec::QuitUser(ServerInstance,a,reason_s);
353 return time_to_die.size();
356 /** This method is used to add the structure to the
357 * hash_map for linear searches. It is only called
358 * by the constructors.
362 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
363 if (iter == Utils->serverlist.end())
364 Utils->serverlist[this->ServerName.c_str()] = this;
367 /** This method removes the reference to this object
368 * from the hash_map which is used for linear searches.
369 * It is only called by the default destructor.
373 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
374 if (iter != Utils->serverlist.end())
375 Utils->serverlist.erase(iter);
378 /** These accessors etc should be pretty self-
381 TreeServer* GetRoute()
386 std::string GetName()
388 return ServerName.c_str();
391 std::string GetDesc()
396 std::string GetVersion()
398 return VersionString;
401 void SetNextPingTime(time_t t)
404 LastPingWasGood = false;
407 time_t NextPingTime()
412 bool AnsweredLastPing()
414 return LastPingWasGood;
419 LastPingWasGood = true;
442 TreeSocket* GetSocket()
447 TreeServer* GetParent()
452 void SetVersion(const std::string &Version)
454 VersionString = Version;
457 unsigned int ChildCount()
459 return Children.size();
462 TreeServer* GetChild(unsigned int n)
464 if (n < Children.size())
466 /* Make sure they cant request
467 * an out-of-range object. After
468 * all we know what these programmer
469 * types are like *grin*.
479 void AddChild(TreeServer* Child)
481 Children.push_back(Child);
484 bool DelChild(TreeServer* Child)
486 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
497 /** Removes child nodes of this node, and of that node, etc etc.
498 * This is used during netsplits to automatically tidy up the
499 * server tree. It is slow, we don't use it for much else.
503 bool stillchildren = true;
504 while (stillchildren)
506 stillchildren = false;
507 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
509 TreeServer* s = (TreeServer*)*a;
513 stillchildren = true;
522 /* We'd better tidy up after ourselves, eh? */
523 this->DelHashEntry();
527 /** Yay for fast searches!
528 * This is hundreds of times faster than recursion
529 * or even scanning a linked list, especially when
530 * there are more than a few servers to deal with.
533 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
535 server_hash::iterator iter;
536 iter = serverlist.find(ServerName.c_str());
537 if (iter != serverlist.end())
547 /** Returns the locally connected server we must route a
548 * message through to reach server 'ServerName'. This
549 * only applies to one-to-one and not one-to-many routing.
550 * See the comments for the constructor of TreeServer
553 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
555 if (ServerName.c_str() == TreeRoot->GetName())
557 TreeServer* Found = FindServer(ServerName);
560 return Found->GetRoute();
568 /** Find the first server matching a given glob mask.
569 * Theres no find-using-glob method of hash_map [awwww :-(]
570 * so instead, we iterate over the list using an iterator
571 * and match each one until we get a hit. Yes its slow,
574 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
576 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
578 if (match(i->first.c_str(),ServerName.c_str()))
584 /* A convenient wrapper that returns true if a server exists */
585 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
587 return (FindServer(ServerName) != NULL);
593 class cmd_rconnect : public command_t
596 SpanningTreeUtilities* Utils;
598 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
600 this->source = "m_spanningtree.so";
601 syntax = "<remote-server-mask> <servermask>";
604 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
606 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
607 /* Is this aimed at our server? */
608 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
610 /* Yes, initiate the given connect */
611 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
613 para[0] = parameters[1];
614 std::string original_command = std::string("CONNECT ") + parameters[1];
615 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
626 /** Every SERVER connection inbound or outbound is represented by
627 * an object of type TreeSocket.
628 * TreeSockets, being inherited from InspSocket, can be tied into
629 * the core socket engine, and we cn therefore receive activity events
630 * for them, just like activex objects on speed. (yes really, that
631 * is a technical term!) Each of these which relates to a locally
632 * connected server is assocated with it, by hooking it onto a
633 * TreeSocket class using its constructor. In this way, we can
634 * maintain a list of servers, some of which are directly connected,
635 * some of which are not.
637 class TreeSocket : public InspSocket
639 SpanningTreeUtilities* Utils;
641 std::string in_buffer;
642 ServerState LinkState;
643 std::string InboundServerName;
644 std::string InboundDescription;
646 int num_lost_servers;
648 bool LastPingWasGood;
652 unsigned int keylength;
653 std::string ModuleList;
654 std::map<std::string,std::string> CapKeys;
658 /** Because most of the I/O gubbins are encapsulated within
659 * InspSocket, we just call the superclass constructor for
660 * most of the action, and append a few of our own values
663 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
664 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
667 this->LinkState = LISTENER;
669 this->ctx_out = NULL;
672 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
673 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
676 this->LinkState = CONNECTING;
678 this->ctx_out = NULL;
681 /** When a listening socket gives us a new file descriptor,
682 * we must associate it with a socket without creating a new
683 * connection. This constructor is used for this purpose.
685 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip)
686 : InspSocket(SI, newfd, ip), Utils(Util)
688 this->LinkState = WAIT_AUTH_1;
690 this->ctx_out = NULL;
691 this->SendCapabilities();
702 void InitAES(std::string key,std::string SName)
709 Instance->Log(DEBUG,"Initialized AES key %s",key.c_str());
710 // key must be 16, 24, 32 etc bytes (multiple of 8)
711 keylength = key.length();
712 if (!(keylength == 16 || keylength == 24 || keylength == 32))
714 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
715 Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
719 if (this->GetState() != I_ERROR)
721 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
722 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\
723 \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 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\
725 \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);
730 /** When an outbound connection finishes connecting, we receive
731 * this event, and must send our SERVER string to the other
732 * side. If the other side is happy, as outlined in the server
733 * to server docs on the inspircd.org site, the other side
734 * will then send back its own server string.
736 virtual bool OnConnected()
738 if (this->LinkState == CONNECTING)
740 /* we do not need to change state here. */
741 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
743 if (x->Name == this->myhost)
745 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
746 this->SendCapabilities();
747 if (x->EncryptionKey != "")
749 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
751 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.");
755 this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
756 this->InitAES(x->EncryptionKey,x->Name.c_str());
759 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
760 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
765 /* There is a (remote) chance that between the /CONNECT and the connection
766 * being accepted, some muppet has removed the <link> block and rehashed.
767 * If that happens the connection hangs here until it's closed. Unlikely
768 * and rather harmless.
770 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
774 virtual void OnError(InspSocketError e)
776 /* We don't handle this method, because all our
777 * dirty work is done in OnClose() (see below)
778 * which is still called on error conditions too.
780 if (e == I_ERR_CONNECT)
782 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
783 Link* MyLink = Utils->FindLink(myhost);
785 Utils->DoFailOver(MyLink);
789 virtual int OnDisconnect()
791 /* For the same reason as above, we don't
792 * handle OnDisconnect()
797 /** Recursively send the server tree with distances as hops.
798 * This is used during network burst to inform the other server
799 * (and any of ITS servers too) of what servers we know about.
800 * If at any point any of these servers already exist on the other
801 * end, our connection may be terminated. The hopcounts given
802 * by this function are relative, this doesn't matter so long as
803 * they are all >1, as all the remote servers re-calculate them
804 * to be relative too, with themselves as hop 0.
806 void SendServers(TreeServer* Current, TreeServer* s, int hops)
809 for (unsigned int q = 0; q < Current->ChildCount(); q++)
811 TreeServer* recursive_server = Current->GetChild(q);
812 if (recursive_server != s)
814 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
815 this->WriteLine(command);
816 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
817 /* down to next level */
818 this->SendServers(recursive_server, s, hops+1);
823 std::string MyCapabilities()
825 std::vector<std::string> modlist;
826 std::string capabilities = "";
828 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
830 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
831 modlist.push_back(this->Instance->Config->module_names[i]);
833 sort(modlist.begin(),modlist.end());
834 for (unsigned int i = 0; i < modlist.size(); i++)
837 capabilities = capabilities + ",";
838 capabilities = capabilities + modlist[i];
843 void SendCapabilities()
845 irc::commasepstream modulelist(MyCapabilities());
847 this->WriteLine("CAPAB START");
849 /* Send module names, split at 509 length */
850 std::string item = "*";
851 std::string line = "CAPAB MODULES ";
852 while ((item = modulelist.GetToken()) != "")
854 if (line.length() + item.length() + 1 > 509)
856 this->WriteLine(line);
857 line = "CAPAB MODULES ";
860 if (line != "CAPAB MODULES ")
865 if (line != "CAPAB MODULES ")
866 this->WriteLine(line);
873 #ifdef SUPPORT_IP6LINKS
876 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));
878 this->WriteLine("CAPAB END");
881 /* Check a comma seperated list for an item */
882 bool HasItem(const std::string &list, const std::string &item)
884 irc::commasepstream seplist(list);
886 std::string item2 = "*";
887 while ((item2 = seplist.GetToken()) != "")
896 /* Isolate and return the elements that are different between two comma seperated lists */
897 std::string ListDifference(const std::string &one, const std::string &two)
899 irc::commasepstream list_one(one);
900 std::string item = "*";
901 std::string result = "";
902 while ((item = list_one.GetToken()) != "")
904 if (!HasItem(two, item))
913 bool Capab(const std::deque<std::string> ¶ms)
915 if (params.size() < 1)
917 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
921 if (params[0] == "START")
923 this->ModuleList = "";
924 this->CapKeys.clear();
926 else if (params[0] == "END")
928 std::string reason = "";
930 #ifdef SUPPORT_IP6LINKS
933 /* Compare ModuleList and check CapKeys...
934 * Maybe this could be tidier? -- Brain
936 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
938 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
941 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
945 diff = "this server:" + diff;
947 if (diff.length() == 12)
948 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
950 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
953 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
954 reason = "We don't both support linking to IPV6 servers";
956 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
957 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
959 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
960 reason = "Maximum nickname lengths differ or remote nickname length not specified";
962 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
964 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
966 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
970 reason = "Protocol version not specified";
974 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))))
975 reason = "We don't both have halfop support enabled/disabled identically";
977 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
978 reason = "Maximum ident lengths differ or remote ident length not specified";
980 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
981 reason = "Maximum channel lengths differ or remote channel length not specified";
983 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
984 reason = "Maximum modes per line differ or remote modes per line not specified";
986 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
987 reason = "Maximum quit lengths differ or remote quit length not specified";
989 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
990 reason = "Maximum topic lengths differ or remote topic length not specified";
992 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
993 reason = "Maximum kick lengths differ or remote kick length not specified";
995 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
996 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
998 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
999 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
1001 if (reason.length())
1003 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
1007 else if ((params[0] == "MODULES") && (params.size() == 2))
1009 if (!this->ModuleList.length())
1011 this->ModuleList.append(params[1]);
1015 this->ModuleList.append(",");
1016 this->ModuleList.append(params[1]);
1019 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
1021 irc::tokenstream capabs(params[1]);
1022 std::string item = "*";
1023 while ((item = capabs.GetToken()) != "")
1025 /* Process each key/value pair */
1026 std::string::size_type equals = item.rfind('=');
1027 if (equals != std::string::npos)
1029 std::string var = item.substr(0, equals);
1030 std::string value = item.substr(equals+1, item.length());
1031 this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
1032 CapKeys[var] = value;
1040 /** This function forces this server to quit, removing this server
1041 * and any users on it (and servers and users below that, etc etc).
1042 * It's very slow and pretty clunky, but luckily unless your network
1043 * is having a REAL bad hair day, this function shouldnt be called
1044 * too many times a month ;-)
1046 void SquitServer(std::string &from, TreeServer* Current)
1048 /* recursively squit the servers attached to 'Current'.
1049 * We're going backwards so we don't remove users
1050 * while we still need them ;)
1052 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1054 TreeServer* recursive_server = Current->GetChild(q);
1055 this->SquitServer(from,recursive_server);
1057 /* Now we've whacked the kids, whack self */
1059 num_lost_users += Current->QuitUsers(from);
1062 /** This is a wrapper function for SquitServer above, which
1063 * does some validation first and passes on the SQUIT to all
1064 * other remaining servers.
1066 void Squit(TreeServer* Current, const std::string &reason)
1068 if ((Current) && (Current != Utils->TreeRoot))
1070 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
1071 rmode.Send(Instance);
1073 std::deque<std::string> params;
1074 params.push_back(Current->GetName());
1075 params.push_back(":"+reason);
1076 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1077 if (Current->GetParent() == Utils->TreeRoot)
1079 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1083 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1085 num_lost_servers = 0;
1087 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1088 SquitServer(from, Current);
1090 Current->GetParent()->DelChild(Current);
1092 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1096 Instance->Log(DEFAULT,"Squit from unknown server");
1100 /** FMODE command - server mode with timestamp checks */
1101 bool ForceMode(const std::string &source, std::deque<std::string> ¶ms)
1103 /* Chances are this is a 1.0 FMODE without TS */
1104 if (params.size() < 3)
1106 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
1111 std::string sourceserv;
1113 /* Are we dealing with an FMODE from a user, or from a server? */
1114 userrec* who = this->Instance->FindNick(source);
1117 /* FMODE from a user, set sourceserv to the users server name */
1118 sourceserv = who->server;
1122 /* FMODE from a server, create a fake user to receive mode feedback */
1123 who = new userrec(this->Instance);
1124 who->SetFd(FD_MAGIC_NUMBER);
1125 smode = true; /* Setting this flag tells us we should free the userrec later */
1126 sourceserv = source; /* Set sourceserv to the actual source string */
1128 const char* modelist[64];
1131 memset(&modelist,0,sizeof(modelist));
1132 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1136 /* The timestamp is in this position.
1137 * We don't want to pass that up to the
1138 * server->client protocol!
1140 TS = atoi(params[q].c_str());
1144 /* Everything else is fine to append to the modelist */
1145 modelist[n++] = params[q].c_str();
1149 /* Extract the TS value of the object, either userrec or chanrec */
1150 userrec* dst = this->Instance->FindNick(params[0]);
1151 chanrec* chan = NULL;
1159 chan = this->Instance->FindChan(params[0]);
1165 /* Oops, channel doesnt exist! */
1169 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1174 Instance->Log(DEBUG,"Entering TS equality check");
1175 ModeHandler* mh = NULL;
1176 unsigned long paramptr = 3;
1177 std::string to_bounce = "";
1178 std::string to_keep = "";
1179 std::vector<std::string> params_to_keep;
1180 std::string params_to_bounce = "";
1182 char cur_change = 1;
1183 char old_change = 0;
1184 char old_bounce_change = 0;
1185 /* Merge modes, basically do special stuff to mode with params */
1186 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1199 /* We only care about whats being set,
1200 * not whats being unset
1202 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1204 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1206 /* We only want to do special things to
1207 * modes with parameters, we are going to rewrite
1211 adding ? cur_change = '+' : cur_change = '-';
1213 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1215 /* The mode is set here, check which we should keep */
1218 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1220 if (which_to_keep == true)
1222 /* Keep ours, bounce theirs:
1223 * Send back ours to them and
1224 * drop their mode changs
1226 adding ? cur_change = '+' : cur_change = '-';
1227 if (cur_change != old_bounce_change)
1228 to_bounce += cur_change;
1230 old_bounce_change = cur_change;
1232 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1233 params_to_bounce.append(" ").append(ret.second);
1237 /* Keep theirs: Accept their mode change,
1240 adding ? cur_change = '+' : cur_change = '-';
1241 if (cur_change != old_change)
1242 to_keep += cur_change;
1244 old_change = cur_change;
1246 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1247 params_to_keep.push_back(params[paramptr]);
1252 /* Mode isnt set here, we want it */
1253 adding ? cur_change = '+' : cur_change = '-';
1254 if (cur_change != old_change)
1255 to_keep += cur_change;
1257 old_change = cur_change;
1259 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1260 params_to_keep.push_back(params[paramptr]);
1267 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1271 adding ? cur_change = '+' : cur_change = '-';
1273 /* Just keep this, safe to merge with no checks
1274 * it has no parameters
1277 if (cur_change != old_change)
1278 to_keep += cur_change;
1280 old_change = cur_change;
1282 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1284 Instance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1285 params_to_keep.push_back(params[paramptr++]);
1292 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1296 /* Taking a mode away */
1297 adding ? cur_change = '+' : cur_change = '-';
1299 if (cur_change != old_change)
1300 to_keep += cur_change;
1302 old_change = cur_change;
1304 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1305 params_to_keep.push_back(params[paramptr++]);
1312 if (to_bounce.length())
1314 std::deque<std::string> newparams;
1315 newparams.push_back(params[0]);
1316 newparams.push_back(ConvToStr(ourTS));
1317 newparams.push_back(to_bounce+params_to_bounce);
1318 Instance->Log(DEBUG,"BOUNCE BACK: %s",(to_bounce+params_to_bounce).c_str());
1319 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1322 if (to_keep.length())
1326 modelist[0] = params[0].c_str();
1327 modelist[1] = to_keep.c_str();
1329 if (params_to_keep.size() > 0)
1331 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1333 Instance->Log(DEBUG,"KEEP Item %d of %d: %s", q, params_to_keep.size(), params_to_keep[q].c_str());
1334 modelist[n++] = params_to_keep[q].c_str();
1340 Instance->Log(DEBUG,"Send mode");
1341 this->Instance->SendMode(modelist, n, who);
1345 Instance->Log(DEBUG,"Send mode client");
1346 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1349 /* HOT POTATO! PASS IT ON! */
1350 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1354 /* U-lined servers always win regardless of their TS */
1355 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1357 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1358 * SHOULD accept it, if its clock is right.
1360 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1361 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1362 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1364 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1365 * writing the code. It took me a while to come up with this solution.
1367 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1370 std::deque<std::string> newparams; /* New parameter list we send back */
1371 newparams.push_back(params[0]); /* Target, user or channel */
1372 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1373 newparams.push_back(""); /* This contains the mode string. For now
1374 * it's empty, we fill it below.
1377 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1378 * set to avoid a desync here.
1380 std::string modebounce = "";
1383 ModeHandler* mh = NULL;
1384 char cur_change = 1;
1385 char old_change = 0;
1386 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1388 /* Iterate over all mode chars in the sent set */
1391 /* Adding or subtracting modes? */
1399 /* Find the mode handler for this mode */
1400 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1402 /* Got a mode handler?
1403 * This also prevents us bouncing modes we have no handler for.
1410 /* Does the mode require a parameter right now?
1411 * If it does, fetch it if we can
1413 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1416 /* Call the ModeSet method to determine if its set with the
1417 * given parameter here or not.
1419 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1421 /* XXX: Really. Dont ask.
1422 * Determine from if its set combined with what the current
1423 * 'state' is (adding or not) as to wether we should 'invert'
1424 * or 'reinforce' the mode change
1426 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1428 /* Quickly determine if we have 'flipped' from + to -,
1429 * or - to +, to prevent unneccessary +/- chars in the
1430 * output string that waste bandwidth
1432 if (cur_change != old_change)
1433 modebounce += cur_change;
1434 old_change = cur_change;
1436 /* Add the mode character to the output string */
1437 modebounce += mh->GetModeChar();
1439 /* We got a parameter back from ModeHandler::ModeSet,
1440 * are we supposed to be sending one out right now?
1442 if (ret.second.length())
1444 if (mh->GetNumParams(cur_change == '+') > 0)
1445 /* Yes we're supposed to be sending out
1446 * the parameter. Make sure it goes
1448 newparams.push_back(ret.second);
1456 /* Update the parameters for FMODE with the new 'bounced' string */
1457 newparams[2] = modebounce;
1458 /* Only send it back the way it came, no need to send it anywhere else */
1459 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1460 Instance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1464 Instance->Log(DEBUG,"Allow modes, TS lower for sender");
1465 /* The server was ulined, but something iffy is up with the TS.
1466 * Sound the alarm bells!
1468 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1470 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());
1472 /* Allow the mode, route it to either server or user command handling */
1474 this->Instance->SendMode(modelist,n,who);
1476 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1478 /* HOT POTATO! PASS IT ON! */
1479 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1481 /* Are we supposed to free the userrec? */
1488 /** FTOPIC command */
1489 bool ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
1491 if (params.size() != 4)
1493 time_t ts = atoi(params[1].c_str());
1494 std::string nsource = source;
1496 chanrec* c = this->Instance->FindChan(params[0]);
1499 if ((ts >= c->topicset) || (!*c->topic))
1501 std::string oldtopic = c->topic;
1502 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1503 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1505 /* if the topic text is the same as the current topic,
1506 * dont bother to send the TOPIC command out, just silently
1507 * update the set time and set nick.
1509 if (oldtopic != params[3])
1511 userrec* user = this->Instance->FindNick(source);
1514 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1518 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1519 nsource = user->server;
1521 /* all done, send it on its way */
1522 params[3] = ":" + params[3];
1523 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1532 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1533 bool ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
1535 /* 1.1 FJOIN works as follows:
1537 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1538 * timestamp 'wins'. From this point on we will refer to this side as the
1539 * winner. The side with the higher timestamp loses, from this point on we
1540 * will call this side the loser or losing side. This should be familiar to
1541 * anyone who's dealt with dreamforge or TS6 before.
1543 * When two sides of a split heal and this occurs, the following things
1546 * If the timestamps are exactly equal, both sides merge their privilages
1547 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1548 * re-created during a split, this is safe to do.
1551 * If the timestamps are NOT equal, the losing side removes all privilage
1552 * modes from all of its users that currently exist in the channel, before
1553 * introducing new users into the channel which are listed in the FJOIN
1554 * command's parameters. This means, all modes +ohv, and privilages added
1555 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1556 * of the channel to match that of the winning side, and the modes of the
1557 * users of the winning side are merged in with the losing side. The loser
1558 * then sends out a set of FMODE commands which 'confirm' that it just
1559 * removed all privilage modes from its existing users, which allows for
1560 * services packages to still work correctly without needing to know the
1561 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1562 * a problem, and services packages must contain code which explicitly
1563 * behaves as TS6 does, removing ops from the losing side of a split where
1564 * neccessary within its internal records, as this state information is
1565 * not explicitly echoed out in that protocol.
1567 * The winning side on the other hand will ignore all user modes from the
1568 * losing side, so only its own modes get applied. Life is simple for those
1569 * who succeed at internets. :-)
1571 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1572 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1573 * you ask? Well, quite simply because we don't need to. They'll be sent
1574 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1575 * the losing side sends any modes for the channel which shouldnt win,
1576 * they wont as their timestamp will be too high :-)
1579 if (params.size() < 3)
1582 char first[MAXBUF]; /* The first parameter of the mode command */
1583 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1584 char* mode_users[127]; /* The values used by the mode command */
1585 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1586 mode_users[0] = first; /* Set this up to be our on-stack value */
1587 mode_users[1] = modestring; /* Same here as above */
1588 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1589 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1591 userrec* who = NULL; /* User we are currently checking */
1592 std::string channel = params[0]; /* Channel name, as a string */
1593 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1595 /* Try and find the channel */
1596 chanrec* chan = this->Instance->FindChan(channel);
1598 /* Initialize channel name in the mode parameters */
1599 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1601 /* default TS is a high value, which if we dont have this
1602 * channel will let the other side apply their modes.
1604 time_t ourTS = Instance->Time(true)+600;
1606 /* Does this channel exist? if it does, get its REAL timestamp */
1610 /* In 1.1, if they have the newer channel, we immediately clear
1611 * all status modes from our users. We then accept their modes.
1612 * If WE have the newer channel its the other side's job to do this.
1613 * Note that this causes the losing server to send out confirming
1618 std::deque<std::string> param_list;
1623 /* Lower the TS here */
1624 if (Utils->AnnounceTSChange && chan)
1625 chan->WriteChannelWithServ(Instance->Config->ServerName,
1626 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1629 param_list.push_back(channel);
1630 /* Zap all the privilage modes on our side */
1631 this->RemoveStatus(Instance->Config->ServerName, param_list);
1634 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1635 irc::tokenstream users(params[2]);
1636 std::string item = "*";
1638 /* do this first, so our mode reversals are correctly received by other servers
1639 * if there is a TS collision.
1641 params[2] = ":" + params[2];
1642 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1644 /* Now, process every 'prefixes,nick' pair */
1647 /* Find next user */
1648 item = users.GetToken();
1650 const char* usr = item.c_str();
1652 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1653 * (is this even possible?) */
1656 const char* permissions = usr;
1658 char* nm = new char[MAXBUF];
1661 /* Iterate through all the prefix values, convert them from prefixes
1662 * to mode letters, and append them to the mode sequence
1664 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1666 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1669 /* This is a valid prefix */
1671 *tnm++ = mh->GetModeChar();
1675 /* Not a valid prefix...
1676 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1678 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1679 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1686 /* Null terminate modes */
1688 /* Advance past the comma, to the nick */
1691 /* Check the user actually exists */
1692 who = this->Instance->FindNick(usr);
1695 /* Did they get any modes? How many times? */
1696 strlcat(modestring, nm, MAXBUF);
1697 for (int k = 0; k < ntimes; k++)
1698 mode_users[modectr++] = strdup(usr);
1700 /* Free temporary buffer used for mode sequence */
1703 /* Check that the user's 'direction' is correct
1704 * based on the server sending the FJOIN. We must
1705 * check each nickname in turn, because the origin of
1706 * the FJOIN may be different to the origin of the nicks
1707 * in the command itself.
1709 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1710 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1712 /* Oh dear oh dear. */
1713 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1716 /* Finally, we can actually place the user into the channel.
1717 * We're sure its right. Final answer, phone a friend.
1719 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1721 /* Have we already queued up MAXMODES modes with parameters
1722 * (+qaohv) ready to be sent to the server?
1724 if (modectr >= (MAXMODES-1))
1726 /* Only actually give the users any status if we lost
1727 * the FJOIN or drew (equal timestamps).
1728 * It isn't actually possible for ourTS to be > TS here,
1729 * only possible to actually have ourTS == TS, or
1730 * ourTS < TS, because if we lost, we already lowered
1731 * our TS above before we entered this loop. We only
1732 * check >= as a safety measure, in case someone stuffed
1733 * up. If someone DID stuff up, it was most likely me.
1734 * Note: I do not like baseball bats in the face...
1738 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1739 this->Instance->SendMode((const char**)mode_users,modectr,who);
1741 /* Something stuffed up, and for some reason, the timestamp is
1742 * NOT lowered right now and should be. Lower it. Usually this
1743 * code won't be executed, doubtless someone will remove it some
1748 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1754 /* Reset all this back to defaults, and
1755 * free any ram we have left allocated.
1757 strcpy(mode_users[1],"+");
1758 for (unsigned int f = 2; f < modectr; f++)
1759 free(mode_users[f]);
1765 /* Remember to free this */
1767 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1768 * We don't try to process the nickname here (that WOULD cause a segfault because
1769 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1770 * in case somehow we're desynched, so that other users which might be able to see
1771 * the nickname get their fair chance to process it.
1773 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1779 /* there werent enough modes built up to flush it during FJOIN,
1780 * or, there are a number left over. flush them out.
1782 if ((modectr > 2) && (who) && (chan))
1786 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1787 this->Instance->SendMode((const char**)mode_users,modectr,who);
1788 /* Yet again, we can't actually get a true value here, if everything else
1789 * is working as it should.
1793 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1799 /* Free anything we have left to free */
1800 for (unsigned int f = 2; f < modectr; f++)
1801 free(mode_users[f]);
1804 /* All done. That wasnt so bad was it, you can wipe
1805 * the sweat from your forehead now. :-)
1811 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1813 if (params.size() < 8)
1815 if (params.size() > 8)
1817 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1820 // NICK age nick host dhost ident +modes ip :gecos
1822 time_t age = atoi(params[0].c_str());
1824 /* This used to have a pretty craq'y loop doing the same thing,
1825 * now we just let the STL do the hard work (more efficiently)
1827 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1828 if (pos_after_plus != std::string::npos)
1829 params[5] = params[5].substr(pos_after_plus);
1831 const char* tempnick = params[1].c_str();
1832 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1834 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1836 if (iter != this->Instance->clientlist.end())
1839 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);
1840 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1841 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1845 userrec* _new = new userrec(this->Instance);
1846 this->Instance->clientlist[tempnick] = _new;
1847 _new->SetFd(FD_MAGIC_NUMBER);
1848 strlcpy(_new->nick, tempnick,NICKMAX-1);
1849 strlcpy(_new->host, params[2].c_str(),63);
1850 strlcpy(_new->dhost, params[3].c_str(),63);
1851 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1852 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1853 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1854 _new->registered = REG_ALL;
1857 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1858 _new->modes[(*v)-65] = 1;
1860 #ifdef SUPPORT_IP6LINKS
1861 if (params[6].find_first_of(":") != std::string::npos)
1862 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1865 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1867 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1869 params[7] = ":" + params[7];
1870 Utils->DoOneToAllButSender(source,"NICK",params,source);
1872 // Increment the Source Servers User Count..
1873 TreeServer* SourceServer = Utils->FindServer(source);
1876 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1877 SourceServer->AddUserCount();
1880 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1885 /** Send one or more FJOINs for a channel of users.
1886 * If the length of a single line is more than 480-NICKMAX
1887 * in length, it is split over multiple lines.
1889 void SendFJoins(TreeServer* Current, chanrec* c)
1893 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1895 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1897 size_t dlen, curlen;
1898 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1900 char* ptr = list + dlen;
1902 CUList *ulist = c->GetUsers();
1903 std::string modes = "";
1904 std::string params = "";
1906 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1908 // The first parameter gets a : before it
1909 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1916 if (curlen > (480-NICKMAX))
1918 buffer.append(list).append("\r\n");
1920 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1928 buffer.append(list).append("\r\n");
1930 /* Sorry for the hax. Because newly created channels assume +nt,
1931 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1933 bool inverted = false;
1934 if (!c->IsModeSet('n'))
1939 if (!c->IsModeSet('t'))
1949 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1952 params.append(" ").append(b->data);
1954 if (params.length() >= MAXMODES)
1956 /* Wrap at MAXMODES */
1957 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");
1963 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1965 /* Only send these if there are any */
1967 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);
1969 this->WriteLine(buffer);
1972 /** Send G, Q, Z and E lines */
1973 void SendXLines(TreeServer* Current)
1977 std::string n = this->Instance->Config->ServerName;
1978 const char* sn = n.c_str();
1980 /* Yes, these arent too nice looking, but they get the job done */
1981 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1983 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);
1984 buffer.append(data);
1986 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1988 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);
1989 buffer.append(data);
1991 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1993 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);
1994 buffer.append(data);
1996 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1998 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);
1999 buffer.append(data);
2001 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
2003 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);
2004 buffer.append(data);
2006 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
2008 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);
2009 buffer.append(data);
2011 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
2013 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);
2014 buffer.append(data);
2016 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
2018 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);
2019 buffer.append(data);
2022 if (!buffer.empty())
2023 this->WriteLine(buffer);
2026 /** Send channel modes and topics */
2027 void SendChannelModes(TreeServer* Current)
2030 std::deque<std::string> list;
2032 std::string n = this->Instance->Config->ServerName;
2033 const char* sn = n.c_str();
2034 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2036 SendFJoins(Current, c->second);
2037 if (*c->second->topic)
2039 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2040 this->WriteLine(data);
2042 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2044 c->second->GetExtList(list);
2045 for (unsigned int j = 0; j < list.size(); j++)
2047 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2052 /** send all users and their oper state/modes */
2053 void SendUsers(TreeServer* Current)
2056 std::deque<std::string> list;
2057 std::string dataline;
2059 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2061 if (u->second->registered == REG_ALL)
2063 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);
2064 this->WriteLine(data);
2065 if (*u->second->oper)
2067 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2068 this->WriteLine(data);
2070 if (*u->second->awaymsg)
2072 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2073 this->WriteLine(data);
2075 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2077 u->second->GetExtList(list);
2078 for (unsigned int j = 0; j < list.size(); j++)
2080 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2086 /** This function is called when we want to send a netburst to a local
2087 * server. There is a set order we must do this, because for example
2088 * users require their servers to exist, and channels require their
2089 * users to exist. You get the idea.
2091 void DoBurst(TreeServer* s)
2093 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2094 std::string endburst = "ENDBURST";
2095 // Because by the end of the netburst, it could be gone!
2096 std::string name = s->GetName();
2097 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2098 this->WriteLine(burst);
2099 /* send our version string */
2100 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2101 /* Send server tree */
2102 this->SendServers(Utils->TreeRoot,s,1);
2103 /* Send users and their oper status */
2105 /* Send everything else (channel modes, xlines etc) */
2106 this->SendChannelModes(s);
2107 this->SendXLines(s);
2108 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2109 this->WriteLine(endburst);
2110 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2113 /** This function is called when we receive data from a remote
2114 * server. We buffer the data in a std::string (it doesnt stay
2115 * there for long), reading using InspSocket::Read() which can
2116 * read up to 16 kilobytes in one operation.
2118 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2119 * THE SOCKET OBJECT FOR US.
2121 virtual bool OnDataReady()
2123 char* data = this->Read();
2124 /* Check that the data read is a valid pointer and it has some content */
2127 this->in_buffer.append(data);
2128 /* While there is at least one new line in the buffer,
2129 * do something useful (we hope!) with it.
2131 while (in_buffer.find("\n") != std::string::npos)
2133 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2134 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2135 /* Use rfind here not find, as theres more
2136 * chance of the \r being near the end of the
2137 * string, not the start.
2139 if (ret.find("\r") != std::string::npos)
2140 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2141 /* Process this one, abort if it
2142 * didnt return true.
2148 memset(result,0,1024);
2150 /* ERROR + CAPAB is still allowed unencryped */
2151 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2153 int nbytes = from64tobits(out, ret.c_str(), 1024);
2154 if ((nbytes > 0) && (nbytes < 1024))
2156 ctx_in->Decrypt(out, result, nbytes, 0);
2157 for (int t = 0; t < nbytes; t++)
2159 if (result[t] == '\7')
2161 /* We only need to stick a \0 on the
2162 * first \7, the rest will be lost
2172 if (!this->ProcessLine(ret))
2179 /* EAGAIN returns an empty but non-NULL string, so this
2180 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2182 return (data && !*data);
2185 int WriteLine(std::string line)
2187 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2191 char result64[10240];
2192 if (this->keylength)
2194 // pad it to the key length
2195 int n = this->keylength - (line.length() % this->keylength);
2197 line.append(n,'\7');
2199 unsigned int ll = line.length();
2200 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2201 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2204 line.append("\r\n");
2205 return this->Write(line);
2208 /* Handle ERROR command */
2209 bool Error(std::deque<std::string> ¶ms)
2211 if (params.size() < 1)
2213 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2214 /* we will return false to cause the socket to close. */
2218 /** remote MOTD. leet, huh? */
2219 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2221 if (params.size() > 0)
2223 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2225 /* It's for our server */
2226 string_list results;
2227 userrec* source = this->Instance->FindNick(prefix);
2231 std::deque<std::string> par;
2232 par.push_back(prefix);
2235 if (!Instance->Config->MOTD.size())
2237 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2238 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2242 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2243 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2245 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2247 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2248 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2251 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2252 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2258 userrec* source = this->Instance->FindNick(prefix);
2260 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2266 /** remote ADMIN. leet, huh? */
2267 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2269 if (params.size() > 0)
2271 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2273 /* It's for our server */
2274 string_list results;
2275 userrec* source = this->Instance->FindNick(prefix);
2279 std::deque<std::string> par;
2280 par.push_back(prefix);
2283 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2284 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2286 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2287 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2289 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2290 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2292 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2293 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2299 userrec* source = this->Instance->FindNick(prefix);
2301 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2307 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2309 /* Get the reply to a STATS query if it matches this servername,
2310 * and send it back as a load of PUSH queries
2312 if (params.size() > 1)
2314 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2316 /* It's for our server */
2317 string_list results;
2318 userrec* source = this->Instance->FindNick(prefix);
2321 std::deque<std::string> par;
2322 par.push_back(prefix);
2324 DoStats(this->Instance, *(params[0].c_str()), source, results);
2325 for (size_t i = 0; i < results.size(); i++)
2327 par[1] = "::" + results[i];
2328 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2335 userrec* source = this->Instance->FindNick(prefix);
2337 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2344 /** Because the core won't let users or even SERVERS set +o,
2345 * we use the OPERTYPE command to do this.
2347 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2349 if (params.size() != 1)
2351 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2354 std::string opertype = params[0];
2355 userrec* u = this->Instance->FindNick(prefix);
2358 u->modes[UM_OPERATOR] = 1;
2359 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2360 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2365 /** Because Andy insists that services-compatible servers must
2366 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2368 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2370 if (params.size() < 3)
2373 userrec* u = this->Instance->FindNick(params[0]);
2377 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2380 std::deque<std::string> par;
2381 par.push_back(params[1]);
2382 /* This is not required as one is sent in OnUserPostNick below
2384 //Utils->DoOneToMany(u->nick,"NICK",par);
2385 if (!u->ForceNickChange(params[1].c_str()))
2387 userrec::QuitUser(this->Instance, u, "Nickname collision");
2390 u->age = atoi(params[2].c_str());
2396 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2398 if (params.size() < 2)
2401 userrec* u = this->Instance->FindNick(params[0]);
2405 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2406 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2411 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2413 if (params.size() < 1)
2416 std::string servermask = params[0];
2418 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2420 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2421 this->Instance->RehashServer();
2422 Utils->ReadConfiguration(false);
2423 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2425 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2429 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2431 if (params.size() != 2)
2434 std::string nick = params[0];
2435 userrec* u = this->Instance->FindNick(prefix);
2436 userrec* who = this->Instance->FindNick(nick);
2440 /* Prepend kill source, if we don't have one */
2441 std::string sourceserv = prefix;
2444 sourceserv = u->server;
2446 if (*(params[1].c_str()) != '[')
2448 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2450 std::string reason = params[1];
2451 params[1] = ":" + params[1];
2452 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2453 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2454 userrec::QuitUser(this->Instance,who,reason);
2459 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2461 if (params.size() < 1)
2464 if (params.size() == 1)
2466 TreeServer* ServerSource = Utils->FindServer(prefix);
2469 ServerSource->SetPingFlag();
2474 std::string forwardto = params[1];
2475 if (forwardto == this->Instance->Config->ServerName)
2478 * this is a PONG for us
2479 * if the prefix is a user, check theyre local, and if they are,
2480 * dump the PONG reply back to their fd. If its a server, do nowt.
2481 * Services might want to send these s->s, but we dont need to yet.
2483 userrec* u = this->Instance->FindNick(prefix);
2487 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2492 // not for us, pass it on :)
2493 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2500 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2502 if (params.size() < 3)
2505 TreeServer* ServerSource = Utils->FindServer(prefix);
2509 if (params[0] == "*")
2511 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2513 else if (*(params[0].c_str()) == '#')
2515 chanrec* c = this->Instance->FindChan(params[0]);
2518 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2521 else if (*(params[0].c_str()) != '#')
2523 userrec* u = this->Instance->FindNick(params[0]);
2526 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2531 params[2] = ":" + params[2];
2532 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2536 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2538 if (params.size() < 1)
2541 TreeServer* ServerSource = Utils->FindServer(prefix);
2545 ServerSource->SetVersion(params[0]);
2547 params[0] = ":" + params[0];
2548 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2552 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2554 if (params.size() < 1)
2557 userrec* u = this->Instance->FindNick(prefix);
2561 u->ChangeDisplayedHost(params[0].c_str());
2562 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2567 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2569 if (params.size() < 6)
2572 bool propogate = false;
2574 switch (*(params[0].c_str()))
2577 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2578 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2581 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2582 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2585 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2586 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2589 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2590 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2593 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2596 /* Just in case... */
2597 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2602 /* Send it on its way */
2605 if (atoi(params[4].c_str()))
2607 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());
2611 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());
2613 params[5] = ":" + params[5];
2614 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2616 if (!this->bursting)
2618 Instance->Log(DEBUG,"Applying lines...");
2619 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2624 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2626 if (params.size() < 1)
2629 userrec* u = this->Instance->FindNick(prefix);
2633 u->ChangeName(params[0].c_str());
2634 params[0] = ":" + params[0];
2635 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2640 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2642 if (params.size() < 1)
2645 Instance->Log(DEBUG,"In IDLE command");
2646 userrec* u = this->Instance->FindNick(prefix);
2650 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2651 // an incoming request
2652 if (params.size() == 1)
2654 userrec* x = this->Instance->FindNick(params[0]);
2655 if ((x) && (IS_LOCAL(x)))
2657 userrec* x = this->Instance->FindNick(params[0]);
2658 char signon[MAXBUF];
2661 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2662 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2663 std::deque<std::string> par;
2664 par.push_back(prefix);
2665 par.push_back(signon);
2666 par.push_back(idle);
2667 // ours, we're done, pass it BACK
2668 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2672 // not ours pass it on
2673 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2676 else if (params.size() == 3)
2678 std::string who_did_the_whois = params[0];
2679 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2680 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2682 // an incoming reply to a whois we sent out
2683 std::string nick_whoised = prefix;
2684 unsigned long signon = atoi(params[1].c_str());
2685 unsigned long idle = atoi(params[2].c_str());
2686 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2687 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2691 // not ours, pass it on
2692 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2699 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2701 if (params.size() < 2)
2704 userrec* u = this->Instance->FindNick(params[0]);
2711 u->Write(params[1]);
2715 // continue the raw onwards
2716 params[1] = ":" + params[1];
2717 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2722 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2724 if (!params.size() || !Utils->EnableTimeSync)
2729 if ((params.size() == 2) && (params[1] == "FORCE"))
2732 time_t rts = atoi(params[0].c_str());
2733 time_t us = Instance->Time(true);
2737 Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2739 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2741 else if (force || (rts < us))
2743 int old = Instance->SetTimeDelta(rts - us);
2744 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2746 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2750 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2752 std::deque<std::string> oparams;
2753 oparams.push_back(ConvToStr(us));
2755 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2761 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2763 // :source.server TIME remote.server sendernick
2764 // :remote.server TIME source.server sendernick TS
2765 if (params.size() == 2)
2767 // someone querying our time?
2768 if (this->Instance->Config->ServerName == params[0])
2770 userrec* u = this->Instance->FindNick(params[1]);
2773 params.push_back(ConvToStr(Instance->Time(false)));
2775 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2780 // not us, pass it on
2781 userrec* u = this->Instance->FindNick(params[1]);
2783 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2786 else if (params.size() == 3)
2788 // a response to a previous TIME
2789 userrec* u = this->Instance->FindNick(params[1]);
2790 if ((u) && (IS_LOCAL(u)))
2792 time_t rawtime = atol(params[2].c_str());
2793 struct tm * timeinfo;
2794 timeinfo = localtime(&rawtime);
2796 snprintf(tms,26,"%s",asctime(timeinfo));
2798 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2803 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2809 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2811 if (params.size() < 1)
2814 if (params.size() == 1)
2816 std::string stufftobounce = params[0];
2817 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2822 std::string forwardto = params[1];
2823 if (forwardto == this->Instance->Config->ServerName)
2825 // this is a ping for us, send back PONG to the requesting server
2826 params[1] = params[0];
2827 params[0] = forwardto;
2828 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2832 // not for us, pass it on :)
2833 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2839 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2841 if (params.size() < 1)
2844 chanrec* c = Instance->FindChan(params[0]);
2848 irc::modestacker modestack(false);
2849 CUList *ulist = c->GetUsers();
2851 std::deque<std::string> stackresult;
2854 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2856 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2857 if (modesequence.length())
2859 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2860 irc::spacesepstream sep(modesequence);
2861 std::string modeletters = sep.GetToken();
2862 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2864 while (!modeletters.empty())
2866 char mletter = *(modeletters.begin());
2867 modestack.Push(mletter,sep.GetToken());
2868 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2869 modeletters.erase(modeletters.begin());
2870 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2875 while (modestack.GetStackedLine(stackresult))
2877 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2878 stackresult.push_front(ConvToStr(c->age));
2879 stackresult.push_front(c->name);
2880 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2881 stackresult.erase(stackresult.begin() + 1);
2882 Instance->Log(DEBUG,"Stacked items:");
2883 for (size_t z = 0; z < stackresult.size(); z++)
2885 y[z] = stackresult[z].c_str();
2886 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2888 userrec* n = new userrec(Instance);
2889 n->SetFd(FD_MAGIC_NUMBER);
2890 Instance->SendMode(y, stackresult.size(), n);
2897 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2899 if (params.size() < 4)
2902 std::string servername = params[0];
2903 std::string password = params[1];
2904 // hopcount is not used for a remote server, we calculate this ourselves
2905 std::string description = params[3];
2906 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2910 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2913 TreeServer* CheckDupe = Utils->FindServer(servername);
2916 this->WriteLine("ERROR :Server "+servername+" already exists!");
2917 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2920 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2921 ParentOfThis->AddChild(Node);
2922 params[3] = ":" + params[3];
2923 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2924 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2928 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2930 if (params.size() < 4)
2933 irc::string servername = params[0].c_str();
2934 std::string sname = params[0];
2935 std::string password = params[1];
2936 int hops = atoi(params[2].c_str());
2940 this->WriteLine("ERROR :Server too far away for authentication");
2941 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2944 std::string description = params[3];
2945 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2947 if ((x->Name == servername) && (x->RecvPass == password))
2949 TreeServer* CheckDupe = Utils->FindServer(sname);
2952 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2953 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2956 // Begin the sync here. this kickstarts the
2957 // other side, waiting in WAIT_AUTH_2 state,
2958 // into starting their burst, as it shows
2959 // that we're happy.
2960 this->LinkState = CONNECTED;
2961 // we should add the details of this server now
2962 // to the servers tree, as a child of the root
2964 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2965 Utils->TreeRoot->AddChild(Node);
2966 params[3] = ":" + params[3];
2967 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2968 this->bursting = true;
2969 this->DoBurst(Node);
2973 this->WriteLine("ERROR :Invalid credentials");
2974 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2978 bool Inbound_Server(std::deque<std::string> ¶ms)
2980 if (params.size() < 4)
2983 irc::string servername = params[0].c_str();
2984 std::string sname = params[0];
2985 std::string password = params[1];
2986 int hops = atoi(params[2].c_str());
2990 this->WriteLine("ERROR :Server too far away for authentication");
2991 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2994 std::string description = params[3];
2995 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2997 if ((x->Name == servername) && (x->RecvPass == password))
2999 TreeServer* CheckDupe = Utils->FindServer(sname);
3002 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3003 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3006 /* If the config says this link is encrypted, but the remote side
3007 * hasnt bothered to send the AES command before SERVER, then we
3008 * boot them off as we MUST have this connection encrypted.
3010 if ((x->EncryptionKey != "") && (!this->ctx_in))
3012 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
3013 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
3016 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
3017 this->InboundServerName = sname;
3018 this->InboundDescription = description;
3019 // this is good. Send our details: Our server name and description and hopcount of 0,
3020 // along with the sendpass from this block.
3021 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3022 // move to the next state, we are now waiting for THEM.
3023 this->LinkState = WAIT_AUTH_2;
3027 this->WriteLine("ERROR :Invalid credentials");
3028 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3032 void Split(const std::string &line, std::deque<std::string> &n)
3035 irc::tokenstream tokens(line);
3037 while ((param = tokens.GetToken()) != "")
3042 bool ProcessLine(std::string &line)
3044 std::deque<std::string> params;
3045 irc::string command;
3051 line = line.substr(0, line.find_first_of("\r\n"));
3053 Instance->Log(DEBUG,"IN: %s", line.c_str());
3055 this->Split(line.c_str(),params);
3057 if ((params[0][0] == ':') && (params.size() > 1))
3059 prefix = params[0].substr(1);
3063 command = params[0].c_str();
3066 if ((!this->ctx_in) && (command == "AES"))
3068 std::string sserv = params[0];
3069 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3071 if ((x->EncryptionKey != "") && (x->Name == sserv))
3073 this->InitAES(x->EncryptionKey,sserv);
3079 else if ((this->ctx_in) && (command == "AES"))
3081 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());
3084 switch (this->LinkState)
3089 // Waiting for SERVER command from remote server. Server initiating
3090 // the connection sends the first SERVER command, listening server
3091 // replies with theirs if its happy, then if the initiator is happy,
3092 // it starts to send its net sync, which starts the merge, otherwise
3093 // it sends an ERROR.
3094 if (command == "PASS")
3096 /* Silently ignored */
3098 else if (command == "SERVER")
3100 return this->Inbound_Server(params);
3102 else if (command == "ERROR")
3104 return this->Error(params);
3106 else if (command == "USER")
3108 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3111 else if (command == "CAPAB")
3113 return this->Capab(params);
3115 else if ((command == "U") || (command == "S"))
3117 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3122 std::string error("ERROR :Invalid command in negotiation phase: ");
3123 error.append(command.c_str());
3124 this->WriteLine(error);
3129 // Waiting for start of other side's netmerge to say they liked our
3131 if (command == "SERVER")
3133 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3137 else if ((command == "U") || (command == "S"))
3139 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3142 else if (command == "BURST")
3144 if (params.size() && Utils->EnableTimeSync)
3146 /* If a time stamp is provided, apply synchronization */
3148 time_t them = atoi(params[0].c_str());
3149 time_t us = Instance->Time(true);
3150 int delta = them - us;
3152 if ((params.size() == 2) && (params[1] == "FORCE"))
3155 if ((delta < -600) || (delta > 600))
3157 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));
3158 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3164 this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3166 else if (force || (us > them))
3168 this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3169 this->Instance->SetTimeDelta(them - us);
3170 // Send this new timestamp to any other servers
3171 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3175 // Override the timestamp
3176 this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3177 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3180 this->LinkState = CONNECTED;
3181 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3182 Utils->TreeRoot->AddChild(Node);
3184 params.push_back(InboundServerName);
3185 params.push_back("*");
3186 params.push_back("1");
3187 params.push_back(":"+InboundDescription);
3188 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3189 this->bursting = true;
3190 this->DoBurst(Node);
3192 else if (command == "ERROR")
3194 return this->Error(params);
3196 else if (command == "CAPAB")
3198 return this->Capab(params);
3203 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3207 if (command == "SERVER")
3209 // another server we connected to, which was in WAIT_AUTH_1 state,
3210 // has just sent us their credentials. If we get this far, theyre
3211 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3212 // if we're happy with this, we should send our netburst which
3213 // kickstarts the merge.
3214 return this->Outbound_Reply_Server(params);
3216 else if (command == "ERROR")
3218 return this->Error(params);
3222 // This is the 'authenticated' state, when all passwords
3223 // have been exchanged and anything past this point is taken
3228 std::string direction = prefix;
3229 userrec* t = this->Instance->FindNick(prefix);
3232 direction = t->server;
3234 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3235 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3237 if (route_back_again)
3238 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3243 * When there is activity on the socket, reset the ping counter so
3244 * that we're not wasting bandwidth pinging an active server.
3246 route_back_again->SetNextPingTime(time(NULL) + 60);
3247 route_back_again->SetPingFlag();
3250 if (command == "SVSMODE")
3252 /* Services expects us to implement
3253 * SVSMODE. In inspircd its the same as
3258 std::string target = "";
3259 /* Yes, know, this is a mess. Its reasonably fast though as we're
3260 * working with std::string here.
3262 if ((command == "NICK") && (params.size() > 1))
3264 return this->IntroduceClient(prefix,params);
3266 else if (command == "FJOIN")
3268 return this->ForceJoin(prefix,params);
3270 else if (command == "STATS")
3272 return this->Stats(prefix, params);
3274 else if (command == "MOTD")
3276 return this->Motd(prefix, params);
3278 else if (command == "ADMIN")
3280 return this->Admin(prefix, params);
3282 else if (command == "SERVER")
3284 return this->RemoteServer(prefix,params);
3286 else if (command == "ERROR")
3288 return this->Error(params);
3290 else if (command == "OPERTYPE")
3292 return this->OperType(prefix,params);
3294 else if (command == "FMODE")
3296 return this->ForceMode(prefix,params);
3298 else if (command == "KILL")
3300 return this->RemoteKill(prefix,params);
3302 else if (command == "FTOPIC")
3304 return this->ForceTopic(prefix,params);
3306 else if (command == "REHASH")
3308 return this->RemoteRehash(prefix,params);
3310 else if (command == "METADATA")
3312 return this->MetaData(prefix,params);
3314 else if (command == "REMSTATUS")
3316 return this->RemoveStatus(prefix,params);
3318 else if (command == "PING")
3321 * We just got a ping from a server that's bursting.
3322 * This can't be right, so set them to not bursting, and
3323 * apply their lines.
3327 this->bursting = false;
3328 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3332 prefix = this->GetName();
3334 return this->LocalPing(prefix,params);
3336 else if (command == "PONG")
3339 * We just got a pong from a server that's bursting.
3340 * This can't be right, so set them to not bursting, and
3341 * apply their lines.
3345 this->bursting = false;
3346 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3350 prefix = this->GetName();
3352 return this->LocalPong(prefix,params);
3354 else if (command == "VERSION")
3356 return this->ServerVersion(prefix,params);
3358 else if (command == "FHOST")
3360 return this->ChangeHost(prefix,params);
3362 else if (command == "FNAME")
3364 return this->ChangeName(prefix,params);
3366 else if (command == "ADDLINE")
3368 return this->AddLine(prefix,params);
3370 else if (command == "SVSNICK")
3374 prefix = this->GetName();
3376 return this->ForceNick(prefix,params);
3378 else if (command == "IDLE")
3380 return this->Whois(prefix,params);
3382 else if (command == "PUSH")
3384 return this->Push(prefix,params);
3386 else if (command == "TIMESET")
3388 return this->HandleSetTime(prefix, params);
3390 else if (command == "TIME")
3392 return this->Time(prefix,params);
3394 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3396 std::string sourceserv = this->myhost;
3397 if (params.size() == 3)
3399 userrec* user = this->Instance->FindNick(params[1]);
3400 chanrec* chan = this->Instance->FindChan(params[0]);
3403 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3404 /* Yikes, the channels gone! */
3408 if (this->InboundServerName != "")
3410 sourceserv = this->InboundServerName;
3412 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3414 else if (command == "SVSJOIN")
3418 prefix = this->GetName();
3420 return this->ServiceJoin(prefix,params);
3422 else if (command == "SQUIT")
3424 if (params.size() == 2)
3426 this->Squit(Utils->FindServer(params[0]),params[1]);
3430 else if (command == "OPERNOTICE")
3432 std::string sourceserv = this->myhost;
3434 if (this->InboundServerName != "")
3435 sourceserv = this->InboundServerName;
3437 if (params.size() >= 1)
3438 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3440 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3442 else if (command == "MODENOTICE")
3444 std::string sourceserv = this->myhost;
3445 if (this->InboundServerName != "")
3446 sourceserv = this->InboundServerName;
3447 if (params.size() >= 2)
3449 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3452 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3454 else if (command == "SNONOTICE")
3456 std::string sourceserv = this->myhost;
3457 if (this->InboundServerName != "")
3458 sourceserv = this->InboundServerName;
3459 if (params.size() >= 2)
3461 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3464 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3466 else if (command == "ENDBURST")
3468 this->bursting = false;
3469 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3470 std::string sourceserv = this->myhost;
3471 if (this->InboundServerName != "")
3473 sourceserv = this->InboundServerName;
3475 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3477 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3478 rmode.Send(Instance);
3484 // not a special inter-server command.
3485 // Emulate the actual user doing the command,
3486 // this saves us having a huge ugly parser.
3487 userrec* who = this->Instance->FindNick(prefix);
3488 std::string sourceserv = this->myhost;
3489 if (this->InboundServerName != "")
3491 sourceserv = this->InboundServerName;
3493 if ((!who) && (command == "MODE"))
3495 if (Utils->IsServer(prefix))
3497 const char* modelist[127];
3498 for (size_t i = 0; i < params.size(); i++)
3499 modelist[i] = params[i].c_str();
3501 userrec* fake = new userrec(Instance);
3502 fake->SetFd(FD_MAGIC_NUMBER);
3504 this->Instance->SendMode(modelist, params.size(), fake);
3508 /* Hot potato! pass it on! */
3509 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3514 if ((command == "NICK") && (params.size() > 0))
3516 /* On nick messages, check that the nick doesnt
3517 * already exist here. If it does, kill their copy,
3520 userrec* x = this->Instance->FindNick(params[0]);
3521 if ((x) && (x != who))
3523 std::deque<std::string> p;
3524 p.push_back(params[0]);
3525 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3526 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3528 p.push_back(prefix);
3529 p.push_back("Nickname collision");
3530 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3531 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3532 userrec* y = this->Instance->FindNick(prefix);
3535 userrec::QuitUser(this->Instance,y,"Nickname collision");
3537 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3541 target = who->server;
3542 const char* strparams[127];
3543 for (unsigned int q = 0; q < params.size(); q++)
3545 strparams[q] = params[q].c_str();
3547 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3550 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3557 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3563 // its not a user. Its either a server, or somethings screwed up.
3564 if (Utils->IsServer(prefix))
3566 target = this->Instance->Config->ServerName;
3570 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3574 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3583 virtual std::string GetName()
3585 std::string sourceserv = this->myhost;
3586 if (this->InboundServerName != "")
3588 sourceserv = this->InboundServerName;
3593 virtual void OnTimeout()
3595 if (this->LinkState == CONNECTING)
3597 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3598 Link* MyLink = Utils->FindLink(myhost);
3600 Utils->DoFailOver(MyLink);
3604 virtual void OnClose()
3606 // Connection closed.
3607 // If the connection is fully up (state CONNECTED)
3608 // then propogate a netsplit to all peers.
3609 std::string quitserver = this->myhost;
3610 if (this->InboundServerName != "")
3612 quitserver = this->InboundServerName;
3614 TreeServer* s = Utils->FindServer(quitserver);
3617 Squit(s,"Remote host closed the connection");
3620 if (quitserver != "")
3621 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3624 virtual int OnIncomingConnection(int newsock, char* ip)
3626 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3627 * or discovering if this port is the server port, we don't allow connections from any
3628 * IPs for which we don't have a link block.
3632 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3635 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3636 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3641 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3646 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3647 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3652 /** This class is used to resolve server hostnames during /connect and autoconnect.
3653 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3654 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3655 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3656 * will have an IP address which we can then use to continue our connection.
3658 class ServernameResolver : public Resolver
3661 /** A copy of the Link tag info for what we're connecting to.
3662 * We take a copy, rather than using a pointer, just in case the
3663 * admin takes the tag away and rehashes while the domain is resolving.
3666 SpanningTreeUtilities* Utils;
3668 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3670 /* Nothing in here, folks */
3673 void OnLookupComplete(const std::string &result)
3675 /* Initiate the connection, now that we have an IP to use.
3676 * Passing a hostname directly to InspSocket causes it to
3677 * just bail and set its FD to -1.
3679 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3680 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3682 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
3683 if (newsocket->GetFd() > -1)
3689 /* Something barfed, show the opers */
3690 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3692 Utils->DoFailOver(&MyLink);
3697 void OnError(ResolverError e, const std::string &errormessage)
3700 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3701 Utils->DoFailOver(&MyLink);
3705 /** Handle resolving of server IPs for the cache
3707 class SecurityIPResolver : public Resolver
3711 SpanningTreeUtilities* Utils;
3713 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3717 void OnLookupComplete(const std::string &result)
3719 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3720 Utils->ValidIPs.push_back(result);
3723 void OnError(ResolverError e, const std::string &errormessage)
3725 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3729 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3732 this->ReadConfiguration(true);
3733 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3736 SpanningTreeUtilities::~SpanningTreeUtilities()
3738 for (unsigned int i = 0; i < Bindings.size(); i++)
3740 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3741 ServerInstance->SE->DelFd(Bindings[i]);
3742 Bindings[i]->Close();
3743 DELETE(Bindings[i]);
3745 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3746 while (TreeRoot->ChildCount())
3748 TreeServer* child_server = TreeRoot->GetChild(0);
3749 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3752 TreeSocket* sock = child_server->GetSocket();
3753 ServerInstance->SE->DelFd(sock);
3761 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3763 for (unsigned int c = 0; c < list.size(); c++)
3765 if (list[c] == server)
3770 list.push_back(server);
3773 /** returns a list of DIRECT servernames for a specific channel */
3774 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3776 CUList *ulist = c->GetUsers();
3777 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3779 if (i->second->GetFd() < 0)
3781 TreeServer* best = this->BestRouteTo(i->second->server);
3783 AddThisServer(best,list);
3789 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3791 TreeServer* omitroute = this->BestRouteTo(omit);
3792 if ((command == "NOTICE") || (command == "PRIVMSG"))
3794 if (params.size() >= 2)
3797 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3799 params[0] = params[0].substr(1, params[0].length()-1);
3801 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3803 // special routing for private messages/notices
3804 userrec* d = ServerInstance->FindNick(params[0]);
3807 std::deque<std::string> par;
3808 par.push_back(params[0]);
3809 par.push_back(":"+params[1]);
3810 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3814 else if (*(params[0].c_str()) == '$')
3816 std::deque<std::string> par;
3817 par.push_back(params[0]);
3818 par.push_back(":"+params[1]);
3819 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3824 chanrec* c = ServerInstance->FindChan(params[0]);
3827 std::deque<TreeServer*> list;
3828 GetListOfServersForChannel(c,list);
3829 unsigned int lsize = list.size();
3830 for (unsigned int i = 0; i < lsize; i++)
3832 TreeSocket* Sock = list[i]->GetSocket();
3833 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3835 Sock->WriteLine(data);
3843 unsigned int items =this->TreeRoot->ChildCount();
3844 for (unsigned int x = 0; x < items; x++)
3846 TreeServer* Route = this->TreeRoot->GetChild(x);
3847 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3849 TreeSocket* Sock = Route->GetSocket();
3851 Sock->WriteLine(data);
3857 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
3859 TreeServer* omitroute = this->BestRouteTo(omit);
3860 std::string FullLine = ":" + prefix + " " + command;
3861 unsigned int words = params.size();
3862 for (unsigned int x = 0; x < words; x++)
3864 FullLine = FullLine + " " + params[x];
3866 unsigned int items = this->TreeRoot->ChildCount();
3867 for (unsigned int x = 0; x < items; x++)
3869 TreeServer* Route = this->TreeRoot->GetChild(x);
3870 // Send the line IF:
3871 // The route has a socket (its a direct connection)
3872 // The route isnt the one to be omitted
3873 // The route isnt the path to the one to be omitted
3874 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3876 TreeSocket* Sock = Route->GetSocket();
3878 Sock->WriteLine(FullLine);
3884 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
3886 std::string FullLine = ":" + prefix + " " + command;
3887 unsigned int words = params.size();
3888 for (unsigned int x = 0; x < words; x++)
3890 FullLine = FullLine + " " + params[x];
3892 unsigned int items = this->TreeRoot->ChildCount();
3893 for (unsigned int x = 0; x < items; x++)
3895 TreeServer* Route = this->TreeRoot->GetChild(x);
3896 if (Route && Route->GetSocket())
3898 TreeSocket* Sock = Route->GetSocket();
3900 Sock->WriteLine(FullLine);
3906 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3908 std::string spfx = prefix;
3909 std::string scmd = command;
3910 return this->DoOneToMany(spfx, scmd, params);
3913 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3915 std::string spfx = prefix;
3916 std::string scmd = command;
3917 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3920 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
3922 TreeServer* Route = this->BestRouteTo(target);
3925 std::string FullLine = ":" + prefix + " " + command;
3926 unsigned int words = params.size();
3927 for (unsigned int x = 0; x < words; x++)
3929 FullLine = FullLine + " " + params[x];
3931 if (Route && Route->GetSocket())
3933 TreeSocket* Sock = Route->GetSocket();
3935 Sock->WriteLine(FullLine);
3945 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3947 ConfigReader* Conf = new ConfigReader(ServerInstance);
3950 for (int j =0; j < Conf->Enumerate("bind"); j++)
3952 std::string Type = Conf->ReadValue("bind","type",j);
3953 std::string IP = Conf->ReadValue("bind","address",j);
3954 std::string Port = Conf->ReadValue("bind","port",j);
3955 if (Type == "servers")
3957 irc::portparser portrange(Port, false);
3959 while ((portno = portrange.GetToken()))
3961 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
3965 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10);
3966 if (listener->GetState() == I_LISTENING)
3968 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
3969 Bindings.push_back(listener);
3973 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
3977 ServerInstance->Log(DEBUG,"Done with this binding");
3982 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3983 HideULines = Conf->ReadFlag("options","hideulines",0);
3984 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3985 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3988 for (int j =0; j < Conf->Enumerate("link"); j++)
3991 std::string Allow = Conf->ReadValue("link","allowmask",j);
3992 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3993 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3994 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3995 L.Port = Conf->ReadInteger("link","port",j,true);
3996 L.SendPass = Conf->ReadValue("link","sendpass",j);
3997 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3998 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3999 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
4000 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
4001 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
4002 L.NextConnectTime = time(NULL) + L.AutoConnect;
4003 /* Bugfix by brain, do not allow people to enter bad configurations */
4004 if (L.Name != ServerInstance->Config->ServerName)
4006 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
4008 ValidIPs.push_back(L.IPAddr);
4011 ValidIPs.push_back(Allow);
4013 /* Needs resolving */
4015 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
4019 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
4020 ServerInstance->AddResolver(sr);
4022 catch (ModuleException& e)
4024 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4028 LinkBlocks.push_back(L);
4029 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4035 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4037 else if (L.RecvPass == "")
4039 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4041 else if (L.SendPass == "")
4043 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4045 else if (L.Name == "")
4047 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4051 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4057 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4063 /** To create a timer which recurs every second, we inherit from InspTimer.
4064 * InspTimer is only one-shot however, so at the end of each Tick() we simply
4065 * insert another of ourselves into the pending queue :)
4067 class TimeSyncTimer : public InspTimer
4071 ModuleSpanningTree *Module;
4073 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4074 virtual void Tick(time_t TIME);
4077 class ModuleSpanningTree : public Module
4081 unsigned int max_local;
4082 unsigned int max_global;
4083 cmd_rconnect* command_rconnect;
4084 SpanningTreeUtilities* Utils;
4087 TimeSyncTimer *SyncTimer;
4089 ModuleSpanningTree(InspIRCd* Me)
4090 : Module::Module(Me), max_local(0), max_global(0)
4092 Utils = new SpanningTreeUtilities(Me, this);
4094 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4095 ServerInstance->AddCommand(command_rconnect);
4097 if (Utils->EnableTimeSync)
4099 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4100 ServerInstance->Timers->AddTimer(SyncTimer);
4106 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4108 std::string Parent = Utils->TreeRoot->GetName();
4109 if (Current->GetParent())
4111 Parent = Current->GetParent()->GetName();
4113 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4115 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4119 ShowLinks(Current->GetChild(q),user,hops+1);
4124 ShowLinks(Current->GetChild(q),user,hops+1);
4127 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4128 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4130 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());
4133 int CountLocalServs()
4135 return Utils->TreeRoot->ChildCount();
4140 return Utils->serverlist.size();
4143 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4145 ShowLinks(Utils->TreeRoot,user,0);
4146 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4150 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4152 unsigned int n_users = ServerInstance->UserCount();
4154 /* Only update these when someone wants to see them, more efficient */
4155 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4156 max_local = ServerInstance->LocalUserCount();
4157 if (n_users > max_global)
4158 max_global = n_users;
4160 unsigned int ulined_count = 0;
4161 unsigned int ulined_local_count = 0;
4163 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4164 * locally and globally (locally means directly connected to us)
4166 if ((Utils->HideULines) && (!*user->oper))
4168 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4170 if (ServerInstance->ULine(q->second->GetName().c_str()))
4173 if (q->second->GetParent() == Utils->TreeRoot)
4174 ulined_local_count++;
4179 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),ulined_count ? this->CountServs() - ulined_count : this->CountServs());
4180 if (ServerInstance->OperCount())
4181 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4182 if (ServerInstance->UnregisteredUserCount())
4183 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4184 if (ServerInstance->ChannelCount())
4185 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4186 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs());
4187 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4188 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4192 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4194 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4198 for (int t = 0; t < depth; t++)
4200 matrix[line][t] = ' ';
4203 // For Aligning, we need to work out exactly how deep this thing is, and produce
4204 // a 'Spacer' String to compensate.
4207 memset(spacer,' ',40);
4208 if ((40 - Current->GetName().length() - depth) > 1) {
4209 spacer[40 - Current->GetName().length() - depth] = '\0';
4218 if (ServerInstance->clientlist.size() == 0) {
4219 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4224 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4226 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4227 totusers += Current->GetUserCount();
4229 strlcpy(&matrix[line][depth],text,80);
4231 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4233 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4237 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4242 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4248 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4252 /* Remote MOTD, the server is within the 1st parameter */
4253 std::deque<std::string> params;
4254 params.push_back(parameters[0]);
4256 /* Send it out remotely, generate no reply yet */
4257 TreeServer* s = Utils->FindServerMask(parameters[0]);
4260 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4264 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4271 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4275 /* Remote ADMIN, the server is within the 1st parameter */
4276 std::deque<std::string> params;
4277 params.push_back(parameters[0]);
4279 /* Send it out remotely, generate no reply yet */
4280 TreeServer* s = Utils->FindServerMask(parameters[0]);
4283 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4287 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4294 int HandleStats(const char** parameters, int pcnt, userrec* user)
4298 /* Remote STATS, the server is within the 2nd parameter */
4299 std::deque<std::string> params;
4300 params.push_back(parameters[0]);
4301 params.push_back(parameters[1]);
4302 /* Send it out remotely, generate no reply yet */
4303 TreeServer* s = Utils->FindServerMask(parameters[1]);
4306 params[1] = s->GetName();
4307 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4311 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4318 // Ok, prepare to be confused.
4319 // After much mulling over how to approach this, it struck me that
4320 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4321 // keeping track of a ton of ascii characters, and line by line
4322 // under recursion working out where to place them using multiplications
4323 // and divisons, we instead render the map onto a backplane of characters
4324 // (a character matrix), then draw the branches as a series of "L" shapes
4325 // from the nodes. This is not only friendlier on CPU it uses less stack.
4327 void HandleMap(const char** parameters, int pcnt, userrec* user)
4329 // This array represents a virtual screen which we will
4330 // "scratch" draw to, as the console device of an irc
4331 // client does not provide for a proper terminal.
4333 float totservers = 0;
4334 char matrix[128][80];
4335 for (unsigned int t = 0; t < 128; t++)
4337 matrix[t][0] = '\0';
4340 // The only recursive bit is called here.
4341 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4342 // Process each line one by one. The algorithm has a limit of
4343 // 128 servers (which is far more than a spanning tree should have
4344 // anyway, so we're ok). This limit can be raised simply by making
4345 // the character matrix deeper, 128 rows taking 10k of memory.
4346 for (int l = 1; l < line; l++)
4348 // scan across the line looking for the start of the
4349 // servername (the recursive part of the algorithm has placed
4350 // the servers at indented positions depending on what they
4352 int first_nonspace = 0;
4353 while (matrix[l][first_nonspace] == ' ')
4358 // Draw the `- (corner) section: this may be overwritten by
4359 // another L shape passing along the same vertical pane, becoming
4360 // a |- (branch) section instead.
4361 matrix[l][first_nonspace] = '-';
4362 matrix[l][first_nonspace-1] = '`';
4364 // Draw upwards until we hit the parent server, causing possibly
4365 // other corners (`-) to become branches (|-)
4366 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4368 matrix[l2][first_nonspace-1] = '|';
4372 // dump the whole lot to the user. This is the easy bit, honest.
4373 for (int t = 0; t < line; t++)
4375 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4377 float avg_users = totusers / totservers;
4378 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);
4379 user->WriteServ("007 %s :End of /MAP",user->nick);
4383 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4385 TreeServer* s = Utils->FindServerMask(parameters[0]);
4388 if (s == Utils->TreeRoot)
4390 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4393 TreeSocket* sock = s->GetSocket();
4396 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4397 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4398 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4399 ServerInstance->SE->DelFd(sock);
4405 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4410 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4415 int HandleTime(const char** parameters, int pcnt, userrec* user)
4417 if ((IS_LOCAL(user)) && (pcnt))
4419 TreeServer* found = Utils->FindServerMask(parameters[0]);
4422 // we dont' override for local server
4423 if (found == Utils->TreeRoot)
4426 std::deque<std::string> params;
4427 params.push_back(found->GetName());
4428 params.push_back(user->nick);
4429 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4433 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4439 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4441 if ((IS_LOCAL(user)) && (pcnt > 1))
4443 userrec* remote = ServerInstance->FindNick(parameters[1]);
4444 if ((remote) && (remote->GetFd() < 0))
4446 std::deque<std::string> params;
4447 params.push_back(parameters[1]);
4448 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4453 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4454 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4461 void DoPingChecks(time_t curtime)
4463 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4465 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4466 TreeSocket* sock = serv->GetSocket();
4469 if (curtime >= serv->NextPingTime())
4471 if (serv->AnsweredLastPing())
4473 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4474 serv->SetNextPingTime(curtime + 60);
4478 // they didnt answer, boot them
4479 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4480 sock->Squit(serv,"Ping timeout");
4481 ServerInstance->SE->DelFd(sock);
4491 void ConnectServer(Link* x)
4495 /* Do we already have an IP? If so, no need to resolve it. */
4496 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4498 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
4499 if (newsocket->GetFd() > -1)
4501 /* Handled automatically on success */
4505 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4507 Utils->DoFailOver(x);
4514 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4515 ServerInstance->AddResolver(snr);
4517 catch (ModuleException& e)
4519 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4520 Utils->DoFailOver(x);
4525 void AutoConnectServers(time_t curtime)
4527 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4529 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4531 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4532 x->NextConnectTime = curtime + x->AutoConnect;
4533 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4534 if (x->FailOver.length())
4536 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4539 /* The failover for this server is currently a member of the network.
4540 * The failover probably succeeded, where the main link did not.
4541 * Don't try the main link until the failover is gone again.
4548 // an autoconnected server is not connected. Check if its time to connect it
4549 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4550 this->ConnectServer(&(*x));
4556 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4558 // we've already checked if pcnt > 0, so this is safe
4559 TreeServer* found = Utils->FindServerMask(parameters[0]);
4562 std::string Version = found->GetVersion();
4563 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4564 if (found == Utils->TreeRoot)
4566 std::stringstream out(ServerInstance->Config->data005);
4567 std::string token = "";
4568 std::string line5 = "";
4569 int token_counter = 0;
4574 line5 = line5 + token + " ";
4577 if ((token_counter >= 13) || (out.eof() == true))
4579 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4588 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4593 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4595 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4597 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4599 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4602 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);
4603 ConnectServer(&(*x));
4608 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());
4613 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4617 void BroadcastTimeSync()
4619 std::deque<std::string> params;
4620 params.push_back(ConvToStr(ServerInstance->Time(true)));
4621 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4624 virtual int OnStats(char statschar, userrec* user, string_list &results)
4626 if (statschar == 'c')
4628 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4630 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');
4631 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4633 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4634 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);
4640 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4642 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4646 if (command == "CONNECT")
4648 return this->HandleConnect(parameters,pcnt,user);
4650 else if (command == "STATS")
4652 return this->HandleStats(parameters,pcnt,user);
4654 else if (command == "MOTD")
4656 return this->HandleMotd(parameters,pcnt,user);
4658 else if (command == "ADMIN")
4660 return this->HandleAdmin(parameters,pcnt,user);
4662 else if (command == "SQUIT")
4664 return this->HandleSquit(parameters,pcnt,user);
4666 else if (command == "MAP")
4668 this->HandleMap(parameters,pcnt,user);
4671 else if ((command == "TIME") && (pcnt > 0))
4673 return this->HandleTime(parameters,pcnt,user);
4675 else if (command == "LUSERS")
4677 this->HandleLusers(parameters,pcnt,user);
4680 else if (command == "LINKS")
4682 this->HandleLinks(parameters,pcnt,user);
4685 else if (command == "WHOIS")
4690 return this->HandleRemoteWhois(parameters,pcnt,user);
4693 else if ((command == "VERSION") && (pcnt > 0))
4695 this->HandleVersion(parameters,pcnt,user);
4702 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4704 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4706 // this bit of code cleverly routes all module commands
4707 // to all remote severs *automatically* so that modules
4708 // can just handle commands locally, without having
4709 // to have any special provision in place for remote
4710 // commands and linking protocols.
4711 std::deque<std::string> params;
4713 for (int j = 0; j < pcnt; j++)
4715 if (strchr(parameters[j],' '))
4717 params.push_back(":" + std::string(parameters[j]));
4721 params.push_back(std::string(parameters[j]));
4724 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4725 Utils->DoOneToMany(user->nick,command,params);
4729 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4731 TreeServer* s = Utils->FindServer(servername);
4734 description = s->GetDesc();
4738 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4740 if (IS_LOCAL(source))
4742 std::deque<std::string> params;
4743 params.push_back(dest->nick);
4744 params.push_back(channel->name);
4745 Utils->DoOneToMany(source->nick,"INVITE",params);
4749 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4751 std::deque<std::string> params;
4752 params.push_back(chan->name);
4753 params.push_back(":"+topic);
4754 Utils->DoOneToMany(user->nick,"TOPIC",params);
4757 virtual void OnWallops(userrec* user, const std::string &text)
4761 std::deque<std::string> params;
4762 params.push_back(":"+text);
4763 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4767 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4769 if (target_type == TYPE_USER)
4771 userrec* d = (userrec*)dest;
4772 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4774 std::deque<std::string> params;
4776 params.push_back(d->nick);
4777 params.push_back(":"+text);
4778 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4781 else if (target_type == TYPE_CHANNEL)
4785 chanrec *c = (chanrec*)dest;
4788 std::string cname = c->name;
4790 cname = status + cname;
4791 std::deque<TreeServer*> list;
4792 Utils->GetListOfServersForChannel(c,list);
4793 unsigned int ucount = list.size();
4794 for (unsigned int i = 0; i < ucount; i++)
4796 TreeSocket* Sock = list[i]->GetSocket();
4798 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4803 else if (target_type == TYPE_SERVER)
4807 char* target = (char*)dest;
4808 std::deque<std::string> par;
4809 par.push_back(target);
4810 par.push_back(":"+text);
4811 Utils->DoOneToMany(user->nick,"NOTICE",par);
4816 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4818 if (target_type == TYPE_USER)
4820 // route private messages which are targetted at clients only to the server
4821 // which needs to receive them
4822 userrec* d = (userrec*)dest;
4823 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4825 std::deque<std::string> params;
4827 params.push_back(d->nick);
4828 params.push_back(":"+text);
4829 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4832 else if (target_type == TYPE_CHANNEL)
4836 chanrec *c = (chanrec*)dest;
4839 std::string cname = c->name;
4841 cname = status + cname;
4842 std::deque<TreeServer*> list;
4843 Utils->GetListOfServersForChannel(c,list);
4844 unsigned int ucount = list.size();
4845 for (unsigned int i = 0; i < ucount; i++)
4847 TreeSocket* Sock = list[i]->GetSocket();
4849 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4854 else if (target_type == TYPE_SERVER)
4858 char* target = (char*)dest;
4859 std::deque<std::string> par;
4860 par.push_back(target);
4861 par.push_back(":"+text);
4862 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4867 virtual void OnBackgroundTimer(time_t curtime)
4869 AutoConnectServers(curtime);
4870 DoPingChecks(curtime);
4873 virtual void OnUserJoin(userrec* user, chanrec* channel)
4875 // Only do this for local users
4878 std::deque<std::string> params;
4880 params.push_back(channel->name);
4881 // set up their permissions and the channel TS with FJOIN.
4882 // All users are FJOINed now, because a module may specify
4883 // new joining permissions for the user.
4885 params.push_back(channel->name);
4886 params.push_back(ConvToStr(channel->age));
4887 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4888 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4889 if (channel->GetUserCounter() == 1)
4891 /* First user in, sync the modes for the channel */
4893 /* This is safe, all inspircd servers default to +nt */
4894 params.push_back("+nt");
4895 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
4900 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4902 // only occurs for local clients
4903 if (user->registered != REG_ALL)
4905 std::deque<std::string> params;
4906 params.push_back(newhost);
4907 Utils->DoOneToMany(user->nick,"FHOST",params);
4910 virtual void OnChangeName(userrec* user, const std::string &gecos)
4912 // only occurs for local clients
4913 if (user->registered != REG_ALL)
4915 std::deque<std::string> params;
4916 params.push_back(gecos);
4917 Utils->DoOneToMany(user->nick,"FNAME",params);
4920 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4924 std::deque<std::string> params;
4925 params.push_back(channel->name);
4926 if (partmessage != "")
4927 params.push_back(":"+partmessage);
4928 Utils->DoOneToMany(user->nick,"PART",params);
4932 virtual void OnUserConnect(userrec* user)
4934 char agestr[MAXBUF];
4937 std::deque<std::string> params;
4938 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4939 params.push_back(agestr);
4940 params.push_back(user->nick);
4941 params.push_back(user->host);
4942 params.push_back(user->dhost);
4943 params.push_back(user->ident);
4944 params.push_back("+"+std::string(user->FormatModes()));
4945 params.push_back(user->GetIPString());
4946 params.push_back(":"+std::string(user->fullname));
4947 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4949 // User is Local, change needs to be reflected!
4950 TreeServer* SourceServer = Utils->FindServer(user->server);
4953 SourceServer->AddUserCount();
4959 virtual void OnUserQuit(userrec* user, const std::string &reason)
4961 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4963 std::deque<std::string> params;
4964 params.push_back(":"+reason);
4965 Utils->DoOneToMany(user->nick,"QUIT",params);
4967 // Regardless, We need to modify the user Counts..
4968 TreeServer* SourceServer = Utils->FindServer(user->server);
4971 SourceServer->DelUserCount();
4976 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4980 std::deque<std::string> params;
4981 params.push_back(user->nick);
4982 Utils->DoOneToMany(oldnick,"NICK",params);
4986 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4988 if ((source) && (IS_LOCAL(source)))
4990 std::deque<std::string> params;
4991 params.push_back(chan->name);
4992 params.push_back(user->nick);
4993 params.push_back(":"+reason);
4994 Utils->DoOneToMany(source->nick,"KICK",params);
4998 std::deque<std::string> params;
4999 params.push_back(chan->name);
5000 params.push_back(user->nick);
5001 params.push_back(":"+reason);
5002 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
5006 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
5008 std::deque<std::string> params;
5009 params.push_back(dest->nick);
5010 params.push_back(":"+reason);
5011 Utils->DoOneToMany(source->nick,"KILL",params);
5014 virtual void OnRehash(const std::string ¶meter)
5016 if (parameter != "")
5018 std::deque<std::string> params;
5019 params.push_back(parameter);
5020 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
5022 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5024 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
5025 ServerInstance->RehashServer();
5028 Utils->ReadConfiguration(false);
5031 // note: the protocol does not allow direct umode +o except
5032 // via NICK with 8 params. sending OPERTYPE infers +o modechange
5034 virtual void OnOper(userrec* user, const std::string &opertype)
5038 std::deque<std::string> params;
5039 params.push_back(opertype);
5040 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5044 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5048 /* Server-set lines */
5050 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5051 (unsigned long)duration, reason.c_str());
5052 std::deque<std::string> params;
5053 params.push_back(data);
5054 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5058 if (IS_LOCAL(source))
5061 snprintf(type,8,"%cLINE",linetype);
5062 std::string stype = type;
5065 char sduration[MAXBUF];
5066 snprintf(sduration,MAXBUF,"%ld",duration);
5067 std::deque<std::string> params;
5068 params.push_back(host);
5069 params.push_back(sduration);
5070 params.push_back(":"+reason);
5071 Utils->DoOneToMany(source->nick,stype,params);
5075 std::deque<std::string> params;
5076 params.push_back(host);
5077 Utils->DoOneToMany(source->nick,stype,params);
5083 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5085 OnLine(source,hostmask,true,'G',duration,reason);
5088 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5090 OnLine(source,ipmask,true,'Z',duration,reason);
5093 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5095 OnLine(source,nickmask,true,'Q',duration,reason);
5098 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5100 OnLine(source,hostmask,true,'E',duration,reason);
5103 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5105 OnLine(source,hostmask,false,'G',0,"");
5108 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5110 OnLine(source,ipmask,false,'Z',0,"");
5113 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5115 OnLine(source,nickmask,false,'Q',0,"");
5118 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5120 OnLine(source,hostmask,false,'E',0,"");
5123 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5125 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5127 if (target_type == TYPE_USER)
5129 userrec* u = (userrec*)dest;
5130 std::deque<std::string> params;
5131 params.push_back(u->nick);
5132 params.push_back(text);
5133 Utils->DoOneToMany(user->nick,"MODE",params);
5137 chanrec* c = (chanrec*)dest;
5138 std::deque<std::string> params;
5139 params.push_back(c->name);
5140 params.push_back(text);
5141 Utils->DoOneToMany(user->nick,"MODE",params);
5146 virtual void OnSetAway(userrec* user)
5150 std::deque<std::string> params;
5151 params.push_back(":"+std::string(user->awaymsg));
5152 Utils->DoOneToMany(user->nick,"AWAY",params);
5156 virtual void OnCancelAway(userrec* user)
5160 std::deque<std::string> params;
5162 Utils->DoOneToMany(user->nick,"AWAY",params);
5166 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5168 TreeSocket* s = (TreeSocket*)opaque;
5171 if (target_type == TYPE_USER)
5173 userrec* u = (userrec*)target;
5174 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5178 chanrec* c = (chanrec*)target;
5179 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5184 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5186 TreeSocket* s = (TreeSocket*)opaque;
5189 if (target_type == TYPE_USER)
5191 userrec* u = (userrec*)target;
5192 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5194 else if (target_type == TYPE_OTHER)
5196 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5198 else if (target_type == TYPE_CHANNEL)
5200 chanrec* c = (chanrec*)target;
5201 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5206 virtual void OnEvent(Event* event)
5208 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5210 if (event->GetEventID() == "send_metadata")
5212 if (params->size() < 3)
5214 (*params)[2] = ":" + (*params)[2];
5215 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5217 else if (event->GetEventID() == "send_topic")
5219 if (params->size() < 2)
5221 (*params)[1] = ":" + (*params)[1];
5222 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5223 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5224 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5226 else if (event->GetEventID() == "send_mode")
5228 if (params->size() < 2)
5230 // Insert the TS value of the object, either userrec or chanrec
5232 userrec* a = ServerInstance->FindNick((*params)[0]);
5239 chanrec* a = ServerInstance->FindChan((*params)[0]);
5245 params->insert(params->begin() + 1,ConvToStr(ourTS));
5246 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5248 else if (event->GetEventID() == "send_mode_explicit")
5250 if (params->size() < 2)
5252 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5254 else if (event->GetEventID() == "send_opers")
5256 if (params->size() < 1)
5258 (*params)[0] = ":" + (*params)[0];
5259 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5261 else if (event->GetEventID() == "send_modeset")
5263 if (params->size() < 2)
5265 (*params)[1] = ":" + (*params)[1];
5266 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5268 else if (event->GetEventID() == "send_snoset")
5270 if (params->size() < 2)
5272 (*params)[1] = ":" + (*params)[1];
5273 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5275 else if (event->GetEventID() == "send_push")
5277 if (params->size() < 2)
5280 userrec *a = ServerInstance->FindNick((*params)[0]);
5285 (*params)[1] = ":" + (*params)[1];
5286 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5290 virtual ~ModuleSpanningTree()
5292 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5293 /* This will also free the listeners */
5296 ServerInstance->Timers->DelTimer(SyncTimer);
5299 virtual Version GetVersion()
5301 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5304 void Implements(char* List)
5306 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5307 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5308 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5309 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5310 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5311 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5312 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5315 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5316 * so that any activity it sees is FINAL, e.g. we arent going to send out
5317 * a NICK message before m_cloaking has finished putting the +x on the user,
5319 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5320 * the module call queue.
5322 Priority Prioritize()
5324 return PRIORITY_LAST;
5328 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5332 void TimeSyncTimer::Tick(time_t TIME)
5334 Module->BroadcastTimeSync();
5335 Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5336 Instance->Timers->AddTimer(Module->SyncTimer);
5339 void SpanningTreeUtilities::DoFailOver(Link* x)
5341 if (x->FailOver.length())
5343 if (x->FailOver == x->Name)
5345 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());
5348 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5351 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5352 Creator->ConnectServer(TryThisOne);
5356 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5361 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5363 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5365 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5373 class ModuleSpanningTreeFactory : public ModuleFactory
5376 ModuleSpanningTreeFactory()
5380 ~ModuleSpanningTreeFactory()
5384 virtual Module * CreateModule(InspIRCd* Me)
5386 return new ModuleSpanningTree(Me);
5392 extern "C" void * init_module( void )
5394 return new ModuleSpanningTreeFactory;