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, char status, const CUList &exempt_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. */
1811 /* find created channel .. */
1812 chan = this->Instance->FindChan(channel);
1814 /* w00t said this shouldnt be needed but it is.
1815 * This isnt strictly true, as chan can be NULL
1816 * if a nick collision has occured and therefore
1817 * the channel was never created.
1822 /* All done. That wasnt so bad was it, you can wipe
1823 * the sweat from your forehead now. :-)
1829 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1831 if (params.size() < 8)
1833 if (params.size() > 8)
1835 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1838 // NICK age nick host dhost ident +modes ip :gecos
1840 time_t age = atoi(params[0].c_str());
1842 /* This used to have a pretty craq'y loop doing the same thing,
1843 * now we just let the STL do the hard work (more efficiently)
1845 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1846 if (pos_after_plus != std::string::npos)
1847 params[5] = params[5].substr(pos_after_plus);
1849 const char* tempnick = params[1].c_str();
1850 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1852 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1854 if (iter != this->Instance->clientlist.end())
1857 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);
1858 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1859 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1863 userrec* _new = new userrec(this->Instance);
1864 this->Instance->clientlist[tempnick] = _new;
1865 _new->SetFd(FD_MAGIC_NUMBER);
1866 strlcpy(_new->nick, tempnick,NICKMAX-1);
1867 strlcpy(_new->host, params[2].c_str(),63);
1868 strlcpy(_new->dhost, params[3].c_str(),63);
1869 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1870 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1871 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1872 _new->registered = REG_ALL;
1875 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1876 _new->modes[(*v)-65] = 1;
1878 #ifdef SUPPORT_IP6LINKS
1879 if (params[6].find_first_of(":") != std::string::npos)
1880 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1883 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1885 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1887 params[7] = ":" + params[7];
1888 Utils->DoOneToAllButSender(source,"NICK",params,source);
1890 // Increment the Source Servers User Count..
1891 TreeServer* SourceServer = Utils->FindServer(source);
1894 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1895 SourceServer->AddUserCount();
1898 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1903 /** Send one or more FJOINs for a channel of users.
1904 * If the length of a single line is more than 480-NICKMAX
1905 * in length, it is split over multiple lines.
1907 void SendFJoins(TreeServer* Current, chanrec* c)
1911 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1913 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1915 size_t dlen, curlen;
1916 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1918 char* ptr = list + dlen;
1920 CUList *ulist = c->GetUsers();
1921 std::string modes = "";
1922 std::string params = "";
1924 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1926 // The first parameter gets a : before it
1927 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1934 if (curlen > (480-NICKMAX))
1936 buffer.append(list).append("\r\n");
1938 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1946 buffer.append(list).append("\r\n");
1948 /* Sorry for the hax. Because newly created channels assume +nt,
1949 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1951 bool inverted = false;
1952 if (!c->IsModeSet('n'))
1957 if (!c->IsModeSet('t'))
1967 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1970 params.append(" ").append(b->data);
1972 if (params.length() >= MAXMODES)
1974 /* Wrap at MAXMODES */
1975 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");
1981 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1983 /* Only send these if there are any */
1985 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);
1987 this->WriteLine(buffer);
1990 /** Send G, Q, Z and E lines */
1991 void SendXLines(TreeServer* Current)
1995 std::string n = this->Instance->Config->ServerName;
1996 const char* sn = n.c_str();
1998 /* Yes, these arent too nice looking, but they get the job done */
1999 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
2001 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);
2002 buffer.append(data);
2004 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
2006 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);
2007 buffer.append(data);
2009 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
2011 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);
2012 buffer.append(data);
2014 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
2016 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);
2017 buffer.append(data);
2019 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
2021 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);
2022 buffer.append(data);
2024 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
2026 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);
2027 buffer.append(data);
2029 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
2031 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);
2032 buffer.append(data);
2034 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
2036 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);
2037 buffer.append(data);
2040 if (!buffer.empty())
2041 this->WriteLine(buffer);
2044 /** Send channel modes and topics */
2045 void SendChannelModes(TreeServer* Current)
2048 std::deque<std::string> list;
2050 std::string n = this->Instance->Config->ServerName;
2051 const char* sn = n.c_str();
2052 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2054 SendFJoins(Current, c->second);
2055 if (*c->second->topic)
2057 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2058 this->WriteLine(data);
2060 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2062 c->second->GetExtList(list);
2063 for (unsigned int j = 0; j < list.size(); j++)
2065 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2070 /** send all users and their oper state/modes */
2071 void SendUsers(TreeServer* Current)
2074 std::deque<std::string> list;
2075 std::string dataline;
2077 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2079 if (u->second->registered == REG_ALL)
2081 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);
2082 this->WriteLine(data);
2083 if (*u->second->oper)
2085 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2086 this->WriteLine(data);
2088 if (*u->second->awaymsg)
2090 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2091 this->WriteLine(data);
2093 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2095 u->second->GetExtList(list);
2096 for (unsigned int j = 0; j < list.size(); j++)
2098 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2104 /** This function is called when we want to send a netburst to a local
2105 * server. There is a set order we must do this, because for example
2106 * users require their servers to exist, and channels require their
2107 * users to exist. You get the idea.
2109 void DoBurst(TreeServer* s)
2111 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2112 std::string endburst = "ENDBURST";
2113 // Because by the end of the netburst, it could be gone!
2114 std::string name = s->GetName();
2115 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2116 this->WriteLine(burst);
2117 /* send our version string */
2118 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2119 /* Send server tree */
2120 this->SendServers(Utils->TreeRoot,s,1);
2121 /* Send users and their oper status */
2123 /* Send everything else (channel modes, xlines etc) */
2124 this->SendChannelModes(s);
2125 this->SendXLines(s);
2126 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2127 this->WriteLine(endburst);
2128 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2131 /** This function is called when we receive data from a remote
2132 * server. We buffer the data in a std::string (it doesnt stay
2133 * there for long), reading using InspSocket::Read() which can
2134 * read up to 16 kilobytes in one operation.
2136 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2137 * THE SOCKET OBJECT FOR US.
2139 virtual bool OnDataReady()
2141 char* data = this->Read();
2142 /* Check that the data read is a valid pointer and it has some content */
2145 this->in_buffer.append(data);
2146 /* While there is at least one new line in the buffer,
2147 * do something useful (we hope!) with it.
2149 while (in_buffer.find("\n") != std::string::npos)
2151 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2152 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2153 /* Use rfind here not find, as theres more
2154 * chance of the \r being near the end of the
2155 * string, not the start.
2157 if (ret.find("\r") != std::string::npos)
2158 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2159 /* Process this one, abort if it
2160 * didnt return true.
2166 memset(result,0,1024);
2168 /* ERROR + CAPAB is still allowed unencryped */
2169 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2171 int nbytes = from64tobits(out, ret.c_str(), 1024);
2172 if ((nbytes > 0) && (nbytes < 1024))
2174 ctx_in->Decrypt(out, result, nbytes, 0);
2175 for (int t = 0; t < nbytes; t++)
2177 if (result[t] == '\7')
2179 /* We only need to stick a \0 on the
2180 * first \7, the rest will be lost
2190 if (!this->ProcessLine(ret))
2197 /* EAGAIN returns an empty but non-NULL string, so this
2198 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2200 return (data && !*data);
2203 int WriteLine(std::string line)
2205 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2209 char result64[10240];
2210 if (this->keylength)
2212 // pad it to the key length
2213 int n = this->keylength - (line.length() % this->keylength);
2215 line.append(n,'\7');
2217 unsigned int ll = line.length();
2218 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2219 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2222 line.append("\r\n");
2223 return this->Write(line);
2226 /* Handle ERROR command */
2227 bool Error(std::deque<std::string> ¶ms)
2229 if (params.size() < 1)
2231 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2232 /* we will return false to cause the socket to close. */
2236 /** remote MOTD. leet, huh? */
2237 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2239 if (params.size() > 0)
2241 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2243 /* It's for our server */
2244 string_list results;
2245 userrec* source = this->Instance->FindNick(prefix);
2249 std::deque<std::string> par;
2250 par.push_back(prefix);
2253 if (!Instance->Config->MOTD.size())
2255 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2256 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2260 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2261 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2263 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2265 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2266 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2269 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2270 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2276 userrec* source = this->Instance->FindNick(prefix);
2278 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2284 /** remote ADMIN. leet, huh? */
2285 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2287 if (params.size() > 0)
2289 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2291 /* It's for our server */
2292 string_list results;
2293 userrec* source = this->Instance->FindNick(prefix);
2297 std::deque<std::string> par;
2298 par.push_back(prefix);
2301 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2302 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2304 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2305 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2307 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2308 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2310 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2311 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2317 userrec* source = this->Instance->FindNick(prefix);
2319 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2325 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2327 /* Get the reply to a STATS query if it matches this servername,
2328 * and send it back as a load of PUSH queries
2330 if (params.size() > 1)
2332 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2334 /* It's for our server */
2335 string_list results;
2336 userrec* source = this->Instance->FindNick(prefix);
2339 std::deque<std::string> par;
2340 par.push_back(prefix);
2342 DoStats(this->Instance, *(params[0].c_str()), source, results);
2343 for (size_t i = 0; i < results.size(); i++)
2345 par[1] = "::" + results[i];
2346 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2353 userrec* source = this->Instance->FindNick(prefix);
2355 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2362 /** Because the core won't let users or even SERVERS set +o,
2363 * we use the OPERTYPE command to do this.
2365 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2367 if (params.size() != 1)
2369 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2372 std::string opertype = params[0];
2373 userrec* u = this->Instance->FindNick(prefix);
2376 u->modes[UM_OPERATOR] = 1;
2377 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2378 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2383 /** Because Andy insists that services-compatible servers must
2384 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2386 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2388 if (params.size() < 3)
2391 userrec* u = this->Instance->FindNick(params[0]);
2395 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2398 std::deque<std::string> par;
2399 par.push_back(params[1]);
2400 /* This is not required as one is sent in OnUserPostNick below
2402 //Utils->DoOneToMany(u->nick,"NICK",par);
2403 if (!u->ForceNickChange(params[1].c_str()))
2405 userrec::QuitUser(this->Instance, u, "Nickname collision");
2408 u->age = atoi(params[2].c_str());
2414 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2416 if (params.size() < 2)
2419 userrec* u = this->Instance->FindNick(params[0]);
2423 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2424 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2429 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2431 if (params.size() < 1)
2434 std::string servermask = params[0];
2436 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2438 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2439 this->Instance->RehashServer();
2440 Utils->ReadConfiguration(false);
2441 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2443 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2447 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2449 if (params.size() != 2)
2452 std::string nick = params[0];
2453 userrec* u = this->Instance->FindNick(prefix);
2454 userrec* who = this->Instance->FindNick(nick);
2458 /* Prepend kill source, if we don't have one */
2459 std::string sourceserv = prefix;
2462 sourceserv = u->server;
2464 if (*(params[1].c_str()) != '[')
2466 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2468 std::string reason = params[1];
2469 params[1] = ":" + params[1];
2470 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2471 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2472 userrec::QuitUser(this->Instance,who,reason);
2477 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2479 if (params.size() < 1)
2482 if (params.size() == 1)
2484 TreeServer* ServerSource = Utils->FindServer(prefix);
2487 ServerSource->SetPingFlag();
2492 std::string forwardto = params[1];
2493 if (forwardto == this->Instance->Config->ServerName)
2496 * this is a PONG for us
2497 * if the prefix is a user, check theyre local, and if they are,
2498 * dump the PONG reply back to their fd. If its a server, do nowt.
2499 * Services might want to send these s->s, but we dont need to yet.
2501 userrec* u = this->Instance->FindNick(prefix);
2505 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2510 // not for us, pass it on :)
2511 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2518 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2520 if (params.size() < 3)
2523 TreeServer* ServerSource = Utils->FindServer(prefix);
2527 if (params[0] == "*")
2529 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2531 else if (*(params[0].c_str()) == '#')
2533 chanrec* c = this->Instance->FindChan(params[0]);
2536 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2539 else if (*(params[0].c_str()) != '#')
2541 userrec* u = this->Instance->FindNick(params[0]);
2544 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2549 params[2] = ":" + params[2];
2550 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2554 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2556 if (params.size() < 1)
2559 TreeServer* ServerSource = Utils->FindServer(prefix);
2563 ServerSource->SetVersion(params[0]);
2565 params[0] = ":" + params[0];
2566 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2570 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2572 if (params.size() < 1)
2575 userrec* u = this->Instance->FindNick(prefix);
2579 u->ChangeDisplayedHost(params[0].c_str());
2580 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2585 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2587 if (params.size() < 6)
2590 bool propogate = false;
2592 switch (*(params[0].c_str()))
2595 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2596 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2599 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2600 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2603 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2604 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2607 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2608 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2611 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2614 /* Just in case... */
2615 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2620 /* Send it on its way */
2623 if (atoi(params[4].c_str()))
2625 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());
2629 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());
2631 params[5] = ":" + params[5];
2632 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2634 if (!this->bursting)
2636 Instance->Log(DEBUG,"Applying lines...");
2637 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2642 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2644 if (params.size() < 1)
2647 userrec* u = this->Instance->FindNick(prefix);
2651 u->ChangeName(params[0].c_str());
2652 params[0] = ":" + params[0];
2653 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2658 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2660 if (params.size() < 1)
2663 Instance->Log(DEBUG,"In IDLE command");
2664 userrec* u = this->Instance->FindNick(prefix);
2668 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2669 // an incoming request
2670 if (params.size() == 1)
2672 userrec* x = this->Instance->FindNick(params[0]);
2673 if ((x) && (IS_LOCAL(x)))
2675 userrec* x = this->Instance->FindNick(params[0]);
2676 char signon[MAXBUF];
2679 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2680 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2681 std::deque<std::string> par;
2682 par.push_back(prefix);
2683 par.push_back(signon);
2684 par.push_back(idle);
2685 // ours, we're done, pass it BACK
2686 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2690 // not ours pass it on
2691 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2694 else if (params.size() == 3)
2696 std::string who_did_the_whois = params[0];
2697 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2698 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2700 // an incoming reply to a whois we sent out
2701 std::string nick_whoised = prefix;
2702 unsigned long signon = atoi(params[1].c_str());
2703 unsigned long idle = atoi(params[2].c_str());
2704 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2705 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2709 // not ours, pass it on
2710 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2717 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2719 if (params.size() < 2)
2722 userrec* u = this->Instance->FindNick(params[0]);
2729 u->Write(params[1]);
2733 // continue the raw onwards
2734 params[1] = ":" + params[1];
2735 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2740 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2742 if (!params.size() || !Utils->EnableTimeSync)
2747 if ((params.size() == 2) && (params[1] == "FORCE"))
2750 time_t rts = atoi(params[0].c_str());
2751 time_t us = Instance->Time(true);
2755 Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2757 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2759 else if (force || (rts < us))
2761 int old = Instance->SetTimeDelta(rts - us);
2762 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2764 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2768 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2770 std::deque<std::string> oparams;
2771 oparams.push_back(ConvToStr(us));
2773 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2779 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2781 // :source.server TIME remote.server sendernick
2782 // :remote.server TIME source.server sendernick TS
2783 if (params.size() == 2)
2785 // someone querying our time?
2786 if (this->Instance->Config->ServerName == params[0])
2788 userrec* u = this->Instance->FindNick(params[1]);
2791 params.push_back(ConvToStr(Instance->Time(false)));
2793 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2798 // not us, pass it on
2799 userrec* u = this->Instance->FindNick(params[1]);
2801 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2804 else if (params.size() == 3)
2806 // a response to a previous TIME
2807 userrec* u = this->Instance->FindNick(params[1]);
2808 if ((u) && (IS_LOCAL(u)))
2810 time_t rawtime = atol(params[2].c_str());
2811 struct tm * timeinfo;
2812 timeinfo = localtime(&rawtime);
2814 snprintf(tms,26,"%s",asctime(timeinfo));
2816 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2821 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2827 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2829 if (params.size() < 1)
2832 if (params.size() == 1)
2834 std::string stufftobounce = params[0];
2835 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2840 std::string forwardto = params[1];
2841 if (forwardto == this->Instance->Config->ServerName)
2843 // this is a ping for us, send back PONG to the requesting server
2844 params[1] = params[0];
2845 params[0] = forwardto;
2846 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2850 // not for us, pass it on :)
2851 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2857 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2859 if (params.size() < 1)
2862 chanrec* c = Instance->FindChan(params[0]);
2866 irc::modestacker modestack(false);
2867 CUList *ulist = c->GetUsers();
2869 std::deque<std::string> stackresult;
2872 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2874 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2875 if (modesequence.length())
2877 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2878 irc::spacesepstream sep(modesequence);
2879 std::string modeletters = sep.GetToken();
2880 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2882 while (!modeletters.empty())
2884 char mletter = *(modeletters.begin());
2885 modestack.Push(mletter,sep.GetToken());
2886 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2887 modeletters.erase(modeletters.begin());
2888 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2893 while (modestack.GetStackedLine(stackresult))
2895 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2896 stackresult.push_front(ConvToStr(c->age));
2897 stackresult.push_front(c->name);
2898 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2899 stackresult.erase(stackresult.begin() + 1);
2900 Instance->Log(DEBUG,"Stacked items:");
2901 for (size_t z = 0; z < stackresult.size(); z++)
2903 y[z] = stackresult[z].c_str();
2904 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2906 userrec* n = new userrec(Instance);
2907 n->SetFd(FD_MAGIC_NUMBER);
2908 Instance->SendMode(y, stackresult.size(), n);
2915 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2917 if (params.size() < 4)
2920 std::string servername = params[0];
2921 std::string password = params[1];
2922 // hopcount is not used for a remote server, we calculate this ourselves
2923 std::string description = params[3];
2924 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2928 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2931 TreeServer* CheckDupe = Utils->FindServer(servername);
2934 this->WriteLine("ERROR :Server "+servername+" already exists!");
2935 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2938 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2939 ParentOfThis->AddChild(Node);
2940 params[3] = ":" + params[3];
2941 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2942 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2946 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2948 if (params.size() < 4)
2951 irc::string servername = params[0].c_str();
2952 std::string sname = params[0];
2953 std::string password = params[1];
2954 int hops = atoi(params[2].c_str());
2958 this->WriteLine("ERROR :Server too far away for authentication");
2959 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2962 std::string description = params[3];
2963 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2965 if ((x->Name == servername) && (x->RecvPass == password))
2967 TreeServer* CheckDupe = Utils->FindServer(sname);
2970 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2971 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2974 // Begin the sync here. this kickstarts the
2975 // other side, waiting in WAIT_AUTH_2 state,
2976 // into starting their burst, as it shows
2977 // that we're happy.
2978 this->LinkState = CONNECTED;
2979 // we should add the details of this server now
2980 // to the servers tree, as a child of the root
2982 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2983 Utils->TreeRoot->AddChild(Node);
2984 params[3] = ":" + params[3];
2985 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2986 this->bursting = true;
2987 this->DoBurst(Node);
2991 this->WriteLine("ERROR :Invalid credentials");
2992 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2996 bool Inbound_Server(std::deque<std::string> ¶ms)
2998 if (params.size() < 4)
3001 irc::string servername = params[0].c_str();
3002 std::string sname = params[0];
3003 std::string password = params[1];
3004 int hops = atoi(params[2].c_str());
3008 this->WriteLine("ERROR :Server too far away for authentication");
3009 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
3012 std::string description = params[3];
3013 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3015 if ((x->Name == servername) && (x->RecvPass == password))
3017 TreeServer* CheckDupe = Utils->FindServer(sname);
3020 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3021 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3024 /* If the config says this link is encrypted, but the remote side
3025 * hasnt bothered to send the AES command before SERVER, then we
3026 * boot them off as we MUST have this connection encrypted.
3028 if ((x->EncryptionKey != "") && (!this->ctx_in))
3030 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
3031 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
3034 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
3035 this->InboundServerName = sname;
3036 this->InboundDescription = description;
3037 // this is good. Send our details: Our server name and description and hopcount of 0,
3038 // along with the sendpass from this block.
3039 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3040 // move to the next state, we are now waiting for THEM.
3041 this->LinkState = WAIT_AUTH_2;
3045 this->WriteLine("ERROR :Invalid credentials");
3046 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3050 void Split(const std::string &line, std::deque<std::string> &n)
3053 irc::tokenstream tokens(line);
3055 while ((param = tokens.GetToken()) != "")
3060 bool ProcessLine(std::string &line)
3062 std::deque<std::string> params;
3063 irc::string command;
3069 line = line.substr(0, line.find_first_of("\r\n"));
3071 Instance->Log(DEBUG,"IN: %s", line.c_str());
3073 this->Split(line.c_str(),params);
3075 if ((params[0][0] == ':') && (params.size() > 1))
3077 prefix = params[0].substr(1);
3081 command = params[0].c_str();
3084 if ((!this->ctx_in) && (command == "AES"))
3086 std::string sserv = params[0];
3087 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3089 if ((x->EncryptionKey != "") && (x->Name == sserv))
3091 this->InitAES(x->EncryptionKey,sserv);
3097 else if ((this->ctx_in) && (command == "AES"))
3099 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());
3102 switch (this->LinkState)
3107 // Waiting for SERVER command from remote server. Server initiating
3108 // the connection sends the first SERVER command, listening server
3109 // replies with theirs if its happy, then if the initiator is happy,
3110 // it starts to send its net sync, which starts the merge, otherwise
3111 // it sends an ERROR.
3112 if (command == "PASS")
3114 /* Silently ignored */
3116 else if (command == "SERVER")
3118 return this->Inbound_Server(params);
3120 else if (command == "ERROR")
3122 return this->Error(params);
3124 else if (command == "USER")
3126 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3129 else if (command == "CAPAB")
3131 return this->Capab(params);
3133 else if ((command == "U") || (command == "S"))
3135 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3140 std::string error("ERROR :Invalid command in negotiation phase: ");
3141 error.append(command.c_str());
3142 this->WriteLine(error);
3147 // Waiting for start of other side's netmerge to say they liked our
3149 if (command == "SERVER")
3151 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3155 else if ((command == "U") || (command == "S"))
3157 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3160 else if (command == "BURST")
3162 if (params.size() && Utils->EnableTimeSync)
3164 /* If a time stamp is provided, apply synchronization */
3166 time_t them = atoi(params[0].c_str());
3167 time_t us = Instance->Time(true);
3168 int delta = them - us;
3170 if ((params.size() == 2) && (params[1] == "FORCE"))
3173 if ((delta < -600) || (delta > 600))
3175 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));
3176 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3182 this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3184 else if (force || (us > them))
3186 this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3187 this->Instance->SetTimeDelta(them - us);
3188 // Send this new timestamp to any other servers
3189 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3193 // Override the timestamp
3194 this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3195 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3198 this->LinkState = CONNECTED;
3199 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3200 Utils->TreeRoot->AddChild(Node);
3202 params.push_back(InboundServerName);
3203 params.push_back("*");
3204 params.push_back("1");
3205 params.push_back(":"+InboundDescription);
3206 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3207 this->bursting = true;
3208 this->DoBurst(Node);
3210 else if (command == "ERROR")
3212 return this->Error(params);
3214 else if (command == "CAPAB")
3216 return this->Capab(params);
3221 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3225 if (command == "SERVER")
3227 // another server we connected to, which was in WAIT_AUTH_1 state,
3228 // has just sent us their credentials. If we get this far, theyre
3229 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3230 // if we're happy with this, we should send our netburst which
3231 // kickstarts the merge.
3232 return this->Outbound_Reply_Server(params);
3234 else if (command == "ERROR")
3236 return this->Error(params);
3240 // This is the 'authenticated' state, when all passwords
3241 // have been exchanged and anything past this point is taken
3246 std::string direction = prefix;
3247 userrec* t = this->Instance->FindNick(prefix);
3250 direction = t->server;
3252 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3253 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3255 if (route_back_again)
3256 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3261 * When there is activity on the socket, reset the ping counter so
3262 * that we're not wasting bandwidth pinging an active server.
3264 route_back_again->SetNextPingTime(time(NULL) + 60);
3265 route_back_again->SetPingFlag();
3268 if (command == "SVSMODE")
3270 /* Services expects us to implement
3271 * SVSMODE. In inspircd its the same as
3276 std::string target = "";
3277 /* Yes, know, this is a mess. Its reasonably fast though as we're
3278 * working with std::string here.
3280 if ((command == "NICK") && (params.size() > 1))
3282 return this->IntroduceClient(prefix,params);
3284 else if (command == "FJOIN")
3286 return this->ForceJoin(prefix,params);
3288 else if (command == "STATS")
3290 return this->Stats(prefix, params);
3292 else if (command == "MOTD")
3294 return this->Motd(prefix, params);
3296 else if (command == "ADMIN")
3298 return this->Admin(prefix, params);
3300 else if (command == "SERVER")
3302 return this->RemoteServer(prefix,params);
3304 else if (command == "ERROR")
3306 return this->Error(params);
3308 else if (command == "OPERTYPE")
3310 return this->OperType(prefix,params);
3312 else if (command == "FMODE")
3314 return this->ForceMode(prefix,params);
3316 else if (command == "KILL")
3318 return this->RemoteKill(prefix,params);
3320 else if (command == "FTOPIC")
3322 return this->ForceTopic(prefix,params);
3324 else if (command == "REHASH")
3326 return this->RemoteRehash(prefix,params);
3328 else if (command == "METADATA")
3330 return this->MetaData(prefix,params);
3332 else if (command == "REMSTATUS")
3334 return this->RemoveStatus(prefix,params);
3336 else if (command == "PING")
3339 * We just got a ping from a server that's bursting.
3340 * This can't be right, so set them to not bursting, and
3341 * apply their lines.
3345 this->bursting = false;
3346 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3350 prefix = this->GetName();
3352 return this->LocalPing(prefix,params);
3354 else if (command == "PONG")
3357 * We just got a pong from a server that's bursting.
3358 * This can't be right, so set them to not bursting, and
3359 * apply their lines.
3363 this->bursting = false;
3364 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3368 prefix = this->GetName();
3370 return this->LocalPong(prefix,params);
3372 else if (command == "VERSION")
3374 return this->ServerVersion(prefix,params);
3376 else if (command == "FHOST")
3378 return this->ChangeHost(prefix,params);
3380 else if (command == "FNAME")
3382 return this->ChangeName(prefix,params);
3384 else if (command == "ADDLINE")
3386 return this->AddLine(prefix,params);
3388 else if (command == "SVSNICK")
3392 prefix = this->GetName();
3394 return this->ForceNick(prefix,params);
3396 else if (command == "IDLE")
3398 return this->Whois(prefix,params);
3400 else if (command == "PUSH")
3402 return this->Push(prefix,params);
3404 else if (command == "TIMESET")
3406 return this->HandleSetTime(prefix, params);
3408 else if (command == "TIME")
3410 return this->Time(prefix,params);
3412 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3414 std::string sourceserv = this->myhost;
3415 if (params.size() == 3)
3417 userrec* user = this->Instance->FindNick(params[1]);
3418 chanrec* chan = this->Instance->FindChan(params[0]);
3421 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3422 /* Yikes, the channels gone! */
3426 if (this->InboundServerName != "")
3428 sourceserv = this->InboundServerName;
3430 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3432 else if (command == "SVSJOIN")
3436 prefix = this->GetName();
3438 return this->ServiceJoin(prefix,params);
3440 else if (command == "SQUIT")
3442 if (params.size() == 2)
3444 this->Squit(Utils->FindServer(params[0]),params[1]);
3448 else if (command == "OPERNOTICE")
3450 std::string sourceserv = this->myhost;
3452 if (this->InboundServerName != "")
3453 sourceserv = this->InboundServerName;
3455 if (params.size() >= 1)
3456 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3458 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3460 else if (command == "MODENOTICE")
3462 std::string sourceserv = this->myhost;
3463 if (this->InboundServerName != "")
3464 sourceserv = this->InboundServerName;
3465 if (params.size() >= 2)
3467 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3470 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3472 else if (command == "SNONOTICE")
3474 std::string sourceserv = this->myhost;
3475 if (this->InboundServerName != "")
3476 sourceserv = this->InboundServerName;
3477 if (params.size() >= 2)
3479 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3482 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3484 else if (command == "ENDBURST")
3486 this->bursting = false;
3487 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3488 std::string sourceserv = this->myhost;
3489 if (this->InboundServerName != "")
3491 sourceserv = this->InboundServerName;
3493 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3495 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3496 rmode.Send(Instance);
3502 // not a special inter-server command.
3503 // Emulate the actual user doing the command,
3504 // this saves us having a huge ugly parser.
3505 userrec* who = this->Instance->FindNick(prefix);
3506 std::string sourceserv = this->myhost;
3507 if (this->InboundServerName != "")
3509 sourceserv = this->InboundServerName;
3511 if ((!who) && (command == "MODE"))
3513 if (Utils->IsServer(prefix))
3515 const char* modelist[127];
3516 for (size_t i = 0; i < params.size(); i++)
3517 modelist[i] = params[i].c_str();
3519 userrec* fake = new userrec(Instance);
3520 fake->SetFd(FD_MAGIC_NUMBER);
3522 this->Instance->SendMode(modelist, params.size(), fake);
3526 /* Hot potato! pass it on! */
3527 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3532 if ((command == "NICK") && (params.size() > 0))
3534 /* On nick messages, check that the nick doesnt
3535 * already exist here. If it does, kill their copy,
3538 userrec* x = this->Instance->FindNick(params[0]);
3539 if ((x) && (x != who))
3541 std::deque<std::string> p;
3542 p.push_back(params[0]);
3543 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3544 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3546 p.push_back(prefix);
3547 p.push_back("Nickname collision");
3548 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3549 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3550 userrec* y = this->Instance->FindNick(prefix);
3553 userrec::QuitUser(this->Instance,y,"Nickname collision");
3555 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3559 target = who->server;
3560 const char* strparams[127];
3561 for (unsigned int q = 0; q < params.size(); q++)
3563 strparams[q] = params[q].c_str();
3565 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3568 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3575 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3581 // its not a user. Its either a server, or somethings screwed up.
3582 if (Utils->IsServer(prefix))
3584 target = this->Instance->Config->ServerName;
3588 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3592 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3601 virtual std::string GetName()
3603 std::string sourceserv = this->myhost;
3604 if (this->InboundServerName != "")
3606 sourceserv = this->InboundServerName;
3611 virtual void OnTimeout()
3613 if (this->LinkState == CONNECTING)
3615 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3616 Link* MyLink = Utils->FindLink(myhost);
3618 Utils->DoFailOver(MyLink);
3622 virtual void OnClose()
3624 // Connection closed.
3625 // If the connection is fully up (state CONNECTED)
3626 // then propogate a netsplit to all peers.
3627 std::string quitserver = this->myhost;
3628 if (this->InboundServerName != "")
3630 quitserver = this->InboundServerName;
3632 TreeServer* s = Utils->FindServer(quitserver);
3635 Squit(s,"Remote host closed the connection");
3638 if (quitserver != "")
3639 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3642 virtual int OnIncomingConnection(int newsock, char* ip)
3644 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3645 * or discovering if this port is the server port, we don't allow connections from any
3646 * IPs for which we don't have a link block.
3650 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3653 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3654 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3659 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3664 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3665 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3670 /** This class is used to resolve server hostnames during /connect and autoconnect.
3671 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3672 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3673 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3674 * will have an IP address which we can then use to continue our connection.
3676 class ServernameResolver : public Resolver
3679 /** A copy of the Link tag info for what we're connecting to.
3680 * We take a copy, rather than using a pointer, just in case the
3681 * admin takes the tag away and rehashes while the domain is resolving.
3684 SpanningTreeUtilities* Utils;
3686 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3688 /* Nothing in here, folks */
3691 void OnLookupComplete(const std::string &result)
3693 /* Initiate the connection, now that we have an IP to use.
3694 * Passing a hostname directly to InspSocket causes it to
3695 * just bail and set its FD to -1.
3697 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3698 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3700 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
3701 if (newsocket->GetFd() > -1)
3707 /* Something barfed, show the opers */
3708 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3710 Utils->DoFailOver(&MyLink);
3715 void OnError(ResolverError e, const std::string &errormessage)
3718 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3719 Utils->DoFailOver(&MyLink);
3723 /** Handle resolving of server IPs for the cache
3725 class SecurityIPResolver : public Resolver
3729 SpanningTreeUtilities* Utils;
3731 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3735 void OnLookupComplete(const std::string &result)
3737 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3738 Utils->ValidIPs.push_back(result);
3741 void OnError(ResolverError e, const std::string &errormessage)
3743 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3747 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3750 this->ReadConfiguration(true);
3751 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3754 SpanningTreeUtilities::~SpanningTreeUtilities()
3756 for (unsigned int i = 0; i < Bindings.size(); i++)
3758 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3759 ServerInstance->SE->DelFd(Bindings[i]);
3760 Bindings[i]->Close();
3761 DELETE(Bindings[i]);
3763 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3764 while (TreeRoot->ChildCount())
3766 TreeServer* child_server = TreeRoot->GetChild(0);
3767 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3770 TreeSocket* sock = child_server->GetSocket();
3771 ServerInstance->SE->DelFd(sock);
3779 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3781 for (unsigned int c = 0; c < list.size(); c++)
3783 if (list[c] == server)
3788 list.push_back(server);
3791 /** returns a list of DIRECT servernames for a specific channel */
3792 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list, char status, const CUList &exempt_list)
3798 ulist = c->GetOppedUsers();
3801 ulist = c->GetHalfoppedUsers();
3804 ulist = c->GetVoicedUsers();
3807 ulist = c->GetUsers();
3810 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3812 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
3814 TreeServer* best = this->BestRouteTo(i->second->server);
3816 AddThisServer(best,list);
3822 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3825 TreeServer* omitroute = this->BestRouteTo(omit);
3826 if ((command == "NOTICE") || (command == "PRIVMSG"))
3828 if (params.size() >= 2)
3831 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3834 params[0] = params[0].substr(1, params[0].length()-1);
3836 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3838 // special routing for private messages/notices
3839 userrec* d = ServerInstance->FindNick(params[0]);
3842 std::deque<std::string> par;
3843 par.push_back(params[0]);
3844 par.push_back(":"+params[1]);
3845 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3849 else if (*(params[0].c_str()) == '$')
3851 std::deque<std::string> par;
3852 par.push_back(params[0]);
3853 par.push_back(":"+params[1]);
3854 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3859 chanrec* c = ServerInstance->FindChan(params[0]);
3860 userrec* u = ServerInstance->FindNick(prefix);
3864 std::deque<TreeServer*> list;
3865 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
3866 GetListOfServersForChannel(c,list,pfx,elist);
3867 unsigned int lsize = list.size();
3868 for (unsigned int i = 0; i < lsize; i++)
3870 TreeSocket* Sock = list[i]->GetSocket();
3871 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3873 Sock->WriteLine(data);
3881 unsigned int items =this->TreeRoot->ChildCount();
3882 for (unsigned int x = 0; x < items; x++)
3884 TreeServer* Route = this->TreeRoot->GetChild(x);
3885 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3887 TreeSocket* Sock = Route->GetSocket();
3889 Sock->WriteLine(data);
3895 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
3897 TreeServer* omitroute = this->BestRouteTo(omit);
3898 std::string FullLine = ":" + prefix + " " + command;
3899 unsigned int words = params.size();
3900 for (unsigned int x = 0; x < words; x++)
3902 FullLine = FullLine + " " + params[x];
3904 unsigned int items = this->TreeRoot->ChildCount();
3905 for (unsigned int x = 0; x < items; x++)
3907 TreeServer* Route = this->TreeRoot->GetChild(x);
3908 // Send the line IF:
3909 // The route has a socket (its a direct connection)
3910 // The route isnt the one to be omitted
3911 // The route isnt the path to the one to be omitted
3912 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3914 TreeSocket* Sock = Route->GetSocket();
3916 Sock->WriteLine(FullLine);
3922 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
3924 std::string FullLine = ":" + prefix + " " + command;
3925 unsigned int words = params.size();
3926 for (unsigned int x = 0; x < words; x++)
3928 FullLine = FullLine + " " + params[x];
3930 unsigned int items = this->TreeRoot->ChildCount();
3931 for (unsigned int x = 0; x < items; x++)
3933 TreeServer* Route = this->TreeRoot->GetChild(x);
3934 if (Route && Route->GetSocket())
3936 TreeSocket* Sock = Route->GetSocket();
3938 Sock->WriteLine(FullLine);
3944 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3946 std::string spfx = prefix;
3947 std::string scmd = command;
3948 return this->DoOneToMany(spfx, scmd, params);
3951 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3953 std::string spfx = prefix;
3954 std::string scmd = command;
3955 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3958 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
3960 TreeServer* Route = this->BestRouteTo(target);
3963 std::string FullLine = ":" + prefix + " " + command;
3964 unsigned int words = params.size();
3965 for (unsigned int x = 0; x < words; x++)
3967 FullLine = FullLine + " " + params[x];
3969 if (Route && Route->GetSocket())
3971 TreeSocket* Sock = Route->GetSocket();
3973 Sock->WriteLine(FullLine);
3983 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3985 ConfigReader* Conf = new ConfigReader(ServerInstance);
3988 for (int j =0; j < Conf->Enumerate("bind"); j++)
3990 std::string Type = Conf->ReadValue("bind","type",j);
3991 std::string IP = Conf->ReadValue("bind","address",j);
3992 std::string Port = Conf->ReadValue("bind","port",j);
3993 if (Type == "servers")
3995 irc::portparser portrange(Port, false);
3997 while ((portno = portrange.GetToken()))
3999 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
4003 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10);
4004 if (listener->GetState() == I_LISTENING)
4006 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
4007 Bindings.push_back(listener);
4011 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
4015 ServerInstance->Log(DEBUG,"Done with this binding");
4020 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
4021 HideULines = Conf->ReadFlag("options","hideulines",0);
4022 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
4023 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
4026 for (int j =0; j < Conf->Enumerate("link"); j++)
4029 std::string Allow = Conf->ReadValue("link","allowmask",j);
4030 L.Name = (Conf->ReadValue("link","name",j)).c_str();
4031 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
4032 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
4033 L.Port = Conf->ReadInteger("link","port",j,true);
4034 L.SendPass = Conf->ReadValue("link","sendpass",j);
4035 L.RecvPass = Conf->ReadValue("link","recvpass",j);
4036 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
4037 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
4038 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
4039 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
4040 L.NextConnectTime = time(NULL) + L.AutoConnect;
4041 /* Bugfix by brain, do not allow people to enter bad configurations */
4042 if (L.Name != ServerInstance->Config->ServerName)
4044 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
4046 ValidIPs.push_back(L.IPAddr);
4049 ValidIPs.push_back(Allow);
4051 /* Needs resolving */
4053 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
4057 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
4058 ServerInstance->AddResolver(sr);
4060 catch (ModuleException& e)
4062 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4066 LinkBlocks.push_back(L);
4067 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4073 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4075 else if (L.RecvPass == "")
4077 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4079 else if (L.SendPass == "")
4081 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4083 else if (L.Name == "")
4085 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4089 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4095 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4101 /** To create a timer which recurs every second, we inherit from InspTimer.
4102 * InspTimer is only one-shot however, so at the end of each Tick() we simply
4103 * insert another of ourselves into the pending queue :)
4105 class TimeSyncTimer : public InspTimer
4109 ModuleSpanningTree *Module;
4111 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4112 virtual void Tick(time_t TIME);
4115 class ModuleSpanningTree : public Module
4119 unsigned int max_local;
4120 unsigned int max_global;
4121 cmd_rconnect* command_rconnect;
4122 SpanningTreeUtilities* Utils;
4125 TimeSyncTimer *SyncTimer;
4127 ModuleSpanningTree(InspIRCd* Me)
4128 : Module::Module(Me), max_local(0), max_global(0)
4130 Utils = new SpanningTreeUtilities(Me, this);
4132 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4133 ServerInstance->AddCommand(command_rconnect);
4135 if (Utils->EnableTimeSync)
4137 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4138 ServerInstance->Timers->AddTimer(SyncTimer);
4144 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4146 std::string Parent = Utils->TreeRoot->GetName();
4147 if (Current->GetParent())
4149 Parent = Current->GetParent()->GetName();
4151 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4153 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4157 ShowLinks(Current->GetChild(q),user,hops+1);
4162 ShowLinks(Current->GetChild(q),user,hops+1);
4165 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4166 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4168 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());
4171 int CountLocalServs()
4173 return Utils->TreeRoot->ChildCount();
4178 return Utils->serverlist.size();
4181 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4183 ShowLinks(Utils->TreeRoot,user,0);
4184 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4188 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4190 unsigned int n_users = ServerInstance->UserCount();
4192 /* Only update these when someone wants to see them, more efficient */
4193 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4194 max_local = ServerInstance->LocalUserCount();
4195 if (n_users > max_global)
4196 max_global = n_users;
4198 unsigned int ulined_count = 0;
4199 unsigned int ulined_local_count = 0;
4201 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4202 * locally and globally (locally means directly connected to us)
4204 if ((Utils->HideULines) && (!*user->oper))
4206 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4208 if (ServerInstance->ULine(q->second->GetName().c_str()))
4211 if (q->second->GetParent() == Utils->TreeRoot)
4212 ulined_local_count++;
4217 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());
4218 if (ServerInstance->OperCount())
4219 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4220 if (ServerInstance->UnregisteredUserCount())
4221 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4222 if (ServerInstance->ChannelCount())
4223 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4224 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());
4225 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4226 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4230 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4232 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4236 for (int t = 0; t < depth; t++)
4238 matrix[line][t] = ' ';
4241 // For Aligning, we need to work out exactly how deep this thing is, and produce
4242 // a 'Spacer' String to compensate.
4245 memset(spacer,' ',40);
4246 if ((40 - Current->GetName().length() - depth) > 1) {
4247 spacer[40 - Current->GetName().length() - depth] = '\0';
4256 if (ServerInstance->clientlist.size() == 0) {
4257 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4262 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4264 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4265 totusers += Current->GetUserCount();
4267 strlcpy(&matrix[line][depth],text,80);
4269 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4271 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4275 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4280 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4286 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4290 /* Remote MOTD, the server is within the 1st parameter */
4291 std::deque<std::string> params;
4292 params.push_back(parameters[0]);
4294 /* Send it out remotely, generate no reply yet */
4295 TreeServer* s = Utils->FindServerMask(parameters[0]);
4298 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4302 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4309 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4313 /* Remote ADMIN, the server is within the 1st parameter */
4314 std::deque<std::string> params;
4315 params.push_back(parameters[0]);
4317 /* Send it out remotely, generate no reply yet */
4318 TreeServer* s = Utils->FindServerMask(parameters[0]);
4321 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4325 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4332 int HandleStats(const char** parameters, int pcnt, userrec* user)
4336 /* Remote STATS, the server is within the 2nd parameter */
4337 std::deque<std::string> params;
4338 params.push_back(parameters[0]);
4339 params.push_back(parameters[1]);
4340 /* Send it out remotely, generate no reply yet */
4341 TreeServer* s = Utils->FindServerMask(parameters[1]);
4344 params[1] = s->GetName();
4345 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4349 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4356 // Ok, prepare to be confused.
4357 // After much mulling over how to approach this, it struck me that
4358 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4359 // keeping track of a ton of ascii characters, and line by line
4360 // under recursion working out where to place them using multiplications
4361 // and divisons, we instead render the map onto a backplane of characters
4362 // (a character matrix), then draw the branches as a series of "L" shapes
4363 // from the nodes. This is not only friendlier on CPU it uses less stack.
4365 void HandleMap(const char** parameters, int pcnt, userrec* user)
4367 // This array represents a virtual screen which we will
4368 // "scratch" draw to, as the console device of an irc
4369 // client does not provide for a proper terminal.
4371 float totservers = 0;
4372 char matrix[128][80];
4373 for (unsigned int t = 0; t < 128; t++)
4375 matrix[t][0] = '\0';
4378 // The only recursive bit is called here.
4379 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4380 // Process each line one by one. The algorithm has a limit of
4381 // 128 servers (which is far more than a spanning tree should have
4382 // anyway, so we're ok). This limit can be raised simply by making
4383 // the character matrix deeper, 128 rows taking 10k of memory.
4384 for (int l = 1; l < line; l++)
4386 // scan across the line looking for the start of the
4387 // servername (the recursive part of the algorithm has placed
4388 // the servers at indented positions depending on what they
4390 int first_nonspace = 0;
4391 while (matrix[l][first_nonspace] == ' ')
4396 // Draw the `- (corner) section: this may be overwritten by
4397 // another L shape passing along the same vertical pane, becoming
4398 // a |- (branch) section instead.
4399 matrix[l][first_nonspace] = '-';
4400 matrix[l][first_nonspace-1] = '`';
4402 // Draw upwards until we hit the parent server, causing possibly
4403 // other corners (`-) to become branches (|-)
4404 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4406 matrix[l2][first_nonspace-1] = '|';
4410 // dump the whole lot to the user. This is the easy bit, honest.
4411 for (int t = 0; t < line; t++)
4413 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4415 float avg_users = totusers / totservers;
4416 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);
4417 user->WriteServ("007 %s :End of /MAP",user->nick);
4421 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4423 TreeServer* s = Utils->FindServerMask(parameters[0]);
4426 if (s == Utils->TreeRoot)
4428 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4431 TreeSocket* sock = s->GetSocket();
4434 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4435 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4436 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4437 ServerInstance->SE->DelFd(sock);
4443 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4448 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4453 int HandleTime(const char** parameters, int pcnt, userrec* user)
4455 if ((IS_LOCAL(user)) && (pcnt))
4457 TreeServer* found = Utils->FindServerMask(parameters[0]);
4460 // we dont' override for local server
4461 if (found == Utils->TreeRoot)
4464 std::deque<std::string> params;
4465 params.push_back(found->GetName());
4466 params.push_back(user->nick);
4467 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4471 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4477 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4479 if ((IS_LOCAL(user)) && (pcnt > 1))
4481 userrec* remote = ServerInstance->FindNick(parameters[1]);
4482 if ((remote) && (remote->GetFd() < 0))
4484 std::deque<std::string> params;
4485 params.push_back(parameters[1]);
4486 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4491 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4492 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4499 void DoPingChecks(time_t curtime)
4501 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4503 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4504 TreeSocket* sock = serv->GetSocket();
4507 if (curtime >= serv->NextPingTime())
4509 if (serv->AnsweredLastPing())
4511 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4512 serv->SetNextPingTime(curtime + 60);
4516 // they didnt answer, boot them
4517 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4518 sock->Squit(serv,"Ping timeout");
4519 ServerInstance->SE->DelFd(sock);
4529 void ConnectServer(Link* x)
4533 /* Do we already have an IP? If so, no need to resolve it. */
4534 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4536 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
4537 if (newsocket->GetFd() > -1)
4539 /* Handled automatically on success */
4543 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4545 Utils->DoFailOver(x);
4552 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4553 ServerInstance->AddResolver(snr);
4555 catch (ModuleException& e)
4557 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4558 Utils->DoFailOver(x);
4563 void AutoConnectServers(time_t curtime)
4565 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4567 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4569 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4570 x->NextConnectTime = curtime + x->AutoConnect;
4571 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4572 if (x->FailOver.length())
4574 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4577 /* The failover for this server is currently a member of the network.
4578 * The failover probably succeeded, where the main link did not.
4579 * Don't try the main link until the failover is gone again.
4586 // an autoconnected server is not connected. Check if its time to connect it
4587 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4588 this->ConnectServer(&(*x));
4594 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4596 // we've already checked if pcnt > 0, so this is safe
4597 TreeServer* found = Utils->FindServerMask(parameters[0]);
4600 std::string Version = found->GetVersion();
4601 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4602 if (found == Utils->TreeRoot)
4604 std::stringstream out(ServerInstance->Config->data005);
4605 std::string token = "";
4606 std::string line5 = "";
4607 int token_counter = 0;
4612 line5 = line5 + token + " ";
4615 if ((token_counter >= 13) || (out.eof() == true))
4617 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4626 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4631 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4633 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4635 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4637 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4640 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);
4641 ConnectServer(&(*x));
4646 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());
4651 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4655 void BroadcastTimeSync()
4657 std::deque<std::string> params;
4658 params.push_back(ConvToStr(ServerInstance->Time(true)));
4659 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4662 virtual int OnStats(char statschar, userrec* user, string_list &results)
4664 if ((statschar == 'c') || (statschar == 'n'))
4666 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4668 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');
4669 if (statschar == 'c')
4670 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4672 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4673 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);
4679 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4681 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4685 if (command == "CONNECT")
4687 return this->HandleConnect(parameters,pcnt,user);
4689 else if (command == "STATS")
4691 return this->HandleStats(parameters,pcnt,user);
4693 else if (command == "MOTD")
4695 return this->HandleMotd(parameters,pcnt,user);
4697 else if (command == "ADMIN")
4699 return this->HandleAdmin(parameters,pcnt,user);
4701 else if (command == "SQUIT")
4703 return this->HandleSquit(parameters,pcnt,user);
4705 else if (command == "MAP")
4707 this->HandleMap(parameters,pcnt,user);
4710 else if ((command == "TIME") && (pcnt > 0))
4712 return this->HandleTime(parameters,pcnt,user);
4714 else if (command == "LUSERS")
4716 this->HandleLusers(parameters,pcnt,user);
4719 else if (command == "LINKS")
4721 this->HandleLinks(parameters,pcnt,user);
4724 else if (command == "WHOIS")
4729 return this->HandleRemoteWhois(parameters,pcnt,user);
4732 else if ((command == "VERSION") && (pcnt > 0))
4734 this->HandleVersion(parameters,pcnt,user);
4741 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4743 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4745 // this bit of code cleverly routes all module commands
4746 // to all remote severs *automatically* so that modules
4747 // can just handle commands locally, without having
4748 // to have any special provision in place for remote
4749 // commands and linking protocols.
4750 std::deque<std::string> params;
4752 for (int j = 0; j < pcnt; j++)
4754 if (strchr(parameters[j],' '))
4756 params.push_back(":" + std::string(parameters[j]));
4760 params.push_back(std::string(parameters[j]));
4763 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4764 Utils->DoOneToMany(user->nick,command,params);
4768 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4770 TreeServer* s = Utils->FindServer(servername);
4773 description = s->GetDesc();
4777 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4779 if (IS_LOCAL(source))
4781 std::deque<std::string> params;
4782 params.push_back(dest->nick);
4783 params.push_back(channel->name);
4784 Utils->DoOneToMany(source->nick,"INVITE",params);
4788 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4790 std::deque<std::string> params;
4791 params.push_back(chan->name);
4792 params.push_back(":"+topic);
4793 Utils->DoOneToMany(user->nick,"TOPIC",params);
4796 virtual void OnWallops(userrec* user, const std::string &text)
4800 std::deque<std::string> params;
4801 params.push_back(":"+text);
4802 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4806 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4808 if (target_type == TYPE_USER)
4810 userrec* d = (userrec*)dest;
4811 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4813 std::deque<std::string> params;
4815 params.push_back(d->nick);
4816 params.push_back(":"+text);
4817 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4820 else if (target_type == TYPE_CHANNEL)
4824 chanrec *c = (chanrec*)dest;
4827 std::string cname = c->name;
4829 cname = status + cname;
4830 std::deque<TreeServer*> list;
4831 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4832 unsigned int ucount = list.size();
4833 for (unsigned int i = 0; i < ucount; i++)
4835 TreeSocket* Sock = list[i]->GetSocket();
4837 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4842 else if (target_type == TYPE_SERVER)
4846 char* target = (char*)dest;
4847 std::deque<std::string> par;
4848 par.push_back(target);
4849 par.push_back(":"+text);
4850 Utils->DoOneToMany(user->nick,"NOTICE",par);
4855 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4857 if (target_type == TYPE_USER)
4859 // route private messages which are targetted at clients only to the server
4860 // which needs to receive them
4861 userrec* d = (userrec*)dest;
4862 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4864 std::deque<std::string> params;
4866 params.push_back(d->nick);
4867 params.push_back(":"+text);
4868 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4871 else if (target_type == TYPE_CHANNEL)
4875 chanrec *c = (chanrec*)dest;
4878 std::string cname = c->name;
4880 cname = status + cname;
4881 std::deque<TreeServer*> list;
4882 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4883 unsigned int ucount = list.size();
4884 for (unsigned int i = 0; i < ucount; i++)
4886 TreeSocket* Sock = list[i]->GetSocket();
4888 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4893 else if (target_type == TYPE_SERVER)
4897 char* target = (char*)dest;
4898 std::deque<std::string> par;
4899 par.push_back(target);
4900 par.push_back(":"+text);
4901 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4906 virtual void OnBackgroundTimer(time_t curtime)
4908 AutoConnectServers(curtime);
4909 DoPingChecks(curtime);
4912 virtual void OnUserJoin(userrec* user, chanrec* channel)
4914 // Only do this for local users
4917 std::deque<std::string> params;
4919 params.push_back(channel->name);
4920 // set up their permissions and the channel TS with FJOIN.
4921 // All users are FJOINed now, because a module may specify
4922 // new joining permissions for the user.
4924 params.push_back(channel->name);
4925 params.push_back(ConvToStr(channel->age));
4926 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4927 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4928 if (channel->GetUserCounter() == 1)
4930 /* First user in, sync the modes for the channel */
4932 /* This is safe, all inspircd servers default to +nt */
4933 params.push_back("+nt");
4934 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
4939 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4941 // only occurs for local clients
4942 if (user->registered != REG_ALL)
4944 std::deque<std::string> params;
4945 params.push_back(newhost);
4946 Utils->DoOneToMany(user->nick,"FHOST",params);
4949 virtual void OnChangeName(userrec* user, const std::string &gecos)
4951 // only occurs for local clients
4952 if (user->registered != REG_ALL)
4954 std::deque<std::string> params;
4955 params.push_back(gecos);
4956 Utils->DoOneToMany(user->nick,"FNAME",params);
4959 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4963 std::deque<std::string> params;
4964 params.push_back(channel->name);
4965 if (partmessage != "")
4966 params.push_back(":"+partmessage);
4967 Utils->DoOneToMany(user->nick,"PART",params);
4971 virtual void OnUserConnect(userrec* user)
4973 char agestr[MAXBUF];
4976 std::deque<std::string> params;
4977 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4978 params.push_back(agestr);
4979 params.push_back(user->nick);
4980 params.push_back(user->host);
4981 params.push_back(user->dhost);
4982 params.push_back(user->ident);
4983 params.push_back("+"+std::string(user->FormatModes()));
4984 params.push_back(user->GetIPString());
4985 params.push_back(":"+std::string(user->fullname));
4986 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4988 // User is Local, change needs to be reflected!
4989 TreeServer* SourceServer = Utils->FindServer(user->server);
4992 SourceServer->AddUserCount();
4998 virtual void OnUserQuit(userrec* user, const std::string &reason)
5000 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5002 std::deque<std::string> params;
5003 params.push_back(":"+reason);
5004 Utils->DoOneToMany(user->nick,"QUIT",params);
5006 // Regardless, We need to modify the user Counts..
5007 TreeServer* SourceServer = Utils->FindServer(user->server);
5010 SourceServer->DelUserCount();
5015 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
5019 std::deque<std::string> params;
5020 params.push_back(user->nick);
5021 Utils->DoOneToMany(oldnick,"NICK",params);
5025 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
5027 if ((source) && (IS_LOCAL(source)))
5029 std::deque<std::string> params;
5030 params.push_back(chan->name);
5031 params.push_back(user->nick);
5032 params.push_back(":"+reason);
5033 Utils->DoOneToMany(source->nick,"KICK",params);
5037 std::deque<std::string> params;
5038 params.push_back(chan->name);
5039 params.push_back(user->nick);
5040 params.push_back(":"+reason);
5041 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
5045 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
5047 std::deque<std::string> params;
5048 params.push_back(dest->nick);
5049 params.push_back(":"+reason);
5050 Utils->DoOneToMany(source->nick,"KILL",params);
5053 virtual void OnRehash(const std::string ¶meter)
5055 if (parameter != "")
5057 std::deque<std::string> params;
5058 params.push_back(parameter);
5059 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
5061 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5063 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
5064 ServerInstance->RehashServer();
5067 Utils->ReadConfiguration(false);
5070 // note: the protocol does not allow direct umode +o except
5071 // via NICK with 8 params. sending OPERTYPE infers +o modechange
5073 virtual void OnOper(userrec* user, const std::string &opertype)
5077 std::deque<std::string> params;
5078 params.push_back(opertype);
5079 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5083 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5087 /* Server-set lines */
5089 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5090 (unsigned long)duration, reason.c_str());
5091 std::deque<std::string> params;
5092 params.push_back(data);
5093 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5097 if (IS_LOCAL(source))
5100 snprintf(type,8,"%cLINE",linetype);
5101 std::string stype = type;
5104 char sduration[MAXBUF];
5105 snprintf(sduration,MAXBUF,"%ld",duration);
5106 std::deque<std::string> params;
5107 params.push_back(host);
5108 params.push_back(sduration);
5109 params.push_back(":"+reason);
5110 Utils->DoOneToMany(source->nick,stype,params);
5114 std::deque<std::string> params;
5115 params.push_back(host);
5116 Utils->DoOneToMany(source->nick,stype,params);
5122 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5124 OnLine(source,hostmask,true,'G',duration,reason);
5127 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5129 OnLine(source,ipmask,true,'Z',duration,reason);
5132 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5134 OnLine(source,nickmask,true,'Q',duration,reason);
5137 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5139 OnLine(source,hostmask,true,'E',duration,reason);
5142 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5144 OnLine(source,hostmask,false,'G',0,"");
5147 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5149 OnLine(source,ipmask,false,'Z',0,"");
5152 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5154 OnLine(source,nickmask,false,'Q',0,"");
5157 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5159 OnLine(source,hostmask,false,'E',0,"");
5162 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5164 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5166 if (target_type == TYPE_USER)
5168 userrec* u = (userrec*)dest;
5169 std::deque<std::string> params;
5170 params.push_back(u->nick);
5171 params.push_back(text);
5172 Utils->DoOneToMany(user->nick,"MODE",params);
5176 chanrec* c = (chanrec*)dest;
5177 std::deque<std::string> params;
5178 params.push_back(c->name);
5179 params.push_back(text);
5180 Utils->DoOneToMany(user->nick,"MODE",params);
5185 virtual void OnSetAway(userrec* user)
5189 std::deque<std::string> params;
5190 params.push_back(":"+std::string(user->awaymsg));
5191 Utils->DoOneToMany(user->nick,"AWAY",params);
5195 virtual void OnCancelAway(userrec* user)
5199 std::deque<std::string> params;
5201 Utils->DoOneToMany(user->nick,"AWAY",params);
5205 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5207 TreeSocket* s = (TreeSocket*)opaque;
5210 if (target_type == TYPE_USER)
5212 userrec* u = (userrec*)target;
5213 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5217 chanrec* c = (chanrec*)target;
5218 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5223 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5225 TreeSocket* s = (TreeSocket*)opaque;
5228 if (target_type == TYPE_USER)
5230 userrec* u = (userrec*)target;
5231 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5233 else if (target_type == TYPE_OTHER)
5235 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5237 else if (target_type == TYPE_CHANNEL)
5239 chanrec* c = (chanrec*)target;
5240 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5245 virtual void OnEvent(Event* event)
5247 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5249 if (event->GetEventID() == "send_metadata")
5251 if (params->size() < 3)
5253 (*params)[2] = ":" + (*params)[2];
5254 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5256 else if (event->GetEventID() == "send_topic")
5258 if (params->size() < 2)
5260 (*params)[1] = ":" + (*params)[1];
5261 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5262 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5263 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5265 else if (event->GetEventID() == "send_mode")
5267 if (params->size() < 2)
5269 // Insert the TS value of the object, either userrec or chanrec
5271 userrec* a = ServerInstance->FindNick((*params)[0]);
5278 chanrec* a = ServerInstance->FindChan((*params)[0]);
5284 params->insert(params->begin() + 1,ConvToStr(ourTS));
5285 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5287 else if (event->GetEventID() == "send_mode_explicit")
5289 if (params->size() < 2)
5291 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5293 else if (event->GetEventID() == "send_opers")
5295 if (params->size() < 1)
5297 (*params)[0] = ":" + (*params)[0];
5298 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5300 else if (event->GetEventID() == "send_modeset")
5302 if (params->size() < 2)
5304 (*params)[1] = ":" + (*params)[1];
5305 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5307 else if (event->GetEventID() == "send_snoset")
5309 if (params->size() < 2)
5311 (*params)[1] = ":" + (*params)[1];
5312 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5314 else if (event->GetEventID() == "send_push")
5316 if (params->size() < 2)
5319 userrec *a = ServerInstance->FindNick((*params)[0]);
5324 (*params)[1] = ":" + (*params)[1];
5325 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5329 virtual ~ModuleSpanningTree()
5331 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5332 /* This will also free the listeners */
5335 ServerInstance->Timers->DelTimer(SyncTimer);
5338 virtual Version GetVersion()
5340 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5343 void Implements(char* List)
5345 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5346 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5347 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5348 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5349 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5350 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5351 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5354 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5355 * so that any activity it sees is FINAL, e.g. we arent going to send out
5356 * a NICK message before m_cloaking has finished putting the +x on the user,
5358 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5359 * the module call queue.
5361 Priority Prioritize()
5363 return PRIORITY_LAST;
5367 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5371 void TimeSyncTimer::Tick(time_t TIME)
5373 Module->BroadcastTimeSync();
5374 Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5375 Instance->Timers->AddTimer(Module->SyncTimer);
5378 void SpanningTreeUtilities::DoFailOver(Link* x)
5380 if (x->FailOver.length())
5382 if (x->FailOver == x->Name)
5384 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());
5387 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5390 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5391 Creator->ConnectServer(TryThisOne);
5395 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5400 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5402 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5404 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5412 class ModuleSpanningTreeFactory : public ModuleFactory
5415 ModuleSpanningTreeFactory()
5419 ~ModuleSpanningTreeFactory()
5423 virtual Module * CreateModule(InspIRCd* Me)
5425 return new ModuleSpanningTree(Me);
5431 extern "C" void * init_module( void )
5433 return new ModuleSpanningTreeFactory;