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 InspIRCd* ServerInstance;
72 extern std::vector<Module*> modules;
73 extern std::vector<ircd_module*> factory;
76 /* Any socket can have one of five states at any one time.
77 * The LISTENER state indicates a socket which is listening
78 * for connections. It cannot receive data itself, only incoming
80 * The CONNECTING state indicates an outbound socket which is
81 * waiting to be writeable.
82 * The WAIT_AUTH_1 state indicates the socket is outbound and
83 * has successfully connected, but has not yet sent and received
85 * The WAIT_AUTH_2 state indicates that the socket is inbound
86 * (allocated by a LISTENER) but has not yet sent and received
88 * The CONNECTED state represents a fully authorized, fully
91 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
93 /* Foward declarations */
97 /* This variable represents the root of the server tree
98 * (for all intents and purposes, it's us)
100 TreeServer *TreeRoot;
104 /* This hash_map holds the hash equivalent of the server
105 * tree, used for rapid linear lookups.
107 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
108 server_hash serverlist;
110 typedef nspace::hash_map<std::string, userrec*> uid_hash;
111 typedef nspace::hash_map<std::string, char*> sid_hash;
113 /* More forward declarations */
114 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
115 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
116 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
117 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms);
118 void ReadConfiguration(bool rebind);
120 /* Flatten links and /MAP for non-opers */
122 /* Hide U-Lined servers in /MAP and /LINKS */
125 /* Imported from xline.cpp for use during netburst */
126 extern std::vector<KLine> klines;
127 extern std::vector<GLine> glines;
128 extern std::vector<ZLine> zlines;
129 extern std::vector<QLine> qlines;
130 extern std::vector<ELine> elines;
131 extern std::vector<KLine> pklines;
132 extern std::vector<GLine> pglines;
133 extern std::vector<ZLine> pzlines;
134 extern std::vector<QLine> pqlines;
135 extern std::vector<ELine> pelines;
137 std::vector<std::string> ValidIPs;
139 class UserManager : public classbase
150 std::string UserToUID(userrec* user)
155 std::string UIDToUser(const std::string &UID)
160 std::string CreateAndAdd(userrec* user)
165 std::string CreateAndAdd(const std::string &servername)
170 std::string ServerToSID(const std::string &servername)
175 std::string SIDToServer(const std::string &SID)
180 userrec* FindByID(const std::string &UID)
187 /* Each server in the tree is represented by one class of
188 * type TreeServer. A locally connected TreeServer can
189 * have a class of type TreeSocket associated with it, for
190 * remote servers, the TreeSocket entry will be NULL.
191 * Each server also maintains a pointer to its parent
192 * (NULL if this server is ours, at the top of the tree)
193 * and a pointer to its "Route" (see the comments in the
194 * constructors below), and also a dynamic list of pointers
195 * to its children which can be iterated recursively
196 * if required. Creating or deleting objects of type
197 i* TreeServer automatically maintains the hash_map of
198 * TreeServer items, deleting and inserting them as they
199 * are created and destroyed.
202 class TreeServer : public classbase
204 TreeServer* Parent; /* Parent entry */
205 TreeServer* Route; /* Route entry */
206 std::vector<TreeServer*> Children; /* List of child objects */
207 irc::string ServerName; /* Server's name */
208 std::string ServerDesc; /* Server's description */
209 std::string VersionString; /* Version string or empty string */
210 int UserCount; /* Not used in this version */
211 int OperCount; /* Not used in this version */
212 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
213 time_t NextPing; /* After this time, the server should be PINGed*/
214 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
218 /* We don't use this constructor. Its a dummy, and won't cause any insertion
219 * of the TreeServer into the hash_map. See below for the two we DO use.
227 UserCount = OperCount = 0;
228 VersionString = Srv->GetVersion();
231 /* We use this constructor only to create the 'root' item, TreeRoot, which
232 * represents our own server. Therefore, it has no route, no parent, and
233 * no socket associated with it. Its version string is our own local version.
235 TreeServer(std::string Name, std::string Desc) : ServerName(Name.c_str()), ServerDesc(Desc)
239 UserCount = OperCount = 0;
240 VersionString = Srv->GetVersion();
242 Socket = NULL; /* Fix by brain */
246 /* When we create a new server, we call this constructor to initialize it.
247 * This constructor initializes the server's Route and Parent, and sets up
248 * its ping counters so that it will be pinged one minute from now.
250 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
253 UserCount = OperCount = 0;
254 this->SetNextPingTime(time(NULL) + 120);
257 /* find the 'route' for this server (e.g. the one directly connected
258 * to the local server, which we can use to reach it)
260 * In the following example, consider we have just added a TreeServer
261 * class for server G on our network, of which we are server A.
262 * To route traffic to G (marked with a *) we must send the data to
263 * B (marked with a +) so this algorithm initializes the 'Route'
264 * value to point at whichever server traffic must be routed through
265 * to get here. If we were to try this algorithm with server B,
266 * the Route pointer would point at its own object ('this').
276 * We only run this algorithm when a server is created, as
277 * the routes remain constant while ever the server exists, and
278 * do not need to be re-calculated.
282 if (Route == TreeRoot)
288 while (this->Route->GetParent() != TreeRoot)
290 this->Route = Route->GetParent();
294 /* Because recursive code is slow and takes a lot of resources,
295 * we store two representations of the server tree. The first
296 * is a recursive structure where each server references its
297 * children and its parent, which is used for netbursts and
298 * netsplits to dump the whole dataset to the other server,
299 * and the second is used for very fast lookups when routing
300 * messages and is instead a hash_map, where each item can
301 * be referenced by its server name. The AddHashEntry()
302 * call below automatically inserts each TreeServer class
303 * into the hash_map as it is created. There is a similar
304 * maintainance call in the destructor to tidy up deleted
308 this->AddHashEntry();
311 int QuitUsers(const std::string &reason)
313 log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
314 const char* reason_s = reason.c_str();
315 std::vector<userrec*> time_to_die;
316 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
318 if (!strcmp(n->second->server, this->ServerName.c_str()))
320 time_to_die.push_back(n->second);
323 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
325 userrec* a = (userrec*)*n;
326 log(DEBUG,"Kill %s fd=%d",a->nick,a->fd);
328 userrec::QuitUser(a,reason_s);
330 return time_to_die.size();
333 /* This method is used to add the structure to the
334 * hash_map for linear searches. It is only called
335 * by the constructors.
339 server_hash::iterator iter;
340 iter = serverlist.find(this->ServerName.c_str());
341 if (iter == serverlist.end())
342 serverlist[this->ServerName.c_str()] = this;
345 /* This method removes the reference to this object
346 * from the hash_map which is used for linear searches.
347 * It is only called by the default destructor.
351 server_hash::iterator iter;
352 iter = serverlist.find(this->ServerName.c_str());
353 if (iter != serverlist.end())
354 serverlist.erase(iter);
357 /* These accessors etc should be pretty self-
361 TreeServer* GetRoute()
366 std::string GetName()
368 return ServerName.c_str();
371 std::string GetDesc()
376 std::string GetVersion()
378 return VersionString;
381 void SetNextPingTime(time_t t)
384 LastPingWasGood = false;
387 time_t NextPingTime()
392 bool AnsweredLastPing()
394 return LastPingWasGood;
399 LastPingWasGood = true;
422 TreeSocket* GetSocket()
427 TreeServer* GetParent()
432 void SetVersion(std::string Version)
434 VersionString = Version;
437 unsigned int ChildCount()
439 return Children.size();
442 TreeServer* GetChild(unsigned int n)
444 if (n < Children.size())
446 /* Make sure they cant request
447 * an out-of-range object. After
448 * all we know what these programmer
449 * types are like *grin*.
459 void AddChild(TreeServer* Child)
461 Children.push_back(Child);
464 bool DelChild(TreeServer* Child)
466 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
477 /* Removes child nodes of this node, and of that node, etc etc.
478 * This is used during netsplits to automatically tidy up the
479 * server tree. It is slow, we don't use it for much else.
483 bool stillchildren = true;
484 while (stillchildren)
486 stillchildren = false;
487 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
489 TreeServer* s = (TreeServer*)*a;
493 stillchildren = true;
502 /* We'd better tidy up after ourselves, eh? */
503 this->DelHashEntry();
507 /* The Link class might as well be a struct,
508 * but this is C++ and we don't believe in structs (!).
509 * It holds the entire information of one <link>
510 * tag from the main config file. We maintain a list
511 * of them, and populate the list on rehash/load.
514 class Link : public classbase
520 std::string SendPass;
521 std::string RecvPass;
522 unsigned long AutoConnect;
523 time_t NextConnectTime;
524 std::string EncryptionKey;
525 bool HiddenFromStats;
528 /* The usual stuff for inspircd modules,
529 * plus the vector of Link classes which we
530 * use to store the <link> tags from the config
534 std::vector<Link> LinkBlocks;
536 /* Yay for fast searches!
537 * This is hundreds of times faster than recursion
538 * or even scanning a linked list, especially when
539 * there are more than a few servers to deal with.
542 TreeServer* FindServer(std::string ServerName)
544 server_hash::iterator iter;
545 iter = serverlist.find(ServerName.c_str());
546 if (iter != serverlist.end())
556 /* Returns the locally connected server we must route a
557 * message through to reach server 'ServerName'. This
558 * only applies to one-to-one and not one-to-many routing.
559 * See the comments for the constructor of TreeServer
562 TreeServer* BestRouteTo(std::string ServerName)
564 if (ServerName.c_str() == TreeRoot->GetName())
566 TreeServer* Found = FindServer(ServerName);
569 return Found->GetRoute();
577 /* Find the first server matching a given glob mask.
578 * Theres no find-using-glob method of hash_map [awwww :-(]
579 * so instead, we iterate over the list using an iterator
580 * and match each one until we get a hit. Yes its slow,
583 TreeServer* FindServerMask(std::string ServerName)
585 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
587 if (Srv->MatchText(i->first.c_str(),ServerName))
593 /* A convenient wrapper that returns true if a server exists */
594 bool IsServer(std::string ServerName)
596 return (FindServer(ServerName) != NULL);
600 class cmd_rconnect : public command_t
604 cmd_rconnect (Module* Callback) : command_t("RCONNECT", 'o', 2), Creator(Callback)
606 this->source = "m_spanningtree.so";
607 syntax = "<remote-server-mask> <servermask>";
610 void Handle (const char** parameters, int pcnt, userrec *user)
612 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
613 /* Is this aimed at our server? */
614 if (Srv->MatchText(Srv->GetServerName(),parameters[0]))
616 /* Yes, initiate the given connect */
617 WriteOpers("*** Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
619 para[0] = parameters[1];
620 Creator->OnPreCommand("CONNECT", para, 1, user, true);
627 /* Every SERVER connection inbound or outbound is represented by
628 * an object of type TreeSocket.
629 * TreeSockets, being inherited from InspSocket, can be tied into
630 * the core socket engine, and we cn therefore receive activity events
631 * for them, just like activex objects on speed. (yes really, that
632 * is a technical term!) Each of these which relates to a locally
633 * connected server is assocated with it, by hooking it onto a
634 * TreeSocket class using its constructor. In this way, we can
635 * maintain a list of servers, some of which are directly connected,
636 * some of which are not.
639 class TreeSocket : public InspSocket
642 std::string in_buffer;
643 ServerState LinkState;
644 std::string InboundServerName;
645 std::string InboundDescription;
647 int num_lost_servers;
649 bool LastPingWasGood;
653 unsigned int keylength;
657 /* Because most of the I/O gubbins are encapsulated within
658 * InspSocket, we just call the superclass constructor for
659 * most of the action, and append a few of our own values
662 TreeSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
663 : InspSocket(SI, host, port, listening, maxtime)
666 this->LinkState = LISTENER;
668 this->ctx_out = NULL;
671 TreeSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
672 : InspSocket(SI, host, port, listening, maxtime)
675 this->LinkState = CONNECTING;
677 this->ctx_out = NULL;
680 /* When a listening socket gives us a new file descriptor,
681 * we must associate it with a socket without creating a new
682 * connection. This constructor is used for this purpose.
684 TreeSocket(InspIRCd* SI, int newfd, char* ip)
685 : InspSocket(SI, newfd, ip)
687 this->LinkState = WAIT_AUTH_1;
689 this->ctx_out = NULL;
690 this->SendCapabilities();
701 void InitAES(std::string key,std::string SName)
708 log(DEBUG,"Initialized AES key %s",key.c_str());
709 // key must be 16, 24, 32 etc bytes (multiple of 8)
710 keylength = key.length();
711 if (!(keylength == 16 || keylength == 24 || keylength == 32))
713 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
714 log(DEBUG,"Key length not 16, 24 or 32 characters!");
718 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
719 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\
720 \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);
721 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\
722 \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 /* When an outbound connection finishes connecting, we receive
727 * this event, and must send our SERVER string to the other
728 * side. If the other side is happy, as outlined in the server
729 * to server docs on the inspircd.org site, the other side
730 * will then send back its own server string.
732 virtual bool OnConnected()
734 if (this->LinkState == CONNECTING)
736 /* we do not need to change state here. */
737 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
739 if (x->Name == this->myhost)
741 Srv->SendOpers("*** Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
742 this->SendCapabilities();
743 if (x->EncryptionKey != "")
745 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
747 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
751 this->WriteLine("AES "+Srv->GetServerName());
752 this->InitAES(x->EncryptionKey,x->Name.c_str());
755 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
756 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
761 /* There is a (remote) chance that between the /CONNECT and the connection
762 * being accepted, some muppet has removed the <link> block and rehashed.
763 * If that happens the connection hangs here until it's closed. Unlikely
764 * and rather harmless.
766 Srv->SendOpers("*** Connection to \2"+myhost+"\2 lost link tag(!)");
770 virtual void OnError(InspSocketError e)
772 /* We don't handle this method, because all our
773 * dirty work is done in OnClose() (see below)
774 * which is still called on error conditions too.
776 if (e == I_ERR_CONNECT)
778 Srv->SendOpers("*** Connection failed: Connection refused");
782 virtual int OnDisconnect()
784 /* For the same reason as above, we don't
785 * handle OnDisconnect()
790 /* Recursively send the server tree with distances as hops.
791 * This is used during network burst to inform the other server
792 * (and any of ITS servers too) of what servers we know about.
793 * If at any point any of these servers already exist on the other
794 * end, our connection may be terminated. The hopcounts given
795 * by this function are relative, this doesn't matter so long as
796 * they are all >1, as all the remote servers re-calculate them
797 * to be relative too, with themselves as hop 0.
799 void SendServers(TreeServer* Current, TreeServer* s, int hops)
802 for (unsigned int q = 0; q < Current->ChildCount(); q++)
804 TreeServer* recursive_server = Current->GetChild(q);
805 if (recursive_server != s)
807 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
808 this->WriteLine(command);
809 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
810 /* down to next level */
811 this->SendServers(recursive_server, s, hops+1);
816 std::string MyCapabilities()
818 std::vector<std::string> modlist;
819 std::string capabilities = "";
821 for (int i = 0; i <= MODCOUNT; i++)
823 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
824 modlist.push_back(ServerInstance->Config->module_names[i]);
826 sort(modlist.begin(),modlist.end());
827 for (unsigned int i = 0; i < modlist.size(); i++)
830 capabilities = capabilities + ",";
831 capabilities = capabilities + modlist[i];
836 void SendCapabilities()
838 this->WriteLine("CAPAB "+MyCapabilities());
841 bool Capab(std::deque<std::string> params)
843 if (params.size() != 1)
845 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
849 if (params[0] != this->MyCapabilities())
851 std::string quitserver = this->myhost;
852 if (this->InboundServerName != "")
854 quitserver = this->InboundServerName;
857 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
858 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
859 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
860 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
861 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
868 /* This function forces this server to quit, removing this server
869 * and any users on it (and servers and users below that, etc etc).
870 * It's very slow and pretty clunky, but luckily unless your network
871 * is having a REAL bad hair day, this function shouldnt be called
872 * too many times a month ;-)
874 void SquitServer(std::string &from, TreeServer* Current)
876 /* recursively squit the servers attached to 'Current'.
877 * We're going backwards so we don't remove users
878 * while we still need them ;)
880 for (unsigned int q = 0; q < Current->ChildCount(); q++)
882 TreeServer* recursive_server = Current->GetChild(q);
883 this->SquitServer(from,recursive_server);
885 /* Now we've whacked the kids, whack self */
887 num_lost_users += Current->QuitUsers(from);
890 /* This is a wrapper function for SquitServer above, which
891 * does some validation first and passes on the SQUIT to all
892 * other remaining servers.
894 void Squit(TreeServer* Current,std::string reason)
896 if ((Current) && (Current != TreeRoot))
898 std::deque<std::string> params;
899 params.push_back(Current->GetName());
900 params.push_back(":"+reason);
901 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
902 if (Current->GetParent() == TreeRoot)
904 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
908 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
910 num_lost_servers = 0;
912 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
913 SquitServer(from, Current);
915 Current->GetParent()->DelChild(Current);
917 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
921 log(DEFAULT,"Squit from unknown server");
925 /* FMODE command - server mode with timestamp checks */
926 bool ForceMode(std::string source, std::deque<std::string> ¶ms)
928 /* Chances are this is a 1.0 FMODE without TS */
929 if (params.size() < 3)
931 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
936 std::string sourceserv;
938 /* Are we dealing with an FMODE from a user, or from a server? */
939 userrec* who = Srv->FindNick(source);
942 /* FMODE from a user, set sourceserv to the users server name */
943 sourceserv = who->server;
947 /* FMODE from a server, create a fake user to receive mode feedback */
949 who->fd = FD_MAGIC_NUMBER;
950 smode = true; /* Setting this flag tells us we should free the userrec later */
951 sourceserv = source; /* Set sourceserv to the actual source string */
953 const char* modelist[64];
956 memset(&modelist,0,sizeof(modelist));
957 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
961 /* The timestamp is in this position.
962 * We don't want to pass that up to the
963 * server->client protocol!
965 TS = atoi(params[q].c_str());
969 /* Everything else is fine to append to the modelist */
970 modelist[n++] = params[q].c_str();
974 /* Extract the TS value of the object, either userrec or chanrec */
975 userrec* dst = Srv->FindNick(params[0]);
976 chanrec* chan = NULL;
984 chan = Srv->FindChannel(params[0]);
991 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
996 log(DEBUG,"Entering TS equality check");
997 ModeHandler* mh = NULL;
998 unsigned long paramptr = 3;
999 std::string to_bounce = "";
1000 std::string to_keep = "";
1001 std::vector<std::string> params_to_keep;
1002 std::string params_to_bounce = "";
1004 char cur_change = 1;
1005 char old_change = 0;
1006 char old_bounce_change = 0;
1007 /* Merge modes, basically do special stuff to mode with params */
1008 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1021 /* We only care about whats being set,
1022 * not whats being unset
1024 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1026 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1028 /* We only want to do special things to
1029 * modes with parameters, we are going to rewrite
1033 adding ? cur_change = '+' : cur_change = '-';
1035 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1037 /* The mode is set here, check which we should keep */
1040 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1042 if (which_to_keep == true)
1044 /* Keep ours, bounce theirs:
1045 * Send back ours to them and
1046 * drop their mode changs
1048 adding ? cur_change = '+' : cur_change = '-';
1049 if (cur_change != old_bounce_change)
1050 to_bounce += cur_change;
1052 old_bounce_change = cur_change;
1054 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1055 params_to_bounce.append(" ").append(ret.second);
1059 /* Keep theirs: Accept their mode change,
1062 adding ? cur_change = '+' : cur_change = '-';
1063 if (cur_change != old_change)
1064 to_keep += cur_change;
1066 old_change = cur_change;
1068 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1069 params_to_keep.push_back(params[paramptr]);
1074 /* Mode isnt set here, we want it */
1075 adding ? cur_change = '+' : cur_change = '-';
1076 if (cur_change != old_change)
1077 to_keep += cur_change;
1079 old_change = cur_change;
1081 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1082 params_to_keep.push_back(params[paramptr]);
1089 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1093 adding ? cur_change = '+' : cur_change = '-';
1095 /* Just keep this, safe to merge with no checks
1096 * it has no parameters
1099 if (cur_change != old_change)
1100 to_keep += cur_change;
1102 old_change = cur_change;
1104 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1106 log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1107 params_to_keep.push_back(params[paramptr++]);
1114 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1118 /* Taking a mode away */
1119 adding ? cur_change = '+' : cur_change = '-';
1121 if (cur_change != old_change)
1122 to_keep += cur_change;
1124 old_change = cur_change;
1126 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1127 params_to_keep.push_back(params[paramptr++]);
1134 if (to_bounce.length())
1136 std::deque<std::string> newparams;
1137 newparams.push_back(params[0]);
1138 newparams.push_back(ConvToStr(ourTS));
1139 newparams.push_back(to_bounce+params_to_bounce);
1140 DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1143 if (to_keep.length())
1147 modelist[0] = params[0].c_str();
1148 modelist[1] = to_keep.c_str();
1150 if (params_to_keep.size() > 2)
1152 for (q = 2; (q < params_to_keep.size()) && (q < 64); q++)
1154 log(DEBUG,"Item %d of %d", q, params_to_keep.size());
1155 modelist[n++] = params_to_keep[q].c_str();
1161 log(DEBUG,"Send mode");
1162 Srv->SendMode(modelist, n+2, who);
1166 log(DEBUG,"Send mode client");
1167 Srv->CallCommandHandler("MODE", modelist, n+2, who);
1170 /* HOT POTATO! PASS IT ON! */
1171 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1175 /* U-lined servers always win regardless of their TS */
1176 if ((TS > ourTS) && (!Srv->IsUlined(source)))
1178 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1179 * SHOULD accept it, if its clock is right.
1181 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1182 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1183 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1185 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1186 * writing the code. It took me a while to come up with this solution.
1188 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1191 std::deque<std::string> newparams; /* New parameter list we send back */
1192 newparams.push_back(params[0]); /* Target, user or channel */
1193 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1194 newparams.push_back(""); /* This contains the mode string. For now
1195 * it's empty, we fill it below.
1198 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1199 * set to avoid a desync here.
1201 std::string modebounce = "";
1204 ModeHandler* mh = NULL;
1205 char cur_change = 1;
1206 char old_change = 0;
1207 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1209 /* Iterate over all mode chars in the sent set */
1212 /* Adding or subtracting modes? */
1220 /* Find the mode handler for this mode */
1221 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1223 /* Got a mode handler?
1224 * This also prevents us bouncing modes we have no handler for.
1231 /* Does the mode require a parameter right now?
1232 * If it does, fetch it if we can
1234 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1237 /* Call the ModeSet method to determine if its set with the
1238 * given parameter here or not.
1240 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1242 /* XXX: Really. Dont ask.
1243 * Determine from if its set combined with what the current
1244 * 'state' is (adding or not) as to wether we should 'invert'
1245 * or 'reinforce' the mode change
1247 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1249 /* Quickly determine if we have 'flipped' from + to -,
1250 * or - to +, to prevent unneccessary +/- chars in the
1251 * output string that waste bandwidth
1253 if (cur_change != old_change)
1254 modebounce += cur_change;
1255 old_change = cur_change;
1257 /* Add the mode character to the output string */
1258 modebounce += mh->GetModeChar();
1260 /* We got a parameter back from ModeHandler::ModeSet,
1261 * are we supposed to be sending one out right now?
1263 if (ret.second.length())
1265 if (mh->GetNumParams(cur_change == '+') > 0)
1266 /* Yes we're supposed to be sending out
1267 * the parameter. Make sure it goes
1269 newparams.push_back(ret.second);
1277 /* Update the parameters for FMODE with the new 'bounced' string */
1278 newparams[2] = modebounce;
1279 /* Only send it back the way it came, no need to send it anywhere else */
1280 DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1281 log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1285 log(DEBUG,"Allow modes, TS lower for sender");
1286 /* The server was ulined, but something iffy is up with the TS.
1287 * Sound the alarm bells!
1289 if ((Srv->IsUlined(sourceserv)) && (TS > ourTS))
1291 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());
1293 /* Allow the mode, route it to either server or user command handling */
1295 Srv->SendMode(modelist,n,who);
1297 Srv->CallCommandHandler("MODE", modelist, n, who);
1299 /* HOT POTATO! PASS IT ON! */
1300 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1302 /* Are we supposed to free the userrec? */
1309 /* FTOPIC command */
1310 bool ForceTopic(std::string source, std::deque<std::string> ¶ms)
1312 if (params.size() != 4)
1314 time_t ts = atoi(params[1].c_str());
1315 std::string nsource = source;
1317 chanrec* c = Srv->FindChannel(params[0]);
1320 if ((ts >= c->topicset) || (!*c->topic))
1322 std::string oldtopic = c->topic;
1323 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1324 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1326 /* if the topic text is the same as the current topic,
1327 * dont bother to send the TOPIC command out, just silently
1328 * update the set time and set nick.
1330 if (oldtopic != params[3])
1332 userrec* user = Srv->FindNick(source);
1335 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1339 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1340 nsource = user->server;
1342 /* all done, send it on its way */
1343 params[3] = ":" + params[3];
1344 DoOneToAllButSender(source,"FTOPIC",params,nsource);
1353 /* FJOIN, similar to unreal SJOIN */
1354 bool ForceJoin(std::string source, std::deque<std::string> ¶ms)
1356 if (params.size() < 3)
1360 char modestring[MAXBUF];
1361 char* mode_users[127];
1362 memset(&mode_users,0,sizeof(mode_users));
1363 mode_users[0] = first;
1364 mode_users[1] = modestring;
1365 strcpy(modestring,"+");
1366 unsigned int modectr = 2;
1368 userrec* who = NULL;
1369 std::string channel = params[0];
1370 time_t TS = atoi(params[1].c_str());
1373 chanrec* chan = Srv->FindChannel(channel);
1378 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1380 /* default is a high value, which if we dont have this
1381 * channel will let the other side apply their modes.
1383 time_t ourTS = time(NULL)+600;
1384 chanrec* us = Srv->FindChannel(channel);
1390 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1392 /* do this first, so our mode reversals are correctly received by other servers
1393 * if there is a TS collision.
1395 DoOneToAllButSender(source,"FJOIN",params,source);
1397 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
1399 /* process one channel at a time, applying modes. */
1400 char* usr = (char*)params[usernum].c_str();
1401 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1402 * (is this even possible?) */
1405 char permissions = *usr;
1406 switch (permissions)
1410 mode_users[modectr++] = usr;
1411 strlcat(modestring,"o",MAXBUF);
1415 mode_users[modectr++] = usr;
1416 strlcat(modestring,"h",MAXBUF);
1420 mode_users[modectr++] = usr;
1421 strlcat(modestring,"v",MAXBUF);
1424 who = Srv->FindNick(usr);
1427 chanrec::JoinUser(who, channel.c_str(), true, key);
1428 if (modectr >= (MAXMODES-1))
1430 /* theres a mode for this user. push them onto the mode queue, and flush it
1431 * if there are more than MAXMODES to go.
1433 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
1435 /* We also always let u-lined clients win, no matter what the TS value */
1436 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1437 Srv->SendMode((const char**)mode_users,modectr,who);
1440 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1447 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1448 /* bouncy bouncy! */
1449 std::deque<std::string> params;
1450 /* modes are now being UNSET... */
1451 *mode_users[1] = '-';
1452 for (unsigned int x = 0; x < modectr; x++)
1456 params.push_back(ConvToStr(us->age));
1458 params.push_back(mode_users[x]);
1461 // tell everyone to bounce the modes. bad modes, bad!
1462 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1464 strcpy(mode_users[1],"+");
1470 /* there werent enough modes built up to flush it during FJOIN,
1471 * or, there are a number left over. flush them out.
1473 if ((modectr > 2) && (who) && (us))
1477 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1478 Srv->SendMode((const char**)mode_users,modectr,who);
1481 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1488 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1489 std::deque<std::string> params;
1490 *mode_users[1] = '-';
1491 for (unsigned int x = 0; x < modectr; x++)
1495 params.push_back(ConvToStr(us->age));
1497 params.push_back(mode_users[x]);
1499 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1505 bool SyncChannelTS(std::string source, std::deque<std::string> ¶ms)
1507 if (params.size() >= 2)
1509 chanrec* c = Srv->FindChannel(params[0]);
1512 time_t theirTS = atoi(params[1].c_str());
1513 time_t ourTS = c->age;
1514 if (ourTS >= theirTS)
1516 log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1521 DoOneToAllButSender(Srv->GetServerName(),"SYNCTS",params,source);
1526 bool IntroduceClient(std::string source, std::deque<std::string> ¶ms)
1528 if (params.size() < 8)
1530 if (params.size() > 8)
1532 this->WriteLine(":"+Srv->GetServerName()+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1535 // NICK age nick host dhost ident +modes ip :gecos
1537 time_t age = atoi(params[0].c_str());
1539 /* This used to have a pretty craq'y loop doing the same thing,
1540 * now we just let the STL do the hard work (more efficiently)
1542 params[5] = params[5].substr(params[5].find_first_not_of('+'));
1544 const char* tempnick = params[1].c_str();
1545 log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1547 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1549 if (iter != this->Instance->clientlist.end())
1552 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);
1553 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1557 userrec* _new = new userrec();
1558 this->Instance->clientlist[tempnick] = _new;
1559 _new->fd = FD_MAGIC_NUMBER;
1560 strlcpy(_new->nick, tempnick,NICKMAX-1);
1561 strlcpy(_new->host, params[2].c_str(),63);
1562 strlcpy(_new->dhost, params[3].c_str(),63);
1563 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1564 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1565 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1566 _new->registered = REG_ALL;
1569 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1570 _new->modes[(*v)-65] = 1;
1572 if (params[6].find_first_of(":") != std::string::npos)
1573 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1575 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1577 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1579 params[7] = ":" + params[7];
1580 DoOneToAllButSender(source,"NICK",params,source);
1582 // Increment the Source Servers User Count..
1583 TreeServer* SourceServer = FindServer(source);
1586 log(DEBUG,"Found source server of %s",_new->nick);
1587 SourceServer->AddUserCount();
1593 /* Send one or more FJOINs for a channel of users.
1594 * If the length of a single line is more than 480-NICKMAX
1595 * in length, it is split over multiple lines.
1597 void SendFJoins(TreeServer* Current, chanrec* c)
1599 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1601 std::string individual_halfops = ":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age);
1603 size_t dlen, curlen;
1604 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1606 char* ptr = list + dlen;
1608 CUList *ulist = c->GetUsers();
1609 std::vector<userrec*> specific_halfop;
1610 std::vector<userrec*> specific_voice;
1611 std::string modes = "";
1612 std::string params = "";
1614 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1616 int x = cflags(i->second,c);
1617 if ((x & UCMODE_HOP) && (x & UCMODE_OP))
1619 specific_halfop.push_back(i->second);
1621 if (((x & UCMODE_HOP) || (x & UCMODE_OP)) && (x & UCMODE_VOICE))
1623 specific_voice.push_back(i->second);
1631 else if (x & UCMODE_HOP)
1635 else if (x & UCMODE_VOICE)
1640 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s", n, i->second->nick);
1647 if (curlen > (480-NICKMAX))
1649 this->WriteLine(list);
1650 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1654 for (unsigned int y = 0; y < specific_voice.size(); y++)
1657 params.append(specific_voice[y]->nick).append(" ");
1658 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1660 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1663 params.append(specific_halfop[y]->nick).append(" ");
1664 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1670 this->WriteLine(list);
1671 for (unsigned int y = 0; y < specific_voice.size(); y++)
1674 params.append(specific_voice[y]->nick).append(" ");
1675 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1677 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1680 params.append(specific_halfop[y]->nick).append(" ");
1681 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1684 //std::string modes = "";
1685 //std::string params = "";
1686 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1689 params.append(b->data).append(" ");
1691 /* XXX: Send each channel mode and its params -- we'll need a method for this in ModeHandler? */
1692 //FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1693 this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+chanmodes(c,true)+modes+" "+params);
1696 /* Send G, Q, Z and E lines */
1697 void SendXLines(TreeServer* Current)
1700 std::string n = Srv->GetServerName();
1701 const char* sn = n.c_str();
1703 /* Yes, these arent too nice looking, but they get the job done */
1704 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++, iterations++)
1706 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);
1707 this->WriteLine(data);
1709 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++, iterations++)
1711 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);
1712 this->WriteLine(data);
1714 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++, iterations++)
1716 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);
1717 this->WriteLine(data);
1719 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++, iterations++)
1721 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);
1722 this->WriteLine(data);
1724 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++, iterations++)
1726 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);
1727 this->WriteLine(data);
1729 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++, iterations++)
1731 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);
1732 this->WriteLine(data);
1734 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++, iterations++)
1736 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);
1737 this->WriteLine(data);
1739 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++, iterations++)
1741 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);
1742 this->WriteLine(data);
1746 /* Send channel modes and topics */
1747 void SendChannelModes(TreeServer* Current)
1750 std::deque<std::string> list;
1752 std::string n = Srv->GetServerName();
1753 const char* sn = n.c_str();
1754 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
1756 SendFJoins(Current, c->second);
1757 if (*c->second->topic)
1759 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1760 this->WriteLine(data);
1762 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1764 c->second->GetExtList(list);
1765 for (unsigned int j = 0; j < list.size(); j++)
1767 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1772 /* send all users and their oper state/modes */
1773 void SendUsers(TreeServer* Current)
1776 std::deque<std::string> list;
1778 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
1780 if (u->second->registered == REG_ALL)
1782 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);
1783 this->WriteLine(data);
1784 if (*u->second->oper)
1786 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1788 if (*u->second->awaymsg)
1790 this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1792 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1794 u->second->GetExtList(list);
1795 for (unsigned int j = 0; j < list.size(); j++)
1797 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1803 /* This function is called when we want to send a netburst to a local
1804 * server. There is a set order we must do this, because for example
1805 * users require their servers to exist, and channels require their
1806 * users to exist. You get the idea.
1808 void DoBurst(TreeServer* s)
1810 std::string burst = "BURST "+ConvToStr(time(NULL));
1811 std::string endburst = "ENDBURST";
1812 // Because by the end of the netburst, it could be gone!
1813 std::string name = s->GetName();
1814 Srv->SendOpers("*** Bursting to \2"+name+"\2.");
1815 this->WriteLine(burst);
1816 /* send our version string */
1817 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1818 /* Send server tree */
1819 this->SendServers(TreeRoot,s,1);
1820 /* Send users and their oper status */
1822 /* Send everything else (channel modes, xlines etc) */
1823 this->SendChannelModes(s);
1824 this->SendXLines(s);
1825 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1826 this->WriteLine(endburst);
1827 Srv->SendOpers("*** Finished bursting to \2"+name+"\2.");
1830 /* This function is called when we receive data from a remote
1831 * server. We buffer the data in a std::string (it doesnt stay
1832 * there for long), reading using InspSocket::Read() which can
1833 * read up to 16 kilobytes in one operation.
1835 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1836 * THE SOCKET OBJECT FOR US.
1838 virtual bool OnDataReady()
1840 char* data = this->Read();
1841 /* Check that the data read is a valid pointer and it has some content */
1844 this->in_buffer.append(data);
1845 /* While there is at least one new line in the buffer,
1846 * do something useful (we hope!) with it.
1848 while (in_buffer.find("\n") != std::string::npos)
1850 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1851 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1852 if (ret.find("\r") != std::string::npos)
1853 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1854 /* Process this one, abort if it
1855 * didnt return true.
1861 memset(result,0,1024);
1863 log(DEBUG,"Original string '%s'",ret.c_str());
1864 /* ERROR + CAPAB is still allowed unencryped */
1865 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1867 int nbytes = from64tobits(out, ret.c_str(), 1024);
1868 if ((nbytes > 0) && (nbytes < 1024))
1870 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1871 ctx_in->Decrypt(out, result, nbytes, 0);
1872 for (int t = 0; t < nbytes; t++)
1873 if (result[t] == '\7') result[t] = 0;
1878 if (!this->ProcessLine(ret))
1880 log(DEBUG,"ProcessLine says no!");
1886 /* EAGAIN returns an empty but non-NULL string, so this
1887 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1889 return (data && !*data);
1892 int WriteLine(std::string line)
1894 log(DEBUG,"OUT: %s",line.c_str());
1898 char result64[10240];
1899 if (this->keylength)
1901 // pad it to the key length
1902 int n = this->keylength - (line.length() % this->keylength);
1905 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);
1906 line.append(n,'\7');
1909 unsigned int ll = line.length();
1910 ctx_out->Encrypt(line.c_str(), result, ll, 0);
1911 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1913 //int from64tobits(char *out, const char *in, int maxlen);
1915 return this->Write(line + "\r\n");
1918 /* Handle ERROR command */
1919 bool Error(std::deque<std::string> ¶ms)
1921 if (params.size() < 1)
1923 WriteOpers("*** ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1924 /* we will return false to cause the socket to close. */
1928 bool Stats(std::string prefix, std::deque<std::string> ¶ms)
1930 /* Get the reply to a STATS query if it matches this servername,
1931 * and send it back as a load of PUSH queries
1933 if (params.size() > 1)
1935 if (Srv->MatchText(Srv->GetServerName(), params[1]))
1937 /* It's for our server */
1938 string_list results;
1939 userrec* source = Srv->FindNick(prefix);
1942 std::deque<std::string> par;
1943 par.push_back(prefix);
1945 DoStats(*(params[0].c_str()), source, results);
1946 for (size_t i = 0; i < results.size(); i++)
1948 par[1] = "::" + results[i];
1949 DoOneToOne(Srv->GetServerName(), "PUSH",par, source->server);
1956 userrec* source = Srv->FindNick(prefix);
1958 DoOneToOne(prefix, "STATS", params, params[1]);
1965 /* Because the core won't let users or even SERVERS set +o,
1966 * we use the OPERTYPE command to do this.
1968 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1970 if (params.size() != 1)
1972 log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
1975 std::string opertype = params[0];
1976 userrec* u = Srv->FindNick(prefix);
1979 u->modes[UM_OPERATOR] = 1;
1980 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1981 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1986 /* Because Andy insists that services-compatible servers must
1987 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1989 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1991 if (params.size() < 3)
1994 userrec* u = Srv->FindNick(params[0]);
1998 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2001 std::deque<std::string> par;
2002 par.push_back(params[1]);
2003 /* This is not required as one is sent in OnUserPostNick below
2005 //DoOneToMany(u->nick,"NICK",par);
2006 if (!u->ForceNickChange(params[1].c_str()))
2008 userrec::QuitUser(u, "Nickname collision");
2011 u->age = atoi(params[2].c_str());
2017 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
2019 if (params.size() < 2)
2022 userrec* u = Srv->FindNick(params[0]);
2026 chanrec::JoinUser(u, params[1].c_str(), false);
2027 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2032 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
2034 if (params.size() < 1)
2037 std::string servermask = params[0];
2039 if (Srv->MatchText(Srv->GetServerName(),servermask))
2041 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
2042 Srv->RehashServer();
2043 ReadConfiguration(false);
2045 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2049 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
2051 if (params.size() != 2)
2054 std::string nick = params[0];
2055 userrec* u = Srv->FindNick(prefix);
2056 userrec* who = Srv->FindNick(nick);
2060 /* Prepend kill source, if we don't have one */
2061 std::string sourceserv = prefix;
2064 sourceserv = u->server;
2066 if (*(params[1].c_str()) != '[')
2068 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2070 std::string reason = params[1];
2071 params[1] = ":" + params[1];
2072 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2073 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2074 userrec::QuitUser(who,reason);
2079 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
2081 if (params.size() < 1)
2084 if (params.size() == 1)
2086 TreeServer* ServerSource = FindServer(prefix);
2089 ServerSource->SetPingFlag();
2094 std::string forwardto = params[1];
2095 if (forwardto == Srv->GetServerName())
2098 * this is a PONG for us
2099 * if the prefix is a user, check theyre local, and if they are,
2100 * dump the PONG reply back to their fd. If its a server, do nowt.
2101 * Services might want to send these s->s, but we dont need to yet.
2103 userrec* u = Srv->FindNick(prefix);
2107 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2112 // not for us, pass it on :)
2113 DoOneToOne(prefix,"PONG",params,forwardto);
2120 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
2122 if (params.size() < 3)
2125 TreeServer* ServerSource = FindServer(prefix);
2129 if (params[0] == "*")
2131 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2133 else if (*(params[0].c_str()) == '#')
2135 chanrec* c = Srv->FindChannel(params[0]);
2138 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2141 else if (*(params[0].c_str()) != '#')
2143 userrec* u = Srv->FindNick(params[0]);
2146 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2151 params[2] = ":" + params[2];
2152 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2156 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
2158 if (params.size() < 1)
2161 TreeServer* ServerSource = FindServer(prefix);
2165 ServerSource->SetVersion(params[0]);
2167 params[0] = ":" + params[0];
2168 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2172 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
2174 if (params.size() < 1)
2177 userrec* u = Srv->FindNick(prefix);
2181 u->ChangeDisplayedHost(params[0].c_str());
2182 DoOneToAllButSender(prefix,"FHOST",params,u->server);
2187 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
2189 if (params.size() < 6)
2192 bool propogate = false;
2194 switch (*(params[0].c_str()))
2197 propogate = add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2198 zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2201 propogate = add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2202 qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2205 propogate = add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2206 eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2209 propogate = add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2210 gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2213 propogate = add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2216 /* Just in case... */
2217 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2222 /* Send it on its way */
2225 if (atoi(params[4].c_str()))
2227 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());
2231 WriteOpers("*** %s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2233 params[5] = ":" + params[5];
2234 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2236 if (!this->bursting)
2238 log(DEBUG,"Applying lines...");
2239 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2244 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
2246 if (params.size() < 1)
2249 userrec* u = Srv->FindNick(prefix);
2253 u->ChangeName(params[0].c_str());
2254 params[0] = ":" + params[0];
2255 DoOneToAllButSender(prefix,"FNAME",params,u->server);
2260 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
2262 if (params.size() < 1)
2265 log(DEBUG,"In IDLE command");
2266 userrec* u = Srv->FindNick(prefix);
2270 log(DEBUG,"USER EXISTS: %s",u->nick);
2271 // an incoming request
2272 if (params.size() == 1)
2274 userrec* x = Srv->FindNick(params[0]);
2275 if ((x) && (IS_LOCAL(x)))
2277 userrec* x = Srv->FindNick(params[0]);
2278 log(DEBUG,"Got IDLE");
2279 char signon[MAXBUF];
2281 log(DEBUG,"Sending back IDLE 3");
2282 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2283 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2284 std::deque<std::string> par;
2285 par.push_back(prefix);
2286 par.push_back(signon);
2287 par.push_back(idle);
2288 // ours, we're done, pass it BACK
2289 DoOneToOne(params[0],"IDLE",par,u->server);
2293 // not ours pass it on
2294 DoOneToOne(prefix,"IDLE",params,x->server);
2297 else if (params.size() == 3)
2299 std::string who_did_the_whois = params[0];
2300 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
2301 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2303 log(DEBUG,"Got final IDLE");
2304 // an incoming reply to a whois we sent out
2305 std::string nick_whoised = prefix;
2306 unsigned long signon = atoi(params[1].c_str());
2307 unsigned long idle = atoi(params[2].c_str());
2308 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2309 do_whois(who_to_send_to,u,signon,idle,nick_whoised.c_str());
2313 // not ours, pass it on
2314 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2321 bool Push(std::string prefix, std::deque<std::string> ¶ms)
2323 if (params.size() < 2)
2326 userrec* u = Srv->FindNick(params[0]);
2333 u->Write(params[1]);
2337 // continue the raw onwards
2338 params[1] = ":" + params[1];
2339 DoOneToOne(prefix,"PUSH",params,u->server);
2344 bool Time(std::string prefix, std::deque<std::string> ¶ms)
2346 // :source.server TIME remote.server sendernick
2347 // :remote.server TIME source.server sendernick TS
2348 if (params.size() == 2)
2350 // someone querying our time?
2351 if (Srv->GetServerName() == params[0])
2353 userrec* u = Srv->FindNick(params[1]);
2357 snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2358 params.push_back(curtime);
2360 DoOneToOne(Srv->GetServerName(),"TIME",params,params[0]);
2365 // not us, pass it on
2366 userrec* u = Srv->FindNick(params[1]);
2368 DoOneToOne(prefix,"TIME",params,params[0]);
2371 else if (params.size() == 3)
2373 // a response to a previous TIME
2374 userrec* u = Srv->FindNick(params[1]);
2375 if ((u) && (IS_LOCAL(u)))
2377 time_t rawtime = atol(params[2].c_str());
2378 struct tm * timeinfo;
2379 timeinfo = localtime(&rawtime);
2381 snprintf(tms,26,"%s",asctime(timeinfo));
2383 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2388 DoOneToOne(prefix,"TIME",params,u->server);
2394 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
2396 if (params.size() < 1)
2399 if (params.size() == 1)
2401 std::string stufftobounce = params[0];
2402 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
2407 std::string forwardto = params[1];
2408 if (forwardto == Srv->GetServerName())
2410 // this is a ping for us, send back PONG to the requesting server
2411 params[1] = params[0];
2412 params[0] = forwardto;
2413 DoOneToOne(forwardto,"PONG",params,params[1]);
2417 // not for us, pass it on :)
2418 DoOneToOne(prefix,"PING",params,forwardto);
2424 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
2426 if (params.size() < 4)
2429 std::string servername = params[0];
2430 std::string password = params[1];
2431 // hopcount is not used for a remote server, we calculate this ourselves
2432 std::string description = params[3];
2433 TreeServer* ParentOfThis = FindServer(prefix);
2437 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2440 TreeServer* CheckDupe = FindServer(servername);
2443 this->WriteLine("ERROR :Server "+servername+" already exists!");
2444 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists");
2447 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
2448 ParentOfThis->AddChild(Node);
2449 params[3] = ":" + params[3];
2450 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2451 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2455 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2457 if (params.size() < 4)
2460 irc::string servername = params[0].c_str();
2461 std::string sname = params[0];
2462 std::string password = params[1];
2463 int hops = atoi(params[2].c_str());
2467 this->WriteLine("ERROR :Server too far away for authentication");
2468 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2471 std::string description = params[3];
2472 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2474 if ((x->Name == servername) && (x->RecvPass == password))
2476 TreeServer* CheckDupe = FindServer(sname);
2479 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2480 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2483 // Begin the sync here. this kickstarts the
2484 // other side, waiting in WAIT_AUTH_2 state,
2485 // into starting their burst, as it shows
2486 // that we're happy.
2487 this->LinkState = CONNECTED;
2488 // we should add the details of this server now
2489 // to the servers tree, as a child of the root
2491 TreeServer* Node = new TreeServer(sname,description,TreeRoot,this);
2492 TreeRoot->AddChild(Node);
2493 params[3] = ":" + params[3];
2494 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2495 this->bursting = true;
2496 this->DoBurst(Node);
2500 this->WriteLine("ERROR :Invalid credentials");
2501 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2505 bool Inbound_Server(std::deque<std::string> ¶ms)
2507 if (params.size() < 4)
2510 irc::string servername = params[0].c_str();
2511 std::string sname = params[0];
2512 std::string password = params[1];
2513 int hops = atoi(params[2].c_str());
2517 this->WriteLine("ERROR :Server too far away for authentication");
2518 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2521 std::string description = params[3];
2522 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2524 if ((x->Name == servername) && (x->RecvPass == password))
2526 TreeServer* CheckDupe = FindServer(sname);
2529 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2530 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2533 /* If the config says this link is encrypted, but the remote side
2534 * hasnt bothered to send the AES command before SERVER, then we
2535 * boot them off as we MUST have this connection encrypted.
2537 if ((x->EncryptionKey != "") && (!this->ctx_in))
2539 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2540 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2543 Srv->SendOpers("*** Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2544 this->InboundServerName = sname;
2545 this->InboundDescription = description;
2546 // this is good. Send our details: Our server name and description and hopcount of 0,
2547 // along with the sendpass from this block.
2548 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
2549 // move to the next state, we are now waiting for THEM.
2550 this->LinkState = WAIT_AUTH_2;
2554 this->WriteLine("ERROR :Invalid credentials");
2555 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2559 void Split(std::string line, std::deque<std::string> &n)
2562 irc::tokenstream tokens(line);
2564 while ((param = tokens.GetToken()) != "")
2569 bool ProcessLine(std::string line)
2571 std::deque<std::string> params;
2572 irc::string command;
2578 line = line.substr(0, line.find_first_of("\r\n"));
2580 log(DEBUG,"IN: %s", line.c_str());
2582 this->Split(line.c_str(),params);
2584 if ((params[0][0] == ':') && (params.size() > 1))
2586 prefix = params[0].substr(1);
2590 command = params[0].c_str();
2593 if ((!this->ctx_in) && (command == "AES"))
2595 std::string sserv = params[0];
2596 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2598 if ((x->EncryptionKey != "") && (x->Name == sserv))
2600 this->InitAES(x->EncryptionKey,sserv);
2606 else if ((this->ctx_in) && (command == "AES"))
2608 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2611 switch (this->LinkState)
2616 // Waiting for SERVER command from remote server. Server initiating
2617 // the connection sends the first SERVER command, listening server
2618 // replies with theirs if its happy, then if the initiator is happy,
2619 // it starts to send its net sync, which starts the merge, otherwise
2620 // it sends an ERROR.
2621 if (command == "PASS")
2623 /* Silently ignored */
2625 else if (command == "SERVER")
2627 return this->Inbound_Server(params);
2629 else if (command == "ERROR")
2631 return this->Error(params);
2633 else if (command == "USER")
2635 this->WriteLine("ERROR :Client connections to this port are prohibited.");
2638 else if (command == "CAPAB")
2640 return this->Capab(params);
2642 else if ((command == "U") || (command == "S"))
2644 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2649 this->WriteLine("ERROR :Invalid command in negotiation phase.");
2654 // Waiting for start of other side's netmerge to say they liked our
2656 if (command == "SERVER")
2658 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2662 else if ((command == "U") || (command == "S"))
2664 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2667 else if (command == "BURST")
2671 /* If a time stamp is provided, try and check syncronization */
2672 time_t THEM = atoi(params[0].c_str());
2673 long delta = THEM-time(NULL);
2674 if ((delta < -600) || (delta > 600))
2676 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));
2677 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2680 else if ((delta < -60) || (delta > 60))
2682 WriteOpers("*** \2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2685 this->LinkState = CONNECTED;
2686 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
2687 TreeRoot->AddChild(Node);
2689 params.push_back(InboundServerName);
2690 params.push_back("*");
2691 params.push_back("1");
2692 params.push_back(":"+InboundDescription);
2693 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2694 this->bursting = true;
2695 this->DoBurst(Node);
2697 else if (command == "ERROR")
2699 return this->Error(params);
2701 else if (command == "CAPAB")
2703 return this->Capab(params);
2708 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2712 if (command == "SERVER")
2714 // another server we connected to, which was in WAIT_AUTH_1 state,
2715 // has just sent us their credentials. If we get this far, theyre
2716 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2717 // if we're happy with this, we should send our netburst which
2718 // kickstarts the merge.
2719 return this->Outbound_Reply_Server(params);
2721 else if (command == "ERROR")
2723 return this->Error(params);
2727 // This is the 'authenticated' state, when all passwords
2728 // have been exchanged and anything past this point is taken
2733 std::string direction = prefix;
2734 userrec* t = Srv->FindNick(prefix);
2737 direction = t->server;
2739 TreeServer* route_back_again = BestRouteTo(direction);
2740 if ((!route_back_again) || (route_back_again->GetSocket() != this))
2742 if (route_back_again)
2743 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2748 * When there is activity on the socket, reset the ping counter so
2749 * that we're not wasting bandwidth pinging an active server.
2751 route_back_again->SetNextPingTime(time(NULL) + 120);
2752 route_back_again->SetPingFlag();
2755 if (command == "SVSMODE")
2757 /* Services expects us to implement
2758 * SVSMODE. In inspircd its the same as
2763 std::string target = "";
2764 /* Yes, know, this is a mess. Its reasonably fast though as we're
2765 * working with std::string here.
2767 if ((command == "NICK") && (params.size() > 1))
2769 return this->IntroduceClient(prefix,params);
2771 else if (command == "FJOIN")
2773 return this->ForceJoin(prefix,params);
2775 else if (command == "STATS")
2777 return this->Stats(prefix, params);
2779 else if (command == "SERVER")
2781 return this->RemoteServer(prefix,params);
2783 else if (command == "ERROR")
2785 return this->Error(params);
2787 else if (command == "OPERTYPE")
2789 return this->OperType(prefix,params);
2791 else if (command == "FMODE")
2793 return this->ForceMode(prefix,params);
2795 else if (command == "KILL")
2797 return this->RemoteKill(prefix,params);
2799 else if (command == "FTOPIC")
2801 return this->ForceTopic(prefix,params);
2803 else if (command == "REHASH")
2805 return this->RemoteRehash(prefix,params);
2807 else if (command == "METADATA")
2809 return this->MetaData(prefix,params);
2811 else if (command == "PING")
2814 * We just got a ping from a server that's bursting.
2815 * This can't be right, so set them to not bursting, and
2816 * apply their lines.
2820 this->bursting = false;
2821 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2825 prefix = this->GetName();
2827 return this->LocalPing(prefix,params);
2829 else if (command == "PONG")
2832 * We just got a pong from a server that's bursting.
2833 * This can't be right, so set them to not bursting, and
2834 * apply their lines.
2838 this->bursting = false;
2839 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2843 prefix = this->GetName();
2845 return this->LocalPong(prefix,params);
2847 else if (command == "VERSION")
2849 return this->ServerVersion(prefix,params);
2851 else if (command == "FHOST")
2853 return this->ChangeHost(prefix,params);
2855 else if (command == "FNAME")
2857 return this->ChangeName(prefix,params);
2859 else if (command == "ADDLINE")
2861 return this->AddLine(prefix,params);
2863 else if (command == "SVSNICK")
2867 prefix = this->GetName();
2869 return this->ForceNick(prefix,params);
2871 else if (command == "IDLE")
2873 return this->Whois(prefix,params);
2875 else if (command == "PUSH")
2877 return this->Push(prefix,params);
2879 else if (command == "TIME")
2881 return this->Time(prefix,params);
2883 else if ((command == "KICK") && (IsServer(prefix)))
2885 std::string sourceserv = this->myhost;
2886 if (params.size() == 3)
2888 userrec* user = Srv->FindNick(params[1]);
2889 chanrec* chan = Srv->FindChannel(params[0]);
2892 if (!chan->ServerKickUser(user, params[2].c_str(), false))
2893 /* Yikes, the channels gone! */
2897 if (this->InboundServerName != "")
2899 sourceserv = this->InboundServerName;
2901 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2903 else if (command == "SVSJOIN")
2907 prefix = this->GetName();
2909 return this->ServiceJoin(prefix,params);
2911 else if (command == "SQUIT")
2913 if (params.size() == 2)
2915 this->Squit(FindServer(params[0]),params[1]);
2919 else if (command == "ENDBURST")
2921 this->bursting = false;
2922 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2923 std::string sourceserv = this->myhost;
2924 if (this->InboundServerName != "")
2926 sourceserv = this->InboundServerName;
2928 WriteOpers("*** Received end of netburst from \2%s\2",sourceserv.c_str());
2933 // not a special inter-server command.
2934 // Emulate the actual user doing the command,
2935 // this saves us having a huge ugly parser.
2936 userrec* who = Srv->FindNick(prefix);
2937 std::string sourceserv = this->myhost;
2938 if (this->InboundServerName != "")
2940 sourceserv = this->InboundServerName;
2944 if ((command == "NICK") && (params.size() > 0))
2946 /* On nick messages, check that the nick doesnt
2947 * already exist here. If it does, kill their copy,
2950 userrec* x = Srv->FindNick(params[0]);
2951 if ((x) && (x != who))
2953 std::deque<std::string> p;
2954 p.push_back(params[0]);
2955 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2956 DoOneToMany(Srv->GetServerName(),"KILL",p);
2958 p.push_back(prefix);
2959 p.push_back("Nickname collision");
2960 DoOneToMany(Srv->GetServerName(),"KILL",p);
2961 userrec::QuitUser(x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2962 userrec* y = Srv->FindNick(prefix);
2965 userrec::QuitUser(y,"Nickname collision");
2967 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2971 target = who->server;
2972 const char* strparams[127];
2973 for (unsigned int q = 0; q < params.size(); q++)
2975 strparams[q] = params[q].c_str();
2977 if (!Srv->CallCommandHandler(command.c_str(), strparams, params.size(), who))
2979 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
2985 // its not a user. Its either a server, or somethings screwed up.
2986 if (IsServer(prefix))
2988 target = Srv->GetServerName();
2992 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2996 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3005 virtual std::string GetName()
3007 std::string sourceserv = this->myhost;
3008 if (this->InboundServerName != "")
3010 sourceserv = this->InboundServerName;
3015 virtual void OnTimeout()
3017 if (this->LinkState == CONNECTING)
3019 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
3023 virtual void OnClose()
3025 // Connection closed.
3026 // If the connection is fully up (state CONNECTED)
3027 // then propogate a netsplit to all peers.
3028 std::string quitserver = this->myhost;
3029 if (this->InboundServerName != "")
3031 quitserver = this->InboundServerName;
3033 TreeServer* s = FindServer(quitserver);
3036 Squit(s,"Remote host closed the connection");
3038 WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
3041 virtual int OnIncomingConnection(int newsock, char* ip)
3043 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3044 * or discovering if this port is the server port, we don't allow connections from any
3045 * IPs for which we don't have a link block.
3049 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3052 for (vector<std::string>::iterator i = ValidIPs.begin(); i != ValidIPs.end(); i++)
3053 if (MatchCIDR(ip, (*i).c_str()))
3058 WriteOpers("Server connection from %s denied (no link blocks with that IP address)", ip);
3063 TreeSocket* s = new TreeSocket(this->Instance, newsock, ip);
3069 /** This class is used to resolve server hostnames during /connect and autoconnect.
3070 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3071 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3072 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3073 * will have an IP address which we can then use to continue our connection.
3075 class ServernameResolver : public Resolver
3078 /** A copy of the Link tag info for what we're connecting to.
3079 * We take a copy, rather than using a pointer, just in case the
3080 * admin takes the tag away and rehashes while the domain is resolving.
3084 ServernameResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3086 /* Nothing in here, folks */
3089 void OnLookupComplete(const std::string &result)
3091 /* Initiate the connection, now that we have an IP to use.
3092 * Passing a hostname directly to InspSocket causes it to
3093 * just bail and set its FD to -1.
3095 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3096 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3098 TreeSocket* newsocket = new TreeSocket(ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str());
3099 if (newsocket->GetFd() > -1)
3102 Srv->AddSocket(newsocket);
3106 /* Something barfed, show the opers */
3107 WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3113 void OnError(ResolverError e, const std::string &errormessage)
3116 WriteOpers("*** CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3120 class SecurityIPResolver : public Resolver
3125 SecurityIPResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3129 void OnLookupComplete(const std::string &result)
3131 log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3132 ValidIPs.push_back(result);
3135 void OnError(ResolverError e, const std::string &errormessage)
3137 log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3141 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3143 for (unsigned int c = 0; c < list.size(); c++)
3145 if (list[c] == server)
3150 list.push_back(server);
3153 // returns a list of DIRECT servernames for a specific channel
3154 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3156 CUList *ulist = c->GetUsers();
3157 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3159 if (i->second->fd < 0)
3161 TreeServer* best = BestRouteTo(i->second->server);
3163 AddThisServer(best,list);
3169 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms)
3171 TreeServer* omitroute = BestRouteTo(omit);
3172 if ((command == "NOTICE") || (command == "PRIVMSG"))
3174 if (params.size() >= 2)
3177 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3179 params[0] = params[0].substr(1, params[0].length()-1);
3181 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3183 // special routing for private messages/notices
3184 userrec* d = Srv->FindNick(params[0]);
3187 std::deque<std::string> par;
3188 par.push_back(params[0]);
3189 par.push_back(":"+params[1]);
3190 DoOneToOne(prefix,command.c_str(),par,d->server);
3194 else if (*(params[0].c_str()) == '$')
3196 std::deque<std::string> par;
3197 par.push_back(params[0]);
3198 par.push_back(":"+params[1]);
3199 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3204 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3205 chanrec* c = Srv->FindChannel(params[0]);
3208 std::deque<TreeServer*> list;
3209 GetListOfServersForChannel(c,list);
3210 log(DEBUG,"Got a list of %d servers",list.size());
3211 unsigned int lsize = list.size();
3212 for (unsigned int i = 0; i < lsize; i++)
3214 TreeSocket* Sock = list[i]->GetSocket();
3215 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3217 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3218 Sock->WriteLine(data);
3226 unsigned int items = TreeRoot->ChildCount();
3227 for (unsigned int x = 0; x < items; x++)
3229 TreeServer* Route = TreeRoot->GetChild(x);
3230 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3232 TreeSocket* Sock = Route->GetSocket();
3233 Sock->WriteLine(data);
3239 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
3241 TreeServer* omitroute = BestRouteTo(omit);
3242 std::string FullLine = ":" + prefix + " " + command;
3243 unsigned int words = params.size();
3244 for (unsigned int x = 0; x < words; x++)
3246 FullLine = FullLine + " " + params[x];
3248 unsigned int items = TreeRoot->ChildCount();
3249 for (unsigned int x = 0; x < items; x++)
3251 TreeServer* Route = TreeRoot->GetChild(x);
3252 // Send the line IF:
3253 // The route has a socket (its a direct connection)
3254 // The route isnt the one to be omitted
3255 // The route isnt the path to the one to be omitted
3256 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3258 TreeSocket* Sock = Route->GetSocket();
3259 Sock->WriteLine(FullLine);
3265 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
3267 std::string FullLine = ":" + prefix + " " + command;
3268 unsigned int words = params.size();
3269 for (unsigned int x = 0; x < words; x++)
3271 FullLine = FullLine + " " + params[x];
3273 unsigned int items = TreeRoot->ChildCount();
3274 for (unsigned int x = 0; x < items; x++)
3276 TreeServer* Route = TreeRoot->GetChild(x);
3277 if (Route->GetSocket())
3279 TreeSocket* Sock = Route->GetSocket();
3280 Sock->WriteLine(FullLine);
3286 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
3288 TreeServer* Route = BestRouteTo(target);
3291 std::string FullLine = ":" + prefix + " " + command;
3292 unsigned int words = params.size();
3293 for (unsigned int x = 0; x < words; x++)
3295 FullLine = FullLine + " " + params[x];
3297 if (Route->GetSocket())
3299 TreeSocket* Sock = Route->GetSocket();
3300 Sock->WriteLine(FullLine);
3310 std::vector<TreeSocket*> Bindings;
3312 void ReadConfiguration(bool rebind)
3314 Conf = new ConfigReader;
3317 for (int j =0; j < Conf->Enumerate("bind"); j++)
3319 std::string Type = Conf->ReadValue("bind","type",j);
3320 std::string IP = Conf->ReadValue("bind","address",j);
3321 long Port = Conf->ReadInteger("bind","port",j,true);
3322 if (Type == "servers")
3328 TreeSocket* listener = new TreeSocket(ServerInstance, IP.c_str(),Port,true,10);
3329 if (listener->GetState() == I_LISTENING)
3331 Srv->AddSocket(listener);
3332 Bindings.push_back(listener);
3336 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3343 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3344 HideULines = Conf->ReadFlag("options","hideulines",0);
3347 for (int j =0; j < Conf->Enumerate("link"); j++)
3350 std::string Allow = Conf->ReadValue("link","allowmask",j);
3351 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3352 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3353 L.Port = Conf->ReadInteger("link","port",j,true);
3354 L.SendPass = Conf->ReadValue("link","sendpass",j);
3355 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3356 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3357 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
3358 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3359 L.NextConnectTime = time(NULL) + L.AutoConnect;
3360 /* Bugfix by brain, do not allow people to enter bad configurations */
3361 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3363 ValidIPs.push_back(L.IPAddr);
3366 ValidIPs.push_back(Allow);
3368 /* Needs resolving */
3370 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3374 SecurityIPResolver* sr = new SecurityIPResolver(L.IPAddr, L);
3375 Srv->AddResolver(sr);
3377 catch (ModuleException& e)
3379 log(DEBUG,"Error in resolver: %s",e.GetReason());
3383 LinkBlocks.push_back(L);
3384 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3390 log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3392 else if (L.RecvPass == "")
3394 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3396 else if (L.SendPass == "")
3398 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3400 else if (L.Name == "")
3402 log(DEFAULT,"Invalid configuration, link tag without a name!");
3406 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3414 class ModuleSpanningTree : public Module
3416 std::vector<TreeSocket*> Bindings;
3419 unsigned int max_local;
3420 unsigned int max_global;
3421 cmd_rconnect* command_rconnect;
3425 ModuleSpanningTree(Server* Me)
3426 : Module::Module(Me), max_local(0), max_global(0)
3431 // Create the root of the tree
3432 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
3434 ReadConfiguration(true);
3436 command_rconnect = new cmd_rconnect(this);
3437 Srv->AddCommand(command_rconnect);
3440 void ShowLinks(TreeServer* Current, userrec* user, int hops)
3442 std::string Parent = TreeRoot->GetName();
3443 if (Current->GetParent())
3445 Parent = Current->GetParent()->GetName();
3447 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3449 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3453 ShowLinks(Current->GetChild(q),user,hops+1);
3458 ShowLinks(Current->GetChild(q),user,hops+1);
3461 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3462 if ((HideULines) && (Srv->IsUlined(Current->GetName())) && (!*user->oper))
3464 user->WriteServ("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());
3467 int CountLocalServs()
3469 return TreeRoot->ChildCount();
3474 return serverlist.size();
3477 void HandleLinks(const char** parameters, int pcnt, userrec* user)
3479 ShowLinks(TreeRoot,user,0);
3480 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
3484 void HandleLusers(const char** parameters, int pcnt, userrec* user)
3486 unsigned int n_users = usercnt();
3488 /* Only update these when someone wants to see them, more efficient */
3489 if ((unsigned int)local_count() > max_local)
3490 max_local = local_count();
3491 if (n_users > max_global)
3492 max_global = n_users;
3494 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-usercount_invisible(),usercount_invisible(),this->CountServs());
3495 if (usercount_opers())
3496 user->WriteServ("252 %s %d :operator(s) online",user->nick,usercount_opers());
3497 if (usercount_unknown())
3498 user->WriteServ("253 %s %d :unknown connections",user->nick,usercount_unknown());
3500 user->WriteServ("254 %s %d :channels formed",user->nick,chancount());
3501 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
3502 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,local_count(),max_local);
3503 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
3507 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3509 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3513 for (int t = 0; t < depth; t++)
3515 matrix[line][t] = ' ';
3518 // For Aligning, we need to work out exactly how deep this thing is, and produce
3519 // a 'Spacer' String to compensate.
3522 memset(spacer,' ',40);
3523 if ((40 - Current->GetName().length() - depth) > 1) {
3524 spacer[40 - Current->GetName().length() - depth] = '\0';
3533 if (ServerInstance->clientlist.size() == 0) {
3534 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3539 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
3541 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3542 totusers += Current->GetUserCount();
3544 strlcpy(&matrix[line][depth],text,80);
3546 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3548 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3552 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3557 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3563 int HandleStats(const char** parameters, int pcnt, userrec* user)
3567 /* Remote STATS, the server is within the 2nd parameter */
3568 std::deque<std::string> params;
3569 params.push_back(parameters[0]);
3570 params.push_back(parameters[1]);
3571 /* Send it out remotely, generate no reply yet */
3572 TreeServer* s = FindServerMask(parameters[1]);
3575 params[1] = s->GetName();
3576 DoOneToOne(user->nick, "STATS", params, s->GetName());
3580 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3587 // Ok, prepare to be confused.
3588 // After much mulling over how to approach this, it struck me that
3589 // the 'usual' way of doing a /MAP isnt the best way. Instead of
3590 // keeping track of a ton of ascii characters, and line by line
3591 // under recursion working out where to place them using multiplications
3592 // and divisons, we instead render the map onto a backplane of characters
3593 // (a character matrix), then draw the branches as a series of "L" shapes
3594 // from the nodes. This is not only friendlier on CPU it uses less stack.
3596 void HandleMap(const char** parameters, int pcnt, userrec* user)
3598 // This array represents a virtual screen which we will
3599 // "scratch" draw to, as the console device of an irc
3600 // client does not provide for a proper terminal.
3602 float totservers = 0;
3603 char matrix[128][80];
3604 for (unsigned int t = 0; t < 128; t++)
3606 matrix[t][0] = '\0';
3609 // The only recursive bit is called here.
3610 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3611 // Process each line one by one. The algorithm has a limit of
3612 // 128 servers (which is far more than a spanning tree should have
3613 // anyway, so we're ok). This limit can be raised simply by making
3614 // the character matrix deeper, 128 rows taking 10k of memory.
3615 for (int l = 1; l < line; l++)
3617 // scan across the line looking for the start of the
3618 // servername (the recursive part of the algorithm has placed
3619 // the servers at indented positions depending on what they
3621 int first_nonspace = 0;
3622 while (matrix[l][first_nonspace] == ' ')
3627 // Draw the `- (corner) section: this may be overwritten by
3628 // another L shape passing along the same vertical pane, becoming
3629 // a |- (branch) section instead.
3630 matrix[l][first_nonspace] = '-';
3631 matrix[l][first_nonspace-1] = '`';
3633 // Draw upwards until we hit the parent server, causing possibly
3634 // other corners (`-) to become branches (|-)
3635 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3637 matrix[l2][first_nonspace-1] = '|';
3641 // dump the whole lot to the user. This is the easy bit, honest.
3642 for (int t = 0; t < line; t++)
3644 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
3646 float avg_users = totusers / totservers;
3647 user->WriteServ("270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
3648 user->WriteServ("007 %s :End of /MAP",user->nick);
3652 int HandleSquit(const char** parameters, int pcnt, userrec* user)
3654 TreeServer* s = FindServerMask(parameters[0]);
3659 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3662 TreeSocket* sock = s->GetSocket();
3665 log(DEBUG,"Splitting server %s",s->GetName().c_str());
3666 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3667 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3668 Srv->RemoveSocket(sock);
3672 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3677 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3682 int HandleTime(const char** parameters, int pcnt, userrec* user)
3684 if ((IS_LOCAL(user)) && (pcnt))
3686 TreeServer* found = FindServerMask(parameters[0]);
3689 // we dont' override for local server
3690 if (found == TreeRoot)
3693 std::deque<std::string> params;
3694 params.push_back(found->GetName());
3695 params.push_back(user->nick);
3696 DoOneToOne(Srv->GetServerName(),"TIME",params,found->GetName());
3700 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
3706 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3708 if ((IS_LOCAL(user)) && (pcnt > 1))
3710 userrec* remote = Srv->FindNick(parameters[1]);
3711 if ((remote) && (remote->fd < 0))
3713 std::deque<std::string> params;
3714 params.push_back(parameters[1]);
3715 DoOneToOne(user->nick,"IDLE",params,remote->server);
3720 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
3721 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
3728 void DoPingChecks(time_t curtime)
3730 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
3732 TreeServer* serv = TreeRoot->GetChild(j);
3733 TreeSocket* sock = serv->GetSocket();
3736 if (curtime >= serv->NextPingTime())
3738 if (serv->AnsweredLastPing())
3740 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
3741 serv->SetNextPingTime(curtime + 120);
3745 // they didnt answer, boot them
3746 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
3747 sock->Squit(serv,"Ping timeout");
3748 Srv->RemoveSocket(sock);
3756 void AutoConnectServers(time_t curtime)
3758 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3760 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
3762 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
3763 x->NextConnectTime = curtime + x->AutoConnect;
3764 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3767 // an autoconnected server is not connected. Check if its time to connect it
3768 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
3772 /* Do we already have an IP? If so, no need to resolve it. */
3773 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3775 TreeSocket* newsocket = new TreeSocket(ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str());
3776 if (newsocket->GetFd() > -1)
3778 Srv->AddSocket(newsocket);
3782 WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3790 ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3791 Srv->AddResolver(snr);
3793 catch (ModuleException& e)
3795 log(DEBUG,"Error in resolver: %s",e.GetReason());
3804 int HandleVersion(const char** parameters, int pcnt, userrec* user)
3806 // we've already checked if pcnt > 0, so this is safe
3807 TreeServer* found = FindServerMask(parameters[0]);
3810 std::string Version = found->GetVersion();
3811 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
3812 if (found == TreeRoot)
3814 std::stringstream out(ServerInstance->Config->data005);
3815 std::string token = "";
3816 std::string line5 = "";
3817 int token_counter = 0;
3822 line5 = line5 + token + " ";
3825 if ((token_counter >= 13) || (out.eof() == true))
3827 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
3836 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
3841 int HandleConnect(const char** parameters, int pcnt, userrec* user)
3843 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3845 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
3847 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3850 user->WriteServ("NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
3853 /* Do we already have an IP? If so, no need to resolve it. */
3854 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3856 TreeSocket* newsocket = new TreeSocket(ServerInstance,x->IPAddr,x->Port,false,10,x->Name.c_str());
3857 if (newsocket->GetFd() > -1)
3859 Srv->AddSocket(newsocket);
3863 WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3871 ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3872 Srv->AddResolver(snr);
3874 catch (ModuleException& e)
3876 log(DEBUG,"Error in resolver: %s",e.GetReason());
3883 user->WriteServ("NOTICE %s :*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
3888 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
3892 virtual int OnStats(char statschar, userrec* user, string_list &results)
3894 if (statschar == 'c')
3896 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
3898 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');
3899 results.push_back(Srv->GetServerName()+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
3901 results.push_back(Srv->GetServerName()+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
3902 WriteOpers("*** Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,ServerInstance->Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
3908 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
3910 /* If the command doesnt appear to be valid, we dont want to mess with it. */
3914 if (command == "CONNECT")
3916 return this->HandleConnect(parameters,pcnt,user);
3918 else if (command == "STATS")
3920 return this->HandleStats(parameters,pcnt,user);
3922 else if (command == "SQUIT")
3924 return this->HandleSquit(parameters,pcnt,user);
3926 else if (command == "MAP")
3928 this->HandleMap(parameters,pcnt,user);
3931 else if ((command == "TIME") && (pcnt > 0))
3933 return this->HandleTime(parameters,pcnt,user);
3935 else if (command == "LUSERS")
3937 this->HandleLusers(parameters,pcnt,user);
3940 else if (command == "LINKS")
3942 this->HandleLinks(parameters,pcnt,user);
3945 else if (command == "WHOIS")
3950 return this->HandleRemoteWhois(parameters,pcnt,user);
3953 else if ((command == "VERSION") && (pcnt > 0))
3955 this->HandleVersion(parameters,pcnt,user);
3958 else if (Srv->IsValidModuleCommand(command, pcnt, user))
3960 // this bit of code cleverly routes all module commands
3961 // to all remote severs *automatically* so that modules
3962 // can just handle commands locally, without having
3963 // to have any special provision in place for remote
3964 // commands and linking protocols.
3965 std::deque<std::string> params;
3967 for (int j = 0; j < pcnt; j++)
3969 if (strchr(parameters[j],' '))
3971 params.push_back(":" + std::string(parameters[j]));
3975 params.push_back(std::string(parameters[j]));
3978 log(DEBUG,"Globally route '%s'",command.c_str());
3979 DoOneToMany(user->nick,command,params);
3984 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
3986 TreeServer* s = FindServer(servername);
3989 description = s->GetDesc();
3993 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
3995 if (IS_LOCAL(source))
3997 std::deque<std::string> params;
3998 params.push_back(dest->nick);
3999 params.push_back(channel->name);
4000 DoOneToMany(source->nick,"INVITE",params);
4004 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4006 std::deque<std::string> params;
4007 params.push_back(chan->name);
4008 params.push_back(":"+topic);
4009 DoOneToMany(user->nick,"TOPIC",params);
4012 virtual void OnWallops(userrec* user, const std::string &text)
4016 std::deque<std::string> params;
4017 params.push_back(":"+text);
4018 DoOneToMany(user->nick,"WALLOPS",params);
4022 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4024 if (target_type == TYPE_USER)
4026 userrec* d = (userrec*)dest;
4027 if ((d->fd < 0) && (IS_LOCAL(user)))
4029 std::deque<std::string> params;
4031 params.push_back(d->nick);
4032 params.push_back(":"+text);
4033 DoOneToOne(user->nick,"NOTICE",params,d->server);
4036 else if (target_type == TYPE_CHANNEL)
4040 chanrec *c = (chanrec*)dest;
4041 std::string cname = c->name;
4043 cname = status + cname;
4044 std::deque<TreeServer*> list;
4045 GetListOfServersForChannel(c,list);
4046 unsigned int ucount = list.size();
4047 for (unsigned int i = 0; i < ucount; i++)
4049 TreeSocket* Sock = list[i]->GetSocket();
4051 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4055 else if (target_type == TYPE_SERVER)
4059 char* target = (char*)dest;
4060 std::deque<std::string> par;
4061 par.push_back(target);
4062 par.push_back(":"+text);
4063 DoOneToMany(user->nick,"NOTICE",par);
4068 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4070 if (target_type == TYPE_USER)
4072 // route private messages which are targetted at clients only to the server
4073 // which needs to receive them
4074 userrec* d = (userrec*)dest;
4075 if ((d->fd < 0) && (IS_LOCAL(user)))
4077 std::deque<std::string> params;
4079 params.push_back(d->nick);
4080 params.push_back(":"+text);
4081 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4084 else if (target_type == TYPE_CHANNEL)
4088 chanrec *c = (chanrec*)dest;
4089 std::string cname = c->name;
4091 cname = status + cname;
4092 std::deque<TreeServer*> list;
4093 GetListOfServersForChannel(c,list);
4094 unsigned int ucount = list.size();
4095 for (unsigned int i = 0; i < ucount; i++)
4097 TreeSocket* Sock = list[i]->GetSocket();
4099 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4103 else if (target_type == TYPE_SERVER)
4107 char* target = (char*)dest;
4108 std::deque<std::string> par;
4109 par.push_back(target);
4110 par.push_back(":"+text);
4111 DoOneToMany(user->nick,"PRIVMSG",par);
4116 virtual void OnBackgroundTimer(time_t curtime)
4118 AutoConnectServers(curtime);
4119 DoPingChecks(curtime);
4122 virtual void OnUserJoin(userrec* user, chanrec* channel)
4124 // Only do this for local users
4127 std::deque<std::string> params;
4129 params.push_back(channel->name);
4131 if (channel->GetUserCounter() > 1)
4133 // not the first in the channel
4134 DoOneToMany(user->nick,"JOIN",params);
4138 // first in the channel, set up their permissions
4139 // and the channel TS with FJOIN.
4141 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4143 params.push_back(channel->name);
4144 params.push_back(ts);
4145 params.push_back("@"+std::string(user->nick));
4146 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
4151 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4153 // only occurs for local clients
4154 if (user->registered != REG_ALL)
4156 std::deque<std::string> params;
4157 params.push_back(newhost);
4158 DoOneToMany(user->nick,"FHOST",params);
4161 virtual void OnChangeName(userrec* user, const std::string &gecos)
4163 // only occurs for local clients
4164 if (user->registered != REG_ALL)
4166 std::deque<std::string> params;
4167 params.push_back(gecos);
4168 DoOneToMany(user->nick,"FNAME",params);
4171 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4175 std::deque<std::string> params;
4176 params.push_back(channel->name);
4177 if (partmessage != "")
4178 params.push_back(":"+partmessage);
4179 DoOneToMany(user->nick,"PART",params);
4183 virtual void OnUserConnect(userrec* user)
4185 char agestr[MAXBUF];
4188 std::deque<std::string> params;
4189 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4190 params.push_back(agestr);
4191 params.push_back(user->nick);
4192 params.push_back(user->host);
4193 params.push_back(user->dhost);
4194 params.push_back(user->ident);
4195 params.push_back("+"+std::string(user->FormatModes()));
4196 params.push_back(user->GetIPString());
4197 params.push_back(":"+std::string(user->fullname));
4198 DoOneToMany(Srv->GetServerName(),"NICK",params);
4200 // User is Local, change needs to be reflected!
4201 TreeServer* SourceServer = FindServer(user->server);
4204 SourceServer->AddUserCount();
4210 virtual void OnUserQuit(userrec* user, const std::string &reason)
4212 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4214 std::deque<std::string> params;
4215 params.push_back(":"+reason);
4216 DoOneToMany(user->nick,"QUIT",params);
4218 // Regardless, We need to modify the user Counts..
4219 TreeServer* SourceServer = FindServer(user->server);
4222 SourceServer->DelUserCount();
4227 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4231 std::deque<std::string> params;
4232 params.push_back(user->nick);
4233 DoOneToMany(oldnick,"NICK",params);
4237 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4239 if ((source) && (IS_LOCAL(source)))
4241 std::deque<std::string> params;
4242 params.push_back(chan->name);
4243 params.push_back(user->nick);
4244 params.push_back(":"+reason);
4245 DoOneToMany(source->nick,"KICK",params);
4249 std::deque<std::string> params;
4250 params.push_back(chan->name);
4251 params.push_back(user->nick);
4252 params.push_back(":"+reason);
4253 DoOneToMany(Srv->GetServerName(),"KICK",params);
4257 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4259 std::deque<std::string> params;
4260 params.push_back(dest->nick);
4261 params.push_back(":"+reason);
4262 DoOneToMany(source->nick,"KILL",params);
4265 virtual void OnRehash(const std::string ¶meter)
4267 if (parameter != "")
4269 std::deque<std::string> params;
4270 params.push_back(parameter);
4271 DoOneToMany(Srv->GetServerName(),"REHASH",params);
4273 if (Srv->MatchText(Srv->GetServerName(),parameter))
4275 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
4276 Srv->RehashServer();
4279 ReadConfiguration(false);
4282 // note: the protocol does not allow direct umode +o except
4283 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4285 virtual void OnOper(userrec* user, const std::string &opertype)
4289 std::deque<std::string> params;
4290 params.push_back(opertype);
4291 DoOneToMany(user->nick,"OPERTYPE",params);
4295 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4297 if (IS_LOCAL(source))
4300 snprintf(type,8,"%cLINE",linetype);
4301 std::string stype = type;
4304 char sduration[MAXBUF];
4305 snprintf(sduration,MAXBUF,"%ld",duration);
4306 std::deque<std::string> params;
4307 params.push_back(host);
4308 params.push_back(sduration);
4309 params.push_back(":"+reason);
4310 DoOneToMany(source->nick,stype,params);
4314 std::deque<std::string> params;
4315 params.push_back(host);
4316 DoOneToMany(source->nick,stype,params);
4321 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4323 OnLine(source,hostmask,true,'G',duration,reason);
4326 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4328 OnLine(source,ipmask,true,'Z',duration,reason);
4331 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4333 OnLine(source,nickmask,true,'Q',duration,reason);
4336 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4338 OnLine(source,hostmask,true,'E',duration,reason);
4341 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4343 OnLine(source,hostmask,false,'G',0,"");
4346 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4348 OnLine(source,ipmask,false,'Z',0,"");
4351 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4353 OnLine(source,nickmask,false,'Q',0,"");
4356 virtual void OnDelELine(userrec* source, const std::string &hostmask)
4358 OnLine(source,hostmask,false,'E',0,"");
4361 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4363 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4365 if (target_type == TYPE_USER)
4367 userrec* u = (userrec*)dest;
4368 std::deque<std::string> params;
4369 params.push_back(u->nick);
4370 params.push_back(text);
4371 DoOneToMany(user->nick,"MODE",params);
4375 chanrec* c = (chanrec*)dest;
4376 std::deque<std::string> params;
4377 params.push_back(c->name);
4378 params.push_back(text);
4379 DoOneToMany(user->nick,"MODE",params);
4384 virtual void OnSetAway(userrec* user)
4388 std::deque<std::string> params;
4389 params.push_back(":"+std::string(user->awaymsg));
4390 DoOneToMany(user->nick,"AWAY",params);
4394 virtual void OnCancelAway(userrec* user)
4398 std::deque<std::string> params;
4400 DoOneToMany(user->nick,"AWAY",params);
4404 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4406 TreeSocket* s = (TreeSocket*)opaque;
4409 if (target_type == TYPE_USER)
4411 userrec* u = (userrec*)target;
4412 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4416 chanrec* c = (chanrec*)target;
4417 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4422 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4424 TreeSocket* s = (TreeSocket*)opaque;
4427 if (target_type == TYPE_USER)
4429 userrec* u = (userrec*)target;
4430 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
4432 else if (target_type == TYPE_OTHER)
4434 s->WriteLine(":"+Srv->GetServerName()+" METADATA * "+extname+" :"+extdata);
4436 else if (target_type == TYPE_CHANNEL)
4438 chanrec* c = (chanrec*)target;
4439 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
4444 virtual void OnEvent(Event* event)
4446 if (event->GetEventID() == "send_metadata")
4448 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4449 if (params->size() < 3)
4451 (*params)[2] = ":" + (*params)[2];
4452 DoOneToMany(Srv->GetServerName(),"METADATA",*params);
4454 else if (event->GetEventID() == "send_mode")
4456 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4457 if (params->size() < 2)
4459 // Insert the TS value of the object, either userrec or chanrec
4461 userrec* a = Srv->FindNick((*params)[0]);
4468 chanrec* a = Srv->FindChannel((*params)[0]);
4474 params->insert(params->begin() + 1,ConvToStr(ourTS));
4475 DoOneToMany(Srv->GetServerName(),"FMODE",*params);
4479 virtual ~ModuleSpanningTree()
4483 virtual Version GetVersion()
4485 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4488 void Implements(char* List)
4490 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4491 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4492 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4493 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4494 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4495 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4496 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4499 /* It is IMPORTANT that m_spanningtree is the last module in the chain
4500 * so that any activity it sees is FINAL, e.g. we arent going to send out
4501 * a NICK message before m_cloaking has finished putting the +x on the user,
4503 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4504 * the module call queue.
4506 Priority Prioritize()
4508 return PRIORITY_LAST;
4513 class ModuleSpanningTreeFactory : public ModuleFactory
4516 ModuleSpanningTreeFactory()
4520 ~ModuleSpanningTreeFactory()
4524 virtual Module * CreateModule(Server* Me)
4526 TreeProtocolModule = new ModuleSpanningTree(Me);
4527 return TreeProtocolModule;
4533 extern "C" void * init_module( void )
4535 return new ModuleSpanningTreeFactory;