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 */
21 #include "configreader.h"
25 #include "commands/cmd_whois.h"
26 #include "commands/cmd_stats.h"
31 #include "cull_list.h"
34 #define nspace __gnu_cxx
37 /** If you make a change which breaks the protocol, increment this.
38 * If you completely change the protocol, completely change the number.
40 const long ProtocolVersion = 1100;
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.
63 using irc::sockets::MatchCIDR;
65 class ModuleSpanningTree;
66 static ModuleSpanningTree* TreeProtocolModule;
67 static InspIRCd* ServerInstance;
69 /* Any socket can have one of five states at any one time.
70 * The LISTENER state indicates a socket which is listening
71 * for connections. It cannot receive data itself, only incoming
73 * The CONNECTING state indicates an outbound socket which is
74 * waiting to be writeable.
75 * The WAIT_AUTH_1 state indicates the socket is outbound and
76 * has successfully connected, but has not yet sent and received
78 * The WAIT_AUTH_2 state indicates that the socket is inbound
79 * (allocated by a LISTENER) but has not yet sent and received
81 * The CONNECTED state represents a fully authorized, fully
84 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
86 /* Foward declarations */
90 /* This variable represents the root of the server tree
91 * (for all intents and purposes, it's us)
95 /* This hash_map holds the hash equivalent of the server
96 * tree, used for rapid linear lookups.
98 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
99 server_hash serverlist;
101 typedef nspace::hash_map<std::string, userrec*> uid_hash;
102 typedef nspace::hash_map<std::string, char*> sid_hash;
104 /* More forward declarations */
105 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
106 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
107 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit);
108 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
109 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms);
110 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms);
111 void ReadConfiguration(bool rebind);
113 /* Flatten links and /MAP for non-opers */
115 /* Hide U-Lined servers in /MAP and /LINKS */
118 std::vector<std::string> ValidIPs;
120 class UserManager : public classbase
131 std::string UserToUID(userrec* user)
136 std::string UIDToUser(const std::string &UID)
141 std::string CreateAndAdd(userrec* user)
146 std::string CreateAndAdd(const std::string &servername)
151 std::string ServerToSID(const std::string &servername)
156 std::string SIDToServer(const std::string &SID)
161 userrec* FindByID(const std::string &UID)
168 /* Each server in the tree is represented by one class of
169 * type TreeServer. A locally connected TreeServer can
170 * have a class of type TreeSocket associated with it, for
171 * remote servers, the TreeSocket entry will be NULL.
172 * Each server also maintains a pointer to its parent
173 * (NULL if this server is ours, at the top of the tree)
174 * and a pointer to its "Route" (see the comments in the
175 * constructors below), and also a dynamic list of pointers
176 * to its children which can be iterated recursively
177 * if required. Creating or deleting objects of type
178 i* TreeServer automatically maintains the hash_map of
179 * TreeServer items, deleting and inserting them as they
180 * are created and destroyed.
183 class TreeServer : public classbase
185 InspIRCd* ServerInstance; /* Creator */
186 TreeServer* Parent; /* Parent entry */
187 TreeServer* Route; /* Route entry */
188 std::vector<TreeServer*> Children; /* List of child objects */
189 irc::string ServerName; /* Server's name */
190 std::string ServerDesc; /* Server's description */
191 std::string VersionString; /* Version string or empty string */
192 int UserCount; /* Not used in this version */
193 int OperCount; /* Not used in this version */
194 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
195 time_t NextPing; /* After this time, the server should be PINGed*/
196 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
200 /* We don't use this constructor. Its a dummy, and won't cause any insertion
201 * of the TreeServer into the hash_map. See below for the two we DO use.
203 TreeServer(InspIRCd* Instance) : ServerInstance(Instance)
209 UserCount = OperCount = 0;
210 VersionString = ServerInstance->GetVersionString();
213 /* We use this constructor only to create the 'root' item, TreeRoot, which
214 * represents our own server. Therefore, it has no route, no parent, and
215 * no socket associated with it. Its version string is our own local version.
217 TreeServer(InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc)
221 UserCount = OperCount = 0;
222 VersionString = ServerInstance->GetVersionString();
224 Socket = NULL; /* Fix by brain */
228 /* When we create a new server, we call this constructor to initialize it.
229 * This constructor initializes the server's Route and Parent, and sets up
230 * its ping counters so that it will be pinged one minute from now.
232 TreeServer(InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
233 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
236 UserCount = OperCount = 0;
237 this->SetNextPingTime(time(NULL) + 60);
240 /* find the 'route' for this server (e.g. the one directly connected
241 * to the local server, which we can use to reach it)
243 * In the following example, consider we have just added a TreeServer
244 * class for server G on our network, of which we are server A.
245 * To route traffic to G (marked with a *) we must send the data to
246 * B (marked with a +) so this algorithm initializes the 'Route'
247 * value to point at whichever server traffic must be routed through
248 * to get here. If we were to try this algorithm with server B,
249 * the Route pointer would point at its own object ('this').
259 * We only run this algorithm when a server is created, as
260 * the routes remain constant while ever the server exists, and
261 * do not need to be re-calculated.
265 if (Route == TreeRoot)
271 while (this->Route->GetParent() != TreeRoot)
273 this->Route = Route->GetParent();
277 /* Because recursive code is slow and takes a lot of resources,
278 * we store two representations of the server tree. The first
279 * is a recursive structure where each server references its
280 * children and its parent, which is used for netbursts and
281 * netsplits to dump the whole dataset to the other server,
282 * and the second is used for very fast lookups when routing
283 * messages and is instead a hash_map, where each item can
284 * be referenced by its server name. The AddHashEntry()
285 * call below automatically inserts each TreeServer class
286 * into the hash_map as it is created. There is a similar
287 * maintainance call in the destructor to tidy up deleted
291 this->AddHashEntry();
294 int QuitUsers(const std::string &reason)
296 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
297 const char* reason_s = reason.c_str();
298 std::vector<userrec*> time_to_die;
299 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
301 if (!strcmp(n->second->server, this->ServerName.c_str()))
303 time_to_die.push_back(n->second);
306 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
308 userrec* a = (userrec*)*n;
309 ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
311 userrec::QuitUser(ServerInstance,a,reason_s);
313 return time_to_die.size();
316 /* This method is used to add the structure to the
317 * hash_map for linear searches. It is only called
318 * by the constructors.
322 server_hash::iterator iter;
323 iter = serverlist.find(this->ServerName.c_str());
324 if (iter == serverlist.end())
325 serverlist[this->ServerName.c_str()] = this;
328 /* This method removes the reference to this object
329 * from the hash_map which is used for linear searches.
330 * It is only called by the default destructor.
334 server_hash::iterator iter;
335 iter = serverlist.find(this->ServerName.c_str());
336 if (iter != serverlist.end())
337 serverlist.erase(iter);
340 /* These accessors etc should be pretty self-
344 TreeServer* GetRoute()
349 std::string GetName()
351 return ServerName.c_str();
354 std::string GetDesc()
359 std::string GetVersion()
361 return VersionString;
364 void SetNextPingTime(time_t t)
367 LastPingWasGood = false;
370 time_t NextPingTime()
375 bool AnsweredLastPing()
377 return LastPingWasGood;
382 LastPingWasGood = true;
405 TreeSocket* GetSocket()
410 TreeServer* GetParent()
415 void SetVersion(std::string Version)
417 VersionString = Version;
420 unsigned int ChildCount()
422 return Children.size();
425 TreeServer* GetChild(unsigned int n)
427 if (n < Children.size())
429 /* Make sure they cant request
430 * an out-of-range object. After
431 * all we know what these programmer
432 * types are like *grin*.
442 void AddChild(TreeServer* Child)
444 Children.push_back(Child);
447 bool DelChild(TreeServer* Child)
449 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
460 /* Removes child nodes of this node, and of that node, etc etc.
461 * This is used during netsplits to automatically tidy up the
462 * server tree. It is slow, we don't use it for much else.
466 bool stillchildren = true;
467 while (stillchildren)
469 stillchildren = false;
470 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
472 TreeServer* s = (TreeServer*)*a;
476 stillchildren = true;
485 /* We'd better tidy up after ourselves, eh? */
486 this->DelHashEntry();
490 /* The Link class might as well be a struct,
491 * but this is C++ and we don't believe in structs (!).
492 * It holds the entire information of one <link>
493 * tag from the main config file. We maintain a list
494 * of them, and populate the list on rehash/load.
497 class Link : public classbase
503 std::string SendPass;
504 std::string RecvPass;
505 unsigned long AutoConnect;
506 time_t NextConnectTime;
507 std::string EncryptionKey;
508 bool HiddenFromStats;
509 irc::string FailOver;
512 void DoFailOver(Link* x);
513 Link* FindLink(const std::string& name);
515 /* The usual stuff for inspircd modules,
516 * plus the vector of Link classes which we
517 * use to store the <link> tags from the config
521 std::vector<Link> LinkBlocks;
523 /* Yay for fast searches!
524 * This is hundreds of times faster than recursion
525 * or even scanning a linked list, especially when
526 * there are more than a few servers to deal with.
529 TreeServer* FindServer(std::string ServerName)
531 server_hash::iterator iter;
532 iter = serverlist.find(ServerName.c_str());
533 if (iter != serverlist.end())
543 /* Returns the locally connected server we must route a
544 * message through to reach server 'ServerName'. This
545 * only applies to one-to-one and not one-to-many routing.
546 * See the comments for the constructor of TreeServer
549 TreeServer* BestRouteTo(std::string ServerName)
551 if (ServerName.c_str() == TreeRoot->GetName())
553 TreeServer* Found = FindServer(ServerName);
556 return Found->GetRoute();
564 /* Find the first server matching a given glob mask.
565 * Theres no find-using-glob method of hash_map [awwww :-(]
566 * so instead, we iterate over the list using an iterator
567 * and match each one until we get a hit. Yes its slow,
570 TreeServer* FindServerMask(std::string ServerName)
572 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
574 if (match(i->first.c_str(),ServerName.c_str()))
580 /* A convenient wrapper that returns true if a server exists */
581 bool IsServer(std::string ServerName)
583 return (FindServer(ServerName) != NULL);
587 class cmd_rconnect : public command_t
591 cmd_rconnect (InspIRCd* Instance, Module* Callback) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback)
593 this->source = "m_spanningtree.so";
594 syntax = "<remote-server-mask> <servermask>";
597 void Handle (const char** parameters, int pcnt, userrec *user)
599 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
600 /* Is this aimed at our server? */
601 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
603 /* Yes, initiate the given connect */
604 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
606 para[0] = parameters[1];
607 Creator->OnPreCommand("CONNECT", para, 1, user, true);
614 /* Every SERVER connection inbound or outbound is represented by
615 * an object of type TreeSocket.
616 * TreeSockets, being inherited from InspSocket, can be tied into
617 * the core socket engine, and we cn therefore receive activity events
618 * for them, just like activex objects on speed. (yes really, that
619 * is a technical term!) Each of these which relates to a locally
620 * connected server is assocated with it, by hooking it onto a
621 * TreeSocket class using its constructor. In this way, we can
622 * maintain a list of servers, some of which are directly connected,
623 * some of which are not.
626 class TreeSocket : public InspSocket
629 std::string in_buffer;
630 ServerState LinkState;
631 std::string InboundServerName;
632 std::string InboundDescription;
634 int num_lost_servers;
636 bool LastPingWasGood;
640 unsigned int keylength;
641 std::string ModuleList;
642 std::map<std::string,std::string> CapKeys;
646 /* Because most of the I/O gubbins are encapsulated within
647 * InspSocket, we just call the superclass constructor for
648 * most of the action, and append a few of our own values
651 TreeSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
652 : InspSocket(SI, host, port, listening, maxtime)
655 this->LinkState = LISTENER;
657 this->ctx_out = NULL;
660 TreeSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
661 : InspSocket(SI, host, port, listening, maxtime)
664 this->LinkState = CONNECTING;
666 this->ctx_out = NULL;
669 /* When a listening socket gives us a new file descriptor,
670 * we must associate it with a socket without creating a new
671 * connection. This constructor is used for this purpose.
673 TreeSocket(InspIRCd* SI, int newfd, char* ip)
674 : InspSocket(SI, newfd, ip)
676 this->LinkState = WAIT_AUTH_1;
678 this->ctx_out = NULL;
679 this->SendCapabilities();
690 void InitAES(std::string key,std::string SName)
697 ServerInstance->Log(DEBUG,"Initialized AES key %s",key.c_str());
698 // key must be 16, 24, 32 etc bytes (multiple of 8)
699 keylength = key.length();
700 if (!(keylength == 16 || keylength == 24 || keylength == 32))
702 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
703 ServerInstance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
707 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
708 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\
709 \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);
710 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\
711 \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);
715 /* When an outbound connection finishes connecting, we receive
716 * this event, and must send our SERVER string to the other
717 * side. If the other side is happy, as outlined in the server
718 * to server docs on the inspircd.org site, the other side
719 * will then send back its own server string.
721 virtual bool OnConnected()
723 if (this->LinkState == CONNECTING)
725 /* we do not need to change state here. */
726 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
728 if (x->Name == this->myhost)
730 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
731 this->SendCapabilities();
732 if (x->EncryptionKey != "")
734 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
736 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.");
740 this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
741 this->InitAES(x->EncryptionKey,x->Name.c_str());
744 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
745 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
750 /* There is a (remote) chance that between the /CONNECT and the connection
751 * being accepted, some muppet has removed the <link> block and rehashed.
752 * If that happens the connection hangs here until it's closed. Unlikely
753 * and rather harmless.
755 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
759 virtual void OnError(InspSocketError e)
761 /* We don't handle this method, because all our
762 * dirty work is done in OnClose() (see below)
763 * which is still called on error conditions too.
765 if (e == I_ERR_CONNECT)
767 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
768 Link* MyLink = FindLink(myhost);
774 virtual int OnDisconnect()
776 /* For the same reason as above, we don't
777 * handle OnDisconnect()
782 /* Recursively send the server tree with distances as hops.
783 * This is used during network burst to inform the other server
784 * (and any of ITS servers too) of what servers we know about.
785 * If at any point any of these servers already exist on the other
786 * end, our connection may be terminated. The hopcounts given
787 * by this function are relative, this doesn't matter so long as
788 * they are all >1, as all the remote servers re-calculate them
789 * to be relative too, with themselves as hop 0.
791 void SendServers(TreeServer* Current, TreeServer* s, int hops)
794 for (unsigned int q = 0; q < Current->ChildCount(); q++)
796 TreeServer* recursive_server = Current->GetChild(q);
797 if (recursive_server != s)
799 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
800 this->WriteLine(command);
801 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
802 /* down to next level */
803 this->SendServers(recursive_server, s, hops+1);
808 std::string MyCapabilities()
810 std::vector<std::string> modlist;
811 std::string capabilities = "";
813 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
815 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
816 modlist.push_back(this->Instance->Config->module_names[i]);
818 sort(modlist.begin(),modlist.end());
819 for (unsigned int i = 0; i < modlist.size(); i++)
822 capabilities = capabilities + ",";
823 capabilities = capabilities + modlist[i];
828 void SendCapabilities()
830 irc::commasepstream modulelist(MyCapabilities());
832 this->WriteLine("CAPAB START");
834 /* Send module names, split at 509 length */
835 std::string item = "*";
836 std::string line = "CAPAB MODULES ";
837 while ((item = modulelist.GetToken()) != "")
839 if (line.length() + item.length() + 1 > 509)
841 this->WriteLine(line);
842 line = "CAPAB MODULES ";
845 if (line != "CAPAB MODULES ")
850 if (line != "CAPAB MODULES ")
851 this->WriteLine(line);
858 #ifdef SUPPORT_IP6LINKS
861 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));
863 this->WriteLine("CAPAB END");
866 /* Check a comma seperated list for an item */
867 bool HasItem(const std::string &list, const std::string &item)
869 irc::commasepstream seplist(list);
871 std::string item2 = "*";
872 while ((item2 = seplist.GetToken()) != "")
881 /* Isolate and return the elements that are different between two comma seperated lists */
882 std::string ListDifference(const std::string &one, const std::string &two)
884 irc::commasepstream list_one(one);
885 std::string item = "*";
886 std::string result = "";
887 while ((item = list_one.GetToken()) != "")
889 if (!HasItem(two, item))
898 bool Capab(std::deque<std::string> params)
900 if (params.size() < 1)
902 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
906 if (params[0] == "START")
908 this->ModuleList = "";
909 this->CapKeys.clear();
911 else if (params[0] == "END")
913 std::string reason = "";
915 #ifdef SUPPORT_IP6LINKS
918 /* Compare ModuleList and check CapKeys...
919 * Maybe this could be tidier? -- Brain
921 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
923 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
926 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
930 diff = "this server:" + diff;
932 if (diff.length() == 12)
933 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
935 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
938 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
939 reason = "We don't both support linking to IPV6 servers";
941 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
942 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
944 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
945 reason = "Maximum nickname lengths differ or remote nickname length not specified";
947 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
949 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
951 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
955 reason = "Protocol version not specified";
959 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))))
960 reason = "We don't both have halfop support enabled/disabled identically";
962 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
963 reason = "Maximum ident lengths differ or remote ident length not specified";
965 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
966 reason = "Maximum channel lengths differ or remote channel length not specified";
968 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
969 reason = "Maximum modes per line differ or remote modes per line not specified";
971 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
972 reason = "Maximum quit lengths differ or remote quit length not specified";
974 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
975 reason = "Maximum topic lengths differ or remote topic length not specified";
977 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
978 reason = "Maximum kick lengths differ or remote kick length not specified";
980 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
981 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
983 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
984 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
988 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
992 else if ((params[0] == "MODULES") && (params.size() == 2))
994 if (!this->ModuleList.length())
996 this->ModuleList.append(params[1]);
1000 this->ModuleList.append(",");
1001 this->ModuleList.append(params[1]);
1004 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
1006 irc::tokenstream capabs(params[1]);
1007 std::string item = "*";
1008 while ((item = capabs.GetToken()) != "")
1010 /* Process each key/value pair */
1011 std::string::size_type equals = item.rfind('=');
1012 if (equals != std::string::npos)
1014 std::string var = item.substr(0, equals);
1015 std::string value = item.substr(equals+1, item.length());
1016 this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
1017 CapKeys[var] = value;
1025 /* This function forces this server to quit, removing this server
1026 * and any users on it (and servers and users below that, etc etc).
1027 * It's very slow and pretty clunky, but luckily unless your network
1028 * is having a REAL bad hair day, this function shouldnt be called
1029 * too many times a month ;-)
1031 void SquitServer(std::string &from, TreeServer* Current)
1033 /* recursively squit the servers attached to 'Current'.
1034 * We're going backwards so we don't remove users
1035 * while we still need them ;)
1037 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1039 TreeServer* recursive_server = Current->GetChild(q);
1040 this->SquitServer(from,recursive_server);
1042 /* Now we've whacked the kids, whack self */
1044 num_lost_users += Current->QuitUsers(from);
1047 /* This is a wrapper function for SquitServer above, which
1048 * does some validation first and passes on the SQUIT to all
1049 * other remaining servers.
1051 void Squit(TreeServer* Current,std::string reason)
1053 if ((Current) && (Current != TreeRoot))
1055 std::deque<std::string> params;
1056 params.push_back(Current->GetName());
1057 params.push_back(":"+reason);
1058 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1059 if (Current->GetParent() == TreeRoot)
1061 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1065 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1067 num_lost_servers = 0;
1069 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1070 SquitServer(from, Current);
1072 Current->GetParent()->DelChild(Current);
1074 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1078 ServerInstance->Log(DEFAULT,"Squit from unknown server");
1082 /* FMODE command - server mode with timestamp checks */
1083 bool ForceMode(std::string source, std::deque<std::string> ¶ms)
1085 /* Chances are this is a 1.0 FMODE without TS */
1086 if (params.size() < 3)
1088 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
1093 std::string sourceserv;
1095 /* Are we dealing with an FMODE from a user, or from a server? */
1096 userrec* who = this->Instance->FindNick(source);
1099 /* FMODE from a user, set sourceserv to the users server name */
1100 sourceserv = who->server;
1104 /* FMODE from a server, create a fake user to receive mode feedback */
1105 who = new userrec(this->Instance);
1106 who->SetFd(FD_MAGIC_NUMBER);
1107 smode = true; /* Setting this flag tells us we should free the userrec later */
1108 sourceserv = source; /* Set sourceserv to the actual source string */
1110 const char* modelist[64];
1113 memset(&modelist,0,sizeof(modelist));
1114 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1118 /* The timestamp is in this position.
1119 * We don't want to pass that up to the
1120 * server->client protocol!
1122 TS = atoi(params[q].c_str());
1126 /* Everything else is fine to append to the modelist */
1127 modelist[n++] = params[q].c_str();
1131 /* Extract the TS value of the object, either userrec or chanrec */
1132 userrec* dst = this->Instance->FindNick(params[0]);
1133 chanrec* chan = NULL;
1141 chan = this->Instance->FindChan(params[0]);
1148 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1153 ServerInstance->Log(DEBUG,"Entering TS equality check");
1154 ModeHandler* mh = NULL;
1155 unsigned long paramptr = 3;
1156 std::string to_bounce = "";
1157 std::string to_keep = "";
1158 std::vector<std::string> params_to_keep;
1159 std::string params_to_bounce = "";
1161 char cur_change = 1;
1162 char old_change = 0;
1163 char old_bounce_change = 0;
1164 /* Merge modes, basically do special stuff to mode with params */
1165 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1178 /* We only care about whats being set,
1179 * not whats being unset
1181 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1183 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1185 /* We only want to do special things to
1186 * modes with parameters, we are going to rewrite
1190 adding ? cur_change = '+' : cur_change = '-';
1192 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1194 /* The mode is set here, check which we should keep */
1197 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1199 if (which_to_keep == true)
1201 /* Keep ours, bounce theirs:
1202 * Send back ours to them and
1203 * drop their mode changs
1205 adding ? cur_change = '+' : cur_change = '-';
1206 if (cur_change != old_bounce_change)
1207 to_bounce += cur_change;
1209 old_bounce_change = cur_change;
1211 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1212 params_to_bounce.append(" ").append(ret.second);
1216 /* Keep theirs: Accept their mode change,
1219 adding ? cur_change = '+' : cur_change = '-';
1220 if (cur_change != old_change)
1221 to_keep += cur_change;
1223 old_change = cur_change;
1225 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1226 params_to_keep.push_back(params[paramptr]);
1231 /* Mode isnt set here, we want it */
1232 adding ? cur_change = '+' : cur_change = '-';
1233 if (cur_change != old_change)
1234 to_keep += cur_change;
1236 old_change = cur_change;
1238 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1239 params_to_keep.push_back(params[paramptr]);
1246 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1250 adding ? cur_change = '+' : cur_change = '-';
1252 /* Just keep this, safe to merge with no checks
1253 * it has no parameters
1256 if (cur_change != old_change)
1257 to_keep += cur_change;
1259 old_change = cur_change;
1261 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1263 ServerInstance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1264 params_to_keep.push_back(params[paramptr++]);
1271 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1275 /* Taking a mode away */
1276 adding ? cur_change = '+' : cur_change = '-';
1278 if (cur_change != old_change)
1279 to_keep += cur_change;
1281 old_change = cur_change;
1283 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1284 params_to_keep.push_back(params[paramptr++]);
1291 if (to_bounce.length())
1293 std::deque<std::string> newparams;
1294 newparams.push_back(params[0]);
1295 newparams.push_back(ConvToStr(ourTS));
1296 newparams.push_back(to_bounce+params_to_bounce);
1297 DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1300 if (to_keep.length())
1304 modelist[0] = params[0].c_str();
1305 modelist[1] = to_keep.c_str();
1307 if (params_to_keep.size() > 2)
1309 for (q = 2; (q < params_to_keep.size()) && (q < 64); q++)
1311 ServerInstance->Log(DEBUG,"Item %d of %d", q, params_to_keep.size());
1312 modelist[n++] = params_to_keep[q].c_str();
1318 ServerInstance->Log(DEBUG,"Send mode");
1319 this->Instance->SendMode(modelist, n+2, who);
1323 ServerInstance->Log(DEBUG,"Send mode client");
1324 this->Instance->CallCommandHandler("MODE", modelist, n+2, who);
1327 /* HOT POTATO! PASS IT ON! */
1328 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1332 /* U-lined servers always win regardless of their TS */
1333 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1335 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1336 * SHOULD accept it, if its clock is right.
1338 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1339 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1340 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1342 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1343 * writing the code. It took me a while to come up with this solution.
1345 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1348 std::deque<std::string> newparams; /* New parameter list we send back */
1349 newparams.push_back(params[0]); /* Target, user or channel */
1350 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1351 newparams.push_back(""); /* This contains the mode string. For now
1352 * it's empty, we fill it below.
1355 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1356 * set to avoid a desync here.
1358 std::string modebounce = "";
1361 ModeHandler* mh = NULL;
1362 char cur_change = 1;
1363 char old_change = 0;
1364 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1366 /* Iterate over all mode chars in the sent set */
1369 /* Adding or subtracting modes? */
1377 /* Find the mode handler for this mode */
1378 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1380 /* Got a mode handler?
1381 * This also prevents us bouncing modes we have no handler for.
1388 /* Does the mode require a parameter right now?
1389 * If it does, fetch it if we can
1391 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1394 /* Call the ModeSet method to determine if its set with the
1395 * given parameter here or not.
1397 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1399 /* XXX: Really. Dont ask.
1400 * Determine from if its set combined with what the current
1401 * 'state' is (adding or not) as to wether we should 'invert'
1402 * or 'reinforce' the mode change
1404 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1406 /* Quickly determine if we have 'flipped' from + to -,
1407 * or - to +, to prevent unneccessary +/- chars in the
1408 * output string that waste bandwidth
1410 if (cur_change != old_change)
1411 modebounce += cur_change;
1412 old_change = cur_change;
1414 /* Add the mode character to the output string */
1415 modebounce += mh->GetModeChar();
1417 /* We got a parameter back from ModeHandler::ModeSet,
1418 * are we supposed to be sending one out right now?
1420 if (ret.second.length())
1422 if (mh->GetNumParams(cur_change == '+') > 0)
1423 /* Yes we're supposed to be sending out
1424 * the parameter. Make sure it goes
1426 newparams.push_back(ret.second);
1434 /* Update the parameters for FMODE with the new 'bounced' string */
1435 newparams[2] = modebounce;
1436 /* Only send it back the way it came, no need to send it anywhere else */
1437 DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1438 ServerInstance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1442 ServerInstance->Log(DEBUG,"Allow modes, TS lower for sender");
1443 /* The server was ulined, but something iffy is up with the TS.
1444 * Sound the alarm bells!
1446 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1448 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());
1450 /* Allow the mode, route it to either server or user command handling */
1452 this->Instance->SendMode(modelist,n,who);
1454 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1456 /* HOT POTATO! PASS IT ON! */
1457 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1459 /* Are we supposed to free the userrec? */
1466 /* FTOPIC command */
1467 bool ForceTopic(std::string source, std::deque<std::string> ¶ms)
1469 if (params.size() != 4)
1471 time_t ts = atoi(params[1].c_str());
1472 std::string nsource = source;
1474 chanrec* c = this->Instance->FindChan(params[0]);
1477 if ((ts >= c->topicset) || (!*c->topic))
1479 std::string oldtopic = c->topic;
1480 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1481 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1483 /* if the topic text is the same as the current topic,
1484 * dont bother to send the TOPIC command out, just silently
1485 * update the set time and set nick.
1487 if (oldtopic != params[3])
1489 userrec* user = this->Instance->FindNick(source);
1492 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1496 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1497 nsource = user->server;
1499 /* all done, send it on its way */
1500 params[3] = ":" + params[3];
1501 DoOneToAllButSender(source,"FTOPIC",params,nsource);
1510 /* FJOIN, similar to unreal SJOIN */
1511 bool ForceJoin(std::string source, std::deque<std::string> ¶ms)
1513 if (params.size() < 3)
1517 char modestring[MAXBUF];
1518 char* mode_users[127];
1519 memset(&mode_users,0,sizeof(mode_users));
1520 mode_users[0] = first;
1521 mode_users[1] = modestring;
1522 strcpy(modestring,"+");
1523 unsigned int modectr = 2;
1525 userrec* who = NULL;
1526 std::string channel = params[0];
1527 time_t TS = atoi(params[1].c_str());
1530 chanrec* chan = this->Instance->FindChan(channel);
1535 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1537 /* default is a high value, which if we dont have this
1538 * channel will let the other side apply their modes.
1540 time_t ourTS = time(NULL)+600;
1541 chanrec* us = this->Instance->FindChan(channel);
1547 ServerInstance->Log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1549 irc::tokenstream users(params[2]);
1550 std::string item = "*";
1552 /* do this first, so our mode reversals are correctly received by other servers
1553 * if there is a TS collision.
1555 params[2] = ":" + params[2];
1556 DoOneToAllButSender(source,"FJOIN",params,source);
1559 item = users.GetToken();
1560 /* process one user at a time, applying modes. */
1561 char* usr = (char*)item.c_str();
1562 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1563 * (is this even possible?) */
1566 char* permissions = usr;
1568 while ((*permissions) && (*permissions != ','))
1570 ModeHandler* mh = ServerInstance->Modes->FindPrefix(*permissions);
1574 charlcat(modestring,mh->GetModeChar(),MAXBUF);
1578 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",mh->GetPrefix());
1579 this->WriteLine(std::string("ERROR :Invalid prefix '")+mh->GetModeChar()+"' in FJOIN");
1587 /* Did they get any modes? How many times? */
1588 for (int k = 0; k < ntimes; k++)
1589 mode_users[modectr++] = strdup(usr); // XXX
1591 who = this->Instance->FindNick(usr);
1594 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, key);
1595 if (modectr >= (MAXMODES-1))
1597 /* theres a mode for this user. push them onto the mode queue, and flush it
1598 * if there are more than MAXMODES to go.
1600 if ((ourTS >= TS) || (this->Instance->ULine(who->server)))
1602 /* We also always let u-lined clients win, no matter what the TS value */
1603 ServerInstance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1604 this->Instance->SendMode((const char**)mode_users,modectr,who);
1607 ServerInstance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1614 ServerInstance->Log(DEBUG,"Their channel newer than ours, bouncing their modes");
1615 /* bouncy bouncy! */
1616 std::deque<std::string> params;
1617 /* modes are now being UNSET... */
1618 *mode_users[1] = '-';
1619 for (unsigned int x = 0; x < modectr; x++)
1623 params.push_back(ConvToStr(us->age));
1625 params.push_back(mode_users[x]);
1628 // tell everyone to bounce the modes. bad modes, bad!
1629 DoOneToMany(this->Instance->Config->ServerName,"FMODE",params);
1631 strcpy(mode_users[1],"+");
1632 for (unsigned int f = 2; f < modectr; f++)
1633 free(mode_users[f]);
1639 for (unsigned int f = 2; f < modectr; f++)
1640 free(mode_users[f]);
1642 this->WriteLine("ERROR :Invalid user '"+std::string(usr)+"' in FJOIN to '"+channel+"'");
1647 /* there werent enough modes built up to flush it during FJOIN,
1648 * or, there are a number left over. flush them out.
1650 if ((modectr > 2) && (who) && (us))
1654 ServerInstance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1655 this->Instance->SendMode((const char**)mode_users,modectr,who);
1658 ServerInstance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1665 ServerInstance->Log(DEBUG,"Their channel newer than ours, bouncing their modes");
1666 std::deque<std::string> params;
1667 *mode_users[1] = '-';
1668 for (unsigned int x = 0; x < modectr; x++)
1672 params.push_back(ConvToStr(us->age));
1674 params.push_back(mode_users[x]);
1676 DoOneToMany(this->Instance->Config->ServerName,"FMODE",params);
1679 for (unsigned int f = 2; f < modectr; f++)
1680 free(mode_users[f]);
1685 bool SyncChannelTS(std::string source, std::deque<std::string> ¶ms)
1687 if (params.size() >= 2)
1689 chanrec* c = this->Instance->FindChan(params[0]);
1692 time_t theirTS = atoi(params[1].c_str());
1693 time_t ourTS = c->age;
1694 if (ourTS >= theirTS)
1696 ServerInstance->Log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1701 DoOneToAllButSender(this->Instance->Config->ServerName,"SYNCTS",params,source);
1706 bool IntroduceClient(std::string source, std::deque<std::string> ¶ms)
1708 if (params.size() < 8)
1710 if (params.size() > 8)
1712 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1715 // NICK age nick host dhost ident +modes ip :gecos
1717 time_t age = atoi(params[0].c_str());
1719 /* This used to have a pretty craq'y loop doing the same thing,
1720 * now we just let the STL do the hard work (more efficiently)
1722 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1723 if (pos_after_plus != std::string::npos)
1724 params[5] = params[5].substr(pos_after_plus);
1726 const char* tempnick = params[1].c_str();
1727 ServerInstance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1729 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1731 if (iter != this->Instance->clientlist.end())
1734 ServerInstance->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);
1735 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1739 userrec* _new = new userrec(this->Instance);
1740 this->Instance->clientlist[tempnick] = _new;
1741 _new->SetFd(FD_MAGIC_NUMBER);
1742 strlcpy(_new->nick, tempnick,NICKMAX-1);
1743 strlcpy(_new->host, params[2].c_str(),63);
1744 strlcpy(_new->dhost, params[3].c_str(),63);
1745 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1746 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1747 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1748 _new->registered = REG_ALL;
1751 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1752 _new->modes[(*v)-65] = 1;
1754 #ifdef SUPPORT_IP6LINKS
1755 if (params[6].find_first_of(":") != std::string::npos)
1756 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1759 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1761 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1763 params[7] = ":" + params[7];
1764 DoOneToAllButSender(source,"NICK",params,source);
1766 // Increment the Source Servers User Count..
1767 TreeServer* SourceServer = FindServer(source);
1770 ServerInstance->Log(DEBUG,"Found source server of %s",_new->nick);
1771 SourceServer->AddUserCount();
1777 /* Send one or more FJOINs for a channel of users.
1778 * If the length of a single line is more than 480-NICKMAX
1779 * in length, it is split over multiple lines.
1781 void SendFJoins(TreeServer* Current, chanrec* c)
1783 ServerInstance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1785 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1787 size_t dlen, curlen;
1788 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1790 char* ptr = list + dlen;
1792 CUList *ulist = c->GetUsers();
1793 std::vector<userrec*> specific_halfop;
1794 std::vector<userrec*> specific_voice;
1795 std::string modes = "";
1796 std::string params = "";
1798 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1800 // The first parameter gets a : before it
1801 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1808 if (curlen > (480-NICKMAX))
1810 this->WriteLine(list);
1811 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1819 this->WriteLine(list);
1821 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1824 params.append(b->data).append(" ");
1826 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+c->ChanModes(true)+modes+" "+params);
1829 /* Send G, Q, Z and E lines */
1830 void SendXLines(TreeServer* Current)
1833 std::string n = this->Instance->Config->ServerName;
1834 const char* sn = n.c_str();
1836 /* Yes, these arent too nice looking, but they get the job done */
1837 for (std::vector<ZLine>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1839 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1840 this->WriteLine(data);
1842 for (std::vector<QLine>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1844 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1845 this->WriteLine(data);
1847 for (std::vector<GLine>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1849 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1850 this->WriteLine(data);
1852 for (std::vector<ELine>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1854 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1855 this->WriteLine(data);
1857 for (std::vector<ZLine>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
1859 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1860 this->WriteLine(data);
1862 for (std::vector<QLine>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
1864 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1865 this->WriteLine(data);
1867 for (std::vector<GLine>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
1869 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1870 this->WriteLine(data);
1872 for (std::vector<ELine>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
1874 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1875 this->WriteLine(data);
1879 /* Send channel modes and topics */
1880 void SendChannelModes(TreeServer* Current)
1883 std::deque<std::string> list;
1885 std::string n = this->Instance->Config->ServerName;
1886 const char* sn = n.c_str();
1887 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
1889 SendFJoins(Current, c->second);
1890 if (*c->second->topic)
1892 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1893 this->WriteLine(data);
1895 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1897 c->second->GetExtList(list);
1898 for (unsigned int j = 0; j < list.size(); j++)
1900 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1905 /* send all users and their oper state/modes */
1906 void SendUsers(TreeServer* Current)
1909 std::deque<std::string> list;
1911 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
1913 if (u->second->registered == REG_ALL)
1915 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);
1916 this->WriteLine(data);
1917 if (*u->second->oper)
1919 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1921 if (*u->second->awaymsg)
1923 this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1925 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1927 u->second->GetExtList(list);
1928 for (unsigned int j = 0; j < list.size(); j++)
1930 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1936 /* This function is called when we want to send a netburst to a local
1937 * server. There is a set order we must do this, because for example
1938 * users require their servers to exist, and channels require their
1939 * users to exist. You get the idea.
1941 void DoBurst(TreeServer* s)
1943 std::string burst = "BURST "+ConvToStr(time(NULL));
1944 std::string endburst = "ENDBURST";
1945 // Because by the end of the netburst, it could be gone!
1946 std::string name = s->GetName();
1947 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1948 this->WriteLine(burst);
1949 /* send our version string */
1950 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1951 /* Send server tree */
1952 this->SendServers(TreeRoot,s,1);
1953 /* Send users and their oper status */
1955 /* Send everything else (channel modes, xlines etc) */
1956 this->SendChannelModes(s);
1957 this->SendXLines(s);
1958 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1959 this->WriteLine(endburst);
1960 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1963 /* This function is called when we receive data from a remote
1964 * server. We buffer the data in a std::string (it doesnt stay
1965 * there for long), reading using InspSocket::Read() which can
1966 * read up to 16 kilobytes in one operation.
1968 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1969 * THE SOCKET OBJECT FOR US.
1971 virtual bool OnDataReady()
1973 char* data = this->Read();
1974 /* Check that the data read is a valid pointer and it has some content */
1977 this->in_buffer.append(data);
1978 /* While there is at least one new line in the buffer,
1979 * do something useful (we hope!) with it.
1981 while (in_buffer.find("\n") != std::string::npos)
1983 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1984 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1985 if (ret.find("\r") != std::string::npos)
1986 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1987 /* Process this one, abort if it
1988 * didnt return true.
1994 memset(result,0,1024);
1996 ServerInstance->Log(DEBUG,"Original string '%s'",ret.c_str());
1997 /* ERROR + CAPAB is still allowed unencryped */
1998 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2000 int nbytes = from64tobits(out, ret.c_str(), 1024);
2001 if ((nbytes > 0) && (nbytes < 1024))
2003 ServerInstance->Log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
2004 ctx_in->Decrypt(out, result, nbytes, 0);
2005 for (int t = 0; t < nbytes; t++)
2006 if (result[t] == '\7') result[t] = 0;
2011 if (!this->ProcessLine(ret))
2013 ServerInstance->Log(DEBUG,"ProcessLine says no!");
2019 /* EAGAIN returns an empty but non-NULL string, so this
2020 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2022 return (data && !*data);
2025 int WriteLine(std::string line)
2027 ServerInstance->Log(DEBUG,"OUT: %s",line.c_str());
2031 char result64[10240];
2032 if (this->keylength)
2034 // pad it to the key length
2035 int n = this->keylength - (line.length() % this->keylength);
2038 ServerInstance->Log(DEBUG,"Append %d chars to line to make it %d long from %d, key length %d",n,n+line.length(),line.length(),this->keylength);
2039 line.append(n,'\7');
2042 unsigned int ll = line.length();
2043 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2044 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2046 //int from64tobits(char *out, const char *in, int maxlen);
2048 return this->Write(line + "\r\n");
2051 /* Handle ERROR command */
2052 bool Error(std::deque<std::string> ¶ms)
2054 if (params.size() < 1)
2056 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2057 /* we will return false to cause the socket to close. */
2061 /* remote MOTD. leet, huh? */
2062 bool Motd(std::string prefix, std::deque<std::string> ¶ms)
2064 if (params.size() > 0)
2066 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2068 /* It's for our server */
2069 string_list results;
2070 userrec* source = this->Instance->FindNick(prefix);
2074 std::deque<std::string> par;
2075 par.push_back(prefix);
2078 if (!ServerInstance->Config->MOTD.size())
2080 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2081 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2085 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 375 "+source->nick+" :"+ServerInstance->Config->ServerName+" message of the day";
2086 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2088 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
2090 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 372 "+source->nick+" :- "+ServerInstance->Config->MOTD[i];
2091 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2094 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2095 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2101 userrec* source = this->Instance->FindNick(prefix);
2103 DoOneToOne(prefix, "MOTD", params, params[0]);
2109 /* remote ADMIN. leet, huh? */
2110 bool Admin(std::string prefix, std::deque<std::string> ¶ms)
2112 if (params.size() > 0)
2114 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2116 /* It's for our server */
2117 string_list results;
2118 userrec* source = this->Instance->FindNick(prefix);
2122 std::deque<std::string> par;
2123 par.push_back(prefix);
2126 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+ServerInstance->Config->ServerName;
2127 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2129 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 257 "+source->nick+" :Name - "+ServerInstance->Config->AdminName;
2130 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2132 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+ServerInstance->Config->AdminNick;
2133 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2135 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+ServerInstance->Config->AdminEmail;
2136 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2142 userrec* source = this->Instance->FindNick(prefix);
2144 DoOneToOne(prefix, "ADMIN", params, params[0]);
2150 bool Stats(std::string prefix, std::deque<std::string> ¶ms)
2152 /* Get the reply to a STATS query if it matches this servername,
2153 * and send it back as a load of PUSH queries
2155 if (params.size() > 1)
2157 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2159 /* It's for our server */
2160 string_list results;
2161 userrec* source = this->Instance->FindNick(prefix);
2164 std::deque<std::string> par;
2165 par.push_back(prefix);
2167 DoStats(this->Instance, *(params[0].c_str()), source, results);
2168 for (size_t i = 0; i < results.size(); i++)
2170 par[1] = "::" + results[i];
2171 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2178 userrec* source = this->Instance->FindNick(prefix);
2180 DoOneToOne(prefix, "STATS", params, params[1]);
2187 /* Because the core won't let users or even SERVERS set +o,
2188 * we use the OPERTYPE command to do this.
2190 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
2192 if (params.size() != 1)
2194 ServerInstance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2197 std::string opertype = params[0];
2198 userrec* u = this->Instance->FindNick(prefix);
2201 u->modes[UM_OPERATOR] = 1;
2202 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2203 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2208 /* Because Andy insists that services-compatible servers must
2209 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2211 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
2213 if (params.size() < 3)
2216 userrec* u = this->Instance->FindNick(params[0]);
2220 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2223 std::deque<std::string> par;
2224 par.push_back(params[1]);
2225 /* This is not required as one is sent in OnUserPostNick below
2227 //DoOneToMany(u->nick,"NICK",par);
2228 if (!u->ForceNickChange(params[1].c_str()))
2230 userrec::QuitUser(this->Instance, u, "Nickname collision");
2233 u->age = atoi(params[2].c_str());
2239 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
2241 if (params.size() < 2)
2244 userrec* u = this->Instance->FindNick(params[0]);
2248 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2249 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2254 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
2256 if (params.size() < 1)
2259 std::string servermask = params[0];
2261 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2263 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2264 this->Instance->RehashServer();
2265 ReadConfiguration(false);
2267 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2271 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
2273 if (params.size() != 2)
2276 std::string nick = params[0];
2277 userrec* u = this->Instance->FindNick(prefix);
2278 userrec* who = this->Instance->FindNick(nick);
2282 /* Prepend kill source, if we don't have one */
2283 std::string sourceserv = prefix;
2286 sourceserv = u->server;
2288 if (*(params[1].c_str()) != '[')
2290 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2292 std::string reason = params[1];
2293 params[1] = ":" + params[1];
2294 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2295 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2296 userrec::QuitUser(this->Instance,who,reason);
2301 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
2303 if (params.size() < 1)
2306 if (params.size() == 1)
2308 TreeServer* ServerSource = FindServer(prefix);
2311 ServerSource->SetPingFlag();
2316 std::string forwardto = params[1];
2317 if (forwardto == this->Instance->Config->ServerName)
2320 * this is a PONG for us
2321 * if the prefix is a user, check theyre local, and if they are,
2322 * dump the PONG reply back to their fd. If its a server, do nowt.
2323 * Services might want to send these s->s, but we dont need to yet.
2325 userrec* u = this->Instance->FindNick(prefix);
2329 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2334 // not for us, pass it on :)
2335 DoOneToOne(prefix,"PONG",params,forwardto);
2342 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
2344 if (params.size() < 3)
2347 TreeServer* ServerSource = FindServer(prefix);
2351 if (params[0] == "*")
2353 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2355 else if (*(params[0].c_str()) == '#')
2357 chanrec* c = this->Instance->FindChan(params[0]);
2360 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2363 else if (*(params[0].c_str()) != '#')
2365 userrec* u = this->Instance->FindNick(params[0]);
2368 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2373 params[2] = ":" + params[2];
2374 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2378 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
2380 if (params.size() < 1)
2383 TreeServer* ServerSource = FindServer(prefix);
2387 ServerSource->SetVersion(params[0]);
2389 params[0] = ":" + params[0];
2390 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2394 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
2396 if (params.size() < 1)
2399 userrec* u = this->Instance->FindNick(prefix);
2403 u->ChangeDisplayedHost(params[0].c_str());
2404 DoOneToAllButSender(prefix,"FHOST",params,u->server);
2409 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
2411 if (params.size() < 6)
2414 bool propogate = false;
2416 switch (*(params[0].c_str()))
2419 propogate = ServerInstance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2420 ServerInstance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2423 propogate = ServerInstance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2424 ServerInstance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2427 propogate = ServerInstance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2428 ServerInstance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2431 propogate = ServerInstance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2432 ServerInstance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2435 propogate = ServerInstance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2438 /* Just in case... */
2439 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2444 /* Send it on its way */
2447 if (atoi(params[4].c_str()))
2449 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());
2453 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());
2455 params[5] = ":" + params[5];
2456 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2458 if (!this->bursting)
2460 ServerInstance->Log(DEBUG,"Applying lines...");
2461 ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2466 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
2468 if (params.size() < 1)
2471 userrec* u = this->Instance->FindNick(prefix);
2475 u->ChangeName(params[0].c_str());
2476 params[0] = ":" + params[0];
2477 DoOneToAllButSender(prefix,"FNAME",params,u->server);
2482 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
2484 if (params.size() < 1)
2487 ServerInstance->Log(DEBUG,"In IDLE command");
2488 userrec* u = this->Instance->FindNick(prefix);
2492 ServerInstance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2493 // an incoming request
2494 if (params.size() == 1)
2496 userrec* x = this->Instance->FindNick(params[0]);
2497 if ((x) && (IS_LOCAL(x)))
2499 userrec* x = this->Instance->FindNick(params[0]);
2500 ServerInstance->Log(DEBUG,"Got IDLE");
2501 char signon[MAXBUF];
2503 ServerInstance->Log(DEBUG,"Sending back IDLE 3");
2504 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2505 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2506 std::deque<std::string> par;
2507 par.push_back(prefix);
2508 par.push_back(signon);
2509 par.push_back(idle);
2510 // ours, we're done, pass it BACK
2511 DoOneToOne(params[0],"IDLE",par,u->server);
2515 // not ours pass it on
2516 DoOneToOne(prefix,"IDLE",params,x->server);
2519 else if (params.size() == 3)
2521 std::string who_did_the_whois = params[0];
2522 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2523 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2525 ServerInstance->Log(DEBUG,"Got final IDLE");
2526 // an incoming reply to a whois we sent out
2527 std::string nick_whoised = prefix;
2528 unsigned long signon = atoi(params[1].c_str());
2529 unsigned long idle = atoi(params[2].c_str());
2530 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2531 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2535 // not ours, pass it on
2536 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2543 bool Push(std::string prefix, std::deque<std::string> ¶ms)
2545 if (params.size() < 2)
2548 userrec* u = this->Instance->FindNick(params[0]);
2555 u->Write(params[1]);
2559 // continue the raw onwards
2560 params[1] = ":" + params[1];
2561 DoOneToOne(prefix,"PUSH",params,u->server);
2566 bool Time(std::string prefix, std::deque<std::string> ¶ms)
2568 // :source.server TIME remote.server sendernick
2569 // :remote.server TIME source.server sendernick TS
2570 if (params.size() == 2)
2572 // someone querying our time?
2573 if (this->Instance->Config->ServerName == params[0])
2575 userrec* u = this->Instance->FindNick(params[1]);
2579 snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2580 params.push_back(curtime);
2582 DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2587 // not us, pass it on
2588 userrec* u = this->Instance->FindNick(params[1]);
2590 DoOneToOne(prefix,"TIME",params,params[0]);
2593 else if (params.size() == 3)
2595 // a response to a previous TIME
2596 userrec* u = this->Instance->FindNick(params[1]);
2597 if ((u) && (IS_LOCAL(u)))
2599 time_t rawtime = atol(params[2].c_str());
2600 struct tm * timeinfo;
2601 timeinfo = localtime(&rawtime);
2603 snprintf(tms,26,"%s",asctime(timeinfo));
2605 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2610 DoOneToOne(prefix,"TIME",params,u->server);
2616 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
2618 if (params.size() < 1)
2621 if (params.size() == 1)
2623 std::string stufftobounce = params[0];
2624 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2629 std::string forwardto = params[1];
2630 if (forwardto == this->Instance->Config->ServerName)
2632 // this is a ping for us, send back PONG to the requesting server
2633 params[1] = params[0];
2634 params[0] = forwardto;
2635 DoOneToOne(forwardto,"PONG",params,params[1]);
2639 // not for us, pass it on :)
2640 DoOneToOne(prefix,"PING",params,forwardto);
2646 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
2648 if (params.size() < 4)
2651 std::string servername = params[0];
2652 std::string password = params[1];
2653 // hopcount is not used for a remote server, we calculate this ourselves
2654 std::string description = params[3];
2655 TreeServer* ParentOfThis = FindServer(prefix);
2659 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2662 TreeServer* CheckDupe = FindServer(servername);
2665 this->WriteLine("ERROR :Server "+servername+" already exists!");
2666 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2669 TreeServer* Node = new TreeServer(this->Instance,servername,description,ParentOfThis,NULL);
2670 ParentOfThis->AddChild(Node);
2671 params[3] = ":" + params[3];
2672 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2673 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2677 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2679 if (params.size() < 4)
2682 irc::string servername = params[0].c_str();
2683 std::string sname = params[0];
2684 std::string password = params[1];
2685 int hops = atoi(params[2].c_str());
2689 this->WriteLine("ERROR :Server too far away for authentication");
2690 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2693 std::string description = params[3];
2694 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2696 if ((x->Name == servername) && (x->RecvPass == password))
2698 TreeServer* CheckDupe = FindServer(sname);
2701 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2702 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2705 // Begin the sync here. this kickstarts the
2706 // other side, waiting in WAIT_AUTH_2 state,
2707 // into starting their burst, as it shows
2708 // that we're happy.
2709 this->LinkState = CONNECTED;
2710 // we should add the details of this server now
2711 // to the servers tree, as a child of the root
2713 TreeServer* Node = new TreeServer(this->Instance,sname,description,TreeRoot,this);
2714 TreeRoot->AddChild(Node);
2715 params[3] = ":" + params[3];
2716 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2717 this->bursting = true;
2718 this->DoBurst(Node);
2722 this->WriteLine("ERROR :Invalid credentials");
2723 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2727 bool Inbound_Server(std::deque<std::string> ¶ms)
2729 if (params.size() < 4)
2732 irc::string servername = params[0].c_str();
2733 std::string sname = params[0];
2734 std::string password = params[1];
2735 int hops = atoi(params[2].c_str());
2739 this->WriteLine("ERROR :Server too far away for authentication");
2740 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2743 std::string description = params[3];
2744 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2746 if ((x->Name == servername) && (x->RecvPass == password))
2748 TreeServer* CheckDupe = FindServer(sname);
2751 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2752 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2755 /* If the config says this link is encrypted, but the remote side
2756 * hasnt bothered to send the AES command before SERVER, then we
2757 * boot them off as we MUST have this connection encrypted.
2759 if ((x->EncryptionKey != "") && (!this->ctx_in))
2761 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2762 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2765 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2766 this->InboundServerName = sname;
2767 this->InboundDescription = description;
2768 // this is good. Send our details: Our server name and description and hopcount of 0,
2769 // along with the sendpass from this block.
2770 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2771 // move to the next state, we are now waiting for THEM.
2772 this->LinkState = WAIT_AUTH_2;
2776 this->WriteLine("ERROR :Invalid credentials");
2777 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2781 void Split(std::string line, std::deque<std::string> &n)
2784 irc::tokenstream tokens(line);
2786 while ((param = tokens.GetToken()) != "")
2791 bool ProcessLine(std::string line)
2793 std::deque<std::string> params;
2794 irc::string command;
2800 line = line.substr(0, line.find_first_of("\r\n"));
2802 ServerInstance->Log(DEBUG,"IN: %s", line.c_str());
2804 this->Split(line.c_str(),params);
2806 if ((params[0][0] == ':') && (params.size() > 1))
2808 prefix = params[0].substr(1);
2812 command = params[0].c_str();
2815 if ((!this->ctx_in) && (command == "AES"))
2817 std::string sserv = params[0];
2818 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2820 if ((x->EncryptionKey != "") && (x->Name == sserv))
2822 this->InitAES(x->EncryptionKey,sserv);
2828 else if ((this->ctx_in) && (command == "AES"))
2830 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());
2833 switch (this->LinkState)
2838 // Waiting for SERVER command from remote server. Server initiating
2839 // the connection sends the first SERVER command, listening server
2840 // replies with theirs if its happy, then if the initiator is happy,
2841 // it starts to send its net sync, which starts the merge, otherwise
2842 // it sends an ERROR.
2843 if (command == "PASS")
2845 /* Silently ignored */
2847 else if (command == "SERVER")
2849 return this->Inbound_Server(params);
2851 else if (command == "ERROR")
2853 return this->Error(params);
2855 else if (command == "USER")
2857 this->WriteLine("ERROR :Client connections to this port are prohibited.");
2860 else if (command == "CAPAB")
2862 return this->Capab(params);
2864 else if ((command == "U") || (command == "S"))
2866 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2871 this->WriteLine("ERROR :Invalid command in negotiation phase.");
2876 // Waiting for start of other side's netmerge to say they liked our
2878 if (command == "SERVER")
2880 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2884 else if ((command == "U") || (command == "S"))
2886 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2889 else if (command == "BURST")
2893 /* If a time stamp is provided, try and check syncronization */
2894 time_t THEM = atoi(params[0].c_str());
2895 long delta = THEM-time(NULL);
2896 if ((delta < -600) || (delta > 600))
2898 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));
2899 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2902 else if ((delta < -60) || (delta > 60))
2904 this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2907 this->LinkState = CONNECTED;
2908 Node = new TreeServer(this->Instance,InboundServerName,InboundDescription,TreeRoot,this);
2909 TreeRoot->AddChild(Node);
2911 params.push_back(InboundServerName);
2912 params.push_back("*");
2913 params.push_back("1");
2914 params.push_back(":"+InboundDescription);
2915 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2916 this->bursting = true;
2917 this->DoBurst(Node);
2919 else if (command == "ERROR")
2921 return this->Error(params);
2923 else if (command == "CAPAB")
2925 return this->Capab(params);
2930 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2934 if (command == "SERVER")
2936 // another server we connected to, which was in WAIT_AUTH_1 state,
2937 // has just sent us their credentials. If we get this far, theyre
2938 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2939 // if we're happy with this, we should send our netburst which
2940 // kickstarts the merge.
2941 return this->Outbound_Reply_Server(params);
2943 else if (command == "ERROR")
2945 return this->Error(params);
2949 // This is the 'authenticated' state, when all passwords
2950 // have been exchanged and anything past this point is taken
2955 std::string direction = prefix;
2956 userrec* t = this->Instance->FindNick(prefix);
2959 direction = t->server;
2961 TreeServer* route_back_again = BestRouteTo(direction);
2962 if ((!route_back_again) || (route_back_again->GetSocket() != this))
2964 if (route_back_again)
2965 ServerInstance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2970 * When there is activity on the socket, reset the ping counter so
2971 * that we're not wasting bandwidth pinging an active server.
2973 route_back_again->SetNextPingTime(time(NULL) + 60);
2974 route_back_again->SetPingFlag();
2977 if (command == "SVSMODE")
2979 /* Services expects us to implement
2980 * SVSMODE. In inspircd its the same as
2985 std::string target = "";
2986 /* Yes, know, this is a mess. Its reasonably fast though as we're
2987 * working with std::string here.
2989 if ((command == "NICK") && (params.size() > 1))
2991 return this->IntroduceClient(prefix,params);
2993 else if (command == "FJOIN")
2995 return this->ForceJoin(prefix,params);
2997 else if (command == "STATS")
2999 return this->Stats(prefix, params);
3001 else if (command == "MOTD")
3003 return this->Motd(prefix, params);
3005 else if (command == "ADMIN")
3007 return this->Admin(prefix, params);
3009 else if (command == "SERVER")
3011 return this->RemoteServer(prefix,params);
3013 else if (command == "ERROR")
3015 return this->Error(params);
3017 else if (command == "OPERTYPE")
3019 return this->OperType(prefix,params);
3021 else if (command == "FMODE")
3023 return this->ForceMode(prefix,params);
3025 else if (command == "KILL")
3027 return this->RemoteKill(prefix,params);
3029 else if (command == "FTOPIC")
3031 return this->ForceTopic(prefix,params);
3033 else if (command == "REHASH")
3035 return this->RemoteRehash(prefix,params);
3037 else if (command == "METADATA")
3039 return this->MetaData(prefix,params);
3041 else if (command == "PING")
3044 * We just got a ping from a server that's bursting.
3045 * This can't be right, so set them to not bursting, and
3046 * apply their lines.
3050 this->bursting = false;
3051 ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3055 prefix = this->GetName();
3057 return this->LocalPing(prefix,params);
3059 else if (command == "PONG")
3062 * We just got a pong from a server that's bursting.
3063 * This can't be right, so set them to not bursting, and
3064 * apply their lines.
3068 this->bursting = false;
3069 ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3073 prefix = this->GetName();
3075 return this->LocalPong(prefix,params);
3077 else if (command == "VERSION")
3079 return this->ServerVersion(prefix,params);
3081 else if (command == "FHOST")
3083 return this->ChangeHost(prefix,params);
3085 else if (command == "FNAME")
3087 return this->ChangeName(prefix,params);
3089 else if (command == "ADDLINE")
3091 return this->AddLine(prefix,params);
3093 else if (command == "SVSNICK")
3097 prefix = this->GetName();
3099 return this->ForceNick(prefix,params);
3101 else if (command == "IDLE")
3103 return this->Whois(prefix,params);
3105 else if (command == "PUSH")
3107 return this->Push(prefix,params);
3109 else if (command == "TIME")
3111 return this->Time(prefix,params);
3113 else if ((command == "KICK") && (IsServer(prefix)))
3115 std::string sourceserv = this->myhost;
3116 if (params.size() == 3)
3118 userrec* user = this->Instance->FindNick(params[1]);
3119 chanrec* chan = this->Instance->FindChan(params[0]);
3122 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3123 /* Yikes, the channels gone! */
3127 if (this->InboundServerName != "")
3129 sourceserv = this->InboundServerName;
3131 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3133 else if (command == "SVSJOIN")
3137 prefix = this->GetName();
3139 return this->ServiceJoin(prefix,params);
3141 else if (command == "SQUIT")
3143 if (params.size() == 2)
3145 this->Squit(FindServer(params[0]),params[1]);
3149 else if (command == "ENDBURST")
3151 this->bursting = false;
3152 ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3153 std::string sourceserv = this->myhost;
3154 if (this->InboundServerName != "")
3156 sourceserv = this->InboundServerName;
3158 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3163 // not a special inter-server command.
3164 // Emulate the actual user doing the command,
3165 // this saves us having a huge ugly parser.
3166 userrec* who = this->Instance->FindNick(prefix);
3167 std::string sourceserv = this->myhost;
3168 if (this->InboundServerName != "")
3170 sourceserv = this->InboundServerName;
3174 if ((command == "NICK") && (params.size() > 0))
3176 /* On nick messages, check that the nick doesnt
3177 * already exist here. If it does, kill their copy,
3180 userrec* x = this->Instance->FindNick(params[0]);
3181 if ((x) && (x != who))
3183 std::deque<std::string> p;
3184 p.push_back(params[0]);
3185 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3186 DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3188 p.push_back(prefix);
3189 p.push_back("Nickname collision");
3190 DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3191 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3192 userrec* y = this->Instance->FindNick(prefix);
3195 userrec::QuitUser(this->Instance,y,"Nickname collision");
3197 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3201 target = who->server;
3202 const char* strparams[127];
3203 for (unsigned int q = 0; q < params.size(); q++)
3205 strparams[q] = params[q].c_str();
3207 if (!this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3209 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3215 // its not a user. Its either a server, or somethings screwed up.
3216 if (IsServer(prefix))
3218 target = this->Instance->Config->ServerName;
3222 ServerInstance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3226 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3235 virtual std::string GetName()
3237 std::string sourceserv = this->myhost;
3238 if (this->InboundServerName != "")
3240 sourceserv = this->InboundServerName;
3245 virtual void OnTimeout()
3247 if (this->LinkState == CONNECTING)
3249 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3250 Link* MyLink = FindLink(myhost);
3256 virtual void OnClose()
3258 // Connection closed.
3259 // If the connection is fully up (state CONNECTED)
3260 // then propogate a netsplit to all peers.
3261 std::string quitserver = this->myhost;
3262 if (this->InboundServerName != "")
3264 quitserver = this->InboundServerName;
3266 TreeServer* s = FindServer(quitserver);
3269 Squit(s,"Remote host closed the connection");
3271 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3274 virtual int OnIncomingConnection(int newsock, char* ip)
3276 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3277 * or discovering if this port is the server port, we don't allow connections from any
3278 * IPs for which we don't have a link block.
3282 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3285 for (vector<std::string>::iterator i = ValidIPs.begin(); i != ValidIPs.end(); i++)
3286 if (MatchCIDR(ip, (*i).c_str()))
3291 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3296 TreeSocket* s = new TreeSocket(this->Instance, newsock, ip);
3297 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3302 /** This class is used to resolve server hostnames during /connect and autoconnect.
3303 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3304 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3305 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3306 * will have an IP address which we can then use to continue our connection.
3308 class ServernameResolver : public Resolver
3311 /** A copy of the Link tag info for what we're connecting to.
3312 * We take a copy, rather than using a pointer, just in case the
3313 * admin takes the tag away and rehashes while the domain is resolving.
3317 ServernameResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
3319 /* Nothing in here, folks */
3322 void OnLookupComplete(const std::string &result)
3324 /* Initiate the connection, now that we have an IP to use.
3325 * Passing a hostname directly to InspSocket causes it to
3326 * just bail and set its FD to -1.
3328 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3329 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3331 TreeSocket* newsocket = new TreeSocket(ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str());
3332 if (newsocket->GetFd() > -1)
3338 /* Something barfed, show the opers */
3339 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3341 DoFailOver(&MyLink);
3346 void OnError(ResolverError e, const std::string &errormessage)
3349 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3350 DoFailOver(&MyLink);
3354 class SecurityIPResolver : public Resolver
3359 SecurityIPResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
3363 void OnLookupComplete(const std::string &result)
3365 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3366 ValidIPs.push_back(result);
3369 void OnError(ResolverError e, const std::string &errormessage)
3371 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3375 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3377 for (unsigned int c = 0; c < list.size(); c++)
3379 if (list[c] == server)
3384 list.push_back(server);
3387 // returns a list of DIRECT servernames for a specific channel
3388 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3390 CUList *ulist = c->GetUsers();
3391 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3393 if (i->second->GetFd() < 0)
3395 TreeServer* best = BestRouteTo(i->second->server);
3397 AddThisServer(best,list);
3403 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms)
3405 TreeServer* omitroute = BestRouteTo(omit);
3406 if ((command == "NOTICE") || (command == "PRIVMSG"))
3408 if (params.size() >= 2)
3411 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3413 params[0] = params[0].substr(1, params[0].length()-1);
3415 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3417 // special routing for private messages/notices
3418 userrec* d = ServerInstance->FindNick(params[0]);
3421 std::deque<std::string> par;
3422 par.push_back(params[0]);
3423 par.push_back(":"+params[1]);
3424 DoOneToOne(prefix,command.c_str(),par,d->server);
3428 else if (*(params[0].c_str()) == '$')
3430 std::deque<std::string> par;
3431 par.push_back(params[0]);
3432 par.push_back(":"+params[1]);
3433 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3438 ServerInstance->Log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3439 chanrec* c = ServerInstance->FindChan(params[0]);
3442 std::deque<TreeServer*> list;
3443 GetListOfServersForChannel(c,list);
3444 ServerInstance->Log(DEBUG,"Got a list of %d servers",list.size());
3445 unsigned int lsize = list.size();
3446 for (unsigned int i = 0; i < lsize; i++)
3448 TreeSocket* Sock = list[i]->GetSocket();
3449 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3451 ServerInstance->Log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3452 Sock->WriteLine(data);
3460 unsigned int items = TreeRoot->ChildCount();
3461 for (unsigned int x = 0; x < items; x++)
3463 TreeServer* Route = TreeRoot->GetChild(x);
3464 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3466 TreeSocket* Sock = Route->GetSocket();
3468 Sock->WriteLine(data);
3474 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
3476 TreeServer* omitroute = BestRouteTo(omit);
3477 std::string FullLine = ":" + prefix + " " + command;
3478 unsigned int words = params.size();
3479 for (unsigned int x = 0; x < words; x++)
3481 FullLine = FullLine + " " + params[x];
3483 unsigned int items = TreeRoot->ChildCount();
3484 for (unsigned int x = 0; x < items; x++)
3486 TreeServer* Route = TreeRoot->GetChild(x);
3487 // Send the line IF:
3488 // The route has a socket (its a direct connection)
3489 // The route isnt the one to be omitted
3490 // The route isnt the path to the one to be omitted
3491 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3493 TreeSocket* Sock = Route->GetSocket();
3495 Sock->WriteLine(FullLine);
3501 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
3503 std::string FullLine = ":" + prefix + " " + command;
3504 unsigned int words = params.size();
3505 for (unsigned int x = 0; x < words; x++)
3507 FullLine = FullLine + " " + params[x];
3509 unsigned int items = TreeRoot->ChildCount();
3510 for (unsigned int x = 0; x < items; x++)
3512 TreeServer* Route = TreeRoot->GetChild(x);
3513 if (Route && Route->GetSocket())
3515 TreeSocket* Sock = Route->GetSocket();
3517 Sock->WriteLine(FullLine);
3523 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3525 std::string spfx = prefix;
3526 std::string scmd = command;
3527 return DoOneToMany(spfx, scmd, params);
3530 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3532 std::string spfx = prefix;
3533 std::string scmd = command;
3534 return DoOneToAllButSender(spfx, scmd, params, omit);
3537 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
3539 TreeServer* Route = BestRouteTo(target);
3542 std::string FullLine = ":" + prefix + " " + command;
3543 unsigned int words = params.size();
3544 for (unsigned int x = 0; x < words; x++)
3546 FullLine = FullLine + " " + params[x];
3548 if (Route && Route->GetSocket())
3550 TreeSocket* Sock = Route->GetSocket();
3552 Sock->WriteLine(FullLine);
3562 std::vector<TreeSocket*> Bindings;
3564 void ReadConfiguration(bool rebind)
3566 Conf = new ConfigReader(ServerInstance);
3569 for (int j =0; j < Conf->Enumerate("bind"); j++)
3571 std::string Type = Conf->ReadValue("bind","type",j);
3572 std::string IP = Conf->ReadValue("bind","address",j);
3573 long Port = Conf->ReadInteger("bind","port",j,true);
3574 if (Type == "servers")
3580 TreeSocket* listener = new TreeSocket(ServerInstance, IP.c_str(),Port,true,10);
3581 if (listener->GetState() == I_LISTENING)
3583 Bindings.push_back(listener);
3587 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3594 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3595 HideULines = Conf->ReadFlag("options","hideulines",0);
3598 for (int j =0; j < Conf->Enumerate("link"); j++)
3601 std::string Allow = Conf->ReadValue("link","allowmask",j);
3602 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3603 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3604 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3605 L.Port = Conf->ReadInteger("link","port",j,true);
3606 L.SendPass = Conf->ReadValue("link","sendpass",j);
3607 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3608 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3609 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
3610 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3611 L.NextConnectTime = time(NULL) + L.AutoConnect;
3612 /* Bugfix by brain, do not allow people to enter bad configurations */
3613 if (L.Name != ServerInstance->Config->ServerName)
3615 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3617 ValidIPs.push_back(L.IPAddr);
3620 ValidIPs.push_back(Allow);
3622 /* Needs resolving */
3624 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3628 SecurityIPResolver* sr = new SecurityIPResolver(ServerInstance, L.IPAddr, L);
3629 ServerInstance->AddResolver(sr);
3631 catch (ModuleException& e)
3633 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
3637 LinkBlocks.push_back(L);
3638 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3644 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3646 else if (L.RecvPass == "")
3648 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3650 else if (L.SendPass == "")
3652 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3654 else if (L.Name == "")
3656 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
3660 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3666 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
3673 class ModuleSpanningTree : public Module
3675 std::vector<TreeSocket*> Bindings;
3678 unsigned int max_local;
3679 unsigned int max_global;
3680 cmd_rconnect* command_rconnect;
3684 ModuleSpanningTree(InspIRCd* Me)
3685 : Module::Module(Me), max_local(0), max_global(0)
3690 ::ServerInstance = Me;
3692 // Create the root of the tree
3693 TreeRoot = new TreeServer(ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3695 ReadConfiguration(true);
3697 command_rconnect = new cmd_rconnect(ServerInstance, this);
3698 ServerInstance->AddCommand(command_rconnect);
3701 void ShowLinks(TreeServer* Current, userrec* user, int hops)
3703 std::string Parent = TreeRoot->GetName();
3704 if (Current->GetParent())
3706 Parent = Current->GetParent()->GetName();
3708 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3710 if ((HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3714 ShowLinks(Current->GetChild(q),user,hops+1);
3719 ShowLinks(Current->GetChild(q),user,hops+1);
3722 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3723 if ((HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
3725 user->WriteServ("364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(FlatLinks && (!*user->oper)) ? ServerInstance->Config->ServerName : Parent.c_str(),(FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3728 int CountLocalServs()
3730 return TreeRoot->ChildCount();
3735 return serverlist.size();
3738 void HandleLinks(const char** parameters, int pcnt, userrec* user)
3740 ShowLinks(TreeRoot,user,0);
3741 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
3745 void HandleLusers(const char** parameters, int pcnt, userrec* user)
3747 unsigned int n_users = ServerInstance->UserCount();
3749 /* Only update these when someone wants to see them, more efficient */
3750 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
3751 max_local = ServerInstance->LocalUserCount();
3752 if (n_users > max_global)
3753 max_global = n_users;
3755 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs());
3756 if (ServerInstance->OperCount())
3757 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
3758 if (ServerInstance->UnregisteredUserCount())
3759 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
3760 if (ServerInstance->ChannelCount())
3761 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
3762 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs());
3763 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
3764 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
3768 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3770 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3774 for (int t = 0; t < depth; t++)
3776 matrix[line][t] = ' ';
3779 // For Aligning, we need to work out exactly how deep this thing is, and produce
3780 // a 'Spacer' String to compensate.
3783 memset(spacer,' ',40);
3784 if ((40 - Current->GetName().length() - depth) > 1) {
3785 spacer[40 - Current->GetName().length() - depth] = '\0';
3794 if (ServerInstance->clientlist.size() == 0) {
3795 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3800 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
3802 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3803 totusers += Current->GetUserCount();
3805 strlcpy(&matrix[line][depth],text,80);
3807 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3809 if ((HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3813 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3818 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3824 int HandleMotd(const char** parameters, int pcnt, userrec* user)
3828 /* Remote MOTD, the server is within the 1st parameter */
3829 std::deque<std::string> params;
3830 params.push_back(parameters[0]);
3832 /* Send it out remotely, generate no reply yet */
3833 TreeServer* s = FindServerMask(parameters[0]);
3836 DoOneToOne(user->nick, "MOTD", params, s->GetName());
3840 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3847 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
3851 /* Remote ADMIN, the server is within the 1st parameter */
3852 std::deque<std::string> params;
3853 params.push_back(parameters[0]);
3855 /* Send it out remotely, generate no reply yet */
3856 TreeServer* s = FindServerMask(parameters[0]);
3859 DoOneToOne(user->nick, "ADMIN", params, s->GetName());
3863 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3870 int HandleStats(const char** parameters, int pcnt, userrec* user)
3874 /* Remote STATS, the server is within the 2nd parameter */
3875 std::deque<std::string> params;
3876 params.push_back(parameters[0]);
3877 params.push_back(parameters[1]);
3878 /* Send it out remotely, generate no reply yet */
3879 TreeServer* s = FindServerMask(parameters[1]);
3882 params[1] = s->GetName();
3883 DoOneToOne(user->nick, "STATS", params, s->GetName());
3887 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3894 // Ok, prepare to be confused.
3895 // After much mulling over how to approach this, it struck me that
3896 // the 'usual' way of doing a /MAP isnt the best way. Instead of
3897 // keeping track of a ton of ascii characters, and line by line
3898 // under recursion working out where to place them using multiplications
3899 // and divisons, we instead render the map onto a backplane of characters
3900 // (a character matrix), then draw the branches as a series of "L" shapes
3901 // from the nodes. This is not only friendlier on CPU it uses less stack.
3903 void HandleMap(const char** parameters, int pcnt, userrec* user)
3905 // This array represents a virtual screen which we will
3906 // "scratch" draw to, as the console device of an irc
3907 // client does not provide for a proper terminal.
3909 float totservers = 0;
3910 char matrix[128][80];
3911 for (unsigned int t = 0; t < 128; t++)
3913 matrix[t][0] = '\0';
3916 // The only recursive bit is called here.
3917 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3918 // Process each line one by one. The algorithm has a limit of
3919 // 128 servers (which is far more than a spanning tree should have
3920 // anyway, so we're ok). This limit can be raised simply by making
3921 // the character matrix deeper, 128 rows taking 10k of memory.
3922 for (int l = 1; l < line; l++)
3924 // scan across the line looking for the start of the
3925 // servername (the recursive part of the algorithm has placed
3926 // the servers at indented positions depending on what they
3928 int first_nonspace = 0;
3929 while (matrix[l][first_nonspace] == ' ')
3934 // Draw the `- (corner) section: this may be overwritten by
3935 // another L shape passing along the same vertical pane, becoming
3936 // a |- (branch) section instead.
3937 matrix[l][first_nonspace] = '-';
3938 matrix[l][first_nonspace-1] = '`';
3940 // Draw upwards until we hit the parent server, causing possibly
3941 // other corners (`-) to become branches (|-)
3942 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3944 matrix[l2][first_nonspace-1] = '|';
3948 // dump the whole lot to the user. This is the easy bit, honest.
3949 for (int t = 0; t < line; t++)
3951 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
3953 float avg_users = totusers / totservers;
3954 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);
3955 user->WriteServ("007 %s :End of /MAP",user->nick);
3959 int HandleSquit(const char** parameters, int pcnt, userrec* user)
3961 TreeServer* s = FindServerMask(parameters[0]);
3966 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3969 TreeSocket* sock = s->GetSocket();
3972 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
3973 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3974 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3975 ServerInstance->SE->DelFd(sock);
3981 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3986 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3991 int HandleTime(const char** parameters, int pcnt, userrec* user)
3993 if ((IS_LOCAL(user)) && (pcnt))
3995 TreeServer* found = FindServerMask(parameters[0]);
3998 // we dont' override for local server
3999 if (found == TreeRoot)
4002 std::deque<std::string> params;
4003 params.push_back(found->GetName());
4004 params.push_back(user->nick);
4005 DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4009 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4015 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4017 if ((IS_LOCAL(user)) && (pcnt > 1))
4019 userrec* remote = ServerInstance->FindNick(parameters[1]);
4020 if ((remote) && (remote->GetFd() < 0))
4022 std::deque<std::string> params;
4023 params.push_back(parameters[1]);
4024 DoOneToOne(user->nick,"IDLE",params,remote->server);
4029 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4030 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4037 void DoPingChecks(time_t curtime)
4039 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
4041 TreeServer* serv = TreeRoot->GetChild(j);
4042 TreeSocket* sock = serv->GetSocket();
4045 if (curtime >= serv->NextPingTime())
4047 if (serv->AnsweredLastPing())
4049 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4050 serv->SetNextPingTime(curtime + 60);
4054 // they didnt answer, boot them
4055 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4056 sock->Squit(serv,"Ping timeout");
4057 ServerInstance->SE->DelFd(sock);
4067 void ConnectServer(Link* x)
4071 /* Do we already have an IP? If so, no need to resolve it. */
4072 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4074 TreeSocket* newsocket = new TreeSocket(ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str());
4075 if (newsocket->GetFd() > -1)
4077 /* Handled automatically on success */
4081 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4083 this->DoFailOver(x);
4090 ServernameResolver* snr = new ServernameResolver(ServerInstance,x->IPAddr, *x);
4091 ServerInstance->AddResolver(snr);
4093 catch (ModuleException& e)
4095 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4096 this->DoFailOver(x);
4101 void DoFailOver(Link* x)
4103 if (x->FailOver.length())
4105 if (x->FailOver == x->Name)
4107 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());
4110 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
4113 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
4114 ConnectServer(TryThisOne);
4118 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
4123 Link* FindLink(const std::string& name)
4125 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4127 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
4135 void AutoConnectServers(time_t curtime)
4137 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4139 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4141 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4142 x->NextConnectTime = curtime + x->AutoConnect;
4143 TreeServer* CheckDupe = FindServer(x->Name.c_str());
4144 if (x->FailOver.length())
4146 TreeServer* CheckFailOver = FindServer(x->FailOver.c_str());
4149 /* The failover for this server is currently a member of the network.
4150 * The failover probably succeeded, where the main link did not.
4151 * Don't try the main link until the failover is gone again.
4158 // an autoconnected server is not connected. Check if its time to connect it
4159 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4160 this->ConnectServer(&(*x));
4166 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4168 // we've already checked if pcnt > 0, so this is safe
4169 TreeServer* found = FindServerMask(parameters[0]);
4172 std::string Version = found->GetVersion();
4173 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4174 if (found == TreeRoot)
4176 std::stringstream out(ServerInstance->Config->data005);
4177 std::string token = "";
4178 std::string line5 = "";
4179 int token_counter = 0;
4184 line5 = line5 + token + " ";
4187 if ((token_counter >= 13) || (out.eof() == true))
4189 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4198 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4203 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4205 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4207 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4209 TreeServer* CheckDupe = FindServer(x->Name.c_str());
4212 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);
4213 ConnectServer(&(*x));
4218 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());
4223 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4227 virtual int OnStats(char statschar, userrec* user, string_list &results)
4229 if (statschar == 'c')
4231 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
4233 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr)+" * "+LinkBlocks[i].Name.c_str()+" "+ConvToStr(LinkBlocks[i].Port)+" "+(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4234 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
4236 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4237 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);
4243 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
4245 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4249 if (command == "CONNECT")
4251 return this->HandleConnect(parameters,pcnt,user);
4253 else if (command == "STATS")
4255 return this->HandleStats(parameters,pcnt,user);
4257 else if (command == "MOTD")
4259 return this->HandleMotd(parameters,pcnt,user);
4261 else if (command == "ADMIN")
4263 return this->HandleAdmin(parameters,pcnt,user);
4265 else if (command == "SQUIT")
4267 return this->HandleSquit(parameters,pcnt,user);
4269 else if (command == "MAP")
4271 this->HandleMap(parameters,pcnt,user);
4274 else if ((command == "TIME") && (pcnt > 0))
4276 return this->HandleTime(parameters,pcnt,user);
4278 else if (command == "LUSERS")
4280 this->HandleLusers(parameters,pcnt,user);
4283 else if (command == "LINKS")
4285 this->HandleLinks(parameters,pcnt,user);
4288 else if (command == "WHOIS")
4293 return this->HandleRemoteWhois(parameters,pcnt,user);
4296 else if ((command == "VERSION") && (pcnt > 0))
4298 this->HandleVersion(parameters,pcnt,user);
4301 else if (ServerInstance->IsValidModuleCommand(command, pcnt, user))
4303 // this bit of code cleverly routes all module commands
4304 // to all remote severs *automatically* so that modules
4305 // can just handle commands locally, without having
4306 // to have any special provision in place for remote
4307 // commands and linking protocols.
4308 std::deque<std::string> params;
4310 for (int j = 0; j < pcnt; j++)
4312 if (strchr(parameters[j],' '))
4314 params.push_back(":" + std::string(parameters[j]));
4318 params.push_back(std::string(parameters[j]));
4321 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4322 DoOneToMany(user->nick,command,params);
4327 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4329 TreeServer* s = FindServer(servername);
4332 description = s->GetDesc();
4336 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4338 if (IS_LOCAL(source))
4340 std::deque<std::string> params;
4341 params.push_back(dest->nick);
4342 params.push_back(channel->name);
4343 DoOneToMany(source->nick,"INVITE",params);
4347 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4349 std::deque<std::string> params;
4350 params.push_back(chan->name);
4351 params.push_back(":"+topic);
4352 DoOneToMany(user->nick,"TOPIC",params);
4355 virtual void OnWallops(userrec* user, const std::string &text)
4359 std::deque<std::string> params;
4360 params.push_back(":"+text);
4361 DoOneToMany(user->nick,"WALLOPS",params);
4365 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4367 if (target_type == TYPE_USER)
4369 userrec* d = (userrec*)dest;
4370 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4372 std::deque<std::string> params;
4374 params.push_back(d->nick);
4375 params.push_back(":"+text);
4376 DoOneToOne(user->nick,"NOTICE",params,d->server);
4379 else if (target_type == TYPE_CHANNEL)
4383 chanrec *c = (chanrec*)dest;
4386 std::string cname = c->name;
4388 cname = status + cname;
4389 std::deque<TreeServer*> list;
4390 GetListOfServersForChannel(c,list);
4391 unsigned int ucount = list.size();
4392 for (unsigned int i = 0; i < ucount; i++)
4394 TreeSocket* Sock = list[i]->GetSocket();
4396 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4401 else if (target_type == TYPE_SERVER)
4405 char* target = (char*)dest;
4406 std::deque<std::string> par;
4407 par.push_back(target);
4408 par.push_back(":"+text);
4409 DoOneToMany(user->nick,"NOTICE",par);
4414 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4416 if (target_type == TYPE_USER)
4418 // route private messages which are targetted at clients only to the server
4419 // which needs to receive them
4420 userrec* d = (userrec*)dest;
4421 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4423 std::deque<std::string> params;
4425 params.push_back(d->nick);
4426 params.push_back(":"+text);
4427 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4430 else if (target_type == TYPE_CHANNEL)
4434 chanrec *c = (chanrec*)dest;
4437 std::string cname = c->name;
4439 cname = status + cname;
4440 std::deque<TreeServer*> list;
4441 GetListOfServersForChannel(c,list);
4442 unsigned int ucount = list.size();
4443 for (unsigned int i = 0; i < ucount; i++)
4445 TreeSocket* Sock = list[i]->GetSocket();
4447 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4452 else if (target_type == TYPE_SERVER)
4456 char* target = (char*)dest;
4457 std::deque<std::string> par;
4458 par.push_back(target);
4459 par.push_back(":"+text);
4460 DoOneToMany(user->nick,"PRIVMSG",par);
4465 virtual void OnBackgroundTimer(time_t curtime)
4467 AutoConnectServers(curtime);
4468 DoPingChecks(curtime);
4471 virtual void OnUserJoin(userrec* user, chanrec* channel)
4473 // Only do this for local users
4476 std::deque<std::string> params;
4478 params.push_back(channel->name);
4480 if (channel->GetUserCounter() > 1)
4482 // not the first in the channel
4483 DoOneToMany(user->nick,"JOIN",params);
4487 // first in the channel, set up their permissions
4488 // and the channel TS with FJOIN.
4490 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4492 params.push_back(channel->name);
4493 params.push_back(ts);
4494 params.push_back("@,"+std::string(user->nick));
4495 DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4500 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4502 // only occurs for local clients
4503 if (user->registered != REG_ALL)
4505 std::deque<std::string> params;
4506 params.push_back(newhost);
4507 DoOneToMany(user->nick,"FHOST",params);
4510 virtual void OnChangeName(userrec* user, const std::string &gecos)
4512 // only occurs for local clients
4513 if (user->registered != REG_ALL)
4515 std::deque<std::string> params;
4516 params.push_back(gecos);
4517 DoOneToMany(user->nick,"FNAME",params);
4520 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4524 std::deque<std::string> params;
4525 params.push_back(channel->name);
4526 if (partmessage != "")
4527 params.push_back(":"+partmessage);
4528 DoOneToMany(user->nick,"PART",params);
4532 virtual void OnUserConnect(userrec* user)
4534 char agestr[MAXBUF];
4537 std::deque<std::string> params;
4538 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4539 params.push_back(agestr);
4540 params.push_back(user->nick);
4541 params.push_back(user->host);
4542 params.push_back(user->dhost);
4543 params.push_back(user->ident);
4544 params.push_back("+"+std::string(user->FormatModes()));
4545 params.push_back(user->GetIPString());
4546 params.push_back(":"+std::string(user->fullname));
4547 DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4549 // User is Local, change needs to be reflected!
4550 TreeServer* SourceServer = FindServer(user->server);
4553 SourceServer->AddUserCount();
4559 virtual void OnUserQuit(userrec* user, const std::string &reason)
4561 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4563 std::deque<std::string> params;
4564 params.push_back(":"+reason);
4565 DoOneToMany(user->nick,"QUIT",params);
4567 // Regardless, We need to modify the user Counts..
4568 TreeServer* SourceServer = FindServer(user->server);
4571 SourceServer->DelUserCount();
4576 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4580 std::deque<std::string> params;
4581 params.push_back(user->nick);
4582 DoOneToMany(oldnick,"NICK",params);
4586 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4588 if ((source) && (IS_LOCAL(source)))
4590 std::deque<std::string> params;
4591 params.push_back(chan->name);
4592 params.push_back(user->nick);
4593 params.push_back(":"+reason);
4594 DoOneToMany(source->nick,"KICK",params);
4598 std::deque<std::string> params;
4599 params.push_back(chan->name);
4600 params.push_back(user->nick);
4601 params.push_back(":"+reason);
4602 DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4606 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4608 std::deque<std::string> params;
4609 params.push_back(dest->nick);
4610 params.push_back(":"+reason);
4611 DoOneToMany(source->nick,"KILL",params);
4614 virtual void OnRehash(const std::string ¶meter)
4616 if (parameter != "")
4618 std::deque<std::string> params;
4619 params.push_back(parameter);
4620 DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4622 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4624 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4625 ServerInstance->RehashServer();
4628 ReadConfiguration(false);
4631 // note: the protocol does not allow direct umode +o except
4632 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4634 virtual void OnOper(userrec* user, const std::string &opertype)
4638 std::deque<std::string> params;
4639 params.push_back(opertype);
4640 DoOneToMany(user->nick,"OPERTYPE",params);
4644 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4646 if (IS_LOCAL(source))
4649 snprintf(type,8,"%cLINE",linetype);
4650 std::string stype = type;
4653 char sduration[MAXBUF];
4654 snprintf(sduration,MAXBUF,"%ld",duration);
4655 std::deque<std::string> params;
4656 params.push_back(host);
4657 params.push_back(sduration);
4658 params.push_back(":"+reason);
4659 DoOneToMany(source->nick,stype,params);
4663 std::deque<std::string> params;
4664 params.push_back(host);
4665 DoOneToMany(source->nick,stype,params);
4670 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4672 OnLine(source,hostmask,true,'G',duration,reason);
4675 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4677 OnLine(source,ipmask,true,'Z',duration,reason);
4680 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4682 OnLine(source,nickmask,true,'Q',duration,reason);
4685 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4687 OnLine(source,hostmask,true,'E',duration,reason);
4690 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4692 OnLine(source,hostmask,false,'G',0,"");
4695 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4697 OnLine(source,ipmask,false,'Z',0,"");
4700 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4702 OnLine(source,nickmask,false,'Q',0,"");
4705 virtual void OnDelELine(userrec* source, const std::string &hostmask)
4707 OnLine(source,hostmask,false,'E',0,"");
4710 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4712 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4714 if (target_type == TYPE_USER)
4716 userrec* u = (userrec*)dest;
4717 std::deque<std::string> params;
4718 params.push_back(u->nick);
4719 params.push_back(text);
4720 DoOneToMany(user->nick,"MODE",params);
4724 chanrec* c = (chanrec*)dest;
4725 std::deque<std::string> params;
4726 params.push_back(c->name);
4727 params.push_back(text);
4728 DoOneToMany(user->nick,"MODE",params);
4733 virtual void OnSetAway(userrec* user)
4737 std::deque<std::string> params;
4738 params.push_back(":"+std::string(user->awaymsg));
4739 DoOneToMany(user->nick,"AWAY",params);
4743 virtual void OnCancelAway(userrec* user)
4747 std::deque<std::string> params;
4749 DoOneToMany(user->nick,"AWAY",params);
4753 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4755 TreeSocket* s = (TreeSocket*)opaque;
4758 if (target_type == TYPE_USER)
4760 userrec* u = (userrec*)target;
4761 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4765 chanrec* c = (chanrec*)target;
4766 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4771 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4773 TreeSocket* s = (TreeSocket*)opaque;
4776 if (target_type == TYPE_USER)
4778 userrec* u = (userrec*)target;
4779 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
4781 else if (target_type == TYPE_OTHER)
4783 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
4785 else if (target_type == TYPE_CHANNEL)
4787 chanrec* c = (chanrec*)target;
4788 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
4793 virtual void OnEvent(Event* event)
4795 if (event->GetEventID() == "send_metadata")
4797 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4798 if (params->size() < 3)
4800 (*params)[2] = ":" + (*params)[2];
4801 DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
4803 else if (event->GetEventID() == "send_mode")
4805 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4806 if (params->size() < 2)
4808 // Insert the TS value of the object, either userrec or chanrec
4810 userrec* a = ServerInstance->FindNick((*params)[0]);
4817 chanrec* a = ServerInstance->FindChan((*params)[0]);
4823 params->insert(params->begin() + 1,ConvToStr(ourTS));
4824 DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
4828 virtual ~ModuleSpanningTree()
4832 virtual Version GetVersion()
4834 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4837 void Implements(char* List)
4839 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4840 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4841 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4842 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4843 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4844 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4845 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4848 /* It is IMPORTANT that m_spanningtree is the last module in the chain
4849 * so that any activity it sees is FINAL, e.g. we arent going to send out
4850 * a NICK message before m_cloaking has finished putting the +x on the user,
4852 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4853 * the module call queue.
4855 Priority Prioritize()
4857 return PRIORITY_LAST;
4861 void DoFailOver(Link* x)
4863 TreeProtocolModule->DoFailOver(x);
4866 Link* FindLink(const std::string& name)
4868 return TreeProtocolModule->FindLink(name);
4871 class ModuleSpanningTreeFactory : public ModuleFactory
4874 ModuleSpanningTreeFactory()
4878 ~ModuleSpanningTreeFactory()
4882 virtual Module * CreateModule(InspIRCd* Me)
4884 TreeProtocolModule = new ModuleSpanningTree(Me);
4885 return TreeProtocolModule;
4891 extern "C" void * init_module( void )
4893 return new ModuleSpanningTreeFactory;