1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
21 #include "configreader.h"
25 #include "commands/cmd_whois.h"
26 #include "commands/cmd_stats.h"
31 #include "cull_list.h"
34 /** If you make a change which breaks the protocol, increment this.
35 * If you completely change the protocol, completely change the number.
37 const long ProtocolVersion = 1101;
40 * The server list in InspIRCd is maintained as two structures
41 * which hold the data in different ways. Most of the time, we
42 * want to very quicky obtain three pieces of information:
44 * (1) The information on a server
45 * (2) The information on the server we must send data through
46 * to actually REACH the server we're after
47 * (3) Potentially, the child/parent objects of this server
49 * The InspIRCd spanning protocol provides easy access to these
50 * by storing the data firstly in a recursive structure, where
51 * each item references its parent item, and a dynamic list
52 * of child items, and another structure which stores the items
53 * hashed, linearly. This means that if we want to find a server
54 * by name quickly, we can look it up in the hash, avoiding
55 * any O(n) lookups. If however, during a split or sync, we want
56 * to apply an operation to a server, and any of its child objects
57 * we can resort to recursion to walk the tree structure.
60 using irc::sockets::MatchCIDR;
62 class ModuleSpanningTree;
63 static ModuleSpanningTree* TreeProtocolModule;
65 /** Any socket can have one of five states at any one time.
66 * The LISTENER state indicates a socket which is listening
67 * for connections. It cannot receive data itself, only incoming
69 * The CONNECTING state indicates an outbound socket which is
70 * waiting to be writeable.
71 * The WAIT_AUTH_1 state indicates the socket is outbound and
72 * has successfully connected, but has not yet sent and received
74 * The WAIT_AUTH_2 state indicates that the socket is inbound
75 * (allocated by a LISTENER) but has not yet sent and received
77 * The CONNECTED state represents a fully authorized, fully
80 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
82 /* Foward declarations */
86 /* This hash_map holds the hash equivalent of the server
87 * tree, used for rapid linear lookups.
89 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
90 server_hash serverlist;
92 typedef nspace::hash_map<std::string, userrec*> uid_hash;
93 typedef nspace::hash_map<std::string, char*> sid_hash;
95 /** Contains helper functions and variables for this module,
96 * and keeps them out of the global namespace
98 class SpanningTreeUtilities
101 InspIRCd* ServerInstance;
103 bool FlatLinks; /* Flatten links and /MAP for non-opers */
104 bool HideULines; /* Hide U-Lined servers in /MAP and /LINKS */
105 bool AnnounceTSChange; /* Announce TS changes to channels on merge */
106 std::vector<TreeSocket*> Bindings; /* Socket bindings */
107 /* This variable represents the root of the server tree
108 * (for all intents and purposes, it's us)
110 TreeServer *TreeRoot;
112 SpanningTreeUtilities(InspIRCd* Instance);
113 ~SpanningTreeUtilities();
114 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
115 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
116 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit);
117 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
118 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms);
119 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms);
120 void ReadConfiguration(bool rebind);
121 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list);
122 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list);
123 TreeServer* FindServer(std::string ServerName);
124 TreeServer* BestRouteTo(std::string ServerName);
125 TreeServer* FindServerMask(std::string ServerName);
126 bool IsServer(std::string ServerName);
130 std::vector<std::string> ValidIPs;
132 /** This will be used in a future version of InspIRCd for UID support
134 class UserManager : public classbase
145 std::string UserToUID(userrec* user)
150 std::string UIDToUser(const std::string &UID)
155 std::string CreateAndAdd(userrec* user)
160 std::string CreateAndAdd(const std::string &servername)
165 std::string ServerToSID(const std::string &servername)
170 std::string SIDToServer(const std::string &SID)
175 userrec* FindByID(const std::string &UID)
182 /** Each server in the tree is represented by one class of
183 * type TreeServer. A locally connected TreeServer can
184 * have a class of type TreeSocket associated with it, for
185 * remote servers, the TreeSocket entry will be NULL.
186 * Each server also maintains a pointer to its parent
187 * (NULL if this server is ours, at the top of the tree)
188 * and a pointer to its "Route" (see the comments in the
189 * constructors below), and also a dynamic list of pointers
190 * to its children which can be iterated recursively
191 * if required. Creating or deleting objects of type
192 i* TreeServer automatically maintains the hash_map of
193 * TreeServer items, deleting and inserting them as they
194 * are created and destroyed.
196 class TreeServer : public classbase
198 InspIRCd* ServerInstance; /* Creator */
199 SpanningTreeUtilities* Utils; /* Utility class */
200 TreeServer* Parent; /* Parent entry */
201 TreeServer* Route; /* Route entry */
202 std::vector<TreeServer*> Children; /* List of child objects */
203 irc::string ServerName; /* Server's name */
204 std::string ServerDesc; /* Server's description */
205 std::string VersionString; /* Version string or empty string */
206 int UserCount; /* Not used in this version */
207 int OperCount; /* Not used in this version */
208 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
209 time_t NextPing; /* After this time, the server should be PINGed*/
210 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
214 /** We don't use this constructor. Its a dummy, and won't cause any insertion
215 * of the TreeServer into the hash_map. See below for the two we DO use.
217 TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance) : ServerInstance(Instance)
223 UserCount = OperCount = 0;
224 VersionString = ServerInstance->GetVersionString();
227 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
228 * represents our own server. Therefore, it has no route, no parent, and
229 * no socket associated with it. Its version string is our own local version.
231 TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc)
235 UserCount = OperCount = 0;
236 VersionString = ServerInstance->GetVersionString();
238 Socket = NULL; /* Fix by brain */
242 /** When we create a new server, we call this constructor to initialize it.
243 * This constructor initializes the server's Route and Parent, and sets up
244 * its ping counters so that it will be pinged one minute from now.
246 TreeServer(SpanningTreeUtilities* Utils, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
247 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
250 UserCount = OperCount = 0;
251 this->SetNextPingTime(time(NULL) + 60);
254 /* find the 'route' for this server (e.g. the one directly connected
255 * to the local server, which we can use to reach it)
257 * In the following example, consider we have just added a TreeServer
258 * class for server G on our network, of which we are server A.
259 * To route traffic to G (marked with a *) we must send the data to
260 * B (marked with a +) so this algorithm initializes the 'Route'
261 * value to point at whichever server traffic must be routed through
262 * to get here. If we were to try this algorithm with server B,
263 * the Route pointer would point at its own object ('this').
273 * We only run this algorithm when a server is created, as
274 * the routes remain constant while ever the server exists, and
275 * do not need to be re-calculated.
279 if (Route == Utils->TreeRoot)
285 while (this->Route->GetParent() != Utils->TreeRoot)
287 this->Route = Route->GetParent();
291 /* Because recursive code is slow and takes a lot of resources,
292 * we store two representations of the server tree. The first
293 * is a recursive structure where each server references its
294 * children and its parent, which is used for netbursts and
295 * netsplits to dump the whole dataset to the other server,
296 * and the second is used for very fast lookups when routing
297 * messages and is instead a hash_map, where each item can
298 * be referenced by its server name. The AddHashEntry()
299 * call below automatically inserts each TreeServer class
300 * into the hash_map as it is created. There is a similar
301 * maintainance call in the destructor to tidy up deleted
305 this->AddHashEntry();
308 int QuitUsers(const std::string &reason)
310 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
311 const char* reason_s = reason.c_str();
312 std::vector<userrec*> time_to_die;
313 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
315 if (!strcmp(n->second->server, this->ServerName.c_str()))
317 time_to_die.push_back(n->second);
320 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
322 userrec* a = (userrec*)*n;
323 ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
325 userrec::QuitUser(ServerInstance,a,reason_s);
327 return time_to_die.size();
330 /** This method is used to add the structure to the
331 * hash_map for linear searches. It is only called
332 * by the constructors.
336 server_hash::iterator iter;
337 iter = serverlist.find(this->ServerName.c_str());
338 if (iter == serverlist.end())
339 serverlist[this->ServerName.c_str()] = this;
342 /** This method removes the reference to this object
343 * from the hash_map which is used for linear searches.
344 * It is only called by the default destructor.
348 server_hash::iterator iter;
349 iter = serverlist.find(this->ServerName.c_str());
350 if (iter != serverlist.end())
351 serverlist.erase(iter);
354 /** These accessors etc should be pretty self-
357 TreeServer* GetRoute()
362 std::string GetName()
364 return ServerName.c_str();
367 std::string GetDesc()
372 std::string GetVersion()
374 return VersionString;
377 void SetNextPingTime(time_t t)
380 LastPingWasGood = false;
383 time_t NextPingTime()
388 bool AnsweredLastPing()
390 return LastPingWasGood;
395 LastPingWasGood = true;
418 TreeSocket* GetSocket()
423 TreeServer* GetParent()
428 void SetVersion(std::string Version)
430 VersionString = Version;
433 unsigned int ChildCount()
435 return Children.size();
438 TreeServer* GetChild(unsigned int n)
440 if (n < Children.size())
442 /* Make sure they cant request
443 * an out-of-range object. After
444 * all we know what these programmer
445 * types are like *grin*.
455 void AddChild(TreeServer* Child)
457 Children.push_back(Child);
460 bool DelChild(TreeServer* Child)
462 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
473 /** Removes child nodes of this node, and of that node, etc etc.
474 * This is used during netsplits to automatically tidy up the
475 * server tree. It is slow, we don't use it for much else.
479 bool stillchildren = true;
480 while (stillchildren)
482 stillchildren = false;
483 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
485 TreeServer* s = (TreeServer*)*a;
489 stillchildren = true;
498 /* We'd better tidy up after ourselves, eh? */
499 this->DelHashEntry();
503 /** The Link class might as well be a struct,
504 * but this is C++ and we don't believe in structs (!).
505 * It holds the entire information of one <link>
506 * tag from the main config file. We maintain a list
507 * of them, and populate the list on rehash/load.
509 class Link : public classbase
515 std::string SendPass;
516 std::string RecvPass;
517 unsigned long AutoConnect;
518 time_t NextConnectTime;
519 std::string EncryptionKey;
520 bool HiddenFromStats;
521 irc::string FailOver;
524 void DoFailOver(Link* x);
525 Link* FindLink(const std::string& name);
527 /* The usual stuff for inspircd modules,
528 * plus the vector of Link classes which we
529 * use to store the <link> tags from the config
533 std::vector<Link> LinkBlocks;
535 /** Yay for fast searches!
536 * This is hundreds of times faster than recursion
537 * or even scanning a linked list, especially when
538 * there are more than a few servers to deal with.
541 TreeServer* SpanningTreeUtilities::FindServer(std::string ServerName)
543 server_hash::iterator iter;
544 iter = serverlist.find(ServerName.c_str());
545 if (iter != serverlist.end())
555 /** Returns the locally connected server we must route a
556 * message through to reach server 'ServerName'. This
557 * only applies to one-to-one and not one-to-many routing.
558 * See the comments for the constructor of TreeServer
561 TreeServer* SpanningTreeUtilities::BestRouteTo(std::string ServerName)
563 if (ServerName.c_str() == TreeRoot->GetName())
565 TreeServer* Found = FindServer(ServerName);
568 return Found->GetRoute();
576 /** Find the first server matching a given glob mask.
577 * Theres no find-using-glob method of hash_map [awwww :-(]
578 * so instead, we iterate over the list using an iterator
579 * and match each one until we get a hit. Yes its slow,
582 TreeServer* SpanningTreeUtilities::FindServerMask(std::string ServerName)
584 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
586 if (match(i->first.c_str(),ServerName.c_str()))
592 /* A convenient wrapper that returns true if a server exists */
593 bool SpanningTreeUtilities::IsServer(std::string ServerName)
595 return (FindServer(ServerName) != NULL);
601 class cmd_rconnect : public command_t
604 SpanningTreeUtilities* Utils;
606 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
608 this->source = "m_spanningtree.so";
609 syntax = "<remote-server-mask> <servermask>";
612 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
614 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
615 /* Is this aimed at our server? */
616 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
618 /* Yes, initiate the given connect */
619 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
621 para[0] = parameters[1];
622 std::string original_command = std::string("CONNECT ") + parameters[1];
623 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
634 /** Every SERVER connection inbound or outbound is represented by
635 * an object of type TreeSocket.
636 * TreeSockets, being inherited from InspSocket, can be tied into
637 * the core socket engine, and we cn therefore receive activity events
638 * for them, just like activex objects on speed. (yes really, that
639 * is a technical term!) Each of these which relates to a locally
640 * connected server is assocated with it, by hooking it onto a
641 * TreeSocket class using its constructor. In this way, we can
642 * maintain a list of servers, some of which are directly connected,
643 * some of which are not.
645 class TreeSocket : public InspSocket
647 SpanningTreeUtilities* Utils;
649 std::string in_buffer;
650 ServerState LinkState;
651 std::string InboundServerName;
652 std::string InboundDescription;
654 int num_lost_servers;
656 bool LastPingWasGood;
660 unsigned int keylength;
661 std::string ModuleList;
662 std::map<std::string,std::string> CapKeys;
666 /** Because most of the I/O gubbins are encapsulated within
667 * InspSocket, we just call the superclass constructor for
668 * most of the action, and append a few of our own values
671 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
672 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
675 this->LinkState = LISTENER;
677 this->ctx_out = NULL;
680 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
681 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
684 this->LinkState = CONNECTING;
686 this->ctx_out = NULL;
689 /** When a listening socket gives us a new file descriptor,
690 * we must associate it with a socket without creating a new
691 * connection. This constructor is used for this purpose.
693 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip)
694 : InspSocket(SI, newfd, ip), Utils(Util)
696 this->LinkState = WAIT_AUTH_1;
698 this->ctx_out = NULL;
699 this->SendCapabilities();
710 void InitAES(std::string key,std::string SName)
717 Instance->Log(DEBUG,"Initialized AES key %s",key.c_str());
718 // key must be 16, 24, 32 etc bytes (multiple of 8)
719 keylength = key.length();
720 if (!(keylength == 16 || keylength == 24 || keylength == 32))
722 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
723 Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
727 if (this->GetState() != I_ERROR)
729 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
730 ctx_in->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
731 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
732 ctx_out->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
733 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
738 /** When an outbound connection finishes connecting, we receive
739 * this event, and must send our SERVER string to the other
740 * side. If the other side is happy, as outlined in the server
741 * to server docs on the inspircd.org site, the other side
742 * will then send back its own server string.
744 virtual bool OnConnected()
746 if (this->LinkState == CONNECTING)
748 /* we do not need to change state here. */
749 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
751 if (x->Name == this->myhost)
753 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
754 this->SendCapabilities();
755 if (x->EncryptionKey != "")
757 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
759 this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
763 this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
764 this->InitAES(x->EncryptionKey,x->Name.c_str());
767 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
768 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
773 /* There is a (remote) chance that between the /CONNECT and the connection
774 * being accepted, some muppet has removed the <link> block and rehashed.
775 * If that happens the connection hangs here until it's closed. Unlikely
776 * and rather harmless.
778 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
782 virtual void OnError(InspSocketError e)
784 /* We don't handle this method, because all our
785 * dirty work is done in OnClose() (see below)
786 * which is still called on error conditions too.
788 if (e == I_ERR_CONNECT)
790 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
791 Link* MyLink = FindLink(myhost);
797 virtual int OnDisconnect()
799 /* For the same reason as above, we don't
800 * handle OnDisconnect()
805 /** Recursively send the server tree with distances as hops.
806 * This is used during network burst to inform the other server
807 * (and any of ITS servers too) of what servers we know about.
808 * If at any point any of these servers already exist on the other
809 * end, our connection may be terminated. The hopcounts given
810 * by this function are relative, this doesn't matter so long as
811 * they are all >1, as all the remote servers re-calculate them
812 * to be relative too, with themselves as hop 0.
814 void SendServers(TreeServer* Current, TreeServer* s, int hops)
817 for (unsigned int q = 0; q < Current->ChildCount(); q++)
819 TreeServer* recursive_server = Current->GetChild(q);
820 if (recursive_server != s)
822 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
823 this->WriteLine(command);
824 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
825 /* down to next level */
826 this->SendServers(recursive_server, s, hops+1);
831 std::string MyCapabilities()
833 std::vector<std::string> modlist;
834 std::string capabilities = "";
836 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
838 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
839 modlist.push_back(this->Instance->Config->module_names[i]);
841 sort(modlist.begin(),modlist.end());
842 for (unsigned int i = 0; i < modlist.size(); i++)
845 capabilities = capabilities + ",";
846 capabilities = capabilities + modlist[i];
851 void SendCapabilities()
853 irc::commasepstream modulelist(MyCapabilities());
855 this->WriteLine("CAPAB START");
857 /* Send module names, split at 509 length */
858 std::string item = "*";
859 std::string line = "CAPAB MODULES ";
860 while ((item = modulelist.GetToken()) != "")
862 if (line.length() + item.length() + 1 > 509)
864 this->WriteLine(line);
865 line = "CAPAB MODULES ";
868 if (line != "CAPAB MODULES ")
873 if (line != "CAPAB MODULES ")
874 this->WriteLine(line);
881 #ifdef SUPPORT_IP6LINKS
884 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));
886 this->WriteLine("CAPAB END");
889 /* Check a comma seperated list for an item */
890 bool HasItem(const std::string &list, const std::string &item)
892 irc::commasepstream seplist(list);
894 std::string item2 = "*";
895 while ((item2 = seplist.GetToken()) != "")
904 /* Isolate and return the elements that are different between two comma seperated lists */
905 std::string ListDifference(const std::string &one, const std::string &two)
907 irc::commasepstream list_one(one);
908 std::string item = "*";
909 std::string result = "";
910 while ((item = list_one.GetToken()) != "")
912 if (!HasItem(two, item))
921 bool Capab(std::deque<std::string> params)
923 if (params.size() < 1)
925 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
929 if (params[0] == "START")
931 this->ModuleList = "";
932 this->CapKeys.clear();
934 else if (params[0] == "END")
936 std::string reason = "";
938 #ifdef SUPPORT_IP6LINKS
941 /* Compare ModuleList and check CapKeys...
942 * Maybe this could be tidier? -- Brain
944 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
946 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
949 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
953 diff = "this server:" + diff;
955 if (diff.length() == 12)
956 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
958 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
961 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
962 reason = "We don't both support linking to IPV6 servers";
964 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
965 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
967 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
968 reason = "Maximum nickname lengths differ or remote nickname length not specified";
970 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
972 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
974 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
978 reason = "Protocol version not specified";
982 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))))
983 reason = "We don't both have halfop support enabled/disabled identically";
985 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
986 reason = "Maximum ident lengths differ or remote ident length not specified";
988 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
989 reason = "Maximum channel lengths differ or remote channel length not specified";
991 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
992 reason = "Maximum modes per line differ or remote modes per line not specified";
994 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
995 reason = "Maximum quit lengths differ or remote quit length not specified";
997 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
998 reason = "Maximum topic lengths differ or remote topic length not specified";
1000 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
1001 reason = "Maximum kick lengths differ or remote kick length not specified";
1003 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
1004 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
1006 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
1007 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
1009 if (reason.length())
1011 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
1015 else if ((params[0] == "MODULES") && (params.size() == 2))
1017 if (!this->ModuleList.length())
1019 this->ModuleList.append(params[1]);
1023 this->ModuleList.append(",");
1024 this->ModuleList.append(params[1]);
1027 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
1029 irc::tokenstream capabs(params[1]);
1030 std::string item = "*";
1031 while ((item = capabs.GetToken()) != "")
1033 /* Process each key/value pair */
1034 std::string::size_type equals = item.rfind('=');
1035 if (equals != std::string::npos)
1037 std::string var = item.substr(0, equals);
1038 std::string value = item.substr(equals+1, item.length());
1039 this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
1040 CapKeys[var] = value;
1048 /** This function forces this server to quit, removing this server
1049 * and any users on it (and servers and users below that, etc etc).
1050 * It's very slow and pretty clunky, but luckily unless your network
1051 * is having a REAL bad hair day, this function shouldnt be called
1052 * too many times a month ;-)
1054 void SquitServer(std::string &from, TreeServer* Current)
1056 /* recursively squit the servers attached to 'Current'.
1057 * We're going backwards so we don't remove users
1058 * while we still need them ;)
1060 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1062 TreeServer* recursive_server = Current->GetChild(q);
1063 this->SquitServer(from,recursive_server);
1065 /* Now we've whacked the kids, whack self */
1067 num_lost_users += Current->QuitUsers(from);
1070 /** This is a wrapper function for SquitServer above, which
1071 * does some validation first and passes on the SQUIT to all
1072 * other remaining servers.
1074 void Squit(TreeServer* Current,std::string reason)
1076 if ((Current) && (Current != Utils->TreeRoot))
1078 std::deque<std::string> params;
1079 params.push_back(Current->GetName());
1080 params.push_back(":"+reason);
1081 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1082 if (Current->GetParent() == Utils->TreeRoot)
1084 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1088 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1090 num_lost_servers = 0;
1092 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1093 SquitServer(from, Current);
1095 Current->GetParent()->DelChild(Current);
1097 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1101 Instance->Log(DEFAULT,"Squit from unknown server");
1105 /** FMODE command - server mode with timestamp checks */
1106 bool ForceMode(std::string source, std::deque<std::string> ¶ms)
1108 /* Chances are this is a 1.0 FMODE without TS */
1109 if (params.size() < 3)
1111 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
1116 std::string sourceserv;
1118 /* Are we dealing with an FMODE from a user, or from a server? */
1119 userrec* who = this->Instance->FindNick(source);
1122 /* FMODE from a user, set sourceserv to the users server name */
1123 sourceserv = who->server;
1127 /* FMODE from a server, create a fake user to receive mode feedback */
1128 who = new userrec(this->Instance);
1129 who->SetFd(FD_MAGIC_NUMBER);
1130 smode = true; /* Setting this flag tells us we should free the userrec later */
1131 sourceserv = source; /* Set sourceserv to the actual source string */
1133 const char* modelist[64];
1136 memset(&modelist,0,sizeof(modelist));
1137 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1141 /* The timestamp is in this position.
1142 * We don't want to pass that up to the
1143 * server->client protocol!
1145 TS = atoi(params[q].c_str());
1149 /* Everything else is fine to append to the modelist */
1150 modelist[n++] = params[q].c_str();
1154 /* Extract the TS value of the object, either userrec or chanrec */
1155 userrec* dst = this->Instance->FindNick(params[0]);
1156 chanrec* chan = NULL;
1164 chan = this->Instance->FindChan(params[0]);
1170 /* Oops, channel doesnt exist! */
1174 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1179 Instance->Log(DEBUG,"Entering TS equality check");
1180 ModeHandler* mh = NULL;
1181 unsigned long paramptr = 3;
1182 std::string to_bounce = "";
1183 std::string to_keep = "";
1184 std::vector<std::string> params_to_keep;
1185 std::string params_to_bounce = "";
1187 char cur_change = 1;
1188 char old_change = 0;
1189 char old_bounce_change = 0;
1190 /* Merge modes, basically do special stuff to mode with params */
1191 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1204 /* We only care about whats being set,
1205 * not whats being unset
1207 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1209 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1211 /* We only want to do special things to
1212 * modes with parameters, we are going to rewrite
1216 adding ? cur_change = '+' : cur_change = '-';
1218 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1220 /* The mode is set here, check which we should keep */
1223 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1225 if (which_to_keep == true)
1227 /* Keep ours, bounce theirs:
1228 * Send back ours to them and
1229 * drop their mode changs
1231 adding ? cur_change = '+' : cur_change = '-';
1232 if (cur_change != old_bounce_change)
1233 to_bounce += cur_change;
1235 old_bounce_change = cur_change;
1237 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1238 params_to_bounce.append(" ").append(ret.second);
1242 /* Keep theirs: Accept their mode change,
1245 adding ? cur_change = '+' : cur_change = '-';
1246 if (cur_change != old_change)
1247 to_keep += cur_change;
1249 old_change = cur_change;
1251 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1252 params_to_keep.push_back(params[paramptr]);
1257 /* Mode isnt set here, we want it */
1258 adding ? cur_change = '+' : cur_change = '-';
1259 if (cur_change != old_change)
1260 to_keep += cur_change;
1262 old_change = cur_change;
1264 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1265 params_to_keep.push_back(params[paramptr]);
1272 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1276 adding ? cur_change = '+' : cur_change = '-';
1278 /* Just keep this, safe to merge with no checks
1279 * it has no parameters
1282 if (cur_change != old_change)
1283 to_keep += cur_change;
1285 old_change = cur_change;
1287 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1289 Instance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1290 params_to_keep.push_back(params[paramptr++]);
1297 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1301 /* Taking a mode away */
1302 adding ? cur_change = '+' : cur_change = '-';
1304 if (cur_change != old_change)
1305 to_keep += cur_change;
1307 old_change = cur_change;
1309 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1310 params_to_keep.push_back(params[paramptr++]);
1317 if (to_bounce.length())
1319 std::deque<std::string> newparams;
1320 newparams.push_back(params[0]);
1321 newparams.push_back(ConvToStr(ourTS));
1322 newparams.push_back(to_bounce+params_to_bounce);
1323 Instance->Log(DEBUG,"BOUNCE BACK: %s",(to_bounce+params_to_bounce).c_str());
1324 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1327 if (to_keep.length())
1331 modelist[0] = params[0].c_str();
1332 modelist[1] = to_keep.c_str();
1334 if (params_to_keep.size() > 0)
1336 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1338 Instance->Log(DEBUG,"KEEP Item %d of %d: %s", q, params_to_keep.size(), params_to_keep[q].c_str());
1339 modelist[n++] = params_to_keep[q].c_str();
1345 Instance->Log(DEBUG,"Send mode");
1346 this->Instance->SendMode(modelist, n, who);
1350 Instance->Log(DEBUG,"Send mode client");
1351 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1354 /* HOT POTATO! PASS IT ON! */
1355 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1359 /* U-lined servers always win regardless of their TS */
1360 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1362 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1363 * SHOULD accept it, if its clock is right.
1365 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1366 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1367 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1369 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1370 * writing the code. It took me a while to come up with this solution.
1372 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1375 std::deque<std::string> newparams; /* New parameter list we send back */
1376 newparams.push_back(params[0]); /* Target, user or channel */
1377 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1378 newparams.push_back(""); /* This contains the mode string. For now
1379 * it's empty, we fill it below.
1382 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1383 * set to avoid a desync here.
1385 std::string modebounce = "";
1388 ModeHandler* mh = NULL;
1389 char cur_change = 1;
1390 char old_change = 0;
1391 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1393 /* Iterate over all mode chars in the sent set */
1396 /* Adding or subtracting modes? */
1404 /* Find the mode handler for this mode */
1405 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1407 /* Got a mode handler?
1408 * This also prevents us bouncing modes we have no handler for.
1415 /* Does the mode require a parameter right now?
1416 * If it does, fetch it if we can
1418 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1421 /* Call the ModeSet method to determine if its set with the
1422 * given parameter here or not.
1424 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1426 /* XXX: Really. Dont ask.
1427 * Determine from if its set combined with what the current
1428 * 'state' is (adding or not) as to wether we should 'invert'
1429 * or 'reinforce' the mode change
1431 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1433 /* Quickly determine if we have 'flipped' from + to -,
1434 * or - to +, to prevent unneccessary +/- chars in the
1435 * output string that waste bandwidth
1437 if (cur_change != old_change)
1438 modebounce += cur_change;
1439 old_change = cur_change;
1441 /* Add the mode character to the output string */
1442 modebounce += mh->GetModeChar();
1444 /* We got a parameter back from ModeHandler::ModeSet,
1445 * are we supposed to be sending one out right now?
1447 if (ret.second.length())
1449 if (mh->GetNumParams(cur_change == '+') > 0)
1450 /* Yes we're supposed to be sending out
1451 * the parameter. Make sure it goes
1453 newparams.push_back(ret.second);
1461 /* Update the parameters for FMODE with the new 'bounced' string */
1462 newparams[2] = modebounce;
1463 /* Only send it back the way it came, no need to send it anywhere else */
1464 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1465 Instance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1469 Instance->Log(DEBUG,"Allow modes, TS lower for sender");
1470 /* The server was ulined, but something iffy is up with the TS.
1471 * Sound the alarm bells!
1473 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1475 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());
1477 /* Allow the mode, route it to either server or user command handling */
1479 this->Instance->SendMode(modelist,n,who);
1481 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1483 /* HOT POTATO! PASS IT ON! */
1484 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1486 /* Are we supposed to free the userrec? */
1493 /** FTOPIC command */
1494 bool ForceTopic(std::string source, std::deque<std::string> ¶ms)
1496 if (params.size() != 4)
1498 time_t ts = atoi(params[1].c_str());
1499 std::string nsource = source;
1501 chanrec* c = this->Instance->FindChan(params[0]);
1504 if ((ts >= c->topicset) || (!*c->topic))
1506 std::string oldtopic = c->topic;
1507 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1508 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1510 /* if the topic text is the same as the current topic,
1511 * dont bother to send the TOPIC command out, just silently
1512 * update the set time and set nick.
1514 if (oldtopic != params[3])
1516 userrec* user = this->Instance->FindNick(source);
1519 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1523 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1524 nsource = user->server;
1526 /* all done, send it on its way */
1527 params[3] = ":" + params[3];
1528 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1537 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1538 bool ForceJoin(std::string source, std::deque<std::string> ¶ms)
1540 /* 1.1 FJOIN works as follows:
1542 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1543 * timestamp 'wins'. From this point on we will refer to this side as the
1544 * winner. The side with the higher timestamp loses, from this point on we
1545 * will call this side the loser or losing side. This should be familiar to
1546 * anyone who's dealt with dreamforge or TS6 before.
1548 * When two sides of a split heal and this occurs, the following things
1551 * If the timestamps are exactly equal, both sides merge their privilages
1552 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1553 * re-created during a split, this is safe to do.
1556 * If the timestamps are NOT equal, the losing side removes all privilage
1557 * modes from all of its users that currently exist in the channel, before
1558 * introducing new users into the channel which are listed in the FJOIN
1559 * command's parameters. This means, all modes +ohv, and privilages added
1560 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1561 * of the channel to match that of the winning side, and the modes of the
1562 * users of the winning side are merged in with the losing side. The loser
1563 * then sends out a set of FMODE commands which 'confirm' that it just
1564 * removed all privilage modes from its existing users, which allows for
1565 * services packages to still work correctly without needing to know the
1566 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1567 * a problem, and services packages must contain code which explicitly
1568 * behaves as TS6 does, removing ops from the losing side of a split where
1569 * neccessary within its internal records, as this state information is
1570 * not explicitly echoed out in that protocol.
1572 * The winning side on the other hand will ignore all user modes from the
1573 * losing side, so only its own modes get applied. Life is simple for those
1574 * who succeed at internets. :-)
1576 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1577 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1578 * you ask? Well, quite simply because we don't need to. They'll be sent
1579 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1580 * the losing side sends any modes for the channel which shouldnt win,
1581 * they wont as their timestamp will be too high :-)
1584 if (params.size() < 3)
1587 char first[MAXBUF]; /* The first parameter of the mode command */
1588 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1589 char* mode_users[127]; /* The values used by the mode command */
1590 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1591 mode_users[0] = first; /* Set this up to be our on-stack value */
1592 mode_users[1] = modestring; /* Same here as above */
1593 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1594 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1596 userrec* who = NULL; /* User we are currently checking */
1597 std::string channel = params[0]; /* Channel name, as a string */
1598 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1600 /* Try and find the channel */
1601 chanrec* chan = this->Instance->FindChan(channel);
1603 /* Initialize channel name in the mode parameters */
1604 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1606 /* default TS is a high value, which if we dont have this
1607 * channel will let the other side apply their modes.
1609 time_t ourTS = time(NULL)+600;
1611 /* Does this channel exist? if it does, get its REAL timestamp */
1615 /* In 1.1, if they have the newer channel, we immediately clear
1616 * all status modes from our users. We then accept their modes.
1617 * If WE have the newer channel its the other side's job to do this.
1618 * Note that this causes the losing server to send out confirming
1623 std::deque<std::string> param_list;
1628 /* Lower the TS here */
1629 if (Utils->AnnounceTSChange && chan)
1630 chan->WriteChannelWithServ(Instance->Config->ServerName,
1631 "TS for %s changed from %lu to %lu", chan->name, ourTS, TS);
1634 param_list.push_back(channel);
1635 /* Zap all the privilage modes on our side */
1636 this->RemoveStatus(Instance->Config->ServerName, param_list);
1639 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1640 irc::tokenstream users(params[2]);
1641 std::string item = "*";
1643 /* do this first, so our mode reversals are correctly received by other servers
1644 * if there is a TS collision.
1646 params[2] = ":" + params[2];
1647 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1649 /* Now, process every 'prefixes,nick' pair */
1652 /* Find next user */
1653 item = users.GetToken();
1655 const char* usr = item.c_str();
1657 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1658 * (is this even possible?) */
1661 const char* permissions = usr;
1663 char* nm = new char[MAXBUF];
1666 /* Iterate through all the prefix values, convert them from prefixes
1667 * to mode letters, and append them to the mode sequence
1669 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1671 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1674 /* This is a valid prefix */
1676 *tnm++ = mh->GetModeChar();
1680 /* Not a valid prefix...
1681 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1683 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1684 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1691 /* Null terminate modes */
1693 /* Advance past the comma, to the nick */
1696 /* Check the user actually exists */
1697 who = this->Instance->FindNick(usr);
1700 /* Did they get any modes? How many times? */
1701 strlcat(modestring, nm, MAXBUF);
1702 for (int k = 0; k < ntimes; k++)
1703 mode_users[modectr++] = strdup(usr);
1705 /* Free temporary buffer used for mode sequence */
1708 /* Check that the user's 'direction' is correct
1709 * based on the server sending the FJOIN. We must
1710 * check each nickname in turn, because the origin of
1711 * the FJOIN may be different to the origin of the nicks
1712 * in the command itself.
1714 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1715 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1717 /* Oh dear oh dear. */
1718 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1721 /* Finally, we can actually place the user into the channel.
1722 * We're sure its right. Final answer, phone a friend.
1724 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1726 /* Have we already queued up MAXMODES modes with parameters
1727 * (+qaohv) ready to be sent to the server?
1729 if (modectr >= (MAXMODES-1))
1731 /* Only actually give the users any status if we lost
1732 * the FJOIN or drew (equal timestamps).
1733 * It isn't actually possible for ourTS to be > TS here,
1734 * only possible to actually have ourTS == TS, or
1735 * ourTS < TS, because if we lost, we already lowered
1736 * our TS above before we entered this loop. We only
1737 * check >= as a safety measure, in case someone stuffed
1738 * up. If someone DID stuff up, it was most likely me.
1739 * Note: I do not like baseball bats in the face...
1743 Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1744 this->Instance->SendMode((const char**)mode_users,modectr,who);
1746 /* Something stuffed up, and for some reason, the timestamp is
1747 * NOT lowered right now and should be. Lower it. Usually this
1748 * code won't be executed, doubtless someone will remove it some
1753 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1759 /* Reset all this back to defaults, and
1760 * free any ram we have left allocated.
1762 strcpy(mode_users[1],"+");
1763 for (unsigned int f = 2; f < modectr; f++)
1764 free(mode_users[f]);
1770 /* Remember to free this */
1772 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1773 * We don't try to process the nickname here (that WOULD cause a segfault because
1774 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1775 * in case somehow we're desynched, so that other users which might be able to see
1776 * the nickname get their fair chance to process it.
1778 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1784 /* there werent enough modes built up to flush it during FJOIN,
1785 * or, there are a number left over. flush them out.
1787 if ((modectr > 2) && (who) && (chan))
1791 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1792 this->Instance->SendMode((const char**)mode_users,modectr,who);
1793 /* Yet again, we can't actually get a true value here, if everything else
1794 * is working as it should.
1798 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1804 /* Free anything we have left to free */
1805 for (unsigned int f = 2; f < modectr; f++)
1806 free(mode_users[f]);
1809 /* All done. That wasnt so bad was it, you can wipe
1810 * the sweat from your forehead now. :-)
1816 bool IntroduceClient(std::string source, std::deque<std::string> ¶ms)
1818 if (params.size() < 8)
1820 if (params.size() > 8)
1822 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1825 // NICK age nick host dhost ident +modes ip :gecos
1827 time_t age = atoi(params[0].c_str());
1829 /* This used to have a pretty craq'y loop doing the same thing,
1830 * now we just let the STL do the hard work (more efficiently)
1832 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1833 if (pos_after_plus != std::string::npos)
1834 params[5] = params[5].substr(pos_after_plus);
1836 const char* tempnick = params[1].c_str();
1837 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1839 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1841 if (iter != this->Instance->clientlist.end())
1844 Instance->Log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,params[4].c_str(),params[2].c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1845 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1846 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1850 userrec* _new = new userrec(this->Instance);
1851 this->Instance->clientlist[tempnick] = _new;
1852 _new->SetFd(FD_MAGIC_NUMBER);
1853 strlcpy(_new->nick, tempnick,NICKMAX-1);
1854 strlcpy(_new->host, params[2].c_str(),63);
1855 strlcpy(_new->dhost, params[3].c_str(),63);
1856 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1857 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1858 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1859 _new->registered = REG_ALL;
1862 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1863 _new->modes[(*v)-65] = 1;
1865 #ifdef SUPPORT_IP6LINKS
1866 if (params[6].find_first_of(":") != std::string::npos)
1867 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1870 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1872 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1874 params[7] = ":" + params[7];
1875 Utils->DoOneToAllButSender(source,"NICK",params,source);
1877 // Increment the Source Servers User Count..
1878 TreeServer* SourceServer = Utils->FindServer(source);
1881 Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1882 SourceServer->AddUserCount();
1885 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1890 /** Send one or more FJOINs for a channel of users.
1891 * If the length of a single line is more than 480-NICKMAX
1892 * in length, it is split over multiple lines.
1894 void SendFJoins(TreeServer* Current, chanrec* c)
1896 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1898 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1900 size_t dlen, curlen;
1901 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1903 char* ptr = list + dlen;
1905 CUList *ulist = c->GetUsers();
1906 std::vector<userrec*> specific_halfop;
1907 std::vector<userrec*> specific_voice;
1908 std::string modes = "";
1909 std::string params = "";
1911 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1913 // The first parameter gets a : before it
1914 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1921 if (curlen > (480-NICKMAX))
1923 this->WriteLine(list);
1924 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1932 this->WriteLine(list);
1934 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1937 params.append(b->data).append(" ");
1939 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+c->ChanModes(true)+modes+" "+params);
1942 /** Send G, Q, Z and E lines */
1943 void SendXLines(TreeServer* Current)
1946 std::string n = this->Instance->Config->ServerName;
1947 const char* sn = n.c_str();
1949 /* Yes, these arent too nice looking, but they get the job done */
1950 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1952 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1953 this->WriteLine(data);
1955 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1957 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1958 this->WriteLine(data);
1960 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1962 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1963 this->WriteLine(data);
1965 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1967 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1968 this->WriteLine(data);
1970 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
1972 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1973 this->WriteLine(data);
1975 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
1977 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1978 this->WriteLine(data);
1980 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
1982 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1983 this->WriteLine(data);
1985 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
1987 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1988 this->WriteLine(data);
1992 /** Send channel modes and topics */
1993 void SendChannelModes(TreeServer* Current)
1996 std::deque<std::string> list;
1998 std::string n = this->Instance->Config->ServerName;
1999 const char* sn = n.c_str();
2000 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2002 SendFJoins(Current, c->second);
2003 if (*c->second->topic)
2005 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2006 this->WriteLine(data);
2008 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
2010 c->second->GetExtList(list);
2011 for (unsigned int j = 0; j < list.size(); j++)
2013 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
2018 /** send all users and their oper state/modes */
2019 void SendUsers(TreeServer* Current)
2022 std::deque<std::string> list;
2024 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2026 if (u->second->registered == REG_ALL)
2028 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);
2029 this->WriteLine(data);
2030 if (*u->second->oper)
2032 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
2034 if (*u->second->awaymsg)
2036 this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
2038 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
2040 u->second->GetExtList(list);
2041 for (unsigned int j = 0; j < list.size(); j++)
2043 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
2049 /** This function is called when we want to send a netburst to a local
2050 * server. There is a set order we must do this, because for example
2051 * users require their servers to exist, and channels require their
2052 * users to exist. You get the idea.
2054 void DoBurst(TreeServer* s)
2056 std::string burst = "BURST "+ConvToStr(time(NULL));
2057 std::string endburst = "ENDBURST";
2058 // Because by the end of the netburst, it could be gone!
2059 std::string name = s->GetName();
2060 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2061 this->WriteLine(burst);
2062 /* send our version string */
2063 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2064 /* Send server tree */
2065 this->SendServers(Utils->TreeRoot,s,1);
2066 /* Send users and their oper status */
2068 /* Send everything else (channel modes, xlines etc) */
2069 this->SendChannelModes(s);
2070 this->SendXLines(s);
2071 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
2072 this->WriteLine(endburst);
2073 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2076 /** This function is called when we receive data from a remote
2077 * server. We buffer the data in a std::string (it doesnt stay
2078 * there for long), reading using InspSocket::Read() which can
2079 * read up to 16 kilobytes in one operation.
2081 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2082 * THE SOCKET OBJECT FOR US.
2084 virtual bool OnDataReady()
2086 char* data = this->Read();
2087 /* Check that the data read is a valid pointer and it has some content */
2090 this->in_buffer.append(data);
2091 /* While there is at least one new line in the buffer,
2092 * do something useful (we hope!) with it.
2094 while (in_buffer.find("\n") != std::string::npos)
2096 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2097 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2098 if (ret.find("\r") != std::string::npos)
2099 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2100 /* Process this one, abort if it
2101 * didnt return true.
2107 memset(result,0,1024);
2109 /* ERROR + CAPAB is still allowed unencryped */
2110 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2112 int nbytes = from64tobits(out, ret.c_str(), 1024);
2113 if ((nbytes > 0) && (nbytes < 1024))
2115 ctx_in->Decrypt(out, result, nbytes, 0);
2116 for (int t = 0; t < nbytes; t++)
2117 if (result[t] == '\7') result[t] = 0;
2122 if (!this->ProcessLine(ret))
2124 Instance->Log(DEBUG,"ProcessLine says no!");
2130 /* EAGAIN returns an empty but non-NULL string, so this
2131 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2133 return (data && !*data);
2136 int WriteLine(std::string line)
2138 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2142 char result64[10240];
2143 if (this->keylength)
2145 // pad it to the key length
2146 int n = this->keylength - (line.length() % this->keylength);
2148 line.append(n,'\7');
2150 unsigned int ll = line.length();
2151 ctx_out->Encrypt(line.c_str(), result, ll, 0);
2152 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2155 return this->Write(line + "\r\n");
2158 /* Handle ERROR command */
2159 bool Error(std::deque<std::string> ¶ms)
2161 if (params.size() < 1)
2163 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2164 /* we will return false to cause the socket to close. */
2168 /** remote MOTD. leet, huh? */
2169 bool Motd(std::string prefix, std::deque<std::string> ¶ms)
2171 if (params.size() > 0)
2173 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2175 /* It's for our server */
2176 string_list results;
2177 userrec* source = this->Instance->FindNick(prefix);
2181 std::deque<std::string> par;
2182 par.push_back(prefix);
2185 if (!Instance->Config->MOTD.size())
2187 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2188 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2192 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2193 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2195 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2197 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2198 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2201 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2202 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2208 userrec* source = this->Instance->FindNick(prefix);
2210 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2216 /** remote ADMIN. leet, huh? */
2217 bool Admin(std::string prefix, std::deque<std::string> ¶ms)
2219 if (params.size() > 0)
2221 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2223 /* It's for our server */
2224 string_list results;
2225 userrec* source = this->Instance->FindNick(prefix);
2229 std::deque<std::string> par;
2230 par.push_back(prefix);
2233 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2234 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2236 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
2237 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2239 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2240 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2242 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
2243 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2249 userrec* source = this->Instance->FindNick(prefix);
2251 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2257 bool Stats(std::string prefix, std::deque<std::string> ¶ms)
2259 /* Get the reply to a STATS query if it matches this servername,
2260 * and send it back as a load of PUSH queries
2262 if (params.size() > 1)
2264 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2266 /* It's for our server */
2267 string_list results;
2268 userrec* source = this->Instance->FindNick(prefix);
2271 std::deque<std::string> par;
2272 par.push_back(prefix);
2274 DoStats(this->Instance, *(params[0].c_str()), source, results);
2275 for (size_t i = 0; i < results.size(); i++)
2277 par[1] = "::" + results[i];
2278 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2285 userrec* source = this->Instance->FindNick(prefix);
2287 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2294 /** Because the core won't let users or even SERVERS set +o,
2295 * we use the OPERTYPE command to do this.
2297 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
2299 if (params.size() != 1)
2301 Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2304 std::string opertype = params[0];
2305 userrec* u = this->Instance->FindNick(prefix);
2308 u->modes[UM_OPERATOR] = 1;
2309 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2310 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2315 /** Because Andy insists that services-compatible servers must
2316 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2318 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
2320 if (params.size() < 3)
2323 userrec* u = this->Instance->FindNick(params[0]);
2327 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2330 std::deque<std::string> par;
2331 par.push_back(params[1]);
2332 /* This is not required as one is sent in OnUserPostNick below
2334 //Utils->DoOneToMany(u->nick,"NICK",par);
2335 if (!u->ForceNickChange(params[1].c_str()))
2337 userrec::QuitUser(this->Instance, u, "Nickname collision");
2340 u->age = atoi(params[2].c_str());
2346 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
2348 if (params.size() < 2)
2351 userrec* u = this->Instance->FindNick(params[0]);
2355 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2356 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2361 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
2363 if (params.size() < 1)
2366 std::string servermask = params[0];
2368 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2370 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2371 this->Instance->RehashServer();
2372 Utils->ReadConfiguration(false);
2373 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2375 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2379 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
2381 if (params.size() != 2)
2384 std::string nick = params[0];
2385 userrec* u = this->Instance->FindNick(prefix);
2386 userrec* who = this->Instance->FindNick(nick);
2390 /* Prepend kill source, if we don't have one */
2391 std::string sourceserv = prefix;
2394 sourceserv = u->server;
2396 if (*(params[1].c_str()) != '[')
2398 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2400 std::string reason = params[1];
2401 params[1] = ":" + params[1];
2402 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2403 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2404 userrec::QuitUser(this->Instance,who,reason);
2409 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
2411 if (params.size() < 1)
2414 if (params.size() == 1)
2416 TreeServer* ServerSource = Utils->FindServer(prefix);
2419 ServerSource->SetPingFlag();
2424 std::string forwardto = params[1];
2425 if (forwardto == this->Instance->Config->ServerName)
2428 * this is a PONG for us
2429 * if the prefix is a user, check theyre local, and if they are,
2430 * dump the PONG reply back to their fd. If its a server, do nowt.
2431 * Services might want to send these s->s, but we dont need to yet.
2433 userrec* u = this->Instance->FindNick(prefix);
2437 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2442 // not for us, pass it on :)
2443 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2450 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
2452 if (params.size() < 3)
2455 TreeServer* ServerSource = Utils->FindServer(prefix);
2459 if (params[0] == "*")
2461 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2463 else if (*(params[0].c_str()) == '#')
2465 chanrec* c = this->Instance->FindChan(params[0]);
2468 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2471 else if (*(params[0].c_str()) != '#')
2473 userrec* u = this->Instance->FindNick(params[0]);
2476 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2481 params[2] = ":" + params[2];
2482 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2486 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
2488 if (params.size() < 1)
2491 TreeServer* ServerSource = Utils->FindServer(prefix);
2495 ServerSource->SetVersion(params[0]);
2497 params[0] = ":" + params[0];
2498 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2502 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
2504 if (params.size() < 1)
2507 userrec* u = this->Instance->FindNick(prefix);
2511 u->ChangeDisplayedHost(params[0].c_str());
2512 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2517 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
2519 if (params.size() < 6)
2522 bool propogate = false;
2524 switch (*(params[0].c_str()))
2527 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2528 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2531 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2532 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2535 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2536 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2539 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2540 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2543 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2546 /* Just in case... */
2547 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2552 /* Send it on its way */
2555 if (atoi(params[4].c_str()))
2557 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());
2561 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());
2563 params[5] = ":" + params[5];
2564 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2566 if (!this->bursting)
2568 Instance->Log(DEBUG,"Applying lines...");
2569 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2574 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
2576 if (params.size() < 1)
2579 userrec* u = this->Instance->FindNick(prefix);
2583 u->ChangeName(params[0].c_str());
2584 params[0] = ":" + params[0];
2585 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2590 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
2592 if (params.size() < 1)
2595 Instance->Log(DEBUG,"In IDLE command");
2596 userrec* u = this->Instance->FindNick(prefix);
2600 Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2601 // an incoming request
2602 if (params.size() == 1)
2604 userrec* x = this->Instance->FindNick(params[0]);
2605 if ((x) && (IS_LOCAL(x)))
2607 userrec* x = this->Instance->FindNick(params[0]);
2608 char signon[MAXBUF];
2611 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2612 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2613 std::deque<std::string> par;
2614 par.push_back(prefix);
2615 par.push_back(signon);
2616 par.push_back(idle);
2617 // ours, we're done, pass it BACK
2618 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2622 // not ours pass it on
2623 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2626 else if (params.size() == 3)
2628 std::string who_did_the_whois = params[0];
2629 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2630 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2632 // an incoming reply to a whois we sent out
2633 std::string nick_whoised = prefix;
2634 unsigned long signon = atoi(params[1].c_str());
2635 unsigned long idle = atoi(params[2].c_str());
2636 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2637 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2641 // not ours, pass it on
2642 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2649 bool Push(std::string prefix, std::deque<std::string> ¶ms)
2651 if (params.size() < 2)
2654 userrec* u = this->Instance->FindNick(params[0]);
2661 u->Write(params[1]);
2665 // continue the raw onwards
2666 params[1] = ":" + params[1];
2667 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2672 bool Time(std::string prefix, std::deque<std::string> ¶ms)
2674 // :source.server TIME remote.server sendernick
2675 // :remote.server TIME source.server sendernick TS
2676 if (params.size() == 2)
2678 // someone querying our time?
2679 if (this->Instance->Config->ServerName == params[0])
2681 userrec* u = this->Instance->FindNick(params[1]);
2685 snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2686 params.push_back(curtime);
2688 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2693 // not us, pass it on
2694 userrec* u = this->Instance->FindNick(params[1]);
2696 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2699 else if (params.size() == 3)
2701 // a response to a previous TIME
2702 userrec* u = this->Instance->FindNick(params[1]);
2703 if ((u) && (IS_LOCAL(u)))
2705 time_t rawtime = atol(params[2].c_str());
2706 struct tm * timeinfo;
2707 timeinfo = localtime(&rawtime);
2709 snprintf(tms,26,"%s",asctime(timeinfo));
2711 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2716 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2722 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
2724 if (params.size() < 1)
2727 if (params.size() == 1)
2729 std::string stufftobounce = params[0];
2730 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2735 std::string forwardto = params[1];
2736 if (forwardto == this->Instance->Config->ServerName)
2738 // this is a ping for us, send back PONG to the requesting server
2739 params[1] = params[0];
2740 params[0] = forwardto;
2741 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2745 // not for us, pass it on :)
2746 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2752 bool RemoveStatus(std::string prefix, std::deque<std::string> ¶ms)
2754 if (params.size() < 1)
2757 chanrec* c = Instance->FindChan(params[0]);
2761 irc::modestacker modestack(false);
2762 CUList *ulist = c->GetUsers();
2764 std::deque<std::string> stackresult;
2767 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2769 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2770 if (modesequence.length())
2772 Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2773 irc::spacesepstream sep(modesequence);
2774 std::string modeletters = sep.GetToken();
2775 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2777 while (!modeletters.empty())
2779 char mletter = *(modeletters.begin());
2780 modestack.Push(mletter,sep.GetToken());
2781 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2782 modeletters.erase(modeletters.begin());
2783 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2788 while (modestack.GetStackedLine(stackresult))
2790 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2791 stackresult.push_front(ConvToStr(c->age));
2792 stackresult.push_front(c->name);
2793 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2794 stackresult.erase(stackresult.begin() + 1);
2795 Instance->Log(DEBUG,"Stacked items:");
2796 for (size_t z = 0; z < stackresult.size(); z++)
2798 y[z] = stackresult[z].c_str();
2799 Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2801 userrec* n = new userrec(Instance);
2802 n->SetFd(FD_MAGIC_NUMBER);
2803 Instance->SendMode(y, stackresult.size(), n);
2810 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
2812 if (params.size() < 4)
2815 std::string servername = params[0];
2816 std::string password = params[1];
2817 // hopcount is not used for a remote server, we calculate this ourselves
2818 std::string description = params[3];
2819 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2823 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2826 TreeServer* CheckDupe = Utils->FindServer(servername);
2829 this->WriteLine("ERROR :Server "+servername+" already exists!");
2830 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2833 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2834 ParentOfThis->AddChild(Node);
2835 params[3] = ":" + params[3];
2836 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2837 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2841 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2843 if (params.size() < 4)
2846 irc::string servername = params[0].c_str();
2847 std::string sname = params[0];
2848 std::string password = params[1];
2849 int hops = atoi(params[2].c_str());
2853 this->WriteLine("ERROR :Server too far away for authentication");
2854 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2857 std::string description = params[3];
2858 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2860 if ((x->Name == servername) && (x->RecvPass == password))
2862 TreeServer* CheckDupe = Utils->FindServer(sname);
2865 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2866 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2869 // Begin the sync here. this kickstarts the
2870 // other side, waiting in WAIT_AUTH_2 state,
2871 // into starting their burst, as it shows
2872 // that we're happy.
2873 this->LinkState = CONNECTED;
2874 // we should add the details of this server now
2875 // to the servers tree, as a child of the root
2877 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2878 Utils->TreeRoot->AddChild(Node);
2879 params[3] = ":" + params[3];
2880 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2881 this->bursting = true;
2882 this->DoBurst(Node);
2886 this->WriteLine("ERROR :Invalid credentials");
2887 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2891 bool Inbound_Server(std::deque<std::string> ¶ms)
2893 if (params.size() < 4)
2896 irc::string servername = params[0].c_str();
2897 std::string sname = params[0];
2898 std::string password = params[1];
2899 int hops = atoi(params[2].c_str());
2903 this->WriteLine("ERROR :Server too far away for authentication");
2904 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2907 std::string description = params[3];
2908 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2910 if ((x->Name == servername) && (x->RecvPass == password))
2912 TreeServer* CheckDupe = Utils->FindServer(sname);
2915 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2916 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2919 /* If the config says this link is encrypted, but the remote side
2920 * hasnt bothered to send the AES command before SERVER, then we
2921 * boot them off as we MUST have this connection encrypted.
2923 if ((x->EncryptionKey != "") && (!this->ctx_in))
2925 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2926 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2929 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2930 this->InboundServerName = sname;
2931 this->InboundDescription = description;
2932 // this is good. Send our details: Our server name and description and hopcount of 0,
2933 // along with the sendpass from this block.
2934 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2935 // move to the next state, we are now waiting for THEM.
2936 this->LinkState = WAIT_AUTH_2;
2940 this->WriteLine("ERROR :Invalid credentials");
2941 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2945 void Split(std::string line, std::deque<std::string> &n)
2948 irc::tokenstream tokens(line);
2950 while ((param = tokens.GetToken()) != "")
2955 bool ProcessLine(std::string line)
2957 std::deque<std::string> params;
2958 irc::string command;
2964 line = line.substr(0, line.find_first_of("\r\n"));
2966 Instance->Log(DEBUG,"IN: %s", line.c_str());
2968 this->Split(line.c_str(),params);
2970 if ((params[0][0] == ':') && (params.size() > 1))
2972 prefix = params[0].substr(1);
2976 command = params[0].c_str();
2979 if ((!this->ctx_in) && (command == "AES"))
2981 std::string sserv = params[0];
2982 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2984 if ((x->EncryptionKey != "") && (x->Name == sserv))
2986 this->InitAES(x->EncryptionKey,sserv);
2992 else if ((this->ctx_in) && (command == "AES"))
2994 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2997 switch (this->LinkState)
3002 // Waiting for SERVER command from remote server. Server initiating
3003 // the connection sends the first SERVER command, listening server
3004 // replies with theirs if its happy, then if the initiator is happy,
3005 // it starts to send its net sync, which starts the merge, otherwise
3006 // it sends an ERROR.
3007 if (command == "PASS")
3009 /* Silently ignored */
3011 else if (command == "SERVER")
3013 return this->Inbound_Server(params);
3015 else if (command == "ERROR")
3017 return this->Error(params);
3019 else if (command == "USER")
3021 this->WriteLine("ERROR :Client connections to this port are prohibited.");
3024 else if (command == "CAPAB")
3026 return this->Capab(params);
3028 else if ((command == "U") || (command == "S"))
3030 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3035 std::string error("ERROR :Invalid command in negotiation phase: ");
3036 error.append(command.c_str());
3037 this->WriteLine(error);
3042 // Waiting for start of other side's netmerge to say they liked our
3044 if (command == "SERVER")
3046 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3050 else if ((command == "U") || (command == "S"))
3052 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3055 else if (command == "BURST")
3059 /* If a time stamp is provided, try and check syncronization */
3060 time_t THEM = atoi(params[0].c_str());
3061 long delta = THEM-time(NULL);
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!");
3068 else if ((delta < -60) || (delta > 60))
3070 this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
3073 this->LinkState = CONNECTED;
3074 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3075 Utils->TreeRoot->AddChild(Node);
3077 params.push_back(InboundServerName);
3078 params.push_back("*");
3079 params.push_back("1");
3080 params.push_back(":"+InboundDescription);
3081 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3082 this->bursting = true;
3083 this->DoBurst(Node);
3085 else if (command == "ERROR")
3087 return this->Error(params);
3089 else if (command == "CAPAB")
3091 return this->Capab(params);
3096 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3100 if (command == "SERVER")
3102 // another server we connected to, which was in WAIT_AUTH_1 state,
3103 // has just sent us their credentials. If we get this far, theyre
3104 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3105 // if we're happy with this, we should send our netburst which
3106 // kickstarts the merge.
3107 return this->Outbound_Reply_Server(params);
3109 else if (command == "ERROR")
3111 return this->Error(params);
3115 // This is the 'authenticated' state, when all passwords
3116 // have been exchanged and anything past this point is taken
3121 std::string direction = prefix;
3122 userrec* t = this->Instance->FindNick(prefix);
3125 direction = t->server;
3127 TreeServer* route_back_again = Utils->BestRouteTo(direction);
3128 if ((!route_back_again) || (route_back_again->GetSocket() != this))
3130 if (route_back_again)
3131 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3136 * When there is activity on the socket, reset the ping counter so
3137 * that we're not wasting bandwidth pinging an active server.
3139 route_back_again->SetNextPingTime(time(NULL) + 60);
3140 route_back_again->SetPingFlag();
3143 if (command == "SVSMODE")
3145 /* Services expects us to implement
3146 * SVSMODE. In inspircd its the same as
3151 std::string target = "";
3152 /* Yes, know, this is a mess. Its reasonably fast though as we're
3153 * working with std::string here.
3155 if ((command == "NICK") && (params.size() > 1))
3157 return this->IntroduceClient(prefix,params);
3159 else if (command == "FJOIN")
3161 return this->ForceJoin(prefix,params);
3163 else if (command == "STATS")
3165 return this->Stats(prefix, params);
3167 else if (command == "MOTD")
3169 return this->Motd(prefix, params);
3171 else if (command == "ADMIN")
3173 return this->Admin(prefix, params);
3175 else if (command == "SERVER")
3177 return this->RemoteServer(prefix,params);
3179 else if (command == "ERROR")
3181 return this->Error(params);
3183 else if (command == "OPERTYPE")
3185 return this->OperType(prefix,params);
3187 else if (command == "FMODE")
3189 return this->ForceMode(prefix,params);
3191 else if (command == "KILL")
3193 return this->RemoteKill(prefix,params);
3195 else if (command == "FTOPIC")
3197 return this->ForceTopic(prefix,params);
3199 else if (command == "REHASH")
3201 return this->RemoteRehash(prefix,params);
3203 else if (command == "METADATA")
3205 return this->MetaData(prefix,params);
3207 else if (command == "REMSTATUS")
3209 return this->RemoveStatus(prefix,params);
3211 else if (command == "PING")
3214 * We just got a ping from a server that's bursting.
3215 * This can't be right, so set them to not bursting, and
3216 * apply their lines.
3220 this->bursting = false;
3221 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3225 prefix = this->GetName();
3227 return this->LocalPing(prefix,params);
3229 else if (command == "PONG")
3232 * We just got a pong from a server that's bursting.
3233 * This can't be right, so set them to not bursting, and
3234 * apply their lines.
3238 this->bursting = false;
3239 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3243 prefix = this->GetName();
3245 return this->LocalPong(prefix,params);
3247 else if (command == "VERSION")
3249 return this->ServerVersion(prefix,params);
3251 else if (command == "FHOST")
3253 return this->ChangeHost(prefix,params);
3255 else if (command == "FNAME")
3257 return this->ChangeName(prefix,params);
3259 else if (command == "ADDLINE")
3261 return this->AddLine(prefix,params);
3263 else if (command == "SVSNICK")
3267 prefix = this->GetName();
3269 return this->ForceNick(prefix,params);
3271 else if (command == "IDLE")
3273 return this->Whois(prefix,params);
3275 else if (command == "PUSH")
3277 return this->Push(prefix,params);
3279 else if (command == "TIME")
3281 return this->Time(prefix,params);
3283 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3285 std::string sourceserv = this->myhost;
3286 if (params.size() == 3)
3288 userrec* user = this->Instance->FindNick(params[1]);
3289 chanrec* chan = this->Instance->FindChan(params[0]);
3292 if (!chan->ServerKickUser(user, params[2].c_str(), false))
3293 /* Yikes, the channels gone! */
3297 if (this->InboundServerName != "")
3299 sourceserv = this->InboundServerName;
3301 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3303 else if (command == "SVSJOIN")
3307 prefix = this->GetName();
3309 return this->ServiceJoin(prefix,params);
3311 else if (command == "SQUIT")
3313 if (params.size() == 2)
3315 this->Squit(Utils->FindServer(params[0]),params[1]);
3319 else if (command == "ENDBURST")
3321 this->bursting = false;
3322 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3323 std::string sourceserv = this->myhost;
3324 if (this->InboundServerName != "")
3326 sourceserv = this->InboundServerName;
3328 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3333 // not a special inter-server command.
3334 // Emulate the actual user doing the command,
3335 // this saves us having a huge ugly parser.
3336 userrec* who = this->Instance->FindNick(prefix);
3337 std::string sourceserv = this->myhost;
3338 if (this->InboundServerName != "")
3340 sourceserv = this->InboundServerName;
3344 if ((command == "NICK") && (params.size() > 0))
3346 /* On nick messages, check that the nick doesnt
3347 * already exist here. If it does, kill their copy,
3350 userrec* x = this->Instance->FindNick(params[0]);
3351 if ((x) && (x != who))
3353 std::deque<std::string> p;
3354 p.push_back(params[0]);
3355 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3356 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3358 p.push_back(prefix);
3359 p.push_back("Nickname collision");
3360 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3361 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3362 userrec* y = this->Instance->FindNick(prefix);
3365 userrec::QuitUser(this->Instance,y,"Nickname collision");
3367 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3371 target = who->server;
3372 const char* strparams[127];
3373 for (unsigned int q = 0; q < params.size(); q++)
3375 strparams[q] = params[q].c_str();
3377 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3380 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3387 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3393 // its not a user. Its either a server, or somethings screwed up.
3394 if (Utils->IsServer(prefix))
3396 target = this->Instance->Config->ServerName;
3400 Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3404 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3413 virtual std::string GetName()
3415 std::string sourceserv = this->myhost;
3416 if (this->InboundServerName != "")
3418 sourceserv = this->InboundServerName;
3423 virtual void OnTimeout()
3425 if (this->LinkState == CONNECTING)
3427 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3428 Link* MyLink = FindLink(myhost);
3434 virtual void OnClose()
3436 // Connection closed.
3437 // If the connection is fully up (state CONNECTED)
3438 // then propogate a netsplit to all peers.
3439 std::string quitserver = this->myhost;
3440 if (this->InboundServerName != "")
3442 quitserver = this->InboundServerName;
3444 TreeServer* s = Utils->FindServer(quitserver);
3447 Squit(s,"Remote host closed the connection");
3449 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3452 virtual int OnIncomingConnection(int newsock, char* ip)
3454 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3455 * or discovering if this port is the server port, we don't allow connections from any
3456 * IPs for which we don't have a link block.
3460 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3463 for (vector<std::string>::iterator i = ValidIPs.begin(); i != ValidIPs.end(); i++)
3464 if (MatchCIDR(ip, (*i).c_str()))
3469 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3474 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3475 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3480 /** This class is used to resolve server hostnames during /connect and autoconnect.
3481 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3482 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3483 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3484 * will have an IP address which we can then use to continue our connection.
3486 class ServernameResolver : public Resolver
3489 /** A copy of the Link tag info for what we're connecting to.
3490 * We take a copy, rather than using a pointer, just in case the
3491 * admin takes the tag away and rehashes while the domain is resolving.
3494 SpanningTreeUtilities* Utils;
3496 ServernameResolver(SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x), Utils(Util)
3498 /* Nothing in here, folks */
3501 void OnLookupComplete(const std::string &result)
3503 /* Initiate the connection, now that we have an IP to use.
3504 * Passing a hostname directly to InspSocket causes it to
3505 * just bail and set its FD to -1.
3507 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3508 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3510 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str());
3511 if (newsocket->GetFd() > -1)
3517 /* Something barfed, show the opers */
3518 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3520 DoFailOver(&MyLink);
3525 void OnError(ResolverError e, const std::string &errormessage)
3528 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3529 DoFailOver(&MyLink);
3533 /** Handle resolving of server IPs for the cache
3535 class SecurityIPResolver : public Resolver
3540 SecurityIPResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
3544 void OnLookupComplete(const std::string &result)
3546 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3547 ValidIPs.push_back(result);
3550 void OnError(ResolverError e, const std::string &errormessage)
3552 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3556 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance) : ServerInstance(Instance)
3559 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3560 this->ReadConfiguration(true);
3563 SpanningTreeUtilities::~SpanningTreeUtilities()
3565 for (unsigned int i = 0; i < Bindings.size(); i++)
3567 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3568 ServerInstance->SE->DelFd(Bindings[i]);
3569 Bindings[i]->Close();
3570 DELETE(Bindings[i]);
3572 ServerInstance->Log(DEBUG,"Freeing connected servers...");
3573 while (TreeRoot->ChildCount())
3575 TreeServer* child_server = TreeRoot->GetChild(0);
3576 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3579 TreeSocket* sock = child_server->GetSocket();
3580 ServerInstance->SE->DelFd(sock);
3587 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3589 for (unsigned int c = 0; c < list.size(); c++)
3591 if (list[c] == server)
3596 list.push_back(server);
3599 /** returns a list of DIRECT servernames for a specific channel */
3600 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3602 CUList *ulist = c->GetUsers();
3603 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3605 if (i->second->GetFd() < 0)
3607 TreeServer* best = this->BestRouteTo(i->second->server);
3609 AddThisServer(best,list);
3615 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms)
3617 TreeServer* omitroute = this->BestRouteTo(omit);
3618 if ((command == "NOTICE") || (command == "PRIVMSG"))
3620 if (params.size() >= 2)
3623 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3625 params[0] = params[0].substr(1, params[0].length()-1);
3627 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3629 // special routing for private messages/notices
3630 userrec* d = ServerInstance->FindNick(params[0]);
3633 std::deque<std::string> par;
3634 par.push_back(params[0]);
3635 par.push_back(":"+params[1]);
3636 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3640 else if (*(params[0].c_str()) == '$')
3642 std::deque<std::string> par;
3643 par.push_back(params[0]);
3644 par.push_back(":"+params[1]);
3645 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3650 chanrec* c = ServerInstance->FindChan(params[0]);
3653 std::deque<TreeServer*> list;
3654 GetListOfServersForChannel(c,list);
3655 unsigned int lsize = list.size();
3656 for (unsigned int i = 0; i < lsize; i++)
3658 TreeSocket* Sock = list[i]->GetSocket();
3659 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3661 Sock->WriteLine(data);
3669 unsigned int items =this->TreeRoot->ChildCount();
3670 for (unsigned int x = 0; x < items; x++)
3672 TreeServer* Route = this->TreeRoot->GetChild(x);
3673 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3675 TreeSocket* Sock = Route->GetSocket();
3677 Sock->WriteLine(data);
3683 bool SpanningTreeUtilities::DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
3685 TreeServer* omitroute = this->BestRouteTo(omit);
3686 std::string FullLine = ":" + prefix + " " + command;
3687 unsigned int words = params.size();
3688 for (unsigned int x = 0; x < words; x++)
3690 FullLine = FullLine + " " + params[x];
3692 unsigned int items = this->TreeRoot->ChildCount();
3693 for (unsigned int x = 0; x < items; x++)
3695 TreeServer* Route = this->TreeRoot->GetChild(x);
3696 // Send the line IF:
3697 // The route has a socket (its a direct connection)
3698 // The route isnt the one to be omitted
3699 // The route isnt the path to the one to be omitted
3700 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3702 TreeSocket* Sock = Route->GetSocket();
3704 Sock->WriteLine(FullLine);
3710 bool SpanningTreeUtilities::DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
3712 std::string FullLine = ":" + prefix + " " + command;
3713 unsigned int words = params.size();
3714 for (unsigned int x = 0; x < words; x++)
3716 FullLine = FullLine + " " + params[x];
3718 unsigned int items = this->TreeRoot->ChildCount();
3719 for (unsigned int x = 0; x < items; x++)
3721 TreeServer* Route = this->TreeRoot->GetChild(x);
3722 if (Route && Route->GetSocket())
3724 TreeSocket* Sock = Route->GetSocket();
3726 Sock->WriteLine(FullLine);
3732 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3734 std::string spfx = prefix;
3735 std::string scmd = command;
3736 return this->DoOneToMany(spfx, scmd, params);
3739 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3741 std::string spfx = prefix;
3742 std::string scmd = command;
3743 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3746 bool SpanningTreeUtilities::DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
3748 TreeServer* Route = this->BestRouteTo(target);
3751 std::string FullLine = ":" + prefix + " " + command;
3752 unsigned int words = params.size();
3753 for (unsigned int x = 0; x < words; x++)
3755 FullLine = FullLine + " " + params[x];
3757 if (Route && Route->GetSocket())
3759 TreeSocket* Sock = Route->GetSocket();
3761 Sock->WriteLine(FullLine);
3771 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3773 Conf = new ConfigReader(ServerInstance);
3776 for (int j =0; j < Conf->Enumerate("bind"); j++)
3778 std::string Type = Conf->ReadValue("bind","type",j);
3779 std::string IP = Conf->ReadValue("bind","address",j);
3780 int Port = Conf->ReadInteger("bind","port",j,true);
3781 if (Type == "servers")
3783 ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), Port);
3788 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(),Port,true,10);
3789 if (listener->GetState() == I_LISTENING)
3791 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), Port);
3792 Bindings.push_back(listener);
3796 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3800 ServerInstance->Log(DEBUG,"Done with this binding");
3804 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3805 HideULines = Conf->ReadFlag("options","hideulines",0);
3806 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3809 for (int j =0; j < Conf->Enumerate("link"); j++)
3812 std::string Allow = Conf->ReadValue("link","allowmask",j);
3813 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3814 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3815 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3816 L.Port = Conf->ReadInteger("link","port",j,true);
3817 L.SendPass = Conf->ReadValue("link","sendpass",j);
3818 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3819 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3820 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
3821 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3822 L.NextConnectTime = time(NULL) + L.AutoConnect;
3823 /* Bugfix by brain, do not allow people to enter bad configurations */
3824 if (L.Name != ServerInstance->Config->ServerName)
3826 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3828 ValidIPs.push_back(L.IPAddr);
3831 ValidIPs.push_back(Allow);
3833 /* Needs resolving */
3835 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3839 SecurityIPResolver* sr = new SecurityIPResolver(ServerInstance, L.IPAddr, L);
3840 ServerInstance->AddResolver(sr);
3842 catch (ModuleException& e)
3844 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
3848 LinkBlocks.push_back(L);
3849 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3855 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3857 else if (L.RecvPass == "")
3859 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3861 else if (L.SendPass == "")
3863 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3865 else if (L.Name == "")
3867 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
3871 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3877 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
3885 class ModuleSpanningTree : public Module
3889 unsigned int max_local;
3890 unsigned int max_global;
3891 cmd_rconnect* command_rconnect;
3892 SpanningTreeUtilities* Utils;
3896 ModuleSpanningTree(InspIRCd* Me)
3897 : Module::Module(Me), max_local(0), max_global(0)
3899 Utils = new SpanningTreeUtilities(Me);
3901 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
3902 ServerInstance->AddCommand(command_rconnect);
3905 void ShowLinks(TreeServer* Current, userrec* user, int hops)
3907 std::string Parent = Utils->TreeRoot->GetName();
3908 if (Current->GetParent())
3910 Parent = Current->GetParent()->GetName();
3912 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3914 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3918 ShowLinks(Current->GetChild(q),user,hops+1);
3923 ShowLinks(Current->GetChild(q),user,hops+1);
3926 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3927 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
3929 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());
3932 int CountLocalServs()
3934 return Utils->TreeRoot->ChildCount();
3939 return serverlist.size();
3942 void HandleLinks(const char** parameters, int pcnt, userrec* user)
3944 ShowLinks(Utils->TreeRoot,user,0);
3945 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
3949 void HandleLusers(const char** parameters, int pcnt, userrec* user)
3951 unsigned int n_users = ServerInstance->UserCount();
3953 /* Only update these when someone wants to see them, more efficient */
3954 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
3955 max_local = ServerInstance->LocalUserCount();
3956 if (n_users > max_global)
3957 max_global = n_users;
3959 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs());
3960 if (ServerInstance->OperCount())
3961 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
3962 if (ServerInstance->UnregisteredUserCount())
3963 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
3964 if (ServerInstance->ChannelCount())
3965 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
3966 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs());
3967 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
3968 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
3972 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3974 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3978 for (int t = 0; t < depth; t++)
3980 matrix[line][t] = ' ';
3983 // For Aligning, we need to work out exactly how deep this thing is, and produce
3984 // a 'Spacer' String to compensate.
3987 memset(spacer,' ',40);
3988 if ((40 - Current->GetName().length() - depth) > 1) {
3989 spacer[40 - Current->GetName().length() - depth] = '\0';
3998 if (ServerInstance->clientlist.size() == 0) {
3999 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4004 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4006 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4007 totusers += Current->GetUserCount();
4009 strlcpy(&matrix[line][depth],text,80);
4011 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4013 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4017 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4022 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4028 int HandleMotd(const char** parameters, int pcnt, userrec* user)
4032 /* Remote MOTD, the server is within the 1st parameter */
4033 std::deque<std::string> params;
4034 params.push_back(parameters[0]);
4036 /* Send it out remotely, generate no reply yet */
4037 TreeServer* s = Utils->FindServerMask(parameters[0]);
4040 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4044 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4051 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4055 /* Remote ADMIN, the server is within the 1st parameter */
4056 std::deque<std::string> params;
4057 params.push_back(parameters[0]);
4059 /* Send it out remotely, generate no reply yet */
4060 TreeServer* s = Utils->FindServerMask(parameters[0]);
4063 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4067 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4074 int HandleStats(const char** parameters, int pcnt, userrec* user)
4078 /* Remote STATS, the server is within the 2nd parameter */
4079 std::deque<std::string> params;
4080 params.push_back(parameters[0]);
4081 params.push_back(parameters[1]);
4082 /* Send it out remotely, generate no reply yet */
4083 TreeServer* s = Utils->FindServerMask(parameters[1]);
4086 params[1] = s->GetName();
4087 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4091 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4098 // Ok, prepare to be confused.
4099 // After much mulling over how to approach this, it struck me that
4100 // the 'usual' way of doing a /MAP isnt the best way. Instead of
4101 // keeping track of a ton of ascii characters, and line by line
4102 // under recursion working out where to place them using multiplications
4103 // and divisons, we instead render the map onto a backplane of characters
4104 // (a character matrix), then draw the branches as a series of "L" shapes
4105 // from the nodes. This is not only friendlier on CPU it uses less stack.
4107 void HandleMap(const char** parameters, int pcnt, userrec* user)
4109 // This array represents a virtual screen which we will
4110 // "scratch" draw to, as the console device of an irc
4111 // client does not provide for a proper terminal.
4113 float totservers = 0;
4114 char matrix[128][80];
4115 for (unsigned int t = 0; t < 128; t++)
4117 matrix[t][0] = '\0';
4120 // The only recursive bit is called here.
4121 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4122 // Process each line one by one. The algorithm has a limit of
4123 // 128 servers (which is far more than a spanning tree should have
4124 // anyway, so we're ok). This limit can be raised simply by making
4125 // the character matrix deeper, 128 rows taking 10k of memory.
4126 for (int l = 1; l < line; l++)
4128 // scan across the line looking for the start of the
4129 // servername (the recursive part of the algorithm has placed
4130 // the servers at indented positions depending on what they
4132 int first_nonspace = 0;
4133 while (matrix[l][first_nonspace] == ' ')
4138 // Draw the `- (corner) section: this may be overwritten by
4139 // another L shape passing along the same vertical pane, becoming
4140 // a |- (branch) section instead.
4141 matrix[l][first_nonspace] = '-';
4142 matrix[l][first_nonspace-1] = '`';
4144 // Draw upwards until we hit the parent server, causing possibly
4145 // other corners (`-) to become branches (|-)
4146 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4148 matrix[l2][first_nonspace-1] = '|';
4152 // dump the whole lot to the user. This is the easy bit, honest.
4153 for (int t = 0; t < line; t++)
4155 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4157 float avg_users = totusers / totservers;
4158 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);
4159 user->WriteServ("007 %s :End of /MAP",user->nick);
4163 int HandleSquit(const char** parameters, int pcnt, userrec* user)
4165 TreeServer* s = Utils->FindServerMask(parameters[0]);
4168 if (s == Utils->TreeRoot)
4170 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4173 TreeSocket* sock = s->GetSocket();
4176 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4177 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4178 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4179 ServerInstance->SE->DelFd(sock);
4185 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4190 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4195 int HandleTime(const char** parameters, int pcnt, userrec* user)
4197 if ((IS_LOCAL(user)) && (pcnt))
4199 TreeServer* found = Utils->FindServerMask(parameters[0]);
4202 // we dont' override for local server
4203 if (found == Utils->TreeRoot)
4206 std::deque<std::string> params;
4207 params.push_back(found->GetName());
4208 params.push_back(user->nick);
4209 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4213 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4219 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4221 if ((IS_LOCAL(user)) && (pcnt > 1))
4223 userrec* remote = ServerInstance->FindNick(parameters[1]);
4224 if ((remote) && (remote->GetFd() < 0))
4226 std::deque<std::string> params;
4227 params.push_back(parameters[1]);
4228 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4233 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4234 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4241 void DoPingChecks(time_t curtime)
4243 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4245 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4246 TreeSocket* sock = serv->GetSocket();
4249 if (curtime >= serv->NextPingTime())
4251 if (serv->AnsweredLastPing())
4253 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4254 serv->SetNextPingTime(curtime + 60);
4258 // they didnt answer, boot them
4259 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4260 sock->Squit(serv,"Ping timeout");
4261 ServerInstance->SE->DelFd(sock);
4271 void ConnectServer(Link* x)
4275 /* Do we already have an IP? If so, no need to resolve it. */
4276 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4278 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str());
4279 if (newsocket->GetFd() > -1)
4281 /* Handled automatically on success */
4285 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4287 this->DoFailOver(x);
4294 ServernameResolver* snr = new ServernameResolver(Utils, ServerInstance,x->IPAddr, *x);
4295 ServerInstance->AddResolver(snr);
4297 catch (ModuleException& e)
4299 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4300 this->DoFailOver(x);
4305 void DoFailOver(Link* x)
4307 if (x->FailOver.length())
4309 if (x->FailOver == x->Name)
4311 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());
4314 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
4317 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
4318 ConnectServer(TryThisOne);
4322 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
4327 Link* FindLink(const std::string& name)
4329 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4331 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
4339 void AutoConnectServers(time_t curtime)
4341 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4343 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4345 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4346 x->NextConnectTime = curtime + x->AutoConnect;
4347 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4348 if (x->FailOver.length())
4350 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4353 /* The failover for this server is currently a member of the network.
4354 * The failover probably succeeded, where the main link did not.
4355 * Don't try the main link until the failover is gone again.
4362 // an autoconnected server is not connected. Check if its time to connect it
4363 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4364 this->ConnectServer(&(*x));
4370 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4372 // we've already checked if pcnt > 0, so this is safe
4373 TreeServer* found = Utils->FindServerMask(parameters[0]);
4376 std::string Version = found->GetVersion();
4377 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4378 if (found == Utils->TreeRoot)
4380 std::stringstream out(ServerInstance->Config->data005);
4381 std::string token = "";
4382 std::string line5 = "";
4383 int token_counter = 0;
4388 line5 = line5 + token + " ";
4391 if ((token_counter >= 13) || (out.eof() == true))
4393 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4402 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4407 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4409 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4411 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4413 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4416 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);
4417 ConnectServer(&(*x));
4422 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());
4427 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4431 virtual int OnStats(char statschar, userrec* user, string_list &results)
4433 if (statschar == 'c')
4435 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
4437 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr)+" * "+LinkBlocks[i].Name.c_str()+" "+ConvToStr(LinkBlocks[i].Port)+" "+(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4438 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
4440 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4441 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);
4447 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4449 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4453 if (command == "CONNECT")
4455 return this->HandleConnect(parameters,pcnt,user);
4457 else if (command == "STATS")
4459 return this->HandleStats(parameters,pcnt,user);
4461 else if (command == "MOTD")
4463 return this->HandleMotd(parameters,pcnt,user);
4465 else if (command == "ADMIN")
4467 return this->HandleAdmin(parameters,pcnt,user);
4469 else if (command == "SQUIT")
4471 return this->HandleSquit(parameters,pcnt,user);
4473 else if (command == "MAP")
4475 this->HandleMap(parameters,pcnt,user);
4478 else if ((command == "TIME") && (pcnt > 0))
4480 return this->HandleTime(parameters,pcnt,user);
4482 else if (command == "LUSERS")
4484 this->HandleLusers(parameters,pcnt,user);
4487 else if (command == "LINKS")
4489 this->HandleLinks(parameters,pcnt,user);
4492 else if (command == "WHOIS")
4497 return this->HandleRemoteWhois(parameters,pcnt,user);
4500 else if ((command == "VERSION") && (pcnt > 0))
4502 this->HandleVersion(parameters,pcnt,user);
4509 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4511 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4513 // this bit of code cleverly routes all module commands
4514 // to all remote severs *automatically* so that modules
4515 // can just handle commands locally, without having
4516 // to have any special provision in place for remote
4517 // commands and linking protocols.
4518 std::deque<std::string> params;
4520 for (int j = 0; j < pcnt; j++)
4522 if (strchr(parameters[j],' '))
4524 params.push_back(":" + std::string(parameters[j]));
4528 params.push_back(std::string(parameters[j]));
4531 ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4532 Utils->DoOneToMany(user->nick,command,params);
4536 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4538 TreeServer* s = Utils->FindServer(servername);
4541 description = s->GetDesc();
4545 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4547 if (IS_LOCAL(source))
4549 std::deque<std::string> params;
4550 params.push_back(dest->nick);
4551 params.push_back(channel->name);
4552 Utils->DoOneToMany(source->nick,"INVITE",params);
4556 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4558 std::deque<std::string> params;
4559 params.push_back(chan->name);
4560 params.push_back(":"+topic);
4561 Utils->DoOneToMany(user->nick,"TOPIC",params);
4564 virtual void OnWallops(userrec* user, const std::string &text)
4568 std::deque<std::string> params;
4569 params.push_back(":"+text);
4570 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4574 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4576 if (target_type == TYPE_USER)
4578 userrec* d = (userrec*)dest;
4579 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4581 std::deque<std::string> params;
4583 params.push_back(d->nick);
4584 params.push_back(":"+text);
4585 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4588 else if (target_type == TYPE_CHANNEL)
4592 chanrec *c = (chanrec*)dest;
4595 std::string cname = c->name;
4597 cname = status + cname;
4598 std::deque<TreeServer*> list;
4599 Utils->GetListOfServersForChannel(c,list);
4600 unsigned int ucount = list.size();
4601 for (unsigned int i = 0; i < ucount; i++)
4603 TreeSocket* Sock = list[i]->GetSocket();
4605 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4610 else if (target_type == TYPE_SERVER)
4614 char* target = (char*)dest;
4615 std::deque<std::string> par;
4616 par.push_back(target);
4617 par.push_back(":"+text);
4618 Utils->DoOneToMany(user->nick,"NOTICE",par);
4623 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4625 if (target_type == TYPE_USER)
4627 // route private messages which are targetted at clients only to the server
4628 // which needs to receive them
4629 userrec* d = (userrec*)dest;
4630 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4632 std::deque<std::string> params;
4634 params.push_back(d->nick);
4635 params.push_back(":"+text);
4636 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4639 else if (target_type == TYPE_CHANNEL)
4643 chanrec *c = (chanrec*)dest;
4646 std::string cname = c->name;
4648 cname = status + cname;
4649 std::deque<TreeServer*> list;
4650 Utils->GetListOfServersForChannel(c,list);
4651 unsigned int ucount = list.size();
4652 for (unsigned int i = 0; i < ucount; i++)
4654 TreeSocket* Sock = list[i]->GetSocket();
4656 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4661 else if (target_type == TYPE_SERVER)
4665 char* target = (char*)dest;
4666 std::deque<std::string> par;
4667 par.push_back(target);
4668 par.push_back(":"+text);
4669 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4674 virtual void OnBackgroundTimer(time_t curtime)
4676 AutoConnectServers(curtime);
4677 DoPingChecks(curtime);
4680 virtual void OnUserJoin(userrec* user, chanrec* channel)
4682 // Only do this for local users
4685 std::deque<std::string> params;
4687 params.push_back(channel->name);
4688 // set up their permissions and the channel TS with FJOIN.
4689 // All users are FJOINed now, because a module may specify
4690 // new joining permissions for the user.
4692 params.push_back(channel->name);
4693 params.push_back(ConvToStr(channel->age));
4694 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4695 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4699 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4701 // only occurs for local clients
4702 if (user->registered != REG_ALL)
4704 std::deque<std::string> params;
4705 params.push_back(newhost);
4706 Utils->DoOneToMany(user->nick,"FHOST",params);
4709 virtual void OnChangeName(userrec* user, const std::string &gecos)
4711 // only occurs for local clients
4712 if (user->registered != REG_ALL)
4714 std::deque<std::string> params;
4715 params.push_back(gecos);
4716 Utils->DoOneToMany(user->nick,"FNAME",params);
4719 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4723 std::deque<std::string> params;
4724 params.push_back(channel->name);
4725 if (partmessage != "")
4726 params.push_back(":"+partmessage);
4727 Utils->DoOneToMany(user->nick,"PART",params);
4731 virtual void OnUserConnect(userrec* user)
4733 char agestr[MAXBUF];
4736 std::deque<std::string> params;
4737 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4738 params.push_back(agestr);
4739 params.push_back(user->nick);
4740 params.push_back(user->host);
4741 params.push_back(user->dhost);
4742 params.push_back(user->ident);
4743 params.push_back("+"+std::string(user->FormatModes()));
4744 params.push_back(user->GetIPString());
4745 params.push_back(":"+std::string(user->fullname));
4746 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4748 // User is Local, change needs to be reflected!
4749 TreeServer* SourceServer = Utils->FindServer(user->server);
4752 SourceServer->AddUserCount();
4758 virtual void OnUserQuit(userrec* user, const std::string &reason)
4760 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4762 std::deque<std::string> params;
4763 params.push_back(":"+reason);
4764 Utils->DoOneToMany(user->nick,"QUIT",params);
4766 // Regardless, We need to modify the user Counts..
4767 TreeServer* SourceServer = Utils->FindServer(user->server);
4770 SourceServer->DelUserCount();
4775 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4779 std::deque<std::string> params;
4780 params.push_back(user->nick);
4781 Utils->DoOneToMany(oldnick,"NICK",params);
4785 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4787 if ((source) && (IS_LOCAL(source)))
4789 std::deque<std::string> params;
4790 params.push_back(chan->name);
4791 params.push_back(user->nick);
4792 params.push_back(":"+reason);
4793 Utils->DoOneToMany(source->nick,"KICK",params);
4797 std::deque<std::string> params;
4798 params.push_back(chan->name);
4799 params.push_back(user->nick);
4800 params.push_back(":"+reason);
4801 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4805 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4807 std::deque<std::string> params;
4808 params.push_back(dest->nick);
4809 params.push_back(":"+reason);
4810 Utils->DoOneToMany(source->nick,"KILL",params);
4813 virtual void OnRehash(const std::string ¶meter)
4815 if (parameter != "")
4817 std::deque<std::string> params;
4818 params.push_back(parameter);
4819 Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4821 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4823 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4824 ServerInstance->RehashServer();
4827 Utils->ReadConfiguration(false);
4830 // note: the protocol does not allow direct umode +o except
4831 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4833 virtual void OnOper(userrec* user, const std::string &opertype)
4837 std::deque<std::string> params;
4838 params.push_back(opertype);
4839 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
4843 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4845 if (IS_LOCAL(source))
4848 snprintf(type,8,"%cLINE",linetype);
4849 std::string stype = type;
4852 char sduration[MAXBUF];
4853 snprintf(sduration,MAXBUF,"%ld",duration);
4854 std::deque<std::string> params;
4855 params.push_back(host);
4856 params.push_back(sduration);
4857 params.push_back(":"+reason);
4858 Utils->DoOneToMany(source->nick,stype,params);
4862 std::deque<std::string> params;
4863 params.push_back(host);
4864 Utils->DoOneToMany(source->nick,stype,params);
4869 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4871 OnLine(source,hostmask,true,'G',duration,reason);
4874 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4876 OnLine(source,ipmask,true,'Z',duration,reason);
4879 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4881 OnLine(source,nickmask,true,'Q',duration,reason);
4884 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4886 OnLine(source,hostmask,true,'E',duration,reason);
4889 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4891 OnLine(source,hostmask,false,'G',0,"");
4894 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4896 OnLine(source,ipmask,false,'Z',0,"");
4899 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4901 OnLine(source,nickmask,false,'Q',0,"");
4904 virtual void OnDelELine(userrec* source, const std::string &hostmask)
4906 OnLine(source,hostmask,false,'E',0,"");
4909 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4911 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4913 if (target_type == TYPE_USER)
4915 userrec* u = (userrec*)dest;
4916 std::deque<std::string> params;
4917 params.push_back(u->nick);
4918 params.push_back(text);
4919 Utils->DoOneToMany(user->nick,"MODE",params);
4923 chanrec* c = (chanrec*)dest;
4924 std::deque<std::string> params;
4925 params.push_back(c->name);
4926 params.push_back(text);
4927 Utils->DoOneToMany(user->nick,"MODE",params);
4932 virtual void OnSetAway(userrec* user)
4936 std::deque<std::string> params;
4937 params.push_back(":"+std::string(user->awaymsg));
4938 Utils->DoOneToMany(user->nick,"AWAY",params);
4942 virtual void OnCancelAway(userrec* user)
4946 std::deque<std::string> params;
4948 Utils->DoOneToMany(user->nick,"AWAY",params);
4952 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4954 TreeSocket* s = (TreeSocket*)opaque;
4957 if (target_type == TYPE_USER)
4959 userrec* u = (userrec*)target;
4960 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4964 chanrec* c = (chanrec*)target;
4965 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4970 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4972 TreeSocket* s = (TreeSocket*)opaque;
4975 if (target_type == TYPE_USER)
4977 userrec* u = (userrec*)target;
4978 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
4980 else if (target_type == TYPE_OTHER)
4982 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
4984 else if (target_type == TYPE_CHANNEL)
4986 chanrec* c = (chanrec*)target;
4987 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
4992 virtual void OnEvent(Event* event)
4994 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4996 if (event->GetEventID() == "send_metadata")
4998 if (params->size() < 3)
5000 (*params)[2] = ":" + (*params)[2];
5001 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5003 else if (event->GetEventID() == "send_topic")
5005 if (params->size() < 2)
5007 (*params)[1] = ":" + (*params)[1];
5008 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5009 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time()));
5010 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5012 else if (event->GetEventID() == "send_mode")
5014 if (params->size() < 2)
5016 // Insert the TS value of the object, either userrec or chanrec
5018 userrec* a = ServerInstance->FindNick((*params)[0]);
5025 chanrec* a = ServerInstance->FindChan((*params)[0]);
5031 params->insert(params->begin() + 1,ConvToStr(ourTS));
5032 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5036 virtual ~ModuleSpanningTree()
5038 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5039 /* This will also free the listeners */
5043 virtual Version GetVersion()
5045 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5048 void Implements(char* List)
5050 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5051 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5052 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5053 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5054 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5055 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5056 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5059 /* It is IMPORTANT that m_spanningtree is the last module in the chain
5060 * so that any activity it sees is FINAL, e.g. we arent going to send out
5061 * a NICK message before m_cloaking has finished putting the +x on the user,
5063 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5064 * the module call queue.
5066 Priority Prioritize()
5068 return PRIORITY_LAST;
5072 void DoFailOver(Link* x)
5074 TreeProtocolModule->DoFailOver(x);
5077 Link* FindLink(const std::string& name)
5079 return TreeProtocolModule->FindLink(name);
5082 class ModuleSpanningTreeFactory : public ModuleFactory
5085 ModuleSpanningTreeFactory()
5089 ~ModuleSpanningTreeFactory()
5093 virtual Module * CreateModule(InspIRCd* Me)
5095 TreeProtocolModule = new ModuleSpanningTree(Me);
5096 return TreeProtocolModule;
5102 extern "C" void * init_module( void )
5104 return new ModuleSpanningTreeFactory;