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 */
1594 bool created = false;
1596 /* Try and find the channel */
1597 chanrec* chan = this->Instance->FindChan(channel);
1599 /* Initialize channel name in the mode parameters */
1600 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1602 /* default TS is a high value, which if we dont have this
1603 * channel will let the other side apply their modes.
1605 time_t ourTS = Instance->Time(true)+600;
1607 /* Does this channel exist? if it does, get its REAL timestamp */
1611 created = true; /* don't perform deops, and set TS to correct time after processing. */
1613 /* In 1.1, if they have the newer channel, we immediately clear
1614 * all status modes from our users. We then accept their modes.
1615 * If WE have the newer channel its the other side's job to do this.
1616 * Note that this causes the losing server to send out confirming
1621 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);
1628 param_list.push_back(channel);
1630 /* Zap all the privilage modes on our side, if the channel exists here */
1633 this->RemoveStatus(Instance->Config->ServerName, param_list);
1638 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1639 irc::tokenstream users(params[2]);
1640 std::string item = "*";
1642 /* do this first, so our mode reversals are correctly received by other servers
1643 * if there is a TS collision.
1645 params[2] = ":" + params[2];
1646 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1648 /* Now, process every 'prefixes,nick' pair */
1651 /* Find next user */
1652 item = users.GetToken();
1654 const char* usr = item.c_str();
1656 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1657 * (is this even possible?) */
1660 const char* permissions = usr;
1662 char* nm = new char[MAXBUF];
1665 /* Iterate through all the prefix values, convert them from prefixes
1666 * to mode letters, and append them to the mode sequence
1668 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1670 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1673 /* This is a valid prefix */
1675 *tnm++ = mh->GetModeChar();
1679 /* Not a valid prefix...
1680 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1682 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1683 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1690 /* Null terminate modes */
1692 /* Advance past the comma, to the nick */
1695 /* Check the user actually exists */
1696 who = this->Instance->FindNick(usr);
1699 /* Did they get any modes? How many times? */
1700 strlcat(modestring, nm, MAXBUF);
1701 for (int k = 0; k < ntimes; k++)
1702 mode_users[modectr++] = strdup(usr);
1704 /* Free temporary buffer used for mode sequence */
1707 /* Check that the user's 'direction' is correct
1708 * based on the server sending the FJOIN. We must
1709 * check each nickname in turn, because the origin of
1710 * the FJOIN may be different to the origin of the nicks
1711 * in the command itself.
1713 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1714 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1716 /* Oh dear oh dear. */
1717 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1720 /* Finally, we can actually place the user into the channel.
1721 * We're sure its right. Final answer, phone a friend.
1723 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1725 /* Have we already queued up MAXMODES modes with parameters
1726 * (+qaohv) ready to be sent to the server?
1728 if (modectr >= (MAXMODES-1))
1730 /* Only actually give the users any status if we lost
1731 * the FJOIN or drew (equal timestamps).
1732 * It isn't actually possible for ourTS to be > TS here,
1733 * only possible to actually have ourTS == TS, or
1734 * ourTS < TS, because if we lost, we already lowered
1735 * our TS above before we entered this loop. We only
1736 * check >= as a safety measure, in case someone stuffed
1737 * up. If someone DID stuff up, it was most likely me.
1738 * Note: I do not like baseball bats in the face...
1742 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1743 this->Instance->SendMode((const char**)mode_users,modectr,who);
1745 /* Something stuffed up, and for some reason, the timestamp is
1746 * NOT lowered right now and should be. Lower it. Usually this
1747 * code won't be executed, doubtless someone will remove it some
1752 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1758 /* Reset all this back to defaults, and
1759 * free any ram we have left allocated.
1761 strcpy(mode_users[1],"+");
1762 for (unsigned int f = 2; f < modectr; f++)
1763 free(mode_users[f]);
1769 /* Remember to free this */
1771 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1772 * We don't try to process the nickname here (that WOULD cause a segfault because
1773 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1774 * in case somehow we're desynched, so that other users which might be able to see
1775 * the nickname get their fair chance to process it.
1777 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1783 /* there werent enough modes built up to flush it during FJOIN,
1784 * or, there are a number left over. flush them out.
1786 if ((modectr > 2) && (who) && (chan))
1790 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1791 this->Instance->SendMode((const char**)mode_users,modectr,who);
1792 /* Yet again, we can't actually get a true value here, if everything else
1793 * is working as it should.
1797 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1803 /* Free anything we have left to free */
1804 for (unsigned int f = 2; f < modectr; f++)
1805 free(mode_users[f]);
1808 /* if we newly created the channel, set it's TS properly. */
1814 /* All done. That wasnt so bad was it, you can wipe
1815 * the sweat from your forehead now. :-)
1821 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1823 if (params.size() < 8)
1825 if (params.size() > 8)
1827 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1830 // NICK age nick host dhost ident +modes ip :gecos
1832 time_t age = atoi(params[0].c_str());
1834 /* This used to have a pretty craq'y loop doing the same thing,
1835 * now we just let the STL do the hard work (more efficiently)
1837 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1838 if (pos_after_plus != std::string::npos)
1839 params[5] = params[5].substr(pos_after_plus);
1841 const char* tempnick = params[1].c_str();
1842 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1844 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1846 if (iter != this->Instance->clientlist.end())
1849 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);
1850 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1851 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1855 userrec* _new = new userrec(this->Instance);
1856 this->Instance->clientlist[tempnick] = _new;
1857 _new->SetFd(FD_MAGIC_NUMBER);
1858 strlcpy(_new->nick, tempnick,NICKMAX-1);
1859 strlcpy(_new->host, params[2].c_str(),63);
1860 strlcpy(_new->dhost, params[3].c_str(),63);
1861 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1862 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1863 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1864 _new->registered = REG_ALL;
1867 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1868 _new->modes[(*v)-65] = 1;
1870 #ifdef SUPPORT_IP6LINKS
1871 if (params[6].find_first_of(":") != std::string::npos)
1872 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1875 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1877 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1879 params[7] = ":" + params[7];
1880 Utils->DoOneToAllButSender(source,"NICK",params,source);
1882 // Increment the Source Servers User Count..
1883 TreeServer* SourceServer = Utils->FindServer(source);
1886 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1887 SourceServer->AddUserCount();
1890 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1895 /** Send one or more FJOINs for a channel of users.
1896 * If the length of a single line is more than 480-NICKMAX
1897 * in length, it is split over multiple lines.
1899 void SendFJoins(TreeServer* Current, chanrec* c)
1903 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1905 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1907 size_t dlen, curlen;
1908 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1910 char* ptr = list + dlen;
1912 CUList *ulist = c->GetUsers();
1913 std::string modes = "";
1914 std::string params = "";
1916 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1918 // The first parameter gets a : before it
1919 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1926 if (curlen > (480-NICKMAX))
1928 buffer.append(list).append("\r\n");
1930 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1938 buffer.append(list).append("\r\n");
1940 /* Sorry for the hax. Because newly created channels assume +nt,
1941 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1943 bool inverted = false;
1944 if (!c->IsModeSet('n'))
1949 if (!c->IsModeSet('t'))
1959 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1962 params.append(" ").append(b->data);
1964 if (params.length() >= MAXMODES)
1966 /* Wrap at MAXMODES */
1967 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");
1973 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1975 /* Only send these if there are any */
1977 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);
1979 this->WriteLine(buffer);
1982 /** Send G, Q, Z and E lines */
1983 void SendXLines(TreeServer* Current)
1987 std::string n = this->Instance->Config->ServerName;
1988 const char* sn = n.c_str();
1990 /* Yes, these arent too nice looking, but they get the job done */
1991 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1993 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);
1994 buffer.append(data);
1996 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1998 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);
1999 buffer.append(data);
2001 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
2003 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);
2004 buffer.append(data);
2006 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
2008 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);
2009 buffer.append(data);
2011 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
2013 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);
2014 buffer.append(data);
2016 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
2018 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);
2019 buffer.append(data);
2021 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
2023 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);
2024 buffer.append(data);
2026 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
2028 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);
2029 buffer.append(data);
2032 if (!buffer.empty())
2033 this->WriteLine(buffer);
2036 /** Send channel modes and topics */
2037 void SendChannelModes(TreeServer* Current)
2040 std::deque<std::string> list;
2042 std::string n = this->Instance->Config->ServerName;
2043 const char* sn = n.c_str();
2044 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2046 SendFJoins(Current, c->second);
2047 if (*c->second->topic)
2049 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2050 this->WriteLine(data);
2052 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2054 c->second->GetExtList(list);
2055 for (unsigned int j = 0; j < list.size(); j++)
2057 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2062 /** send all users and their oper state/modes */
2063 void SendUsers(TreeServer* Current)
2066 std::deque<std::string> list;
2067 std::string dataline;
2069 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2071 if (u->second->registered == REG_ALL)
2073 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);
2074 this->WriteLine(data);
2075 if (*u->second->oper)
2077 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2078 this->WriteLine(data);
2080 if (*u->second->awaymsg)
2082 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2083 this->WriteLine(data);
2085 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2087 u->second->GetExtList(list);
2088 for (unsigned int j = 0; j < list.size(); j++)
2090 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2096 /** This function is called when we want to send a netburst to a local
2097 * server. There is a set order we must do this, because for example
2098 * users require their servers to exist, and channels require their
2099 * users to exist. You get the idea.
2101 void DoBurst(TreeServer* s)
2103 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2104 std::string endburst = "ENDBURST";
2105 // Because by the end of the netburst, it could be gone!
2106 std::string name = s->GetName();
2107 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2108 this->WriteLine(burst);
2109 /* send our version string */
2110 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2111 /* Send server tree */
2112 this->SendServers(Utils->TreeRoot,s,1);
2113 /* Send users and their oper status */
2115 /* Send everything else (channel modes, xlines etc) */
2116 this->SendChannelModes(s);
2117 this->SendXLines(s);
2118 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2119 this->WriteLine(endburst);
2120 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2123 /** This function is called when we receive data from a remote
2124 * server. We buffer the data in a std::string (it doesnt stay
2125 * there for long), reading using InspSocket::Read() which can
2126 * read up to 16 kilobytes in one operation.
2128 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2129 * THE SOCKET OBJECT FOR US.
2131 virtual bool OnDataReady()
2133 char* data = this->Read();
2134 /* Check that the data read is a valid pointer and it has some content */
2137 this->in_buffer.append(data);
2138 /* While there is at least one new line in the buffer,
2139 * do something useful (we hope!) with it.
2141 while (in_buffer.find("\n") != std::string::npos)
2143 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2144 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2145 /* Use rfind here not find, as theres more
2146 * chance of the \r being near the end of the
2147 * string, not the start.
2149 if (ret.find("\r") != std::string::npos)
2150 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2151 /* Process this one, abort if it
2152 * didnt return true.
2158 memset(result,0,1024);
2160 /* ERROR + CAPAB is still allowed unencryped */
2161 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2163 int nbytes = from64tobits(out, ret.c_str(), 1024);
2164 if ((nbytes > 0) && (nbytes < 1024))
2166 ctx_in->Decrypt(out, result, nbytes, 0);
2167 for (int t = 0; t < nbytes; t++)
2169 if (result[t] == '\7')
2171 /* We only need to stick a \0 on the
2172 * first \7, the rest will be lost
2182 if (!this->ProcessLine(ret))
2189 /* EAGAIN returns an empty but non-NULL string, so this
2190 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2192 return (data && !*data);
2195 int WriteLine(std::string line)
2197 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2201 char result64[10240];
2202 if (this->keylength)
2204 // pad it to the key length
2205 int n = this->keylength - (line.length() % this->keylength);
2207 line.append(n,'\7');
2209 unsigned int ll = line.length();
2210 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2211 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2214 line.append("\r\n");
2215 return this->Write(line);
2218 /* Handle ERROR command */
2219 bool Error(std::deque<std::string> ¶ms)
2221 if (params.size() < 1)
2223 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2224 /* we will return false to cause the socket to close. */
2228 /** remote MOTD. leet, huh? */
2229 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2231 if (params.size() > 0)
2233 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2235 /* It's for our server */
2236 string_list results;
2237 userrec* source = this->Instance->FindNick(prefix);
2241 std::deque<std::string> par;
2242 par.push_back(prefix);
2245 if (!Instance->Config->MOTD.size())
2247 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2248 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2252 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2253 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2255 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2257 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2258 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2261 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2262 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2268 userrec* source = this->Instance->FindNick(prefix);
2270 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2276 /** remote ADMIN. leet, huh? */
2277 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2279 if (params.size() > 0)
2281 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2283 /* It's for our server */
2284 string_list results;
2285 userrec* source = this->Instance->FindNick(prefix);
2289 std::deque<std::string> par;
2290 par.push_back(prefix);
2293 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2294 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2296 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2297 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2299 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2300 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2302 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2303 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2309 userrec* source = this->Instance->FindNick(prefix);
2311 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2317 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2319 /* Get the reply to a STATS query if it matches this servername,
2320 * and send it back as a load of PUSH queries
2322 if (params.size() > 1)
2324 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2326 /* It's for our server */
2327 string_list results;
2328 userrec* source = this->Instance->FindNick(prefix);
2331 std::deque<std::string> par;
2332 par.push_back(prefix);
2334 DoStats(this->Instance, *(params[0].c_str()), source, results);
2335 for (size_t i = 0; i < results.size(); i++)
2337 par[1] = "::" + results[i];
2338 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2345 userrec* source = this->Instance->FindNick(prefix);
2347 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2354 /** Because the core won't let users or even SERVERS set +o,
2355 * we use the OPERTYPE command to do this.
2357 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2359 if (params.size() != 1)
2361 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2364 std::string opertype = params[0];
2365 userrec* u = this->Instance->FindNick(prefix);
2368 u->modes[UM_OPERATOR] = 1;
2369 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2370 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2375 /** Because Andy insists that services-compatible servers must
2376 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2378 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2380 if (params.size() < 3)
2383 userrec* u = this->Instance->FindNick(params[0]);
2387 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2390 std::deque<std::string> par;
2391 par.push_back(params[1]);
2392 /* This is not required as one is sent in OnUserPostNick below
2394 //Utils->DoOneToMany(u->nick,"NICK",par);
2395 if (!u->ForceNickChange(params[1].c_str()))
2397 userrec::QuitUser(this->Instance, u, "Nickname collision");
2400 u->age = atoi(params[2].c_str());
2406 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2408 if (params.size() < 2)
2411 userrec* u = this->Instance->FindNick(params[0]);
2415 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2416 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2421 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2423 if (params.size() < 1)
2426 std::string servermask = params[0];
2428 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2430 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2431 this->Instance->RehashServer();
2432 Utils->ReadConfiguration(false);
2433 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2435 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2439 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2441 if (params.size() != 2)
2444 std::string nick = params[0];
2445 userrec* u = this->Instance->FindNick(prefix);
2446 userrec* who = this->Instance->FindNick(nick);
2450 /* Prepend kill source, if we don't have one */
2451 std::string sourceserv = prefix;
2454 sourceserv = u->server;
2456 if (*(params[1].c_str()) != '[')
2458 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2460 std::string reason = params[1];
2461 params[1] = ":" + params[1];
2462 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2463 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2464 userrec::QuitUser(this->Instance,who,reason);
2469 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2471 if (params.size() < 1)
2474 if (params.size() == 1)
2476 TreeServer* ServerSource = Utils->FindServer(prefix);
2479 ServerSource->SetPingFlag();
2484 std::string forwardto = params[1];
2485 if (forwardto == this->Instance->Config->ServerName)
2488 * this is a PONG for us
2489 * if the prefix is a user, check theyre local, and if they are,
2490 * dump the PONG reply back to their fd. If its a server, do nowt.
2491 * Services might want to send these s->s, but we dont need to yet.
2493 userrec* u = this->Instance->FindNick(prefix);
2497 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2502 // not for us, pass it on :)
2503 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2510 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2512 if (params.size() < 3)
2515 TreeServer* ServerSource = Utils->FindServer(prefix);
2519 if (params[0] == "*")
2521 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2523 else if (*(params[0].c_str()) == '#')
2525 chanrec* c = this->Instance->FindChan(params[0]);
2528 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2531 else if (*(params[0].c_str()) != '#')
2533 userrec* u = this->Instance->FindNick(params[0]);
2536 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2541 params[2] = ":" + params[2];
2542 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2546 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2548 if (params.size() < 1)
2551 TreeServer* ServerSource = Utils->FindServer(prefix);
2555 ServerSource->SetVersion(params[0]);
2557 params[0] = ":" + params[0];
2558 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2562 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2564 if (params.size() < 1)
2567 userrec* u = this->Instance->FindNick(prefix);
2571 u->ChangeDisplayedHost(params[0].c_str());
2572 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2577 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2579 if (params.size() < 6)
2582 bool propogate = false;
2584 switch (*(params[0].c_str()))
2587 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2588 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2591 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2592 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2595 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2596 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2599 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2600 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2603 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2606 /* Just in case... */
2607 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2612 /* Send it on its way */
2615 if (atoi(params[4].c_str()))
2617 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());
2621 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());
2623 params[5] = ":" + params[5];
2624 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2626 if (!this->bursting)
2628 Instance->Log(DEBUG,"Applying lines...");
2629 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2634 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2636 if (params.size() < 1)
2639 userrec* u = this->Instance->FindNick(prefix);
2643 u->ChangeName(params[0].c_str());
2644 params[0] = ":" + params[0];
2645 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2650 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2652 if (params.size() < 1)
2655 Instance->Log(DEBUG,"In IDLE command");
2656 userrec* u = this->Instance->FindNick(prefix);
2660 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2661 // an incoming request
2662 if (params.size() == 1)
2664 userrec* x = this->Instance->FindNick(params[0]);
2665 if ((x) && (IS_LOCAL(x)))
2667 userrec* x = this->Instance->FindNick(params[0]);
2668 char signon[MAXBUF];
2671 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2672 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2673 std::deque<std::string> par;
2674 par.push_back(prefix);
2675 par.push_back(signon);
2676 par.push_back(idle);
2677 // ours, we're done, pass it BACK
2678 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2682 // not ours pass it on
2683 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2686 else if (params.size() == 3)
2688 std::string who_did_the_whois = params[0];
2689 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2690 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2692 // an incoming reply to a whois we sent out
2693 std::string nick_whoised = prefix;
2694 unsigned long signon = atoi(params[1].c_str());
2695 unsigned long idle = atoi(params[2].c_str());
2696 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2697 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2701 // not ours, pass it on
2702 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2709 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2711 if (params.size() < 2)
2714 userrec* u = this->Instance->FindNick(params[0]);
2721 u->Write(params[1]);
2725 // continue the raw onwards
2726 params[1] = ":" + params[1];
2727 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2732 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2734 if (!params.size() || !Utils->EnableTimeSync)
2739 if ((params.size() == 2) && (params[1] == "FORCE"))
2742 time_t rts = atoi(params[0].c_str());
2743 time_t us = Instance->Time(true);
2747 Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2749 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2751 else if (force || (rts < us))
2753 int old = Instance->SetTimeDelta(rts - us);
2754 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2756 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2760 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2762 std::deque<std::string> oparams;
2763 oparams.push_back(ConvToStr(us));
2765 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2771 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2773 // :source.server TIME remote.server sendernick
2774 // :remote.server TIME source.server sendernick TS
2775 if (params.size() == 2)
2777 // someone querying our time?
2778 if (this->Instance->Config->ServerName == params[0])
2780 userrec* u = this->Instance->FindNick(params[1]);
2783 params.push_back(ConvToStr(Instance->Time(false)));
2785 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2790 // not us, pass it on
2791 userrec* u = this->Instance->FindNick(params[1]);
2793 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2796 else if (params.size() == 3)
2798 // a response to a previous TIME
2799 userrec* u = this->Instance->FindNick(params[1]);
2800 if ((u) && (IS_LOCAL(u)))
2802 time_t rawtime = atol(params[2].c_str());
2803 struct tm * timeinfo;
2804 timeinfo = localtime(&rawtime);
2806 snprintf(tms,26,"%s",asctime(timeinfo));
2808 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2813 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2819 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2821 if (params.size() < 1)
2824 if (params.size() == 1)
2826 std::string stufftobounce = params[0];
2827 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2832 std::string forwardto = params[1];
2833 if (forwardto == this->Instance->Config->ServerName)
2835 // this is a ping for us, send back PONG to the requesting server
2836 params[1] = params[0];
2837 params[0] = forwardto;
2838 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2842 // not for us, pass it on :)
2843 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2849 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2851 if (params.size() < 1)
2854 chanrec* c = Instance->FindChan(params[0]);
2858 irc::modestacker modestack(false);
2859 CUList *ulist = c->GetUsers();
2861 std::deque<std::string> stackresult;
2864 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2866 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2867 if (modesequence.length())
2869 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2870 irc::spacesepstream sep(modesequence);
2871 std::string modeletters = sep.GetToken();
2872 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2874 while (!modeletters.empty())
2876 char mletter = *(modeletters.begin());
2877 modestack.Push(mletter,sep.GetToken());
2878 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2879 modeletters.erase(modeletters.begin());
2880 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2885 while (modestack.GetStackedLine(stackresult))
2887 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2888 stackresult.push_front(ConvToStr(c->age));
2889 stackresult.push_front(c->name);
2890 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2891 stackresult.erase(stackresult.begin() + 1);
2892 Instance->Log(DEBUG,"Stacked items:");
2893 for (size_t z = 0; z < stackresult.size(); z++)
2895 y[z] = stackresult[z].c_str();
2896 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2898 userrec* n = new userrec(Instance);
2899 n->SetFd(FD_MAGIC_NUMBER);
2900 Instance->SendMode(y, stackresult.size(), n);
2907 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2909 if (params.size() < 4)
2912 std::string servername = params[0];
2913 std::string password = params[1];
2914 // hopcount is not used for a remote server, we calculate this ourselves
2915 std::string description = params[3];
2916 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2920 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2923 TreeServer* CheckDupe = Utils->FindServer(servername);
2926 this->WriteLine("ERROR :Server "+servername+" already exists!");
2927 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2930 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2931 ParentOfThis->AddChild(Node);
2932 params[3] = ":" + params[3];
2933 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2934 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2938 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2940 if (params.size() < 4)
2943 irc::string servername = params[0].c_str();
2944 std::string sname = params[0];
2945 std::string password = params[1];
2946 int hops = atoi(params[2].c_str());
2950 this->WriteLine("ERROR :Server too far away for authentication");
2951 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2954 std::string description = params[3];
2955 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2957 if ((x->Name == servername) && (x->RecvPass == password))
2959 TreeServer* CheckDupe = Utils->FindServer(sname);
2962 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2963 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2966 // Begin the sync here. this kickstarts the
2967 // other side, waiting in WAIT_AUTH_2 state,
2968 // into starting their burst, as it shows
2969 // that we're happy.
2970 this->LinkState = CONNECTED;
2971 // we should add the details of this server now
2972 // to the servers tree, as a child of the root
2974 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2975 Utils->TreeRoot->AddChild(Node);
2976 params[3] = ":" + params[3];
2977 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2978 this->bursting = true;
2979 this->DoBurst(Node);
2983 this->WriteLine("ERROR :Invalid credentials");
2984 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2988 bool Inbound_Server(std::deque<std::string> ¶ms)
2990 if (params.size() < 4)
2993 irc::string servername = params[0].c_str();
2994 std::string sname = params[0];
2995 std::string password = params[1];
2996 int hops = atoi(params[2].c_str());
3000 this->WriteLine("ERROR :Server too far away for authentication");
3001 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3004 std::string description = params[3];
3005 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3007 if ((x->Name == servername) && (x->RecvPass == password))
3009 TreeServer* CheckDupe = Utils->FindServer(sname);
3012 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3013 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3016 /* If the config says this link is encrypted, but the remote side
3017 * hasnt bothered to send the AES command before SERVER, then we
3018 * boot them off as we MUST have this connection encrypted.
3020 if ((x->EncryptionKey != "") && (!this->ctx_in))
3022 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
3023 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
3026 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
3027 this->InboundServerName = sname;
3028 this->InboundDescription = description;
3029 // this is good. Send our details: Our server name and description and hopcount of 0,
3030 // along with the sendpass from this block.
3031 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3032 // move to the next state, we are now waiting for THEM.
3033 this->LinkState = WAIT_AUTH_2;
3037 this->WriteLine("ERROR :Invalid credentials");
3038 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3042 void Split(const std::string &line, std::deque<std::string> &n)
3045 irc::tokenstream tokens(line);
3047 while ((param = tokens.GetToken()) != "")
3052 bool ProcessLine(std::string &line)
3054 std::deque<std::string> params;
3055 irc::string command;
3061 line = line.substr(0, line.find_first_of("\r\n"));
3063 Instance->Log(DEBUG,"IN: %s", line.c_str());
3065 this->Split(line.c_str(),params);
3067 if ((params[0][0] == ':') && (params.size() > 1))
3069 prefix = params[0].substr(1);
3073 command = params[0].c_str();
3076 if ((!this->ctx_in) && (command == "AES"))
3078 std::string sserv = params[0];
3079 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3081 if ((x->EncryptionKey != "") && (x->Name == sserv))
3083 this->InitAES(x->EncryptionKey,sserv);
3089 else if ((this->ctx_in) && (command == "AES"))
3091 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());
3094 switch (this->LinkState)
3099 // Waiting for SERVER command from remote server. Server initiating
3100 // the connection sends the first SERVER command, listening server
3101 // replies with theirs if its happy, then if the initiator is happy,
3102 // it starts to send its net sync, which starts the merge, otherwise
3103 // it sends an ERROR.
3104 if (command == "PASS")
3106 /* Silently ignored */
3108 else if (command == "SERVER")
3110 return this->Inbound_Server(params);
3112 else if (command == "ERROR")
3114 return this->Error(params);
3116 else if (command == "USER")
3118 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3121 else if (command == "CAPAB")
3123 return this->Capab(params);
3125 else if ((command == "U") || (command == "S"))
3127 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3132 std::string error("ERROR :Invalid command in negotiation phase: ");
3133 error.append(command.c_str());
3134 this->WriteLine(error);
3139 // Waiting for start of other side's netmerge to say they liked our
3141 if (command == "SERVER")
3143 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3147 else if ((command == "U") || (command == "S"))
3149 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3152 else if (command == "BURST")
3154 if (params.size() && Utils->EnableTimeSync)
3156 /* If a time stamp is provided, apply synchronization */
3158 time_t them = atoi(params[0].c_str());
3159 time_t us = Instance->Time(true);
3160 int delta = them - us;
3162 if ((params.size() == 2) && (params[1] == "FORCE"))
3165 if ((delta < -600) || (delta > 600))
3167 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));
3168 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3174 this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3176 else if (force || (us > them))
3178 this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3179 this->Instance->SetTimeDelta(them - us);
3180 // Send this new timestamp to any other servers
3181 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3185 // Override the timestamp
3186 this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3187 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3190 this->LinkState = CONNECTED;
3191 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3192 Utils->TreeRoot->AddChild(Node);
3194 params.push_back(InboundServerName);
3195 params.push_back("*");
3196 params.push_back("1");
3197 params.push_back(":"+InboundDescription);
3198 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3199 this->bursting = true;
3200 this->DoBurst(Node);
3202 else if (command == "ERROR")
3204 return this->Error(params);
3206 else if (command == "CAPAB")
3208 return this->Capab(params);
3213 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3217 if (command == "SERVER")
3219 // another server we connected to, which was in WAIT_AUTH_1 state,
3220 // has just sent us their credentials. If we get this far, theyre
3221 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3222 // if we're happy with this, we should send our netburst which
3223 // kickstarts the merge.
3224 return this->Outbound_Reply_Server(params);
3226 else if (command == "ERROR")
3228 return this->Error(params);
3232 // This is the 'authenticated' state, when all passwords
3233 // have been exchanged and anything past this point is taken
3238 std::string direction = prefix;
3239 userrec* t = this->Instance->FindNick(prefix);
3242 direction = t->server;
3244 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3245 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3247 if (route_back_again)
3248 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3253 * When there is activity on the socket, reset the ping counter so
3254 * that we're not wasting bandwidth pinging an active server.
3256 route_back_again->SetNextPingTime(time(NULL) + 60);
3257 route_back_again->SetPingFlag();
3260 if (command == "SVSMODE")
3262 /* Services expects us to implement
3263 * SVSMODE. In inspircd its the same as
3268 std::string target = "";
3269 /* Yes, know, this is a mess. Its reasonably fast though as we're
3270 * working with std::string here.
3272 if ((command == "NICK") && (params.size() > 1))
3274 return this->IntroduceClient(prefix,params);
3276 else if (command == "FJOIN")
3278 return this->ForceJoin(prefix,params);
3280 else if (command == "STATS")
3282 return this->Stats(prefix, params);
3284 else if (command == "MOTD")
3286 return this->Motd(prefix, params);
3288 else if (command == "ADMIN")
3290 return this->Admin(prefix, params);
3292 else if (command == "SERVER")
3294 return this->RemoteServer(prefix,params);
3296 else if (command == "ERROR")
3298 return this->Error(params);
3300 else if (command == "OPERTYPE")
3302 return this->OperType(prefix,params);
3304 else if (command == "FMODE")
3306 return this->ForceMode(prefix,params);
3308 else if (command == "KILL")
3310 return this->RemoteKill(prefix,params);
3312 else if (command == "FTOPIC")
3314 return this->ForceTopic(prefix,params);
3316 else if (command == "REHASH")
3318 return this->RemoteRehash(prefix,params);
3320 else if (command == "METADATA")
3322 return this->MetaData(prefix,params);
3324 else if (command == "REMSTATUS")
3326 return this->RemoveStatus(prefix,params);
3328 else if (command == "PING")
3331 * We just got a ping from a server that's bursting.
3332 * This can't be right, so set them to not bursting, and
3333 * apply their lines.
3337 this->bursting = false;
3338 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3342 prefix = this->GetName();
3344 return this->LocalPing(prefix,params);
3346 else if (command == "PONG")
3349 * We just got a pong from a server that's bursting.
3350 * This can't be right, so set them to not bursting, and
3351 * apply their lines.
3355 this->bursting = false;
3356 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3360 prefix = this->GetName();
3362 return this->LocalPong(prefix,params);
3364 else if (command == "VERSION")
3366 return this->ServerVersion(prefix,params);
3368 else if (command == "FHOST")
3370 return this->ChangeHost(prefix,params);
3372 else if (command == "FNAME")
3374 return this->ChangeName(prefix,params);
3376 else if (command == "ADDLINE")
3378 return this->AddLine(prefix,params);
3380 else if (command == "SVSNICK")
3384 prefix = this->GetName();
3386 return this->ForceNick(prefix,params);
3388 else if (command == "IDLE")
3390 return this->Whois(prefix,params);
3392 else if (command == "PUSH")
3394 return this->Push(prefix,params);
3396 else if (command == "TIMESET")
3398 return this->HandleSetTime(prefix, params);
3400 else if (command == "TIME")
3402 return this->Time(prefix,params);
3404 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3406 std::string sourceserv = this->myhost;
3407 if (params.size() == 3)
3409 userrec* user = this->Instance->FindNick(params[1]);
3410 chanrec* chan = this->Instance->FindChan(params[0]);
3413 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3414 /* Yikes, the channels gone! */
3418 if (this->InboundServerName != "")
3420 sourceserv = this->InboundServerName;
3422 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3424 else if (command == "SVSJOIN")
3428 prefix = this->GetName();
3430 return this->ServiceJoin(prefix,params);
3432 else if (command == "SQUIT")
3434 if (params.size() == 2)
3436 this->Squit(Utils->FindServer(params[0]),params[1]);
3440 else if (command == "OPERNOTICE")
3442 std::string sourceserv = this->myhost;
3444 if (this->InboundServerName != "")
3445 sourceserv = this->InboundServerName;
3447 if (params.size() >= 1)
3448 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3450 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3452 else if (command == "MODENOTICE")
3454 std::string sourceserv = this->myhost;
3455 if (this->InboundServerName != "")
3456 sourceserv = this->InboundServerName;
3457 if (params.size() >= 2)
3459 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3462 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3464 else if (command == "SNONOTICE")
3466 std::string sourceserv = this->myhost;
3467 if (this->InboundServerName != "")
3468 sourceserv = this->InboundServerName;
3469 if (params.size() >= 2)
3471 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3474 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3476 else if (command == "ENDBURST")
3478 this->bursting = false;
3479 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3480 std::string sourceserv = this->myhost;
3481 if (this->InboundServerName != "")
3483 sourceserv = this->InboundServerName;
3485 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3487 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3488 rmode.Send(Instance);
3494 // not a special inter-server command.
3495 // Emulate the actual user doing the command,
3496 // this saves us having a huge ugly parser.
3497 userrec* who = this->Instance->FindNick(prefix);
3498 std::string sourceserv = this->myhost;
3499 if (this->InboundServerName != "")
3501 sourceserv = this->InboundServerName;
3503 if ((!who) && (command == "MODE"))
3505 if (Utils->IsServer(prefix))
3507 const char* modelist[127];
3508 for (size_t i = 0; i < params.size(); i++)
3509 modelist[i] = params[i].c_str();
3511 userrec* fake = new userrec(Instance);
3512 fake->SetFd(FD_MAGIC_NUMBER);
3514 this->Instance->SendMode(modelist, params.size(), fake);
3518 /* Hot potato! pass it on! */
3519 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3524 if ((command == "NICK") && (params.size() > 0))
3526 /* On nick messages, check that the nick doesnt
3527 * already exist here. If it does, kill their copy,
3530 userrec* x = this->Instance->FindNick(params[0]);
3531 if ((x) && (x != who))
3533 std::deque<std::string> p;
3534 p.push_back(params[0]);
3535 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3536 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3538 p.push_back(prefix);
3539 p.push_back("Nickname collision");
3540 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3541 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3542 userrec* y = this->Instance->FindNick(prefix);
3545 userrec::QuitUser(this->Instance,y,"Nickname collision");
3547 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3551 target = who->server;
3552 const char* strparams[127];
3553 for (unsigned int q = 0; q < params.size(); q++)
3555 strparams[q] = params[q].c_str();
3557 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3560 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3567 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3573 // its not a user. Its either a server, or somethings screwed up.
3574 if (Utils->IsServer(prefix))
3576 target = this->Instance->Config->ServerName;
3580 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3584 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3593 virtual std::string GetName()
3595 std::string sourceserv = this->myhost;
3596 if (this->InboundServerName != "")
3598 sourceserv = this->InboundServerName;
3603 virtual void OnTimeout()
3605 if (this->LinkState == CONNECTING)
3607 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3608 Link* MyLink = Utils->FindLink(myhost);
3610 Utils->DoFailOver(MyLink);
3614 virtual void OnClose()
3616 // Connection closed.
3617 // If the connection is fully up (state CONNECTED)
3618 // then propogate a netsplit to all peers.
3619 std::string quitserver = this->myhost;
3620 if (this->InboundServerName != "")
3622 quitserver = this->InboundServerName;
3624 TreeServer* s = Utils->FindServer(quitserver);
3627 Squit(s,"Remote host closed the connection");
3630 if (quitserver != "")
3631 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3634 virtual int OnIncomingConnection(int newsock, char* ip)
3636 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3637 * or discovering if this port is the server port, we don't allow connections from any
3638 * IPs for which we don't have a link block.
3642 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3645 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3646 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3651 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3656 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3657 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3662 /** This class is used to resolve server hostnames during /connect and autoconnect.
3663 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3664 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3665 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3666 * will have an IP address which we can then use to continue our connection.
3668 class ServernameResolver : public Resolver
3671 /** A copy of the Link tag info for what we're connecting to.
3672 * We take a copy, rather than using a pointer, just in case the
3673 * admin takes the tag away and rehashes while the domain is resolving.
3676 SpanningTreeUtilities* Utils;
3678 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3680 /* Nothing in here, folks */
3683 void OnLookupComplete(const std::string &result)
3685 /* Initiate the connection, now that we have an IP to use.
3686 * Passing a hostname directly to InspSocket causes it to
3687 * just bail and set its FD to -1.
3689 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3690 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3692 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
3693 if (newsocket->GetFd() > -1)
3699 /* Something barfed, show the opers */
3700 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3702 Utils->DoFailOver(&MyLink);
3707 void OnError(ResolverError e, const std::string &errormessage)
3710 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3711 Utils->DoFailOver(&MyLink);
3715 /** Handle resolving of server IPs for the cache
3717 class SecurityIPResolver : public Resolver
3721 SpanningTreeUtilities* Utils;
3723 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3727 void OnLookupComplete(const std::string &result)
3729 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3730 Utils->ValidIPs.push_back(result);
3733 void OnError(ResolverError e, const std::string &errormessage)
3735 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3739 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3742 this->ReadConfiguration(true);
3743 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3746 SpanningTreeUtilities::~SpanningTreeUtilities()
3748 for (unsigned int i = 0; i < Bindings.size(); i++)
3750 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3751 ServerInstance->SE->DelFd(Bindings[i]);
3752 Bindings[i]->Close();
3753 DELETE(Bindings[i]);
3755 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3756 while (TreeRoot->ChildCount())
3758 TreeServer* child_server = TreeRoot->GetChild(0);
3759 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3762 TreeSocket* sock = child_server->GetSocket();
3763 ServerInstance->SE->DelFd(sock);
3771 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3773 for (unsigned int c = 0; c < list.size(); c++)
3775 if (list[c] == server)
3780 list.push_back(server);
3783 /** returns a list of DIRECT servernames for a specific channel */
3784 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3786 CUList *ulist = c->GetUsers();
3787 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3789 if (i->second->GetFd() < 0)
3791 TreeServer* best = this->BestRouteTo(i->second->server);
3793 AddThisServer(best,list);
3799 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3801 TreeServer* omitroute = this->BestRouteTo(omit);
3802 if ((command == "NOTICE") || (command == "PRIVMSG"))
3804 if (params.size() >= 2)
3807 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3809 params[0] = params[0].substr(1, params[0].length()-1);
3811 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3813 // special routing for private messages/notices
3814 userrec* d = ServerInstance->FindNick(params[0]);
3817 std::deque<std::string> par;
3818 par.push_back(params[0]);
3819 par.push_back(":"+params[1]);
3820 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3824 else if (*(params[0].c_str()) == '$')
3826 std::deque<std::string> par;
3827 par.push_back(params[0]);
3828 par.push_back(":"+params[1]);
3829 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3834 chanrec* c = ServerInstance->FindChan(params[0]);
3837 std::deque<TreeServer*> list;
3838 GetListOfServersForChannel(c,list);
3839 unsigned int lsize = list.size();
3840 for (unsigned int i = 0; i < lsize; i++)
3842 TreeSocket* Sock = list[i]->GetSocket();
3843 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3845 Sock->WriteLine(data);
3853 unsigned int items =this->TreeRoot->ChildCount();
3854 for (unsigned int x = 0; x < items; x++)
3856 TreeServer* Route = this->TreeRoot->GetChild(x);
3857 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3859 TreeSocket* Sock = Route->GetSocket();
3861 Sock->WriteLine(data);
3867 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
3869 TreeServer* omitroute = this->BestRouteTo(omit);
3870 std::string FullLine = ":" + prefix + " " + command;
3871 unsigned int words = params.size();
3872 for (unsigned int x = 0; x < words; x++)
3874 FullLine = FullLine + " " + params[x];
3876 unsigned int items = this->TreeRoot->ChildCount();
3877 for (unsigned int x = 0; x < items; x++)
3879 TreeServer* Route = this->TreeRoot->GetChild(x);
3880 // Send the line IF:
3881 // The route has a socket (its a direct connection)
3882 // The route isnt the one to be omitted
3883 // The route isnt the path to the one to be omitted
3884 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3886 TreeSocket* Sock = Route->GetSocket();
3888 Sock->WriteLine(FullLine);
3894 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
3896 std::string FullLine = ":" + prefix + " " + command;
3897 unsigned int words = params.size();
3898 for (unsigned int x = 0; x < words; x++)
3900 FullLine = FullLine + " " + params[x];
3902 unsigned int items = this->TreeRoot->ChildCount();
3903 for (unsigned int x = 0; x < items; x++)
3905 TreeServer* Route = this->TreeRoot->GetChild(x);
3906 if (Route && Route->GetSocket())
3908 TreeSocket* Sock = Route->GetSocket();
3910 Sock->WriteLine(FullLine);
3916 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3918 std::string spfx = prefix;
3919 std::string scmd = command;
3920 return this->DoOneToMany(spfx, scmd, params);
3923 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3925 std::string spfx = prefix;
3926 std::string scmd = command;
3927 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3930 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
3932 TreeServer* Route = this->BestRouteTo(target);
3935 std::string FullLine = ":" + prefix + " " + command;
3936 unsigned int words = params.size();
3937 for (unsigned int x = 0; x < words; x++)
3939 FullLine = FullLine + " " + params[x];
3941 if (Route && Route->GetSocket())
3943 TreeSocket* Sock = Route->GetSocket();
3945 Sock->WriteLine(FullLine);
3955 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3957 ConfigReader* Conf = new ConfigReader(ServerInstance);
3960 for (int j =0; j < Conf->Enumerate("bind"); j++)
3962 std::string Type = Conf->ReadValue("bind","type",j);
3963 std::string IP = Conf->ReadValue("bind","address",j);
3964 std::string Port = Conf->ReadValue("bind","port",j);
3965 if (Type == "servers")
3967 irc::portparser portrange(Port, false);
3969 while ((portno = portrange.GetToken()))
3971 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
3975 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10);
3976 if (listener->GetState() == I_LISTENING)
3978 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
3979 Bindings.push_back(listener);
3983 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
3987 ServerInstance->Log(DEBUG,"Done with this binding");
3992 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3993 HideULines = Conf->ReadFlag("options","hideulines",0);
3994 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3995 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3998 for (int j =0; j < Conf->Enumerate("link"); j++)
4001 std::string Allow = Conf->ReadValue("link","allowmask",j);
4002 L.Name = (Conf->ReadValue("link","name",j)).c_str();
4003 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
4004 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
4005 L.Port = Conf->ReadInteger("link","port",j,true);
4006 L.SendPass = Conf->ReadValue("link","sendpass",j);
4007 L.RecvPass = Conf->ReadValue("link","recvpass",j);
4008 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
4009 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
4010 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
4011 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
4012 L.NextConnectTime = time(NULL) + L.AutoConnect;
4013 /* Bugfix by brain, do not allow people to enter bad configurations */
4014 if (L.Name != ServerInstance->Config->ServerName)
4016 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
4018 ValidIPs.push_back(L.IPAddr);
4021 ValidIPs.push_back(Allow);
4023 /* Needs resolving */
4025 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
4029 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
4030 ServerInstance->AddResolver(sr);
4032 catch (ModuleException& e)
4034 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4038 LinkBlocks.push_back(L);
4039 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4045 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4047 else if (L.RecvPass == "")
4049 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4051 else if (L.SendPass == "")
4053 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4055 else if (L.Name == "")
4057 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4061 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4067 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4073 /** To create a timer which recurs every second, we inherit from InspTimer.
4074 * InspTimer is only one-shot however, so at the end of each Tick() we simply
4075 * insert another of ourselves into the pending queue :)
4077 class TimeSyncTimer : public InspTimer
4081 ModuleSpanningTree *Module;
4083 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4084 virtual void Tick(time_t TIME);
4087 class ModuleSpanningTree : public Module
4091 unsigned int max_local;
4092 unsigned int max_global;
4093 cmd_rconnect* command_rconnect;
4094 SpanningTreeUtilities* Utils;
4097 TimeSyncTimer *SyncTimer;
4099 ModuleSpanningTree(InspIRCd* Me)
4100 : Module::Module(Me), max_local(0), max_global(0)
4102 Utils = new SpanningTreeUtilities(Me, this);
4104 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4105 ServerInstance->AddCommand(command_rconnect);
4107 if (Utils->EnableTimeSync)
4109 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4110 ServerInstance->Timers->AddTimer(SyncTimer);
4116 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4118 std::string Parent = Utils->TreeRoot->GetName();
4119 if (Current->GetParent())
4121 Parent = Current->GetParent()->GetName();
4123 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4125 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4129 ShowLinks(Current->GetChild(q),user,hops+1);
4134 ShowLinks(Current->GetChild(q),user,hops+1);
4137 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4138 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4140 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());
4143 int CountLocalServs()
4145 return Utils->TreeRoot->ChildCount();
4150 return Utils->serverlist.size();
4153 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4155 ShowLinks(Utils->TreeRoot,user,0);
4156 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4160 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4162 unsigned int n_users = ServerInstance->UserCount();
4164 /* Only update these when someone wants to see them, more efficient */
4165 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4166 max_local = ServerInstance->LocalUserCount();
4167 if (n_users > max_global)
4168 max_global = n_users;
4170 unsigned int ulined_count = 0;
4171 unsigned int ulined_local_count = 0;
4173 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4174 * locally and globally (locally means directly connected to us)
4176 if ((Utils->HideULines) && (!*user->oper))
4178 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4180 if (ServerInstance->ULine(q->second->GetName().c_str()))
4183 if (q->second->GetParent() == Utils->TreeRoot)
4184 ulined_local_count++;
4189 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());
4190 if (ServerInstance->OperCount())
4191 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4192 if (ServerInstance->UnregisteredUserCount())
4193 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4194 if (ServerInstance->ChannelCount())
4195 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4196 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());
4197 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4198 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4202 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4204 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4208 for (int t = 0; t < depth; t++)
4210 matrix[line][t] = ' ';
4213 // For Aligning, we need to work out exactly how deep this thing is, and produce
4214 // a 'Spacer' String to compensate.
4217 memset(spacer,' ',40);
4218 if ((40 - Current->GetName().length() - depth) > 1) {
4219 spacer[40 - Current->GetName().length() - depth] = '\0';
4228 if (ServerInstance->clientlist.size() == 0) {
4229 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4234 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4236 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4237 totusers += Current->GetUserCount();
4239 strlcpy(&matrix[line][depth],text,80);
4241 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4243 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4247 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4252 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4258 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4262 /* Remote MOTD, the server is within the 1st parameter */
4263 std::deque<std::string> params;
4264 params.push_back(parameters[0]);
4266 /* Send it out remotely, generate no reply yet */
4267 TreeServer* s = Utils->FindServerMask(parameters[0]);
4270 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4274 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4281 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4285 /* Remote ADMIN, the server is within the 1st parameter */
4286 std::deque<std::string> params;
4287 params.push_back(parameters[0]);
4289 /* Send it out remotely, generate no reply yet */
4290 TreeServer* s = Utils->FindServerMask(parameters[0]);
4293 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4297 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4304 int HandleStats(const char** parameters, int pcnt, userrec* user)
4308 /* Remote STATS, the server is within the 2nd parameter */
4309 std::deque<std::string> params;
4310 params.push_back(parameters[0]);
4311 params.push_back(parameters[1]);
4312 /* Send it out remotely, generate no reply yet */
4313 TreeServer* s = Utils->FindServerMask(parameters[1]);
4316 params[1] = s->GetName();
4317 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4321 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4328 // Ok, prepare to be confused.
4329 // After much mulling over how to approach this, it struck me that
4330 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4331 // keeping track of a ton of ascii characters, and line by line
4332 // under recursion working out where to place them using multiplications
4333 // and divisons, we instead render the map onto a backplane of characters
4334 // (a character matrix), then draw the branches as a series of "L" shapes
4335 // from the nodes. This is not only friendlier on CPU it uses less stack.
4337 void HandleMap(const char** parameters, int pcnt, userrec* user)
4339 // This array represents a virtual screen which we will
4340 // "scratch" draw to, as the console device of an irc
4341 // client does not provide for a proper terminal.
4343 float totservers = 0;
4344 char matrix[128][80];
4345 for (unsigned int t = 0; t < 128; t++)
4347 matrix[t][0] = '\0';
4350 // The only recursive bit is called here.
4351 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4352 // Process each line one by one. The algorithm has a limit of
4353 // 128 servers (which is far more than a spanning tree should have
4354 // anyway, so we're ok). This limit can be raised simply by making
4355 // the character matrix deeper, 128 rows taking 10k of memory.
4356 for (int l = 1; l < line; l++)
4358 // scan across the line looking for the start of the
4359 // servername (the recursive part of the algorithm has placed
4360 // the servers at indented positions depending on what they
4362 int first_nonspace = 0;
4363 while (matrix[l][first_nonspace] == ' ')
4368 // Draw the `- (corner) section: this may be overwritten by
4369 // another L shape passing along the same vertical pane, becoming
4370 // a |- (branch) section instead.
4371 matrix[l][first_nonspace] = '-';
4372 matrix[l][first_nonspace-1] = '`';
4374 // Draw upwards until we hit the parent server, causing possibly
4375 // other corners (`-) to become branches (|-)
4376 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4378 matrix[l2][first_nonspace-1] = '|';
4382 // dump the whole lot to the user. This is the easy bit, honest.
4383 for (int t = 0; t < line; t++)
4385 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4387 float avg_users = totusers / totservers;
4388 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);
4389 user->WriteServ("007 %s :End of /MAP",user->nick);
4393 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4395 TreeServer* s = Utils->FindServerMask(parameters[0]);
4398 if (s == Utils->TreeRoot)
4400 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4403 TreeSocket* sock = s->GetSocket();
4406 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4407 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4408 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4409 ServerInstance->SE->DelFd(sock);
4415 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4420 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4425 int HandleTime(const char** parameters, int pcnt, userrec* user)
4427 if ((IS_LOCAL(user)) && (pcnt))
4429 TreeServer* found = Utils->FindServerMask(parameters[0]);
4432 // we dont' override for local server
4433 if (found == Utils->TreeRoot)
4436 std::deque<std::string> params;
4437 params.push_back(found->GetName());
4438 params.push_back(user->nick);
4439 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4443 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4449 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4451 if ((IS_LOCAL(user)) && (pcnt > 1))
4453 userrec* remote = ServerInstance->FindNick(parameters[1]);
4454 if ((remote) && (remote->GetFd() < 0))
4456 std::deque<std::string> params;
4457 params.push_back(parameters[1]);
4458 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4463 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4464 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4471 void DoPingChecks(time_t curtime)
4473 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4475 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4476 TreeSocket* sock = serv->GetSocket();
4479 if (curtime >= serv->NextPingTime())
4481 if (serv->AnsweredLastPing())
4483 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4484 serv->SetNextPingTime(curtime + 60);
4488 // they didnt answer, boot them
4489 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4490 sock->Squit(serv,"Ping timeout");
4491 ServerInstance->SE->DelFd(sock);
4501 void ConnectServer(Link* x)
4505 /* Do we already have an IP? If so, no need to resolve it. */
4506 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4508 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
4509 if (newsocket->GetFd() > -1)
4511 /* Handled automatically on success */
4515 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4517 Utils->DoFailOver(x);
4524 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4525 ServerInstance->AddResolver(snr);
4527 catch (ModuleException& e)
4529 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4530 Utils->DoFailOver(x);
4535 void AutoConnectServers(time_t curtime)
4537 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4539 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4541 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4542 x->NextConnectTime = curtime + x->AutoConnect;
4543 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4544 if (x->FailOver.length())
4546 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4549 /* The failover for this server is currently a member of the network.
4550 * The failover probably succeeded, where the main link did not.
4551 * Don't try the main link until the failover is gone again.
4558 // an autoconnected server is not connected. Check if its time to connect it
4559 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4560 this->ConnectServer(&(*x));
4566 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4568 // we've already checked if pcnt > 0, so this is safe
4569 TreeServer* found = Utils->FindServerMask(parameters[0]);
4572 std::string Version = found->GetVersion();
4573 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4574 if (found == Utils->TreeRoot)
4576 std::stringstream out(ServerInstance->Config->data005);
4577 std::string token = "";
4578 std::string line5 = "";
4579 int token_counter = 0;
4584 line5 = line5 + token + " ";
4587 if ((token_counter >= 13) || (out.eof() == true))
4589 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4598 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4603 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4605 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4607 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4609 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4612 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);
4613 ConnectServer(&(*x));
4618 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());
4623 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4627 void BroadcastTimeSync()
4629 std::deque<std::string> params;
4630 params.push_back(ConvToStr(ServerInstance->Time(true)));
4631 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4634 virtual int OnStats(char statschar, userrec* user, string_list &results)
4636 if ((statschar == 'c') || (statschar == 'n'))
4638 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4640 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4641 if (statschar == 'c')
4642 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4644 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4645 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);
4651 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4653 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4657 if (command == "CONNECT")
4659 return this->HandleConnect(parameters,pcnt,user);
4661 else if (command == "STATS")
4663 return this->HandleStats(parameters,pcnt,user);
4665 else if (command == "MOTD")
4667 return this->HandleMotd(parameters,pcnt,user);
4669 else if (command == "ADMIN")
4671 return this->HandleAdmin(parameters,pcnt,user);
4673 else if (command == "SQUIT")
4675 return this->HandleSquit(parameters,pcnt,user);
4677 else if (command == "MAP")
4679 this->HandleMap(parameters,pcnt,user);
4682 else if ((command == "TIME") && (pcnt > 0))
4684 return this->HandleTime(parameters,pcnt,user);
4686 else if (command == "LUSERS")
4688 this->HandleLusers(parameters,pcnt,user);
4691 else if (command == "LINKS")
4693 this->HandleLinks(parameters,pcnt,user);
4696 else if (command == "WHOIS")
4701 return this->HandleRemoteWhois(parameters,pcnt,user);
4704 else if ((command == "VERSION") && (pcnt > 0))
4706 this->HandleVersion(parameters,pcnt,user);
4713 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4715 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4717 // this bit of code cleverly routes all module commands
4718 // to all remote severs *automatically* so that modules
4719 // can just handle commands locally, without having
4720 // to have any special provision in place for remote
4721 // commands and linking protocols.
4722 std::deque<std::string> params;
4724 for (int j = 0; j < pcnt; j++)
4726 if (strchr(parameters[j],' '))
4728 params.push_back(":" + std::string(parameters[j]));
4732 params.push_back(std::string(parameters[j]));
4735 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4736 Utils->DoOneToMany(user->nick,command,params);
4740 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4742 TreeServer* s = Utils->FindServer(servername);
4745 description = s->GetDesc();
4749 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4751 if (IS_LOCAL(source))
4753 std::deque<std::string> params;
4754 params.push_back(dest->nick);
4755 params.push_back(channel->name);
4756 Utils->DoOneToMany(source->nick,"INVITE",params);
4760 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4762 std::deque<std::string> params;
4763 params.push_back(chan->name);
4764 params.push_back(":"+topic);
4765 Utils->DoOneToMany(user->nick,"TOPIC",params);
4768 virtual void OnWallops(userrec* user, const std::string &text)
4772 std::deque<std::string> params;
4773 params.push_back(":"+text);
4774 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4778 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4780 if (target_type == TYPE_USER)
4782 userrec* d = (userrec*)dest;
4783 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4785 std::deque<std::string> params;
4787 params.push_back(d->nick);
4788 params.push_back(":"+text);
4789 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4792 else if (target_type == TYPE_CHANNEL)
4796 chanrec *c = (chanrec*)dest;
4799 std::string cname = c->name;
4801 cname = status + cname;
4802 std::deque<TreeServer*> list;
4803 Utils->GetListOfServersForChannel(c,list);
4804 unsigned int ucount = list.size();
4805 for (unsigned int i = 0; i < ucount; i++)
4807 TreeSocket* Sock = list[i]->GetSocket();
4809 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4814 else if (target_type == TYPE_SERVER)
4818 char* target = (char*)dest;
4819 std::deque<std::string> par;
4820 par.push_back(target);
4821 par.push_back(":"+text);
4822 Utils->DoOneToMany(user->nick,"NOTICE",par);
4827 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4829 if (target_type == TYPE_USER)
4831 // route private messages which are targetted at clients only to the server
4832 // which needs to receive them
4833 userrec* d = (userrec*)dest;
4834 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4836 std::deque<std::string> params;
4838 params.push_back(d->nick);
4839 params.push_back(":"+text);
4840 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4843 else if (target_type == TYPE_CHANNEL)
4847 chanrec *c = (chanrec*)dest;
4850 std::string cname = c->name;
4852 cname = status + cname;
4853 std::deque<TreeServer*> list;
4854 Utils->GetListOfServersForChannel(c,list);
4855 unsigned int ucount = list.size();
4856 for (unsigned int i = 0; i < ucount; i++)
4858 TreeSocket* Sock = list[i]->GetSocket();
4860 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4865 else if (target_type == TYPE_SERVER)
4869 char* target = (char*)dest;
4870 std::deque<std::string> par;
4871 par.push_back(target);
4872 par.push_back(":"+text);
4873 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4878 virtual void OnBackgroundTimer(time_t curtime)
4880 AutoConnectServers(curtime);
4881 DoPingChecks(curtime);
4884 virtual void OnUserJoin(userrec* user, chanrec* channel)
4886 // Only do this for local users
4889 std::deque<std::string> params;
4891 params.push_back(channel->name);
4892 // set up their permissions and the channel TS with FJOIN.
4893 // All users are FJOINed now, because a module may specify
4894 // new joining permissions for the user.
4896 params.push_back(channel->name);
4897 params.push_back(ConvToStr(channel->age));
4898 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4899 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4900 if (channel->GetUserCounter() == 1)
4902 /* First user in, sync the modes for the channel */
4904 /* This is safe, all inspircd servers default to +nt */
4905 params.push_back("+nt");
4906 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
4911 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4913 // only occurs for local clients
4914 if (user->registered != REG_ALL)
4916 std::deque<std::string> params;
4917 params.push_back(newhost);
4918 Utils->DoOneToMany(user->nick,"FHOST",params);
4921 virtual void OnChangeName(userrec* user, const std::string &gecos)
4923 // only occurs for local clients
4924 if (user->registered != REG_ALL)
4926 std::deque<std::string> params;
4927 params.push_back(gecos);
4928 Utils->DoOneToMany(user->nick,"FNAME",params);
4931 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4935 std::deque<std::string> params;
4936 params.push_back(channel->name);
4937 if (partmessage != "")
4938 params.push_back(":"+partmessage);
4939 Utils->DoOneToMany(user->nick,"PART",params);
4943 virtual void OnUserConnect(userrec* user)
4945 char agestr[MAXBUF];
4948 std::deque<std::string> params;
4949 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4950 params.push_back(agestr);
4951 params.push_back(user->nick);
4952 params.push_back(user->host);
4953 params.push_back(user->dhost);
4954 params.push_back(user->ident);
4955 params.push_back("+"+std::string(user->FormatModes()));
4956 params.push_back(user->GetIPString());
4957 params.push_back(":"+std::string(user->fullname));
4958 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4960 // User is Local, change needs to be reflected!
4961 TreeServer* SourceServer = Utils->FindServer(user->server);
4964 SourceServer->AddUserCount();
4970 virtual void OnUserQuit(userrec* user, const std::string &reason)
4972 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4974 std::deque<std::string> params;
4975 params.push_back(":"+reason);
4976 Utils->DoOneToMany(user->nick,"QUIT",params);
4978 // Regardless, We need to modify the user Counts..
4979 TreeServer* SourceServer = Utils->FindServer(user->server);
4982 SourceServer->DelUserCount();
4987 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4991 std::deque<std::string> params;
4992 params.push_back(user->nick);
4993 Utils->DoOneToMany(oldnick,"NICK",params);
4997 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4999 if ((source) && (IS_LOCAL(source)))
5001 std::deque<std::string> params;
5002 params.push_back(chan->name);
5003 params.push_back(user->nick);
5004 params.push_back(":"+reason);
5005 Utils->DoOneToMany(source->nick,"KICK",params);
5009 std::deque<std::string> params;
5010 params.push_back(chan->name);
5011 params.push_back(user->nick);
5012 params.push_back(":"+reason);
5013 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
5017 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
5019 std::deque<std::string> params;
5020 params.push_back(dest->nick);
5021 params.push_back(":"+reason);
5022 Utils->DoOneToMany(source->nick,"KILL",params);
5025 virtual void OnRehash(const std::string ¶meter)
5027 if (parameter != "")
5029 std::deque<std::string> params;
5030 params.push_back(parameter);
5031 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
5033 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5035 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
5036 ServerInstance->RehashServer();
5039 Utils->ReadConfiguration(false);
5042 // note: the protocol does not allow direct umode +o except
5043 // via NICK with 8 params. sending OPERTYPE infers +o modechange
5045 virtual void OnOper(userrec* user, const std::string &opertype)
5049 std::deque<std::string> params;
5050 params.push_back(opertype);
5051 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5055 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5059 /* Server-set lines */
5061 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5062 (unsigned long)duration, reason.c_str());
5063 std::deque<std::string> params;
5064 params.push_back(data);
5065 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5069 if (IS_LOCAL(source))
5072 snprintf(type,8,"%cLINE",linetype);
5073 std::string stype = type;
5076 char sduration[MAXBUF];
5077 snprintf(sduration,MAXBUF,"%ld",duration);
5078 std::deque<std::string> params;
5079 params.push_back(host);
5080 params.push_back(sduration);
5081 params.push_back(":"+reason);
5082 Utils->DoOneToMany(source->nick,stype,params);
5086 std::deque<std::string> params;
5087 params.push_back(host);
5088 Utils->DoOneToMany(source->nick,stype,params);
5094 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5096 OnLine(source,hostmask,true,'G',duration,reason);
5099 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5101 OnLine(source,ipmask,true,'Z',duration,reason);
5104 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5106 OnLine(source,nickmask,true,'Q',duration,reason);
5109 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5111 OnLine(source,hostmask,true,'E',duration,reason);
5114 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5116 OnLine(source,hostmask,false,'G',0,"");
5119 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5121 OnLine(source,ipmask,false,'Z',0,"");
5124 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5126 OnLine(source,nickmask,false,'Q',0,"");
5129 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5131 OnLine(source,hostmask,false,'E',0,"");
5134 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5136 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5138 if (target_type == TYPE_USER)
5140 userrec* u = (userrec*)dest;
5141 std::deque<std::string> params;
5142 params.push_back(u->nick);
5143 params.push_back(text);
5144 Utils->DoOneToMany(user->nick,"MODE",params);
5148 chanrec* c = (chanrec*)dest;
5149 std::deque<std::string> params;
5150 params.push_back(c->name);
5151 params.push_back(text);
5152 Utils->DoOneToMany(user->nick,"MODE",params);
5157 virtual void OnSetAway(userrec* user)
5161 std::deque<std::string> params;
5162 params.push_back(":"+std::string(user->awaymsg));
5163 Utils->DoOneToMany(user->nick,"AWAY",params);
5167 virtual void OnCancelAway(userrec* user)
5171 std::deque<std::string> params;
5173 Utils->DoOneToMany(user->nick,"AWAY",params);
5177 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5179 TreeSocket* s = (TreeSocket*)opaque;
5182 if (target_type == TYPE_USER)
5184 userrec* u = (userrec*)target;
5185 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5189 chanrec* c = (chanrec*)target;
5190 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5195 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5197 TreeSocket* s = (TreeSocket*)opaque;
5200 if (target_type == TYPE_USER)
5202 userrec* u = (userrec*)target;
5203 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5205 else if (target_type == TYPE_OTHER)
5207 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5209 else if (target_type == TYPE_CHANNEL)
5211 chanrec* c = (chanrec*)target;
5212 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5217 virtual void OnEvent(Event* event)
5219 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5221 if (event->GetEventID() == "send_metadata")
5223 if (params->size() < 3)
5225 (*params)[2] = ":" + (*params)[2];
5226 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5228 else if (event->GetEventID() == "send_topic")
5230 if (params->size() < 2)
5232 (*params)[1] = ":" + (*params)[1];
5233 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5234 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5235 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5237 else if (event->GetEventID() == "send_mode")
5239 if (params->size() < 2)
5241 // Insert the TS value of the object, either userrec or chanrec
5243 userrec* a = ServerInstance->FindNick((*params)[0]);
5250 chanrec* a = ServerInstance->FindChan((*params)[0]);
5256 params->insert(params->begin() + 1,ConvToStr(ourTS));
5257 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5259 else if (event->GetEventID() == "send_mode_explicit")
5261 if (params->size() < 2)
5263 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5265 else if (event->GetEventID() == "send_opers")
5267 if (params->size() < 1)
5269 (*params)[0] = ":" + (*params)[0];
5270 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5272 else if (event->GetEventID() == "send_modeset")
5274 if (params->size() < 2)
5276 (*params)[1] = ":" + (*params)[1];
5277 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5279 else if (event->GetEventID() == "send_snoset")
5281 if (params->size() < 2)
5283 (*params)[1] = ":" + (*params)[1];
5284 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5286 else if (event->GetEventID() == "send_push")
5288 if (params->size() < 2)
5291 userrec *a = ServerInstance->FindNick((*params)[0]);
5296 (*params)[1] = ":" + (*params)[1];
5297 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5301 virtual ~ModuleSpanningTree()
5303 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5304 /* This will also free the listeners */
5307 ServerInstance->Timers->DelTimer(SyncTimer);
5310 virtual Version GetVersion()
5312 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5315 void Implements(char* List)
5317 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5318 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5319 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5320 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5321 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5322 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5323 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5326 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5327 * so that any activity it sees is FINAL, e.g. we arent going to send out
5328 * a NICK message before m_cloaking has finished putting the +x on the user,
5330 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5331 * the module call queue.
5333 Priority Prioritize()
5335 return PRIORITY_LAST;
5339 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5343 void TimeSyncTimer::Tick(time_t TIME)
5345 Module->BroadcastTimeSync();
5346 Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5347 Instance->Timers->AddTimer(Module->SyncTimer);
5350 void SpanningTreeUtilities::DoFailOver(Link* x)
5352 if (x->FailOver.length())
5354 if (x->FailOver == x->Name)
5356 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());
5359 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5362 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5363 Creator->ConnectServer(TryThisOne);
5367 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5372 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5374 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5376 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5384 class ModuleSpanningTreeFactory : public ModuleFactory
5387 ModuleSpanningTreeFactory()
5391 ~ModuleSpanningTreeFactory()
5395 virtual Module * CreateModule(InspIRCd* Me)
5397 return new ModuleSpanningTree(Me);
5403 extern "C" void * init_module( void )
5405 return new ModuleSpanningTreeFactory;