1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 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 <ext/hash_map>
36 #include "helperfuncs.h"
38 #include "inspstring.h"
43 #include "cull_list.h"
47 #define nspace __gnu_cxx
53 * The server list in InspIRCd is maintained as two structures
54 * which hold the data in different ways. Most of the time, we
55 * want to very quicky obtain three pieces of information:
57 * (1) The information on a server
58 * (2) The information on the server we must send data through
59 * to actually REACH the server we're after
60 * (3) Potentially, the child/parent objects of this server
62 * The InspIRCd spanning protocol provides easy access to these
63 * by storing the data firstly in a recursive structure, where
64 * each item references its parent item, and a dynamic list
65 * of child items, and another structure which stores the items
66 * hashed, linearly. This means that if we want to find a server
67 * by name quickly, we can look it up in the hash, avoiding
68 * any O(n) lookups. If however, during a split or sync, we want
69 * to apply an operation to a server, and any of its child objects
70 * we can resort to recursion to walk the tree structure.
73 class ModuleSpanningTree;
74 static ModuleSpanningTree* TreeProtocolModule;
76 extern ServerConfig* Config;
78 extern std::vector<Module*> modules;
79 extern std::vector<ircd_module*> factory;
82 /* Any socket can have one of five states at any one time.
83 * The LISTENER state indicates a socket which is listening
84 * for connections. It cannot receive data itself, only incoming
86 * The CONNECTING state indicates an outbound socket which is
87 * waiting to be writeable.
88 * The WAIT_AUTH_1 state indicates the socket is outbound and
89 * has successfully connected, but has not yet sent and received
91 * The WAIT_AUTH_2 state indicates that the socket is inbound
92 * (allocated by a LISTENER) but has not yet sent and received
94 * The CONNECTED state represents a fully authorized, fully
97 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
99 /* We need to import these from the core for use in netbursts */
100 extern user_hash clientlist;
101 extern chan_hash chanlist;
103 /* Foward declarations */
107 /* This variable represents the root of the server tree
108 * (for all intents and purposes, it's us)
110 TreeServer *TreeRoot;
114 /* This hash_map holds the hash equivalent of the server
115 * tree, used for rapid linear lookups.
117 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
118 server_hash serverlist;
120 /* More forward declarations */
121 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
122 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
123 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
124 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
125 void ReadConfiguration(bool rebind);
127 /* Imported from xline.cpp for use during netburst */
128 extern std::vector<KLine> klines;
129 extern std::vector<GLine> glines;
130 extern std::vector<ZLine> zlines;
131 extern std::vector<QLine> qlines;
132 extern std::vector<ELine> elines;
133 extern std::vector<KLine> pklines;
134 extern std::vector<GLine> pglines;
135 extern std::vector<ZLine> pzlines;
136 extern std::vector<QLine> pqlines;
137 extern std::vector<ELine> pelines;
139 /* Each server in the tree is represented by one class of
140 * type TreeServer. A locally connected TreeServer can
141 * have a class of type TreeSocket associated with it, for
142 * remote servers, the TreeSocket entry will be NULL.
143 * Each server also maintains a pointer to its parent
144 * (NULL if this server is ours, at the top of the tree)
145 * and a pointer to its "Route" (see the comments in the
146 * constructors below), and also a dynamic list of pointers
147 * to its children which can be iterated recursively
148 * if required. Creating or deleting objects of type
149 * TreeServer automatically maintains the hash_map of
150 * TreeServer items, deleting and inserting them as they
151 * are created and destroyed.
156 TreeServer* Parent; /* Parent entry */
157 TreeServer* Route; /* Route entry */
158 std::vector<TreeServer*> Children; /* List of child objects */
159 std::string ServerName; /* Server's name */
160 std::string ServerDesc; /* Server's description */
161 std::string VersionString; /* Version string or empty string */
162 int UserCount; /* Not used in this version */
163 int OperCount; /* Not used in this version */
164 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
165 time_t NextPing; /* After this time, the server should be PINGed*/
166 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
170 /* We don't use this constructor. Its a dummy, and won't cause any insertion
171 * of the TreeServer into the hash_map. See below for the two we DO use.
179 UserCount = OperCount = 0;
180 VersionString = Srv->GetVersion();
183 /* We use this constructor only to create the 'root' item, TreeRoot, which
184 * represents our own server. Therefore, it has no route, no parent, and
185 * no socket associated with it. Its version string is our own local version.
187 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
191 UserCount = OperCount = 0;
192 VersionString = Srv->GetVersion();
194 Socket = NULL; /* Fix by brain */
198 /* When we create a new server, we call this constructor to initialize it.
199 * This constructor initializes the server's Route and Parent, and sets up
200 * its ping counters so that it will be pinged one minute from now.
202 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
205 UserCount = OperCount = 0;
206 this->SetNextPingTime(time(NULL) + 60);
209 /* find the 'route' for this server (e.g. the one directly connected
210 * to the local server, which we can use to reach it)
212 * In the following example, consider we have just added a TreeServer
213 * class for server G on our network, of which we are server A.
214 * To route traffic to G (marked with a *) we must send the data to
215 * B (marked with a +) so this algorithm initializes the 'Route'
216 * value to point at whichever server traffic must be routed through
217 * to get here. If we were to try this algorithm with server B,
218 * the Route pointer would point at its own object ('this').
228 * We only run this algorithm when a server is created, as
229 * the routes remain constant while ever the server exists, and
230 * do not need to be re-calculated.
234 if (Route == TreeRoot)
240 while (this->Route->GetParent() != TreeRoot)
242 this->Route = Route->GetParent();
246 /* Because recursive code is slow and takes a lot of resources,
247 * we store two representations of the server tree. The first
248 * is a recursive structure where each server references its
249 * children and its parent, which is used for netbursts and
250 * netsplits to dump the whole dataset to the other server,
251 * and the second is used for very fast lookups when routing
252 * messages and is instead a hash_map, where each item can
253 * be referenced by its server name. The AddHashEntry()
254 * call below automatically inserts each TreeServer class
255 * into the hash_map as it is created. There is a similar
256 * maintainance call in the destructor to tidy up deleted
260 this->AddHashEntry();
263 /* This method is used to add the structure to the
264 * hash_map for linear searches. It is only called
265 * by the constructors.
269 server_hash::iterator iter;
270 iter = serverlist.find(this->ServerName);
271 if (iter == serverlist.end())
272 serverlist[this->ServerName] = this;
275 /* This method removes the reference to this object
276 * from the hash_map which is used for linear searches.
277 * It is only called by the default destructor.
281 server_hash::iterator iter;
282 iter = serverlist.find(this->ServerName);
283 if (iter != serverlist.end())
284 serverlist.erase(iter);
287 /* These accessors etc should be pretty self-
291 TreeServer* GetRoute()
296 std::string GetName()
301 std::string GetDesc()
306 std::string GetVersion()
308 return VersionString;
311 void SetNextPingTime(time_t t)
314 LastPingWasGood = false;
317 time_t NextPingTime()
322 bool AnsweredLastPing()
324 return LastPingWasGood;
329 LastPingWasGood = true;
342 TreeSocket* GetSocket()
347 TreeServer* GetParent()
352 void SetVersion(std::string Version)
354 VersionString = Version;
357 unsigned int ChildCount()
359 return Children.size();
362 TreeServer* GetChild(unsigned int n)
364 if (n < Children.size())
366 /* Make sure they cant request
367 * an out-of-range object. After
368 * all we know what these programmer
369 * types are like *grin*.
379 void AddChild(TreeServer* Child)
381 Children.push_back(Child);
384 bool DelChild(TreeServer* Child)
386 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
397 /* Removes child nodes of this node, and of that node, etc etc.
398 * This is used during netsplits to automatically tidy up the
399 * server tree. It is slow, we don't use it for much else.
403 bool stillchildren = true;
404 while (stillchildren)
406 stillchildren = false;
407 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
409 TreeServer* s = (TreeServer*)*a;
413 stillchildren = true;
422 /* We'd better tidy up after ourselves, eh? */
423 this->DelHashEntry();
427 /* The Link class might as well be a struct,
428 * but this is C++ and we don't believe in structs (!).
429 * It holds the entire information of one <link>
430 * tag from the main config file. We maintain a list
431 * of them, and populate the list on rehash/load.
440 std::string SendPass;
441 std::string RecvPass;
442 unsigned long AutoConnect;
443 time_t NextConnectTime;
444 std::string EncryptionKey;
447 /* The usual stuff for inspircd modules,
448 * plus the vector of Link classes which we
449 * use to store the <link> tags from the config
453 std::vector<Link> LinkBlocks;
455 /* Yay for fast searches!
456 * This is hundreds of times faster than recursion
457 * or even scanning a linked list, especially when
458 * there are more than a few servers to deal with.
461 TreeServer* FindServer(std::string ServerName)
463 server_hash::iterator iter;
464 iter = serverlist.find(ServerName);
465 if (iter != serverlist.end())
475 /* Returns the locally connected server we must route a
476 * message through to reach server 'ServerName'. This
477 * only applies to one-to-one and not one-to-many routing.
478 * See the comments for the constructor of TreeServer
481 TreeServer* BestRouteTo(std::string ServerName)
483 if (ServerName.c_str() == TreeRoot->GetName())
485 TreeServer* Found = FindServer(ServerName);
488 return Found->GetRoute();
496 /* Find the first server matching a given glob mask.
497 * Theres no find-using-glob method of hash_map [awwww :-(]
498 * so instead, we iterate over the list using an iterator
499 * and match each one until we get a hit. Yes its slow,
502 TreeServer* FindServerMask(std::string ServerName)
504 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
506 if (Srv->MatchText(i->first,ServerName))
512 /* A convenient wrapper that returns true if a server exists */
513 bool IsServer(std::string ServerName)
515 return (FindServer(ServerName) != NULL);
518 /* Every SERVER connection inbound or outbound is represented by
519 * an object of type TreeSocket.
520 * TreeSockets, being inherited from InspSocket, can be tied into
521 * the core socket engine, and we cn therefore receive activity events
522 * for them, just like activex objects on speed. (yes really, that
523 * is a technical term!) Each of these which relates to a locally
524 * connected server is assocated with it, by hooking it onto a
525 * TreeSocket class using its constructor. In this way, we can
526 * maintain a list of servers, some of which are directly connected,
527 * some of which are not.
530 class TreeSocket : public InspSocket
533 std::string in_buffer;
534 ServerState LinkState;
535 std::string InboundServerName;
536 std::string InboundDescription;
538 int num_lost_servers;
540 bool LastPingWasGood;
543 unsigned int keylength;
547 /* Because most of the I/O gubbins are encapsulated within
548 * InspSocket, we just call the superclass constructor for
549 * most of the action, and append a few of our own values
552 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
553 : InspSocket(host, port, listening, maxtime)
556 this->LinkState = LISTENER;
560 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
561 : InspSocket(host, port, listening, maxtime)
564 this->LinkState = CONNECTING;
568 /* When a listening socket gives us a new file descriptor,
569 * we must associate it with a socket without creating a new
570 * connection. This constructor is used for this purpose.
572 TreeSocket(int newfd, char* ip)
573 : InspSocket(newfd, ip)
575 this->LinkState = WAIT_AUTH_1;
577 this->SendCapabilities();
586 void InitAES(std::string key,std::string SName)
592 log(DEBUG,"Initialized AES key %s",key.c_str());
593 // key must be 16, 24, 32 etc bytes (multiple of 8)
594 keylength = key.length();
595 if (!(keylength == 16 || keylength == 24 || keylength == 32))
597 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
598 log(DEBUG,"Key length not 16, 24 or 32 characters!");
602 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
603 ctx->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\
604 \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);
608 /* When an outbound connection finishes connecting, we receive
609 * this event, and must send our SERVER string to the other
610 * side. If the other side is happy, as outlined in the server
611 * to server docs on the inspircd.org site, the other side
612 * will then send back its own server string.
614 virtual bool OnConnected()
616 if (this->LinkState == CONNECTING)
618 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
619 /* we do not need to change state here. */
620 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
622 if (x->Name == this->myhost)
624 this->SendCapabilities();
625 if (x->EncryptionKey != "")
627 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
629 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
633 this->WriteLine("AES "+Srv->GetServerName());
634 this->InitAES(x->EncryptionKey,x->Name);
637 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
638 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
643 /* There is a (remote) chance that between the /CONNECT and the connection
644 * being accepted, some muppet has removed the <link> block and rehashed.
645 * If that happens the connection hangs here until it's closed. Unlikely
646 * and rather harmless.
651 virtual void OnError(InspSocketError e)
653 /* We don't handle this method, because all our
654 * dirty work is done in OnClose() (see below)
655 * which is still called on error conditions too.
659 virtual int OnDisconnect()
661 /* For the same reason as above, we don't
662 * handle OnDisconnect()
667 /* Recursively send the server tree with distances as hops.
668 * This is used during network burst to inform the other server
669 * (and any of ITS servers too) of what servers we know about.
670 * If at any point any of these servers already exist on the other
671 * end, our connection may be terminated. The hopcounts given
672 * by this function are relative, this doesn't matter so long as
673 * they are all >1, as all the remote servers re-calculate them
674 * to be relative too, with themselves as hop 0.
676 void SendServers(TreeServer* Current, TreeServer* s, int hops)
679 for (unsigned int q = 0; q < Current->ChildCount(); q++)
681 TreeServer* recursive_server = Current->GetChild(q);
682 if (recursive_server != s)
684 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
685 this->WriteLine(command);
686 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
687 /* down to next level */
688 this->SendServers(recursive_server, s, hops+1);
693 std::string MyCapabilities()
695 ServerConfig* Config = Srv->GetConfig();
696 std::vector<std::string> modlist;
697 std::string capabilities = "";
699 for (int i = 0; i <= MODCOUNT; i++)
701 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
702 modlist.push_back(Config->module_names[i]);
704 sort(modlist.begin(),modlist.end());
705 for (unsigned int i = 0; i < modlist.size(); i++)
708 capabilities = capabilities + ",";
709 capabilities = capabilities + modlist[i];
714 void SendCapabilities()
716 this->WriteLine("CAPAB "+MyCapabilities());
719 bool Capab(std::deque<std::string> params)
721 if (params.size() != 1)
723 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
726 if (params[0] != this->MyCapabilities())
728 std::string quitserver = this->myhost;
729 if (this->InboundServerName != "")
731 quitserver = this->InboundServerName;
733 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
734 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
735 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
736 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
737 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
743 /* This function forces this server to quit, removing this server
744 * and any users on it (and servers and users below that, etc etc).
745 * It's very slow and pretty clunky, but luckily unless your network
746 * is having a REAL bad hair day, this function shouldnt be called
747 * too many times a month ;-)
749 void SquitServer(TreeServer* Current, CullList* Goners)
751 /* recursively squit the servers attached to 'Current'.
752 * We're going backwards so we don't remove users
753 * while we still need them ;)
755 for (unsigned int q = 0; q < Current->ChildCount(); q++)
757 TreeServer* recursive_server = Current->GetChild(q);
758 this->SquitServer(recursive_server,Goners);
760 /* Now we've whacked the kids, whack self */
762 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
764 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
766 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
767 Goners->AddItem(u->second,qreason);
773 /* This is a wrapper function for SquitServer above, which
774 * does some validation first and passes on the SQUIT to all
775 * other remaining servers.
777 void Squit(TreeServer* Current,std::string reason)
779 if ((Current) && (Current != TreeRoot))
781 std::deque<std::string> params;
782 params.push_back(Current->GetName());
783 params.push_back(":"+reason);
784 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
785 if (Current->GetParent() == TreeRoot)
787 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
791 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
793 num_lost_servers = 0;
795 CullList* Goners = new CullList();
796 SquitServer(Current, Goners);
799 Current->GetParent()->DelChild(Current);
802 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
806 log(DEFAULT,"Squit from unknown server");
811 bool ForceMode(std::string source, std::deque<std::string> params)
813 userrec* who = new userrec;
814 who->fd = FD_MAGIC_NUMBER;
815 if (params.size() < 2)
818 for (unsigned int q = 0; q < params.size(); q++)
820 modelist[q] = (char*)params[q].c_str();
822 Srv->SendMode(modelist,params.size(),who);
823 DoOneToAllButSender(source,"FMODE",params,source);
829 bool ForceTopic(std::string source, std::deque<std::string> params)
831 if (params.size() != 4)
833 std::string channel = params[0];
834 time_t ts = atoi(params[1].c_str());
835 std::string setby = params[2];
836 std::string topic = params[3];
838 chanrec* c = Srv->FindChannel(channel);
841 if ((ts >= c->topicset) || (!*c->topic))
843 std::string oldtopic = c->topic;
844 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
845 strlcpy(c->setby,setby.c_str(),NICKMAX);
847 /* if the topic text is the same as the current topic,
848 * dont bother to send the TOPIC command out, just silently
849 * update the set time and set nick.
851 if (oldtopic != topic)
852 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
857 /* all done, send it on its way */
858 params[3] = ":" + params[3];
859 DoOneToAllButSender(source,"FTOPIC",params,source);
864 /* FJOIN, similar to unreal SJOIN */
865 bool ForceJoin(std::string source, std::deque<std::string> params)
867 if (params.size() < 3)
871 char modestring[MAXBUF];
872 char* mode_users[127];
873 mode_users[0] = first;
874 mode_users[1] = modestring;
875 strcpy(mode_users[1],"+");
876 unsigned int modectr = 2;
879 std::string channel = params[0];
880 time_t TS = atoi(params[1].c_str());
883 chanrec* chan = Srv->FindChannel(channel);
888 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
890 /* default is a high value, which if we dont have this
891 * channel will let the other side apply their modes.
893 time_t ourTS = time(NULL)+600;
894 chanrec* us = Srv->FindChannel(channel);
900 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
902 /* do this first, so our mode reversals are correctly received by other servers
903 * if there is a TS collision.
905 DoOneToAllButSender(source,"FJOIN",params,source);
907 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
909 /* process one channel at a time, applying modes. */
910 char* usr = (char*)params[usernum].c_str();
911 char permissions = *usr;
916 mode_users[modectr++] = usr;
917 strlcat(modestring,"o",MAXBUF);
921 mode_users[modectr++] = usr;
922 strlcat(modestring,"h",MAXBUF);
926 mode_users[modectr++] = usr;
927 strlcat(modestring,"v",MAXBUF);
930 who = Srv->FindNick(usr);
933 Srv->JoinUserToChannel(who,channel,key);
934 if (modectr >= (MAXMODES-1))
936 /* theres a mode for this user. push them onto the mode queue, and flush it
937 * if there are more than MAXMODES to go.
939 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
941 /* We also always let u-lined clients win, no matter what the TS value */
942 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
943 Srv->SendMode(mode_users,modectr,who);
947 log(DEBUG,"Their channel newer than ours, bouncing their modes");
949 std::deque<std::string> params;
950 /* modes are now being UNSET... */
951 *mode_users[1] = '-';
952 for (unsigned int x = 0; x < modectr; x++)
954 params.push_back(mode_users[x]);
956 // tell everyone to bounce the modes. bad modes, bad!
957 DoOneToMany(Srv->GetServerName(),"FMODE",params);
959 strcpy(mode_users[1],"+");
964 /* there werent enough modes built up to flush it during FJOIN,
965 * or, there are a number left over. flush them out.
967 if ((modectr > 2) && (who))
971 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
972 Srv->SendMode(mode_users,modectr,who);
976 log(DEBUG,"Their channel newer than ours, bouncing their modes");
977 std::deque<std::string> params;
978 *mode_users[1] = '-';
979 for (unsigned int x = 0; x < modectr; x++)
981 params.push_back(mode_users[x]);
983 DoOneToMany(Srv->GetServerName(),"FMODE",params);
990 bool IntroduceClient(std::string source, std::deque<std::string> params)
992 if (params.size() < 8)
994 // NICK age nick host dhost ident +modes ip :gecos
996 std::string nick = params[1];
997 std::string host = params[2];
998 std::string dhost = params[3];
999 std::string ident = params[4];
1000 time_t age = atoi(params[0].c_str());
1001 std::string modes = params[5];
1002 while (*(modes.c_str()) == '+')
1004 char* m = (char*)modes.c_str();
1008 std::string ip = params[6];
1009 std::string gecos = params[7];
1010 char* tempnick = (char*)nick.c_str();
1011 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1013 user_hash::iterator iter;
1014 iter = clientlist.find(tempnick);
1015 if (iter != clientlist.end())
1018 log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,ident.c_str(),host.c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1019 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1023 clientlist[tempnick] = new userrec();
1024 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1025 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1026 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1027 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1028 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1029 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1030 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1031 clientlist[tempnick]->registered = 7;
1032 clientlist[tempnick]->signon = age;
1033 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1034 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1039 for (int i = 0; i < MAXCHANS; i++)
1040 clientlist[tempnick]->chans.push_back(a);
1042 if (!this->bursting)
1044 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1046 params[7] = ":" + params[7];
1047 DoOneToAllButSender(source,"NICK",params,source);
1051 /* Send one or more FJOINs for a channel of users.
1052 * If the length of a single line is more than 480-NICKMAX
1053 * in length, it is split over multiple lines.
1055 void SendFJoins(TreeServer* Current, chanrec* c)
1057 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1059 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1060 std::vector<char*> *ulist = c->GetUsers();
1061 for (unsigned int i = 0; i < ulist->size(); i++)
1063 char* o = (*ulist)[i];
1064 userrec* otheruser = (userrec*)o;
1065 strlcat(list," ",MAXBUF);
1066 strlcat(list,cmode(otheruser,c),MAXBUF);
1067 strlcat(list,otheruser->nick,MAXBUF);
1068 if (strlen(list)>(480-NICKMAX))
1070 log(DEBUG,"FJOIN line wrapped");
1071 this->WriteLine(list);
1072 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1075 if (list[strlen(list)-1] != ':')
1077 log(DEBUG,"Final FJOIN line");
1078 this->WriteLine(list);
1082 /* Send G, Q, Z and E lines */
1083 void SendXLines(TreeServer* Current)
1086 /* Yes, these arent too nice looking, but they get the job done */
1087 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1089 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1090 this->WriteLine(data);
1092 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1094 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1095 this->WriteLine(data);
1097 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1099 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1100 this->WriteLine(data);
1102 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1104 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1105 this->WriteLine(data);
1107 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1109 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1110 this->WriteLine(data);
1112 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1114 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1115 this->WriteLine(data);
1117 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1119 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1120 this->WriteLine(data);
1122 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1124 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1125 this->WriteLine(data);
1129 /* Send channel modes and topics */
1130 void SendChannelModes(TreeServer* Current)
1133 std::deque<std::string> list;
1134 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1136 SendFJoins(Current, c->second);
1137 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1138 this->WriteLine(data);
1139 if (*c->second->topic)
1141 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",Srv->GetServerName().c_str(),c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1142 this->WriteLine(data);
1144 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1146 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1147 this->WriteLine(data);
1149 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1151 c->second->GetExtList(list);
1152 for (unsigned int j = 0; j < list.size(); j++)
1154 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1159 /* send all users and their oper state/modes */
1160 void SendUsers(TreeServer* Current)
1163 std::deque<std::string> list;
1164 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1166 if (u->second->registered == 7)
1168 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->modes,u->second->ip,u->second->fullname);
1169 this->WriteLine(data);
1170 if (strchr(u->second->modes,'o'))
1172 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1174 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1176 u->second->GetExtList(list);
1177 for (unsigned int j = 0; j < list.size(); j++)
1179 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1185 /* This function is called when we want to send a netburst to a local
1186 * server. There is a set order we must do this, because for example
1187 * users require their servers to exist, and channels require their
1188 * users to exist. You get the idea.
1190 void DoBurst(TreeServer* s)
1192 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1193 this->WriteLine("BURST");
1194 /* send our version string */
1195 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1196 /* Send server tree */
1197 this->SendServers(TreeRoot,s,1);
1198 /* Send users and their oper status */
1200 /* Send everything else (channel modes, xlines etc) */
1201 this->SendChannelModes(s);
1202 this->SendXLines(s);
1203 this->WriteLine("ENDBURST");
1204 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1207 /* This function is called when we receive data from a remote
1208 * server. We buffer the data in a std::string (it doesnt stay
1209 * there for long), reading using InspSocket::Read() which can
1210 * read up to 16 kilobytes in one operation.
1212 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1213 * THE SOCKET OBJECT FOR US.
1215 virtual bool OnDataReady()
1217 char* data = this->Read();
1220 this->in_buffer += data;
1221 /* While there is at least one new line in the buffer,
1222 * do something useful (we hope!) with it.
1224 while (in_buffer.find("\n") != std::string::npos)
1226 char* line = (char*)in_buffer.c_str();
1227 std::string ret = "";
1228 while ((*line != '\n') && (strlen(line)))
1233 if ((*line == '\n') || (*line == '\r'))
1236 /* Process this one, abort if it
1237 * didnt return true.
1243 memset(result,0,1024);
1245 log(DEBUG,"Original string '%s'",ret.c_str());
1246 /* ERROR + CAPAB is still allowed unencryped */
1247 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1249 int nbytes = from64tobits(out, ret.c_str(), 1024);
1252 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1253 ctx->Decrypt(out, result, nbytes, 0);
1254 for (int t = 0; t < nbytes; t++)
1255 if (result[t] == '\7') result[t] = 0;
1260 if (!this->ProcessLine(ret))
1266 return (data != NULL);
1269 int WriteLine(std::string line)
1271 log(DEBUG,"OUT: %s",line.c_str());
1274 log(DEBUG,"AES context");
1276 char result64[10240];
1277 if (this->keylength)
1279 while (line.length() % this->keylength != 0)
1281 // pad it to be a multiple of the key length
1285 unsigned int ll = line.length();
1286 log(DEBUG,"Plaintext line with padding = %d chars",ll);
1287 ctx->Encrypt(line.c_str(), result, ll, 0);
1288 log(DEBUG,"Encrypted.");
1289 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1291 log(DEBUG,"Encrypted: %s",line.c_str());
1292 //int from64tobits(char *out, const char *in, int maxlen);
1294 return this->Write(line + "\r\n");
1297 /* Handle ERROR command */
1298 bool Error(std::deque<std::string> params)
1300 if (params.size() < 1)
1302 std::string Errmsg = params[0];
1303 std::string SName = myhost;
1304 if (InboundServerName != "")
1306 SName = InboundServerName;
1308 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1309 /* we will return false to cause the socket to close.
1314 /* Because the core won't let users or even SERVERS set +o,
1315 * we use the OPERTYPE command to do this.
1317 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1319 if (params.size() != 1)
1321 std::string opertype = params[0];
1322 userrec* u = Srv->FindNick(prefix);
1325 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1326 if (!strchr(u->modes,'o'))
1328 strcat(u->modes,"o");
1330 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1335 /* Because Andy insists that services-compatible servers must
1336 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1338 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1340 if (params.size() < 3)
1342 userrec* u = Srv->FindNick(params[0]);
1345 Srv->ChangeUserNick(u,params[1]);
1346 u->age = atoi(params[2].c_str());
1347 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1352 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1354 if (params.size() < 2)
1356 userrec* u = Srv->FindNick(params[0]);
1359 Srv->JoinUserToChannel(u,params[1],"");
1360 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1365 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1367 if (params.size() < 1)
1369 std::string servermask = params[0];
1370 if (Srv->MatchText(Srv->GetServerName(),servermask))
1372 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1373 Srv->RehashServer();
1374 ReadConfiguration(false);
1376 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1380 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1382 if (params.size() != 2)
1384 std::string nick = params[0];
1385 userrec* u = Srv->FindNick(prefix);
1386 userrec* who = Srv->FindNick(nick);
1389 /* Prepend kill source, if we don't have one */
1390 std::string sourceserv = prefix;
1393 sourceserv = u->server;
1395 if (*(params[1].c_str()) != '[')
1397 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1399 std::string reason = params[1];
1400 params[1] = ":" + params[1];
1401 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1402 Srv->QuitUser(who,reason);
1407 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1409 if (params.size() < 1)
1411 TreeServer* ServerSource = FindServer(prefix);
1414 ServerSource->SetPingFlag();
1419 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1421 if (params.size() < 3)
1423 TreeServer* ServerSource = FindServer(prefix);
1426 if (*(params[0].c_str()) == '#')
1428 chanrec* c = Srv->FindChannel(params[0]);
1431 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1436 userrec* u = Srv->FindNick(params[0]);
1439 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1443 params[2] = ":" + params[2];
1444 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1448 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1450 if (params.size() < 1)
1452 TreeServer* ServerSource = FindServer(prefix);
1455 ServerSource->SetVersion(params[0]);
1457 params[0] = ":" + params[0];
1458 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1462 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1464 if (params.size() < 1)
1466 userrec* u = Srv->FindNick(prefix);
1469 Srv->ChangeHost(u,params[0]);
1470 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1475 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1477 if (params.size() < 6)
1479 std::string linetype = params[0]; /* Z, Q, E, G, K */
1480 std::string mask = params[1]; /* Line type dependent */
1481 std::string source = params[2]; /* may not be online or may be a server */
1482 std::string settime = params[3]; /* EPOCH time set */
1483 std::string duration = params[4]; /* Duration secs */
1484 std::string reason = params[5];
1486 switch (*(linetype.c_str()))
1489 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1490 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1493 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1494 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1497 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1498 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1501 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1502 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1505 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1508 /* Just in case... */
1509 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1512 /* Send it on its way */
1513 params[5] = ":" + params[5];
1514 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1518 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1520 if (params.size() < 1)
1522 userrec* u = Srv->FindNick(prefix);
1525 Srv->ChangeGECOS(u,params[0]);
1526 params[0] = ":" + params[0];
1527 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1532 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1534 if (params.size() < 1)
1536 log(DEBUG,"In IDLE command");
1537 userrec* u = Srv->FindNick(prefix);
1540 log(DEBUG,"USER EXISTS: %s",u->nick);
1541 // an incoming request
1542 if (params.size() == 1)
1544 userrec* x = Srv->FindNick(params[0]);
1547 userrec* x = Srv->FindNick(params[0]);
1548 log(DEBUG,"Got IDLE");
1549 char signon[MAXBUF];
1551 log(DEBUG,"Sending back IDLE 3");
1552 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1553 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1554 std::deque<std::string> par;
1555 par.push_back(prefix);
1556 par.push_back(signon);
1557 par.push_back(idle);
1558 // ours, we're done, pass it BACK
1559 DoOneToOne(params[0],"IDLE",par,u->server);
1563 // not ours pass it on
1564 DoOneToOne(prefix,"IDLE",params,x->server);
1567 else if (params.size() == 3)
1569 std::string who_did_the_whois = params[0];
1570 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1571 if (who_to_send_to->fd > -1)
1573 log(DEBUG,"Got final IDLE");
1574 // an incoming reply to a whois we sent out
1575 std::string nick_whoised = prefix;
1576 unsigned long signon = atoi(params[1].c_str());
1577 unsigned long idle = atoi(params[2].c_str());
1578 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1579 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1583 // not ours, pass it on
1584 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1591 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1593 if (params.size() < 1)
1595 std::string stufftobounce = params[0];
1596 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1600 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1602 if (params.size() < 4)
1604 std::string servername = params[0];
1605 std::string password = params[1];
1606 // hopcount is not used for a remote server, we calculate this ourselves
1607 std::string description = params[3];
1608 TreeServer* ParentOfThis = FindServer(prefix);
1611 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1614 TreeServer* CheckDupe = FindServer(servername);
1617 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1618 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1621 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1622 ParentOfThis->AddChild(Node);
1623 params[3] = ":" + params[3];
1624 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1625 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1629 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1631 if (params.size() < 4)
1633 std::string servername = params[0];
1634 std::string password = params[1];
1635 int hops = atoi(params[2].c_str());
1638 this->WriteLine("ERROR :Server too far away for authentication");
1639 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1642 std::string description = params[3];
1643 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1645 if ((x->Name == servername) && (x->RecvPass == password))
1647 TreeServer* CheckDupe = FindServer(servername);
1650 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1651 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1654 // Begin the sync here. this kickstarts the
1655 // other side, waiting in WAIT_AUTH_2 state,
1656 // into starting their burst, as it shows
1657 // that we're happy.
1658 this->LinkState = CONNECTED;
1659 // we should add the details of this server now
1660 // to the servers tree, as a child of the root
1662 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1663 TreeRoot->AddChild(Node);
1664 params[3] = ":" + params[3];
1665 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1666 this->bursting = true;
1667 this->DoBurst(Node);
1671 this->WriteLine("ERROR :Invalid credentials");
1672 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1676 bool Inbound_Server(std::deque<std::string> ¶ms)
1678 if (params.size() < 4)
1680 std::string servername = params[0];
1681 std::string password = params[1];
1682 int hops = atoi(params[2].c_str());
1685 this->WriteLine("ERROR :Server too far away for authentication");
1686 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1689 std::string description = params[3];
1690 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1692 if ((x->Name == servername) && (x->RecvPass == password))
1694 TreeServer* CheckDupe = FindServer(servername);
1697 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1698 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1701 /* If the config says this link is encrypted, but the remote side
1702 * hasnt bothered to send the AES command before SERVER, then we
1703 * boot them off as we MUST have this connection encrypted.
1705 if ((x->EncryptionKey != "") && (!this->ctx))
1707 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1708 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1711 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1712 this->InboundServerName = servername;
1713 this->InboundDescription = description;
1714 // this is good. Send our details: Our server name and description and hopcount of 0,
1715 // along with the sendpass from this block.
1716 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1717 // move to the next state, we are now waiting for THEM.
1718 this->LinkState = WAIT_AUTH_2;
1722 this->WriteLine("ERROR :Invalid credentials");
1723 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1727 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1729 if (!strchr(line.c_str(),' '))
1734 std::stringstream s(line);
1735 std::string param = "";
1754 if ((param == ":") && (item > 0))
1777 bool ProcessLine(std::string line)
1779 char* l = (char*)line.c_str();
1780 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1781 l[strlen(l)-1] = '\0';
1785 Srv->Log(DEBUG,"IN: "+line);
1786 std::deque<std::string> params;
1787 this->Split(line,true,params);
1788 std::string command = "";
1789 std::string prefix = "";
1790 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1793 command = params[1];
1794 char* pref = (char*)prefix.c_str();
1802 command = params[0];
1806 if ((!this->ctx) && (command == "AES"))
1808 std::string sserv = params[0];
1809 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1811 if ((x->EncryptionKey != "") && (x->Name == sserv))
1813 this->InitAES(x->EncryptionKey,sserv);
1818 else if ((this->ctx) && (command == "AES"))
1820 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1823 switch (this->LinkState)
1828 // Waiting for SERVER command from remote server. Server initiating
1829 // the connection sends the first SERVER command, listening server
1830 // replies with theirs if its happy, then if the initiator is happy,
1831 // it starts to send its net sync, which starts the merge, otherwise
1832 // it sends an ERROR.
1833 if (command == "PASS")
1835 /* Silently ignored */
1837 else if (command == "SERVER")
1839 return this->Inbound_Server(params);
1841 else if (command == "ERROR")
1843 return this->Error(params);
1845 else if (command == "USER")
1847 this->WriteLine("ERROR :Client connections to this port are prohibited.");
1850 else if (command == "CAPAB")
1852 return this->Capab(params);
1856 this->WriteLine("ERROR :Invalid command in negotiation phase.");
1861 // Waiting for start of other side's netmerge to say they liked our
1863 if (command == "SERVER")
1865 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1869 else if (command == "BURST")
1871 this->LinkState = CONNECTED;
1872 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1873 TreeRoot->AddChild(Node);
1875 params.push_back(InboundServerName);
1876 params.push_back("*");
1877 params.push_back("1");
1878 params.push_back(":"+InboundDescription);
1879 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1880 this->bursting = true;
1881 this->DoBurst(Node);
1883 else if (command == "ERROR")
1885 return this->Error(params);
1887 else if (command == "CAPAB")
1889 return this->Capab(params);
1894 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1898 if (command == "SERVER")
1900 // another server we connected to, which was in WAIT_AUTH_1 state,
1901 // has just sent us their credentials. If we get this far, theyre
1902 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1903 // if we're happy with this, we should send our netburst which
1904 // kickstarts the merge.
1905 return this->Outbound_Reply_Server(params);
1907 else if (command == "ERROR")
1909 return this->Error(params);
1913 // This is the 'authenticated' state, when all passwords
1914 // have been exchanged and anything past this point is taken
1919 std::string direction = prefix;
1920 userrec* t = Srv->FindNick(prefix);
1923 direction = t->server;
1925 TreeServer* route_back_again = BestRouteTo(direction);
1926 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1928 if (route_back_again)
1930 WriteOpers("*** Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1934 WriteOpers("*** Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1941 if (command == "SVSMODE")
1943 /* Services expects us to implement
1944 * SVSMODE. In inspircd its the same as
1949 std::string target = "";
1950 /* Yes, know, this is a mess. Its reasonably fast though as we're
1951 * working with std::string here.
1953 if ((command == "NICK") && (params.size() > 1))
1955 return this->IntroduceClient(prefix,params);
1957 else if (command == "FJOIN")
1959 return this->ForceJoin(prefix,params);
1961 else if (command == "SERVER")
1963 return this->RemoteServer(prefix,params);
1965 else if (command == "ERROR")
1967 return this->Error(params);
1969 else if (command == "OPERTYPE")
1971 return this->OperType(prefix,params);
1973 else if (command == "FMODE")
1975 return this->ForceMode(prefix,params);
1977 else if (command == "KILL")
1979 return this->RemoteKill(prefix,params);
1981 else if (command == "FTOPIC")
1983 return this->ForceTopic(prefix,params);
1985 else if (command == "REHASH")
1987 return this->RemoteRehash(prefix,params);
1989 else if (command == "METADATA")
1991 return this->MetaData(prefix,params);
1993 else if (command == "PING")
1995 return this->LocalPing(prefix,params);
1997 else if (command == "PONG")
1999 return this->LocalPong(prefix,params);
2001 else if (command == "VERSION")
2003 return this->ServerVersion(prefix,params);
2005 else if (command == "FHOST")
2007 return this->ChangeHost(prefix,params);
2009 else if (command == "FNAME")
2011 return this->ChangeName(prefix,params);
2013 else if (command == "ADDLINE")
2015 return this->AddLine(prefix,params);
2017 else if (command == "SVSNICK")
2021 prefix = this->GetName();
2023 return this->ForceNick(prefix,params);
2025 else if (command == "IDLE")
2027 return this->Whois(prefix,params);
2029 else if (command == "SVSJOIN")
2033 prefix = this->GetName();
2035 return this->ServiceJoin(prefix,params);
2037 else if (command == "SQUIT")
2039 if (params.size() == 2)
2041 this->Squit(FindServer(params[0]),params[1]);
2045 else if (command == "ENDBURST")
2047 this->bursting = false;
2052 // not a special inter-server command.
2053 // Emulate the actual user doing the command,
2054 // this saves us having a huge ugly parser.
2055 userrec* who = Srv->FindNick(prefix);
2056 std::string sourceserv = this->myhost;
2057 if (this->InboundServerName != "")
2059 sourceserv = this->InboundServerName;
2064 target = who->server;
2065 char* strparams[127];
2066 for (unsigned int q = 0; q < params.size(); q++)
2068 strparams[q] = (char*)params[q].c_str();
2070 Srv->CallCommandHandler(command, strparams, params.size(), who);
2074 // its not a user. Its either a server, or somethings screwed up.
2075 if (IsServer(prefix))
2077 target = Srv->GetServerName();
2081 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2085 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2094 virtual std::string GetName()
2096 std::string sourceserv = this->myhost;
2097 if (this->InboundServerName != "")
2099 sourceserv = this->InboundServerName;
2104 virtual void OnTimeout()
2106 if (this->LinkState == CONNECTING)
2108 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2112 virtual void OnClose()
2114 // Connection closed.
2115 // If the connection is fully up (state CONNECTED)
2116 // then propogate a netsplit to all peers.
2117 std::string quitserver = this->myhost;
2118 if (this->InboundServerName != "")
2120 quitserver = this->InboundServerName;
2122 TreeServer* s = FindServer(quitserver);
2125 Squit(s,"Remote host closed the connection");
2127 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2130 virtual int OnIncomingConnection(int newsock, char* ip)
2132 TreeSocket* s = new TreeSocket(newsock, ip);
2138 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2140 for (unsigned int c = 0; c < list.size(); c++)
2142 if (list[c] == server)
2147 list.push_back(server);
2150 // returns a list of DIRECT servernames for a specific channel
2151 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2153 std::vector<char*> *ulist = c->GetUsers();
2154 unsigned int ucount = ulist->size();
2155 for (unsigned int i = 0; i < ucount; i++)
2157 char* o = (*ulist)[i];
2158 userrec* otheruser = (userrec*)o;
2159 if (otheruser->fd < 0)
2161 TreeServer* best = BestRouteTo(otheruser->server);
2163 AddThisServer(best,list);
2169 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2171 TreeServer* omitroute = BestRouteTo(omit);
2172 if ((command == "NOTICE") || (command == "PRIVMSG"))
2174 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2176 if (*(params[0].c_str()) != '#')
2178 // special routing for private messages/notices
2179 userrec* d = Srv->FindNick(params[0]);
2182 std::deque<std::string> par;
2183 par.push_back(params[0]);
2184 par.push_back(":"+params[1]);
2185 DoOneToOne(prefix,command,par,d->server);
2191 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2192 chanrec* c = Srv->FindChannel(params[0]);
2195 std::deque<TreeServer*> list;
2196 GetListOfServersForChannel(c,list);
2197 log(DEBUG,"Got a list of %d servers",list.size());
2198 unsigned int lsize = list.size();
2199 for (unsigned int i = 0; i < lsize; i++)
2201 TreeSocket* Sock = list[i]->GetSocket();
2202 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2204 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2205 Sock->WriteLine(data);
2213 unsigned int items = TreeRoot->ChildCount();
2214 for (unsigned int x = 0; x < items; x++)
2216 TreeServer* Route = TreeRoot->GetChild(x);
2217 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2219 TreeSocket* Sock = Route->GetSocket();
2220 Sock->WriteLine(data);
2226 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2228 TreeServer* omitroute = BestRouteTo(omit);
2229 std::string FullLine = ":" + prefix + " " + command;
2230 unsigned int words = params.size();
2231 for (unsigned int x = 0; x < words; x++)
2233 FullLine = FullLine + " " + params[x];
2235 unsigned int items = TreeRoot->ChildCount();
2236 for (unsigned int x = 0; x < items; x++)
2238 TreeServer* Route = TreeRoot->GetChild(x);
2239 // Send the line IF:
2240 // The route has a socket (its a direct connection)
2241 // The route isnt the one to be omitted
2242 // The route isnt the path to the one to be omitted
2243 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2245 TreeSocket* Sock = Route->GetSocket();
2246 Sock->WriteLine(FullLine);
2252 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2254 std::string FullLine = ":" + prefix + " " + command;
2255 unsigned int words = params.size();
2256 for (unsigned int x = 0; x < words; x++)
2258 FullLine = FullLine + " " + params[x];
2260 unsigned int items = TreeRoot->ChildCount();
2261 for (unsigned int x = 0; x < items; x++)
2263 TreeServer* Route = TreeRoot->GetChild(x);
2264 if (Route->GetSocket())
2266 TreeSocket* Sock = Route->GetSocket();
2267 Sock->WriteLine(FullLine);
2273 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2275 TreeServer* Route = BestRouteTo(target);
2278 std::string FullLine = ":" + prefix + " " + command;
2279 unsigned int words = params.size();
2280 for (unsigned int x = 0; x < words; x++)
2282 FullLine = FullLine + " " + params[x];
2284 if (Route->GetSocket())
2286 TreeSocket* Sock = Route->GetSocket();
2287 Sock->WriteLine(FullLine);
2297 std::vector<TreeSocket*> Bindings;
2299 void ReadConfiguration(bool rebind)
2301 Conf = new ConfigReader;
2304 for (int j =0; j < Conf->Enumerate("bind"); j++)
2306 std::string Type = Conf->ReadValue("bind","type",j);
2307 std::string IP = Conf->ReadValue("bind","address",j);
2308 long Port = Conf->ReadInteger("bind","port",j,true);
2309 if (Type == "servers")
2315 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2316 if (listener->GetState() == I_LISTENING)
2318 Srv->AddSocket(listener);
2319 Bindings.push_back(listener);
2323 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2331 for (int j =0; j < Conf->Enumerate("link"); j++)
2334 L.Name = Conf->ReadValue("link","name",j);
2335 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2336 L.Port = Conf->ReadInteger("link","port",j,true);
2337 L.SendPass = Conf->ReadValue("link","sendpass",j);
2338 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2339 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2340 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2341 L.NextConnectTime = time(NULL) + L.AutoConnect;
2342 /* Bugfix by brain, do not allow people to enter bad configurations */
2343 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2345 LinkBlocks.push_back(L);
2346 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2350 log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2357 class ModuleSpanningTree : public Module
2359 std::vector<TreeSocket*> Bindings;
2365 ModuleSpanningTree(Server* Me)
2366 : Module::Module(Me)
2371 // Create the root of the tree
2372 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2374 ReadConfiguration(true);
2377 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2379 std::string Parent = TreeRoot->GetName();
2380 if (Current->GetParent())
2382 Parent = Current->GetParent()->GetName();
2384 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2386 ShowLinks(Current->GetChild(q),user,hops+1);
2388 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2391 int CountLocalServs()
2393 return TreeRoot->ChildCount();
2398 return serverlist.size();
2401 void HandleLinks(char** parameters, int pcnt, userrec* user)
2403 ShowLinks(TreeRoot,user,0);
2404 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2408 void HandleLusers(char** parameters, int pcnt, userrec* user)
2410 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2411 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2412 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2413 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2414 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2418 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2420 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2424 for (int t = 0; t < depth; t++)
2426 matrix[line][t] = ' ';
2428 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2430 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2432 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2437 // Ok, prepare to be confused.
2438 // After much mulling over how to approach this, it struck me that
2439 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2440 // keeping track of a ton of ascii characters, and line by line
2441 // under recursion working out where to place them using multiplications
2442 // and divisons, we instead render the map onto a backplane of characters
2443 // (a character matrix), then draw the branches as a series of "L" shapes
2444 // from the nodes. This is not only friendlier on CPU it uses less stack.
2446 void HandleMap(char** parameters, int pcnt, userrec* user)
2448 // This array represents a virtual screen which we will
2449 // "scratch" draw to, as the console device of an irc
2450 // client does not provide for a proper terminal.
2451 char matrix[128][80];
2452 for (unsigned int t = 0; t < 128; t++)
2454 matrix[t][0] = '\0';
2457 // The only recursive bit is called here.
2458 ShowMap(TreeRoot,user,0,matrix);
2459 // Process each line one by one. The algorithm has a limit of
2460 // 128 servers (which is far more than a spanning tree should have
2461 // anyway, so we're ok). This limit can be raised simply by making
2462 // the character matrix deeper, 128 rows taking 10k of memory.
2463 for (int l = 1; l < line; l++)
2465 // scan across the line looking for the start of the
2466 // servername (the recursive part of the algorithm has placed
2467 // the servers at indented positions depending on what they
2469 int first_nonspace = 0;
2470 while (matrix[l][first_nonspace] == ' ')
2475 // Draw the `- (corner) section: this may be overwritten by
2476 // another L shape passing along the same vertical pane, becoming
2477 // a |- (branch) section instead.
2478 matrix[l][first_nonspace] = '-';
2479 matrix[l][first_nonspace-1] = '`';
2481 // Draw upwards until we hit the parent server, causing possibly
2482 // other corners (`-) to become branches (|-)
2483 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2485 matrix[l2][first_nonspace-1] = '|';
2489 // dump the whole lot to the user. This is the easy bit, honest.
2490 for (int t = 0; t < line; t++)
2492 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2494 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2498 int HandleSquit(char** parameters, int pcnt, userrec* user)
2500 TreeServer* s = FindServerMask(parameters[0]);
2505 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2508 TreeSocket* sock = s->GetSocket();
2511 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2512 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2513 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2518 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2523 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2528 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2530 if ((user->fd > -1) && (pcnt > 1))
2532 userrec* remote = Srv->FindNick(parameters[1]);
2533 if ((remote) && (remote->fd < 0))
2535 std::deque<std::string> params;
2536 params.push_back(parameters[1]);
2537 DoOneToOne(user->nick,"IDLE",params,remote->server);
2542 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2543 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2550 void DoPingChecks(time_t curtime)
2552 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2554 TreeServer* serv = TreeRoot->GetChild(j);
2555 TreeSocket* sock = serv->GetSocket();
2558 if (curtime >= serv->NextPingTime())
2560 if (serv->AnsweredLastPing())
2562 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2563 serv->SetNextPingTime(curtime + 60);
2567 // they didnt answer, boot them
2568 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2569 sock->Squit(serv,"Ping timeout");
2578 void AutoConnectServers(time_t curtime)
2580 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2582 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2584 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2585 x->NextConnectTime = curtime + x->AutoConnect;
2586 TreeServer* CheckDupe = FindServer(x->Name);
2589 // an autoconnected server is not connected. Check if its time to connect it
2590 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2591 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2592 Srv->AddSocket(newsocket);
2598 int HandleVersion(char** parameters, int pcnt, userrec* user)
2600 // we've already checked if pcnt > 0, so this is safe
2601 TreeServer* found = FindServerMask(parameters[0]);
2604 std::string Version = found->GetVersion();
2605 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2609 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2614 int HandleConnect(char** parameters, int pcnt, userrec* user)
2616 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2618 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2620 TreeServer* CheckDupe = FindServer(x->Name);
2623 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
2624 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2625 Srv->AddSocket(newsocket);
2630 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
2635 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2639 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2641 if (*parameters[0] == 'c')
2643 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2645 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %s",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? "es" : " s"));
2646 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2648 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2649 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2655 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2657 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2661 if (command == "CONNECT")
2663 return this->HandleConnect(parameters,pcnt,user);
2665 else if (command == "SQUIT")
2667 return this->HandleSquit(parameters,pcnt,user);
2669 else if (command == "STATS")
2671 return this->HandleStats(parameters,pcnt,user);
2673 else if (command == "MAP")
2675 this->HandleMap(parameters,pcnt,user);
2678 else if (command == "LUSERS")
2680 this->HandleLusers(parameters,pcnt,user);
2683 else if (command == "LINKS")
2685 this->HandleLinks(parameters,pcnt,user);
2688 else if (command == "WHOIS")
2693 return this->HandleRemoteWhois(parameters,pcnt,user);
2696 else if ((command == "VERSION") && (pcnt > 0))
2698 this->HandleVersion(parameters,pcnt,user);
2701 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2703 // this bit of code cleverly routes all module commands
2704 // to all remote severs *automatically* so that modules
2705 // can just handle commands locally, without having
2706 // to have any special provision in place for remote
2707 // commands and linking protocols.
2708 std::deque<std::string> params;
2710 for (int j = 0; j < pcnt; j++)
2712 if (strchr(parameters[j],' '))
2714 params.push_back(":" + std::string(parameters[j]));
2718 params.push_back(std::string(parameters[j]));
2721 DoOneToMany(user->nick,command,params);
2726 virtual void OnGetServerDescription(std::string servername,std::string &description)
2728 TreeServer* s = FindServer(servername);
2731 description = s->GetDesc();
2735 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2737 if (source->fd > -1)
2739 std::deque<std::string> params;
2740 params.push_back(dest->nick);
2741 params.push_back(channel->name);
2742 DoOneToMany(source->nick,"INVITE",params);
2746 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2748 std::deque<std::string> params;
2749 params.push_back(chan->name);
2750 params.push_back(":"+topic);
2751 DoOneToMany(user->nick,"TOPIC",params);
2754 virtual void OnWallops(userrec* user, std::string text)
2758 std::deque<std::string> params;
2759 params.push_back(":"+text);
2760 DoOneToMany(user->nick,"WALLOPS",params);
2764 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2766 if (target_type == TYPE_USER)
2768 userrec* d = (userrec*)dest;
2769 if ((d->fd < 0) && (user->fd > -1))
2771 std::deque<std::string> params;
2773 params.push_back(d->nick);
2774 params.push_back(":"+text);
2775 DoOneToOne(user->nick,"NOTICE",params,d->server);
2782 chanrec *c = (chanrec*)dest;
2783 std::deque<TreeServer*> list;
2784 GetListOfServersForChannel(c,list);
2785 unsigned int ucount = list.size();
2786 for (unsigned int i = 0; i < ucount; i++)
2788 TreeSocket* Sock = list[i]->GetSocket();
2790 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2796 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2798 if (target_type == TYPE_USER)
2800 // route private messages which are targetted at clients only to the server
2801 // which needs to receive them
2802 userrec* d = (userrec*)dest;
2803 if ((d->fd < 0) && (user->fd > -1))
2805 std::deque<std::string> params;
2807 params.push_back(d->nick);
2808 params.push_back(":"+text);
2809 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2816 chanrec *c = (chanrec*)dest;
2817 std::deque<TreeServer*> list;
2818 GetListOfServersForChannel(c,list);
2819 unsigned int ucount = list.size();
2820 for (unsigned int i = 0; i < ucount; i++)
2822 TreeSocket* Sock = list[i]->GetSocket();
2824 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2830 virtual void OnBackgroundTimer(time_t curtime)
2832 AutoConnectServers(curtime);
2833 DoPingChecks(curtime);
2836 virtual void OnUserJoin(userrec* user, chanrec* channel)
2838 // Only do this for local users
2841 std::deque<std::string> params;
2843 params.push_back(channel->name);
2846 // if the channel has a key, force the join by emulating the key.
2847 params.push_back(channel->key);
2849 if (channel->GetUserCounter() > 1)
2851 // not the first in the channel
2852 DoOneToMany(user->nick,"JOIN",params);
2856 // first in the channel, set up their permissions
2857 // and the channel TS with FJOIN.
2859 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2861 params.push_back(channel->name);
2862 params.push_back(ts);
2863 params.push_back("@"+std::string(user->nick));
2864 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2869 virtual void OnChangeHost(userrec* user, std::string newhost)
2871 // only occurs for local clients
2872 if (user->registered != 7)
2874 std::deque<std::string> params;
2875 params.push_back(newhost);
2876 DoOneToMany(user->nick,"FHOST",params);
2879 virtual void OnChangeName(userrec* user, std::string gecos)
2881 // only occurs for local clients
2882 if (user->registered != 7)
2884 std::deque<std::string> params;
2885 params.push_back(gecos);
2886 DoOneToMany(user->nick,"FNAME",params);
2889 virtual void OnUserPart(userrec* user, chanrec* channel)
2893 std::deque<std::string> params;
2894 params.push_back(channel->name);
2895 DoOneToMany(user->nick,"PART",params);
2899 virtual void OnUserConnect(userrec* user)
2901 char agestr[MAXBUF];
2904 std::deque<std::string> params;
2905 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2906 params.push_back(agestr);
2907 params.push_back(user->nick);
2908 params.push_back(user->host);
2909 params.push_back(user->dhost);
2910 params.push_back(user->ident);
2911 params.push_back("+"+std::string(user->modes));
2912 params.push_back(user->ip);
2913 params.push_back(":"+std::string(user->fullname));
2914 DoOneToMany(Srv->GetServerName(),"NICK",params);
2918 virtual void OnUserQuit(userrec* user, std::string reason)
2920 if ((user->fd > -1) && (user->registered == 7))
2922 std::deque<std::string> params;
2923 params.push_back(":"+reason);
2924 DoOneToMany(user->nick,"QUIT",params);
2928 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2932 std::deque<std::string> params;
2933 params.push_back(user->nick);
2934 DoOneToMany(oldnick,"NICK",params);
2938 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2940 if (source->fd > -1)
2942 std::deque<std::string> params;
2943 params.push_back(chan->name);
2944 params.push_back(user->nick);
2945 params.push_back(":"+reason);
2946 DoOneToMany(source->nick,"KICK",params);
2950 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2952 std::deque<std::string> params;
2953 params.push_back(dest->nick);
2954 params.push_back(":"+reason);
2955 DoOneToMany(source->nick,"KILL",params);
2958 virtual void OnRehash(std::string parameter)
2960 if (parameter != "")
2962 std::deque<std::string> params;
2963 params.push_back(parameter);
2964 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2966 if (Srv->MatchText(Srv->GetServerName(),parameter))
2968 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2969 Srv->RehashServer();
2972 ReadConfiguration(false);
2975 // note: the protocol does not allow direct umode +o except
2976 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2978 virtual void OnOper(userrec* user, std::string opertype)
2982 std::deque<std::string> params;
2983 params.push_back(opertype);
2984 DoOneToMany(user->nick,"OPERTYPE",params);
2988 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2990 if (source->fd > -1)
2993 snprintf(type,8,"%cLINE",linetype);
2994 std::string stype = type;
2997 char sduration[MAXBUF];
2998 snprintf(sduration,MAXBUF,"%ld",duration);
2999 std::deque<std::string> params;
3000 params.push_back(host);
3001 params.push_back(sduration);
3002 params.push_back(":"+reason);
3003 DoOneToMany(source->nick,stype,params);
3007 std::deque<std::string> params;
3008 params.push_back(host);
3009 DoOneToMany(source->nick,stype,params);
3014 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3016 OnLine(source,hostmask,true,'G',duration,reason);
3019 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3021 OnLine(source,ipmask,true,'Z',duration,reason);
3024 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3026 OnLine(source,nickmask,true,'Q',duration,reason);
3029 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3031 OnLine(source,hostmask,true,'E',duration,reason);
3034 virtual void OnDelGLine(userrec* source, std::string hostmask)
3036 OnLine(source,hostmask,false,'G',0,"");
3039 virtual void OnDelZLine(userrec* source, std::string ipmask)
3041 OnLine(source,ipmask,false,'Z',0,"");
3044 virtual void OnDelQLine(userrec* source, std::string nickmask)
3046 OnLine(source,nickmask,false,'Q',0,"");
3049 virtual void OnDelELine(userrec* source, std::string hostmask)
3051 OnLine(source,hostmask,false,'E',0,"");
3054 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3056 if ((user->fd > -1) && (user->registered == 7))
3058 if (target_type == TYPE_USER)
3060 userrec* u = (userrec*)dest;
3061 std::deque<std::string> params;
3062 params.push_back(u->nick);
3063 params.push_back(text);
3064 DoOneToMany(user->nick,"MODE",params);
3068 chanrec* c = (chanrec*)dest;
3069 std::deque<std::string> params;
3070 params.push_back(c->name);
3071 params.push_back(text);
3072 DoOneToMany(user->nick,"MODE",params);
3077 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3079 TreeSocket* s = (TreeSocket*)opaque;
3082 if (target_type == TYPE_USER)
3084 userrec* u = (userrec*)target;
3085 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3089 chanrec* c = (chanrec*)target;
3090 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3095 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3097 TreeSocket* s = (TreeSocket*)opaque;
3100 if (target_type == TYPE_USER)
3102 userrec* u = (userrec*)target;
3103 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3107 chanrec* c = (chanrec*)target;
3108 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3113 virtual ~ModuleSpanningTree()
3117 virtual Version GetVersion()
3119 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3122 void Implements(char* List)
3124 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3125 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3126 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3127 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3128 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3129 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3130 List[I_ProtoSendMetaData] = 1;
3135 class ModuleSpanningTreeFactory : public ModuleFactory
3138 ModuleSpanningTreeFactory()
3142 ~ModuleSpanningTreeFactory()
3146 virtual Module * CreateModule(Server* Me)
3148 TreeProtocolModule = new ModuleSpanningTree(Me);
3149 return TreeProtocolModule;
3155 extern "C" void * init_module( void )
3157 return new ModuleSpanningTreeFactory;