1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $ModDesc: Provides a spanning tree server link protocol */
16 #include "configreader.h"
20 #include "commands/cmd_whois.h"
21 #include "commands/cmd_stats.h"
26 #include "transport.h"
28 #include "m_spanningtree/utils.h"
30 /** If you make a change which breaks the protocol, increment this.
31 * If you completely change the protocol, completely change the number.
33 * IMPORTANT: If you make changes, document your changes here, without fail:
34 * http://www.inspircd.org/wiki/List_of_protocol_changes_between_versions
36 * Failure to document your protocol changes will result in a painfully
37 * painful death by pain. You have been warned.
39 const long ProtocolVersion = 1103;
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 /** The Link class might as well be a struct,
84 * but this is C++ and we don't believe in structs (!).
85 * It holds the entire information of one <link>
86 * tag from the main config file. We maintain a list
87 * of them, and populate the list on rehash/load.
89 class Link : public classbase
97 unsigned long AutoConnect;
98 time_t NextConnectTime;
100 std::string FailOver;
105 class HandshakeTimer : public InspTimer
111 SpanningTreeUtilities* Utils;
114 HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u);
115 virtual void Tick(time_t TIME);
118 /** Each server in the tree is represented by one class of
119 * type TreeServer. A locally connected TreeServer can
120 * have a class of type TreeSocket associated with it, for
121 * remote servers, the TreeSocket entry will be NULL.
122 * Each server also maintains a pointer to its parent
123 * (NULL if this server is ours, at the top of the tree)
124 * and a pointer to its "Route" (see the comments in the
125 * constructors below), and also a dynamic list of pointers
126 * to its children which can be iterated recursively
127 * if required. Creating or deleting objects of type
128 i* TreeServer automatically maintains the hash_map of
129 * TreeServer items, deleting and inserting them as they
130 * are created and destroyed.
132 class TreeServer : public classbase
134 InspIRCd* ServerInstance; /* Creator */
135 TreeServer* Parent; /* Parent entry */
136 TreeServer* Route; /* Route entry */
137 std::vector<TreeServer*> Children; /* List of child objects */
138 irc::string ServerName; /* Server's name */
139 std::string ServerDesc; /* Server's description */
140 std::string VersionString; /* Version string or empty string */
141 int UserCount; /* Not used in this version */
142 int OperCount; /* Not used in this version */
143 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
144 time_t NextPing; /* After this time, the server should be PINGed*/
145 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
146 SpanningTreeUtilities* Utils; /* Utility class */
150 /** We don't use this constructor. Its a dummy, and won't cause any insertion
151 * of the TreeServer into the hash_map. See below for the two we DO use.
153 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance) : ServerInstance(Instance), Utils(Util)
159 UserCount = OperCount = 0;
160 VersionString = ServerInstance->GetVersionString();
163 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
164 * represents our own server. Therefore, it has no route, no parent, and
165 * no socket associated with it. Its version string is our own local version.
167 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util)
171 UserCount = ServerInstance->UserCount();
172 OperCount = ServerInstance->OperCount();
173 VersionString = ServerInstance->GetVersionString();
175 Socket = NULL; /* Fix by brain */
179 /** When we create a new server, we call this constructor to initialize it.
180 * This constructor initializes the server's Route and Parent, and sets up
181 * its ping counters so that it will be pinged one minute from now.
183 TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
184 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util)
187 UserCount = OperCount = 0;
188 this->SetNextPingTime(time(NULL) + 60);
191 /* find the 'route' for this server (e.g. the one directly connected
192 * to the local server, which we can use to reach it)
194 * In the following example, consider we have just added a TreeServer
195 * class for server G on our network, of which we are server A.
196 * To route traffic to G (marked with a *) we must send the data to
197 * B (marked with a +) so this algorithm initializes the 'Route'
198 * value to point at whichever server traffic must be routed through
199 * to get here. If we were to try this algorithm with server B,
200 * the Route pointer would point at its own object ('this').
210 * We only run this algorithm when a server is created, as
211 * the routes remain constant while ever the server exists, and
212 * do not need to be re-calculated.
216 if (Route == Utils->TreeRoot)
222 while (this->Route->GetParent() != Utils->TreeRoot)
224 this->Route = Route->GetParent();
228 /* Because recursive code is slow and takes a lot of resources,
229 * we store two representations of the server tree. The first
230 * is a recursive structure where each server references its
231 * children and its parent, which is used for netbursts and
232 * netsplits to dump the whole dataset to the other server,
233 * and the second is used for very fast lookups when routing
234 * messages and is instead a hash_map, where each item can
235 * be referenced by its server name. The AddHashEntry()
236 * call below automatically inserts each TreeServer class
237 * into the hash_map as it is created. There is a similar
238 * maintainance call in the destructor to tidy up deleted
242 this->AddHashEntry();
245 int QuitUsers(const std::string &reason)
247 const char* reason_s = reason.c_str();
248 std::vector<userrec*> time_to_die;
249 for (user_hash::iterator n = ServerInstance->clientlist->begin(); n != ServerInstance->clientlist->end(); n++)
251 if (!strcmp(n->second->server, this->ServerName.c_str()))
253 time_to_die.push_back(n->second);
256 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
258 userrec* a = (userrec*)*n;
260 userrec::QuitUser(ServerInstance,a,reason_s);
262 return time_to_die.size();
265 /** This method is used to add the structure to the
266 * hash_map for linear searches. It is only called
267 * by the constructors.
271 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
272 if (iter == Utils->serverlist.end())
273 Utils->serverlist[this->ServerName.c_str()] = this;
276 /** This method removes the reference to this object
277 * from the hash_map which is used for linear searches.
278 * It is only called by the default destructor.
282 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
283 if (iter != Utils->serverlist.end())
284 Utils->serverlist.erase(iter);
287 /** These accessors etc should be pretty self-
290 TreeServer* GetRoute()
295 std::string GetName()
297 return ServerName.c_str();
300 std::string GetDesc()
305 std::string GetVersion()
307 return VersionString;
310 void SetNextPingTime(time_t t)
313 LastPingWasGood = false;
316 time_t NextPingTime()
321 bool AnsweredLastPing()
323 return LastPingWasGood;
328 LastPingWasGood = true;
351 TreeSocket* GetSocket()
356 TreeServer* GetParent()
361 void SetVersion(const std::string &Version)
363 VersionString = Version;
366 unsigned int ChildCount()
368 return Children.size();
371 TreeServer* GetChild(unsigned int n)
373 if (n < Children.size())
375 /* Make sure they cant request
376 * an out-of-range object. After
377 * all we know what these programmer
378 * types are like *grin*.
388 void AddChild(TreeServer* Child)
390 Children.push_back(Child);
393 bool DelChild(TreeServer* Child)
395 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
406 /** Removes child nodes of this node, and of that node, etc etc.
407 * This is used during netsplits to automatically tidy up the
408 * server tree. It is slow, we don't use it for much else.
412 bool stillchildren = true;
413 while (stillchildren)
415 stillchildren = false;
416 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
418 TreeServer* s = (TreeServer*)*a;
422 stillchildren = true;
431 /* We'd better tidy up after ourselves, eh? */
432 this->DelHashEntry();
436 /** Yay for fast searches!
437 * This is hundreds of times faster than recursion
438 * or even scanning a linked list, especially when
439 * there are more than a few servers to deal with.
442 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
444 server_hash::iterator iter;
445 iter = serverlist.find(ServerName.c_str());
446 if (iter != serverlist.end())
456 /** Returns the locally connected server we must route a
457 * message through to reach server 'ServerName'. This
458 * only applies to one-to-one and not one-to-many routing.
459 * See the comments for the constructor of TreeServer
462 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
464 if (ServerName.c_str() == TreeRoot->GetName())
466 TreeServer* Found = FindServer(ServerName);
469 return Found->GetRoute();
477 /** Find the first server matching a given glob mask.
478 * Theres no find-using-glob method of hash_map [awwww :-(]
479 * so instead, we iterate over the list using an iterator
480 * and match each one until we get a hit. Yes its slow,
483 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
485 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
487 if (match(i->first.c_str(),ServerName.c_str()))
493 /* A convenient wrapper that returns true if a server exists */
494 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
496 return (FindServer(ServerName) != NULL);
502 class cmd_rconnect : public command_t
505 SpanningTreeUtilities* Utils;
507 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
509 this->source = "m_spanningtree.so";
510 syntax = "<remote-server-mask> <target-server-mask>";
513 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
517 if (!Utils->FindServer(parameters[0]))
519 user->WriteServ("NOTICE %s :*** RCONNECT: Server \002%s\002 isn't connected to the network!", user->nick, parameters[0]);
523 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
526 /* Is this aimed at our server? */
527 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
529 /* Yes, initiate the given connect */
530 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
532 para[0] = parameters[1];
533 std::string original_command = std::string("CONNECT ") + parameters[1];
534 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
543 /** Every SERVER connection inbound or outbound is represented by
544 * an object of type TreeSocket.
545 * TreeSockets, being inherited from InspSocket, can be tied into
546 * the core socket engine, and we cn therefore receive activity events
547 * for them, just like activex objects on speed. (yes really, that
548 * is a technical term!) Each of these which relates to a locally
549 * connected server is assocated with it, by hooking it onto a
550 * TreeSocket class using its constructor. In this way, we can
551 * maintain a list of servers, some of which are directly connected,
552 * some of which are not.
554 class TreeSocket : public InspSocket
556 SpanningTreeUtilities* Utils;
558 std::string in_buffer;
559 ServerState LinkState;
560 std::string InboundServerName;
561 std::string InboundDescription;
563 int num_lost_servers;
565 bool LastPingWasGood;
567 unsigned int keylength;
568 std::string ModuleList;
569 std::map<std::string,std::string> CapKeys;
574 /** Because most of the I/O gubbins are encapsulated within
575 * InspSocket, we just call the superclass constructor for
576 * most of the action, and append a few of our own values
579 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod = NULL)
580 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
583 this->LinkState = LISTENER;
584 if (listening && Hook)
585 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
588 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName, Module* HookMod = NULL)
589 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
592 this->LinkState = CONNECTING;
595 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
598 /** When a listening socket gives us a new file descriptor,
599 * we must associate it with a socket without creating a new
600 * connection. This constructor is used for this purpose.
602 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod = NULL)
603 : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
605 this->LinkState = WAIT_AUTH_1;
607 /* If we have a transport module hooked to the parent, hook the same module to this
608 * socket, and set a timer waiting for handshake before we send CAPAB etc.
612 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
613 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils));
617 /* Otherwise, theres no lower layer transport in plain TCP/IP,
618 * so just send the capabilities right now.
620 this->SendCapabilities();
624 ServerState GetLinkState()
626 return this->LinkState;
637 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
640 /** When an outbound connection finishes connecting, we receive
641 * this event, and must send our SERVER string to the other
642 * side. If the other side is happy, as outlined in the server
643 * to server docs on the inspircd.org site, the other side
644 * will then send back its own server string.
646 virtual bool OnConnected()
648 if (this->LinkState == CONNECTING)
650 /* we do not need to change state here. */
651 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
653 if (x->Name == this->myhost)
655 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
659 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
660 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+x->Hook+"\2");
663 this->SendCapabilities();
665 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
667 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
669 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
675 /* There is a (remote) chance that between the /CONNECT and the connection
676 * being accepted, some muppet has removed the <link> block and rehashed.
677 * If that happens the connection hangs here until it's closed. Unlikely
678 * and rather harmless.
680 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
684 virtual void OnError(InspSocketError e)
686 /* We don't handle this method, because all our
687 * dirty work is done in OnClose() (see below)
688 * which is still called on error conditions too.
690 if (e == I_ERR_CONNECT)
692 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
693 Link* MyLink = Utils->FindLink(myhost);
695 Utils->DoFailOver(MyLink);
699 virtual int OnDisconnect()
701 /* For the same reason as above, we don't
702 * handle OnDisconnect()
707 /** Recursively send the server tree with distances as hops.
708 * This is used during network burst to inform the other server
709 * (and any of ITS servers too) of what servers we know about.
710 * If at any point any of these servers already exist on the other
711 * end, our connection may be terminated. The hopcounts given
712 * by this function are relative, this doesn't matter so long as
713 * they are all >1, as all the remote servers re-calculate them
714 * to be relative too, with themselves as hop 0.
716 void SendServers(TreeServer* Current, TreeServer* s, int hops)
719 for (unsigned int q = 0; q < Current->ChildCount(); q++)
721 TreeServer* recursive_server = Current->GetChild(q);
722 if (recursive_server != s)
724 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
725 this->WriteLine(command);
726 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
727 /* down to next level */
728 this->SendServers(recursive_server, s, hops+1);
733 std::string MyCapabilities()
735 std::vector<std::string> modlist;
736 std::string capabilities = "";
738 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
740 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
741 modlist.push_back(this->Instance->Config->module_names[i]);
743 sort(modlist.begin(),modlist.end());
744 for (unsigned int i = 0; i < modlist.size(); i++)
747 capabilities = capabilities + ",";
748 capabilities = capabilities + modlist[i];
753 void SendCapabilities()
755 irc::commasepstream modulelist(MyCapabilities());
757 this->WriteLine("CAPAB START");
759 /* Send module names, split at 509 length */
760 std::string item = "*";
761 std::string line = "CAPAB MODULES ";
762 while ((item = modulelist.GetToken()) != "")
764 if (line.length() + item.length() + 1 > 509)
766 this->WriteLine(line);
767 line = "CAPAB MODULES ";
770 if (line != "CAPAB MODULES ")
775 if (line != "CAPAB MODULES ")
776 this->WriteLine(line);
783 #ifdef SUPPORT_IP6LINKS
786 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));
788 this->WriteLine("CAPAB END");
791 /* Check a comma seperated list for an item */
792 bool HasItem(const std::string &list, const std::string &item)
794 irc::commasepstream seplist(list);
796 std::string item2 = "*";
797 while ((item2 = seplist.GetToken()) != "")
806 /* Isolate and return the elements that are different between two comma seperated lists */
807 std::string ListDifference(const std::string &one, const std::string &two)
809 irc::commasepstream list_one(one);
810 std::string item = "*";
811 std::string result = "";
812 while ((item = list_one.GetToken()) != "")
814 if (!HasItem(two, item))
823 bool Capab(const std::deque<std::string> ¶ms)
825 if (params.size() < 1)
827 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
831 if (params[0] == "START")
833 this->ModuleList = "";
834 this->CapKeys.clear();
836 else if (params[0] == "END")
838 std::string reason = "";
840 #ifdef SUPPORT_IP6LINKS
843 /* Compare ModuleList and check CapKeys...
844 * Maybe this could be tidier? -- Brain
846 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
848 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
851 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
855 diff = "this server:" + diff;
857 if (diff.length() == 12)
858 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
860 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
863 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
864 reason = "We don't both support linking to IPV6 servers";
866 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
867 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
869 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
870 reason = "Maximum nickname lengths differ or remote nickname length not specified";
872 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
874 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
876 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
880 reason = "Protocol version not specified";
884 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))))
885 reason = "We don't both have halfop support enabled/disabled identically";
887 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
888 reason = "Maximum ident lengths differ or remote ident length not specified";
890 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
891 reason = "Maximum channel lengths differ or remote channel length not specified";
893 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
894 reason = "Maximum modes per line differ or remote modes per line not specified";
896 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
897 reason = "Maximum quit lengths differ or remote quit length not specified";
899 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
900 reason = "Maximum topic lengths differ or remote topic length not specified";
902 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
903 reason = "Maximum kick lengths differ or remote kick length not specified";
905 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
906 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
908 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
909 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
913 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
917 else if ((params[0] == "MODULES") && (params.size() == 2))
919 if (!this->ModuleList.length())
921 this->ModuleList.append(params[1]);
925 this->ModuleList.append(",");
926 this->ModuleList.append(params[1]);
929 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
931 irc::tokenstream capabs(params[1]);
932 std::string item = "*";
933 while ((item = capabs.GetToken()) != "")
935 /* Process each key/value pair */
936 std::string::size_type equals = item.rfind('=');
937 if (equals != std::string::npos)
939 std::string var = item.substr(0, equals);
940 std::string value = item.substr(equals+1, item.length());
941 CapKeys[var] = value;
949 /** This function forces this server to quit, removing this server
950 * and any users on it (and servers and users below that, etc etc).
951 * It's very slow and pretty clunky, but luckily unless your network
952 * is having a REAL bad hair day, this function shouldnt be called
953 * too many times a month ;-)
955 void SquitServer(std::string &from, TreeServer* Current)
957 /* recursively squit the servers attached to 'Current'.
958 * We're going backwards so we don't remove users
959 * while we still need them ;)
961 for (unsigned int q = 0; q < Current->ChildCount(); q++)
963 TreeServer* recursive_server = Current->GetChild(q);
964 this->SquitServer(from,recursive_server);
966 /* Now we've whacked the kids, whack self */
968 num_lost_users += Current->QuitUsers(from);
971 /** This is a wrapper function for SquitServer above, which
972 * does some validation first and passes on the SQUIT to all
973 * other remaining servers.
975 void Squit(TreeServer* Current, const std::string &reason)
977 if ((Current) && (Current != Utils->TreeRoot))
979 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
980 rmode.Send(Instance);
982 std::deque<std::string> params;
983 params.push_back(Current->GetName());
984 params.push_back(":"+reason);
985 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
986 if (Current->GetParent() == Utils->TreeRoot)
988 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
992 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
994 num_lost_servers = 0;
996 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
997 SquitServer(from, Current);
999 Current->GetParent()->DelChild(Current);
1001 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1005 Instance->Log(DEFAULT,"Squit from unknown server");
1009 /** FMODE command - server mode with timestamp checks */
1010 bool ForceMode(const std::string &source, std::deque<std::string> ¶ms)
1012 /* Chances are this is a 1.0 FMODE without TS */
1013 if (params.size() < 3)
1015 /* No modes were in the command, probably a channel with no modes set on it */
1020 std::string sourceserv;
1022 /* Are we dealing with an FMODE from a user, or from a server? */
1023 userrec* who = this->Instance->FindNick(source);
1026 /* FMODE from a user, set sourceserv to the users server name */
1027 sourceserv = who->server;
1031 /* FMODE from a server, create a fake user to receive mode feedback */
1032 who = new userrec(this->Instance);
1033 who->SetFd(FD_MAGIC_NUMBER);
1034 smode = true; /* Setting this flag tells us we should free the userrec later */
1035 sourceserv = source; /* Set sourceserv to the actual source string */
1037 const char* modelist[64];
1040 memset(&modelist,0,sizeof(modelist));
1041 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1045 /* The timestamp is in this position.
1046 * We don't want to pass that up to the
1047 * server->client protocol!
1049 TS = atoi(params[q].c_str());
1053 /* Everything else is fine to append to the modelist */
1054 modelist[n++] = params[q].c_str();
1058 /* Extract the TS value of the object, either userrec or chanrec */
1059 userrec* dst = this->Instance->FindNick(params[0]);
1060 chanrec* chan = NULL;
1068 chan = this->Instance->FindChan(params[0]);
1074 /* Oops, channel doesnt exist! */
1078 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1083 ModeHandler* mh = NULL;
1084 unsigned long paramptr = 3;
1085 std::string to_bounce = "";
1086 std::string to_keep = "";
1087 std::vector<std::string> params_to_keep;
1088 std::string params_to_bounce = "";
1090 char cur_change = 1;
1091 char old_change = 0;
1092 char old_bounce_change = 0;
1093 /* Merge modes, basically do special stuff to mode with params */
1094 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1107 /* We only care about whats being set,
1108 * not whats being unset
1110 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1112 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1114 /* We only want to do special things to
1115 * modes with parameters, we are going to rewrite
1119 adding ? cur_change = '+' : cur_change = '-';
1121 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1123 /* The mode is set here, check which we should keep */
1126 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1128 if (which_to_keep == true)
1130 /* Keep ours, bounce theirs:
1131 * Send back ours to them and
1132 * drop their mode changs
1134 adding ? cur_change = '+' : cur_change = '-';
1135 if (cur_change != old_bounce_change)
1136 to_bounce += cur_change;
1138 old_bounce_change = cur_change;
1140 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1141 params_to_bounce.append(" ").append(ret.second);
1145 /* Keep theirs: Accept their mode change,
1148 adding ? cur_change = '+' : cur_change = '-';
1149 if (cur_change != old_change)
1150 to_keep += cur_change;
1152 old_change = cur_change;
1154 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1155 params_to_keep.push_back(params[paramptr]);
1160 /* Mode isnt set here, we want it */
1161 adding ? cur_change = '+' : cur_change = '-';
1162 if (cur_change != old_change)
1163 to_keep += cur_change;
1165 old_change = cur_change;
1167 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1168 params_to_keep.push_back(params[paramptr]);
1175 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1179 adding ? cur_change = '+' : cur_change = '-';
1181 /* Just keep this, safe to merge with no checks
1182 * it has no parameters
1185 if (cur_change != old_change)
1186 to_keep += cur_change;
1188 old_change = cur_change;
1190 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1192 params_to_keep.push_back(params[paramptr++]);
1199 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1203 /* Taking a mode away */
1204 adding ? cur_change = '+' : cur_change = '-';
1206 if (cur_change != old_change)
1207 to_keep += cur_change;
1209 old_change = cur_change;
1211 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1212 params_to_keep.push_back(params[paramptr++]);
1219 if (to_bounce.length())
1221 std::deque<std::string> newparams;
1222 newparams.push_back(params[0]);
1223 newparams.push_back(ConvToStr(ourTS));
1224 newparams.push_back(to_bounce+params_to_bounce);
1225 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1228 if (to_keep.length())
1232 modelist[0] = params[0].c_str();
1233 modelist[1] = to_keep.c_str();
1235 if (params_to_keep.size() > 0)
1237 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1239 modelist[n++] = params_to_keep[q].c_str();
1245 this->Instance->SendMode(modelist, n, who);
1249 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1252 /* HOT POTATO! PASS IT ON! */
1253 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1257 /* U-lined servers always win regardless of their TS */
1258 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1260 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1261 * SHOULD accept it, if its clock is right.
1263 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1264 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1265 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1267 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1268 * writing the code. It took me a while to come up with this solution.
1270 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1273 std::deque<std::string> newparams; /* New parameter list we send back */
1274 newparams.push_back(params[0]); /* Target, user or channel */
1275 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1276 newparams.push_back(""); /* This contains the mode string. For now
1277 * it's empty, we fill it below.
1280 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1281 * set to avoid a desync here.
1283 std::string modebounce = "";
1286 ModeHandler* mh = NULL;
1287 char cur_change = 1;
1288 char old_change = 0;
1289 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1291 /* Iterate over all mode chars in the sent set */
1294 /* Adding or subtracting modes? */
1302 /* Find the mode handler for this mode */
1303 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1305 /* Got a mode handler?
1306 * This also prevents us bouncing modes we have no handler for.
1313 /* Does the mode require a parameter right now?
1314 * If it does, fetch it if we can
1316 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1319 /* Call the ModeSet method to determine if its set with the
1320 * given parameter here or not.
1322 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1324 /* XXX: Really. Dont ask.
1325 * Determine from if its set combined with what the current
1326 * 'state' is (adding or not) as to wether we should 'invert'
1327 * or 'reinforce' the mode change
1329 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1331 /* Quickly determine if we have 'flipped' from + to -,
1332 * or - to +, to prevent unneccessary +/- chars in the
1333 * output string that waste bandwidth
1335 if (cur_change != old_change)
1336 modebounce += cur_change;
1337 old_change = cur_change;
1339 /* Add the mode character to the output string */
1340 modebounce += mh->GetModeChar();
1342 /* We got a parameter back from ModeHandler::ModeSet,
1343 * are we supposed to be sending one out right now?
1345 if (ret.second.length())
1347 if (mh->GetNumParams(cur_change == '+') > 0)
1348 /* Yes we're supposed to be sending out
1349 * the parameter. Make sure it goes
1351 newparams.push_back(ret.second);
1359 /* Update the parameters for FMODE with the new 'bounced' string */
1360 newparams[2] = modebounce;
1361 /* Only send it back the way it came, no need to send it anywhere else */
1362 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1366 /* The server was ulined, but something iffy is up with the TS.
1367 * Sound the alarm bells!
1369 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1371 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());
1373 /* Allow the mode, route it to either server or user command handling */
1375 this->Instance->SendMode(modelist,n,who);
1377 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1379 /* HOT POTATO! PASS IT ON! */
1380 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1382 /* Are we supposed to free the userrec? */
1389 /** FTOPIC command */
1390 bool ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
1392 if (params.size() != 4)
1394 time_t ts = atoi(params[1].c_str());
1395 std::string nsource = source;
1397 chanrec* c = this->Instance->FindChan(params[0]);
1400 if ((ts >= c->topicset) || (!*c->topic))
1402 std::string oldtopic = c->topic;
1403 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1404 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1406 /* if the topic text is the same as the current topic,
1407 * dont bother to send the TOPIC command out, just silently
1408 * update the set time and set nick.
1410 if (oldtopic != params[3])
1412 userrec* user = this->Instance->FindNick(source);
1415 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1419 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1420 nsource = user->server;
1422 /* all done, send it on its way */
1423 params[3] = ":" + params[3];
1424 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1433 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1434 bool ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
1436 /* 1.1 FJOIN works as follows:
1438 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1439 * timestamp 'wins'. From this point on we will refer to this side as the
1440 * winner. The side with the higher timestamp loses, from this point on we
1441 * will call this side the loser or losing side. This should be familiar to
1442 * anyone who's dealt with dreamforge or TS6 before.
1444 * When two sides of a split heal and this occurs, the following things
1447 * If the timestamps are exactly equal, both sides merge their privilages
1448 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1449 * re-created during a split, this is safe to do.
1452 * If the timestamps are NOT equal, the losing side removes all privilage
1453 * modes from all of its users that currently exist in the channel, before
1454 * introducing new users into the channel which are listed in the FJOIN
1455 * command's parameters. This means, all modes +ohv, and privilages added
1456 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1457 * of the channel to match that of the winning side, and the modes of the
1458 * users of the winning side are merged in with the losing side. The loser
1459 * then sends out a set of FMODE commands which 'confirm' that it just
1460 * removed all privilage modes from its existing users, which allows for
1461 * services packages to still work correctly without needing to know the
1462 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1463 * a problem, and services packages must contain code which explicitly
1464 * behaves as TS6 does, removing ops from the losing side of a split where
1465 * neccessary within its internal records, as this state information is
1466 * not explicitly echoed out in that protocol.
1468 * The winning side on the other hand will ignore all user modes from the
1469 * losing side, so only its own modes get applied. Life is simple for those
1470 * who succeed at internets. :-)
1472 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1473 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1474 * you ask? Well, quite simply because we don't need to. They'll be sent
1475 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1476 * the losing side sends any modes for the channel which shouldnt win,
1477 * they wont as their timestamp will be too high :-)
1480 if (params.size() < 3)
1483 char first[MAXBUF]; /* The first parameter of the mode command */
1484 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1485 char* mode_users[127]; /* The values used by the mode command */
1486 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1487 mode_users[0] = first; /* Set this up to be our on-stack value */
1488 mode_users[1] = modestring; /* Same here as above */
1489 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1490 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1492 userrec* who = NULL; /* User we are currently checking */
1493 std::string channel = params[0]; /* Channel name, as a string */
1494 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1495 bool created = false;
1497 /* Try and find the channel */
1498 chanrec* chan = this->Instance->FindChan(channel);
1500 /* Initialize channel name in the mode parameters */
1501 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1503 /* default TS is a high value, which if we dont have this
1504 * channel will let the other side apply their modes.
1506 time_t ourTS = Instance->Time(true)+600;
1508 /* Does this channel exist? if it does, get its REAL timestamp */
1512 created = true; /* don't perform deops, and set TS to correct time after processing. */
1514 /* In 1.1, if they have the newer channel, we immediately clear
1515 * all status modes from our users. We then accept their modes.
1516 * If WE have the newer channel its the other side's job to do this.
1517 * Note that this causes the losing server to send out confirming
1522 std::deque<std::string> param_list;
1524 /* Lower the TS here */
1525 if (Utils->AnnounceTSChange && chan)
1526 chan->WriteChannelWithServ(Instance->Config->ServerName,
1527 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1530 /* Zap all the privilage modes on our side, if the channel exists here */
1533 param_list.push_back(channel);
1534 /* Do this first! */
1536 this->RemoveStatus(Instance->Config->ServerName, param_list);
1540 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1541 irc::tokenstream users(params[2]);
1542 std::string item = "*";
1544 /* do this first, so our mode reversals are correctly received by other servers
1545 * if there is a TS collision.
1547 params[2] = ":" + params[2];
1548 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1550 /* Now, process every 'prefixes,nick' pair */
1553 /* Find next user */
1554 item = users.GetToken();
1556 const char* usr = item.c_str();
1558 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1559 * (is this even possible?) */
1562 const char* permissions = usr;
1564 char* nm = new char[MAXBUF];
1567 /* Iterate through all the prefix values, convert them from prefixes
1568 * to mode letters, and append them to the mode sequence
1570 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1572 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1575 /* This is a valid prefix */
1577 *tnm++ = mh->GetModeChar();
1581 /* Not a valid prefix...
1582 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1584 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1585 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1592 /* Null terminate modes */
1594 /* Advance past the comma, to the nick */
1597 /* Check the user actually exists */
1598 who = this->Instance->FindNick(usr);
1601 /* Did they get any modes? How many times? */
1602 strlcat(modestring, nm, MAXBUF);
1603 for (int k = 0; k < ntimes; k++)
1604 mode_users[modectr++] = strdup(usr);
1606 /* Free temporary buffer used for mode sequence */
1609 /* Check that the user's 'direction' is correct
1610 * based on the server sending the FJOIN. We must
1611 * check each nickname in turn, because the origin of
1612 * the FJOIN may be different to the origin of the nicks
1613 * in the command itself.
1615 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1616 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1618 /* Oh dear oh dear. */
1621 /* Finally, we can actually place the user into the channel.
1622 * We're sure its right. Final answer, phone a friend.
1624 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1626 /* Have we already queued up MAXMODES modes with parameters
1627 * (+qaohv) ready to be sent to the server?
1629 if (modectr >= (MAXMODES-1))
1631 /* Only actually give the users any status if we lost
1632 * the FJOIN or drew (equal timestamps).
1633 * It isn't actually possible for ourTS to be > TS here,
1634 * only possible to actually have ourTS == TS, or
1635 * ourTS < TS, because if we lost, we already lowered
1636 * our TS above before we entered this loop. We only
1637 * check >= as a safety measure, in case someone stuffed
1638 * up. If someone DID stuff up, it was most likely me.
1639 * Note: I do not like baseball bats in the face...
1643 this->Instance->SendMode((const char**)mode_users,modectr,who);
1645 /* Something stuffed up, and for some reason, the timestamp is
1646 * NOT lowered right now and should be. Lower it. Usually this
1647 * code won't be executed, doubtless someone will remove it some
1652 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1658 /* Reset all this back to defaults, and
1659 * free any ram we have left allocated.
1661 strcpy(mode_users[1],"+");
1662 for (unsigned int f = 2; f < modectr; f++)
1663 free(mode_users[f]);
1669 /* Remember to free this */
1671 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1672 * We don't try to process the nickname here (that WOULD cause a segfault because
1673 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1674 * in case somehow we're desynched, so that other users which might be able to see
1675 * the nickname get their fair chance to process it.
1677 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1683 /* there werent enough modes built up to flush it during FJOIN,
1684 * or, there are a number left over. flush them out.
1686 if ((modectr > 2) && (who) && (chan))
1690 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1691 this->Instance->SendMode((const char**)mode_users,modectr,who);
1692 /* Yet again, we can't actually get a true value here, if everything else
1693 * is working as it should.
1697 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1703 /* Free anything we have left to free */
1704 for (unsigned int f = 2; f < modectr; f++)
1705 free(mode_users[f]);
1708 /* if we newly created the channel, set it's TS properly. */
1711 /* find created channel .. */
1712 chan = this->Instance->FindChan(channel);
1714 /* w00t said this shouldnt be needed but it is.
1715 * This isnt strictly true, as chan can be NULL
1716 * if a nick collision has occured and therefore
1717 * the channel was never created.
1722 /* All done. That wasnt so bad was it, you can wipe
1723 * the sweat from your forehead now. :-)
1729 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1731 if (params.size() < 8)
1733 if (params.size() > 8)
1735 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1738 // NICK age nick host dhost ident +modes ip :gecos
1740 time_t age = atoi(params[0].c_str());
1742 const char* tempnick = params[1].c_str();
1743 Instance->Log(DEBUG,"New remote client %s",tempnick);
1745 user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
1747 if (iter != this->Instance->clientlist->end())
1750 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1751 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1755 userrec* _new = new userrec(this->Instance);
1756 (*(this->Instance->clientlist))[tempnick] = _new;
1757 _new->SetFd(FD_MAGIC_NUMBER);
1758 strlcpy(_new->nick, tempnick,NICKMAX-1);
1759 strlcpy(_new->host, params[2].c_str(),63);
1760 strlcpy(_new->dhost, params[3].c_str(),63);
1761 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1762 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1763 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1764 _new->registered = REG_ALL;
1768 * we need to remove the + from the modestring, so we can do our stuff
1770 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1771 if (pos_after_plus != std::string::npos)
1772 params[5] = params[5].substr(pos_after_plus);
1775 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1777 _new->modes[(*v)-65] = 1;
1778 /* For each mode thats set, increase counter */
1779 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
1784 /* now we've done with modes processing, put the + back for remote servers */
1785 params[5] = "+" + params[5];
1787 #ifdef SUPPORT_IP6LINKS
1788 if (params[6].find_first_of(":") != std::string::npos)
1789 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1792 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1794 Instance->AddGlobalClone(_new);
1796 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1798 params[7] = ":" + params[7];
1799 Utils->DoOneToAllButSender(source,"NICK", params, source);
1801 // Increment the Source Servers User Count..
1802 TreeServer* SourceServer = Utils->FindServer(source);
1805 SourceServer->AddUserCount();
1808 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1813 /** Send one or more FJOINs for a channel of users.
1814 * If the length of a single line is more than 480-NICKMAX
1815 * in length, it is split over multiple lines.
1817 void SendFJoins(TreeServer* Current, chanrec* c)
1821 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1823 size_t dlen, curlen;
1824 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1826 char* ptr = list + dlen;
1828 CUList *ulist = c->GetUsers();
1829 std::string modes = "";
1830 std::string params = "";
1832 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1834 // The first parameter gets a : before it
1835 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1842 if (curlen > (480-NICKMAX))
1844 buffer.append(list).append("\r\n");
1846 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1854 buffer.append(list).append("\r\n");
1856 /* Sorry for the hax. Because newly created channels assume +nt,
1857 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1859 bool inverted = false;
1860 if (!c->IsModeSet('n'))
1865 if (!c->IsModeSet('t'))
1875 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1878 params.append(" ").append(b->data);
1880 if (params.length() >= MAXMODES)
1882 /* Wrap at MAXMODES */
1883 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params).append("\r\n");
1889 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1891 /* Only send these if there are any */
1893 buffer.append("\r\n").append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1895 this->WriteLine(buffer);
1898 /** Send G, Q, Z and E lines */
1899 void SendXLines(TreeServer* Current)
1903 std::string n = this->Instance->Config->ServerName;
1904 const char* sn = n.c_str();
1906 /* Yes, these arent too nice looking, but they get the job done */
1907 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
1909 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1910 buffer.append(data);
1912 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
1914 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1915 buffer.append(data);
1917 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
1919 snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1920 buffer.append(data);
1922 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
1924 snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1925 buffer.append(data);
1927 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
1929 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1930 buffer.append(data);
1932 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
1934 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1935 buffer.append(data);
1937 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
1939 snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1940 buffer.append(data);
1942 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
1944 snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1945 buffer.append(data);
1948 if (!buffer.empty())
1949 this->WriteLine(buffer);
1952 /** Send channel modes and topics */
1953 void SendChannelModes(TreeServer* Current)
1956 std::deque<std::string> list;
1957 std::string n = this->Instance->Config->ServerName;
1958 const char* sn = n.c_str();
1959 for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
1961 SendFJoins(Current, c->second);
1962 if (*c->second->topic)
1964 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1965 this->WriteLine(data);
1967 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1969 c->second->GetExtList(list);
1970 for (unsigned int j = 0; j < list.size(); j++)
1972 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1977 /** send all users and their oper state/modes */
1978 void SendUsers(TreeServer* Current)
1981 std::deque<std::string> list;
1982 std::string dataline;
1983 for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
1985 if (u->second->registered == REG_ALL)
1987 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);
1988 this->WriteLine(data);
1989 if (*u->second->oper)
1991 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
1992 this->WriteLine(data);
1994 if (*u->second->awaymsg)
1996 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
1997 this->WriteLine(data);
1999 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2001 u->second->GetExtList(list);
2002 for (unsigned int j = 0; j < list.size(); j++)
2004 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2010 /** This function is called when we want to send a netburst to a local
2011 * server. There is a set order we must do this, because for example
2012 * users require their servers to exist, and channels require their
2013 * users to exist. You get the idea.
2015 void DoBurst(TreeServer* s)
2017 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2018 std::string endburst = "ENDBURST";
2019 // Because by the end of the netburst, it could be gone!
2020 std::string name = s->GetName();
2021 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2022 this->WriteLine(burst);
2023 /* send our version string */
2024 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2025 /* Send server tree */
2026 this->SendServers(Utils->TreeRoot,s,1);
2027 /* Send users and their oper status */
2029 /* Send everything else (channel modes, xlines etc) */
2030 this->SendChannelModes(s);
2031 this->SendXLines(s);
2032 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2033 this->WriteLine(endburst);
2034 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2037 /** This function is called when we receive data from a remote
2038 * server. We buffer the data in a std::string (it doesnt stay
2039 * there for long), reading using InspSocket::Read() which can
2040 * read up to 16 kilobytes in one operation.
2042 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2043 * THE SOCKET OBJECT FOR US.
2045 virtual bool OnDataReady()
2047 char* data = this->Read();
2048 /* Check that the data read is a valid pointer and it has some content */
2051 this->in_buffer.append(data);
2052 /* While there is at least one new line in the buffer,
2053 * do something useful (we hope!) with it.
2055 while (in_buffer.find("\n") != std::string::npos)
2057 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2058 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2059 /* Use rfind here not find, as theres more
2060 * chance of the \r being near the end of the
2061 * string, not the start.
2063 if (ret.find("\r") != std::string::npos)
2064 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2065 /* Process this one, abort if it
2066 * didnt return true.
2068 if (!this->ProcessLine(ret))
2075 /* EAGAIN returns an empty but non-NULL string, so this
2076 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2078 return (data && !*data);
2081 int WriteLine(std::string line)
2083 Instance->Log(DEBUG, "-> %s", line.c_str());
2084 line.append("\r\n");
2085 return this->Write(line);
2088 /* Handle ERROR command */
2089 bool Error(std::deque<std::string> ¶ms)
2091 if (params.size() < 1)
2093 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2094 /* we will return false to cause the socket to close. */
2098 /** remote MOTD. leet, huh? */
2099 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
2101 if (params.size() > 0)
2103 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2105 /* It's for our server */
2106 string_list results;
2107 userrec* source = this->Instance->FindNick(prefix);
2111 std::deque<std::string> par;
2112 par.push_back(prefix);
2115 if (!Instance->Config->MOTD.size())
2117 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2118 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2122 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2123 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2125 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2127 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2128 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2131 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2132 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2138 userrec* source = this->Instance->FindNick(prefix);
2140 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2146 /** remote ADMIN. leet, huh? */
2147 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
2149 if (params.size() > 0)
2151 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2153 /* It's for our server */
2154 string_list results;
2155 userrec* source = this->Instance->FindNick(prefix);
2159 std::deque<std::string> par;
2160 par.push_back(prefix);
2163 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2164 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2166 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2167 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2169 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2170 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2172 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2173 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2179 userrec* source = this->Instance->FindNick(prefix);
2181 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2187 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
2189 /* Get the reply to a STATS query if it matches this servername,
2190 * and send it back as a load of PUSH queries
2192 if (params.size() > 1)
2194 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2196 /* It's for our server */
2197 string_list results;
2198 userrec* source = this->Instance->FindNick(prefix);
2201 std::deque<std::string> par;
2202 par.push_back(prefix);
2204 DoStats(this->Instance, *(params[0].c_str()), source, results);
2205 for (size_t i = 0; i < results.size(); i++)
2207 par[1] = "::" + results[i];
2208 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2215 userrec* source = this->Instance->FindNick(prefix);
2217 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2224 /** Because the core won't let users or even SERVERS set +o,
2225 * we use the OPERTYPE command to do this.
2227 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
2229 if (params.size() != 1)
2231 std::string opertype = params[0];
2232 userrec* u = this->Instance->FindNick(prefix);
2235 u->modes[UM_OPERATOR] = 1;
2236 this->Instance->all_opers.push_back(u);
2237 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2238 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2239 this->Instance->SNO->WriteToSnoMask('o',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server, u->nick,u->ident,u->host,irc::Spacify(opertype.c_str()));
2245 /** Because Andy insists that services-compatible servers must
2246 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2248 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
2250 if (params.size() < 3)
2253 userrec* u = this->Instance->FindNick(params[0]);
2257 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2260 std::deque<std::string> par;
2261 par.push_back(params[1]);
2262 /* This is not required as one is sent in OnUserPostNick below
2264 //Utils->DoOneToMany(u->nick,"NICK",par);
2265 if (!u->ForceNickChange(params[1].c_str()))
2267 userrec::QuitUser(this->Instance, u, "Nickname collision");
2270 u->age = atoi(params[2].c_str());
2277 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
2278 * then let that server do the dirty work (squit it!). Example:
2279 * A -> B -> C -> D: oper on A squits D, A routes to B, B routes to C, C notices D connected locally, kills it. -- w00t
2281 bool RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
2283 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
2284 if (params.size() < 2)
2287 TreeServer* s = Utils->FindServerMask(params[0]);
2291 if (s == Utils->TreeRoot)
2293 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
2297 TreeSocket* sock = s->GetSocket();
2301 /* it's locally connected, KILL IT! */
2302 Instance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s: %s", params[0].c_str(), prefix.c_str(), params[1].c_str());
2303 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
2304 Instance->SE->DelFd(sock);
2310 /* route the rsquit */
2311 params[1] = ":" + params[1];
2312 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
2317 /* mother fucker! it doesn't exist */
2323 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
2325 if (params.size() < 2)
2328 userrec* u = this->Instance->FindNick(params[0]);
2332 /* only join if it's local, otherwise just pass it on! */
2334 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2335 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2340 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
2342 if (params.size() < 1)
2345 std::string servermask = params[0];
2347 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2349 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
2350 this->Instance->RehashServer();
2351 Utils->ReadConfiguration(false);
2352 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2354 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2358 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
2360 if (params.size() != 2)
2363 std::string nick = params[0];
2364 userrec* u = this->Instance->FindNick(prefix);
2365 userrec* who = this->Instance->FindNick(nick);
2369 /* Prepend kill source, if we don't have one */
2370 std::string sourceserv = prefix;
2373 sourceserv = u->server;
2375 if (*(params[1].c_str()) != '[')
2377 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2379 std::string reason = params[1];
2380 params[1] = ":" + params[1];
2381 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2382 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2383 userrec::QuitUser(this->Instance,who,reason);
2388 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2390 if (params.size() < 1)
2393 if (params.size() == 1)
2395 TreeServer* ServerSource = Utils->FindServer(prefix);
2398 ServerSource->SetPingFlag();
2403 std::string forwardto = params[1];
2404 if (forwardto == this->Instance->Config->ServerName)
2407 * this is a PONG for us
2408 * if the prefix is a user, check theyre local, and if they are,
2409 * dump the PONG reply back to their fd. If its a server, do nowt.
2410 * Services might want to send these s->s, but we dont need to yet.
2412 userrec* u = this->Instance->FindNick(prefix);
2416 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2421 // not for us, pass it on :)
2422 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2429 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2431 if (params.size() < 3)
2434 TreeServer* ServerSource = Utils->FindServer(prefix);
2438 if (params[0] == "*")
2440 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2442 else if (*(params[0].c_str()) == '#')
2444 chanrec* c = this->Instance->FindChan(params[0]);
2447 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2450 else if (*(params[0].c_str()) != '#')
2452 userrec* u = this->Instance->FindNick(params[0]);
2455 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2460 params[2] = ":" + params[2];
2461 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2465 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2467 if (params.size() < 1)
2470 TreeServer* ServerSource = Utils->FindServer(prefix);
2474 ServerSource->SetVersion(params[0]);
2476 params[0] = ":" + params[0];
2477 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2481 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2483 if (params.size() < 1)
2486 userrec* u = this->Instance->FindNick(prefix);
2490 u->ChangeDisplayedHost(params[0].c_str());
2491 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2496 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2498 if (params.size() < 6)
2501 bool propogate = false;
2503 if (!this->bursting)
2504 Utils->lines_to_apply = 0;
2506 switch (*(params[0].c_str()))
2509 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2510 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2512 Utils->lines_to_apply |= APPLY_ZLINES;
2515 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2516 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2518 Utils->lines_to_apply |= APPLY_QLINES;
2521 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2522 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2525 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2526 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2528 Utils->lines_to_apply |= APPLY_GLINES;
2531 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2533 Utils->lines_to_apply |= APPLY_KLINES;
2536 /* Just in case... */
2537 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2542 /* Send it on its way */
2545 if (atoi(params[4].c_str()))
2547 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());
2551 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());
2553 params[5] = ":" + params[5];
2554 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2556 if (!this->bursting)
2558 Instance->XLines->apply_lines(Utils->lines_to_apply);
2559 Utils->lines_to_apply = 0;
2564 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2566 if (params.size() < 1)
2569 userrec* u = this->Instance->FindNick(prefix);
2573 u->ChangeName(params[0].c_str());
2574 params[0] = ":" + params[0];
2575 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2580 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2582 if (params.size() < 1)
2585 userrec* u = this->Instance->FindNick(prefix);
2588 // an incoming request
2589 if (params.size() == 1)
2591 userrec* x = this->Instance->FindNick(params[0]);
2592 if ((x) && (IS_LOCAL(x)))
2594 userrec* x = this->Instance->FindNick(params[0]);
2595 char signon[MAXBUF];
2598 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2599 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2600 std::deque<std::string> par;
2601 par.push_back(prefix);
2602 par.push_back(signon);
2603 par.push_back(idle);
2604 // ours, we're done, pass it BACK
2605 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2609 // not ours pass it on
2610 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2613 else if (params.size() == 3)
2615 std::string who_did_the_whois = params[0];
2616 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2617 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2619 // an incoming reply to a whois we sent out
2620 std::string nick_whoised = prefix;
2621 unsigned long signon = atoi(params[1].c_str());
2622 unsigned long idle = atoi(params[2].c_str());
2623 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2624 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2628 // not ours, pass it on
2629 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2636 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2638 if (params.size() < 2)
2641 userrec* u = this->Instance->FindNick(params[0]);
2648 u->Write(params[1]);
2652 // continue the raw onwards
2653 params[1] = ":" + params[1];
2654 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2659 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2661 if (!params.size() || !Utils->EnableTimeSync)
2666 if ((params.size() == 2) && (params[1] == "FORCE"))
2669 time_t rts = atoi(params[0].c_str());
2670 time_t us = Instance->Time(true);
2674 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2676 else if (force || (rts < us))
2678 int old = Instance->SetTimeDelta(rts - us);
2679 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2681 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2685 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2687 std::deque<std::string> oparams;
2688 oparams.push_back(ConvToStr(us));
2690 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2696 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2698 // :source.server TIME remote.server sendernick
2699 // :remote.server TIME source.server sendernick TS
2700 if (params.size() == 2)
2702 // someone querying our time?
2703 if (this->Instance->Config->ServerName == params[0])
2705 userrec* u = this->Instance->FindNick(params[1]);
2708 params.push_back(ConvToStr(Instance->Time(false)));
2710 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2715 // not us, pass it on
2716 userrec* u = this->Instance->FindNick(params[1]);
2718 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2721 else if (params.size() == 3)
2723 // a response to a previous TIME
2724 userrec* u = this->Instance->FindNick(params[1]);
2725 if ((u) && (IS_LOCAL(u)))
2727 time_t rawtime = atol(params[2].c_str());
2728 struct tm * timeinfo;
2729 timeinfo = localtime(&rawtime);
2731 snprintf(tms,26,"%s",asctime(timeinfo));
2733 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2738 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2744 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2746 if (params.size() < 1)
2749 if (params.size() == 1)
2751 std::string stufftobounce = params[0];
2752 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2757 std::string forwardto = params[1];
2758 if (forwardto == this->Instance->Config->ServerName)
2760 // this is a ping for us, send back PONG to the requesting server
2761 params[1] = params[0];
2762 params[0] = forwardto;
2763 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2767 // not for us, pass it on :)
2768 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2774 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2776 if (params.size() < 1)
2779 chanrec* c = Instance->FindChan(params[0]);
2783 irc::modestacker modestack(false);
2784 CUList *ulist = c->GetUsers();
2786 std::deque<std::string> stackresult;
2789 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2791 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2792 if (modesequence.length())
2794 irc::spacesepstream sep(modesequence);
2795 std::string modeletters = sep.GetToken();
2797 while (!modeletters.empty())
2799 char mletter = *(modeletters.begin());
2800 modestack.Push(mletter,sep.GetToken());
2801 modeletters.erase(modeletters.begin());
2806 while (modestack.GetStackedLine(stackresult))
2808 stackresult.push_front(ConvToStr(c->age));
2809 stackresult.push_front(c->name);
2810 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2811 stackresult.erase(stackresult.begin() + 1);
2812 for (size_t z = 0; z < stackresult.size(); z++)
2814 y[z] = stackresult[z].c_str();
2816 userrec* n = new userrec(Instance);
2817 n->SetFd(FD_MAGIC_NUMBER);
2818 Instance->SendMode(y, stackresult.size(), n);
2825 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2827 if (params.size() < 4)
2830 std::string servername = params[0];
2831 std::string password = params[1];
2832 // hopcount is not used for a remote server, we calculate this ourselves
2833 std::string description = params[3];
2834 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2838 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2841 TreeServer* CheckDupe = Utils->FindServer(servername);
2844 this->WriteLine("ERROR :Server "+servername+" already exists!");
2845 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2848 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2849 ParentOfThis->AddChild(Node);
2850 params[3] = ":" + params[3];
2851 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2852 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2856 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2858 if (params.size() < 4)
2861 irc::string servername = params[0].c_str();
2862 std::string sname = params[0];
2863 std::string password = params[1];
2864 int hops = atoi(params[2].c_str());
2868 this->WriteLine("ERROR :Server too far away for authentication");
2869 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2872 std::string description = params[3];
2873 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2875 if ((x->Name == servername) && (x->RecvPass == password))
2877 TreeServer* CheckDupe = Utils->FindServer(sname);
2880 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2881 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2884 // Begin the sync here. this kickstarts the
2885 // other side, waiting in WAIT_AUTH_2 state,
2886 // into starting their burst, as it shows
2887 // that we're happy.
2888 this->LinkState = CONNECTED;
2889 // we should add the details of this server now
2890 // to the servers tree, as a child of the root
2892 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2893 Utils->TreeRoot->AddChild(Node);
2894 params[3] = ":" + params[3];
2895 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2896 this->bursting = true;
2897 this->DoBurst(Node);
2901 this->WriteLine("ERROR :Invalid credentials");
2902 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2906 bool Inbound_Server(std::deque<std::string> ¶ms)
2908 if (params.size() < 4)
2911 irc::string servername = params[0].c_str();
2912 std::string sname = params[0];
2913 std::string password = params[1];
2914 int hops = atoi(params[2].c_str());
2918 this->WriteLine("ERROR :Server too far away for authentication");
2919 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2922 std::string description = params[3];
2923 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2925 if ((x->Name == servername) && (x->RecvPass == password))
2927 TreeServer* CheckDupe = Utils->FindServer(sname);
2930 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2931 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2934 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2938 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
2939 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
2942 this->InboundServerName = sname;
2943 this->InboundDescription = description;
2944 // this is good. Send our details: Our server name and description and hopcount of 0,
2945 // along with the sendpass from this block.
2946 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2947 // move to the next state, we are now waiting for THEM.
2948 this->LinkState = WAIT_AUTH_2;
2952 this->WriteLine("ERROR :Invalid credentials");
2953 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2957 void Split(const std::string &line, std::deque<std::string> &n)
2960 irc::tokenstream tokens(line);
2962 while ((param = tokens.GetToken()) != "")
2967 bool ProcessLine(std::string &line)
2969 std::deque<std::string> params;
2970 irc::string command;
2973 line = line.substr(0, line.find_first_of("\r\n"));
2978 Instance->Log(DEBUG, "<- %s", line.c_str());
2980 this->Split(line.c_str(),params);
2982 if ((params[0][0] == ':') && (params.size() > 1))
2984 prefix = params[0].substr(1);
2988 command = params[0].c_str();
2991 switch (this->LinkState)
2996 // Waiting for SERVER command from remote server. Server initiating
2997 // the connection sends the first SERVER command, listening server
2998 // replies with theirs if its happy, then if the initiator is happy,
2999 // it starts to send its net sync, which starts the merge, otherwise
3000 // it sends an ERROR.
3001 if (command == "PASS")
3003 /* Silently ignored */
3005 else if (command == "SERVER")
3007 return this->Inbound_Server(params);
3009 else if (command == "ERROR")
3011 return this->Error(params);
3013 else if (command == "USER")
3015 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3018 else if (command == "CAPAB")
3020 return this->Capab(params);
3022 else if ((command == "U") || (command == "S"))
3024 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3029 std::string error("ERROR :Invalid command in negotiation phase: ");
3030 error.append(command.c_str());
3031 this->WriteLine(error);
3036 // Waiting for start of other side's netmerge to say they liked our
3038 if (command == "SERVER")
3040 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3044 else if ((command == "U") || (command == "S"))
3046 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3049 else if (command == "BURST")
3051 if (params.size() && Utils->EnableTimeSync)
3053 /* If a time stamp is provided, apply synchronization */
3055 time_t them = atoi(params[0].c_str());
3056 time_t us = Instance->Time(true);
3057 int delta = them - us;
3059 if ((params.size() == 2) && (params[1] == "FORCE"))
3062 if ((delta < -600) || (delta > 600))
3064 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));
3065 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3069 if (force || (us > them))
3071 this->Instance->SetTimeDelta(them - us);
3072 // Send this new timestamp to any other servers
3073 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3077 // Override the timestamp
3078 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3081 this->LinkState = CONNECTED;
3082 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3083 Utils->TreeRoot->AddChild(Node);
3085 params.push_back(InboundServerName);
3086 params.push_back("*");
3087 params.push_back("1");
3088 params.push_back(":"+InboundDescription);
3089 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3090 this->bursting = true;
3091 this->DoBurst(Node);
3093 else if (command == "ERROR")
3095 return this->Error(params);
3097 else if (command == "CAPAB")
3099 return this->Capab(params);
3104 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3108 if (command == "SERVER")
3110 // another server we connected to, which was in WAIT_AUTH_1 state,
3111 // has just sent us their credentials. If we get this far, theyre
3112 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3113 // if we're happy with this, we should send our netburst which
3114 // kickstarts the merge.
3115 return this->Outbound_Reply_Server(params);
3117 else if (command == "ERROR")
3119 return this->Error(params);
3123 // This is the 'authenticated' state, when all passwords
3124 // have been exchanged and anything past this point is taken
3129 std::string direction = prefix;
3130 userrec* t = this->Instance->FindNick(prefix);
3133 direction = t->server;
3135 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3136 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3138 if (route_back_again)
3139 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3144 * When there is activity on the socket, reset the ping counter so
3145 * that we're not wasting bandwidth pinging an active server.
3147 route_back_again->SetNextPingTime(time(NULL) + 60);
3148 route_back_again->SetPingFlag();
3151 if (command == "SVSMODE")
3153 /* Services expects us to implement
3154 * SVSMODE. In inspircd its the same as
3159 std::string target = "";
3160 /* Yes, know, this is a mess. Its reasonably fast though as we're
3161 * working with std::string here.
3163 if ((command == "NICK") && (params.size() > 1))
3165 return this->IntroduceClient(prefix,params);
3167 else if (command == "FJOIN")
3169 return this->ForceJoin(prefix,params);
3171 else if (command == "STATS")
3173 return this->Stats(prefix, params);
3175 else if (command == "MOTD")
3177 return this->Motd(prefix, params);
3179 else if (command == "ADMIN")
3181 return this->Admin(prefix, params);
3183 else if (command == "SERVER")
3185 return this->RemoteServer(prefix,params);
3187 else if (command == "ERROR")
3189 return this->Error(params);
3191 else if (command == "OPERTYPE")
3193 return this->OperType(prefix,params);
3195 else if (command == "FMODE")
3197 return this->ForceMode(prefix,params);
3199 else if (command == "KILL")
3201 return this->RemoteKill(prefix,params);
3203 else if (command == "FTOPIC")
3205 return this->ForceTopic(prefix,params);
3207 else if (command == "REHASH")
3209 return this->RemoteRehash(prefix,params);
3211 else if (command == "METADATA")
3213 return this->MetaData(prefix,params);
3215 else if (command == "REMSTATUS")
3217 return this->RemoveStatus(prefix,params);
3219 else if (command == "PING")
3222 * We just got a ping from a server that's bursting.
3223 * This can't be right, so set them to not bursting, and
3224 * apply their lines.
3228 this->bursting = false;
3229 Instance->XLines->apply_lines(Utils->lines_to_apply);
3230 Utils->lines_to_apply = 0;
3234 prefix = this->GetName();
3236 return this->LocalPing(prefix,params);
3238 else if (command == "PONG")
3241 * We just got a pong from a server that's bursting.
3242 * This can't be right, so set them to not bursting, and
3243 * apply their lines.
3247 this->bursting = false;
3248 Instance->XLines->apply_lines(Utils->lines_to_apply);
3249 Utils->lines_to_apply = 0;
3253 prefix = this->GetName();
3255 return this->LocalPong(prefix,params);
3257 else if (command == "VERSION")
3259 return this->ServerVersion(prefix,params);
3261 else if (command == "FHOST")
3263 return this->ChangeHost(prefix,params);
3265 else if (command == "FNAME")
3267 return this->ChangeName(prefix,params);
3269 else if (command == "ADDLINE")
3271 return this->AddLine(prefix,params);
3273 else if (command == "SVSNICK")
3277 prefix = this->GetName();
3279 return this->ForceNick(prefix,params);
3281 else if (command == "RSQUIT")
3283 return this->RemoteSquit(prefix, params);
3285 else if (command == "IDLE")
3287 return this->Whois(prefix,params);
3289 else if (command == "PUSH")
3291 return this->Push(prefix,params);
3293 else if (command == "TIMESET")
3295 return this->HandleSetTime(prefix, params);
3297 else if (command == "TIME")
3299 return this->Time(prefix,params);
3301 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3303 std::string sourceserv = this->myhost;
3304 if (params.size() == 3)
3306 userrec* user = this->Instance->FindNick(params[1]);
3307 chanrec* chan = this->Instance->FindChan(params[0]);
3310 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3311 /* Yikes, the channels gone! */
3315 if (this->InboundServerName != "")
3317 sourceserv = this->InboundServerName;
3319 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3321 else if (command == "SVSJOIN")
3325 prefix = this->GetName();
3327 return this->ServiceJoin(prefix,params);
3329 else if (command == "SQUIT")
3331 if (params.size() == 2)
3333 this->Squit(Utils->FindServer(params[0]),params[1]);
3337 else if (command == "OPERNOTICE")
3339 std::string sourceserv = this->myhost;
3341 if (this->InboundServerName != "")
3342 sourceserv = this->InboundServerName;
3344 if (params.size() >= 1)
3345 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3347 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3349 else if (command == "MODENOTICE")
3351 std::string sourceserv = this->myhost;
3352 if (this->InboundServerName != "")
3353 sourceserv = this->InboundServerName;
3354 if (params.size() >= 2)
3356 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3359 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3361 else if (command == "SNONOTICE")
3363 std::string sourceserv = this->myhost;
3364 if (this->InboundServerName != "")
3365 sourceserv = this->InboundServerName;
3366 if (params.size() >= 2)
3368 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3371 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3373 else if (command == "ENDBURST")
3375 this->bursting = false;
3376 Instance->XLines->apply_lines(Utils->lines_to_apply);
3377 Utils->lines_to_apply = 0;
3378 std::string sourceserv = this->myhost;
3379 if (this->InboundServerName != "")
3381 sourceserv = this->InboundServerName;
3383 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3385 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3386 rmode.Send(Instance);
3392 // not a special inter-server command.
3393 // Emulate the actual user doing the command,
3394 // this saves us having a huge ugly parser.
3395 userrec* who = this->Instance->FindNick(prefix);
3396 std::string sourceserv = this->myhost;
3397 if (this->InboundServerName != "")
3399 sourceserv = this->InboundServerName;
3401 if ((!who) && (command == "MODE"))
3403 if (Utils->IsServer(prefix))
3405 const char* modelist[127];
3406 for (size_t i = 0; i < params.size(); i++)
3407 modelist[i] = params[i].c_str();
3409 userrec* fake = new userrec(Instance);
3410 fake->SetFd(FD_MAGIC_NUMBER);
3412 this->Instance->SendMode(modelist, params.size(), fake);
3416 /* Hot potato! pass it on! */
3417 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3422 if ((command == "NICK") && (params.size() > 0))
3424 /* On nick messages, check that the nick doesnt
3425 * already exist here. If it does, kill their copy,
3428 userrec* x = this->Instance->FindNick(params[0]);
3429 if ((x) && (x != who))
3431 std::deque<std::string> p;
3432 p.push_back(params[0]);
3433 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3434 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3436 p.push_back(prefix);
3437 p.push_back("Nickname collision");
3438 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3439 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3440 userrec* y = this->Instance->FindNick(prefix);
3443 userrec::QuitUser(this->Instance,y,"Nickname collision");
3445 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3449 target = who->server;
3450 const char* strparams[127];
3451 for (unsigned int q = 0; q < params.size(); q++)
3453 strparams[q] = params[q].c_str();
3455 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3458 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3465 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3471 // its not a user. Its either a server, or somethings screwed up.
3472 if (Utils->IsServer(prefix))
3473 target = this->Instance->Config->ServerName;
3477 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3486 virtual std::string GetName()
3488 std::string sourceserv = this->myhost;
3489 if (this->InboundServerName != "")
3491 sourceserv = this->InboundServerName;
3496 virtual void OnTimeout()
3498 if (this->LinkState == CONNECTING)
3500 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3501 Link* MyLink = Utils->FindLink(myhost);
3503 Utils->DoFailOver(MyLink);
3507 virtual void OnClose()
3509 // Connection closed.
3510 // If the connection is fully up (state CONNECTED)
3511 // then propogate a netsplit to all peers.
3512 std::string quitserver = this->myhost;
3513 if (this->InboundServerName != "")
3515 quitserver = this->InboundServerName;
3517 TreeServer* s = Utils->FindServer(quitserver);
3520 Squit(s,"Remote host closed the connection");
3523 if (quitserver != "")
3524 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3527 virtual int OnIncomingConnection(int newsock, char* ip)
3529 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3530 * or discovering if this port is the server port, we don't allow connections from any
3531 * IPs for which we don't have a link block.
3535 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3538 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3539 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3544 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3550 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
3552 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3557 /** This class is used to resolve server hostnames during /connect and autoconnect.
3558 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3559 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3560 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3561 * will have an IP address which we can then use to continue our connection.
3563 class ServernameResolver : public Resolver
3566 /** A copy of the Link tag info for what we're connecting to.
3567 * We take a copy, rather than using a pointer, just in case the
3568 * admin takes the tag away and rehashes while the domain is resolving.
3571 SpanningTreeUtilities* Utils;
3573 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(Util)
3575 /* Nothing in here, folks */
3578 void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
3580 /* Initiate the connection, now that we have an IP to use.
3581 * Passing a hostname directly to InspSocket causes it to
3582 * just bail and set its FD to -1.
3584 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3585 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3588 if ((!MyLink.Hook.empty()) && (Utils->hooks.find(MyLink.Hook.c_str()) == Utils->hooks.end()))
3591 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str(),
3592 MyLink.Hook.empty() ? NULL : Utils->hooks[MyLink.Hook.c_str()]);
3593 if (newsocket->GetFd() > -1)
3599 /* Something barfed, show the opers */
3600 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3602 Utils->DoFailOver(&MyLink);
3607 void OnError(ResolverError e, const std::string &errormessage)
3610 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3611 Utils->DoFailOver(&MyLink);
3615 /** Handle resolving of server IPs for the cache
3617 class SecurityIPResolver : public Resolver
3621 SpanningTreeUtilities* Utils;
3623 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(U)
3627 void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
3629 Utils->ValidIPs.push_back(result);
3632 void OnError(ResolverError e, const std::string &errormessage)
3634 ServerInstance->Log(DEFAULT,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3638 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3644 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3646 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
3648 /* Did we find any modules? */
3651 /* Yes, enumerate them all to find out the hook name */
3652 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
3654 /* Make a request to it for its name, its implementing
3655 * InspSocketHook so we know its safe to do this
3657 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
3658 /* Build a map of them */
3659 hooks[name.c_str()] = *m;
3660 hooknames.push_back(name);
3664 this->ReadConfiguration(true);
3667 SpanningTreeUtilities::~SpanningTreeUtilities()
3669 for (unsigned int i = 0; i < Bindings.size(); i++)
3671 ServerInstance->SE->DelFd(Bindings[i]);
3672 Bindings[i]->Close();
3673 DELETE(Bindings[i]);
3675 while (TreeRoot->ChildCount())
3677 TreeServer* child_server = TreeRoot->GetChild(0);
3680 TreeSocket* sock = child_server->GetSocket();
3681 ServerInstance->SE->DelFd(sock);
3689 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
3691 if (list.find(server) == list.end())
3692 list[server] = server;
3695 /** returns a list of DIRECT servernames for a specific channel */
3696 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
3702 ulist = c->GetOppedUsers();
3705 ulist = c->GetHalfoppedUsers();
3708 ulist = c->GetVoicedUsers();
3711 ulist = c->GetUsers();
3714 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3716 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
3718 TreeServer* best = this->BestRouteTo(i->second->server);
3720 AddThisServer(best,list);
3726 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3729 TreeServer* omitroute = this->BestRouteTo(omit);
3730 if ((command == "NOTICE") || (command == "PRIVMSG"))
3732 if (params.size() >= 2)
3735 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3738 params[0] = params[0].substr(1, params[0].length()-1);
3740 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3742 // special routing for private messages/notices
3743 userrec* d = ServerInstance->FindNick(params[0]);
3746 std::deque<std::string> par;
3747 par.push_back(params[0]);
3748 par.push_back(":"+params[1]);
3749 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3753 else if (*(params[0].c_str()) == '$')
3755 std::deque<std::string> par;
3756 par.push_back(params[0]);
3757 par.push_back(":"+params[1]);
3758 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3763 chanrec* c = ServerInstance->FindChan(params[0]);
3764 userrec* u = ServerInstance->FindNick(prefix);
3768 TreeServerList list;
3769 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
3770 GetListOfServersForChannel(c,list,pfx,elist);
3772 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
3774 TreeSocket* Sock = i->second->GetSocket();
3775 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
3777 Sock->WriteLine(data);
3785 unsigned int items =this->TreeRoot->ChildCount();
3786 for (unsigned int x = 0; x < items; x++)
3788 TreeServer* Route = this->TreeRoot->GetChild(x);
3789 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3791 TreeSocket* Sock = Route->GetSocket();
3793 Sock->WriteLine(data);
3799 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
3801 TreeServer* omitroute = this->BestRouteTo(omit);
3802 std::string FullLine = ":" + prefix + " " + command;
3803 unsigned int words = params.size();
3804 for (unsigned int x = 0; x < words; x++)
3806 FullLine = FullLine + " " + params[x];
3808 unsigned int items = this->TreeRoot->ChildCount();
3809 for (unsigned int x = 0; x < items; x++)
3811 TreeServer* Route = this->TreeRoot->GetChild(x);
3812 // Send the line IF:
3813 // The route has a socket (its a direct connection)
3814 // The route isnt the one to be omitted
3815 // The route isnt the path to the one to be omitted
3816 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3818 TreeSocket* Sock = Route->GetSocket();
3820 Sock->WriteLine(FullLine);
3826 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
3828 std::string FullLine = ":" + prefix + " " + command;
3829 unsigned int words = params.size();
3830 for (unsigned int x = 0; x < words; x++)
3832 FullLine = FullLine + " " + params[x];
3834 unsigned int items = this->TreeRoot->ChildCount();
3835 for (unsigned int x = 0; x < items; x++)
3837 TreeServer* Route = this->TreeRoot->GetChild(x);
3838 if (Route && Route->GetSocket())
3840 TreeSocket* Sock = Route->GetSocket();
3842 Sock->WriteLine(FullLine);
3848 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3850 std::string spfx = prefix;
3851 std::string scmd = command;
3852 return this->DoOneToMany(spfx, scmd, params);
3855 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3857 std::string spfx = prefix;
3858 std::string scmd = command;
3859 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3862 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
3864 TreeServer* Route = this->BestRouteTo(target);
3867 std::string FullLine = ":" + prefix + " " + command;
3868 unsigned int words = params.size();
3869 for (unsigned int x = 0; x < words; x++)
3871 FullLine = FullLine + " " + params[x];
3873 if (Route && Route->GetSocket())
3875 TreeSocket* Sock = Route->GetSocket();
3877 Sock->WriteLine(FullLine);
3887 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3889 ConfigReader* Conf = new ConfigReader(ServerInstance);
3892 for (int j =0; j < Conf->Enumerate("bind"); j++)
3894 std::string Type = Conf->ReadValue("bind","type",j);
3895 std::string IP = Conf->ReadValue("bind","address",j);
3896 std::string Port = Conf->ReadValue("bind","port",j);
3897 std::string transport = Conf->ReadValue("bind","transport",j);
3898 if (Type == "servers")
3900 irc::portparser portrange(Port, false);
3902 while ((portno = portrange.GetToken()))
3907 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
3909 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for port %s:%s - maybe you forgot to load it BEFORE m_spanningtree in your config file? - Skipping this port binding",
3910 transport.c_str(), IP.c_str(), Port.c_str());
3914 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
3915 if (listener->GetState() == I_LISTENING)
3917 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
3918 Bindings.push_back(listener);
3922 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
3930 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3931 HideULines = Conf->ReadFlag("options","hideulines",0);
3932 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3933 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3936 for (int j =0; j < Conf->Enumerate("link"); j++)
3939 std::string Allow = Conf->ReadValue("link","allowmask",j);
3940 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3941 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3942 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3943 L.Port = Conf->ReadInteger("link","port",j,true);
3944 L.SendPass = Conf->ReadValue("link","sendpass",j);
3945 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3946 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3947 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3948 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
3949 L.Hook = Conf->ReadValue("link", "transport", j);
3951 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
3953 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for link '%s' - maybe you forgot to load it BEFORE m_spanningtree in your config file? Skipping <link> tag completely.",
3954 L.Hook.c_str(), L.Name.c_str());
3959 L.NextConnectTime = time(NULL) + L.AutoConnect;
3960 /* Bugfix by brain, do not allow people to enter bad configurations */
3961 if (L.Name != ServerInstance->Config->ServerName)
3963 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3965 ValidIPs.push_back(L.IPAddr);
3968 ValidIPs.push_back(Allow);
3970 /* Needs resolving */
3972 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3977 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached);
3978 ServerInstance->AddResolver(sr, cached);
3980 catch (ModuleException& e)
3985 LinkBlocks.push_back(L);
3991 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3993 else if (L.RecvPass == "")
3995 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3997 else if (L.SendPass == "")
3999 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4001 else if (L.Name == "")
4003 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4007 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4013 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4019 /** To create a timer which recurs every second, we inherit from InspTimer.
4020 * InspTimer is only one-shot however, so at the end of each Tick() we simply
4021 * insert another of ourselves into the pending queue :)
4023 class TimeSyncTimer : public InspTimer
4027 ModuleSpanningTree *Module;
4029 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4030 virtual void Tick(time_t TIME);
4033 HandshakeTimer::HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u) : InspTimer(1, time(NULL)), Instance(Inst), sock(s), lnk(l), Utils(u)
4035 thefd = sock->GetFd();
4038 void HandshakeTimer::Tick(time_t TIME)
4040 if (Instance->SE->GetRef(thefd) == sock)
4042 if (sock->GetHook() && InspSocketHSCompleteRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send())
4044 InspSocketAttachCertRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send();
4045 sock->SendCapabilities();
4046 if (sock->GetLinkState() == CONNECTING)
4048 sock->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+lnk->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
4053 Instance->Timers->AddTimer(new HandshakeTimer(Instance, sock, lnk, Utils));
4058 class ModuleSpanningTree : public Module
4062 unsigned int max_local;
4063 unsigned int max_global;
4064 cmd_rconnect* command_rconnect;
4065 SpanningTreeUtilities* Utils;
4068 TimeSyncTimer *SyncTimer;
4070 ModuleSpanningTree(InspIRCd* Me)
4071 : Module::Module(Me), max_local(0), max_global(0)
4073 ServerInstance->UseInterface("InspSocketHook");
4075 Utils = new SpanningTreeUtilities(Me, this);
4077 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4078 ServerInstance->AddCommand(command_rconnect);
4080 if (Utils->EnableTimeSync)
4082 SyncTimer = new TimeSyncTimer(ServerInstance, this);
4083 ServerInstance->Timers->AddTimer(SyncTimer);
4089 void ShowLinks(TreeServer* Current, userrec* user, int hops)
4091 std::string Parent = Utils->TreeRoot->GetName();
4092 if (Current->GetParent())
4094 Parent = Current->GetParent()->GetName();
4096 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4098 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4102 ShowLinks(Current->GetChild(q),user,hops+1);
4107 ShowLinks(Current->GetChild(q),user,hops+1);
4110 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4111 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4113 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());
4116 int CountLocalServs()
4118 return Utils->TreeRoot->ChildCount();
4123 return Utils->serverlist.size();
4126 void HandleLinks(const char** parameters, int pcnt, userrec* user)
4128 ShowLinks(Utils->TreeRoot,user,0);
4129 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4133 void HandleLusers(const char** parameters, int pcnt, userrec* user)
4135 unsigned int n_users = ServerInstance->UserCount();
4137 /* Only update these when someone wants to see them, more efficient */
4138 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4139 max_local = ServerInstance->LocalUserCount();
4140 if (n_users > max_global)
4141 max_global = n_users;
4143 unsigned int ulined_count = 0;
4144 unsigned int ulined_local_count = 0;
4146 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4147 * locally and globally (locally means directly connected to us)
4149 if ((Utils->HideULines) && (!*user->oper))
4151 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4153 if (ServerInstance->ULine(q->second->GetName().c_str()))
4156 if (q->second->GetParent() == Utils->TreeRoot)
4157 ulined_local_count++;
4162 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),ulined_count ? this->CountServs() - ulined_count : this->CountServs());
4163 if (ServerInstance->OperCount())
4164 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4165 if (ServerInstance->UnregisteredUserCount())
4166 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4167 if (ServerInstance->ChannelCount())
4168 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4169 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs());
4170 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4171 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
4175 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4177 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4181 for (int t = 0; t < depth; t++)
4183 matrix[line][t] = ' ';
4186 // For Aligning, we need to work out exactly how deep this thing is, and produce
4187 // a 'Spacer' String to compensate.
4190 memset(spacer,' ',40);
4191 if ((40 - Current->GetName().length() - depth) > 1) {
4192 spacer[40 - Current->GetName().length() - depth] = '\0';
4201 if (ServerInstance->clientlist->size() == 0) {
4202 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4207 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist->size()) * 100;
4209 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4210 totusers += Current->GetUserCount();
4212 strlcpy(&matrix[line][depth],text,80);
4214 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4216 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4220 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4225 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4231 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4235 /* Remote MOTD, the server is within the 1st parameter */
4236 std::deque<std::string> params;
4237 params.push_back(parameters[0]);
4239 /* Send it out remotely, generate no reply yet */
4240 TreeServer* s = Utils->FindServerMask(parameters[0]);
4243 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4247 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4254 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4258 /* Remote ADMIN, the server is within the 1st parameter */
4259 std::deque<std::string> params;
4260 params.push_back(parameters[0]);
4262 /* Send it out remotely, generate no reply yet */
4263 TreeServer* s = Utils->FindServerMask(parameters[0]);
4266 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4270 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4277 int HandleStats(const char** parameters, int pcnt, userrec* user)
4281 /* Remote STATS, the server is within the 2nd parameter */
4282 std::deque<std::string> params;
4283 params.push_back(parameters[0]);
4284 params.push_back(parameters[1]);
4285 /* Send it out remotely, generate no reply yet */
4286 TreeServer* s = Utils->FindServerMask(parameters[1]);
4289 params[1] = s->GetName();
4290 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4294 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4301 // Ok, prepare to be confused.
4302 // After much mulling over how to approach this, it struck me that
4303 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4304 // keeping track of a ton of ascii characters, and line by line
4305 // under recursion working out where to place them using multiplications
4306 // and divisons, we instead render the map onto a backplane of characters
4307 // (a character matrix), then draw the branches as a series of "L" shapes
4308 // from the nodes. This is not only friendlier on CPU it uses less stack.
4310 void HandleMap(const char** parameters, int pcnt, userrec* user)
4312 // This array represents a virtual screen which we will
4313 // "scratch" draw to, as the console device of an irc
4314 // client does not provide for a proper terminal.
4316 float totservers = 0;
4317 char matrix[128][80];
4318 for (unsigned int t = 0; t < 128; t++)
4320 matrix[t][0] = '\0';
4323 // The only recursive bit is called here.
4324 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4325 // Process each line one by one. The algorithm has a limit of
4326 // 128 servers (which is far more than a spanning tree should have
4327 // anyway, so we're ok). This limit can be raised simply by making
4328 // the character matrix deeper, 128 rows taking 10k of memory.
4329 for (int l = 1; l < line; l++)
4331 // scan across the line looking for the start of the
4332 // servername (the recursive part of the algorithm has placed
4333 // the servers at indented positions depending on what they
4335 int first_nonspace = 0;
4336 while (matrix[l][first_nonspace] == ' ')
4341 // Draw the `- (corner) section: this may be overwritten by
4342 // another L shape passing along the same vertical pane, becoming
4343 // a |- (branch) section instead.
4344 matrix[l][first_nonspace] = '-';
4345 matrix[l][first_nonspace-1] = '`';
4347 // Draw upwards until we hit the parent server, causing possibly
4348 // other corners (`-) to become branches (|-)
4349 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4351 matrix[l2][first_nonspace-1] = '|';
4355 // dump the whole lot to the user. This is the easy bit, honest.
4356 for (int t = 0; t < line; t++)
4358 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4360 float avg_users = totusers / totservers;
4361 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);
4362 user->WriteServ("007 %s :End of /MAP",user->nick);
4366 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4368 TreeServer* s = Utils->FindServerMask(parameters[0]);
4371 if (s == Utils->TreeRoot)
4373 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4376 TreeSocket* sock = s->GetSocket();
4379 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4380 sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost());
4381 ServerInstance->SE->DelFd(sock);
4388 std::deque<std::string> params;
4389 params.push_back(parameters[0]);
4390 params.push_back(std::string(":Server quit by ") + user->GetFullRealHost());
4391 Utils->DoOneToOne(user->nick, "RSQUIT", params, parameters[0]);
4396 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4401 int HandleTime(const char** parameters, int pcnt, userrec* user)
4403 if ((IS_LOCAL(user)) && (pcnt))
4405 TreeServer* found = Utils->FindServerMask(parameters[0]);
4408 // we dont' override for local server
4409 if (found == Utils->TreeRoot)
4412 std::deque<std::string> params;
4413 params.push_back(found->GetName());
4414 params.push_back(user->nick);
4415 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4419 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4425 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4427 if ((IS_LOCAL(user)) && (pcnt > 1))
4429 userrec* remote = ServerInstance->FindNick(parameters[1]);
4430 if ((remote) && (remote->GetFd() < 0))
4432 std::deque<std::string> params;
4433 params.push_back(parameters[1]);
4434 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4439 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4440 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4447 void DoPingChecks(time_t curtime)
4449 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4451 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4452 TreeSocket* sock = serv->GetSocket();
4455 if (curtime >= serv->NextPingTime())
4457 if (serv->AnsweredLastPing())
4459 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4460 serv->SetNextPingTime(curtime + 60);
4464 // they didnt answer, boot them
4465 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4466 sock->Squit(serv,"Ping timeout");
4467 ServerInstance->SE->DelFd(sock);
4477 void ConnectServer(Link* x)
4481 /* Do we already have an IP? If so, no need to resolve it. */
4482 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4484 /* Gave a hook, but it wasnt one we know */
4485 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
4488 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str(), x->Hook.empty() ? NULL : Utils->hooks[x->Hook.c_str()]);
4489 if (newsocket->GetFd() > -1)
4491 /* Handled automatically on success */
4495 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4497 Utils->DoFailOver(x);
4505 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached);
4506 ServerInstance->AddResolver(snr, cached);
4508 catch (ModuleException& e)
4510 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
4511 Utils->DoFailOver(x);
4516 void AutoConnectServers(time_t curtime)
4518 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4520 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4522 x->NextConnectTime = curtime + x->AutoConnect;
4523 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4524 if (x->FailOver.length())
4526 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4529 /* The failover for this server is currently a member of the network.
4530 * The failover probably succeeded, where the main link did not.
4531 * Don't try the main link until the failover is gone again.
4538 // an autoconnected server is not connected. Check if its time to connect it
4539 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4540 this->ConnectServer(&(*x));
4546 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4548 // we've already checked if pcnt > 0, so this is safe
4549 TreeServer* found = Utils->FindServerMask(parameters[0]);
4552 std::string Version = found->GetVersion();
4553 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4554 if (found == Utils->TreeRoot)
4556 ServerInstance->Config->Send005(user);
4561 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4566 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4568 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4570 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4572 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4575 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);
4576 ConnectServer(&(*x));
4581 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());
4586 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4590 void BroadcastTimeSync()
4592 std::deque<std::string> params;
4593 params.push_back(ConvToStr(ServerInstance->Time(true)));
4594 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4597 virtual int OnStats(char statschar, userrec* user, string_list &results)
4599 if ((statschar == 'c') || (statschar == 'n'))
4601 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4603 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].Hook.empty() ? "plaintext" : Utils->LinkBlocks[i].Hook)+" "+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4604 if (statschar == 'c')
4605 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4607 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4608 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);
4614 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4616 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4620 if (command == "CONNECT")
4622 return this->HandleConnect(parameters,pcnt,user);
4624 else if (command == "STATS")
4626 return this->HandleStats(parameters,pcnt,user);
4628 else if (command == "MOTD")
4630 return this->HandleMotd(parameters,pcnt,user);
4632 else if (command == "ADMIN")
4634 return this->HandleAdmin(parameters,pcnt,user);
4636 else if (command == "SQUIT")
4638 return this->HandleSquit(parameters,pcnt,user);
4640 else if (command == "MAP")
4642 this->HandleMap(parameters,pcnt,user);
4645 else if ((command == "TIME") && (pcnt > 0))
4647 return this->HandleTime(parameters,pcnt,user);
4649 else if (command == "LUSERS")
4651 this->HandleLusers(parameters,pcnt,user);
4654 else if (command == "LINKS")
4656 this->HandleLinks(parameters,pcnt,user);
4659 else if (command == "WHOIS")
4664 return this->HandleRemoteWhois(parameters,pcnt,user);
4667 else if ((command == "VERSION") && (pcnt > 0))
4669 this->HandleVersion(parameters,pcnt,user);
4676 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4678 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4680 // this bit of code cleverly routes all module commands
4681 // to all remote severs *automatically* so that modules
4682 // can just handle commands locally, without having
4683 // to have any special provision in place for remote
4684 // commands and linking protocols.
4685 std::deque<std::string> params;
4687 for (int j = 0; j < pcnt; j++)
4689 if (strchr(parameters[j],' '))
4691 params.push_back(":" + std::string(parameters[j]));
4695 params.push_back(std::string(parameters[j]));
4698 Utils->DoOneToMany(user->nick,command,params);
4702 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4704 TreeServer* s = Utils->FindServer(servername);
4707 description = s->GetDesc();
4711 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4713 if (IS_LOCAL(source))
4715 std::deque<std::string> params;
4716 params.push_back(dest->nick);
4717 params.push_back(channel->name);
4718 Utils->DoOneToMany(source->nick,"INVITE",params);
4722 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4724 std::deque<std::string> params;
4725 params.push_back(chan->name);
4726 params.push_back(":"+topic);
4727 Utils->DoOneToMany(user->nick,"TOPIC",params);
4730 virtual void OnWallops(userrec* user, const std::string &text)
4734 std::deque<std::string> params;
4735 params.push_back(":"+text);
4736 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4740 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4742 if (target_type == TYPE_USER)
4744 userrec* d = (userrec*)dest;
4745 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4747 std::deque<std::string> params;
4749 params.push_back(d->nick);
4750 params.push_back(":"+text);
4751 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4754 else if (target_type == TYPE_CHANNEL)
4758 chanrec *c = (chanrec*)dest;
4761 std::string cname = c->name;
4763 cname = status + cname;
4764 TreeServerList list;
4765 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4767 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
4769 TreeSocket* Sock = i->second->GetSocket();
4771 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4776 else if (target_type == TYPE_SERVER)
4780 char* target = (char*)dest;
4781 std::deque<std::string> par;
4782 par.push_back(target);
4783 par.push_back(":"+text);
4784 Utils->DoOneToMany(user->nick,"NOTICE",par);
4789 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4791 if (target_type == TYPE_USER)
4793 // route private messages which are targetted at clients only to the server
4794 // which needs to receive them
4795 userrec* d = (userrec*)dest;
4796 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4798 std::deque<std::string> params;
4800 params.push_back(d->nick);
4801 params.push_back(":"+text);
4802 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4805 else if (target_type == TYPE_CHANNEL)
4809 chanrec *c = (chanrec*)dest;
4812 std::string cname = c->name;
4814 cname = status + cname;
4815 TreeServerList list;
4816 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4818 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
4820 TreeSocket* Sock = i->second->GetSocket();
4822 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4827 else if (target_type == TYPE_SERVER)
4831 char* target = (char*)dest;
4832 std::deque<std::string> par;
4833 par.push_back(target);
4834 par.push_back(":"+text);
4835 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4840 virtual void OnBackgroundTimer(time_t curtime)
4842 AutoConnectServers(curtime);
4843 DoPingChecks(curtime);
4846 virtual void OnUserJoin(userrec* user, chanrec* channel)
4848 // Only do this for local users
4851 if (channel->GetUserCounter() == 1)
4853 std::deque<std::string> params;
4854 // set up their permissions and the channel TS with FJOIN.
4855 // All users are FJOINed now, because a module may specify
4856 // new joining permissions for the user.
4857 params.push_back(channel->name);
4858 params.push_back(ConvToStr(channel->age));
4859 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4860 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4861 /* First user in, sync the modes for the channel */
4863 /* This is safe, all inspircd servers default to +nt */
4864 params.push_back("+nt");
4865 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
4869 std::deque<std::string> params;
4870 params.push_back(channel->name);
4871 params.push_back(ConvToStr(channel->age));
4872 Utils->DoOneToMany(user->nick,"JOIN",params);
4877 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4879 // only occurs for local clients
4880 if (user->registered != REG_ALL)
4882 std::deque<std::string> params;
4883 params.push_back(newhost);
4884 Utils->DoOneToMany(user->nick,"FHOST",params);
4887 virtual void OnChangeName(userrec* user, const std::string &gecos)
4889 // only occurs for local clients
4890 if (user->registered != REG_ALL)
4892 std::deque<std::string> params;
4893 params.push_back(gecos);
4894 Utils->DoOneToMany(user->nick,"FNAME",params);
4897 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4901 std::deque<std::string> params;
4902 params.push_back(channel->name);
4903 if (partmessage != "")
4904 params.push_back(":"+partmessage);
4905 Utils->DoOneToMany(user->nick,"PART",params);
4909 virtual void OnUserConnect(userrec* user)
4911 char agestr[MAXBUF];
4914 std::deque<std::string> params;
4915 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4916 params.push_back(agestr);
4917 params.push_back(user->nick);
4918 params.push_back(user->host);
4919 params.push_back(user->dhost);
4920 params.push_back(user->ident);
4921 params.push_back("+"+std::string(user->FormatModes()));
4922 params.push_back(user->GetIPString());
4923 params.push_back(":"+std::string(user->fullname));
4924 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4926 // User is Local, change needs to be reflected!
4927 TreeServer* SourceServer = Utils->FindServer(user->server);
4930 SourceServer->AddUserCount();
4936 virtual void OnUserQuit(userrec* user, const std::string &reason)
4938 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4940 std::deque<std::string> params;
4941 params.push_back(":"+reason);
4942 Utils->DoOneToMany(user->nick,"QUIT",params);
4944 // Regardless, We need to modify the user Counts..
4945 TreeServer* SourceServer = Utils->FindServer(user->server);
4948 SourceServer->DelUserCount();
4953 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4957 std::deque<std::string> params;
4958 params.push_back(user->nick);
4959 Utils->DoOneToMany(oldnick,"NICK",params);
4963 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4965 if ((source) && (IS_LOCAL(source)))
4967 std::deque<std::string> params;
4968 params.push_back(chan->name);
4969 params.push_back(user->nick);
4970 params.push_back(":"+reason);
4971 Utils->DoOneToMany(source->nick,"KICK",params);
4975 std::deque<std::string> params;
4976 params.push_back(chan->name);
4977 params.push_back(user->nick);
4978 params.push_back(":"+reason);
4979 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4983 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4985 std::deque<std::string> params;
4986 params.push_back(dest->nick);
4987 params.push_back(":"+reason);
4988 Utils->DoOneToMany(source->nick,"KILL",params);
4991 virtual void OnRehash(userrec* user, const std::string ¶meter)
4993 if (parameter != "")
4995 std::deque<std::string> params;
4996 params.push_back(parameter);
4997 Utils->DoOneToMany(user ? user->nick : ServerInstance->Config->ServerName, "REHASH", params);
4999 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5001 ServerInstance->WriteOpers("*** Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName);
5002 ServerInstance->RehashServer();
5005 Utils->ReadConfiguration(false);
5006 InitializeDisabledCommands(ServerInstance->Config->DisabledCommands, ServerInstance);
5009 // note: the protocol does not allow direct umode +o except
5010 // via NICK with 8 params. sending OPERTYPE infers +o modechange
5012 virtual void OnOper(userrec* user, const std::string &opertype)
5016 std::deque<std::string> params;
5017 params.push_back(opertype);
5018 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5022 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5026 /* Server-set lines */
5028 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5029 (unsigned long)duration, reason.c_str());
5030 std::deque<std::string> params;
5031 params.push_back(data);
5032 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5036 if (IS_LOCAL(source))
5039 snprintf(type,8,"%cLINE",linetype);
5040 std::string stype = type;
5043 char sduration[MAXBUF];
5044 snprintf(sduration,MAXBUF,"%ld",duration);
5045 std::deque<std::string> params;
5046 params.push_back(host);
5047 params.push_back(sduration);
5048 params.push_back(":"+reason);
5049 Utils->DoOneToMany(source->nick,stype,params);
5053 std::deque<std::string> params;
5054 params.push_back(host);
5055 Utils->DoOneToMany(source->nick,stype,params);
5061 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5063 OnLine(source,hostmask,true,'G',duration,reason);
5066 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5068 OnLine(source,ipmask,true,'Z',duration,reason);
5071 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5073 OnLine(source,nickmask,true,'Q',duration,reason);
5076 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5078 OnLine(source,hostmask,true,'E',duration,reason);
5081 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5083 OnLine(source,hostmask,false,'G',0,"");
5086 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5088 OnLine(source,ipmask,false,'Z',0,"");
5091 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5093 OnLine(source,nickmask,false,'Q',0,"");
5096 virtual void OnDelELine(userrec* source, const std::string &hostmask)
5098 OnLine(source,hostmask,false,'E',0,"");
5101 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5103 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5105 if (target_type == TYPE_USER)
5107 userrec* u = (userrec*)dest;
5108 std::deque<std::string> params;
5109 params.push_back(u->nick);
5110 params.push_back(text);
5111 Utils->DoOneToMany(user->nick,"MODE",params);
5115 chanrec* c = (chanrec*)dest;
5116 std::deque<std::string> params;
5117 params.push_back(c->name);
5118 params.push_back(text);
5119 Utils->DoOneToMany(user->nick,"MODE",params);
5124 virtual void OnSetAway(userrec* user)
5128 std::deque<std::string> params;
5129 params.push_back(":"+std::string(user->awaymsg));
5130 Utils->DoOneToMany(user->nick,"AWAY",params);
5134 virtual void OnCancelAway(userrec* user)
5138 std::deque<std::string> params;
5140 Utils->DoOneToMany(user->nick,"AWAY",params);
5144 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5146 TreeSocket* s = (TreeSocket*)opaque;
5149 if (target_type == TYPE_USER)
5151 userrec* u = (userrec*)target;
5152 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5156 chanrec* c = (chanrec*)target;
5157 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5162 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5164 TreeSocket* s = (TreeSocket*)opaque;
5167 if (target_type == TYPE_USER)
5169 userrec* u = (userrec*)target;
5170 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5172 else if (target_type == TYPE_CHANNEL)
5174 chanrec* c = (chanrec*)target;
5175 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5178 if (target_type == TYPE_OTHER)
5180 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5184 virtual void OnEvent(Event* event)
5186 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5188 if (event->GetEventID() == "send_metadata")
5190 if (params->size() < 3)
5192 (*params)[2] = ":" + (*params)[2];
5193 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5195 else if (event->GetEventID() == "send_topic")
5197 if (params->size() < 2)
5199 (*params)[1] = ":" + (*params)[1];
5200 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5201 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5202 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5204 else if (event->GetEventID() == "send_mode")
5206 if (params->size() < 2)
5208 // Insert the TS value of the object, either userrec or chanrec
5210 userrec* a = ServerInstance->FindNick((*params)[0]);
5217 chanrec* a = ServerInstance->FindChan((*params)[0]);
5223 params->insert(params->begin() + 1,ConvToStr(ourTS));
5224 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5226 else if (event->GetEventID() == "send_mode_explicit")
5228 if (params->size() < 2)
5230 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5232 else if (event->GetEventID() == "send_opers")
5234 if (params->size() < 1)
5236 (*params)[0] = ":" + (*params)[0];
5237 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5239 else if (event->GetEventID() == "send_modeset")
5241 if (params->size() < 2)
5243 (*params)[1] = ":" + (*params)[1];
5244 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5246 else if (event->GetEventID() == "send_snoset")
5248 if (params->size() < 2)
5250 (*params)[1] = ":" + (*params)[1];
5251 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5253 else if (event->GetEventID() == "send_push")
5255 if (params->size() < 2)
5258 userrec *a = ServerInstance->FindNick((*params)[0]);
5263 (*params)[1] = ":" + (*params)[1];
5264 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5268 virtual ~ModuleSpanningTree()
5270 /* This will also free the listeners */
5273 ServerInstance->Timers->DelTimer(SyncTimer);
5275 ServerInstance->DoneWithInterface("InspSocketHook");
5278 virtual Version GetVersion()
5280 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5283 void Implements(char* List)
5285 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5286 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5287 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5288 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5289 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5290 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5291 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5294 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5295 * so that any activity it sees is FINAL, e.g. we arent going to send out
5296 * a NICK message before m_cloaking has finished putting the +x on the user,
5298 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5299 * the module call queue.
5301 Priority Prioritize()
5303 return PRIORITY_LAST;
5307 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time(), true), Instance(Inst), Module(Mod)
5311 void TimeSyncTimer::Tick(time_t TIME)
5313 Module->BroadcastTimeSync();
5316 void SpanningTreeUtilities::DoFailOver(Link* x)
5318 if (x->FailOver.length())
5320 if (x->FailOver == x->Name)
5322 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());
5325 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5328 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5329 Creator->ConnectServer(TryThisOne);
5333 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5338 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5340 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5342 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5350 class ModuleSpanningTreeFactory : public ModuleFactory
5353 ModuleSpanningTreeFactory()
5357 ~ModuleSpanningTreeFactory()
5361 virtual Module * CreateModule(InspIRCd* Me)
5363 return new ModuleSpanningTree(Me);
5369 extern "C" void * init_module( void )
5371 return new ModuleSpanningTreeFactory;