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"
41 #include "cull_list.h"
44 #define nspace __gnu_cxx
47 * The server list in InspIRCd is maintained as two structures
48 * which hold the data in different ways. Most of the time, we
49 * want to very quicky obtain three pieces of information:
51 * (1) The information on a server
52 * (2) The information on the server we must send data through
53 * to actually REACH the server we're after
54 * (3) Potentially, the child/parent objects of this server
56 * The InspIRCd spanning protocol provides easy access to these
57 * by storing the data firstly in a recursive structure, where
58 * each item references its parent item, and a dynamic list
59 * of child items, and another structure which stores the items
60 * hashed, linearly. This means that if we want to find a server
61 * by name quickly, we can look it up in the hash, avoiding
62 * any O(n) lookups. If however, during a split or sync, we want
63 * to apply an operation to a server, and any of its child objects
64 * we can resort to recursion to walk the tree structure.
67 using irc::sockets::MatchCIDR;
69 class ModuleSpanningTree;
70 static ModuleSpanningTree* TreeProtocolModule;
72 extern InspIRCd* ServerInstance;
74 /* Any socket can have one of five states at any one time.
75 * The LISTENER state indicates a socket which is listening
76 * for connections. It cannot receive data itself, only incoming
78 * The CONNECTING state indicates an outbound socket which is
79 * waiting to be writeable.
80 * The WAIT_AUTH_1 state indicates the socket is outbound and
81 * has successfully connected, but has not yet sent and received
83 * The WAIT_AUTH_2 state indicates that the socket is inbound
84 * (allocated by a LISTENER) but has not yet sent and received
86 * The CONNECTED state represents a fully authorized, fully
89 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
91 /* Foward declarations */
95 /* This variable represents the root of the server tree
96 * (for all intents and purposes, it's us)
102 /* This hash_map holds the hash equivalent of the server
103 * tree, used for rapid linear lookups.
105 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
106 server_hash serverlist;
108 typedef nspace::hash_map<std::string, userrec*> uid_hash;
109 typedef nspace::hash_map<std::string, char*> sid_hash;
111 /* More forward declarations */
112 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
113 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
114 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
115 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms);
116 void ReadConfiguration(bool rebind);
118 /* Flatten links and /MAP for non-opers */
120 /* Hide U-Lined servers in /MAP and /LINKS */
123 /* Imported from xline.cpp for use during netburst */
124 extern std::vector<KLine> klines;
125 extern std::vector<GLine> glines;
126 extern std::vector<ZLine> zlines;
127 extern std::vector<QLine> qlines;
128 extern std::vector<ELine> elines;
129 extern std::vector<KLine> pklines;
130 extern std::vector<GLine> pglines;
131 extern std::vector<ZLine> pzlines;
132 extern std::vector<QLine> pqlines;
133 extern std::vector<ELine> pelines;
135 std::vector<std::string> ValidIPs;
137 class UserManager : public classbase
148 std::string UserToUID(userrec* user)
153 std::string UIDToUser(const std::string &UID)
158 std::string CreateAndAdd(userrec* user)
163 std::string CreateAndAdd(const std::string &servername)
168 std::string ServerToSID(const std::string &servername)
173 std::string SIDToServer(const std::string &SID)
178 userrec* FindByID(const std::string &UID)
185 /* Each server in the tree is represented by one class of
186 * type TreeServer. A locally connected TreeServer can
187 * have a class of type TreeSocket associated with it, for
188 * remote servers, the TreeSocket entry will be NULL.
189 * Each server also maintains a pointer to its parent
190 * (NULL if this server is ours, at the top of the tree)
191 * and a pointer to its "Route" (see the comments in the
192 * constructors below), and also a dynamic list of pointers
193 * to its children which can be iterated recursively
194 * if required. Creating or deleting objects of type
195 i* TreeServer automatically maintains the hash_map of
196 * TreeServer items, deleting and inserting them as they
197 * are created and destroyed.
200 class TreeServer : public classbase
202 TreeServer* Parent; /* Parent entry */
203 TreeServer* Route; /* Route entry */
204 std::vector<TreeServer*> Children; /* List of child objects */
205 irc::string ServerName; /* Server's name */
206 std::string ServerDesc; /* Server's description */
207 std::string VersionString; /* Version string or empty string */
208 int UserCount; /* Not used in this version */
209 int OperCount; /* Not used in this version */
210 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
211 time_t NextPing; /* After this time, the server should be PINGed*/
212 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
216 /* We don't use this constructor. Its a dummy, and won't cause any insertion
217 * of the TreeServer into the hash_map. See below for the two we DO use.
225 UserCount = OperCount = 0;
226 VersionString = ServerInstance->GetVersionString();
229 /* We use this constructor only to create the 'root' item, TreeRoot, which
230 * represents our own server. Therefore, it has no route, no parent, and
231 * no socket associated with it. Its version string is our own local version.
233 TreeServer(std::string Name, std::string Desc) : ServerName(Name.c_str()), ServerDesc(Desc)
237 UserCount = OperCount = 0;
238 VersionString = ServerInstance->GetVersionString();
240 Socket = NULL; /* Fix by brain */
244 /* When we create a new server, we call this constructor to initialize it.
245 * This constructor initializes the server's Route and Parent, and sets up
246 * its ping counters so that it will be pinged one minute from now.
248 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
251 UserCount = OperCount = 0;
252 this->SetNextPingTime(time(NULL) + 120);
255 /* find the 'route' for this server (e.g. the one directly connected
256 * to the local server, which we can use to reach it)
258 * In the following example, consider we have just added a TreeServer
259 * class for server G on our network, of which we are server A.
260 * To route traffic to G (marked with a *) we must send the data to
261 * B (marked with a +) so this algorithm initializes the 'Route'
262 * value to point at whichever server traffic must be routed through
263 * to get here. If we were to try this algorithm with server B,
264 * the Route pointer would point at its own object ('this').
274 * We only run this algorithm when a server is created, as
275 * the routes remain constant while ever the server exists, and
276 * do not need to be re-calculated.
280 if (Route == TreeRoot)
286 while (this->Route->GetParent() != TreeRoot)
288 this->Route = Route->GetParent();
292 /* Because recursive code is slow and takes a lot of resources,
293 * we store two representations of the server tree. The first
294 * is a recursive structure where each server references its
295 * children and its parent, which is used for netbursts and
296 * netsplits to dump the whole dataset to the other server,
297 * and the second is used for very fast lookups when routing
298 * messages and is instead a hash_map, where each item can
299 * be referenced by its server name. The AddHashEntry()
300 * call below automatically inserts each TreeServer class
301 * into the hash_map as it is created. There is a similar
302 * maintainance call in the destructor to tidy up deleted
306 this->AddHashEntry();
309 int QuitUsers(const std::string &reason)
311 log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
312 const char* reason_s = reason.c_str();
313 std::vector<userrec*> time_to_die;
314 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
316 if (!strcmp(n->second->server, this->ServerName.c_str()))
318 time_to_die.push_back(n->second);
321 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
323 userrec* a = (userrec*)*n;
324 log(DEBUG,"Kill %s fd=%d",a->nick,a->fd);
326 userrec::QuitUser(ServerInstance,a,reason_s);
328 return time_to_die.size();
331 /* This method is used to add the structure to the
332 * hash_map for linear searches. It is only called
333 * by the constructors.
337 server_hash::iterator iter;
338 iter = serverlist.find(this->ServerName.c_str());
339 if (iter == serverlist.end())
340 serverlist[this->ServerName.c_str()] = this;
343 /* This method removes the reference to this object
344 * from the hash_map which is used for linear searches.
345 * It is only called by the default destructor.
349 server_hash::iterator iter;
350 iter = serverlist.find(this->ServerName.c_str());
351 if (iter != serverlist.end())
352 serverlist.erase(iter);
355 /* These accessors etc should be pretty self-
359 TreeServer* GetRoute()
364 std::string GetName()
366 return ServerName.c_str();
369 std::string GetDesc()
374 std::string GetVersion()
376 return VersionString;
379 void SetNextPingTime(time_t t)
382 LastPingWasGood = false;
385 time_t NextPingTime()
390 bool AnsweredLastPing()
392 return LastPingWasGood;
397 LastPingWasGood = true;
420 TreeSocket* GetSocket()
425 TreeServer* GetParent()
430 void SetVersion(std::string Version)
432 VersionString = Version;
435 unsigned int ChildCount()
437 return Children.size();
440 TreeServer* GetChild(unsigned int n)
442 if (n < Children.size())
444 /* Make sure they cant request
445 * an out-of-range object. After
446 * all we know what these programmer
447 * types are like *grin*.
457 void AddChild(TreeServer* Child)
459 Children.push_back(Child);
462 bool DelChild(TreeServer* Child)
464 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
475 /* Removes child nodes of this node, and of that node, etc etc.
476 * This is used during netsplits to automatically tidy up the
477 * server tree. It is slow, we don't use it for much else.
481 bool stillchildren = true;
482 while (stillchildren)
484 stillchildren = false;
485 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
487 TreeServer* s = (TreeServer*)*a;
491 stillchildren = true;
500 /* We'd better tidy up after ourselves, eh? */
501 this->DelHashEntry();
505 /* The Link class might as well be a struct,
506 * but this is C++ and we don't believe in structs (!).
507 * It holds the entire information of one <link>
508 * tag from the main config file. We maintain a list
509 * of them, and populate the list on rehash/load.
512 class Link : public classbase
518 std::string SendPass;
519 std::string RecvPass;
520 unsigned long AutoConnect;
521 time_t NextConnectTime;
522 std::string EncryptionKey;
523 bool HiddenFromStats;
526 /* The usual stuff for inspircd modules,
527 * plus the vector of Link classes which we
528 * use to store the <link> tags from the config
532 std::vector<Link> LinkBlocks;
534 /* Yay for fast searches!
535 * This is hundreds of times faster than recursion
536 * or even scanning a linked list, especially when
537 * there are more than a few servers to deal with.
540 TreeServer* FindServer(std::string ServerName)
542 server_hash::iterator iter;
543 iter = serverlist.find(ServerName.c_str());
544 if (iter != serverlist.end())
554 /* Returns the locally connected server we must route a
555 * message through to reach server 'ServerName'. This
556 * only applies to one-to-one and not one-to-many routing.
557 * See the comments for the constructor of TreeServer
560 TreeServer* BestRouteTo(std::string ServerName)
562 if (ServerName.c_str() == TreeRoot->GetName())
564 TreeServer* Found = FindServer(ServerName);
567 return Found->GetRoute();
575 /* Find the first server matching a given glob mask.
576 * Theres no find-using-glob method of hash_map [awwww :-(]
577 * so instead, we iterate over the list using an iterator
578 * and match each one until we get a hit. Yes its slow,
581 TreeServer* FindServerMask(std::string ServerName)
583 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
585 if (ServerInstance->MatchText(i->first.c_str(),ServerName))
591 /* A convenient wrapper that returns true if a server exists */
592 bool IsServer(std::string ServerName)
594 return (FindServer(ServerName) != NULL);
598 class cmd_rconnect : public command_t
602 cmd_rconnect (InspIRCd* Instance, Module* Callback) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback)
604 this->source = "m_spanningtree.so";
605 syntax = "<remote-server-mask> <servermask>";
608 void Handle (const char** parameters, int pcnt, userrec *user)
610 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
611 /* Is this aimed at our server? */
612 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
614 /* Yes, initiate the given connect */
615 ServerInstance->WriteOpers("*** Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
617 para[0] = parameters[1];
618 Creator->OnPreCommand("CONNECT", para, 1, user, true);
625 /* Every SERVER connection inbound or outbound is represented by
626 * an object of type TreeSocket.
627 * TreeSockets, being inherited from InspSocket, can be tied into
628 * the core socket engine, and we cn therefore receive activity events
629 * for them, just like activex objects on speed. (yes really, that
630 * is a technical term!) Each of these which relates to a locally
631 * connected server is assocated with it, by hooking it onto a
632 * TreeSocket class using its constructor. In this way, we can
633 * maintain a list of servers, some of which are directly connected,
634 * some of which are not.
637 class TreeSocket : public InspSocket
640 std::string in_buffer;
641 ServerState LinkState;
642 std::string InboundServerName;
643 std::string InboundDescription;
645 int num_lost_servers;
647 bool LastPingWasGood;
651 unsigned int keylength;
655 /* Because most of the I/O gubbins are encapsulated within
656 * InspSocket, we just call the superclass constructor for
657 * most of the action, and append a few of our own values
660 TreeSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
661 : InspSocket(SI, host, port, listening, maxtime)
664 this->LinkState = LISTENER;
666 this->ctx_out = NULL;
669 TreeSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
670 : InspSocket(SI, host, port, listening, maxtime)
673 this->LinkState = CONNECTING;
675 this->ctx_out = NULL;
678 /* When a listening socket gives us a new file descriptor,
679 * we must associate it with a socket without creating a new
680 * connection. This constructor is used for this purpose.
682 TreeSocket(InspIRCd* SI, int newfd, char* ip)
683 : InspSocket(SI, newfd, ip)
685 this->LinkState = WAIT_AUTH_1;
687 this->ctx_out = NULL;
688 this->SendCapabilities();
699 void InitAES(std::string key,std::string SName)
706 log(DEBUG,"Initialized AES key %s",key.c_str());
707 // key must be 16, 24, 32 etc bytes (multiple of 8)
708 keylength = key.length();
709 if (!(keylength == 16 || keylength == 24 || keylength == 32))
711 ServerInstance->WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
712 log(DEBUG,"Key length not 16, 24 or 32 characters!");
716 ServerInstance->WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
717 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\
718 \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);
719 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\
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);
724 /* When an outbound connection finishes connecting, we receive
725 * this event, and must send our SERVER string to the other
726 * side. If the other side is happy, as outlined in the server
727 * to server docs on the inspircd.org site, the other side
728 * will then send back its own server string.
730 virtual bool OnConnected()
732 if (this->LinkState == CONNECTING)
734 /* we do not need to change state here. */
735 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
737 if (x->Name == this->myhost)
739 ServerInstance->WriteOpers("*** Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
740 this->SendCapabilities();
741 if (x->EncryptionKey != "")
743 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
745 ServerInstance->WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
749 this->WriteLine(std::string("AES ")+ServerInstance->Config->ServerName);
750 this->InitAES(x->EncryptionKey,x->Name.c_str());
753 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
754 this->WriteLine(std::string("SERVER ")+ServerInstance->Config->ServerName+" "+x->SendPass+" 0 :"+ServerInstance->Config->ServerDesc);
759 /* There is a (remote) chance that between the /CONNECT and the connection
760 * being accepted, some muppet has removed the <link> block and rehashed.
761 * If that happens the connection hangs here until it's closed. Unlikely
762 * and rather harmless.
764 ServerInstance->WriteOpers("*** Connection to \2"+myhost+"\2 lost link tag(!)");
768 virtual void OnError(InspSocketError e)
770 /* We don't handle this method, because all our
771 * dirty work is done in OnClose() (see below)
772 * which is still called on error conditions too.
774 if (e == I_ERR_CONNECT)
776 ServerInstance->WriteOpers("*** Connection failed: Connection refused");
780 virtual int OnDisconnect()
782 /* For the same reason as above, we don't
783 * handle OnDisconnect()
788 /* Recursively send the server tree with distances as hops.
789 * This is used during network burst to inform the other server
790 * (and any of ITS servers too) of what servers we know about.
791 * If at any point any of these servers already exist on the other
792 * end, our connection may be terminated. The hopcounts given
793 * by this function are relative, this doesn't matter so long as
794 * they are all >1, as all the remote servers re-calculate them
795 * to be relative too, with themselves as hop 0.
797 void SendServers(TreeServer* Current, TreeServer* s, int hops)
800 for (unsigned int q = 0; q < Current->ChildCount(); q++)
802 TreeServer* recursive_server = Current->GetChild(q);
803 if (recursive_server != s)
805 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
806 this->WriteLine(command);
807 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
808 /* down to next level */
809 this->SendServers(recursive_server, s, hops+1);
814 std::string MyCapabilities()
816 std::vector<std::string> modlist;
817 std::string capabilities = "";
819 for (int i = 0; i <= ServerInstance->GetModuleCount(); i++)
821 if ((ServerInstance->modules[i]->GetVersion().Flags & VF_STATIC) || (ServerInstance->modules[i]->GetVersion().Flags & VF_COMMON))
822 modlist.push_back(ServerInstance->Config->module_names[i]);
824 sort(modlist.begin(),modlist.end());
825 for (unsigned int i = 0; i < modlist.size(); i++)
828 capabilities = capabilities + ",";
829 capabilities = capabilities + modlist[i];
834 void SendCapabilities()
836 this->WriteLine("CAPAB "+MyCapabilities());
839 bool Capab(std::deque<std::string> params)
841 if (params.size() != 1)
843 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
847 if (params[0] != this->MyCapabilities())
849 std::string quitserver = this->myhost;
850 if (this->InboundServerName != "")
852 quitserver = this->InboundServerName;
855 ServerInstance->WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
856 ServerInstance->WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
857 ServerInstance->WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
858 ServerInstance->WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
859 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
866 /* This function forces this server to quit, removing this server
867 * and any users on it (and servers and users below that, etc etc).
868 * It's very slow and pretty clunky, but luckily unless your network
869 * is having a REAL bad hair day, this function shouldnt be called
870 * too many times a month ;-)
872 void SquitServer(std::string &from, TreeServer* Current)
874 /* recursively squit the servers attached to 'Current'.
875 * We're going backwards so we don't remove users
876 * while we still need them ;)
878 for (unsigned int q = 0; q < Current->ChildCount(); q++)
880 TreeServer* recursive_server = Current->GetChild(q);
881 this->SquitServer(from,recursive_server);
883 /* Now we've whacked the kids, whack self */
885 num_lost_users += Current->QuitUsers(from);
888 /* This is a wrapper function for SquitServer above, which
889 * does some validation first and passes on the SQUIT to all
890 * other remaining servers.
892 void Squit(TreeServer* Current,std::string reason)
894 if ((Current) && (Current != TreeRoot))
896 std::deque<std::string> params;
897 params.push_back(Current->GetName());
898 params.push_back(":"+reason);
899 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
900 if (Current->GetParent() == TreeRoot)
902 ServerInstance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
906 ServerInstance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
908 num_lost_servers = 0;
910 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
911 SquitServer(from, Current);
913 Current->GetParent()->DelChild(Current);
915 ServerInstance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
919 log(DEFAULT,"Squit from unknown server");
923 /* FMODE command - server mode with timestamp checks */
924 bool ForceMode(std::string source, std::deque<std::string> ¶ms)
926 /* Chances are this is a 1.0 FMODE without TS */
927 if (params.size() < 3)
929 this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
934 std::string sourceserv;
936 /* Are we dealing with an FMODE from a user, or from a server? */
937 userrec* who = ServerInstance->FindNick(source);
940 /* FMODE from a user, set sourceserv to the users server name */
941 sourceserv = who->server;
945 /* FMODE from a server, create a fake user to receive mode feedback */
946 who = new userrec(ServerInstance);
947 who->fd = FD_MAGIC_NUMBER;
948 smode = true; /* Setting this flag tells us we should free the userrec later */
949 sourceserv = source; /* Set sourceserv to the actual source string */
951 const char* modelist[64];
954 memset(&modelist,0,sizeof(modelist));
955 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
959 /* The timestamp is in this position.
960 * We don't want to pass that up to the
961 * server->client protocol!
963 TS = atoi(params[q].c_str());
967 /* Everything else is fine to append to the modelist */
968 modelist[n++] = params[q].c_str();
972 /* Extract the TS value of the object, either userrec or chanrec */
973 userrec* dst = ServerInstance->FindNick(params[0]);
974 chanrec* chan = NULL;
982 chan = ServerInstance->FindChan(params[0]);
989 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
994 log(DEBUG,"Entering TS equality check");
995 ModeHandler* mh = NULL;
996 unsigned long paramptr = 3;
997 std::string to_bounce = "";
998 std::string to_keep = "";
999 std::vector<std::string> params_to_keep;
1000 std::string params_to_bounce = "";
1002 char cur_change = 1;
1003 char old_change = 0;
1004 char old_bounce_change = 0;
1005 /* Merge modes, basically do special stuff to mode with params */
1006 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1019 /* We only care about whats being set,
1020 * not whats being unset
1022 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1024 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1026 /* We only want to do special things to
1027 * modes with parameters, we are going to rewrite
1031 adding ? cur_change = '+' : cur_change = '-';
1033 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1035 /* The mode is set here, check which we should keep */
1038 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1040 if (which_to_keep == true)
1042 /* Keep ours, bounce theirs:
1043 * Send back ours to them and
1044 * drop their mode changs
1046 adding ? cur_change = '+' : cur_change = '-';
1047 if (cur_change != old_bounce_change)
1048 to_bounce += cur_change;
1050 old_bounce_change = cur_change;
1052 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1053 params_to_bounce.append(" ").append(ret.second);
1057 /* Keep theirs: Accept their mode change,
1060 adding ? cur_change = '+' : cur_change = '-';
1061 if (cur_change != old_change)
1062 to_keep += cur_change;
1064 old_change = cur_change;
1066 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1067 params_to_keep.push_back(params[paramptr]);
1072 /* Mode isnt set here, we want it */
1073 adding ? cur_change = '+' : cur_change = '-';
1074 if (cur_change != old_change)
1075 to_keep += cur_change;
1077 old_change = cur_change;
1079 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1080 params_to_keep.push_back(params[paramptr]);
1087 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1091 adding ? cur_change = '+' : cur_change = '-';
1093 /* Just keep this, safe to merge with no checks
1094 * it has no parameters
1097 if (cur_change != old_change)
1098 to_keep += cur_change;
1100 old_change = cur_change;
1102 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1104 log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1105 params_to_keep.push_back(params[paramptr++]);
1112 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1116 /* Taking a mode away */
1117 adding ? cur_change = '+' : cur_change = '-';
1119 if (cur_change != old_change)
1120 to_keep += cur_change;
1122 old_change = cur_change;
1124 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1125 params_to_keep.push_back(params[paramptr++]);
1132 if (to_bounce.length())
1134 std::deque<std::string> newparams;
1135 newparams.push_back(params[0]);
1136 newparams.push_back(ConvToStr(ourTS));
1137 newparams.push_back(to_bounce+params_to_bounce);
1138 DoOneToOne(ServerInstance->Config->ServerName,"FMODE",newparams,sourceserv);
1141 if (to_keep.length())
1145 modelist[0] = params[0].c_str();
1146 modelist[1] = to_keep.c_str();
1148 if (params_to_keep.size() > 2)
1150 for (q = 2; (q < params_to_keep.size()) && (q < 64); q++)
1152 log(DEBUG,"Item %d of %d", q, params_to_keep.size());
1153 modelist[n++] = params_to_keep[q].c_str();
1159 log(DEBUG,"Send mode");
1160 ServerInstance->SendMode(modelist, n+2, who);
1164 log(DEBUG,"Send mode client");
1165 ServerInstance->CallCommandHandler("MODE", modelist, n+2, who);
1168 /* HOT POTATO! PASS IT ON! */
1169 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1173 /* U-lined servers always win regardless of their TS */
1174 if ((TS > ourTS) && (!ServerInstance->IsUlined(source)))
1176 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1177 * SHOULD accept it, if its clock is right.
1179 * NOTE: We should check that we arent bouncing anything thats already set at this end.
1180 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1181 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1183 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1184 * writing the code. It took me a while to come up with this solution.
1186 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1189 std::deque<std::string> newparams; /* New parameter list we send back */
1190 newparams.push_back(params[0]); /* Target, user or channel */
1191 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
1192 newparams.push_back(""); /* This contains the mode string. For now
1193 * it's empty, we fill it below.
1196 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1197 * set to avoid a desync here.
1199 std::string modebounce = "";
1202 ModeHandler* mh = NULL;
1203 char cur_change = 1;
1204 char old_change = 0;
1205 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1207 /* Iterate over all mode chars in the sent set */
1210 /* Adding or subtracting modes? */
1218 /* Find the mode handler for this mode */
1219 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1221 /* Got a mode handler?
1222 * This also prevents us bouncing modes we have no handler for.
1229 /* Does the mode require a parameter right now?
1230 * If it does, fetch it if we can
1232 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1235 /* Call the ModeSet method to determine if its set with the
1236 * given parameter here or not.
1238 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1240 /* XXX: Really. Dont ask.
1241 * Determine from if its set combined with what the current
1242 * 'state' is (adding or not) as to wether we should 'invert'
1243 * or 'reinforce' the mode change
1245 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1247 /* Quickly determine if we have 'flipped' from + to -,
1248 * or - to +, to prevent unneccessary +/- chars in the
1249 * output string that waste bandwidth
1251 if (cur_change != old_change)
1252 modebounce += cur_change;
1253 old_change = cur_change;
1255 /* Add the mode character to the output string */
1256 modebounce += mh->GetModeChar();
1258 /* We got a parameter back from ModeHandler::ModeSet,
1259 * are we supposed to be sending one out right now?
1261 if (ret.second.length())
1263 if (mh->GetNumParams(cur_change == '+') > 0)
1264 /* Yes we're supposed to be sending out
1265 * the parameter. Make sure it goes
1267 newparams.push_back(ret.second);
1275 /* Update the parameters for FMODE with the new 'bounced' string */
1276 newparams[2] = modebounce;
1277 /* Only send it back the way it came, no need to send it anywhere else */
1278 DoOneToOne(ServerInstance->Config->ServerName,"FMODE",newparams,sourceserv);
1279 log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1283 log(DEBUG,"Allow modes, TS lower for sender");
1284 /* The server was ulined, but something iffy is up with the TS.
1285 * Sound the alarm bells!
1287 if ((ServerInstance->IsUlined(sourceserv)) && (TS > ourTS))
1289 ServerInstance->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());
1291 /* Allow the mode, route it to either server or user command handling */
1293 ServerInstance->SendMode(modelist,n,who);
1295 ServerInstance->CallCommandHandler("MODE", modelist, n, who);
1297 /* HOT POTATO! PASS IT ON! */
1298 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1300 /* Are we supposed to free the userrec? */
1307 /* FTOPIC command */
1308 bool ForceTopic(std::string source, std::deque<std::string> ¶ms)
1310 if (params.size() != 4)
1312 time_t ts = atoi(params[1].c_str());
1313 std::string nsource = source;
1315 chanrec* c = ServerInstance->FindChan(params[0]);
1318 if ((ts >= c->topicset) || (!*c->topic))
1320 std::string oldtopic = c->topic;
1321 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1322 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1324 /* if the topic text is the same as the current topic,
1325 * dont bother to send the TOPIC command out, just silently
1326 * update the set time and set nick.
1328 if (oldtopic != params[3])
1330 userrec* user = ServerInstance->FindNick(source);
1333 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1337 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1338 nsource = user->server;
1340 /* all done, send it on its way */
1341 params[3] = ":" + params[3];
1342 DoOneToAllButSender(source,"FTOPIC",params,nsource);
1351 /* FJOIN, similar to unreal SJOIN */
1352 bool ForceJoin(std::string source, std::deque<std::string> ¶ms)
1354 if (params.size() < 3)
1358 char modestring[MAXBUF];
1359 char* mode_users[127];
1360 memset(&mode_users,0,sizeof(mode_users));
1361 mode_users[0] = first;
1362 mode_users[1] = modestring;
1363 strcpy(modestring,"+");
1364 unsigned int modectr = 2;
1366 userrec* who = NULL;
1367 std::string channel = params[0];
1368 time_t TS = atoi(params[1].c_str());
1371 chanrec* chan = ServerInstance->FindChan(channel);
1376 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1378 /* default is a high value, which if we dont have this
1379 * channel will let the other side apply their modes.
1381 time_t ourTS = time(NULL)+600;
1382 chanrec* us = ServerInstance->FindChan(channel);
1388 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1390 /* do this first, so our mode reversals are correctly received by other servers
1391 * if there is a TS collision.
1393 DoOneToAllButSender(source,"FJOIN",params,source);
1395 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
1397 /* process one channel at a time, applying modes. */
1398 char* usr = (char*)params[usernum].c_str();
1399 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1400 * (is this even possible?) */
1403 char permissions = *usr;
1404 switch (permissions)
1408 mode_users[modectr++] = usr;
1409 strlcat(modestring,"o",MAXBUF);
1413 mode_users[modectr++] = usr;
1414 strlcat(modestring,"h",MAXBUF);
1418 mode_users[modectr++] = usr;
1419 strlcat(modestring,"v",MAXBUF);
1422 who = ServerInstance->FindNick(usr);
1425 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, key);
1426 if (modectr >= (MAXMODES-1))
1428 /* theres a mode for this user. push them onto the mode queue, and flush it
1429 * if there are more than MAXMODES to go.
1431 if ((ourTS >= TS) || (ServerInstance->IsUlined(who->server)))
1433 /* We also always let u-lined clients win, no matter what the TS value */
1434 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1435 ServerInstance->SendMode((const char**)mode_users,modectr,who);
1438 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1445 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1446 /* bouncy bouncy! */
1447 std::deque<std::string> params;
1448 /* modes are now being UNSET... */
1449 *mode_users[1] = '-';
1450 for (unsigned int x = 0; x < modectr; x++)
1454 params.push_back(ConvToStr(us->age));
1456 params.push_back(mode_users[x]);
1459 // tell everyone to bounce the modes. bad modes, bad!
1460 DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
1462 strcpy(mode_users[1],"+");
1468 /* there werent enough modes built up to flush it during FJOIN,
1469 * or, there are a number left over. flush them out.
1471 if ((modectr > 2) && (who) && (us))
1475 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1476 ServerInstance->SendMode((const char**)mode_users,modectr,who);
1479 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1486 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1487 std::deque<std::string> params;
1488 *mode_users[1] = '-';
1489 for (unsigned int x = 0; x < modectr; x++)
1493 params.push_back(ConvToStr(us->age));
1495 params.push_back(mode_users[x]);
1497 DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
1503 bool SyncChannelTS(std::string source, std::deque<std::string> ¶ms)
1505 if (params.size() >= 2)
1507 chanrec* c = ServerInstance->FindChan(params[0]);
1510 time_t theirTS = atoi(params[1].c_str());
1511 time_t ourTS = c->age;
1512 if (ourTS >= theirTS)
1514 log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1519 DoOneToAllButSender(ServerInstance->Config->ServerName,"SYNCTS",params,source);
1524 bool IntroduceClient(std::string source, std::deque<std::string> ¶ms)
1526 if (params.size() < 8)
1528 if (params.size() > 8)
1530 this->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1533 // NICK age nick host dhost ident +modes ip :gecos
1535 time_t age = atoi(params[0].c_str());
1537 /* This used to have a pretty craq'y loop doing the same thing,
1538 * now we just let the STL do the hard work (more efficiently)
1540 params[5] = params[5].substr(params[5].find_first_not_of('+'));
1542 const char* tempnick = params[1].c_str();
1543 log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1545 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1547 if (iter != this->Instance->clientlist.end())
1550 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);
1551 this->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1555 userrec* _new = new userrec(this->Instance);
1556 this->Instance->clientlist[tempnick] = _new;
1557 _new->fd = FD_MAGIC_NUMBER;
1558 strlcpy(_new->nick, tempnick,NICKMAX-1);
1559 strlcpy(_new->host, params[2].c_str(),63);
1560 strlcpy(_new->dhost, params[3].c_str(),63);
1561 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1562 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1563 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1564 _new->registered = REG_ALL;
1567 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1568 _new->modes[(*v)-65] = 1;
1570 if (params[6].find_first_of(":") != std::string::npos)
1571 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1573 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1575 ServerInstance->WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1577 params[7] = ":" + params[7];
1578 DoOneToAllButSender(source,"NICK",params,source);
1580 // Increment the Source Servers User Count..
1581 TreeServer* SourceServer = FindServer(source);
1584 log(DEBUG,"Found source server of %s",_new->nick);
1585 SourceServer->AddUserCount();
1591 /* Send one or more FJOINs for a channel of users.
1592 * If the length of a single line is more than 480-NICKMAX
1593 * in length, it is split over multiple lines.
1595 void SendFJoins(TreeServer* Current, chanrec* c)
1597 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1599 std::string individual_halfops = std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1601 size_t dlen, curlen;
1602 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",ServerInstance->Config->ServerName,c->name,(unsigned long)c->age);
1604 char* ptr = list + dlen;
1606 CUList *ulist = c->GetUsers();
1607 std::vector<userrec*> specific_halfop;
1608 std::vector<userrec*> specific_voice;
1609 std::string modes = "";
1610 std::string params = "";
1612 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1614 int x = c->GetStatusFlags(i->second);
1615 if ((x & UCMODE_HOP) && (x & UCMODE_OP))
1617 specific_halfop.push_back(i->second);
1619 if (((x & UCMODE_HOP) || (x & UCMODE_OP)) && (x & UCMODE_VOICE))
1621 specific_voice.push_back(i->second);
1629 else if (x & UCMODE_HOP)
1633 else if (x & UCMODE_VOICE)
1638 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s", n, i->second->nick);
1645 if (curlen > (480-NICKMAX))
1647 this->WriteLine(list);
1648 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",ServerInstance->Config->ServerName,c->name,(unsigned long)c->age);
1652 for (unsigned int y = 0; y < specific_voice.size(); y++)
1655 params.append(specific_voice[y]->nick).append(" ");
1656 //this->WriteLine(":"+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1658 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1661 params.append(specific_halfop[y]->nick).append(" ");
1662 //this->WriteLine(":"+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1668 this->WriteLine(list);
1669 for (unsigned int y = 0; y < specific_voice.size(); y++)
1672 params.append(specific_voice[y]->nick).append(" ");
1673 //this->WriteLine(":"+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1675 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1678 params.append(specific_halfop[y]->nick).append(" ");
1679 //this->WriteLine(":"+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1682 //std::string modes = "";
1683 //std::string params = "";
1684 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1687 params.append(b->data).append(" ");
1689 /* XXX: Send each channel mode and its params -- we'll need a method for this in ModeHandler? */
1690 //FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1691 this->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+c->ChanModes(true)+modes+" "+params);
1694 /* Send G, Q, Z and E lines */
1695 void SendXLines(TreeServer* Current)
1698 std::string n = ServerInstance->Config->ServerName;
1699 const char* sn = n.c_str();
1701 /* Yes, these arent too nice looking, but they get the job done */
1702 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++, iterations++)
1704 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);
1705 this->WriteLine(data);
1707 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++, iterations++)
1709 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);
1710 this->WriteLine(data);
1712 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++, iterations++)
1714 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);
1715 this->WriteLine(data);
1717 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++, iterations++)
1719 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);
1720 this->WriteLine(data);
1722 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++, iterations++)
1724 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);
1725 this->WriteLine(data);
1727 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++, iterations++)
1729 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);
1730 this->WriteLine(data);
1732 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++, iterations++)
1734 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);
1735 this->WriteLine(data);
1737 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++, iterations++)
1739 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);
1740 this->WriteLine(data);
1744 /* Send channel modes and topics */
1745 void SendChannelModes(TreeServer* Current)
1748 std::deque<std::string> list;
1750 std::string n = ServerInstance->Config->ServerName;
1751 const char* sn = n.c_str();
1752 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
1754 SendFJoins(Current, c->second);
1755 if (*c->second->topic)
1757 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1758 this->WriteLine(data);
1760 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1762 c->second->GetExtList(list);
1763 for (unsigned int j = 0; j < list.size(); j++)
1765 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1770 /* send all users and their oper state/modes */
1771 void SendUsers(TreeServer* Current)
1774 std::deque<std::string> list;
1776 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
1778 if (u->second->registered == REG_ALL)
1780 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);
1781 this->WriteLine(data);
1782 if (*u->second->oper)
1784 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1786 if (*u->second->awaymsg)
1788 this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1790 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1792 u->second->GetExtList(list);
1793 for (unsigned int j = 0; j < list.size(); j++)
1795 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1801 /* This function is called when we want to send a netburst to a local
1802 * server. There is a set order we must do this, because for example
1803 * users require their servers to exist, and channels require their
1804 * users to exist. You get the idea.
1806 void DoBurst(TreeServer* s)
1808 std::string burst = "BURST "+ConvToStr(time(NULL));
1809 std::string endburst = "ENDBURST";
1810 // Because by the end of the netburst, it could be gone!
1811 std::string name = s->GetName();
1812 ServerInstance->WriteOpers("*** Bursting to \2"+name+"\2.");
1813 this->WriteLine(burst);
1814 /* send our version string */
1815 this->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1816 /* Send server tree */
1817 this->SendServers(TreeRoot,s,1);
1818 /* Send users and their oper status */
1820 /* Send everything else (channel modes, xlines etc) */
1821 this->SendChannelModes(s);
1822 this->SendXLines(s);
1823 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1824 this->WriteLine(endburst);
1825 ServerInstance->WriteOpers("*** Finished bursting to \2"+name+"\2.");
1828 /* This function is called when we receive data from a remote
1829 * server. We buffer the data in a std::string (it doesnt stay
1830 * there for long), reading using InspSocket::Read() which can
1831 * read up to 16 kilobytes in one operation.
1833 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1834 * THE SOCKET OBJECT FOR US.
1836 virtual bool OnDataReady()
1838 char* data = this->Read();
1839 /* Check that the data read is a valid pointer and it has some content */
1842 this->in_buffer.append(data);
1843 /* While there is at least one new line in the buffer,
1844 * do something useful (we hope!) with it.
1846 while (in_buffer.find("\n") != std::string::npos)
1848 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1849 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1850 if (ret.find("\r") != std::string::npos)
1851 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1852 /* Process this one, abort if it
1853 * didnt return true.
1859 memset(result,0,1024);
1861 log(DEBUG,"Original string '%s'",ret.c_str());
1862 /* ERROR + CAPAB is still allowed unencryped */
1863 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1865 int nbytes = from64tobits(out, ret.c_str(), 1024);
1866 if ((nbytes > 0) && (nbytes < 1024))
1868 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1869 ctx_in->Decrypt(out, result, nbytes, 0);
1870 for (int t = 0; t < nbytes; t++)
1871 if (result[t] == '\7') result[t] = 0;
1876 if (!this->ProcessLine(ret))
1878 log(DEBUG,"ProcessLine says no!");
1884 /* EAGAIN returns an empty but non-NULL string, so this
1885 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1887 return (data && !*data);
1890 int WriteLine(std::string line)
1892 log(DEBUG,"OUT: %s",line.c_str());
1896 char result64[10240];
1897 if (this->keylength)
1899 // pad it to the key length
1900 int n = this->keylength - (line.length() % this->keylength);
1903 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);
1904 line.append(n,'\7');
1907 unsigned int ll = line.length();
1908 ctx_out->Encrypt(line.c_str(), result, ll, 0);
1909 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1911 //int from64tobits(char *out, const char *in, int maxlen);
1913 return this->Write(line + "\r\n");
1916 /* Handle ERROR command */
1917 bool Error(std::deque<std::string> ¶ms)
1919 if (params.size() < 1)
1921 ServerInstance->WriteOpers("*** ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1922 /* we will return false to cause the socket to close. */
1926 bool Stats(std::string prefix, std::deque<std::string> ¶ms)
1928 /* Get the reply to a STATS query if it matches this servername,
1929 * and send it back as a load of PUSH queries
1931 if (params.size() > 1)
1933 if (ServerInstance->MatchText(ServerInstance->Config->ServerName, params[1]))
1935 /* It's for our server */
1936 string_list results;
1937 userrec* source = ServerInstance->FindNick(prefix);
1940 std::deque<std::string> par;
1941 par.push_back(prefix);
1943 DoStats(*(params[0].c_str()), source, results);
1944 for (size_t i = 0; i < results.size(); i++)
1946 par[1] = "::" + results[i];
1947 DoOneToOne(ServerInstance->Config->ServerName, "PUSH",par, source->server);
1954 userrec* source = ServerInstance->FindNick(prefix);
1956 DoOneToOne(prefix, "STATS", params, params[1]);
1963 /* Because the core won't let users or even SERVERS set +o,
1964 * we use the OPERTYPE command to do this.
1966 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1968 if (params.size() != 1)
1970 log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
1973 std::string opertype = params[0];
1974 userrec* u = ServerInstance->FindNick(prefix);
1977 u->modes[UM_OPERATOR] = 1;
1978 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1979 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1984 /* Because Andy insists that services-compatible servers must
1985 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1987 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1989 if (params.size() < 3)
1992 userrec* u = ServerInstance->FindNick(params[0]);
1996 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1999 std::deque<std::string> par;
2000 par.push_back(params[1]);
2001 /* This is not required as one is sent in OnUserPostNick below
2003 //DoOneToMany(u->nick,"NICK",par);
2004 if (!u->ForceNickChange(params[1].c_str()))
2006 userrec::QuitUser(this->Instance, u, "Nickname collision");
2009 u->age = atoi(params[2].c_str());
2015 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
2017 if (params.size() < 2)
2020 userrec* u = ServerInstance->FindNick(params[0]);
2024 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2025 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2030 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
2032 if (params.size() < 1)
2035 std::string servermask = params[0];
2037 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,servermask))
2039 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
2040 ServerInstance->RehashServer();
2041 ReadConfiguration(false);
2043 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2047 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
2049 if (params.size() != 2)
2052 std::string nick = params[0];
2053 userrec* u = ServerInstance->FindNick(prefix);
2054 userrec* who = ServerInstance->FindNick(nick);
2058 /* Prepend kill source, if we don't have one */
2059 std::string sourceserv = prefix;
2062 sourceserv = u->server;
2064 if (*(params[1].c_str()) != '[')
2066 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2068 std::string reason = params[1];
2069 params[1] = ":" + params[1];
2070 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2071 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2072 userrec::QuitUser(this->Instance,who,reason);
2077 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
2079 if (params.size() < 1)
2082 if (params.size() == 1)
2084 TreeServer* ServerSource = FindServer(prefix);
2087 ServerSource->SetPingFlag();
2092 std::string forwardto = params[1];
2093 if (forwardto == ServerInstance->Config->ServerName)
2096 * this is a PONG for us
2097 * if the prefix is a user, check theyre local, and if they are,
2098 * dump the PONG reply back to their fd. If its a server, do nowt.
2099 * Services might want to send these s->s, but we dont need to yet.
2101 userrec* u = ServerInstance->FindNick(prefix);
2105 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2110 // not for us, pass it on :)
2111 DoOneToOne(prefix,"PONG",params,forwardto);
2118 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
2120 if (params.size() < 3)
2123 TreeServer* ServerSource = FindServer(prefix);
2127 if (params[0] == "*")
2129 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2131 else if (*(params[0].c_str()) == '#')
2133 chanrec* c = ServerInstance->FindChan(params[0]);
2136 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2139 else if (*(params[0].c_str()) != '#')
2141 userrec* u = ServerInstance->FindNick(params[0]);
2144 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2149 params[2] = ":" + params[2];
2150 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2154 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
2156 if (params.size() < 1)
2159 TreeServer* ServerSource = FindServer(prefix);
2163 ServerSource->SetVersion(params[0]);
2165 params[0] = ":" + params[0];
2166 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2170 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
2172 if (params.size() < 1)
2175 userrec* u = ServerInstance->FindNick(prefix);
2179 u->ChangeDisplayedHost(params[0].c_str());
2180 DoOneToAllButSender(prefix,"FHOST",params,u->server);
2185 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
2187 if (params.size() < 6)
2190 bool propogate = false;
2192 switch (*(params[0].c_str()))
2195 propogate = add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2196 zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2199 propogate = add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2200 qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2203 propogate = add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2204 eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2207 propogate = add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2208 gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2211 propogate = add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2214 /* Just in case... */
2215 ServerInstance->WriteOpers("*** \2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2220 /* Send it on its way */
2223 if (atoi(params[4].c_str()))
2225 ServerInstance->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());
2229 ServerInstance->WriteOpers("*** %s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2231 params[5] = ":" + params[5];
2232 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2234 if (!this->bursting)
2236 log(DEBUG,"Applying lines...");
2237 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2242 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
2244 if (params.size() < 1)
2247 userrec* u = ServerInstance->FindNick(prefix);
2251 u->ChangeName(params[0].c_str());
2252 params[0] = ":" + params[0];
2253 DoOneToAllButSender(prefix,"FNAME",params,u->server);
2258 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
2260 if (params.size() < 1)
2263 log(DEBUG,"In IDLE command");
2264 userrec* u = ServerInstance->FindNick(prefix);
2268 log(DEBUG,"USER EXISTS: %s",u->nick);
2269 // an incoming request
2270 if (params.size() == 1)
2272 userrec* x = ServerInstance->FindNick(params[0]);
2273 if ((x) && (IS_LOCAL(x)))
2275 userrec* x = ServerInstance->FindNick(params[0]);
2276 log(DEBUG,"Got IDLE");
2277 char signon[MAXBUF];
2279 log(DEBUG,"Sending back IDLE 3");
2280 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2281 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2282 std::deque<std::string> par;
2283 par.push_back(prefix);
2284 par.push_back(signon);
2285 par.push_back(idle);
2286 // ours, we're done, pass it BACK
2287 DoOneToOne(params[0],"IDLE",par,u->server);
2291 // not ours pass it on
2292 DoOneToOne(prefix,"IDLE",params,x->server);
2295 else if (params.size() == 3)
2297 std::string who_did_the_whois = params[0];
2298 userrec* who_to_send_to = ServerInstance->FindNick(who_did_the_whois);
2299 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2301 log(DEBUG,"Got final IDLE");
2302 // an incoming reply to a whois we sent out
2303 std::string nick_whoised = prefix;
2304 unsigned long signon = atoi(params[1].c_str());
2305 unsigned long idle = atoi(params[2].c_str());
2306 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2307 do_whois(who_to_send_to,u,signon,idle,nick_whoised.c_str());
2311 // not ours, pass it on
2312 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2319 bool Push(std::string prefix, std::deque<std::string> ¶ms)
2321 if (params.size() < 2)
2324 userrec* u = ServerInstance->FindNick(params[0]);
2331 u->Write(params[1]);
2335 // continue the raw onwards
2336 params[1] = ":" + params[1];
2337 DoOneToOne(prefix,"PUSH",params,u->server);
2342 bool Time(std::string prefix, std::deque<std::string> ¶ms)
2344 // :source.server TIME remote.server sendernick
2345 // :remote.server TIME source.server sendernick TS
2346 if (params.size() == 2)
2348 // someone querying our time?
2349 if (ServerInstance->Config->ServerName == params[0])
2351 userrec* u = ServerInstance->FindNick(params[1]);
2355 snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2356 params.push_back(curtime);
2358 DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,params[0]);
2363 // not us, pass it on
2364 userrec* u = ServerInstance->FindNick(params[1]);
2366 DoOneToOne(prefix,"TIME",params,params[0]);
2369 else if (params.size() == 3)
2371 // a response to a previous TIME
2372 userrec* u = ServerInstance->FindNick(params[1]);
2373 if ((u) && (IS_LOCAL(u)))
2375 time_t rawtime = atol(params[2].c_str());
2376 struct tm * timeinfo;
2377 timeinfo = localtime(&rawtime);
2379 snprintf(tms,26,"%s",asctime(timeinfo));
2381 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2386 DoOneToOne(prefix,"TIME",params,u->server);
2392 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
2394 if (params.size() < 1)
2397 if (params.size() == 1)
2399 std::string stufftobounce = params[0];
2400 this->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PONG "+stufftobounce);
2405 std::string forwardto = params[1];
2406 if (forwardto == ServerInstance->Config->ServerName)
2408 // this is a ping for us, send back PONG to the requesting server
2409 params[1] = params[0];
2410 params[0] = forwardto;
2411 DoOneToOne(forwardto,"PONG",params,params[1]);
2415 // not for us, pass it on :)
2416 DoOneToOne(prefix,"PING",params,forwardto);
2422 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
2424 if (params.size() < 4)
2427 std::string servername = params[0];
2428 std::string password = params[1];
2429 // hopcount is not used for a remote server, we calculate this ourselves
2430 std::string description = params[3];
2431 TreeServer* ParentOfThis = FindServer(prefix);
2435 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2438 TreeServer* CheckDupe = FindServer(servername);
2441 this->WriteLine("ERROR :Server "+servername+" already exists!");
2442 ServerInstance->WriteOpers("*** Server connection from \2"+servername+"\2 denied, already exists");
2445 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
2446 ParentOfThis->AddChild(Node);
2447 params[3] = ":" + params[3];
2448 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2449 ServerInstance->WriteOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2453 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2455 if (params.size() < 4)
2458 irc::string servername = params[0].c_str();
2459 std::string sname = params[0];
2460 std::string password = params[1];
2461 int hops = atoi(params[2].c_str());
2465 this->WriteLine("ERROR :Server too far away for authentication");
2466 ServerInstance->WriteOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2469 std::string description = params[3];
2470 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2472 if ((x->Name == servername) && (x->RecvPass == password))
2474 TreeServer* CheckDupe = FindServer(sname);
2477 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2478 ServerInstance->WriteOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2481 // Begin the sync here. this kickstarts the
2482 // other side, waiting in WAIT_AUTH_2 state,
2483 // into starting their burst, as it shows
2484 // that we're happy.
2485 this->LinkState = CONNECTED;
2486 // we should add the details of this server now
2487 // to the servers tree, as a child of the root
2489 TreeServer* Node = new TreeServer(sname,description,TreeRoot,this);
2490 TreeRoot->AddChild(Node);
2491 params[3] = ":" + params[3];
2492 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2493 this->bursting = true;
2494 this->DoBurst(Node);
2498 this->WriteLine("ERROR :Invalid credentials");
2499 ServerInstance->WriteOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2503 bool Inbound_Server(std::deque<std::string> ¶ms)
2505 if (params.size() < 4)
2508 irc::string servername = params[0].c_str();
2509 std::string sname = params[0];
2510 std::string password = params[1];
2511 int hops = atoi(params[2].c_str());
2515 this->WriteLine("ERROR :Server too far away for authentication");
2516 ServerInstance->WriteOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2519 std::string description = params[3];
2520 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2522 if ((x->Name == servername) && (x->RecvPass == password))
2524 TreeServer* CheckDupe = FindServer(sname);
2527 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2528 ServerInstance->WriteOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2531 /* If the config says this link is encrypted, but the remote side
2532 * hasnt bothered to send the AES command before SERVER, then we
2533 * boot them off as we MUST have this connection encrypted.
2535 if ((x->EncryptionKey != "") && (!this->ctx_in))
2537 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2538 ServerInstance->WriteOpers("*** Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2541 ServerInstance->WriteOpers("*** Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2542 this->InboundServerName = sname;
2543 this->InboundDescription = description;
2544 // this is good. Send our details: Our server name and description and hopcount of 0,
2545 // along with the sendpass from this block.
2546 this->WriteLine(std::string("SERVER ")+ServerInstance->Config->ServerName+" "+x->SendPass+" 0 :"+ServerInstance->Config->ServerDesc);
2547 // move to the next state, we are now waiting for THEM.
2548 this->LinkState = WAIT_AUTH_2;
2552 this->WriteLine("ERROR :Invalid credentials");
2553 ServerInstance->WriteOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2557 void Split(std::string line, std::deque<std::string> &n)
2560 irc::tokenstream tokens(line);
2562 while ((param = tokens.GetToken()) != "")
2567 bool ProcessLine(std::string line)
2569 std::deque<std::string> params;
2570 irc::string command;
2576 line = line.substr(0, line.find_first_of("\r\n"));
2578 log(DEBUG,"IN: %s", line.c_str());
2580 this->Split(line.c_str(),params);
2582 if ((params[0][0] == ':') && (params.size() > 1))
2584 prefix = params[0].substr(1);
2588 command = params[0].c_str();
2591 if ((!this->ctx_in) && (command == "AES"))
2593 std::string sserv = params[0];
2594 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2596 if ((x->EncryptionKey != "") && (x->Name == sserv))
2598 this->InitAES(x->EncryptionKey,sserv);
2604 else if ((this->ctx_in) && (command == "AES"))
2606 ServerInstance->WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2609 switch (this->LinkState)
2614 // Waiting for SERVER command from remote server. Server initiating
2615 // the connection sends the first SERVER command, listening server
2616 // replies with theirs if its happy, then if the initiator is happy,
2617 // it starts to send its net sync, which starts the merge, otherwise
2618 // it sends an ERROR.
2619 if (command == "PASS")
2621 /* Silently ignored */
2623 else if (command == "SERVER")
2625 return this->Inbound_Server(params);
2627 else if (command == "ERROR")
2629 return this->Error(params);
2631 else if (command == "USER")
2633 this->WriteLine("ERROR :Client connections to this port are prohibited.");
2636 else if (command == "CAPAB")
2638 return this->Capab(params);
2640 else if ((command == "U") || (command == "S"))
2642 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2647 this->WriteLine("ERROR :Invalid command in negotiation phase.");
2652 // Waiting for start of other side's netmerge to say they liked our
2654 if (command == "SERVER")
2656 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2660 else if ((command == "U") || (command == "S"))
2662 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2665 else if (command == "BURST")
2669 /* If a time stamp is provided, try and check syncronization */
2670 time_t THEM = atoi(params[0].c_str());
2671 long delta = THEM-time(NULL);
2672 if ((delta < -600) || (delta > 600))
2674 ServerInstance->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));
2675 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2678 else if ((delta < -60) || (delta > 60))
2680 ServerInstance->WriteOpers("*** \2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2683 this->LinkState = CONNECTED;
2684 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
2685 TreeRoot->AddChild(Node);
2687 params.push_back(InboundServerName);
2688 params.push_back("*");
2689 params.push_back("1");
2690 params.push_back(":"+InboundDescription);
2691 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2692 this->bursting = true;
2693 this->DoBurst(Node);
2695 else if (command == "ERROR")
2697 return this->Error(params);
2699 else if (command == "CAPAB")
2701 return this->Capab(params);
2706 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2710 if (command == "SERVER")
2712 // another server we connected to, which was in WAIT_AUTH_1 state,
2713 // has just sent us their credentials. If we get this far, theyre
2714 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2715 // if we're happy with this, we should send our netburst which
2716 // kickstarts the merge.
2717 return this->Outbound_Reply_Server(params);
2719 else if (command == "ERROR")
2721 return this->Error(params);
2725 // This is the 'authenticated' state, when all passwords
2726 // have been exchanged and anything past this point is taken
2731 std::string direction = prefix;
2732 userrec* t = ServerInstance->FindNick(prefix);
2735 direction = t->server;
2737 TreeServer* route_back_again = BestRouteTo(direction);
2738 if ((!route_back_again) || (route_back_again->GetSocket() != this))
2740 if (route_back_again)
2741 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2746 * When there is activity on the socket, reset the ping counter so
2747 * that we're not wasting bandwidth pinging an active server.
2749 route_back_again->SetNextPingTime(time(NULL) + 120);
2750 route_back_again->SetPingFlag();
2753 if (command == "SVSMODE")
2755 /* Services expects us to implement
2756 * SVSMODE. In inspircd its the same as
2761 std::string target = "";
2762 /* Yes, know, this is a mess. Its reasonably fast though as we're
2763 * working with std::string here.
2765 if ((command == "NICK") && (params.size() > 1))
2767 return this->IntroduceClient(prefix,params);
2769 else if (command == "FJOIN")
2771 return this->ForceJoin(prefix,params);
2773 else if (command == "STATS")
2775 return this->Stats(prefix, params);
2777 else if (command == "SERVER")
2779 return this->RemoteServer(prefix,params);
2781 else if (command == "ERROR")
2783 return this->Error(params);
2785 else if (command == "OPERTYPE")
2787 return this->OperType(prefix,params);
2789 else if (command == "FMODE")
2791 return this->ForceMode(prefix,params);
2793 else if (command == "KILL")
2795 return this->RemoteKill(prefix,params);
2797 else if (command == "FTOPIC")
2799 return this->ForceTopic(prefix,params);
2801 else if (command == "REHASH")
2803 return this->RemoteRehash(prefix,params);
2805 else if (command == "METADATA")
2807 return this->MetaData(prefix,params);
2809 else if (command == "PING")
2812 * We just got a ping from a server that's bursting.
2813 * This can't be right, so set them to not bursting, and
2814 * apply their lines.
2818 this->bursting = false;
2819 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2823 prefix = this->GetName();
2825 return this->LocalPing(prefix,params);
2827 else if (command == "PONG")
2830 * We just got a pong from a server that's bursting.
2831 * This can't be right, so set them to not bursting, and
2832 * apply their lines.
2836 this->bursting = false;
2837 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2841 prefix = this->GetName();
2843 return this->LocalPong(prefix,params);
2845 else if (command == "VERSION")
2847 return this->ServerVersion(prefix,params);
2849 else if (command == "FHOST")
2851 return this->ChangeHost(prefix,params);
2853 else if (command == "FNAME")
2855 return this->ChangeName(prefix,params);
2857 else if (command == "ADDLINE")
2859 return this->AddLine(prefix,params);
2861 else if (command == "SVSNICK")
2865 prefix = this->GetName();
2867 return this->ForceNick(prefix,params);
2869 else if (command == "IDLE")
2871 return this->Whois(prefix,params);
2873 else if (command == "PUSH")
2875 return this->Push(prefix,params);
2877 else if (command == "TIME")
2879 return this->Time(prefix,params);
2881 else if ((command == "KICK") && (IsServer(prefix)))
2883 std::string sourceserv = this->myhost;
2884 if (params.size() == 3)
2886 userrec* user = ServerInstance->FindNick(params[1]);
2887 chanrec* chan = ServerInstance->FindChan(params[0]);
2890 if (!chan->ServerKickUser(user, params[2].c_str(), false))
2891 /* Yikes, the channels gone! */
2895 if (this->InboundServerName != "")
2897 sourceserv = this->InboundServerName;
2899 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2901 else if (command == "SVSJOIN")
2905 prefix = this->GetName();
2907 return this->ServiceJoin(prefix,params);
2909 else if (command == "SQUIT")
2911 if (params.size() == 2)
2913 this->Squit(FindServer(params[0]),params[1]);
2917 else if (command == "ENDBURST")
2919 this->bursting = false;
2920 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2921 std::string sourceserv = this->myhost;
2922 if (this->InboundServerName != "")
2924 sourceserv = this->InboundServerName;
2926 ServerInstance->WriteOpers("*** Received end of netburst from \2%s\2",sourceserv.c_str());
2931 // not a special inter-server command.
2932 // Emulate the actual user doing the command,
2933 // this saves us having a huge ugly parser.
2934 userrec* who = ServerInstance->FindNick(prefix);
2935 std::string sourceserv = this->myhost;
2936 if (this->InboundServerName != "")
2938 sourceserv = this->InboundServerName;
2942 if ((command == "NICK") && (params.size() > 0))
2944 /* On nick messages, check that the nick doesnt
2945 * already exist here. If it does, kill their copy,
2948 userrec* x = ServerInstance->FindNick(params[0]);
2949 if ((x) && (x != who))
2951 std::deque<std::string> p;
2952 p.push_back(params[0]);
2953 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2954 DoOneToMany(ServerInstance->Config->ServerName,"KILL",p);
2956 p.push_back(prefix);
2957 p.push_back("Nickname collision");
2958 DoOneToMany(ServerInstance->Config->ServerName,"KILL",p);
2959 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2960 userrec* y = ServerInstance->FindNick(prefix);
2963 userrec::QuitUser(this->Instance,y,"Nickname collision");
2965 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2969 target = who->server;
2970 const char* strparams[127];
2971 for (unsigned int q = 0; q < params.size(); q++)
2973 strparams[q] = params[q].c_str();
2975 if (!ServerInstance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
2977 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
2983 // its not a user. Its either a server, or somethings screwed up.
2984 if (IsServer(prefix))
2986 target = ServerInstance->Config->ServerName;
2990 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2994 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3003 virtual std::string GetName()
3005 std::string sourceserv = this->myhost;
3006 if (this->InboundServerName != "")
3008 sourceserv = this->InboundServerName;
3013 virtual void OnTimeout()
3015 if (this->LinkState == CONNECTING)
3017 ServerInstance->WriteOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
3021 virtual void OnClose()
3023 // Connection closed.
3024 // If the connection is fully up (state CONNECTED)
3025 // then propogate a netsplit to all peers.
3026 std::string quitserver = this->myhost;
3027 if (this->InboundServerName != "")
3029 quitserver = this->InboundServerName;
3031 TreeServer* s = FindServer(quitserver);
3034 Squit(s,"Remote host closed the connection");
3036 ServerInstance->WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
3039 virtual int OnIncomingConnection(int newsock, char* ip)
3041 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3042 * or discovering if this port is the server port, we don't allow connections from any
3043 * IPs for which we don't have a link block.
3047 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3050 for (vector<std::string>::iterator i = ValidIPs.begin(); i != ValidIPs.end(); i++)
3051 if (MatchCIDR(ip, (*i).c_str()))
3056 ServerInstance->WriteOpers("Server connection from %s denied (no link blocks with that IP address)", ip);
3061 TreeSocket* s = new TreeSocket(this->Instance, newsock, ip);
3062 ServerInstance->AddSocket(s);
3067 /** This class is used to resolve server hostnames during /connect and autoconnect.
3068 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3069 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3070 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3071 * will have an IP address which we can then use to continue our connection.
3073 class ServernameResolver : public Resolver
3076 /** A copy of the Link tag info for what we're connecting to.
3077 * We take a copy, rather than using a pointer, just in case the
3078 * admin takes the tag away and rehashes while the domain is resolving.
3082 ServernameResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
3084 /* Nothing in here, folks */
3087 void OnLookupComplete(const std::string &result)
3089 /* Initiate the connection, now that we have an IP to use.
3090 * Passing a hostname directly to InspSocket causes it to
3091 * just bail and set its FD to -1.
3093 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3094 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3096 TreeSocket* newsocket = new TreeSocket(ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str());
3097 if (newsocket->GetFd() > -1)
3100 ServerInstance->AddSocket(newsocket);
3104 /* Something barfed, show the opers */
3105 ServerInstance->WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3111 void OnError(ResolverError e, const std::string &errormessage)
3114 ServerInstance->WriteOpers("*** CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3118 class SecurityIPResolver : public Resolver
3123 SecurityIPResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
3127 void OnLookupComplete(const std::string &result)
3129 log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3130 ValidIPs.push_back(result);
3133 void OnError(ResolverError e, const std::string &errormessage)
3135 log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3139 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3141 for (unsigned int c = 0; c < list.size(); c++)
3143 if (list[c] == server)
3148 list.push_back(server);
3151 // returns a list of DIRECT servernames for a specific channel
3152 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3154 CUList *ulist = c->GetUsers();
3155 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3157 if (i->second->fd < 0)
3159 TreeServer* best = BestRouteTo(i->second->server);
3161 AddThisServer(best,list);
3167 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> ¶ms)
3169 TreeServer* omitroute = BestRouteTo(omit);
3170 if ((command == "NOTICE") || (command == "PRIVMSG"))
3172 if (params.size() >= 2)
3175 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3177 params[0] = params[0].substr(1, params[0].length()-1);
3179 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3181 // special routing for private messages/notices
3182 userrec* d = ServerInstance->FindNick(params[0]);
3185 std::deque<std::string> par;
3186 par.push_back(params[0]);
3187 par.push_back(":"+params[1]);
3188 DoOneToOne(prefix,command.c_str(),par,d->server);
3192 else if (*(params[0].c_str()) == '$')
3194 std::deque<std::string> par;
3195 par.push_back(params[0]);
3196 par.push_back(":"+params[1]);
3197 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3202 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3203 chanrec* c = ServerInstance->FindChan(params[0]);
3206 std::deque<TreeServer*> list;
3207 GetListOfServersForChannel(c,list);
3208 log(DEBUG,"Got a list of %d servers",list.size());
3209 unsigned int lsize = list.size();
3210 for (unsigned int i = 0; i < lsize; i++)
3212 TreeSocket* Sock = list[i]->GetSocket();
3213 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3215 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3216 Sock->WriteLine(data);
3224 unsigned int items = TreeRoot->ChildCount();
3225 for (unsigned int x = 0; x < items; x++)
3227 TreeServer* Route = TreeRoot->GetChild(x);
3228 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3230 TreeSocket* Sock = Route->GetSocket();
3231 Sock->WriteLine(data);
3237 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
3239 TreeServer* omitroute = BestRouteTo(omit);
3240 std::string FullLine = ":" + prefix + " " + command;
3241 unsigned int words = params.size();
3242 for (unsigned int x = 0; x < words; x++)
3244 FullLine = FullLine + " " + params[x];
3246 unsigned int items = TreeRoot->ChildCount();
3247 for (unsigned int x = 0; x < items; x++)
3249 TreeServer* Route = TreeRoot->GetChild(x);
3250 // Send the line IF:
3251 // The route has a socket (its a direct connection)
3252 // The route isnt the one to be omitted
3253 // The route isnt the path to the one to be omitted
3254 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3256 TreeSocket* Sock = Route->GetSocket();
3257 Sock->WriteLine(FullLine);
3263 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
3265 std::string FullLine = ":" + prefix + " " + command;
3266 unsigned int words = params.size();
3267 for (unsigned int x = 0; x < words; x++)
3269 FullLine = FullLine + " " + params[x];
3271 unsigned int items = TreeRoot->ChildCount();
3272 for (unsigned int x = 0; x < items; x++)
3274 TreeServer* Route = TreeRoot->GetChild(x);
3275 if (Route->GetSocket())
3277 TreeSocket* Sock = Route->GetSocket();
3278 Sock->WriteLine(FullLine);
3284 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
3286 TreeServer* Route = BestRouteTo(target);
3289 std::string FullLine = ":" + prefix + " " + command;
3290 unsigned int words = params.size();
3291 for (unsigned int x = 0; x < words; x++)
3293 FullLine = FullLine + " " + params[x];
3295 if (Route->GetSocket())
3297 TreeSocket* Sock = Route->GetSocket();
3298 Sock->WriteLine(FullLine);
3308 std::vector<TreeSocket*> Bindings;
3310 void ReadConfiguration(bool rebind)
3312 Conf = new ConfigReader;
3315 for (int j =0; j < Conf->Enumerate("bind"); j++)
3317 std::string Type = Conf->ReadValue("bind","type",j);
3318 std::string IP = Conf->ReadValue("bind","address",j);
3319 long Port = Conf->ReadInteger("bind","port",j,true);
3320 if (Type == "servers")
3326 TreeSocket* listener = new TreeSocket(ServerInstance, IP.c_str(),Port,true,10);
3327 if (listener->GetState() == I_LISTENING)
3329 ServerInstance->AddSocket(listener);
3330 Bindings.push_back(listener);
3334 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3341 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3342 HideULines = Conf->ReadFlag("options","hideulines",0);
3345 for (int j =0; j < Conf->Enumerate("link"); j++)
3348 std::string Allow = Conf->ReadValue("link","allowmask",j);
3349 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3350 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3351 L.Port = Conf->ReadInteger("link","port",j,true);
3352 L.SendPass = Conf->ReadValue("link","sendpass",j);
3353 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3354 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3355 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
3356 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3357 L.NextConnectTime = time(NULL) + L.AutoConnect;
3358 /* Bugfix by brain, do not allow people to enter bad configurations */
3359 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3361 ValidIPs.push_back(L.IPAddr);
3364 ValidIPs.push_back(Allow);
3366 /* Needs resolving */
3368 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3372 SecurityIPResolver* sr = new SecurityIPResolver(ServerInstance, L.IPAddr, L);
3373 ServerInstance->AddResolver(sr);
3375 catch (ModuleException& e)
3377 log(DEBUG,"Error in resolver: %s",e.GetReason());
3381 LinkBlocks.push_back(L);
3382 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3388 log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3390 else if (L.RecvPass == "")
3392 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3394 else if (L.SendPass == "")
3396 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3398 else if (L.Name == "")
3400 log(DEFAULT,"Invalid configuration, link tag without a name!");
3404 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3412 class ModuleSpanningTree : public Module
3414 std::vector<TreeSocket*> Bindings;
3417 unsigned int max_local;
3418 unsigned int max_global;
3419 cmd_rconnect* command_rconnect;
3423 ModuleSpanningTree(InspIRCd* Me)
3424 : Module::Module(Me), max_local(0), max_global(0)
3429 // Create the root of the tree
3430 TreeRoot = new TreeServer(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3432 ReadConfiguration(true);
3434 command_rconnect = new cmd_rconnect(ServerInstance, this);
3435 ServerInstance->AddCommand(command_rconnect);
3438 void ShowLinks(TreeServer* Current, userrec* user, int hops)
3440 std::string Parent = TreeRoot->GetName();
3441 if (Current->GetParent())
3443 Parent = Current->GetParent()->GetName();
3445 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3447 if ((HideULines) && (ServerInstance->IsUlined(Current->GetChild(q)->GetName())))
3451 ShowLinks(Current->GetChild(q),user,hops+1);
3456 ShowLinks(Current->GetChild(q),user,hops+1);
3459 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3460 if ((HideULines) && (ServerInstance->IsUlined(Current->GetName())) && (!*user->oper))
3462 user->WriteServ("364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(FlatLinks && (!*user->oper)) ? ServerInstance->Config->ServerName : Parent.c_str(),(FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3465 int CountLocalServs()
3467 return TreeRoot->ChildCount();
3472 return serverlist.size();
3475 void HandleLinks(const char** parameters, int pcnt, userrec* user)
3477 ShowLinks(TreeRoot,user,0);
3478 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
3482 void HandleLusers(const char** parameters, int pcnt, userrec* user)
3484 unsigned int n_users = ServerInstance->usercnt();
3486 /* Only update these when someone wants to see them, more efficient */
3487 if ((unsigned int)ServerInstance->local_count() > max_local)
3488 max_local = ServerInstance->local_count();
3489 if (n_users > max_global)
3490 max_global = n_users;
3492 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->usercount_invisible(),ServerInstance->usercount_invisible(),this->CountServs());
3493 if (ServerInstance->usercount_opers())
3494 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->usercount_opers());
3495 if (ServerInstance->usercount_unknown())
3496 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->usercount_unknown());
3497 if (ServerInstance->chancount())
3498 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->chancount());
3499 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->local_count(),this->CountLocalServs());
3500 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->local_count(),max_local);
3501 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
3505 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3507 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3511 for (int t = 0; t < depth; t++)
3513 matrix[line][t] = ' ';
3516 // For Aligning, we need to work out exactly how deep this thing is, and produce
3517 // a 'Spacer' String to compensate.
3520 memset(spacer,' ',40);
3521 if ((40 - Current->GetName().length() - depth) > 1) {
3522 spacer[40 - Current->GetName().length() - depth] = '\0';
3531 if (ServerInstance->clientlist.size() == 0) {
3532 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3537 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
3539 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3540 totusers += Current->GetUserCount();
3542 strlcpy(&matrix[line][depth],text,80);
3544 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3546 if ((HideULines) && (ServerInstance->IsUlined(Current->GetChild(q)->GetName())))
3550 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3555 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3561 int HandleStats(const char** parameters, int pcnt, userrec* user)
3565 /* Remote STATS, the server is within the 2nd parameter */
3566 std::deque<std::string> params;
3567 params.push_back(parameters[0]);
3568 params.push_back(parameters[1]);
3569 /* Send it out remotely, generate no reply yet */
3570 TreeServer* s = FindServerMask(parameters[1]);
3573 params[1] = s->GetName();
3574 DoOneToOne(user->nick, "STATS", params, s->GetName());
3578 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3585 // Ok, prepare to be confused.
3586 // After much mulling over how to approach this, it struck me that
3587 // the 'usual' way of doing a /MAP isnt the best way. Instead of
3588 // keeping track of a ton of ascii characters, and line by line
3589 // under recursion working out where to place them using multiplications
3590 // and divisons, we instead render the map onto a backplane of characters
3591 // (a character matrix), then draw the branches as a series of "L" shapes
3592 // from the nodes. This is not only friendlier on CPU it uses less stack.
3594 void HandleMap(const char** parameters, int pcnt, userrec* user)
3596 // This array represents a virtual screen which we will
3597 // "scratch" draw to, as the console device of an irc
3598 // client does not provide for a proper terminal.
3600 float totservers = 0;
3601 char matrix[128][80];
3602 for (unsigned int t = 0; t < 128; t++)
3604 matrix[t][0] = '\0';
3607 // The only recursive bit is called here.
3608 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3609 // Process each line one by one. The algorithm has a limit of
3610 // 128 servers (which is far more than a spanning tree should have
3611 // anyway, so we're ok). This limit can be raised simply by making
3612 // the character matrix deeper, 128 rows taking 10k of memory.
3613 for (int l = 1; l < line; l++)
3615 // scan across the line looking for the start of the
3616 // servername (the recursive part of the algorithm has placed
3617 // the servers at indented positions depending on what they
3619 int first_nonspace = 0;
3620 while (matrix[l][first_nonspace] == ' ')
3625 // Draw the `- (corner) section: this may be overwritten by
3626 // another L shape passing along the same vertical pane, becoming
3627 // a |- (branch) section instead.
3628 matrix[l][first_nonspace] = '-';
3629 matrix[l][first_nonspace-1] = '`';
3631 // Draw upwards until we hit the parent server, causing possibly
3632 // other corners (`-) to become branches (|-)
3633 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3635 matrix[l2][first_nonspace-1] = '|';
3639 // dump the whole lot to the user. This is the easy bit, honest.
3640 for (int t = 0; t < line; t++)
3642 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
3644 float avg_users = totusers / totservers;
3645 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);
3646 user->WriteServ("007 %s :End of /MAP",user->nick);
3650 int HandleSquit(const char** parameters, int pcnt, userrec* user)
3652 TreeServer* s = FindServerMask(parameters[0]);
3657 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3660 TreeSocket* sock = s->GetSocket();
3663 log(DEBUG,"Splitting server %s",s->GetName().c_str());
3664 ServerInstance->WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3665 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3666 ServerInstance->RemoveSocket(sock);
3670 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3675 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3680 int HandleTime(const char** parameters, int pcnt, userrec* user)
3682 if ((IS_LOCAL(user)) && (pcnt))
3684 TreeServer* found = FindServerMask(parameters[0]);
3687 // we dont' override for local server
3688 if (found == TreeRoot)
3691 std::deque<std::string> params;
3692 params.push_back(found->GetName());
3693 params.push_back(user->nick);
3694 DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
3698 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
3704 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3706 if ((IS_LOCAL(user)) && (pcnt > 1))
3708 userrec* remote = ServerInstance->FindNick(parameters[1]);
3709 if ((remote) && (remote->fd < 0))
3711 std::deque<std::string> params;
3712 params.push_back(parameters[1]);
3713 DoOneToOne(user->nick,"IDLE",params,remote->server);
3718 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
3719 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
3726 void DoPingChecks(time_t curtime)
3728 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
3730 TreeServer* serv = TreeRoot->GetChild(j);
3731 TreeSocket* sock = serv->GetSocket();
3734 if (curtime >= serv->NextPingTime())
3736 if (serv->AnsweredLastPing())
3738 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
3739 serv->SetNextPingTime(curtime + 120);
3743 // they didnt answer, boot them
3744 ServerInstance->WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
3745 sock->Squit(serv,"Ping timeout");
3746 ServerInstance->RemoveSocket(sock);
3754 void AutoConnectServers(time_t curtime)
3756 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3758 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
3760 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
3761 x->NextConnectTime = curtime + x->AutoConnect;
3762 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3765 // an autoconnected server is not connected. Check if its time to connect it
3766 ServerInstance->WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
3770 /* Do we already have an IP? If so, no need to resolve it. */
3771 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3773 TreeSocket* newsocket = new TreeSocket(ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str());
3774 if (newsocket->GetFd() > -1)
3776 ServerInstance->AddSocket(newsocket);
3780 ServerInstance->WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3788 ServernameResolver* snr = new ServernameResolver(ServerInstance,x->IPAddr, *x);
3789 ServerInstance->AddResolver(snr);
3791 catch (ModuleException& e)
3793 log(DEBUG,"Error in resolver: %s",e.GetReason());
3802 int HandleVersion(const char** parameters, int pcnt, userrec* user)
3804 // we've already checked if pcnt > 0, so this is safe
3805 TreeServer* found = FindServerMask(parameters[0]);
3808 std::string Version = found->GetVersion();
3809 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
3810 if (found == TreeRoot)
3812 std::stringstream out(ServerInstance->Config->data005);
3813 std::string token = "";
3814 std::string line5 = "";
3815 int token_counter = 0;
3820 line5 = line5 + token + " ";
3823 if ((token_counter >= 13) || (out.eof() == true))
3825 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
3834 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
3839 int HandleConnect(const char** parameters, int pcnt, userrec* user)
3841 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3843 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
3845 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3848 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);
3851 /* Do we already have an IP? If so, no need to resolve it. */
3852 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3854 TreeSocket* newsocket = new TreeSocket(ServerInstance,x->IPAddr,x->Port,false,10,x->Name.c_str());
3855 if (newsocket->GetFd() > -1)
3857 ServerInstance->AddSocket(newsocket);
3861 ServerInstance->WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3869 ServernameResolver* snr = new ServernameResolver(ServerInstance, x->IPAddr, *x);
3870 ServerInstance->AddResolver(snr);
3872 catch (ModuleException& e)
3874 log(DEBUG,"Error in resolver: %s",e.GetReason());
3881 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());
3886 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
3890 virtual int OnStats(char statschar, userrec* user, string_list &results)
3892 if (statschar == 'c')
3894 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
3896 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr)+" * "+LinkBlocks[i].Name.c_str()+" "+ConvToStr(LinkBlocks[i].Port)+" "+(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
3897 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
3899 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
3900 ServerInstance->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);
3906 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
3908 /* If the command doesnt appear to be valid, we dont want to mess with it. */
3912 if (command == "CONNECT")
3914 return this->HandleConnect(parameters,pcnt,user);
3916 else if (command == "STATS")
3918 return this->HandleStats(parameters,pcnt,user);
3920 else if (command == "SQUIT")
3922 return this->HandleSquit(parameters,pcnt,user);
3924 else if (command == "MAP")
3926 this->HandleMap(parameters,pcnt,user);
3929 else if ((command == "TIME") && (pcnt > 0))
3931 return this->HandleTime(parameters,pcnt,user);
3933 else if (command == "LUSERS")
3935 this->HandleLusers(parameters,pcnt,user);
3938 else if (command == "LINKS")
3940 this->HandleLinks(parameters,pcnt,user);
3943 else if (command == "WHOIS")
3948 return this->HandleRemoteWhois(parameters,pcnt,user);
3951 else if ((command == "VERSION") && (pcnt > 0))
3953 this->HandleVersion(parameters,pcnt,user);
3956 else if (ServerInstance->IsValidModuleCommand(command, pcnt, user))
3958 // this bit of code cleverly routes all module commands
3959 // to all remote severs *automatically* so that modules
3960 // can just handle commands locally, without having
3961 // to have any special provision in place for remote
3962 // commands and linking protocols.
3963 std::deque<std::string> params;
3965 for (int j = 0; j < pcnt; j++)
3967 if (strchr(parameters[j],' '))
3969 params.push_back(":" + std::string(parameters[j]));
3973 params.push_back(std::string(parameters[j]));
3976 log(DEBUG,"Globally route '%s'",command.c_str());
3977 DoOneToMany(user->nick,command,params);
3982 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
3984 TreeServer* s = FindServer(servername);
3987 description = s->GetDesc();
3991 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
3993 if (IS_LOCAL(source))
3995 std::deque<std::string> params;
3996 params.push_back(dest->nick);
3997 params.push_back(channel->name);
3998 DoOneToMany(source->nick,"INVITE",params);
4002 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4004 std::deque<std::string> params;
4005 params.push_back(chan->name);
4006 params.push_back(":"+topic);
4007 DoOneToMany(user->nick,"TOPIC",params);
4010 virtual void OnWallops(userrec* user, const std::string &text)
4014 std::deque<std::string> params;
4015 params.push_back(":"+text);
4016 DoOneToMany(user->nick,"WALLOPS",params);
4020 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4022 if (target_type == TYPE_USER)
4024 userrec* d = (userrec*)dest;
4025 if ((d->fd < 0) && (IS_LOCAL(user)))
4027 std::deque<std::string> params;
4029 params.push_back(d->nick);
4030 params.push_back(":"+text);
4031 DoOneToOne(user->nick,"NOTICE",params,d->server);
4034 else if (target_type == TYPE_CHANNEL)
4038 chanrec *c = (chanrec*)dest;
4039 std::string cname = c->name;
4041 cname = status + cname;
4042 std::deque<TreeServer*> list;
4043 GetListOfServersForChannel(c,list);
4044 unsigned int ucount = list.size();
4045 for (unsigned int i = 0; i < ucount; i++)
4047 TreeSocket* Sock = list[i]->GetSocket();
4049 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4053 else if (target_type == TYPE_SERVER)
4057 char* target = (char*)dest;
4058 std::deque<std::string> par;
4059 par.push_back(target);
4060 par.push_back(":"+text);
4061 DoOneToMany(user->nick,"NOTICE",par);
4066 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4068 if (target_type == TYPE_USER)
4070 // route private messages which are targetted at clients only to the server
4071 // which needs to receive them
4072 userrec* d = (userrec*)dest;
4073 if ((d->fd < 0) && (IS_LOCAL(user)))
4075 std::deque<std::string> params;
4077 params.push_back(d->nick);
4078 params.push_back(":"+text);
4079 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4082 else if (target_type == TYPE_CHANNEL)
4086 chanrec *c = (chanrec*)dest;
4087 std::string cname = c->name;
4089 cname = status + cname;
4090 std::deque<TreeServer*> list;
4091 GetListOfServersForChannel(c,list);
4092 unsigned int ucount = list.size();
4093 for (unsigned int i = 0; i < ucount; i++)
4095 TreeSocket* Sock = list[i]->GetSocket();
4097 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4101 else if (target_type == TYPE_SERVER)
4105 char* target = (char*)dest;
4106 std::deque<std::string> par;
4107 par.push_back(target);
4108 par.push_back(":"+text);
4109 DoOneToMany(user->nick,"PRIVMSG",par);
4114 virtual void OnBackgroundTimer(time_t curtime)
4116 AutoConnectServers(curtime);
4117 DoPingChecks(curtime);
4120 virtual void OnUserJoin(userrec* user, chanrec* channel)
4122 // Only do this for local users
4125 std::deque<std::string> params;
4127 params.push_back(channel->name);
4129 if (channel->GetUserCounter() > 1)
4131 // not the first in the channel
4132 DoOneToMany(user->nick,"JOIN",params);
4136 // first in the channel, set up their permissions
4137 // and the channel TS with FJOIN.
4139 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4141 params.push_back(channel->name);
4142 params.push_back(ts);
4143 params.push_back("@"+std::string(user->nick));
4144 DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4149 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4151 // only occurs for local clients
4152 if (user->registered != REG_ALL)
4154 std::deque<std::string> params;
4155 params.push_back(newhost);
4156 DoOneToMany(user->nick,"FHOST",params);
4159 virtual void OnChangeName(userrec* user, const std::string &gecos)
4161 // only occurs for local clients
4162 if (user->registered != REG_ALL)
4164 std::deque<std::string> params;
4165 params.push_back(gecos);
4166 DoOneToMany(user->nick,"FNAME",params);
4169 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4173 std::deque<std::string> params;
4174 params.push_back(channel->name);
4175 if (partmessage != "")
4176 params.push_back(":"+partmessage);
4177 DoOneToMany(user->nick,"PART",params);
4181 virtual void OnUserConnect(userrec* user)
4183 char agestr[MAXBUF];
4186 std::deque<std::string> params;
4187 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4188 params.push_back(agestr);
4189 params.push_back(user->nick);
4190 params.push_back(user->host);
4191 params.push_back(user->dhost);
4192 params.push_back(user->ident);
4193 params.push_back("+"+std::string(user->FormatModes()));
4194 params.push_back(user->GetIPString());
4195 params.push_back(":"+std::string(user->fullname));
4196 DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4198 // User is Local, change needs to be reflected!
4199 TreeServer* SourceServer = FindServer(user->server);
4202 SourceServer->AddUserCount();
4208 virtual void OnUserQuit(userrec* user, const std::string &reason)
4210 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4212 std::deque<std::string> params;
4213 params.push_back(":"+reason);
4214 DoOneToMany(user->nick,"QUIT",params);
4216 // Regardless, We need to modify the user Counts..
4217 TreeServer* SourceServer = FindServer(user->server);
4220 SourceServer->DelUserCount();
4225 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4229 std::deque<std::string> params;
4230 params.push_back(user->nick);
4231 DoOneToMany(oldnick,"NICK",params);
4235 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4237 if ((source) && (IS_LOCAL(source)))
4239 std::deque<std::string> params;
4240 params.push_back(chan->name);
4241 params.push_back(user->nick);
4242 params.push_back(":"+reason);
4243 DoOneToMany(source->nick,"KICK",params);
4247 std::deque<std::string> params;
4248 params.push_back(chan->name);
4249 params.push_back(user->nick);
4250 params.push_back(":"+reason);
4251 DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4255 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4257 std::deque<std::string> params;
4258 params.push_back(dest->nick);
4259 params.push_back(":"+reason);
4260 DoOneToMany(source->nick,"KILL",params);
4263 virtual void OnRehash(const std::string ¶meter)
4265 if (parameter != "")
4267 std::deque<std::string> params;
4268 params.push_back(parameter);
4269 DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4271 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4273 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4274 ServerInstance->RehashServer();
4277 ReadConfiguration(false);
4280 // note: the protocol does not allow direct umode +o except
4281 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4283 virtual void OnOper(userrec* user, const std::string &opertype)
4287 std::deque<std::string> params;
4288 params.push_back(opertype);
4289 DoOneToMany(user->nick,"OPERTYPE",params);
4293 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4295 if (IS_LOCAL(source))
4298 snprintf(type,8,"%cLINE",linetype);
4299 std::string stype = type;
4302 char sduration[MAXBUF];
4303 snprintf(sduration,MAXBUF,"%ld",duration);
4304 std::deque<std::string> params;
4305 params.push_back(host);
4306 params.push_back(sduration);
4307 params.push_back(":"+reason);
4308 DoOneToMany(source->nick,stype,params);
4312 std::deque<std::string> params;
4313 params.push_back(host);
4314 DoOneToMany(source->nick,stype,params);
4319 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4321 OnLine(source,hostmask,true,'G',duration,reason);
4324 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4326 OnLine(source,ipmask,true,'Z',duration,reason);
4329 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4331 OnLine(source,nickmask,true,'Q',duration,reason);
4334 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4336 OnLine(source,hostmask,true,'E',duration,reason);
4339 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4341 OnLine(source,hostmask,false,'G',0,"");
4344 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4346 OnLine(source,ipmask,false,'Z',0,"");
4349 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4351 OnLine(source,nickmask,false,'Q',0,"");
4354 virtual void OnDelELine(userrec* source, const std::string &hostmask)
4356 OnLine(source,hostmask,false,'E',0,"");
4359 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4361 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4363 if (target_type == TYPE_USER)
4365 userrec* u = (userrec*)dest;
4366 std::deque<std::string> params;
4367 params.push_back(u->nick);
4368 params.push_back(text);
4369 DoOneToMany(user->nick,"MODE",params);
4373 chanrec* c = (chanrec*)dest;
4374 std::deque<std::string> params;
4375 params.push_back(c->name);
4376 params.push_back(text);
4377 DoOneToMany(user->nick,"MODE",params);
4382 virtual void OnSetAway(userrec* user)
4386 std::deque<std::string> params;
4387 params.push_back(":"+std::string(user->awaymsg));
4388 DoOneToMany(user->nick,"AWAY",params);
4392 virtual void OnCancelAway(userrec* user)
4396 std::deque<std::string> params;
4398 DoOneToMany(user->nick,"AWAY",params);
4402 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4404 TreeSocket* s = (TreeSocket*)opaque;
4407 if (target_type == TYPE_USER)
4409 userrec* u = (userrec*)target;
4410 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4414 chanrec* c = (chanrec*)target;
4415 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4420 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4422 TreeSocket* s = (TreeSocket*)opaque;
4425 if (target_type == TYPE_USER)
4427 userrec* u = (userrec*)target;
4428 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
4430 else if (target_type == TYPE_OTHER)
4432 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
4434 else if (target_type == TYPE_CHANNEL)
4436 chanrec* c = (chanrec*)target;
4437 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
4442 virtual void OnEvent(Event* event)
4444 if (event->GetEventID() == "send_metadata")
4446 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4447 if (params->size() < 3)
4449 (*params)[2] = ":" + (*params)[2];
4450 DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
4452 else if (event->GetEventID() == "send_mode")
4454 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4455 if (params->size() < 2)
4457 // Insert the TS value of the object, either userrec or chanrec
4459 userrec* a = ServerInstance->FindNick((*params)[0]);
4466 chanrec* a = ServerInstance->FindChan((*params)[0]);
4472 params->insert(params->begin() + 1,ConvToStr(ourTS));
4473 DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
4477 virtual ~ModuleSpanningTree()
4481 virtual Version GetVersion()
4483 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4486 void Implements(char* List)
4488 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4489 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4490 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4491 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4492 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4493 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4494 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4497 /* It is IMPORTANT that m_spanningtree is the last module in the chain
4498 * so that any activity it sees is FINAL, e.g. we arent going to send out
4499 * a NICK message before m_cloaking has finished putting the +x on the user,
4501 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4502 * the module call queue.
4504 Priority Prioritize()
4506 return PRIORITY_LAST;
4511 class ModuleSpanningTreeFactory : public ModuleFactory
4514 ModuleSpanningTreeFactory()
4518 ~ModuleSpanningTreeFactory()
4522 virtual Module * CreateModule(InspIRCd* Me)
4524 TreeProtocolModule = new ModuleSpanningTree(Me);
4525 return TreeProtocolModule;
4531 extern "C" void * init_module( void )
4533 return new ModuleSpanningTreeFactory;