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 */
25 #include "inspircd_config.h"
27 #include "configreader.h"
32 #include "commands/cmd_whois.h"
33 #include "commands/cmd_stats.h"
35 #include "helperfuncs.h"
37 #include "inspstring.h"
42 #include "cull_list.h"
45 #define nspace __gnu_cxx
48 * The server list in InspIRCd is maintained as two structures
49 * which hold the data in different ways. Most of the time, we
50 * want to very quicky obtain three pieces of information:
52 * (1) The information on a server
53 * (2) The information on the server we must send data through
54 * to actually REACH the server we're after
55 * (3) Potentially, the child/parent objects of this server
57 * The InspIRCd spanning protocol provides easy access to these
58 * by storing the data firstly in a recursive structure, where
59 * each item references its parent item, and a dynamic list
60 * of child items, and another structure which stores the items
61 * hashed, linearly. This means that if we want to find a server
62 * by name quickly, we can look it up in the hash, avoiding
63 * any O(n) lookups. If however, during a split or sync, we want
64 * to apply an operation to a server, and any of its child objects
65 * we can resort to recursion to walk the tree structure.
68 class ModuleSpanningTree;
69 static ModuleSpanningTree* TreeProtocolModule;
71 extern ServerConfig* Config;
72 extern InspIRCd* ServerInstance;
73 extern std::vector<Module*> modules;
74 extern std::vector<ircd_module*> factory;
77 /* Any socket can have one of five states at any one time.
78 * The LISTENER state indicates a socket which is listening
79 * for connections. It cannot receive data itself, only incoming
81 * The CONNECTING state indicates an outbound socket which is
82 * waiting to be writeable.
83 * The WAIT_AUTH_1 state indicates the socket is outbound and
84 * has successfully connected, but has not yet sent and received
86 * The WAIT_AUTH_2 state indicates that the socket is inbound
87 * (allocated by a LISTENER) but has not yet sent and received
89 * The CONNECTED state represents a fully authorized, fully
92 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
94 /* We need to import these from the core for use in netbursts */
95 extern user_hash clientlist;
96 extern chan_hash chanlist;
98 /* Foward declarations */
102 /* This variable represents the root of the server tree
103 * (for all intents and purposes, it's us)
105 TreeServer *TreeRoot;
109 /* This hash_map holds the hash equivalent of the server
110 * tree, used for rapid linear lookups.
112 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
113 server_hash serverlist;
115 typedef nspace::hash_map<std::string, userrec*> uid_hash;
116 typedef nspace::hash_map<std::string, char*> sid_hash;
118 /* More forward declarations */
119 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
121 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
122 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms);
123 void ReadConfiguration(bool rebind);
125 /* Flatten links and /MAP for non-opers */
127 /* Hide U-Lined servers in /MAP and /LINKS */
130 /* Imported from xline.cpp for use during netburst */
131 extern std::vector<KLine> klines;
132 extern std::vector<GLine> glines;
133 extern std::vector<ZLine> zlines;
134 extern std::vector<QLine> qlines;
135 extern std::vector<ELine> elines;
136 extern std::vector<KLine> pklines;
137 extern std::vector<GLine> pglines;
138 extern std::vector<ZLine> pzlines;
139 extern std::vector<QLine> pqlines;
140 extern std::vector<ELine> pelines;
142 std::vector<std::string> ValidIPs;
144 class UserManager : public classbase
155 std::string UserToUID(userrec* user)
160 std::string UIDToUser(const std::string &UID)
165 std::string CreateAndAdd(userrec* user)
170 std::string CreateAndAdd(const std::string &servername)
175 std::string ServerToSID(const std::string &servername)
180 std::string SIDToServer(const std::string &SID)
185 userrec* FindByID(const std::string &UID)
192 /* Each server in the tree is represented by one class of
193 * type TreeServer. A locally connected TreeServer can
194 * have a class of type TreeSocket associated with it, for
195 * remote servers, the TreeSocket entry will be NULL.
196 * Each server also maintains a pointer to its parent
197 * (NULL if this server is ours, at the top of the tree)
198 * and a pointer to its "Route" (see the comments in the
199 * constructors below), and also a dynamic list of pointers
200 * to its children which can be iterated recursively
201 * if required. Creating or deleting objects of type
202 i* TreeServer automatically maintains the hash_map of
203 * TreeServer items, deleting and inserting them as they
204 * are created and destroyed.
207 class TreeServer : public classbase
209 TreeServer* Parent; /* Parent entry */
210 TreeServer* Route; /* Route entry */
211 std::vector<TreeServer*> Children; /* List of child objects */
212 irc::string ServerName; /* Server's name */
213 std::string ServerDesc; /* Server's description */
214 std::string VersionString; /* Version string or empty string */
215 int UserCount; /* Not used in this version */
216 int OperCount; /* Not used in this version */
217 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
218 time_t NextPing; /* After this time, the server should be PINGed*/
219 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
223 /* We don't use this constructor. Its a dummy, and won't cause any insertion
224 * of the TreeServer into the hash_map. See below for the two we DO use.
232 UserCount = OperCount = 0;
233 VersionString = Srv->GetVersion();
236 /* We use this constructor only to create the 'root' item, TreeRoot, which
237 * represents our own server. Therefore, it has no route, no parent, and
238 * no socket associated with it. Its version string is our own local version.
240 TreeServer(std::string Name, std::string Desc) : ServerName(Name.c_str()), ServerDesc(Desc)
244 UserCount = OperCount = 0;
245 VersionString = Srv->GetVersion();
247 Socket = NULL; /* Fix by brain */
251 /* When we create a new server, we call this constructor to initialize it.
252 * This constructor initializes the server's Route and Parent, and sets up
253 * its ping counters so that it will be pinged one minute from now.
255 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
258 UserCount = OperCount = 0;
259 this->SetNextPingTime(time(NULL) + 120);
262 /* find the 'route' for this server (e.g. the one directly connected
263 * to the local server, which we can use to reach it)
265 * In the following example, consider we have just added a TreeServer
266 * class for server G on our network, of which we are server A.
267 * To route traffic to G (marked with a *) we must send the data to
268 * B (marked with a +) so this algorithm initializes the 'Route'
269 * value to point at whichever server traffic must be routed through
270 * to get here. If we were to try this algorithm with server B,
271 * the Route pointer would point at its own object ('this').
281 * We only run this algorithm when a server is created, as
282 * the routes remain constant while ever the server exists, and
283 * do not need to be re-calculated.
287 if (Route == TreeRoot)
293 while (this->Route->GetParent() != TreeRoot)
295 this->Route = Route->GetParent();
299 /* Because recursive code is slow and takes a lot of resources,
300 * we store two representations of the server tree. The first
301 * is a recursive structure where each server references its
302 * children and its parent, which is used for netbursts and
303 * netsplits to dump the whole dataset to the other server,
304 * and the second is used for very fast lookups when routing
305 * messages and is instead a hash_map, where each item can
306 * be referenced by its server name. The AddHashEntry()
307 * call below automatically inserts each TreeServer class
308 * into the hash_map as it is created. There is a similar
309 * maintainance call in the destructor to tidy up deleted
313 this->AddHashEntry();
316 int QuitUsers(const std::string &reason)
318 log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
319 const char* reason_s = reason.c_str();
320 std::vector<userrec*> time_to_die;
321 for (user_hash::iterator n = clientlist.begin(); n != clientlist.end(); n++)
323 if (!strcmp(n->second->server, this->ServerName.c_str()))
325 time_to_die.push_back(n->second);
328 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
330 userrec* a = (userrec*)*n;
331 log(DEBUG,"Kill %s fd=%d",a->nick,a->fd);
333 kill_link(a,reason_s);
335 return time_to_die.size();
338 /* This method is used to add the structure to the
339 * hash_map for linear searches. It is only called
340 * by the constructors.
344 server_hash::iterator iter;
345 iter = serverlist.find(this->ServerName.c_str());
346 if (iter == serverlist.end())
347 serverlist[this->ServerName.c_str()] = this;
350 /* This method removes the reference to this object
351 * from the hash_map which is used for linear searches.
352 * It is only called by the default destructor.
356 server_hash::iterator iter;
357 iter = serverlist.find(this->ServerName.c_str());
358 if (iter != serverlist.end())
359 serverlist.erase(iter);
362 /* These accessors etc should be pretty self-
366 TreeServer* GetRoute()
371 std::string GetName()
373 return ServerName.c_str();
376 std::string GetDesc()
381 std::string GetVersion()
383 return VersionString;
386 void SetNextPingTime(time_t t)
389 LastPingWasGood = false;
392 time_t NextPingTime()
397 bool AnsweredLastPing()
399 return LastPingWasGood;
404 LastPingWasGood = true;
427 TreeSocket* GetSocket()
432 TreeServer* GetParent()
437 void SetVersion(std::string Version)
439 VersionString = Version;
442 unsigned int ChildCount()
444 return Children.size();
447 TreeServer* GetChild(unsigned int n)
449 if (n < Children.size())
451 /* Make sure they cant request
452 * an out-of-range object. After
453 * all we know what these programmer
454 * types are like *grin*.
464 void AddChild(TreeServer* Child)
466 Children.push_back(Child);
469 bool DelChild(TreeServer* Child)
471 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
482 /* Removes child nodes of this node, and of that node, etc etc.
483 * This is used during netsplits to automatically tidy up the
484 * server tree. It is slow, we don't use it for much else.
488 bool stillchildren = true;
489 while (stillchildren)
491 stillchildren = false;
492 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
494 TreeServer* s = (TreeServer*)*a;
498 stillchildren = true;
507 /* We'd better tidy up after ourselves, eh? */
508 this->DelHashEntry();
512 /* The Link class might as well be a struct,
513 * but this is C++ and we don't believe in structs (!).
514 * It holds the entire information of one <link>
515 * tag from the main config file. We maintain a list
516 * of them, and populate the list on rehash/load.
519 class Link : public classbase
525 std::string SendPass;
526 std::string RecvPass;
527 unsigned long AutoConnect;
528 time_t NextConnectTime;
529 std::string EncryptionKey;
530 bool HiddenFromStats;
533 /* The usual stuff for inspircd modules,
534 * plus the vector of Link classes which we
535 * use to store the <link> tags from the config
539 std::vector<Link> LinkBlocks;
541 /* Yay for fast searches!
542 * This is hundreds of times faster than recursion
543 * or even scanning a linked list, especially when
544 * there are more than a few servers to deal with.
547 TreeServer* FindServer(std::string ServerName)
549 server_hash::iterator iter;
550 iter = serverlist.find(ServerName.c_str());
551 if (iter != serverlist.end())
561 /* Returns the locally connected server we must route a
562 * message through to reach server 'ServerName'. This
563 * only applies to one-to-one and not one-to-many routing.
564 * See the comments for the constructor of TreeServer
567 TreeServer* BestRouteTo(std::string ServerName)
569 if (ServerName.c_str() == TreeRoot->GetName())
571 TreeServer* Found = FindServer(ServerName);
574 return Found->GetRoute();
582 /* Find the first server matching a given glob mask.
583 * Theres no find-using-glob method of hash_map [awwww :-(]
584 * so instead, we iterate over the list using an iterator
585 * and match each one until we get a hit. Yes its slow,
588 TreeServer* FindServerMask(std::string ServerName)
590 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
592 if (Srv->MatchText(i->first.c_str(),ServerName))
598 /* A convenient wrapper that returns true if a server exists */
599 bool IsServer(std::string ServerName)
601 return (FindServer(ServerName) != NULL);
605 class cmd_rconnect : public command_t
609 cmd_rconnect (Module* Callback) : command_t("RCONNECT", 'o', 2), Creator(Callback)
611 this->source = "m_spanningtree.so";
612 syntax = "<remote-server-mask> <servermask>";
615 void Handle (const char** parameters, int pcnt, userrec *user)
617 WriteServ(user->fd,"NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
618 /* Is this aimed at our server? */
619 if (Srv->MatchText(Srv->GetServerName(),parameters[0]))
621 /* Yes, initiate the given connect */
622 WriteOpers("*** Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
624 para[0] = parameters[1];
625 Creator->OnPreCommand("CONNECT", para, 1, user, true);
632 /* Every SERVER connection inbound or outbound is represented by
633 * an object of type TreeSocket.
634 * TreeSockets, being inherited from InspSocket, can be tied into
635 * the core socket engine, and we cn therefore receive activity events
636 * for them, just like activex objects on speed. (yes really, that
637 * is a technical term!) Each of these which relates to a locally
638 * connected server is assocated with it, by hooking it onto a
639 * TreeSocket class using its constructor. In this way, we can
640 * maintain a list of servers, some of which are directly connected,
641 * some of which are not.
644 class TreeSocket : public InspSocket
647 std::string in_buffer;
648 ServerState LinkState;
649 std::string InboundServerName;
650 std::string InboundDescription;
652 int num_lost_servers;
654 bool LastPingWasGood;
658 unsigned int keylength;
662 /* Because most of the I/O gubbins are encapsulated within
663 * InspSocket, we just call the superclass constructor for
664 * most of the action, and append a few of our own values
667 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
668 : InspSocket(host, port, listening, maxtime)
671 this->LinkState = LISTENER;
673 this->ctx_out = NULL;
676 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
677 : InspSocket(host, port, listening, maxtime)
680 this->LinkState = CONNECTING;
682 this->ctx_out = NULL;
685 /* When a listening socket gives us a new file descriptor,
686 * we must associate it with a socket without creating a new
687 * connection. This constructor is used for this purpose.
689 TreeSocket(int newfd, char* ip)
690 : InspSocket(newfd, ip)
692 this->LinkState = WAIT_AUTH_1;
694 this->ctx_out = NULL;
695 this->SendCapabilities();
706 void InitAES(std::string key,std::string SName)
713 log(DEBUG,"Initialized AES key %s",key.c_str());
714 // key must be 16, 24, 32 etc bytes (multiple of 8)
715 keylength = key.length();
716 if (!(keylength == 16 || keylength == 24 || keylength == 32))
718 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
719 log(DEBUG,"Key length not 16, 24 or 32 characters!");
723 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
724 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\
725 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
726 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\
727 \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);
731 /* When an outbound connection finishes connecting, we receive
732 * this event, and must send our SERVER string to the other
733 * side. If the other side is happy, as outlined in the server
734 * to server docs on the inspircd.org site, the other side
735 * will then send back its own server string.
737 virtual bool OnConnected()
739 if (this->LinkState == CONNECTING)
741 /* we do not need to change state here. */
742 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
744 if (x->Name == this->myhost)
746 Srv->SendOpers("*** Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
747 this->SendCapabilities();
748 if (x->EncryptionKey != "")
750 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
752 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
756 this->WriteLine("AES "+Srv->GetServerName());
757 this->InitAES(x->EncryptionKey,x->Name.c_str());
760 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
761 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
766 /* There is a (remote) chance that between the /CONNECT and the connection
767 * being accepted, some muppet has removed the <link> block and rehashed.
768 * If that happens the connection hangs here until it's closed. Unlikely
769 * and rather harmless.
771 Srv->SendOpers("*** Connection to \2"+myhost+"\2 lost link tag(!)");
775 virtual void OnError(InspSocketError e)
777 /* We don't handle this method, because all our
778 * dirty work is done in OnClose() (see below)
779 * which is still called on error conditions too.
781 if (e == I_ERR_CONNECT)
783 Srv->SendOpers("*** Connection failed: Connection refused");
787 virtual int OnDisconnect()
789 /* For the same reason as above, we don't
790 * handle OnDisconnect()
795 /* Recursively send the server tree with distances as hops.
796 * This is used during network burst to inform the other server
797 * (and any of ITS servers too) of what servers we know about.
798 * If at any point any of these servers already exist on the other
799 * end, our connection may be terminated. The hopcounts given
800 * by this function are relative, this doesn't matter so long as
801 * they are all >1, as all the remote servers re-calculate them
802 * to be relative too, with themselves as hop 0.
804 void SendServers(TreeServer* Current, TreeServer* s, int hops)
807 for (unsigned int q = 0; q < Current->ChildCount(); q++)
809 TreeServer* recursive_server = Current->GetChild(q);
810 if (recursive_server != s)
812 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
813 this->WriteLine(command);
814 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
815 /* down to next level */
816 this->SendServers(recursive_server, s, hops+1);
821 std::string MyCapabilities()
823 ServerConfig* Config = Srv->GetConfig();
824 std::vector<std::string> modlist;
825 std::string capabilities = "";
827 for (int i = 0; i <= MODCOUNT; i++)
829 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
830 modlist.push_back(Config->module_names[i]);
832 sort(modlist.begin(),modlist.end());
833 for (unsigned int i = 0; i < modlist.size(); i++)
836 capabilities = capabilities + ",";
837 capabilities = capabilities + modlist[i];
842 void SendCapabilities()
844 this->WriteLine("CAPAB "+MyCapabilities());
847 bool Capab(std::deque<std::string> params)
849 if (params.size() != 1)
851 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
855 if (params[0] != this->MyCapabilities())
857 std::string quitserver = this->myhost;
858 if (this->InboundServerName != "")
860 quitserver = this->InboundServerName;
863 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
864 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
865 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
866 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
867 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
874 /* This function forces this server to quit, removing this server
875 * and any users on it (and servers and users below that, etc etc).
876 * It's very slow and pretty clunky, but luckily unless your network
877 * is having a REAL bad hair day, this function shouldnt be called
878 * too many times a month ;-)
880 void SquitServer(std::string &from, TreeServer* Current)
882 /* recursively squit the servers attached to 'Current'.
883 * We're going backwards so we don't remove users
884 * while we still need them ;)
886 for (unsigned int q = 0; q < Current->ChildCount(); q++)
888 TreeServer* recursive_server = Current->GetChild(q);
889 this->SquitServer(from,recursive_server);
891 /* Now we've whacked the kids, whack self */
893 num_lost_users += Current->QuitUsers(from);
896 /* This is a wrapper function for SquitServer above, which
897 * does some validation first and passes on the SQUIT to all
898 * other remaining servers.
900 void Squit(TreeServer* Current,std::string reason)
902 if ((Current) && (Current != TreeRoot))
904 std::deque<std::string> params;
905 params.push_back(Current->GetName());
906 params.push_back(":"+reason);
907 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
908 if (Current->GetParent() == TreeRoot)
910 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
914 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
916 num_lost_servers = 0;
918 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
919 SquitServer(from, Current);
921 Current->GetParent()->DelChild(Current);
923 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
927 log(DEFAULT,"Squit from unknown server");
931 /* FMODE command - server mode with timestamp checks */
932 bool ForceMode(std::string source, std::deque<std::string> ¶ms)
934 /* Chances are this is a 1.0 FMODE without TS */
935 if (params.size() < 3)
937 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
942 std::string sourceserv;
944 /* Are we dealing with an FMODE from a user, or from a server? */
945 userrec* who = Srv->FindNick(source);
948 /* FMODE from a user, set sourceserv to the users server name */
949 sourceserv = who->server;
953 /* FMODE from a server, create a fake user to receive mode feedback */
955 who->fd = FD_MAGIC_NUMBER;
956 smode = true; /* Setting this flag tells us we should free the userrec later */
957 sourceserv = source; /* Set sourceserv to the actual source string */
959 const char* modelist[64];
962 memset(&modelist,0,sizeof(modelist));
963 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
967 /* The timestamp is in this position.
968 * We don't want to pass that up to the
969 * server->client protocol!
971 TS = atoi(params[q].c_str());
975 /* Everything else is fine to append to the modelist */
976 modelist[n++] = params[q].c_str();
980 /* Extract the TS value of the object, either userrec or chanrec */
981 userrec* dst = Srv->FindNick(params[0]);
982 chanrec* chan = NULL;
990 chan = Srv->FindChannel(params[0]);
997 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1002 log(DEBUG,"Entering TS equality check");
1003 ModeHandler* mh = NULL;
1004 unsigned long paramptr = 3;
1005 std::string to_bounce = "";
1006 std::string to_keep = "";
1007 std::vector<std::string> params_to_keep;
1008 std::string params_to_bounce = "";
1010 char cur_change = 1;
1011 char old_change = 0;
1012 char old_bounce_change = 0;
1013 /* Merge modes, basically do special stuff to mode with params */
1014 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1027 /* We only care about whats being set,
1028 * not whats being unset
1030 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1032 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1034 /* We only want to do special things to
1035 * modes with parameters, we are going to rewrite
1039 adding ? cur_change = '+' : cur_change = '-';
1041 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1043 /* The mode is set here, check which we should keep */
1046 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1048 if (which_to_keep == true)
1050 /* Keep ours, bounce theirs:
1051 * Send back ours to them and
1052 * drop their mode changs
1054 adding ? cur_change = '+' : cur_change = '-';
1055 if (cur_change != old_bounce_change)
1056 to_bounce += cur_change;
1058 old_bounce_change = cur_change;
1060 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1061 params_to_bounce.append(" ").append(ret.second);
1065 /* Keep theirs: Accept their mode change,
1068 adding ? cur_change = '+' : cur_change = '-';
1069 if (cur_change != old_change)
1070 to_keep += cur_change;
1072 old_change = cur_change;
1074 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1075 params_to_keep.push_back(params[paramptr]);
1080 /* Mode isnt set here, we want it */
1081 adding ? cur_change = '+' : cur_change = '-';
1082 if (cur_change != old_change)
1083 to_keep += cur_change;
1085 old_change = cur_change;
1087 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1088 params_to_keep.push_back(params[paramptr]);
1095 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1099 adding ? cur_change = '+' : cur_change = '-';
1101 /* Just keep this, safe to merge with no checks
1102 * it has no parameters
1105 if (cur_change != old_change)
1106 to_keep += cur_change;
1108 old_change = cur_change;
1110 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1112 log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1113 params_to_keep.push_back(params[paramptr++]);
1120 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1124 /* Taking a mode away */
1125 adding ? cur_change = '+' : cur_change = '-';
1127 if (cur_change != old_change)
1128 to_keep += cur_change;
1130 old_change = cur_change;
1132 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1133 params_to_keep.push_back(params[paramptr++]);
1140 if (to_bounce.length())
1142 std::deque<std::string> newparams;
1143 newparams.push_back(params[0]);
1144 newparams.push_back(ConvToStr(ourTS));
1145 newparams.push_back(to_bounce+params_to_bounce);
1146 DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1149 if (to_keep.length())
1153 modelist[0] = params[0].c_str();
1154 modelist[1] = to_keep.c_str();
1156 if (params_to_keep.size() > 2)
1158 for (q = 2; (q < params_to_keep.size()) && (q < 64); q++)
1160 log(DEBUG,"Item %d of %d", q, params_to_keep.size());
1161 modelist[n++] = params_to_keep[q].c_str();
1167 log(DEBUG,"Send mode");
1168 Srv->SendMode(modelist, n+2, who);
1172 log(DEBUG,"Send mode client");
1173 Srv->CallCommandHandler("MODE", modelist, n+2, who);
1176 /* HOT POTATO! PASS IT ON! */
1177 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1181 /* U-lined servers always win regardless of their TS */
1182 if ((TS > ourTS) && (!Srv->IsUlined(source)))
1184 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1185 * SHOULD accept it, if its clock is right.
1187 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1188 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1189 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1191 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1192 * writing the code. It took me a while to come up with this solution.
1194 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1197 std::deque<std::string> newparams; /* New parameter list we send back */
1198 newparams.push_back(params[0]); /* Target, user or channel */
1199 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1200 newparams.push_back(""); /* This contains the mode string. For now
1201 * it's empty, we fill it below.
1204 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1205 * set to avoid a desync here.
1207 std::string modebounce = "";
1210 ModeHandler* mh = NULL;
1211 char cur_change = 1;
1212 char old_change = 0;
1213 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1215 /* Iterate over all mode chars in the sent set */
1218 /* Adding or subtracting modes? */
1226 /* Find the mode handler for this mode */
1227 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1229 /* Got a mode handler?
1230 * This also prevents us bouncing modes we have no handler for.
1237 /* Does the mode require a parameter right now?
1238 * If it does, fetch it if we can
1240 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1243 /* Call the ModeSet method to determine if its set with the
1244 * given parameter here or not.
1246 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1248 /* XXX: Really. Dont ask.
1249 * Determine from if its set combined with what the current
1250 * 'state' is (adding or not) as to wether we should 'invert'
1251 * or 'reinforce' the mode change
1253 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1255 /* Quickly determine if we have 'flipped' from + to -,
1256 * or - to +, to prevent unneccessary +/- chars in the
1257 * output string that waste bandwidth
1259 if (cur_change != old_change)
1260 modebounce += cur_change;
1261 old_change = cur_change;
1263 /* Add the mode character to the output string */
1264 modebounce += mh->GetModeChar();
1266 /* We got a parameter back from ModeHandler::ModeSet,
1267 * are we supposed to be sending one out right now?
1269 if (ret.second.length())
1271 if (mh->GetNumParams(cur_change == '+') > 0)
1272 /* Yes we're supposed to be sending out
1273 * the parameter. Make sure it goes
1275 newparams.push_back(ret.second);
1283 /* Update the parameters for FMODE with the new 'bounced' string */
1284 newparams[2] = modebounce;
1285 /* Only send it back the way it came, no need to send it anywhere else */
1286 DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1287 log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1291 log(DEBUG,"Allow modes, TS lower for sender");
1292 /* The server was ulined, but something iffy is up with the TS.
1293 * Sound the alarm bells!
1295 if ((Srv->IsUlined(sourceserv)) && (TS > ourTS))
1297 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());
1299 /* Allow the mode, route it to either server or user command handling */
1301 Srv->SendMode(modelist,n,who);
1303 Srv->CallCommandHandler("MODE", modelist, n, who);
1305 /* HOT POTATO! PASS IT ON! */
1306 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1308 /* Are we supposed to free the userrec? */
1315 /* FTOPIC command */
1316 bool ForceTopic(std::string source, std::deque<std::string> ¶ms)
1318 if (params.size() != 4)
1320 time_t ts = atoi(params[1].c_str());
1321 std::string nsource = source;
1323 chanrec* c = Srv->FindChannel(params[0]);
1326 if ((ts >= c->topicset) || (!*c->topic))
1328 std::string oldtopic = c->topic;
1329 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1330 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1332 /* if the topic text is the same as the current topic,
1333 * dont bother to send the TOPIC command out, just silently
1334 * update the set time and set nick.
1336 if (oldtopic != params[3])
1338 userrec* user = Srv->FindNick(source);
1341 WriteChannelWithServ(source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
1345 WriteChannel(c, user, "TOPIC %s :%s", c->name, c->topic);
1346 nsource = user->server;
1348 /* all done, send it on its way */
1349 params[3] = ":" + params[3];
1350 DoOneToAllButSender(source,"FTOPIC",params,nsource);
1359 /* FJOIN, similar to unreal SJOIN */
1360 bool ForceJoin(std::string source, std::deque<std::string> ¶ms)
1362 if (params.size() < 3)
1366 char modestring[MAXBUF];
1367 char* mode_users[127];
1368 memset(&mode_users,0,sizeof(mode_users));
1369 mode_users[0] = first;
1370 mode_users[1] = modestring;
1371 strcpy(modestring,"+");
1372 unsigned int modectr = 2;
1374 userrec* who = NULL;
1375 std::string channel = params[0];
1376 time_t TS = atoi(params[1].c_str());
1379 chanrec* chan = Srv->FindChannel(channel);
1384 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1386 /* default is a high value, which if we dont have this
1387 * channel will let the other side apply their modes.
1389 time_t ourTS = time(NULL)+600;
1390 chanrec* us = Srv->FindChannel(channel);
1396 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1398 /* do this first, so our mode reversals are correctly received by other servers
1399 * if there is a TS collision.
1401 DoOneToAllButSender(source,"FJOIN",params,source);
1403 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
1405 /* process one channel at a time, applying modes. */
1406 char* usr = (char*)params[usernum].c_str();
1407 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1408 * (is this even possible?) */
1411 char permissions = *usr;
1412 switch (permissions)
1416 mode_users[modectr++] = usr;
1417 strlcat(modestring,"o",MAXBUF);
1421 mode_users[modectr++] = usr;
1422 strlcat(modestring,"h",MAXBUF);
1426 mode_users[modectr++] = usr;
1427 strlcat(modestring,"v",MAXBUF);
1430 who = Srv->FindNick(usr);
1433 Srv->JoinUserToChannel(who,channel,key);
1434 if (modectr >= (MAXMODES-1))
1436 /* theres a mode for this user. push them onto the mode queue, and flush it
1437 * if there are more than MAXMODES to go.
1439 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
1441 /* We also always let u-lined clients win, no matter what the TS value */
1442 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1443 Srv->SendMode((const char**)mode_users,modectr,who);
1446 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1453 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1454 /* bouncy bouncy! */
1455 std::deque<std::string> params;
1456 /* modes are now being UNSET... */
1457 *mode_users[1] = '-';
1458 for (unsigned int x = 0; x < modectr; x++)
1462 params.push_back(ConvToStr(us->age));
1464 params.push_back(mode_users[x]);
1467 // tell everyone to bounce the modes. bad modes, bad!
1468 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1470 strcpy(mode_users[1],"+");
1476 /* there werent enough modes built up to flush it during FJOIN,
1477 * or, there are a number left over. flush them out.
1479 if ((modectr > 2) && (who) && (us))
1483 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1484 Srv->SendMode((const char**)mode_users,modectr,who);
1487 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1494 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1495 std::deque<std::string> params;
1496 *mode_users[1] = '-';
1497 for (unsigned int x = 0; x < modectr; x++)
1501 params.push_back(ConvToStr(us->age));
1503 params.push_back(mode_users[x]);
1505 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1511 bool SyncChannelTS(std::string source, std::deque<std::string> ¶ms)
1513 if (params.size() >= 2)
1515 chanrec* c = Srv->FindChannel(params[0]);
1518 time_t theirTS = atoi(params[1].c_str());
1519 time_t ourTS = c->age;
1520 if (ourTS >= theirTS)
1522 log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1527 DoOneToAllButSender(Srv->GetServerName(),"SYNCTS",params,source);
1532 bool IntroduceClient(std::string source, std::deque<std::string> ¶ms)
1534 if (params.size() < 8)
1536 if (params.size() > 8)
1538 this->WriteLine(":"+Srv->GetServerName()+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1541 // NICK age nick host dhost ident +modes ip :gecos
1543 time_t age = atoi(params[0].c_str());
1545 /* This used to have a pretty craq'y loop doing the same thing,
1546 * now we just let the STL do the hard work (more efficiently)
1548 params[5] = params[5].substr(params[5].find_first_not_of('+'));
1550 const char* tempnick = params[1].c_str();
1551 log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1553 user_hash::iterator iter = clientlist.find(tempnick);
1555 if (iter != clientlist.end())
1558 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);
1559 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1563 clientlist[tempnick] = new userrec();
1564 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1565 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX-1);
1566 strlcpy(clientlist[tempnick]->host, params[2].c_str(),63);
1567 strlcpy(clientlist[tempnick]->dhost, params[3].c_str(),63);
1568 clientlist[tempnick]->server = FindServerNamePtr(source.c_str());
1569 strlcpy(clientlist[tempnick]->ident, params[4].c_str(),IDENTMAX);
1570 strlcpy(clientlist[tempnick]->fullname, params[7].c_str(),MAXGECOS);
1571 clientlist[tempnick]->registered = REG_ALL;
1572 clientlist[tempnick]->signon = age;
1574 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1576 clientlist[tempnick]->modes[(*v)-65] = 1;
1579 if (params[6].find_first_of(":") != std::string::npos)
1580 clientlist[tempnick]->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1582 clientlist[tempnick]->SetSockAddr(AF_INET, params[6].c_str(), 0);
1584 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host, clientlist[tempnick]->GetIPString());
1586 params[7] = ":" + params[7];
1587 DoOneToAllButSender(source,"NICK",params,source);
1589 // Increment the Source Servers User Count..
1590 TreeServer* SourceServer = FindServer(source);
1593 log(DEBUG,"Found source server of %s",clientlist[tempnick]->nick);
1594 SourceServer->AddUserCount();
1600 /* Send one or more FJOINs for a channel of users.
1601 * If the length of a single line is more than 480-NICKMAX
1602 * in length, it is split over multiple lines.
1604 void SendFJoins(TreeServer* Current, chanrec* c)
1606 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1608 std::string individual_halfops = ":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age);
1610 size_t dlen, curlen;
1611 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1613 char* ptr = list + dlen;
1615 CUList *ulist = c->GetUsers();
1616 std::vector<userrec*> specific_halfop;
1617 std::vector<userrec*> specific_voice;
1618 std::string modes = "";
1619 std::string params = "";
1621 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1623 int x = cflags(i->second,c);
1624 if ((x & UCMODE_HOP) && (x & UCMODE_OP))
1626 specific_halfop.push_back(i->second);
1628 if (((x & UCMODE_HOP) || (x & UCMODE_OP)) && (x & UCMODE_VOICE))
1630 specific_voice.push_back(i->second);
1638 else if (x & UCMODE_HOP)
1642 else if (x & UCMODE_VOICE)
1647 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s", n, i->second->nick);
1654 if (curlen > (480-NICKMAX))
1656 this->WriteLine(list);
1657 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1661 for (unsigned int y = 0; y < specific_voice.size(); y++)
1664 params.append(specific_voice[y]->nick).append(" ");
1665 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1667 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1670 params.append(specific_halfop[y]->nick).append(" ");
1671 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1677 this->WriteLine(list);
1678 for (unsigned int y = 0; y < specific_voice.size(); y++)
1681 params.append(specific_voice[y]->nick).append(" ");
1682 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1684 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1687 params.append(specific_halfop[y]->nick).append(" ");
1688 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1691 //std::string modes = "";
1692 //std::string params = "";
1693 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1696 params.append(b->data).append(" ");
1698 /* XXX: Send each channel mode and its params -- we'll need a method for this in ModeHandler? */
1699 //FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1700 this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+chanmodes(c,true)+modes+" "+params);
1703 /* Send G, Q, Z and E lines */
1704 void SendXLines(TreeServer* Current)
1707 std::string n = Srv->GetServerName();
1708 const char* sn = n.c_str();
1710 /* Yes, these arent too nice looking, but they get the job done */
1711 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++, iterations++)
1713 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);
1714 this->WriteLine(data);
1716 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++, iterations++)
1718 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);
1719 this->WriteLine(data);
1721 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++, iterations++)
1723 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);
1724 this->WriteLine(data);
1726 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++, iterations++)
1728 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);
1729 this->WriteLine(data);
1731 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++, iterations++)
1733 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);
1734 this->WriteLine(data);
1736 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++, iterations++)
1738 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);
1739 this->WriteLine(data);
1741 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++, iterations++)
1743 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);
1744 this->WriteLine(data);
1746 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++, iterations++)
1748 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);
1749 this->WriteLine(data);
1753 /* Send channel modes and topics */
1754 void SendChannelModes(TreeServer* Current)
1757 std::deque<std::string> list;
1759 std::string n = Srv->GetServerName();
1760 const char* sn = n.c_str();
1761 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++, iterations++)
1763 SendFJoins(Current, c->second);
1764 if (*c->second->topic)
1766 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1767 this->WriteLine(data);
1769 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1771 c->second->GetExtList(list);
1772 for (unsigned int j = 0; j < list.size(); j++)
1774 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1779 /* send all users and their oper state/modes */
1780 void SendUsers(TreeServer* Current)
1783 std::deque<std::string> list;
1785 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++, iterations++)
1787 if (u->second->registered == REG_ALL)
1789 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);
1790 this->WriteLine(data);
1791 if (*u->second->oper)
1793 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1795 if (*u->second->awaymsg)
1797 this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1799 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1801 u->second->GetExtList(list);
1802 for (unsigned int j = 0; j < list.size(); j++)
1804 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1810 /* This function is called when we want to send a netburst to a local
1811 * server. There is a set order we must do this, because for example
1812 * users require their servers to exist, and channels require their
1813 * users to exist. You get the idea.
1815 void DoBurst(TreeServer* s)
1817 /* The calls here to ServerInstance-> yield the processing
1818 * back to the core so that a large burst is split into at least 6 sections
1821 std::string burst = "BURST "+ConvToStr(time(NULL));
1822 std::string endburst = "ENDBURST";
1823 // Because by the end of the netburst, it could be gone!
1824 std::string name = s->GetName();
1825 Srv->SendOpers("*** Bursting to \2"+name+"\2.");
1826 this->WriteLine(burst);
1827 /* send our version string */
1828 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1829 /* Send server tree */
1830 this->SendServers(TreeRoot,s,1);
1831 /* Send users and their oper status */
1833 /* Send everything else (channel modes, xlines etc) */
1834 this->SendChannelModes(s);
1835 this->SendXLines(s);
1836 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1837 this->WriteLine(endburst);
1838 Srv->SendOpers("*** Finished bursting to \2"+name+"\2.");
1841 /* This function is called when we receive data from a remote
1842 * server. We buffer the data in a std::string (it doesnt stay
1843 * there for long), reading using InspSocket::Read() which can
1844 * read up to 16 kilobytes in one operation.
1846 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1847 * THE SOCKET OBJECT FOR US.
1849 virtual bool OnDataReady()
1851 char* data = this->Read();
1852 /* Check that the data read is a valid pointer and it has some content */
1855 this->in_buffer.append(data);
1856 /* While there is at least one new line in the buffer,
1857 * do something useful (we hope!) with it.
1859 while (in_buffer.find("\n") != std::string::npos)
1861 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1862 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1863 if (ret.find("\r") != std::string::npos)
1864 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1865 /* Process this one, abort if it
1866 * didnt return true.
1872 memset(result,0,1024);
1874 log(DEBUG,"Original string '%s'",ret.c_str());
1875 /* ERROR + CAPAB is still allowed unencryped */
1876 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1878 int nbytes = from64tobits(out, ret.c_str(), 1024);
1879 if ((nbytes > 0) && (nbytes < 1024))
1881 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1882 ctx_in->Decrypt(out, result, nbytes, 0);
1883 for (int t = 0; t < nbytes; t++)
1884 if (result[t] == '\7') result[t] = 0;
1889 if (!this->ProcessLine(ret))
1891 log(DEBUG,"ProcessLine says no!");
1897 /* EAGAIN returns an empty but non-NULL string, so this
1898 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1900 return (data && !*data);
1903 int WriteLine(std::string line)
1905 log(DEBUG,"OUT: %s",line.c_str());
1909 char result64[10240];
1910 if (this->keylength)
1912 // pad it to the key length
1913 int n = this->keylength - (line.length() % this->keylength);
1916 log(DEBUG,"Append %d chars to line to make it %d long from %d, key length %d",n,n+line.length(),line.length(),this->keylength);
1917 line.append(n,'\7');
1920 unsigned int ll = line.length();
1921 ctx_out->Encrypt(line.c_str(), result, ll, 0);
1922 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1924 //int from64tobits(char *out, const char *in, int maxlen);
1926 return this->Write(line + "\r\n");
1929 /* Handle ERROR command */
1930 bool Error(std::deque<std::string> ¶ms)
1932 if (params.size() < 1)
1934 WriteOpers("*** ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1935 /* we will return false to cause the socket to close. */
1939 bool Stats(std::string prefix, std::deque<std::string> ¶ms)
1941 /* Get the reply to a STATS query if it matches this servername,
1942 * and send it back as a load of PUSH queries
1944 if (params.size() > 1)
1946 if (Srv->MatchText(Srv->GetServerName(), params[1]))
1948 /* It's for our server */
1949 string_list results;
1950 userrec* source = Srv->FindNick(prefix);
1953 std::deque<std::string> par;
1954 par.push_back(prefix);
1956 DoStats(*(params[0].c_str()), source, results);
1957 for (size_t i = 0; i < results.size(); i++)
1959 par[1] = "::" + results[i];
1960 DoOneToOne(Srv->GetServerName(), "PUSH",par, source->server);
1967 userrec* source = Srv->FindNick(prefix);
1969 DoOneToOne(prefix, "STATS", params, params[1]);
1976 /* Because the core won't let users or even SERVERS set +o,
1977 * we use the OPERTYPE command to do this.
1979 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1981 if (params.size() != 1)
1983 log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
1986 std::string opertype = params[0];
1987 userrec* u = Srv->FindNick(prefix);
1990 u->modes[UM_OPERATOR] = 1;
1991 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1992 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1997 /* Because Andy insists that services-compatible servers must
1998 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2000 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
2002 if (params.size() < 3)
2005 userrec* u = Srv->FindNick(params[0]);
2009 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2012 std::deque<std::string> par;
2013 par.push_back(params[1]);
2014 /* This is not required as one is sent in OnUserPostNick below
2016 //DoOneToMany(u->nick,"NICK",par);
2017 Srv->ChangeUserNick(u,params[1]);
2018 u->age = atoi(params[2].c_str());
2024 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
2026 if (params.size() < 2)
2029 userrec* u = Srv->FindNick(params[0]);
2033 Srv->JoinUserToChannel(u,params[1],"");
2034 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2039 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
2041 if (params.size() < 1)
2044 std::string servermask = params[0];
2046 if (Srv->MatchText(Srv->GetServerName(),servermask))
2048 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
2049 Srv->RehashServer();
2050 ReadConfiguration(false);
2052 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2056 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
2058 if (params.size() != 2)
2061 std::string nick = params[0];
2062 userrec* u = Srv->FindNick(prefix);
2063 userrec* who = Srv->FindNick(nick);
2067 /* Prepend kill source, if we don't have one */
2068 std::string sourceserv = prefix;
2071 sourceserv = u->server;
2073 if (*(params[1].c_str()) != '[')
2075 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2077 std::string reason = params[1];
2078 params[1] = ":" + params[1];
2079 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2080 ::Write(who->fd, ":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2081 Srv->QuitUser(who,reason);
2086 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
2088 if (params.size() < 1)
2091 if (params.size() == 1)
2093 TreeServer* ServerSource = FindServer(prefix);
2096 ServerSource->SetPingFlag();
2101 std::string forwardto = params[1];
2102 if (forwardto == Srv->GetServerName())
2105 * this is a PONG for us
2106 * if the prefix is a user, check theyre local, and if they are,
2107 * dump the PONG reply back to their fd. If its a server, do nowt.
2108 * Services might want to send these s->s, but we dont need to yet.
2110 userrec* u = Srv->FindNick(prefix);
2114 WriteServ(u->fd,"PONG %s %s",params[0].c_str(),params[1].c_str());
2119 // not for us, pass it on :)
2120 DoOneToOne(prefix,"PONG",params,forwardto);
2127 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
2129 if (params.size() < 3)
2132 TreeServer* ServerSource = FindServer(prefix);
2136 if (params[0] == "*")
2138 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2140 else if (*(params[0].c_str()) == '#')
2142 chanrec* c = Srv->FindChannel(params[0]);
2145 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2148 else if (*(params[0].c_str()) != '#')
2150 userrec* u = Srv->FindNick(params[0]);
2153 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2158 params[2] = ":" + params[2];
2159 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2163 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
2165 if (params.size() < 1)
2168 TreeServer* ServerSource = FindServer(prefix);
2172 ServerSource->SetVersion(params[0]);
2174 params[0] = ":" + params[0];
2175 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2179 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
2181 if (params.size() < 1)
2184 userrec* u = Srv->FindNick(prefix);
2188 Srv->ChangeHost(u,params[0]);
2189 DoOneToAllButSender(prefix,"FHOST",params,u->server);
2194 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
2196 if (params.size() < 6)
2199 bool propogate = false;
2201 switch (*(params[0].c_str()))
2204 propogate = add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2205 zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2208 propogate = add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2209 qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2212 propogate = add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2213 eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2216 propogate = add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2217 gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2220 propogate = add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2223 /* Just in case... */
2224 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2229 /* Send it on its way */
2232 if (atoi(params[4].c_str()))
2234 WriteOpers("*** %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());
2238 WriteOpers("*** %s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2240 params[5] = ":" + params[5];
2241 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2243 if (!this->bursting)
2245 log(DEBUG,"Applying lines...");
2246 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2251 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
2253 if (params.size() < 1)
2256 userrec* u = Srv->FindNick(prefix);
2260 Srv->ChangeGECOS(u,params[0]);
2261 params[0] = ":" + params[0];
2262 DoOneToAllButSender(prefix,"FNAME",params,u->server);
2267 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
2269 if (params.size() < 1)
2272 log(DEBUG,"In IDLE command");
2273 userrec* u = Srv->FindNick(prefix);
2277 log(DEBUG,"USER EXISTS: %s",u->nick);
2278 // an incoming request
2279 if (params.size() == 1)
2281 userrec* x = Srv->FindNick(params[0]);
2282 if ((x) && (IS_LOCAL(x)))
2284 userrec* x = Srv->FindNick(params[0]);
2285 log(DEBUG,"Got IDLE");
2286 char signon[MAXBUF];
2288 log(DEBUG,"Sending back IDLE 3");
2289 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2290 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2291 std::deque<std::string> par;
2292 par.push_back(prefix);
2293 par.push_back(signon);
2294 par.push_back(idle);
2295 // ours, we're done, pass it BACK
2296 DoOneToOne(params[0],"IDLE",par,u->server);
2300 // not ours pass it on
2301 DoOneToOne(prefix,"IDLE",params,x->server);
2304 else if (params.size() == 3)
2306 std::string who_did_the_whois = params[0];
2307 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
2308 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2310 log(DEBUG,"Got final IDLE");
2311 // an incoming reply to a whois we sent out
2312 std::string nick_whoised = prefix;
2313 unsigned long signon = atoi(params[1].c_str());
2314 unsigned long idle = atoi(params[2].c_str());
2315 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2316 do_whois(who_to_send_to,u,signon,idle,nick_whoised.c_str());
2320 // not ours, pass it on
2321 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2328 bool Push(std::string prefix, std::deque<std::string> ¶ms)
2330 if (params.size() < 2)
2333 userrec* u = Srv->FindNick(params[0]);
2340 ::Write(u->fd,"%s",params[1].c_str());
2344 // continue the raw onwards
2345 params[1] = ":" + params[1];
2346 DoOneToOne(prefix,"PUSH",params,u->server);
2351 bool Time(std::string prefix, std::deque<std::string> ¶ms)
2353 // :source.server TIME remote.server sendernick
2354 // :remote.server TIME source.server sendernick TS
2355 if (params.size() == 2)
2357 // someone querying our time?
2358 if (Srv->GetServerName() == params[0])
2360 userrec* u = Srv->FindNick(params[1]);
2364 snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2365 params.push_back(curtime);
2367 DoOneToOne(Srv->GetServerName(),"TIME",params,params[0]);
2372 // not us, pass it on
2373 userrec* u = Srv->FindNick(params[1]);
2375 DoOneToOne(prefix,"TIME",params,params[0]);
2378 else if (params.size() == 3)
2380 // a response to a previous TIME
2381 userrec* u = Srv->FindNick(params[1]);
2382 if ((u) && (IS_LOCAL(u)))
2384 time_t rawtime = atol(params[2].c_str());
2385 struct tm * timeinfo;
2386 timeinfo = localtime(&rawtime);
2388 snprintf(tms,26,"%s",asctime(timeinfo));
2390 WriteServ(u->fd,"391 %s %s :%s",u->nick,prefix.c_str(),tms);
2395 DoOneToOne(prefix,"TIME",params,u->server);
2401 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
2403 if (params.size() < 1)
2406 if (params.size() == 1)
2408 std::string stufftobounce = params[0];
2409 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
2414 std::string forwardto = params[1];
2415 if (forwardto == Srv->GetServerName())
2417 // this is a ping for us, send back PONG to the requesting server
2418 params[1] = params[0];
2419 params[0] = forwardto;
2420 DoOneToOne(forwardto,"PONG",params,params[1]);
2424 // not for us, pass it on :)
2425 DoOneToOne(prefix,"PING",params,forwardto);
2431 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
2433 if (params.size() < 4)
2436 std::string servername = params[0];
2437 std::string password = params[1];
2438 // hopcount is not used for a remote server, we calculate this ourselves
2439 std::string description = params[3];
2440 TreeServer* ParentOfThis = FindServer(prefix);
2444 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2447 TreeServer* CheckDupe = FindServer(servername);
2450 this->WriteLine("ERROR :Server "+servername+" already exists!");
2451 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists");
2454 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
2455 ParentOfThis->AddChild(Node);
2456 params[3] = ":" + params[3];
2457 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2458 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2462 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2464 if (params.size() < 4)
2467 irc::string servername = params[0].c_str();
2468 std::string sname = params[0];
2469 std::string password = params[1];
2470 int hops = atoi(params[2].c_str());
2474 this->WriteLine("ERROR :Server too far away for authentication");
2475 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2478 std::string description = params[3];
2479 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2481 if ((x->Name == servername) && (x->RecvPass == password))
2483 TreeServer* CheckDupe = FindServer(sname);
2486 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2487 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2490 // Begin the sync here. this kickstarts the
2491 // other side, waiting in WAIT_AUTH_2 state,
2492 // into starting their burst, as it shows
2493 // that we're happy.
2494 this->LinkState = CONNECTED;
2495 // we should add the details of this server now
2496 // to the servers tree, as a child of the root
2498 TreeServer* Node = new TreeServer(sname,description,TreeRoot,this);
2499 TreeRoot->AddChild(Node);
2500 params[3] = ":" + params[3];
2501 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2502 this->bursting = true;
2503 this->DoBurst(Node);
2507 this->WriteLine("ERROR :Invalid credentials");
2508 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2512 bool Inbound_Server(std::deque<std::string> ¶ms)
2514 if (params.size() < 4)
2517 irc::string servername = params[0].c_str();
2518 std::string sname = params[0];
2519 std::string password = params[1];
2520 int hops = atoi(params[2].c_str());
2524 this->WriteLine("ERROR :Server too far away for authentication");
2525 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2528 std::string description = params[3];
2529 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2531 if ((x->Name == servername) && (x->RecvPass == password))
2533 TreeServer* CheckDupe = FindServer(sname);
2536 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2537 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2540 /* If the config says this link is encrypted, but the remote side
2541 * hasnt bothered to send the AES command before SERVER, then we
2542 * boot them off as we MUST have this connection encrypted.
2544 if ((x->EncryptionKey != "") && (!this->ctx_in))
2546 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2547 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2550 Srv->SendOpers("*** Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2551 this->InboundServerName = sname;
2552 this->InboundDescription = description;
2553 // this is good. Send our details: Our server name and description and hopcount of 0,
2554 // along with the sendpass from this block.
2555 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
2556 // move to the next state, we are now waiting for THEM.
2557 this->LinkState = WAIT_AUTH_2;
2561 this->WriteLine("ERROR :Invalid credentials");
2562 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2566 void Split(std::string line, std::deque<std::string> &n)
2569 irc::tokenstream tokens(line);
2571 while ((param = tokens.GetToken()) != "")
2576 bool ProcessLine(std::string line)
2578 std::deque<std::string> params;
2579 irc::string command;
2585 line = line.substr(0, line.find_first_of("\r\n"));
2587 log(DEBUG,"IN: %s", line.c_str());
2589 this->Split(line.c_str(),params);
2591 if ((params[0][0] == ':') && (params.size() > 1))
2593 prefix = params[0].substr(1);
2597 command = params[0].c_str();
2600 if ((!this->ctx_in) && (command == "AES"))
2602 std::string sserv = params[0];
2603 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2605 if ((x->EncryptionKey != "") && (x->Name == sserv))
2607 this->InitAES(x->EncryptionKey,sserv);
2613 else if ((this->ctx_in) && (command == "AES"))
2615 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2618 switch (this->LinkState)
2623 // Waiting for SERVER command from remote server. Server initiating
2624 // the connection sends the first SERVER command, listening server
2625 // replies with theirs if its happy, then if the initiator is happy,
2626 // it starts to send its net sync, which starts the merge, otherwise
2627 // it sends an ERROR.
2628 if (command == "PASS")
2630 /* Silently ignored */
2632 else if (command == "SERVER")
2634 return this->Inbound_Server(params);
2636 else if (command == "ERROR")
2638 return this->Error(params);
2640 else if (command == "USER")
2642 this->WriteLine("ERROR :Client connections to this port are prohibited.");
2645 else if (command == "CAPAB")
2647 return this->Capab(params);
2649 else if ((command == "U") || (command == "S"))
2651 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2656 this->WriteLine("ERROR :Invalid command in negotiation phase.");
2661 // Waiting for start of other side's netmerge to say they liked our
2663 if (command == "SERVER")
2665 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2669 else if ((command == "U") || (command == "S"))
2671 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2674 else if (command == "BURST")
2678 /* If a time stamp is provided, try and check syncronization */
2679 time_t THEM = atoi(params[0].c_str());
2680 long delta = THEM-time(NULL);
2681 if ((delta < -600) || (delta > 600))
2683 WriteOpers("*** \2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
2684 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2687 else if ((delta < -60) || (delta > 60))
2689 WriteOpers("*** \2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2692 this->LinkState = CONNECTED;
2693 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
2694 TreeRoot->AddChild(Node);
2696 params.push_back(InboundServerName);
2697 params.push_back("*");
2698 params.push_back("1");
2699 params.push_back(":"+InboundDescription);
2700 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2701 this->bursting = true;
2702 this->DoBurst(Node);
2704 else if (command == "ERROR")
2706 return this->Error(params);
2708 else if (command == "CAPAB")
2710 return this->Capab(params);
2715 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2719 if (command == "SERVER")
2721 // another server we connected to, which was in WAIT_AUTH_1 state,
2722 // has just sent us their credentials. If we get this far, theyre
2723 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2724 // if we're happy with this, we should send our netburst which
2725 // kickstarts the merge.
2726 return this->Outbound_Reply_Server(params);
2728 else if (command == "ERROR")
2730 return this->Error(params);
2734 // This is the 'authenticated' state, when all passwords
2735 // have been exchanged and anything past this point is taken
2740 std::string direction = prefix;
2741 userrec* t = Srv->FindNick(prefix);
2744 direction = t->server;
2746 TreeServer* route_back_again = BestRouteTo(direction);
2747 if ((!route_back_again) || (route_back_again->GetSocket() != this))
2749 if (route_back_again)
2750 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2755 * When there is activity on the socket, reset the ping counter so
2756 * that we're not wasting bandwidth pinging an active server.
2758 route_back_again->SetNextPingTime(time(NULL) + 120);
2759 route_back_again->SetPingFlag();
2762 if (command == "SVSMODE")
2764 /* Services expects us to implement
2765 * SVSMODE. In inspircd its the same as
2770 std::string target = "";
2771 /* Yes, know, this is a mess. Its reasonably fast though as we're
2772 * working with std::string here.
2774 if ((command == "NICK") && (params.size() > 1))
2776 return this->IntroduceClient(prefix,params);
2778 else if (command == "FJOIN")
2780 return this->ForceJoin(prefix,params);
2782 else if (command == "STATS")
2784 return this->Stats(prefix, params);
2786 else if (command == "SERVER")
2788 return this->RemoteServer(prefix,params);
2790 else if (command == "ERROR")
2792 return this->Error(params);
2794 else if (command == "OPERTYPE")
2796 return this->OperType(prefix,params);
2798 else if (command == "FMODE")
2800 return this->ForceMode(prefix,params);
2802 else if (command == "KILL")
2804 return this->RemoteKill(prefix,params);
2806 else if (command == "FTOPIC")
2808 return this->ForceTopic(prefix,params);
2810 else if (command == "REHASH")
2812 return this->RemoteRehash(prefix,params);
2814 else if (command == "METADATA")
2816 return this->MetaData(prefix,params);
2818 else if (command == "PING")
2821 * We just got a ping from a server that's bursting.
2822 * This can't be right, so set them to not bursting, and
2823 * apply their lines.
2827 this->bursting = false;
2828 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2832 prefix = this->GetName();
2834 return this->LocalPing(prefix,params);
2836 else if (command == "PONG")
2839 * We just got a pong from a server that's bursting.
2840 * This can't be right, so set them to not bursting, and
2841 * apply their lines.
2845 this->bursting = false;
2846 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2850 prefix = this->GetName();
2852 return this->LocalPong(prefix,params);
2854 else if (command == "VERSION")
2856 return this->ServerVersion(prefix,params);
2858 else if (command == "FHOST")
2860 return this->ChangeHost(prefix,params);
2862 else if (command == "FNAME")
2864 return this->ChangeName(prefix,params);
2866 else if (command == "ADDLINE")
2868 return this->AddLine(prefix,params);
2870 else if (command == "SVSNICK")
2874 prefix = this->GetName();
2876 return this->ForceNick(prefix,params);
2878 else if (command == "IDLE")
2880 return this->Whois(prefix,params);
2882 else if (command == "PUSH")
2884 return this->Push(prefix,params);
2886 else if (command == "TIME")
2888 return this->Time(prefix,params);
2890 else if ((command == "KICK") && (IsServer(prefix)))
2892 std::string sourceserv = this->myhost;
2893 if (params.size() == 3)
2895 userrec* user = Srv->FindNick(params[1]);
2896 chanrec* chan = Srv->FindChannel(params[0]);
2899 server_kick_channel(user,chan,(char*)params[2].c_str(),false);
2902 if (this->InboundServerName != "")
2904 sourceserv = this->InboundServerName;
2906 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2908 else if (command == "SVSJOIN")
2912 prefix = this->GetName();
2914 return this->ServiceJoin(prefix,params);
2916 else if (command == "SQUIT")
2918 if (params.size() == 2)
2920 this->Squit(FindServer(params[0]),params[1]);
2924 else if (command == "ENDBURST")
2926 this->bursting = false;
2927 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2928 std::string sourceserv = this->myhost;
2929 if (this->InboundServerName != "")
2931 sourceserv = this->InboundServerName;
2933 WriteOpers("*** Received end of netburst from \2%s\2",sourceserv.c_str());
2938 // not a special inter-server command.
2939 // Emulate the actual user doing the command,
2940 // this saves us having a huge ugly parser.
2941 userrec* who = Srv->FindNick(prefix);
2942 std::string sourceserv = this->myhost;
2943 if (this->InboundServerName != "")
2945 sourceserv = this->InboundServerName;
2949 if ((command == "NICK") && (params.size() > 0))
2951 /* On nick messages, check that the nick doesnt
2952 * already exist here. If it does, kill their copy,
2955 userrec* x = Srv->FindNick(params[0]);
2956 if ((x) && (x != who))
2958 std::deque<std::string> p;
2959 p.push_back(params[0]);
2960 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2961 DoOneToMany(Srv->GetServerName(),"KILL",p);
2963 p.push_back(prefix);
2964 p.push_back("Nickname collision");
2965 DoOneToMany(Srv->GetServerName(),"KILL",p);
2966 Srv->QuitUser(x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2967 userrec* y = Srv->FindNick(prefix);
2970 Srv->QuitUser(y,"Nickname collision");
2972 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2976 target = who->server;
2977 const char* strparams[127];
2978 for (unsigned int q = 0; q < params.size(); q++)
2980 strparams[q] = params[q].c_str();
2982 if (!Srv->CallCommandHandler(command.c_str(), strparams, params.size(), who))
2984 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
2990 // its not a user. Its either a server, or somethings screwed up.
2991 if (IsServer(prefix))
2993 target = Srv->GetServerName();
2997 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3001 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3010 virtual std::string GetName()
3012 std::string sourceserv = this->myhost;
3013 if (this->InboundServerName != "")
3015 sourceserv = this->InboundServerName;
3020 virtual void OnTimeout()
3022 if (this->LinkState == CONNECTING)
3024 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
3028 virtual void OnClose()
3030 // Connection closed.
3031 // If the connection is fully up (state CONNECTED)
3032 // then propogate a netsplit to all peers.
3033 std::string quitserver = this->myhost;
3034 if (this->InboundServerName != "")
3036 quitserver = this->InboundServerName;
3038 TreeServer* s = FindServer(quitserver);
3041 Squit(s,"Remote host closed the connection");
3043 WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
3046 virtual int OnIncomingConnection(int newsock, char* ip)
3048 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3049 * or discovering if this port is the server port, we don't allow connections from any
3050 * IPs for which we don't have a link block.
3054 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3057 for (vector<std::string>::iterator i = ValidIPs.begin(); i != ValidIPs.end(); i++)
3058 if (MatchCIDR(ip, (*i).c_str()))
3063 WriteOpers("Server connection from %s denied (no link blocks with that IP address)", ip);
3068 TreeSocket* s = new TreeSocket(newsock, ip);
3074 /** This class is used to resolve server hostnames during /connect and autoconnect.
3075 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3076 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3077 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3078 * will have an IP address which we can then use to continue our connection.
3080 class ServernameResolver : public Resolver
3083 /** A copy of the Link tag info for what we're connecting to.
3084 * We take a copy, rather than using a pointer, just in case the
3085 * admin takes the tag away and rehashes while the domain is resolving.
3089 ServernameResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3091 /* Nothing in here, folks */
3094 void OnLookupComplete(const std::string &result)
3096 /* Initiate the connection, now that we have an IP to use.
3097 * Passing a hostname directly to InspSocket causes it to
3098 * just bail and set its FD to -1.
3100 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3101 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3103 TreeSocket* newsocket = new TreeSocket(result,MyLink.Port,false,10,MyLink.Name.c_str());
3104 if (newsocket->GetFd() > -1)
3107 Srv->AddSocket(newsocket);
3111 /* Something barfed, show the opers */
3112 WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3118 void OnError(ResolverError e, const std::string &errormessage)
3121 WriteOpers("*** CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3125 class SecurityIPResolver : public Resolver
3130 SecurityIPResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3134 void OnLookupComplete(const std::string &result)
3136 log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3137 ValidIPs.push_back(result);
3140 void OnError(ResolverError e, const std::string &errormessage)
3142 log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3146 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3148 for (unsigned int c = 0; c < list.size(); c++)
3150 if (list[c] == server)
3155 list.push_back(server);
3158 // returns a list of DIRECT servernames for a specific channel
3159 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3161 CUList *ulist = c->GetUsers();
3162 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3164 if (i->second->fd < 0)
3166 TreeServer* best = BestRouteTo(i->second->server);
3168 AddThisServer(best,list);
3174 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms)
3176 TreeServer* omitroute = BestRouteTo(omit);
3177 if ((command == "NOTICE") || (command == "PRIVMSG"))
3179 if (params.size() >= 2)
3182 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3184 params[0] = params[0].substr(1, params[0].length()-1);
3186 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3188 // special routing for private messages/notices
3189 userrec* d = Srv->FindNick(params[0]);
3192 std::deque<std::string> par;
3193 par.push_back(params[0]);
3194 par.push_back(":"+params[1]);
3195 DoOneToOne(prefix,command.c_str(),par,d->server);
3199 else if (*(params[0].c_str()) == '$')
3201 std::deque<std::string> par;
3202 par.push_back(params[0]);
3203 par.push_back(":"+params[1]);
3204 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3209 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3210 chanrec* c = Srv->FindChannel(params[0]);
3213 std::deque<TreeServer*> list;
3214 GetListOfServersForChannel(c,list);
3215 log(DEBUG,"Got a list of %d servers",list.size());
3216 unsigned int lsize = list.size();
3217 for (unsigned int i = 0; i < lsize; i++)
3219 TreeSocket* Sock = list[i]->GetSocket();
3220 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3222 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3223 Sock->WriteLine(data);
3231 unsigned int items = TreeRoot->ChildCount();
3232 for (unsigned int x = 0; x < items; x++)
3234 TreeServer* Route = TreeRoot->GetChild(x);
3235 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3237 TreeSocket* Sock = Route->GetSocket();
3238 Sock->WriteLine(data);
3244 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
3246 TreeServer* omitroute = BestRouteTo(omit);
3247 std::string FullLine = ":" + prefix + " " + command;
3248 unsigned int words = params.size();
3249 for (unsigned int x = 0; x < words; x++)
3251 FullLine = FullLine + " " + params[x];
3253 unsigned int items = TreeRoot->ChildCount();
3254 for (unsigned int x = 0; x < items; x++)
3256 TreeServer* Route = TreeRoot->GetChild(x);
3257 // Send the line IF:
3258 // The route has a socket (its a direct connection)
3259 // The route isnt the one to be omitted
3260 // The route isnt the path to the one to be omitted
3261 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3263 TreeSocket* Sock = Route->GetSocket();
3264 Sock->WriteLine(FullLine);
3270 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
3272 std::string FullLine = ":" + prefix + " " + command;
3273 unsigned int words = params.size();
3274 for (unsigned int x = 0; x < words; x++)
3276 FullLine = FullLine + " " + params[x];
3278 unsigned int items = TreeRoot->ChildCount();
3279 for (unsigned int x = 0; x < items; x++)
3281 TreeServer* Route = TreeRoot->GetChild(x);
3282 if (Route->GetSocket())
3284 TreeSocket* Sock = Route->GetSocket();
3285 Sock->WriteLine(FullLine);
3291 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
3293 TreeServer* Route = BestRouteTo(target);
3296 std::string FullLine = ":" + prefix + " " + command;
3297 unsigned int words = params.size();
3298 for (unsigned int x = 0; x < words; x++)
3300 FullLine = FullLine + " " + params[x];
3302 if (Route->GetSocket())
3304 TreeSocket* Sock = Route->GetSocket();
3305 Sock->WriteLine(FullLine);
3315 std::vector<TreeSocket*> Bindings;
3317 void ReadConfiguration(bool rebind)
3319 Conf = new ConfigReader;
3322 for (int j =0; j < Conf->Enumerate("bind"); j++)
3324 std::string Type = Conf->ReadValue("bind","type",j);
3325 std::string IP = Conf->ReadValue("bind","address",j);
3326 long Port = Conf->ReadInteger("bind","port",j,true);
3327 if (Type == "servers")
3333 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
3334 if (listener->GetState() == I_LISTENING)
3336 Srv->AddSocket(listener);
3337 Bindings.push_back(listener);
3341 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3348 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3349 HideULines = Conf->ReadFlag("options","hideulines",0);
3352 for (int j =0; j < Conf->Enumerate("link"); j++)
3355 std::string Allow = Conf->ReadValue("link","allowmask",j);
3356 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3357 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3358 L.Port = Conf->ReadInteger("link","port",j,true);
3359 L.SendPass = Conf->ReadValue("link","sendpass",j);
3360 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3361 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3362 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
3363 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3364 L.NextConnectTime = time(NULL) + L.AutoConnect;
3365 /* Bugfix by brain, do not allow people to enter bad configurations */
3366 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3368 ValidIPs.push_back(L.IPAddr);
3371 ValidIPs.push_back(Allow);
3373 /* Needs resolving */
3375 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3379 SecurityIPResolver* sr = new SecurityIPResolver(L.IPAddr, L);
3380 Srv->AddResolver(sr);
3382 catch (ModuleException& e)
3384 log(DEBUG,"Error in resolver: %s",e.GetReason());
3388 LinkBlocks.push_back(L);
3389 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3395 log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3397 else if (L.RecvPass == "")
3399 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3401 else if (L.SendPass == "")
3403 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3405 else if (L.Name == "")
3407 log(DEFAULT,"Invalid configuration, link tag without a name!");
3411 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3419 class ModuleSpanningTree : public Module
3421 std::vector<TreeSocket*> Bindings;
3424 unsigned int max_local;
3425 unsigned int max_global;
3426 cmd_rconnect* command_rconnect;
3430 ModuleSpanningTree(Server* Me)
3431 : Module::Module(Me), max_local(0), max_global(0)
3436 // Create the root of the tree
3437 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
3439 ReadConfiguration(true);
3441 command_rconnect = new cmd_rconnect(this);
3442 Srv->AddCommand(command_rconnect);
3445 void ShowLinks(TreeServer* Current, userrec* user, int hops)
3447 std::string Parent = TreeRoot->GetName();
3448 if (Current->GetParent())
3450 Parent = Current->GetParent()->GetName();
3452 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3454 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3458 ShowLinks(Current->GetChild(q),user,hops+1);
3463 ShowLinks(Current->GetChild(q),user,hops+1);
3466 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3467 if ((HideULines) && (Srv->IsUlined(Current->GetName())) && (!*user->oper))
3469 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(FlatLinks && (!*user->oper)) ? Srv->GetServerName().c_str() : Parent.c_str(),(FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3472 int CountLocalServs()
3474 return TreeRoot->ChildCount();
3479 return serverlist.size();
3482 void HandleLinks(const char** parameters, int pcnt, userrec* user)
3484 ShowLinks(TreeRoot,user,0);
3485 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
3489 void HandleLusers(const char** parameters, int pcnt, userrec* user)
3491 unsigned int n_users = usercnt();
3493 /* Only update these when someone wants to see them, more efficient */
3494 if ((unsigned int)local_count() > max_local)
3495 max_local = local_count();
3496 if (n_users > max_global)
3497 max_global = n_users;
3499 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-usercount_invisible(),usercount_invisible(),this->CountServs());
3500 if (usercount_opers())
3501 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3502 if (usercount_unknown())
3503 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3505 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3506 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
3507 WriteServ(user->fd,"265 %s :Current Local Users: %d Max: %d",user->nick,local_count(),max_local);
3508 WriteServ(user->fd,"266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
3512 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3514 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3518 for (int t = 0; t < depth; t++)
3520 matrix[line][t] = ' ';
3523 // For Aligning, we need to work out exactly how deep this thing is, and produce
3524 // a 'Spacer' String to compensate.
3527 memset(spacer,' ',40);
3528 if ((40 - Current->GetName().length() - depth) > 1) {
3529 spacer[40 - Current->GetName().length() - depth] = '\0';
3538 if (clientlist.size() == 0) {
3539 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3544 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
3546 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3547 totusers += Current->GetUserCount();
3549 strlcpy(&matrix[line][depth],text,80);
3551 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3553 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3557 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3562 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3568 int HandleStats(const char** parameters, int pcnt, userrec* user)
3572 /* Remote STATS, the server is within the 2nd parameter */
3573 std::deque<std::string> params;
3574 params.push_back(parameters[0]);
3575 params.push_back(parameters[1]);
3576 /* Send it out remotely, generate no reply yet */
3577 TreeServer* s = FindServerMask(parameters[1]);
3580 params[1] = s->GetName();
3581 DoOneToOne(user->nick, "STATS", params, s->GetName());
3585 WriteServ(user->fd, "402 %s %s :No such server", user->nick, parameters[0]);
3592 // Ok, prepare to be confused.
3593 // After much mulling over how to approach this, it struck me that
3594 // the 'usual' way of doing a /MAP isnt the best way. Instead of
3595 // keeping track of a ton of ascii characters, and line by line
3596 // under recursion working out where to place them using multiplications
3597 // and divisons, we instead render the map onto a backplane of characters
3598 // (a character matrix), then draw the branches as a series of "L" shapes
3599 // from the nodes. This is not only friendlier on CPU it uses less stack.
3601 void HandleMap(const char** parameters, int pcnt, userrec* user)
3603 // This array represents a virtual screen which we will
3604 // "scratch" draw to, as the console device of an irc
3605 // client does not provide for a proper terminal.
3607 float totservers = 0;
3608 char matrix[128][80];
3609 for (unsigned int t = 0; t < 128; t++)
3611 matrix[t][0] = '\0';
3614 // The only recursive bit is called here.
3615 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3616 // Process each line one by one. The algorithm has a limit of
3617 // 128 servers (which is far more than a spanning tree should have
3618 // anyway, so we're ok). This limit can be raised simply by making
3619 // the character matrix deeper, 128 rows taking 10k of memory.
3620 for (int l = 1; l < line; l++)
3622 // scan across the line looking for the start of the
3623 // servername (the recursive part of the algorithm has placed
3624 // the servers at indented positions depending on what they
3626 int first_nonspace = 0;
3627 while (matrix[l][first_nonspace] == ' ')
3632 // Draw the `- (corner) section: this may be overwritten by
3633 // another L shape passing along the same vertical pane, becoming
3634 // a |- (branch) section instead.
3635 matrix[l][first_nonspace] = '-';
3636 matrix[l][first_nonspace-1] = '`';
3638 // Draw upwards until we hit the parent server, causing possibly
3639 // other corners (`-) to become branches (|-)
3640 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3642 matrix[l2][first_nonspace-1] = '|';
3646 // dump the whole lot to the user. This is the easy bit, honest.
3647 for (int t = 0; t < line; t++)
3649 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
3651 float avg_users = totusers / totservers;
3652 WriteServ(user->fd,"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);
3653 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
3657 int HandleSquit(const char** parameters, int pcnt, userrec* user)
3659 TreeServer* s = FindServerMask(parameters[0]);
3664 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3667 TreeSocket* sock = s->GetSocket();
3670 log(DEBUG,"Splitting server %s",s->GetName().c_str());
3671 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3672 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3673 Srv->RemoveSocket(sock);
3677 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3682 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3687 int HandleTime(const char** parameters, int pcnt, userrec* user)
3689 if ((IS_LOCAL(user)) && (pcnt))
3691 TreeServer* found = FindServerMask(parameters[0]);
3694 // we dont' override for local server
3695 if (found == TreeRoot)
3698 std::deque<std::string> params;
3699 params.push_back(found->GetName());
3700 params.push_back(user->nick);
3701 DoOneToOne(Srv->GetServerName(),"TIME",params,found->GetName());
3705 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3711 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3713 if ((IS_LOCAL(user)) && (pcnt > 1))
3715 userrec* remote = Srv->FindNick(parameters[1]);
3716 if ((remote) && (remote->fd < 0))
3718 std::deque<std::string> params;
3719 params.push_back(parameters[1]);
3720 DoOneToOne(user->nick,"IDLE",params,remote->server);
3725 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3726 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
3733 void DoPingChecks(time_t curtime)
3735 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
3737 TreeServer* serv = TreeRoot->GetChild(j);
3738 TreeSocket* sock = serv->GetSocket();
3741 if (curtime >= serv->NextPingTime())
3743 if (serv->AnsweredLastPing())
3745 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
3746 serv->SetNextPingTime(curtime + 120);
3750 // they didnt answer, boot them
3751 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
3752 sock->Squit(serv,"Ping timeout");
3753 Srv->RemoveSocket(sock);
3761 void AutoConnectServers(time_t curtime)
3763 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3765 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
3767 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
3768 x->NextConnectTime = curtime + x->AutoConnect;
3769 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3772 // an autoconnected server is not connected. Check if its time to connect it
3773 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
3777 /* Do we already have an IP? If so, no need to resolve it. */
3778 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3780 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3781 if (newsocket->GetFd() > -1)
3783 Srv->AddSocket(newsocket);
3787 WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3795 ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3796 Srv->AddResolver(snr);
3798 catch (ModuleException& e)
3800 log(DEBUG,"Error in resolver: %s",e.GetReason());
3809 int HandleVersion(const char** parameters, int pcnt, userrec* user)
3811 // we've already checked if pcnt > 0, so this is safe
3812 TreeServer* found = FindServerMask(parameters[0]);
3815 std::string Version = found->GetVersion();
3816 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
3817 if (found == TreeRoot)
3819 std::stringstream out(Config->data005);
3820 std::string token = "";
3821 std::string line5 = "";
3822 int token_counter = 0;
3827 line5 = line5 + token + " ";
3830 if ((token_counter >= 13) || (out.eof() == true))
3832 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
3841 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3846 int HandleConnect(const char** parameters, int pcnt, userrec* user)
3848 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3850 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
3852 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3855 WriteServ(user->fd,"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);
3858 /* Do we already have an IP? If so, no need to resolve it. */
3859 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3861 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3862 if (newsocket->GetFd() > -1)
3864 Srv->AddSocket(newsocket);
3868 WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3876 ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3877 Srv->AddResolver(snr);
3879 catch (ModuleException& e)
3881 log(DEBUG,"Error in resolver: %s",e.GetReason());
3888 WriteServ(user->fd,"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());
3893 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
3897 virtual int OnStats(char statschar, userrec* user, string_list &results)
3899 if (statschar == 'c')
3901 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
3903 results.push_back(Srv->GetServerName()+" 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');
3904 results.push_back(Srv->GetServerName()+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
3906 results.push_back(Srv->GetServerName()+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
3907 WriteOpers("*** Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
3913 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
3915 /* If the command doesnt appear to be valid, we dont want to mess with it. */
3919 if (command == "CONNECT")
3921 return this->HandleConnect(parameters,pcnt,user);
3923 else if (command == "STATS")
3925 return this->HandleStats(parameters,pcnt,user);
3927 else if (command == "SQUIT")
3929 return this->HandleSquit(parameters,pcnt,user);
3931 else if (command == "MAP")
3933 this->HandleMap(parameters,pcnt,user);
3936 else if ((command == "TIME") && (pcnt > 0))
3938 return this->HandleTime(parameters,pcnt,user);
3940 else if (command == "LUSERS")
3942 this->HandleLusers(parameters,pcnt,user);
3945 else if (command == "LINKS")
3947 this->HandleLinks(parameters,pcnt,user);
3950 else if (command == "WHOIS")
3955 return this->HandleRemoteWhois(parameters,pcnt,user);
3958 else if ((command == "VERSION") && (pcnt > 0))
3960 this->HandleVersion(parameters,pcnt,user);
3963 else if (Srv->IsValidModuleCommand(command, pcnt, user))
3965 // this bit of code cleverly routes all module commands
3966 // to all remote severs *automatically* so that modules
3967 // can just handle commands locally, without having
3968 // to have any special provision in place for remote
3969 // commands and linking protocols.
3970 std::deque<std::string> params;
3972 for (int j = 0; j < pcnt; j++)
3974 if (strchr(parameters[j],' '))
3976 params.push_back(":" + std::string(parameters[j]));
3980 params.push_back(std::string(parameters[j]));
3983 log(DEBUG,"Globally route '%s'",command.c_str());
3984 DoOneToMany(user->nick,command,params);
3989 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
3991 TreeServer* s = FindServer(servername);
3994 description = s->GetDesc();
3998 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4000 if (IS_LOCAL(source))
4002 std::deque<std::string> params;
4003 params.push_back(dest->nick);
4004 params.push_back(channel->name);
4005 DoOneToMany(source->nick,"INVITE",params);
4009 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4011 std::deque<std::string> params;
4012 params.push_back(chan->name);
4013 params.push_back(":"+topic);
4014 DoOneToMany(user->nick,"TOPIC",params);
4017 virtual void OnWallops(userrec* user, const std::string &text)
4021 std::deque<std::string> params;
4022 params.push_back(":"+text);
4023 DoOneToMany(user->nick,"WALLOPS",params);
4027 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4029 if (target_type == TYPE_USER)
4031 userrec* d = (userrec*)dest;
4032 if ((d->fd < 0) && (IS_LOCAL(user)))
4034 std::deque<std::string> params;
4036 params.push_back(d->nick);
4037 params.push_back(":"+text);
4038 DoOneToOne(user->nick,"NOTICE",params,d->server);
4041 else if (target_type == TYPE_CHANNEL)
4045 chanrec *c = (chanrec*)dest;
4046 std::string cname = c->name;
4048 cname = status + cname;
4049 std::deque<TreeServer*> list;
4050 GetListOfServersForChannel(c,list);
4051 unsigned int ucount = list.size();
4052 for (unsigned int i = 0; i < ucount; i++)
4054 TreeSocket* Sock = list[i]->GetSocket();
4056 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4060 else if (target_type == TYPE_SERVER)
4064 char* target = (char*)dest;
4065 std::deque<std::string> par;
4066 par.push_back(target);
4067 par.push_back(":"+text);
4068 DoOneToMany(user->nick,"NOTICE",par);
4073 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4075 if (target_type == TYPE_USER)
4077 // route private messages which are targetted at clients only to the server
4078 // which needs to receive them
4079 userrec* d = (userrec*)dest;
4080 if ((d->fd < 0) && (IS_LOCAL(user)))
4082 std::deque<std::string> params;
4084 params.push_back(d->nick);
4085 params.push_back(":"+text);
4086 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4089 else if (target_type == TYPE_CHANNEL)
4093 chanrec *c = (chanrec*)dest;
4094 std::string cname = c->name;
4096 cname = status + cname;
4097 std::deque<TreeServer*> list;
4098 GetListOfServersForChannel(c,list);
4099 unsigned int ucount = list.size();
4100 for (unsigned int i = 0; i < ucount; i++)
4102 TreeSocket* Sock = list[i]->GetSocket();
4104 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4108 else if (target_type == TYPE_SERVER)
4112 char* target = (char*)dest;
4113 std::deque<std::string> par;
4114 par.push_back(target);
4115 par.push_back(":"+text);
4116 DoOneToMany(user->nick,"PRIVMSG",par);
4121 virtual void OnBackgroundTimer(time_t curtime)
4123 AutoConnectServers(curtime);
4124 DoPingChecks(curtime);
4127 virtual void OnUserJoin(userrec* user, chanrec* channel)
4129 // Only do this for local users
4132 std::deque<std::string> params;
4134 params.push_back(channel->name);
4136 if (channel->GetUserCounter() > 1)
4138 // not the first in the channel
4139 DoOneToMany(user->nick,"JOIN",params);
4143 // first in the channel, set up their permissions
4144 // and the channel TS with FJOIN.
4146 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4148 params.push_back(channel->name);
4149 params.push_back(ts);
4150 params.push_back("@"+std::string(user->nick));
4151 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
4156 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4158 // only occurs for local clients
4159 if (user->registered != REG_ALL)
4161 std::deque<std::string> params;
4162 params.push_back(newhost);
4163 DoOneToMany(user->nick,"FHOST",params);
4166 virtual void OnChangeName(userrec* user, const std::string &gecos)
4168 // only occurs for local clients
4169 if (user->registered != REG_ALL)
4171 std::deque<std::string> params;
4172 params.push_back(gecos);
4173 DoOneToMany(user->nick,"FNAME",params);
4176 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4180 std::deque<std::string> params;
4181 params.push_back(channel->name);
4182 if (partmessage != "")
4183 params.push_back(":"+partmessage);
4184 DoOneToMany(user->nick,"PART",params);
4188 virtual void OnUserConnect(userrec* user)
4190 char agestr[MAXBUF];
4193 std::deque<std::string> params;
4194 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4195 params.push_back(agestr);
4196 params.push_back(user->nick);
4197 params.push_back(user->host);
4198 params.push_back(user->dhost);
4199 params.push_back(user->ident);
4200 params.push_back("+"+std::string(user->FormatModes()));
4201 params.push_back(user->GetIPString());
4202 params.push_back(":"+std::string(user->fullname));
4203 DoOneToMany(Srv->GetServerName(),"NICK",params);
4205 // User is Local, change needs to be reflected!
4206 TreeServer* SourceServer = FindServer(user->server);
4209 SourceServer->AddUserCount();
4215 virtual void OnUserQuit(userrec* user, const std::string &reason)
4217 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4219 std::deque<std::string> params;
4220 params.push_back(":"+reason);
4221 DoOneToMany(user->nick,"QUIT",params);
4223 // Regardless, We need to modify the user Counts..
4224 TreeServer* SourceServer = FindServer(user->server);
4227 SourceServer->DelUserCount();
4232 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4236 std::deque<std::string> params;
4237 params.push_back(user->nick);
4238 DoOneToMany(oldnick,"NICK",params);
4242 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4244 if ((source) && (IS_LOCAL(source)))
4246 std::deque<std::string> params;
4247 params.push_back(chan->name);
4248 params.push_back(user->nick);
4249 params.push_back(":"+reason);
4250 DoOneToMany(source->nick,"KICK",params);
4254 std::deque<std::string> params;
4255 params.push_back(chan->name);
4256 params.push_back(user->nick);
4257 params.push_back(":"+reason);
4258 DoOneToMany(Srv->GetServerName(),"KICK",params);
4262 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4264 std::deque<std::string> params;
4265 params.push_back(dest->nick);
4266 params.push_back(":"+reason);
4267 DoOneToMany(source->nick,"KILL",params);
4270 virtual void OnRehash(const std::string ¶meter)
4272 if (parameter != "")
4274 std::deque<std::string> params;
4275 params.push_back(parameter);
4276 DoOneToMany(Srv->GetServerName(),"REHASH",params);
4278 if (Srv->MatchText(Srv->GetServerName(),parameter))
4280 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
4281 Srv->RehashServer();
4284 ReadConfiguration(false);
4287 // note: the protocol does not allow direct umode +o except
4288 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4290 virtual void OnOper(userrec* user, const std::string &opertype)
4294 std::deque<std::string> params;
4295 params.push_back(opertype);
4296 DoOneToMany(user->nick,"OPERTYPE",params);
4300 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4302 if (IS_LOCAL(source))
4305 snprintf(type,8,"%cLINE",linetype);
4306 std::string stype = type;
4309 char sduration[MAXBUF];
4310 snprintf(sduration,MAXBUF,"%ld",duration);
4311 std::deque<std::string> params;
4312 params.push_back(host);
4313 params.push_back(sduration);
4314 params.push_back(":"+reason);
4315 DoOneToMany(source->nick,stype,params);
4319 std::deque<std::string> params;
4320 params.push_back(host);
4321 DoOneToMany(source->nick,stype,params);
4326 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4328 OnLine(source,hostmask,true,'G',duration,reason);
4331 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4333 OnLine(source,ipmask,true,'Z',duration,reason);
4336 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4338 OnLine(source,nickmask,true,'Q',duration,reason);
4341 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4343 OnLine(source,hostmask,true,'E',duration,reason);
4346 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4348 OnLine(source,hostmask,false,'G',0,"");
4351 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4353 OnLine(source,ipmask,false,'Z',0,"");
4356 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4358 OnLine(source,nickmask,false,'Q',0,"");
4361 virtual void OnDelELine(userrec* source, const std::string &hostmask)
4363 OnLine(source,hostmask,false,'E',0,"");
4366 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4368 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4370 if (target_type == TYPE_USER)
4372 userrec* u = (userrec*)dest;
4373 std::deque<std::string> params;
4374 params.push_back(u->nick);
4375 params.push_back(text);
4376 DoOneToMany(user->nick,"MODE",params);
4380 chanrec* c = (chanrec*)dest;
4381 std::deque<std::string> params;
4382 params.push_back(c->name);
4383 params.push_back(text);
4384 DoOneToMany(user->nick,"MODE",params);
4389 virtual void OnSetAway(userrec* user)
4393 std::deque<std::string> params;
4394 params.push_back(":"+std::string(user->awaymsg));
4395 DoOneToMany(user->nick,"AWAY",params);
4399 virtual void OnCancelAway(userrec* user)
4403 std::deque<std::string> params;
4405 DoOneToMany(user->nick,"AWAY",params);
4409 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4411 TreeSocket* s = (TreeSocket*)opaque;
4414 if (target_type == TYPE_USER)
4416 userrec* u = (userrec*)target;
4417 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4421 chanrec* c = (chanrec*)target;
4422 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4427 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4429 TreeSocket* s = (TreeSocket*)opaque;
4432 if (target_type == TYPE_USER)
4434 userrec* u = (userrec*)target;
4435 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
4437 else if (target_type == TYPE_OTHER)
4439 s->WriteLine(":"+Srv->GetServerName()+" METADATA * "+extname+" :"+extdata);
4441 else if (target_type == TYPE_CHANNEL)
4443 chanrec* c = (chanrec*)target;
4444 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
4449 virtual void OnEvent(Event* event)
4451 if (event->GetEventID() == "send_metadata")
4453 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4454 if (params->size() < 3)
4456 (*params)[2] = ":" + (*params)[2];
4457 DoOneToMany(Srv->GetServerName(),"METADATA",*params);
4459 else if (event->GetEventID() == "send_mode")
4461 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4462 if (params->size() < 2)
4464 // Insert the TS value of the object, either userrec or chanrec
4466 userrec* a = Srv->FindNick((*params)[0]);
4473 chanrec* a = Srv->FindChannel((*params)[0]);
4479 params->insert(params->begin() + 1,ConvToStr(ourTS));
4480 DoOneToMany(Srv->GetServerName(),"FMODE",*params);
4484 virtual ~ModuleSpanningTree()
4488 virtual Version GetVersion()
4490 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4493 void Implements(char* List)
4495 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4496 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4497 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4498 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4499 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4500 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4501 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4504 /* It is IMPORTANT that m_spanningtree is the last module in the chain
4505 * so that any activity it sees is FINAL, e.g. we arent going to send out
4506 * a NICK message before m_cloaking has finished putting the +x on the user,
4508 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4509 * the module call queue.
4511 Priority Prioritize()
4513 return PRIORITY_LAST;
4518 class ModuleSpanningTreeFactory : public ModuleFactory
4521 ModuleSpanningTreeFactory()
4525 ~ModuleSpanningTreeFactory()
4529 virtual Module * CreateModule(Server* Me)
4531 TreeProtocolModule = new ModuleSpanningTree(Me);
4532 return TreeProtocolModule;
4538 extern "C" void * init_module( void )
4540 return new ModuleSpanningTreeFactory;