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 using irc::sockets::MatchCIDR;
36 /** If you make a change which breaks the protocol, increment this.
37 * If you completely change the protocol, completely change the number.
39 const long ProtocolVersion = 1101;
42 * The server list in InspIRCd is maintained as two structures
43 * which hold the data in different ways. Most of the time, we
44 * want to very quicky obtain three pieces of information:
46 * (1) The information on a server
47 * (2) The information on the server we must send data through
48 * to actually REACH the server we're after
49 * (3) Potentially, the child/parent objects of this server
51 * The InspIRCd spanning protocol provides easy access to these
52 * by storing the data firstly in a recursive structure, where
53 * each item references its parent item, and a dynamic list
54 * of child items, and another structure which stores the items
55 * hashed, linearly. This means that if we want to find a server
56 * by name quickly, we can look it up in the hash, avoiding
57 * any O(n) lookups. If however, during a split or sync, we want
58 * to apply an operation to a server, and any of its child objects
59 * we can resort to recursion to walk the tree structure.
60 * Any socket can have one of five states at any one time.
61 * The LISTENER state indicates a socket which is listening
62 * for connections. It cannot receive data itself, only incoming
64 * The CONNECTING state indicates an outbound socket which is
65 * waiting to be writeable.
66 * The WAIT_AUTH_1 state indicates the socket is outbound and
67 * has successfully connected, but has not yet sent and received
69 * The WAIT_AUTH_2 state indicates that the socket is inbound
70 * (allocated by a LISTENER) but has not yet sent and received
72 * The CONNECTED state represents a fully authorized, fully
75 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
77 /* Foward declarations */
81 class ModuleSpanningTree;
83 /* This hash_map holds the hash equivalent of the server
84 * tree, used for rapid linear lookups.
86 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
88 /** Contains helper functions and variables for this module,
89 * and keeps them out of the global namespace
91 class SpanningTreeUtilities
94 InspIRCd* ServerInstance;
96 ModuleSpanningTree* Creator;
97 bool FlatLinks; /* Flatten links and /MAP for non-opers */
98 bool HideULines; /* Hide U-Lined servers in /MAP and /LINKS */
99 bool AnnounceTSChange; /* Announce TS changes to channels on merge */
100 std::vector<TreeSocket*> Bindings; /* Socket bindings */
101 /* This variable represents the root of the server tree */
102 TreeServer *TreeRoot;
103 /* IPs allowed to link to us */
104 std::vector<std::string> ValidIPs;
105 /* Hash of currently connected servers by name */
106 server_hash serverlist;
107 /* Holds the data from the <link> tags in the conf */
108 std::vector<Link> LinkBlocks;
110 SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator);
111 ~SpanningTreeUtilities();
112 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
113 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
114 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit);
115 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
116 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms);
117 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms);
118 void ReadConfiguration(bool rebind);
119 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list);
120 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list);
121 TreeServer* FindServer(std::string ServerName);
122 TreeServer* BestRouteTo(std::string ServerName);
123 TreeServer* FindServerMask(std::string ServerName);
124 bool IsServer(std::string ServerName);
125 void DoFailOver(Link* x);
126 Link* FindLink(const std::string& name);
130 /** Each server in the tree is represented by one class of
131 * type TreeServer. A locally connected TreeServer can
132 * have a class of type TreeSocket associated with it, for
133 * remote servers, the TreeSocket entry will be NULL.
134 * Each server also maintains a pointer to its parent
135 * (NULL if this server is ours, at the top of the tree)
136 * and a pointer to its "Route" (see the comments in the
137 * constructors below), and also a dynamic list of pointers
138 * to its children which can be iterated recursively
139 * if required. Creating or deleting objects of type
140 i* TreeServer automatically maintains the hash_map of
141 * TreeServer items, deleting and inserting them as they
142 * are created and destroyed.
144 class TreeServer : public classbase
146 InspIRCd* ServerInstance; /* Creator */
147 SpanningTreeUtilities* Utils; /* Utility class */
148 TreeServer* Parent; /* Parent entry */
149 TreeServer* Route; /* Route entry */
150 std::vector<TreeServer*> Children; /* List of child objects */
151 irc::string ServerName; /* Server's name */
152 std::string ServerDesc; /* Server's description */
153 std::string VersionString; /* Version string or empty string */
154 int UserCount; /* Not used in this version */
155 int OperCount; /* Not used in this version */
156 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
157 time_t NextPing; /* After this time, the server should be PINGed*/
158 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
162 /** We don't use this constructor. Its a dummy, and won't cause any insertion
163 * of the TreeServer into the hash_map. See below for the two we DO use.
165 TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance) : ServerInstance(Instance)
171 UserCount = OperCount = 0;
172 VersionString = ServerInstance->GetVersionString();
175 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
176 * represents our own server. Therefore, it has no route, no parent, and
177 * no socket associated with it. Its version string is our own local version.
179 TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc)
183 UserCount = OperCount = 0;
184 VersionString = ServerInstance->GetVersionString();
186 Socket = NULL; /* Fix by brain */
190 /** When we create a new server, we call this constructor to initialize it.
191 * This constructor initializes the server's Route and Parent, and sets up
192 * its ping counters so that it will be pinged one minute from now.
194 TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
195 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
198 UserCount = OperCount = 0;
199 this->SetNextPingTime(time(NULL) + 60);
202 /* find the 'route' for this server (e.g. the one directly connected
203 * to the local server, which we can use to reach it)
205 * In the following example, consider we have just added a TreeServer
206 * class for server G on our network, of which we are server A.
207 * To route traffic to G (marked with a *) we must send the data to
208 * B (marked with a +) so this algorithm initializes the 'Route'
209 * value to point at whichever server traffic must be routed through
210 * to get here. If we were to try this algorithm with server B,
211 * the Route pointer would point at its own object ('this').
221 * We only run this algorithm when a server is created, as
222 * the routes remain constant while ever the server exists, and
223 * do not need to be re-calculated.
227 if (Route == Utils->TreeRoot)
233 while (this->Route->GetParent() != Utils->TreeRoot)
235 this->Route = Route->GetParent();
239 /* Because recursive code is slow and takes a lot of resources,
240 * we store two representations of the server tree. The first
241 * is a recursive structure where each server references its
242 * children and its parent, which is used for netbursts and
243 * netsplits to dump the whole dataset to the other server,
244 * and the second is used for very fast lookups when routing
245 * messages and is instead a hash_map, where each item can
246 * be referenced by its server name. The AddHashEntry()
247 * call below automatically inserts each TreeServer class
248 * into the hash_map as it is created. There is a similar
249 * maintainance call in the destructor to tidy up deleted
253 this->AddHashEntry();
256 int QuitUsers(const std::string &reason)
258 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
259 const char* reason_s = reason.c_str();
260 std::vector<userrec*> time_to_die;
261 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
263 if (!strcmp(n->second->server, this->ServerName.c_str()))
265 time_to_die.push_back(n->second);
268 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
270 userrec* a = (userrec*)*n;
271 ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
273 userrec::QuitUser(ServerInstance,a,reason_s);
275 return time_to_die.size();
278 /** This method is used to add the structure to the
279 * hash_map for linear searches. It is only called
280 * by the constructors.
284 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
285 if (iter == Utils->serverlist.end())
286 Utils->serverlist[this->ServerName.c_str()] = this;
289 /** This method removes the reference to this object
290 * from the hash_map which is used for linear searches.
291 * It is only called by the default destructor.
295 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
296 if (iter != Utils->serverlist.end())
297 Utils->serverlist.erase(iter);
300 /** These accessors etc should be pretty self-
303 TreeServer* GetRoute()
308 std::string GetName()
310 return ServerName.c_str();
313 std::string GetDesc()
318 std::string GetVersion()
320 return VersionString;
323 void SetNextPingTime(time_t t)
326 LastPingWasGood = false;
329 time_t NextPingTime()
334 bool AnsweredLastPing()
336 return LastPingWasGood;
341 LastPingWasGood = true;
364 TreeSocket* GetSocket()
369 TreeServer* GetParent()
374 void SetVersion(std::string Version)
376 VersionString = Version;
379 unsigned int ChildCount()
381 return Children.size();
384 TreeServer* GetChild(unsigned int n)
386 if (n < Children.size())
388 /* Make sure they cant request
389 * an out-of-range object. After
390 * all we know what these programmer
391 * types are like *grin*.
401 void AddChild(TreeServer* Child)
403 Children.push_back(Child);
406 bool DelChild(TreeServer* Child)
408 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
419 /** Removes child nodes of this node, and of that node, etc etc.
420 * This is used during netsplits to automatically tidy up the
421 * server tree. It is slow, we don't use it for much else.
425 bool stillchildren = true;
426 while (stillchildren)
428 stillchildren = false;
429 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
431 TreeServer* s = (TreeServer*)*a;
435 stillchildren = true;
444 /* We'd better tidy up after ourselves, eh? */
445 this->DelHashEntry();
449 /** The Link class might as well be a struct,
450 * but this is C++ and we don't believe in structs (!).
451 * It holds the entire information of one <link>
452 * tag from the main config file. We maintain a list
453 * of them, and populate the list on rehash/load.
455 class Link : public classbase
461 std::string SendPass;
462 std::string RecvPass;
463 unsigned long AutoConnect;
464 time_t NextConnectTime;
465 std::string EncryptionKey;
466 bool HiddenFromStats;
467 irc::string FailOver;
470 /** Yay for fast searches!
471 * This is hundreds of times faster than recursion
472 * or even scanning a linked list, especially when
473 * there are more than a few servers to deal with.
476 TreeServer* SpanningTreeUtilities::FindServer(std::string ServerName)
478 server_hash::iterator iter;
479 iter = serverlist.find(ServerName.c_str());
480 if (iter != serverlist.end())
490 /** Returns the locally connected server we must route a
491 * message through to reach server 'ServerName'. This
492 * only applies to one-to-one and not one-to-many routing.
493 * See the comments for the constructor of TreeServer
496 TreeServer* SpanningTreeUtilities::BestRouteTo(std::string ServerName)
498 if (ServerName.c_str() == TreeRoot->GetName())
500 TreeServer* Found = FindServer(ServerName);
503 return Found->GetRoute();
511 /** Find the first server matching a given glob mask.
512 * Theres no find-using-glob method of hash_map [awwww :-(]
513 * so instead, we iterate over the list using an iterator
514 * and match each one until we get a hit. Yes its slow,
517 TreeServer* SpanningTreeUtilities::FindServerMask(std::string ServerName)
519 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
521 if (match(i->first.c_str(),ServerName.c_str()))
527 /* A convenient wrapper that returns true if a server exists */
528 bool SpanningTreeUtilities::IsServer(std::string ServerName)
530 return (FindServer(ServerName) != NULL);
536 class cmd_rconnect : public command_t
539 SpanningTreeUtilities* Utils;
541 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
543 this->source = "m_spanningtree.so";
544 syntax = "<remote-server-mask> <servermask>";
547 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
549 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
550 /* Is this aimed at our server? */
551 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
553 /* Yes, initiate the given connect */
554 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
556 para[0] = parameters[1];
557 std::string original_command = std::string("CONNECT ") + parameters[1];
558 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
569 /** Every SERVER connection inbound or outbound is represented by
570 * an object of type TreeSocket.
571 * TreeSockets, being inherited from InspSocket, can be tied into
572 * the core socket engine, and we cn therefore receive activity events
573 * for them, just like activex objects on speed. (yes really, that
574 * is a technical term!) Each of these which relates to a locally
575 * connected server is assocated with it, by hooking it onto a
576 * TreeSocket class using its constructor. In this way, we can
577 * maintain a list of servers, some of which are directly connected,
578 * some of which are not.
580 class TreeSocket : public InspSocket
582 SpanningTreeUtilities* Utils;
584 std::string in_buffer;
585 ServerState LinkState;
586 std::string InboundServerName;
587 std::string InboundDescription;
589 int num_lost_servers;
591 bool LastPingWasGood;
595 unsigned int keylength;
596 std::string ModuleList;
597 std::map<std::string,std::string> CapKeys;
601 /** Because most of the I/O gubbins are encapsulated within
602 * InspSocket, we just call the superclass constructor for
603 * most of the action, and append a few of our own values
606 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
607 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
610 this->LinkState = LISTENER;
612 this->ctx_out = NULL;
615 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
616 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
619 this->LinkState = CONNECTING;
621 this->ctx_out = NULL;
624 /** When a listening socket gives us a new file descriptor,
625 * we must associate it with a socket without creating a new
626 * connection. This constructor is used for this purpose.
628 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip)
629 : InspSocket(SI, newfd, ip), Utils(Util)
631 this->LinkState = WAIT_AUTH_1;
633 this->ctx_out = NULL;
634 this->SendCapabilities();
645 void InitAES(std::string key,std::string SName)
652 Instance->Log(DEBUG,"Initialized AES key %s",key.c_str());
653 // key must be 16, 24, 32 etc bytes (multiple of 8)
654 keylength = key.length();
655 if (!(keylength == 16 || keylength == 24 || keylength == 32))
657 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
658 Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
662 if (this->GetState() != I_ERROR)
664 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
665 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\
666 \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);
667 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\
668 \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);
673 /** When an outbound connection finishes connecting, we receive
674 * this event, and must send our SERVER string to the other
675 * side. If the other side is happy, as outlined in the server
676 * to server docs on the inspircd.org site, the other side
677 * will then send back its own server string.
679 virtual bool OnConnected()
681 if (this->LinkState == CONNECTING)
683 /* we do not need to change state here. */
684 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
686 if (x->Name == this->myhost)
688 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
689 this->SendCapabilities();
690 if (x->EncryptionKey != "")
692 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
694 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.");
698 this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
699 this->InitAES(x->EncryptionKey,x->Name.c_str());
702 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
703 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
708 /* There is a (remote) chance that between the /CONNECT and the connection
709 * being accepted, some muppet has removed the <link> block and rehashed.
710 * If that happens the connection hangs here until it's closed. Unlikely
711 * and rather harmless.
713 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
717 virtual void OnError(InspSocketError e)
719 /* We don't handle this method, because all our
720 * dirty work is done in OnClose() (see below)
721 * which is still called on error conditions too.
723 if (e == I_ERR_CONNECT)
725 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
726 Link* MyLink = Utils->FindLink(myhost);
728 Utils->DoFailOver(MyLink);
732 virtual int OnDisconnect()
734 /* For the same reason as above, we don't
735 * handle OnDisconnect()
740 /** Recursively send the server tree with distances as hops.
741 * This is used during network burst to inform the other server
742 * (and any of ITS servers too) of what servers we know about.
743 * If at any point any of these servers already exist on the other
744 * end, our connection may be terminated. The hopcounts given
745 * by this function are relative, this doesn't matter so long as
746 * they are all >1, as all the remote servers re-calculate them
747 * to be relative too, with themselves as hop 0.
749 void SendServers(TreeServer* Current, TreeServer* s, int hops)
752 for (unsigned int q = 0; q < Current->ChildCount(); q++)
754 TreeServer* recursive_server = Current->GetChild(q);
755 if (recursive_server != s)
757 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
758 this->WriteLine(command);
759 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
760 /* down to next level */
761 this->SendServers(recursive_server, s, hops+1);
766 std::string MyCapabilities()
768 std::vector<std::string> modlist;
769 std::string capabilities = "";
771 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
773 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
774 modlist.push_back(this->Instance->Config->module_names[i]);
776 sort(modlist.begin(),modlist.end());
777 for (unsigned int i = 0; i < modlist.size(); i++)
780 capabilities = capabilities + ",";
781 capabilities = capabilities + modlist[i];
786 void SendCapabilities()
788 irc::commasepstream modulelist(MyCapabilities());
790 this->WriteLine("CAPAB START");
792 /* Send module names, split at 509 length */
793 std::string item = "*";
794 std::string line = "CAPAB MODULES ";
795 while ((item = modulelist.GetToken()) != "")
797 if (line.length() + item.length() + 1 > 509)
799 this->WriteLine(line);
800 line = "CAPAB MODULES ";
803 if (line != "CAPAB MODULES ")
808 if (line != "CAPAB MODULES ")
809 this->WriteLine(line);
816 #ifdef SUPPORT_IP6LINKS
819 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));
821 this->WriteLine("CAPAB END");
824 /* Check a comma seperated list for an item */
825 bool HasItem(const std::string &list, const std::string &item)
827 irc::commasepstream seplist(list);
829 std::string item2 = "*";
830 while ((item2 = seplist.GetToken()) != "")
839 /* Isolate and return the elements that are different between two comma seperated lists */
840 std::string ListDifference(const std::string &one, const std::string &two)
842 irc::commasepstream list_one(one);
843 std::string item = "*";
844 std::string result = "";
845 while ((item = list_one.GetToken()) != "")
847 if (!HasItem(two, item))
856 bool Capab(std::deque<std::string> params)
858 if (params.size() < 1)
860 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
864 if (params[0] == "START")
866 this->ModuleList = "";
867 this->CapKeys.clear();
869 else if (params[0] == "END")
871 std::string reason = "";
873 #ifdef SUPPORT_IP6LINKS
876 /* Compare ModuleList and check CapKeys...
877 * Maybe this could be tidier? -- Brain
879 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
881 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
884 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
888 diff = "this server:" + diff;
890 if (diff.length() == 12)
891 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
893 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
896 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
897 reason = "We don't both support linking to IPV6 servers";
899 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
900 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
902 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
903 reason = "Maximum nickname lengths differ or remote nickname length not specified";
905 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
907 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
909 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
913 reason = "Protocol version not specified";
917 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))))
918 reason = "We don't both have halfop support enabled/disabled identically";
920 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
921 reason = "Maximum ident lengths differ or remote ident length not specified";
923 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
924 reason = "Maximum channel lengths differ or remote channel length not specified";
926 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
927 reason = "Maximum modes per line differ or remote modes per line not specified";
929 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
930 reason = "Maximum quit lengths differ or remote quit length not specified";
932 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
933 reason = "Maximum topic lengths differ or remote topic length not specified";
935 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
936 reason = "Maximum kick lengths differ or remote kick length not specified";
938 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
939 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
941 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
942 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
946 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
950 else if ((params[0] == "MODULES") && (params.size() == 2))
952 if (!this->ModuleList.length())
954 this->ModuleList.append(params[1]);
958 this->ModuleList.append(",");
959 this->ModuleList.append(params[1]);
962 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
964 irc::tokenstream capabs(params[1]);
965 std::string item = "*";
966 while ((item = capabs.GetToken()) != "")
968 /* Process each key/value pair */
969 std::string::size_type equals = item.rfind('=');
970 if (equals != std::string::npos)
972 std::string var = item.substr(0, equals);
973 std::string value = item.substr(equals+1, item.length());
974 this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
975 CapKeys[var] = value;
983 /** This function forces this server to quit, removing this server
984 * and any users on it (and servers and users below that, etc etc).
985 * It's very slow and pretty clunky, but luckily unless your network
986 * is having a REAL bad hair day, this function shouldnt be called
987 * too many times a month ;-)
989 void SquitServer(std::string &from, TreeServer* Current)
991 /* recursively squit the servers attached to 'Current'.
992 * We're going backwards so we don't remove users
993 * while we still need them ;)
995 for (unsigned int q = 0; q < Current->ChildCount(); q++)
997 TreeServer* recursive_server = Current->GetChild(q);
998 this->SquitServer(from,recursive_server);
1000 /* Now we've whacked the kids, whack self */
1002 num_lost_users += Current->QuitUsers(from);
1005 /** This is a wrapper function for SquitServer above, which
1006 * does some validation first and passes on the SQUIT to all
1007 * other remaining servers.
1009 void Squit(TreeServer* Current,std::string reason)
1011 if ((Current) && (Current != Utils->TreeRoot))
1013 std::deque<std::string> params;
1014 params.push_back(Current->GetName());
1015 params.push_back(":"+reason);
1016 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1017 if (Current->GetParent() == Utils->TreeRoot)
1019 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1023 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1025 num_lost_servers = 0;
1027 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1028 SquitServer(from, Current);
1030 Current->GetParent()->DelChild(Current);
1032 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1036 Instance->Log(DEFAULT,"Squit from unknown server");
1040 /** FMODE command - server mode with timestamp checks */
1041 bool ForceMode(std::string source, std::deque<std::string> ¶ms)
1043 /* Chances are this is a 1.0 FMODE without TS */
1044 if (params.size() < 3)
1046 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
1051 std::string sourceserv;
1053 /* Are we dealing with an FMODE from a user, or from a server? */
1054 userrec* who = this->Instance->FindNick(source);
1057 /* FMODE from a user, set sourceserv to the users server name */
1058 sourceserv = who->server;
1062 /* FMODE from a server, create a fake user to receive mode feedback */
1063 who = new userrec(this->Instance);
1064 who->SetFd(FD_MAGIC_NUMBER);
1065 smode = true; /* Setting this flag tells us we should free the userrec later */
1066 sourceserv = source; /* Set sourceserv to the actual source string */
1068 const char* modelist[64];
1071 memset(&modelist,0,sizeof(modelist));
1072 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1076 /* The timestamp is in this position.
1077 * We don't want to pass that up to the
1078 * server->client protocol!
1080 TS = atoi(params[q].c_str());
1084 /* Everything else is fine to append to the modelist */
1085 modelist[n++] = params[q].c_str();
1089 /* Extract the TS value of the object, either userrec or chanrec */
1090 userrec* dst = this->Instance->FindNick(params[0]);
1091 chanrec* chan = NULL;
1099 chan = this->Instance->FindChan(params[0]);
1105 /* Oops, channel doesnt exist! */
1109 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1114 Instance->Log(DEBUG,"Entering TS equality check");
1115 ModeHandler* mh = NULL;
1116 unsigned long paramptr = 3;
1117 std::string to_bounce = "";
1118 std::string to_keep = "";
1119 std::vector<std::string> params_to_keep;
1120 std::string params_to_bounce = "";
1122 char cur_change = 1;
1123 char old_change = 0;
1124 char old_bounce_change = 0;
1125 /* Merge modes, basically do special stuff to mode with params */
1126 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1139 /* We only care about whats being set,
1140 * not whats being unset
1142 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1144 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1146 /* We only want to do special things to
1147 * modes with parameters, we are going to rewrite
1151 adding ? cur_change = '+' : cur_change = '-';
1153 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1155 /* The mode is set here, check which we should keep */
1158 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1160 if (which_to_keep == true)
1162 /* Keep ours, bounce theirs:
1163 * Send back ours to them and
1164 * drop their mode changs
1166 adding ? cur_change = '+' : cur_change = '-';
1167 if (cur_change != old_bounce_change)
1168 to_bounce += cur_change;
1170 old_bounce_change = cur_change;
1172 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1173 params_to_bounce.append(" ").append(ret.second);
1177 /* Keep theirs: Accept their mode change,
1180 adding ? cur_change = '+' : cur_change = '-';
1181 if (cur_change != old_change)
1182 to_keep += cur_change;
1184 old_change = cur_change;
1186 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1187 params_to_keep.push_back(params[paramptr]);
1192 /* Mode isnt set here, we want it */
1193 adding ? cur_change = '+' : cur_change = '-';
1194 if (cur_change != old_change)
1195 to_keep += cur_change;
1197 old_change = cur_change;
1199 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1200 params_to_keep.push_back(params[paramptr]);
1207 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1211 adding ? cur_change = '+' : cur_change = '-';
1213 /* Just keep this, safe to merge with no checks
1214 * it has no parameters
1217 if (cur_change != old_change)
1218 to_keep += cur_change;
1220 old_change = cur_change;
1222 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1224 Instance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1225 params_to_keep.push_back(params[paramptr++]);
1232 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1236 /* Taking a mode away */
1237 adding ? cur_change = '+' : cur_change = '-';
1239 if (cur_change != old_change)
1240 to_keep += cur_change;
1242 old_change = cur_change;
1244 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1245 params_to_keep.push_back(params[paramptr++]);
1252 if (to_bounce.length())
1254 std::deque<std::string> newparams;
1255 newparams.push_back(params[0]);
1256 newparams.push_back(ConvToStr(ourTS));
1257 newparams.push_back(to_bounce+params_to_bounce);
1258 Instance->Log(DEBUG,"BOUNCE BACK: %s",(to_bounce+params_to_bounce).c_str());
1259 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1262 if (to_keep.length())
1266 modelist[0] = params[0].c_str();
1267 modelist[1] = to_keep.c_str();
1269 if (params_to_keep.size() > 0)
1271 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1273 Instance->Log(DEBUG,"KEEP Item %d of %d: %s", q, params_to_keep.size(), params_to_keep[q].c_str());
1274 modelist[n++] = params_to_keep[q].c_str();
1280 Instance->Log(DEBUG,"Send mode");
1281 this->Instance->SendMode(modelist, n, who);
1285 Instance->Log(DEBUG,"Send mode client");
1286 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1289 /* HOT POTATO! PASS IT ON! */
1290 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1294 /* U-lined servers always win regardless of their TS */
1295 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1297 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1298 * SHOULD accept it, if its clock is right.
1300 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1301 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1302 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1304 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1305 * writing the code. It took me a while to come up with this solution.
1307 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1310 std::deque<std::string> newparams; /* New parameter list we send back */
1311 newparams.push_back(params[0]); /* Target, user or channel */
1312 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1313 newparams.push_back(""); /* This contains the mode string. For now
1314 * it's empty, we fill it below.
1317 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1318 * set to avoid a desync here.
1320 std::string modebounce = "";
1323 ModeHandler* mh = NULL;
1324 char cur_change = 1;
1325 char old_change = 0;
1326 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1328 /* Iterate over all mode chars in the sent set */
1331 /* Adding or subtracting modes? */
1339 /* Find the mode handler for this mode */
1340 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1342 /* Got a mode handler?
1343 * This also prevents us bouncing modes we have no handler for.
1350 /* Does the mode require a parameter right now?
1351 * If it does, fetch it if we can
1353 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1356 /* Call the ModeSet method to determine if its set with the
1357 * given parameter here or not.
1359 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1361 /* XXX: Really. Dont ask.
1362 * Determine from if its set combined with what the current
1363 * 'state' is (adding or not) as to wether we should 'invert'
1364 * or 'reinforce' the mode change
1366 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1368 /* Quickly determine if we have 'flipped' from + to -,
1369 * or - to +, to prevent unneccessary +/- chars in the
1370 * output string that waste bandwidth
1372 if (cur_change != old_change)
1373 modebounce += cur_change;
1374 old_change = cur_change;
1376 /* Add the mode character to the output string */
1377 modebounce += mh->GetModeChar();
1379 /* We got a parameter back from ModeHandler::ModeSet,
1380 * are we supposed to be sending one out right now?
1382 if (ret.second.length())
1384 if (mh->GetNumParams(cur_change == '+') > 0)
1385 /* Yes we're supposed to be sending out
1386 * the parameter. Make sure it goes
1388 newparams.push_back(ret.second);
1396 /* Update the parameters for FMODE with the new 'bounced' string */
1397 newparams[2] = modebounce;
1398 /* Only send it back the way it came, no need to send it anywhere else */
1399 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1400 Instance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1404 Instance->Log(DEBUG,"Allow modes, TS lower for sender");
1405 /* The server was ulined, but something iffy is up with the TS.
1406 * Sound the alarm bells!
1408 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1410 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());
1412 /* Allow the mode, route it to either server or user command handling */
1414 this->Instance->SendMode(modelist,n,who);
1416 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1418 /* HOT POTATO! PASS IT ON! */
1419 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1421 /* Are we supposed to free the userrec? */
1428 /** FTOPIC command */
1429 bool ForceTopic(std::string source, std::deque<std::string> ¶ms)
1431 if (params.size() != 4)
1433 time_t ts = atoi(params[1].c_str());
1434 std::string nsource = source;
1436 chanrec* c = this->Instance->FindChan(params[0]);
1439 if ((ts >= c->topicset) || (!*c->topic))
1441 std::string oldtopic = c->topic;
1442 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1443 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1445 /* if the topic text is the same as the current topic,
1446 * dont bother to send the TOPIC command out, just silently
1447 * update the set time and set nick.
1449 if (oldtopic != params[3])
1451 userrec* user = this->Instance->FindNick(source);
1454 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1458 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1459 nsource = user->server;
1461 /* all done, send it on its way */
1462 params[3] = ":" + params[3];
1463 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1472 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1473 bool ForceJoin(std::string source, std::deque<std::string> ¶ms)
1475 /* 1.1 FJOIN works as follows:
1477 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1478 * timestamp 'wins'. From this point on we will refer to this side as the
1479 * winner. The side with the higher timestamp loses, from this point on we
1480 * will call this side the loser or losing side. This should be familiar to
1481 * anyone who's dealt with dreamforge or TS6 before.
1483 * When two sides of a split heal and this occurs, the following things
1486 * If the timestamps are exactly equal, both sides merge their privilages
1487 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1488 * re-created during a split, this is safe to do.
1491 * If the timestamps are NOT equal, the losing side removes all privilage
1492 * modes from all of its users that currently exist in the channel, before
1493 * introducing new users into the channel which are listed in the FJOIN
1494 * command's parameters. This means, all modes +ohv, and privilages added
1495 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1496 * of the channel to match that of the winning side, and the modes of the
1497 * users of the winning side are merged in with the losing side. The loser
1498 * then sends out a set of FMODE commands which 'confirm' that it just
1499 * removed all privilage modes from its existing users, which allows for
1500 * services packages to still work correctly without needing to know the
1501 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1502 * a problem, and services packages must contain code which explicitly
1503 * behaves as TS6 does, removing ops from the losing side of a split where
1504 * neccessary within its internal records, as this state information is
1505 * not explicitly echoed out in that protocol.
1507 * The winning side on the other hand will ignore all user modes from the
1508 * losing side, so only its own modes get applied. Life is simple for those
1509 * who succeed at internets. :-)
1511 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1512 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1513 * you ask? Well, quite simply because we don't need to. They'll be sent
1514 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1515 * the losing side sends any modes for the channel which shouldnt win,
1516 * they wont as their timestamp will be too high :-)
1519 if (params.size() < 3)
1522 char first[MAXBUF]; /* The first parameter of the mode command */
1523 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1524 char* mode_users[127]; /* The values used by the mode command */
1525 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1526 mode_users[0] = first; /* Set this up to be our on-stack value */
1527 mode_users[1] = modestring; /* Same here as above */
1528 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1529 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1531 userrec* who = NULL; /* User we are currently checking */
1532 std::string channel = params[0]; /* Channel name, as a string */
1533 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1535 /* Try and find the channel */
1536 chanrec* chan = this->Instance->FindChan(channel);
1538 /* Initialize channel name in the mode parameters */
1539 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1541 /* default TS is a high value, which if we dont have this
1542 * channel will let the other side apply their modes.
1544 time_t ourTS = time(NULL)+600;
1546 /* Does this channel exist? if it does, get its REAL timestamp */
1550 /* In 1.1, if they have the newer channel, we immediately clear
1551 * all status modes from our users. We then accept their modes.
1552 * If WE have the newer channel its the other side's job to do this.
1553 * Note that this causes the losing server to send out confirming
1558 std::deque<std::string> param_list;
1563 /* Lower the TS here */
1564 if (Utils->AnnounceTSChange && chan)
1565 chan->WriteChannelWithServ(Instance->Config->ServerName,
1566 "TS for %s changed from %lu to %lu", chan->name, ourTS, TS);
1569 param_list.push_back(channel);
1570 /* Zap all the privilage modes on our side */
1571 this->RemoveStatus(Instance->Config->ServerName, param_list);
1574 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1575 irc::tokenstream users(params[2]);
1576 std::string item = "*";
1578 /* do this first, so our mode reversals are correctly received by other servers
1579 * if there is a TS collision.
1581 params[2] = ":" + params[2];
1582 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1584 /* Now, process every 'prefixes,nick' pair */
1587 /* Find next user */
1588 item = users.GetToken();
1590 const char* usr = item.c_str();
1592 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1593 * (is this even possible?) */
1596 const char* permissions = usr;
1598 char* nm = new char[MAXBUF];
1601 /* Iterate through all the prefix values, convert them from prefixes
1602 * to mode letters, and append them to the mode sequence
1604 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1606 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1609 /* This is a valid prefix */
1611 *tnm++ = mh->GetModeChar();
1615 /* Not a valid prefix...
1616 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1618 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1619 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1626 /* Null terminate modes */
1628 /* Advance past the comma, to the nick */
1631 /* Check the user actually exists */
1632 who = this->Instance->FindNick(usr);
1635 /* Did they get any modes? How many times? */
1636 strlcat(modestring, nm, MAXBUF);
1637 for (int k = 0; k < ntimes; k++)
1638 mode_users[modectr++] = strdup(usr);
1640 /* Free temporary buffer used for mode sequence */
1643 /* Check that the user's 'direction' is correct
1644 * based on the server sending the FJOIN. We must
1645 * check each nickname in turn, because the origin of
1646 * the FJOIN may be different to the origin of the nicks
1647 * in the command itself.
1649 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1650 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1652 /* Oh dear oh dear. */
1653 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1656 /* Finally, we can actually place the user into the channel.
1657 * We're sure its right. Final answer, phone a friend.
1659 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1661 /* Have we already queued up MAXMODES modes with parameters
1662 * (+qaohv) ready to be sent to the server?
1664 if (modectr >= (MAXMODES-1))
1666 /* Only actually give the users any status if we lost
1667 * the FJOIN or drew (equal timestamps).
1668 * It isn't actually possible for ourTS to be > TS here,
1669 * only possible to actually have ourTS == TS, or
1670 * ourTS < TS, because if we lost, we already lowered
1671 * our TS above before we entered this loop. We only
1672 * check >= as a safety measure, in case someone stuffed
1673 * up. If someone DID stuff up, it was most likely me.
1674 * Note: I do not like baseball bats in the face...
1678 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1679 this->Instance->SendMode((const char**)mode_users,modectr,who);
1681 /* Something stuffed up, and for some reason, the timestamp is
1682 * NOT lowered right now and should be. Lower it. Usually this
1683 * code won't be executed, doubtless someone will remove it some
1688 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1694 /* Reset all this back to defaults, and
1695 * free any ram we have left allocated.
1697 strcpy(mode_users[1],"+");
1698 for (unsigned int f = 2; f < modectr; f++)
1699 free(mode_users[f]);
1705 /* Remember to free this */
1707 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1708 * We don't try to process the nickname here (that WOULD cause a segfault because
1709 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1710 * in case somehow we're desynched, so that other users which might be able to see
1711 * the nickname get their fair chance to process it.
1713 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1719 /* there werent enough modes built up to flush it during FJOIN,
1720 * or, there are a number left over. flush them out.
1722 if ((modectr > 2) && (who) && (chan))
1726 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1727 this->Instance->SendMode((const char**)mode_users,modectr,who);
1728 /* Yet again, we can't actually get a true value here, if everything else
1729 * is working as it should.
1733 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1739 /* Free anything we have left to free */
1740 for (unsigned int f = 2; f < modectr; f++)
1741 free(mode_users[f]);
1744 /* All done. That wasnt so bad was it, you can wipe
1745 * the sweat from your forehead now. :-)
1751 bool IntroduceClient(std::string source, std::deque<std::string> ¶ms)
1753 if (params.size() < 8)
1755 if (params.size() > 8)
1757 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1760 // NICK age nick host dhost ident +modes ip :gecos
1762 time_t age = atoi(params[0].c_str());
1764 /* This used to have a pretty craq'y loop doing the same thing,
1765 * now we just let the STL do the hard work (more efficiently)
1767 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1768 if (pos_after_plus != std::string::npos)
1769 params[5] = params[5].substr(pos_after_plus);
1771 const char* tempnick = params[1].c_str();
1772 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1774 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1776 if (iter != this->Instance->clientlist.end())
1779 Instance->Log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,params[4].c_str(),params[2].c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1780 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1781 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1785 userrec* _new = new userrec(this->Instance);
1786 this->Instance->clientlist[tempnick] = _new;
1787 _new->SetFd(FD_MAGIC_NUMBER);
1788 strlcpy(_new->nick, tempnick,NICKMAX-1);
1789 strlcpy(_new->host, params[2].c_str(),63);
1790 strlcpy(_new->dhost, params[3].c_str(),63);
1791 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1792 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1793 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1794 _new->registered = REG_ALL;
1797 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1798 _new->modes[(*v)-65] = 1;
1800 #ifdef SUPPORT_IP6LINKS
1801 if (params[6].find_first_of(":") != std::string::npos)
1802 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1805 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1807 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1809 params[7] = ":" + params[7];
1810 Utils->DoOneToAllButSender(source,"NICK",params,source);
1812 // Increment the Source Servers User Count..
1813 TreeServer* SourceServer = Utils->FindServer(source);
1816 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1817 SourceServer->AddUserCount();
1820 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1825 /** Send one or more FJOINs for a channel of users.
1826 * If the length of a single line is more than 480-NICKMAX
1827 * in length, it is split over multiple lines.
1829 void SendFJoins(TreeServer* Current, chanrec* c)
1831 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1833 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1835 size_t dlen, curlen;
1836 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1838 char* ptr = list + dlen;
1840 CUList *ulist = c->GetUsers();
1841 std::vector<userrec*> specific_halfop;
1842 std::vector<userrec*> specific_voice;
1843 std::string modes = "";
1844 std::string params = "";
1846 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1848 // The first parameter gets a : before it
1849 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1856 if (curlen > (480-NICKMAX))
1858 this->WriteLine(list);
1859 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1867 this->WriteLine(list);
1869 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1872 params.append(b->data).append(" ");
1874 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+c->ChanModes(true)+modes+" "+params);
1877 /** Send G, Q, Z and E lines */
1878 void SendXLines(TreeServer* Current)
1881 std::string n = this->Instance->Config->ServerName;
1882 const char* sn = n.c_str();
1884 /* Yes, these arent too nice looking, but they get the job done */
1885 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1887 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);
1888 this->WriteLine(data);
1890 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1892 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);
1893 this->WriteLine(data);
1895 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1897 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);
1898 this->WriteLine(data);
1900 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1902 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);
1903 this->WriteLine(data);
1905 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
1907 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);
1908 this->WriteLine(data);
1910 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
1912 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);
1913 this->WriteLine(data);
1915 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
1917 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);
1918 this->WriteLine(data);
1920 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
1922 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);
1923 this->WriteLine(data);
1927 /** Send channel modes and topics */
1928 void SendChannelModes(TreeServer* Current)
1931 std::deque<std::string> list;
1933 std::string n = this->Instance->Config->ServerName;
1934 const char* sn = n.c_str();
1935 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
1937 SendFJoins(Current, c->second);
1938 if (*c->second->topic)
1940 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1941 this->WriteLine(data);
1943 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1945 c->second->GetExtList(list);
1946 for (unsigned int j = 0; j < list.size(); j++)
1948 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1953 /** send all users and their oper state/modes */
1954 void SendUsers(TreeServer* Current)
1957 std::deque<std::string> list;
1959 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
1961 if (u->second->registered == REG_ALL)
1963 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);
1964 this->WriteLine(data);
1965 if (*u->second->oper)
1967 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1969 if (*u->second->awaymsg)
1971 this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1973 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
1975 u->second->GetExtList(list);
1976 for (unsigned int j = 0; j < list.size(); j++)
1978 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
1984 /** This function is called when we want to send a netburst to a local
1985 * server. There is a set order we must do this, because for example
1986 * users require their servers to exist, and channels require their
1987 * users to exist. You get the idea.
1989 void DoBurst(TreeServer* s)
1991 std::string burst = "BURST "+ConvToStr(time(NULL));
1992 std::string endburst = "ENDBURST";
1993 // Because by the end of the netburst, it could be gone!
1994 std::string name = s->GetName();
1995 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1996 this->WriteLine(burst);
1997 /* send our version string */
1998 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1999 /* Send server tree */
2000 this->SendServers(Utils->TreeRoot,s,1);
2001 /* Send users and their oper status */
2003 /* Send everything else (channel modes, xlines etc) */
2004 this->SendChannelModes(s);
2005 this->SendXLines(s);
2006 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2007 this->WriteLine(endburst);
2008 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2011 /** This function is called when we receive data from a remote
2012 * server. We buffer the data in a std::string (it doesnt stay
2013 * there for long), reading using InspSocket::Read() which can
2014 * read up to 16 kilobytes in one operation.
2016 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2017 * THE SOCKET OBJECT FOR US.
2019 virtual bool OnDataReady()
2021 char* data = this->Read();
2022 /* Check that the data read is a valid pointer and it has some content */
2025 this->in_buffer.append(data);
2026 /* While there is at least one new line in the buffer,
2027 * do something useful (we hope!) with it.
2029 while (in_buffer.find("\n") != std::string::npos)
2031 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2032 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2033 if (ret.find("\r") != std::string::npos)
2034 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2035 /* Process this one, abort if it
2036 * didnt return true.
2042 memset(result,0,1024);
2044 /* ERROR + CAPAB is still allowed unencryped */
2045 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2047 int nbytes = from64tobits(out, ret.c_str(), 1024);
2048 if ((nbytes > 0) && (nbytes < 1024))
2050 ctx_in->Decrypt(out, result, nbytes, 0);
2051 for (int t = 0; t < nbytes; t++)
2052 if (result[t] == '\7') result[t] = 0;
2057 if (!this->ProcessLine(ret))
2059 Instance->Log(DEBUG,"ProcessLine says no!");
2065 /* EAGAIN returns an empty but non-NULL string, so this
2066 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2068 return (data && !*data);
2071 int WriteLine(std::string line)
2073 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2077 char result64[10240];
2078 if (this->keylength)
2080 // pad it to the key length
2081 int n = this->keylength - (line.length() % this->keylength);
2083 line.append(n,'\7');
2085 unsigned int ll = line.length();
2086 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2087 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2090 return this->Write(line + "\r\n");
2093 /* Handle ERROR command */
2094 bool Error(std::deque<std::string> ¶ms)
2096 if (params.size() < 1)
2098 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2099 /* we will return false to cause the socket to close. */
2103 /** remote MOTD. leet, huh? */
2104 bool Motd(std::string prefix, std::deque<std::string> ¶ms)
2106 if (params.size() > 0)
2108 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2110 /* It's for our server */
2111 string_list results;
2112 userrec* source = this->Instance->FindNick(prefix);
2116 std::deque<std::string> par;
2117 par.push_back(prefix);
2120 if (!Instance->Config->MOTD.size())
2122 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2123 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2127 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2128 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2130 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2132 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2133 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2136 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2137 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2143 userrec* source = this->Instance->FindNick(prefix);
2145 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2151 /** remote ADMIN. leet, huh? */
2152 bool Admin(std::string prefix, std::deque<std::string> ¶ms)
2154 if (params.size() > 0)
2156 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2158 /* It's for our server */
2159 string_list results;
2160 userrec* source = this->Instance->FindNick(prefix);
2164 std::deque<std::string> par;
2165 par.push_back(prefix);
2168 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2169 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2171 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2172 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2174 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2175 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2177 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2178 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2184 userrec* source = this->Instance->FindNick(prefix);
2186 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2192 bool Stats(std::string prefix, std::deque<std::string> ¶ms)
2194 /* Get the reply to a STATS query if it matches this servername,
2195 * and send it back as a load of PUSH queries
2197 if (params.size() > 1)
2199 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2201 /* It's for our server */
2202 string_list results;
2203 userrec* source = this->Instance->FindNick(prefix);
2206 std::deque<std::string> par;
2207 par.push_back(prefix);
2209 DoStats(this->Instance, *(params[0].c_str()), source, results);
2210 for (size_t i = 0; i < results.size(); i++)
2212 par[1] = "::" + results[i];
2213 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2220 userrec* source = this->Instance->FindNick(prefix);
2222 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2229 /** Because the core won't let users or even SERVERS set +o,
2230 * we use the OPERTYPE command to do this.
2232 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
2234 if (params.size() != 1)
2236 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2239 std::string opertype = params[0];
2240 userrec* u = this->Instance->FindNick(prefix);
2243 u->modes[UM_OPERATOR] = 1;
2244 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2245 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2250 /** Because Andy insists that services-compatible servers must
2251 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2253 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
2255 if (params.size() < 3)
2258 userrec* u = this->Instance->FindNick(params[0]);
2262 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2265 std::deque<std::string> par;
2266 par.push_back(params[1]);
2267 /* This is not required as one is sent in OnUserPostNick below
2269 //Utils->DoOneToMany(u->nick,"NICK",par);
2270 if (!u->ForceNickChange(params[1].c_str()))
2272 userrec::QuitUser(this->Instance, u, "Nickname collision");
2275 u->age = atoi(params[2].c_str());
2281 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
2283 if (params.size() < 2)
2286 userrec* u = this->Instance->FindNick(params[0]);
2290 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2291 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2296 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
2298 if (params.size() < 1)
2301 std::string servermask = params[0];
2303 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2305 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2306 this->Instance->RehashServer();
2307 Utils->ReadConfiguration(false);
2308 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2310 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2314 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
2316 if (params.size() != 2)
2319 std::string nick = params[0];
2320 userrec* u = this->Instance->FindNick(prefix);
2321 userrec* who = this->Instance->FindNick(nick);
2325 /* Prepend kill source, if we don't have one */
2326 std::string sourceserv = prefix;
2329 sourceserv = u->server;
2331 if (*(params[1].c_str()) != '[')
2333 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2335 std::string reason = params[1];
2336 params[1] = ":" + params[1];
2337 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2338 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2339 userrec::QuitUser(this->Instance,who,reason);
2344 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
2346 if (params.size() < 1)
2349 if (params.size() == 1)
2351 TreeServer* ServerSource = Utils->FindServer(prefix);
2354 ServerSource->SetPingFlag();
2359 std::string forwardto = params[1];
2360 if (forwardto == this->Instance->Config->ServerName)
2363 * this is a PONG for us
2364 * if the prefix is a user, check theyre local, and if they are,
2365 * dump the PONG reply back to their fd. If its a server, do nowt.
2366 * Services might want to send these s->s, but we dont need to yet.
2368 userrec* u = this->Instance->FindNick(prefix);
2372 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2377 // not for us, pass it on :)
2378 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2385 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
2387 if (params.size() < 3)
2390 TreeServer* ServerSource = Utils->FindServer(prefix);
2394 if (params[0] == "*")
2396 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2398 else if (*(params[0].c_str()) == '#')
2400 chanrec* c = this->Instance->FindChan(params[0]);
2403 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2406 else if (*(params[0].c_str()) != '#')
2408 userrec* u = this->Instance->FindNick(params[0]);
2411 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2416 params[2] = ":" + params[2];
2417 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2421 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
2423 if (params.size() < 1)
2426 TreeServer* ServerSource = Utils->FindServer(prefix);
2430 ServerSource->SetVersion(params[0]);
2432 params[0] = ":" + params[0];
2433 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2437 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
2439 if (params.size() < 1)
2442 userrec* u = this->Instance->FindNick(prefix);
2446 u->ChangeDisplayedHost(params[0].c_str());
2447 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2452 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
2454 if (params.size() < 6)
2457 bool propogate = false;
2459 switch (*(params[0].c_str()))
2462 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2463 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2466 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2467 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2470 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2471 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2474 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2475 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2478 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2481 /* Just in case... */
2482 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2487 /* Send it on its way */
2490 if (atoi(params[4].c_str()))
2492 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());
2496 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());
2498 params[5] = ":" + params[5];
2499 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2501 if (!this->bursting)
2503 Instance->Log(DEBUG,"Applying lines...");
2504 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2509 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
2511 if (params.size() < 1)
2514 userrec* u = this->Instance->FindNick(prefix);
2518 u->ChangeName(params[0].c_str());
2519 params[0] = ":" + params[0];
2520 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2525 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
2527 if (params.size() < 1)
2530 Instance->Log(DEBUG,"In IDLE command");
2531 userrec* u = this->Instance->FindNick(prefix);
2535 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2536 // an incoming request
2537 if (params.size() == 1)
2539 userrec* x = this->Instance->FindNick(params[0]);
2540 if ((x) && (IS_LOCAL(x)))
2542 userrec* x = this->Instance->FindNick(params[0]);
2543 char signon[MAXBUF];
2546 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2547 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2548 std::deque<std::string> par;
2549 par.push_back(prefix);
2550 par.push_back(signon);
2551 par.push_back(idle);
2552 // ours, we're done, pass it BACK
2553 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2557 // not ours pass it on
2558 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2561 else if (params.size() == 3)
2563 std::string who_did_the_whois = params[0];
2564 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2565 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2567 // an incoming reply to a whois we sent out
2568 std::string nick_whoised = prefix;
2569 unsigned long signon = atoi(params[1].c_str());
2570 unsigned long idle = atoi(params[2].c_str());
2571 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2572 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2576 // not ours, pass it on
2577 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2584 bool Push(std::string prefix, std::deque<std::string> ¶ms)
2586 if (params.size() < 2)
2589 userrec* u = this->Instance->FindNick(params[0]);
2596 u->Write(params[1]);
2600 // continue the raw onwards
2601 params[1] = ":" + params[1];
2602 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2607 bool Time(std::string prefix, std::deque<std::string> ¶ms)
2609 // :source.server TIME remote.server sendernick
2610 // :remote.server TIME source.server sendernick TS
2611 if (params.size() == 2)
2613 // someone querying our time?
2614 if (this->Instance->Config->ServerName == params[0])
2616 userrec* u = this->Instance->FindNick(params[1]);
2620 snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2621 params.push_back(curtime);
2623 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2628 // not us, pass it on
2629 userrec* u = this->Instance->FindNick(params[1]);
2631 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2634 else if (params.size() == 3)
2636 // a response to a previous TIME
2637 userrec* u = this->Instance->FindNick(params[1]);
2638 if ((u) && (IS_LOCAL(u)))
2640 time_t rawtime = atol(params[2].c_str());
2641 struct tm * timeinfo;
2642 timeinfo = localtime(&rawtime);
2644 snprintf(tms,26,"%s",asctime(timeinfo));
2646 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2651 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2657 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
2659 if (params.size() < 1)
2662 if (params.size() == 1)
2664 std::string stufftobounce = params[0];
2665 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2670 std::string forwardto = params[1];
2671 if (forwardto == this->Instance->Config->ServerName)
2673 // this is a ping for us, send back PONG to the requesting server
2674 params[1] = params[0];
2675 params[0] = forwardto;
2676 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2680 // not for us, pass it on :)
2681 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2687 bool RemoveStatus(std::string prefix, std::deque<std::string> ¶ms)
2689 if (params.size() < 1)
2692 chanrec* c = Instance->FindChan(params[0]);
2696 irc::modestacker modestack(false);
2697 CUList *ulist = c->GetUsers();
2699 std::deque<std::string> stackresult;
2702 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2704 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2705 if (modesequence.length())
2707 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2708 irc::spacesepstream sep(modesequence);
2709 std::string modeletters = sep.GetToken();
2710 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2712 while (!modeletters.empty())
2714 char mletter = *(modeletters.begin());
2715 modestack.Push(mletter,sep.GetToken());
2716 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2717 modeletters.erase(modeletters.begin());
2718 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2723 while (modestack.GetStackedLine(stackresult))
2725 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2726 stackresult.push_front(ConvToStr(c->age));
2727 stackresult.push_front(c->name);
2728 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2729 stackresult.erase(stackresult.begin() + 1);
2730 Instance->Log(DEBUG,"Stacked items:");
2731 for (size_t z = 0; z < stackresult.size(); z++)
2733 y[z] = stackresult[z].c_str();
2734 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2736 userrec* n = new userrec(Instance);
2737 n->SetFd(FD_MAGIC_NUMBER);
2738 Instance->SendMode(y, stackresult.size(), n);
2745 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
2747 if (params.size() < 4)
2750 std::string servername = params[0];
2751 std::string password = params[1];
2752 // hopcount is not used for a remote server, we calculate this ourselves
2753 std::string description = params[3];
2754 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2758 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2761 TreeServer* CheckDupe = Utils->FindServer(servername);
2764 this->WriteLine("ERROR :Server "+servername+" already exists!");
2765 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2768 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2769 ParentOfThis->AddChild(Node);
2770 params[3] = ":" + params[3];
2771 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2772 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2776 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2778 if (params.size() < 4)
2781 irc::string servername = params[0].c_str();
2782 std::string sname = params[0];
2783 std::string password = params[1];
2784 int hops = atoi(params[2].c_str());
2788 this->WriteLine("ERROR :Server too far away for authentication");
2789 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2792 std::string description = params[3];
2793 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2795 if ((x->Name == servername) && (x->RecvPass == password))
2797 TreeServer* CheckDupe = Utils->FindServer(sname);
2800 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2801 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2804 // Begin the sync here. this kickstarts the
2805 // other side, waiting in WAIT_AUTH_2 state,
2806 // into starting their burst, as it shows
2807 // that we're happy.
2808 this->LinkState = CONNECTED;
2809 // we should add the details of this server now
2810 // to the servers tree, as a child of the root
2812 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2813 Utils->TreeRoot->AddChild(Node);
2814 params[3] = ":" + params[3];
2815 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2816 this->bursting = true;
2817 this->DoBurst(Node);
2821 this->WriteLine("ERROR :Invalid credentials");
2822 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2826 bool Inbound_Server(std::deque<std::string> ¶ms)
2828 if (params.size() < 4)
2831 irc::string servername = params[0].c_str();
2832 std::string sname = params[0];
2833 std::string password = params[1];
2834 int hops = atoi(params[2].c_str());
2838 this->WriteLine("ERROR :Server too far away for authentication");
2839 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2842 std::string description = params[3];
2843 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2845 if ((x->Name == servername) && (x->RecvPass == password))
2847 TreeServer* CheckDupe = Utils->FindServer(sname);
2850 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2851 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2854 /* If the config says this link is encrypted, but the remote side
2855 * hasnt bothered to send the AES command before SERVER, then we
2856 * boot them off as we MUST have this connection encrypted.
2858 if ((x->EncryptionKey != "") && (!this->ctx_in))
2860 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2861 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2864 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2865 this->InboundServerName = sname;
2866 this->InboundDescription = description;
2867 // this is good. Send our details: Our server name and description and hopcount of 0,
2868 // along with the sendpass from this block.
2869 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2870 // move to the next state, we are now waiting for THEM.
2871 this->LinkState = WAIT_AUTH_2;
2875 this->WriteLine("ERROR :Invalid credentials");
2876 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2880 void Split(std::string line, std::deque<std::string> &n)
2883 irc::tokenstream tokens(line);
2885 while ((param = tokens.GetToken()) != "")
2890 bool ProcessLine(std::string line)
2892 std::deque<std::string> params;
2893 irc::string command;
2899 line = line.substr(0, line.find_first_of("\r\n"));
2901 Instance->Log(DEBUG,"IN: %s", line.c_str());
2903 this->Split(line.c_str(),params);
2905 if ((params[0][0] == ':') && (params.size() > 1))
2907 prefix = params[0].substr(1);
2911 command = params[0].c_str();
2914 if ((!this->ctx_in) && (command == "AES"))
2916 std::string sserv = params[0];
2917 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2919 if ((x->EncryptionKey != "") && (x->Name == sserv))
2921 this->InitAES(x->EncryptionKey,sserv);
2927 else if ((this->ctx_in) && (command == "AES"))
2929 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());
2932 switch (this->LinkState)
2937 // Waiting for SERVER command from remote server. Server initiating
2938 // the connection sends the first SERVER command, listening server
2939 // replies with theirs if its happy, then if the initiator is happy,
2940 // it starts to send its net sync, which starts the merge, otherwise
2941 // it sends an ERROR.
2942 if (command == "PASS")
2944 /* Silently ignored */
2946 else if (command == "SERVER")
2948 return this->Inbound_Server(params);
2950 else if (command == "ERROR")
2952 return this->Error(params);
2954 else if (command == "USER")
2956 this->WriteLine("ERROR :Client connections to this port are prohibited.");
2959 else if (command == "CAPAB")
2961 return this->Capab(params);
2963 else if ((command == "U") || (command == "S"))
2965 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2970 std::string error("ERROR :Invalid command in negotiation phase: ");
2971 error.append(command.c_str());
2972 this->WriteLine(error);
2977 // Waiting for start of other side's netmerge to say they liked our
2979 if (command == "SERVER")
2981 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2985 else if ((command == "U") || (command == "S"))
2987 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2990 else if (command == "BURST")
2994 /* If a time stamp is provided, try and check syncronization */
2995 time_t THEM = atoi(params[0].c_str());
2996 long delta = THEM-time(NULL);
2997 if ((delta < -600) || (delta > 600))
2999 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));
3000 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3003 else if ((delta < -60) || (delta > 60))
3005 this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
3008 this->LinkState = CONNECTED;
3009 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3010 Utils->TreeRoot->AddChild(Node);
3012 params.push_back(InboundServerName);
3013 params.push_back("*");
3014 params.push_back("1");
3015 params.push_back(":"+InboundDescription);
3016 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3017 this->bursting = true;
3018 this->DoBurst(Node);
3020 else if (command == "ERROR")
3022 return this->Error(params);
3024 else if (command == "CAPAB")
3026 return this->Capab(params);
3031 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3035 if (command == "SERVER")
3037 // another server we connected to, which was in WAIT_AUTH_1 state,
3038 // has just sent us their credentials. If we get this far, theyre
3039 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3040 // if we're happy with this, we should send our netburst which
3041 // kickstarts the merge.
3042 return this->Outbound_Reply_Server(params);
3044 else if (command == "ERROR")
3046 return this->Error(params);
3050 // This is the 'authenticated' state, when all passwords
3051 // have been exchanged and anything past this point is taken
3056 std::string direction = prefix;
3057 userrec* t = this->Instance->FindNick(prefix);
3060 direction = t->server;
3062 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3063 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3065 if (route_back_again)
3066 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3071 * When there is activity on the socket, reset the ping counter so
3072 * that we're not wasting bandwidth pinging an active server.
3074 route_back_again->SetNextPingTime(time(NULL) + 60);
3075 route_back_again->SetPingFlag();
3078 if (command == "SVSMODE")
3080 /* Services expects us to implement
3081 * SVSMODE. In inspircd its the same as
3086 std::string target = "";
3087 /* Yes, know, this is a mess. Its reasonably fast though as we're
3088 * working with std::string here.
3090 if ((command == "NICK") && (params.size() > 1))
3092 return this->IntroduceClient(prefix,params);
3094 else if (command == "FJOIN")
3096 return this->ForceJoin(prefix,params);
3098 else if (command == "STATS")
3100 return this->Stats(prefix, params);
3102 else if (command == "MOTD")
3104 return this->Motd(prefix, params);
3106 else if (command == "ADMIN")
3108 return this->Admin(prefix, params);
3110 else if (command == "SERVER")
3112 return this->RemoteServer(prefix,params);
3114 else if (command == "ERROR")
3116 return this->Error(params);
3118 else if (command == "OPERTYPE")
3120 return this->OperType(prefix,params);
3122 else if (command == "FMODE")
3124 return this->ForceMode(prefix,params);
3126 else if (command == "KILL")
3128 return this->RemoteKill(prefix,params);
3130 else if (command == "FTOPIC")
3132 return this->ForceTopic(prefix,params);
3134 else if (command == "REHASH")
3136 return this->RemoteRehash(prefix,params);
3138 else if (command == "METADATA")
3140 return this->MetaData(prefix,params);
3142 else if (command == "REMSTATUS")
3144 return this->RemoveStatus(prefix,params);
3146 else if (command == "PING")
3149 * We just got a ping from a server that's bursting.
3150 * This can't be right, so set them to not bursting, and
3151 * apply their lines.
3155 this->bursting = false;
3156 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3160 prefix = this->GetName();
3162 return this->LocalPing(prefix,params);
3164 else if (command == "PONG")
3167 * We just got a pong from a server that's bursting.
3168 * This can't be right, so set them to not bursting, and
3169 * apply their lines.
3173 this->bursting = false;
3174 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3178 prefix = this->GetName();
3180 return this->LocalPong(prefix,params);
3182 else if (command == "VERSION")
3184 return this->ServerVersion(prefix,params);
3186 else if (command == "FHOST")
3188 return this->ChangeHost(prefix,params);
3190 else if (command == "FNAME")
3192 return this->ChangeName(prefix,params);
3194 else if (command == "ADDLINE")
3196 return this->AddLine(prefix,params);
3198 else if (command == "SVSNICK")
3202 prefix = this->GetName();
3204 return this->ForceNick(prefix,params);
3206 else if (command == "IDLE")
3208 return this->Whois(prefix,params);
3210 else if (command == "PUSH")
3212 return this->Push(prefix,params);
3214 else if (command == "TIME")
3216 return this->Time(prefix,params);
3218 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3220 std::string sourceserv = this->myhost;
3221 if (params.size() == 3)
3223 userrec* user = this->Instance->FindNick(params[1]);
3224 chanrec* chan = this->Instance->FindChan(params[0]);
3227 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3228 /* Yikes, the channels gone! */
3232 if (this->InboundServerName != "")
3234 sourceserv = this->InboundServerName;
3236 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3238 else if (command == "SVSJOIN")
3242 prefix = this->GetName();
3244 return this->ServiceJoin(prefix,params);
3246 else if (command == "SQUIT")
3248 if (params.size() == 2)
3250 this->Squit(Utils->FindServer(params[0]),params[1]);
3254 else if (command == "ENDBURST")
3256 this->bursting = false;
3257 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3258 std::string sourceserv = this->myhost;
3259 if (this->InboundServerName != "")
3261 sourceserv = this->InboundServerName;
3263 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3268 // not a special inter-server command.
3269 // Emulate the actual user doing the command,
3270 // this saves us having a huge ugly parser.
3271 userrec* who = this->Instance->FindNick(prefix);
3272 std::string sourceserv = this->myhost;
3273 if (this->InboundServerName != "")
3275 sourceserv = this->InboundServerName;
3279 if ((command == "NICK") && (params.size() > 0))
3281 /* On nick messages, check that the nick doesnt
3282 * already exist here. If it does, kill their copy,
3285 userrec* x = this->Instance->FindNick(params[0]);
3286 if ((x) && (x != who))
3288 std::deque<std::string> p;
3289 p.push_back(params[0]);
3290 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3291 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3293 p.push_back(prefix);
3294 p.push_back("Nickname collision");
3295 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3296 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3297 userrec* y = this->Instance->FindNick(prefix);
3300 userrec::QuitUser(this->Instance,y,"Nickname collision");
3302 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3306 target = who->server;
3307 const char* strparams[127];
3308 for (unsigned int q = 0; q < params.size(); q++)
3310 strparams[q] = params[q].c_str();
3312 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3315 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3322 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3328 // its not a user. Its either a server, or somethings screwed up.
3329 if (Utils->IsServer(prefix))
3331 target = this->Instance->Config->ServerName;
3335 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3339 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3348 virtual std::string GetName()
3350 std::string sourceserv = this->myhost;
3351 if (this->InboundServerName != "")
3353 sourceserv = this->InboundServerName;
3358 virtual void OnTimeout()
3360 if (this->LinkState == CONNECTING)
3362 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3363 Link* MyLink = Utils->FindLink(myhost);
3365 Utils->DoFailOver(MyLink);
3369 virtual void OnClose()
3371 // Connection closed.
3372 // If the connection is fully up (state CONNECTED)
3373 // then propogate a netsplit to all peers.
3374 std::string quitserver = this->myhost;
3375 if (this->InboundServerName != "")
3377 quitserver = this->InboundServerName;
3379 TreeServer* s = Utils->FindServer(quitserver);
3382 Squit(s,"Remote host closed the connection");
3384 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3387 virtual int OnIncomingConnection(int newsock, char* ip)
3389 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3390 * or discovering if this port is the server port, we don't allow connections from any
3391 * IPs for which we don't have a link block.
3395 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3398 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3399 if (MatchCIDR(ip, (*i).c_str()))
3404 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3409 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3410 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3415 /** This class is used to resolve server hostnames during /connect and autoconnect.
3416 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3417 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3418 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3419 * will have an IP address which we can then use to continue our connection.
3421 class ServernameResolver : public Resolver
3424 /** A copy of the Link tag info for what we're connecting to.
3425 * We take a copy, rather than using a pointer, just in case the
3426 * admin takes the tag away and rehashes while the domain is resolving.
3429 SpanningTreeUtilities* Utils;
3431 ServernameResolver(SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(Util)
3433 /* Nothing in here, folks */
3436 void OnLookupComplete(const std::string &result)
3438 /* Initiate the connection, now that we have an IP to use.
3439 * Passing a hostname directly to InspSocket causes it to
3440 * just bail and set its FD to -1.
3442 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3443 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3445 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str());
3446 if (newsocket->GetFd() > -1)
3452 /* Something barfed, show the opers */
3453 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3455 Utils->DoFailOver(&MyLink);
3460 void OnError(ResolverError e, const std::string &errormessage)
3463 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3464 Utils->DoFailOver(&MyLink);
3468 /** Handle resolving of server IPs for the cache
3470 class SecurityIPResolver : public Resolver
3474 SpanningTreeUtilities* Utils;
3476 SecurityIPResolver(SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(U)
3480 void OnLookupComplete(const std::string &result)
3482 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3483 Utils->ValidIPs.push_back(result);
3486 void OnError(ResolverError e, const std::string &errormessage)
3488 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3492 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3495 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3496 this->ReadConfiguration(true);
3499 SpanningTreeUtilities::~SpanningTreeUtilities()
3501 for (unsigned int i = 0; i < Bindings.size(); i++)
3503 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3504 ServerInstance->SE->DelFd(Bindings[i]);
3505 Bindings[i]->Close();
3506 DELETE(Bindings[i]);
3508 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3509 while (TreeRoot->ChildCount())
3511 TreeServer* child_server = TreeRoot->GetChild(0);
3512 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3515 TreeSocket* sock = child_server->GetSocket();
3516 ServerInstance->SE->DelFd(sock);
3523 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3525 for (unsigned int c = 0; c < list.size(); c++)
3527 if (list[c] == server)
3532 list.push_back(server);
3535 /** returns a list of DIRECT servernames for a specific channel */
3536 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3538 CUList *ulist = c->GetUsers();
3539 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3541 if (i->second->GetFd() < 0)
3543 TreeServer* best = this->BestRouteTo(i->second->server);
3545 AddThisServer(best,list);
3551 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms)
3553 TreeServer* omitroute = this->BestRouteTo(omit);
3554 if ((command == "NOTICE") || (command == "PRIVMSG"))
3556 if (params.size() >= 2)
3559 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3561 params[0] = params[0].substr(1, params[0].length()-1);
3563 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3565 // special routing for private messages/notices
3566 userrec* d = ServerInstance->FindNick(params[0]);
3569 std::deque<std::string> par;
3570 par.push_back(params[0]);
3571 par.push_back(":"+params[1]);
3572 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3576 else if (*(params[0].c_str()) == '$')
3578 std::deque<std::string> par;
3579 par.push_back(params[0]);
3580 par.push_back(":"+params[1]);
3581 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3586 chanrec* c = ServerInstance->FindChan(params[0]);
3589 std::deque<TreeServer*> list;
3590 GetListOfServersForChannel(c,list);
3591 unsigned int lsize = list.size();
3592 for (unsigned int i = 0; i < lsize; i++)
3594 TreeSocket* Sock = list[i]->GetSocket();
3595 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3597 Sock->WriteLine(data);
3605 unsigned int items =this->TreeRoot->ChildCount();
3606 for (unsigned int x = 0; x < items; x++)
3608 TreeServer* Route = this->TreeRoot->GetChild(x);
3609 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3611 TreeSocket* Sock = Route->GetSocket();
3613 Sock->WriteLine(data);
3619 bool SpanningTreeUtilities::DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
3621 TreeServer* omitroute = this->BestRouteTo(omit);
3622 std::string FullLine = ":" + prefix + " " + command;
3623 unsigned int words = params.size();
3624 for (unsigned int x = 0; x < words; x++)
3626 FullLine = FullLine + " " + params[x];
3628 unsigned int items = this->TreeRoot->ChildCount();
3629 for (unsigned int x = 0; x < items; x++)
3631 TreeServer* Route = this->TreeRoot->GetChild(x);
3632 // Send the line IF:
3633 // The route has a socket (its a direct connection)
3634 // The route isnt the one to be omitted
3635 // The route isnt the path to the one to be omitted
3636 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3638 TreeSocket* Sock = Route->GetSocket();
3640 Sock->WriteLine(FullLine);
3646 bool SpanningTreeUtilities::DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
3648 std::string FullLine = ":" + prefix + " " + command;
3649 unsigned int words = params.size();
3650 for (unsigned int x = 0; x < words; x++)
3652 FullLine = FullLine + " " + params[x];
3654 unsigned int items = this->TreeRoot->ChildCount();
3655 for (unsigned int x = 0; x < items; x++)
3657 TreeServer* Route = this->TreeRoot->GetChild(x);
3658 if (Route && Route->GetSocket())
3660 TreeSocket* Sock = Route->GetSocket();
3662 Sock->WriteLine(FullLine);
3668 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3670 std::string spfx = prefix;
3671 std::string scmd = command;
3672 return this->DoOneToMany(spfx, scmd, params);
3675 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3677 std::string spfx = prefix;
3678 std::string scmd = command;
3679 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3682 bool SpanningTreeUtilities::DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
3684 TreeServer* Route = this->BestRouteTo(target);
3687 std::string FullLine = ":" + prefix + " " + command;
3688 unsigned int words = params.size();
3689 for (unsigned int x = 0; x < words; x++)
3691 FullLine = FullLine + " " + params[x];
3693 if (Route && Route->GetSocket())
3695 TreeSocket* Sock = Route->GetSocket();
3697 Sock->WriteLine(FullLine);
3707 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3709 ConfigReader* Conf = new ConfigReader(ServerInstance);
3712 for (int j =0; j < Conf->Enumerate("bind"); j++)
3714 std::string Type = Conf->ReadValue("bind","type",j);
3715 std::string IP = Conf->ReadValue("bind","address",j);
3716 int Port = Conf->ReadInteger("bind","port",j,true);
3717 if (Type == "servers")
3719 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), Port);
3724 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(),Port,true,10);
3725 if (listener->GetState() == I_LISTENING)
3727 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), Port);
3728 Bindings.push_back(listener);
3732 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3736 ServerInstance->Log(DEBUG,"Done with this binding");
3740 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3741 HideULines = Conf->ReadFlag("options","hideulines",0);
3742 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3745 for (int j =0; j < Conf->Enumerate("link"); j++)
3748 std::string Allow = Conf->ReadValue("link","allowmask",j);
3749 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3750 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3751 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3752 L.Port = Conf->ReadInteger("link","port",j,true);
3753 L.SendPass = Conf->ReadValue("link","sendpass",j);
3754 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3755 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3756 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
3757 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3758 L.NextConnectTime = time(NULL) + L.AutoConnect;
3759 /* Bugfix by brain, do not allow people to enter bad configurations */
3760 if (L.Name != ServerInstance->Config->ServerName)
3762 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3764 ValidIPs.push_back(L.IPAddr);
3767 ValidIPs.push_back(Allow);
3769 /* Needs resolving */
3771 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3775 SecurityIPResolver* sr = new SecurityIPResolver(this, ServerInstance, L.IPAddr, L);
3776 ServerInstance->AddResolver(sr);
3778 catch (ModuleException& e)
3780 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
3784 LinkBlocks.push_back(L);
3785 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3791 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3793 else if (L.RecvPass == "")
3795 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3797 else if (L.SendPass == "")
3799 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3801 else if (L.Name == "")
3803 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
3807 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3813 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
3821 class ModuleSpanningTree : public Module
3825 unsigned int max_local;
3826 unsigned int max_global;
3827 cmd_rconnect* command_rconnect;
3828 SpanningTreeUtilities* Utils;
3832 ModuleSpanningTree(InspIRCd* Me)
3833 : Module::Module(Me), max_local(0), max_global(0)
3835 Utils = new SpanningTreeUtilities(Me, this);
3837 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
3838 ServerInstance->AddCommand(command_rconnect);
3841 void ShowLinks(TreeServer* Current, userrec* user, int hops)
3843 std::string Parent = Utils->TreeRoot->GetName();
3844 if (Current->GetParent())
3846 Parent = Current->GetParent()->GetName();
3848 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3850 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3854 ShowLinks(Current->GetChild(q),user,hops+1);
3859 ShowLinks(Current->GetChild(q),user,hops+1);
3862 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3863 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
3865 user->WriteServ("364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(Utils->FlatLinks && (!*user->oper)) ? ServerInstance->Config->ServerName : Parent.c_str(),(Utils->FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3868 int CountLocalServs()
3870 return Utils->TreeRoot->ChildCount();
3875 return Utils->serverlist.size();
3878 void HandleLinks(const char** parameters, int pcnt, userrec* user)
3880 ShowLinks(Utils->TreeRoot,user,0);
3881 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
3885 void HandleLusers(const char** parameters, int pcnt, userrec* user)
3887 unsigned int n_users = ServerInstance->UserCount();
3889 /* Only update these when someone wants to see them, more efficient */
3890 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
3891 max_local = ServerInstance->LocalUserCount();
3892 if (n_users > max_global)
3893 max_global = n_users;
3895 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs());
3896 if (ServerInstance->OperCount())
3897 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
3898 if (ServerInstance->UnregisteredUserCount())
3899 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
3900 if (ServerInstance->ChannelCount())
3901 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
3902 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs());
3903 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
3904 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
3908 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3910 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3914 for (int t = 0; t < depth; t++)
3916 matrix[line][t] = ' ';
3919 // For Aligning, we need to work out exactly how deep this thing is, and produce
3920 // a 'Spacer' String to compensate.
3923 memset(spacer,' ',40);
3924 if ((40 - Current->GetName().length() - depth) > 1) {
3925 spacer[40 - Current->GetName().length() - depth] = '\0';
3934 if (ServerInstance->clientlist.size() == 0) {
3935 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3940 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
3942 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3943 totusers += Current->GetUserCount();
3945 strlcpy(&matrix[line][depth],text,80);
3947 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3949 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3953 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3958 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3964 int HandleMotd(const char** parameters, int pcnt, userrec* user)
3968 /* Remote MOTD, the server is within the 1st parameter */
3969 std::deque<std::string> params;
3970 params.push_back(parameters[0]);
3972 /* Send it out remotely, generate no reply yet */
3973 TreeServer* s = Utils->FindServerMask(parameters[0]);
3976 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
3980 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3987 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
3991 /* Remote ADMIN, the server is within the 1st parameter */
3992 std::deque<std::string> params;
3993 params.push_back(parameters[0]);
3995 /* Send it out remotely, generate no reply yet */
3996 TreeServer* s = Utils->FindServerMask(parameters[0]);
3999 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4003 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4010 int HandleStats(const char** parameters, int pcnt, userrec* user)
4014 /* Remote STATS, the server is within the 2nd parameter */
4015 std::deque<std::string> params;
4016 params.push_back(parameters[0]);
4017 params.push_back(parameters[1]);
4018 /* Send it out remotely, generate no reply yet */
4019 TreeServer* s = Utils->FindServerMask(parameters[1]);
4022 params[1] = s->GetName();
4023 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4027 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4034 // Ok, prepare to be confused.
4035 // After much mulling over how to approach this, it struck me that
4036 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4037 // keeping track of a ton of ascii characters, and line by line
4038 // under recursion working out where to place them using multiplications
4039 // and divisons, we instead render the map onto a backplane of characters
4040 // (a character matrix), then draw the branches as a series of "L" shapes
4041 // from the nodes. This is not only friendlier on CPU it uses less stack.
4043 void HandleMap(const char** parameters, int pcnt, userrec* user)
4045 // This array represents a virtual screen which we will
4046 // "scratch" draw to, as the console device of an irc
4047 // client does not provide for a proper terminal.
4049 float totservers = 0;
4050 char matrix[128][80];
4051 for (unsigned int t = 0; t < 128; t++)
4053 matrix[t][0] = '\0';
4056 // The only recursive bit is called here.
4057 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4058 // Process each line one by one. The algorithm has a limit of
4059 // 128 servers (which is far more than a spanning tree should have
4060 // anyway, so we're ok). This limit can be raised simply by making
4061 // the character matrix deeper, 128 rows taking 10k of memory.
4062 for (int l = 1; l < line; l++)
4064 // scan across the line looking for the start of the
4065 // servername (the recursive part of the algorithm has placed
4066 // the servers at indented positions depending on what they
4068 int first_nonspace = 0;
4069 while (matrix[l][first_nonspace] == ' ')
4074 // Draw the `- (corner) section: this may be overwritten by
4075 // another L shape passing along the same vertical pane, becoming
4076 // a |- (branch) section instead.
4077 matrix[l][first_nonspace] = '-';
4078 matrix[l][first_nonspace-1] = '`';
4080 // Draw upwards until we hit the parent server, causing possibly
4081 // other corners (`-) to become branches (|-)
4082 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4084 matrix[l2][first_nonspace-1] = '|';
4088 // dump the whole lot to the user. This is the easy bit, honest.
4089 for (int t = 0; t < line; t++)
4091 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4093 float avg_users = totusers / totservers;
4094 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);
4095 user->WriteServ("007 %s :End of /MAP",user->nick);
4099 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4101 TreeServer* s = Utils->FindServerMask(parameters[0]);
4104 if (s == Utils->TreeRoot)
4106 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4109 TreeSocket* sock = s->GetSocket();
4112 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4113 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4114 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4115 ServerInstance->SE->DelFd(sock);
4121 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4126 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4131 int HandleTime(const char** parameters, int pcnt, userrec* user)
4133 if ((IS_LOCAL(user)) && (pcnt))
4135 TreeServer* found = Utils->FindServerMask(parameters[0]);
4138 // we dont' override for local server
4139 if (found == Utils->TreeRoot)
4142 std::deque<std::string> params;
4143 params.push_back(found->GetName());
4144 params.push_back(user->nick);
4145 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4149 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4155 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4157 if ((IS_LOCAL(user)) && (pcnt > 1))
4159 userrec* remote = ServerInstance->FindNick(parameters[1]);
4160 if ((remote) && (remote->GetFd() < 0))
4162 std::deque<std::string> params;
4163 params.push_back(parameters[1]);
4164 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4169 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4170 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4177 void DoPingChecks(time_t curtime)
4179 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4181 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4182 TreeSocket* sock = serv->GetSocket();
4185 if (curtime >= serv->NextPingTime())
4187 if (serv->AnsweredLastPing())
4189 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4190 serv->SetNextPingTime(curtime + 60);
4194 // they didnt answer, boot them
4195 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4196 sock->Squit(serv,"Ping timeout");
4197 ServerInstance->SE->DelFd(sock);
4207 void ConnectServer(Link* x)
4211 /* Do we already have an IP? If so, no need to resolve it. */
4212 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4214 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str());
4215 if (newsocket->GetFd() > -1)
4217 /* Handled automatically on success */
4221 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4223 Utils->DoFailOver(x);
4230 ServernameResolver* snr = new ServernameResolver(Utils, ServerInstance,x->IPAddr, *x);
4231 ServerInstance->AddResolver(snr);
4233 catch (ModuleException& e)
4235 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4236 Utils->DoFailOver(x);
4241 void AutoConnectServers(time_t curtime)
4243 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4245 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4247 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4248 x->NextConnectTime = curtime + x->AutoConnect;
4249 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4250 if (x->FailOver.length())
4252 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4255 /* The failover for this server is currently a member of the network.
4256 * The failover probably succeeded, where the main link did not.
4257 * Don't try the main link until the failover is gone again.
4264 // an autoconnected server is not connected. Check if its time to connect it
4265 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4266 this->ConnectServer(&(*x));
4272 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4274 // we've already checked if pcnt > 0, so this is safe
4275 TreeServer* found = Utils->FindServerMask(parameters[0]);
4278 std::string Version = found->GetVersion();
4279 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4280 if (found == Utils->TreeRoot)
4282 std::stringstream out(ServerInstance->Config->data005);
4283 std::string token = "";
4284 std::string line5 = "";
4285 int token_counter = 0;
4290 line5 = line5 + token + " ";
4293 if ((token_counter >= 13) || (out.eof() == true))
4295 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4304 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4309 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4311 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4313 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4315 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4318 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);
4319 ConnectServer(&(*x));
4324 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());
4329 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4333 virtual int OnStats(char statschar, userrec* user, string_list &results)
4335 if (statschar == 'c')
4337 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4339 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4340 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4342 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4343 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);
4349 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4351 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4355 if (command == "CONNECT")
4357 return this->HandleConnect(parameters,pcnt,user);
4359 else if (command == "STATS")
4361 return this->HandleStats(parameters,pcnt,user);
4363 else if (command == "MOTD")
4365 return this->HandleMotd(parameters,pcnt,user);
4367 else if (command == "ADMIN")
4369 return this->HandleAdmin(parameters,pcnt,user);
4371 else if (command == "SQUIT")
4373 return this->HandleSquit(parameters,pcnt,user);
4375 else if (command == "MAP")
4377 this->HandleMap(parameters,pcnt,user);
4380 else if ((command == "TIME") && (pcnt > 0))
4382 return this->HandleTime(parameters,pcnt,user);
4384 else if (command == "LUSERS")
4386 this->HandleLusers(parameters,pcnt,user);
4389 else if (command == "LINKS")
4391 this->HandleLinks(parameters,pcnt,user);
4394 else if (command == "WHOIS")
4399 return this->HandleRemoteWhois(parameters,pcnt,user);
4402 else if ((command == "VERSION") && (pcnt > 0))
4404 this->HandleVersion(parameters,pcnt,user);
4411 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4413 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4415 // this bit of code cleverly routes all module commands
4416 // to all remote severs *automatically* so that modules
4417 // can just handle commands locally, without having
4418 // to have any special provision in place for remote
4419 // commands and linking protocols.
4420 std::deque<std::string> params;
4422 for (int j = 0; j < pcnt; j++)
4424 if (strchr(parameters[j],' '))
4426 params.push_back(":" + std::string(parameters[j]));
4430 params.push_back(std::string(parameters[j]));
4433 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4434 Utils->DoOneToMany(user->nick,command,params);
4438 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4440 TreeServer* s = Utils->FindServer(servername);
4443 description = s->GetDesc();
4447 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4449 if (IS_LOCAL(source))
4451 std::deque<std::string> params;
4452 params.push_back(dest->nick);
4453 params.push_back(channel->name);
4454 Utils->DoOneToMany(source->nick,"INVITE",params);
4458 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4460 std::deque<std::string> params;
4461 params.push_back(chan->name);
4462 params.push_back(":"+topic);
4463 Utils->DoOneToMany(user->nick,"TOPIC",params);
4466 virtual void OnWallops(userrec* user, const std::string &text)
4470 std::deque<std::string> params;
4471 params.push_back(":"+text);
4472 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4476 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4478 if (target_type == TYPE_USER)
4480 userrec* d = (userrec*)dest;
4481 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4483 std::deque<std::string> params;
4485 params.push_back(d->nick);
4486 params.push_back(":"+text);
4487 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4490 else if (target_type == TYPE_CHANNEL)
4494 chanrec *c = (chanrec*)dest;
4497 std::string cname = c->name;
4499 cname = status + cname;
4500 std::deque<TreeServer*> list;
4501 Utils->GetListOfServersForChannel(c,list);
4502 unsigned int ucount = list.size();
4503 for (unsigned int i = 0; i < ucount; i++)
4505 TreeSocket* Sock = list[i]->GetSocket();
4507 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4512 else if (target_type == TYPE_SERVER)
4516 char* target = (char*)dest;
4517 std::deque<std::string> par;
4518 par.push_back(target);
4519 par.push_back(":"+text);
4520 Utils->DoOneToMany(user->nick,"NOTICE",par);
4525 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4527 if (target_type == TYPE_USER)
4529 // route private messages which are targetted at clients only to the server
4530 // which needs to receive them
4531 userrec* d = (userrec*)dest;
4532 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4534 std::deque<std::string> params;
4536 params.push_back(d->nick);
4537 params.push_back(":"+text);
4538 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4541 else if (target_type == TYPE_CHANNEL)
4545 chanrec *c = (chanrec*)dest;
4548 std::string cname = c->name;
4550 cname = status + cname;
4551 std::deque<TreeServer*> list;
4552 Utils->GetListOfServersForChannel(c,list);
4553 unsigned int ucount = list.size();
4554 for (unsigned int i = 0; i < ucount; i++)
4556 TreeSocket* Sock = list[i]->GetSocket();
4558 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4563 else if (target_type == TYPE_SERVER)
4567 char* target = (char*)dest;
4568 std::deque<std::string> par;
4569 par.push_back(target);
4570 par.push_back(":"+text);
4571 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4576 virtual void OnBackgroundTimer(time_t curtime)
4578 AutoConnectServers(curtime);
4579 DoPingChecks(curtime);
4582 virtual void OnUserJoin(userrec* user, chanrec* channel)
4584 // Only do this for local users
4587 std::deque<std::string> params;
4589 params.push_back(channel->name);
4590 // set up their permissions and the channel TS with FJOIN.
4591 // All users are FJOINed now, because a module may specify
4592 // new joining permissions for the user.
4594 params.push_back(channel->name);
4595 params.push_back(ConvToStr(channel->age));
4596 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4597 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4601 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4603 // only occurs for local clients
4604 if (user->registered != REG_ALL)
4606 std::deque<std::string> params;
4607 params.push_back(newhost);
4608 Utils->DoOneToMany(user->nick,"FHOST",params);
4611 virtual void OnChangeName(userrec* user, const std::string &gecos)
4613 // only occurs for local clients
4614 if (user->registered != REG_ALL)
4616 std::deque<std::string> params;
4617 params.push_back(gecos);
4618 Utils->DoOneToMany(user->nick,"FNAME",params);
4621 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4625 std::deque<std::string> params;
4626 params.push_back(channel->name);
4627 if (partmessage != "")
4628 params.push_back(":"+partmessage);
4629 Utils->DoOneToMany(user->nick,"PART",params);
4633 virtual void OnUserConnect(userrec* user)
4635 char agestr[MAXBUF];
4638 std::deque<std::string> params;
4639 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4640 params.push_back(agestr);
4641 params.push_back(user->nick);
4642 params.push_back(user->host);
4643 params.push_back(user->dhost);
4644 params.push_back(user->ident);
4645 params.push_back("+"+std::string(user->FormatModes()));
4646 params.push_back(user->GetIPString());
4647 params.push_back(":"+std::string(user->fullname));
4648 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4650 // User is Local, change needs to be reflected!
4651 TreeServer* SourceServer = Utils->FindServer(user->server);
4654 SourceServer->AddUserCount();
4660 virtual void OnUserQuit(userrec* user, const std::string &reason)
4662 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4664 std::deque<std::string> params;
4665 params.push_back(":"+reason);
4666 Utils->DoOneToMany(user->nick,"QUIT",params);
4668 // Regardless, We need to modify the user Counts..
4669 TreeServer* SourceServer = Utils->FindServer(user->server);
4672 SourceServer->DelUserCount();
4677 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4681 std::deque<std::string> params;
4682 params.push_back(user->nick);
4683 Utils->DoOneToMany(oldnick,"NICK",params);
4687 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4689 if ((source) && (IS_LOCAL(source)))
4691 std::deque<std::string> params;
4692 params.push_back(chan->name);
4693 params.push_back(user->nick);
4694 params.push_back(":"+reason);
4695 Utils->DoOneToMany(source->nick,"KICK",params);
4699 std::deque<std::string> params;
4700 params.push_back(chan->name);
4701 params.push_back(user->nick);
4702 params.push_back(":"+reason);
4703 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4707 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4709 std::deque<std::string> params;
4710 params.push_back(dest->nick);
4711 params.push_back(":"+reason);
4712 Utils->DoOneToMany(source->nick,"KILL",params);
4715 virtual void OnRehash(const std::string ¶meter)
4717 if (parameter != "")
4719 std::deque<std::string> params;
4720 params.push_back(parameter);
4721 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4723 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4725 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4726 ServerInstance->RehashServer();
4729 Utils->ReadConfiguration(false);
4732 // note: the protocol does not allow direct umode +o except
4733 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4735 virtual void OnOper(userrec* user, const std::string &opertype)
4739 std::deque<std::string> params;
4740 params.push_back(opertype);
4741 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
4745 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4747 if (IS_LOCAL(source))
4750 snprintf(type,8,"%cLINE",linetype);
4751 std::string stype = type;
4754 char sduration[MAXBUF];
4755 snprintf(sduration,MAXBUF,"%ld",duration);
4756 std::deque<std::string> params;
4757 params.push_back(host);
4758 params.push_back(sduration);
4759 params.push_back(":"+reason);
4760 Utils->DoOneToMany(source->nick,stype,params);
4764 std::deque<std::string> params;
4765 params.push_back(host);
4766 Utils->DoOneToMany(source->nick,stype,params);
4771 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4773 OnLine(source,hostmask,true,'G',duration,reason);
4776 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4778 OnLine(source,ipmask,true,'Z',duration,reason);
4781 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4783 OnLine(source,nickmask,true,'Q',duration,reason);
4786 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4788 OnLine(source,hostmask,true,'E',duration,reason);
4791 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4793 OnLine(source,hostmask,false,'G',0,"");
4796 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4798 OnLine(source,ipmask,false,'Z',0,"");
4801 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4803 OnLine(source,nickmask,false,'Q',0,"");
4806 virtual void OnDelELine(userrec* source, const std::string &hostmask)
4808 OnLine(source,hostmask,false,'E',0,"");
4811 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4813 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4815 if (target_type == TYPE_USER)
4817 userrec* u = (userrec*)dest;
4818 std::deque<std::string> params;
4819 params.push_back(u->nick);
4820 params.push_back(text);
4821 Utils->DoOneToMany(user->nick,"MODE",params);
4825 chanrec* c = (chanrec*)dest;
4826 std::deque<std::string> params;
4827 params.push_back(c->name);
4828 params.push_back(text);
4829 Utils->DoOneToMany(user->nick,"MODE",params);
4834 virtual void OnSetAway(userrec* user)
4838 std::deque<std::string> params;
4839 params.push_back(":"+std::string(user->awaymsg));
4840 Utils->DoOneToMany(user->nick,"AWAY",params);
4844 virtual void OnCancelAway(userrec* user)
4848 std::deque<std::string> params;
4850 Utils->DoOneToMany(user->nick,"AWAY",params);
4854 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4856 TreeSocket* s = (TreeSocket*)opaque;
4859 if (target_type == TYPE_USER)
4861 userrec* u = (userrec*)target;
4862 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4866 chanrec* c = (chanrec*)target;
4867 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4872 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4874 TreeSocket* s = (TreeSocket*)opaque;
4877 if (target_type == TYPE_USER)
4879 userrec* u = (userrec*)target;
4880 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
4882 else if (target_type == TYPE_OTHER)
4884 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
4886 else if (target_type == TYPE_CHANNEL)
4888 chanrec* c = (chanrec*)target;
4889 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
4894 virtual void OnEvent(Event* event)
4896 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4898 if (event->GetEventID() == "send_metadata")
4900 if (params->size() < 3)
4902 (*params)[2] = ":" + (*params)[2];
4903 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
4905 else if (event->GetEventID() == "send_topic")
4907 if (params->size() < 2)
4909 (*params)[1] = ":" + (*params)[1];
4910 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
4911 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time()));
4912 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
4914 else if (event->GetEventID() == "send_mode")
4916 if (params->size() < 2)
4918 // Insert the TS value of the object, either userrec or chanrec
4920 userrec* a = ServerInstance->FindNick((*params)[0]);
4927 chanrec* a = ServerInstance->FindChan((*params)[0]);
4933 params->insert(params->begin() + 1,ConvToStr(ourTS));
4934 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
4938 virtual ~ModuleSpanningTree()
4940 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
4941 /* This will also free the listeners */
4945 virtual Version GetVersion()
4947 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
4950 void Implements(char* List)
4952 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4953 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4954 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4955 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4956 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4957 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4958 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
4961 /* It is IMPORTANT that m_spanningtree is the last module in the chain
4962 * so that any activity it sees is FINAL, e.g. we arent going to send out
4963 * a NICK message before m_cloaking has finished putting the +x on the user,
4965 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4966 * the module call queue.
4968 Priority Prioritize()
4970 return PRIORITY_LAST;
4974 void SpanningTreeUtilities::DoFailOver(Link* x)
4976 if (x->FailOver.length())
4978 if (x->FailOver == x->Name)
4980 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());
4983 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
4986 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
4987 Creator->ConnectServer(TryThisOne);
4991 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
4996 Link* SpanningTreeUtilities::FindLink(const std::string& name)
4998 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5000 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5009 class ModuleSpanningTreeFactory : public ModuleFactory
5012 ModuleSpanningTreeFactory()
5016 ~ModuleSpanningTreeFactory()
5020 virtual Module * CreateModule(InspIRCd* Me)
5022 return new ModuleSpanningTree(Me);
5028 extern "C" void * init_module( void )
5030 return new ModuleSpanningTreeFactory;