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;
544 unsigned int keylength;
548 /* Because most of the I/O gubbins are encapsulated within
549 * InspSocket, we just call the superclass constructor for
550 * most of the action, and append a few of our own values
553 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
554 : InspSocket(host, port, listening, maxtime)
557 this->LinkState = LISTENER;
559 this->ctx_out = NULL;
562 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
563 : InspSocket(host, port, listening, maxtime)
566 this->LinkState = CONNECTING;
568 this->ctx_out = NULL;
571 /* When a listening socket gives us a new file descriptor,
572 * we must associate it with a socket without creating a new
573 * connection. This constructor is used for this purpose.
575 TreeSocket(int newfd, char* ip)
576 : InspSocket(newfd, ip)
578 this->LinkState = WAIT_AUTH_1;
580 this->ctx_out = NULL;
581 this->SendCapabilities();
592 void InitAES(std::string key,std::string SName)
599 log(DEBUG,"Initialized AES key %s",key.c_str());
600 // key must be 16, 24, 32 etc bytes (multiple of 8)
601 keylength = key.length();
602 if (!(keylength == 16 || keylength == 24 || keylength == 32))
604 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
605 log(DEBUG,"Key length not 16, 24 or 32 characters!");
609 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
610 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\
611 \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);
612 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\
613 \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);
617 /* When an outbound connection finishes connecting, we receive
618 * this event, and must send our SERVER string to the other
619 * side. If the other side is happy, as outlined in the server
620 * to server docs on the inspircd.org site, the other side
621 * will then send back its own server string.
623 virtual bool OnConnected()
625 if (this->LinkState == CONNECTING)
627 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
628 /* we do not need to change state here. */
629 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
631 if (x->Name == this->myhost)
633 this->SendCapabilities();
634 if (x->EncryptionKey != "")
636 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
638 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
642 this->WriteLine("AES "+Srv->GetServerName());
643 this->InitAES(x->EncryptionKey,x->Name);
646 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
647 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
652 /* There is a (remote) chance that between the /CONNECT and the connection
653 * being accepted, some muppet has removed the <link> block and rehashed.
654 * If that happens the connection hangs here until it's closed. Unlikely
655 * and rather harmless.
660 virtual void OnError(InspSocketError e)
662 /* We don't handle this method, because all our
663 * dirty work is done in OnClose() (see below)
664 * which is still called on error conditions too.
668 virtual int OnDisconnect()
670 /* For the same reason as above, we don't
671 * handle OnDisconnect()
676 /* Recursively send the server tree with distances as hops.
677 * This is used during network burst to inform the other server
678 * (and any of ITS servers too) of what servers we know about.
679 * If at any point any of these servers already exist on the other
680 * end, our connection may be terminated. The hopcounts given
681 * by this function are relative, this doesn't matter so long as
682 * they are all >1, as all the remote servers re-calculate them
683 * to be relative too, with themselves as hop 0.
685 void SendServers(TreeServer* Current, TreeServer* s, int hops)
688 for (unsigned int q = 0; q < Current->ChildCount(); q++)
690 TreeServer* recursive_server = Current->GetChild(q);
691 if (recursive_server != s)
693 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
694 this->WriteLine(command);
695 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
696 /* down to next level */
697 this->SendServers(recursive_server, s, hops+1);
702 std::string MyCapabilities()
704 ServerConfig* Config = Srv->GetConfig();
705 std::vector<std::string> modlist;
706 std::string capabilities = "";
708 for (int i = 0; i <= MODCOUNT; i++)
710 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
711 modlist.push_back(Config->module_names[i]);
713 sort(modlist.begin(),modlist.end());
714 for (unsigned int i = 0; i < modlist.size(); i++)
717 capabilities = capabilities + ",";
718 capabilities = capabilities + modlist[i];
723 void SendCapabilities()
725 this->WriteLine("CAPAB "+MyCapabilities());
728 bool Capab(std::deque<std::string> params)
730 if (params.size() != 1)
732 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
735 if (params[0] != this->MyCapabilities())
737 std::string quitserver = this->myhost;
738 if (this->InboundServerName != "")
740 quitserver = this->InboundServerName;
742 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
743 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
744 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
745 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
746 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
752 /* This function forces this server to quit, removing this server
753 * and any users on it (and servers and users below that, etc etc).
754 * It's very slow and pretty clunky, but luckily unless your network
755 * is having a REAL bad hair day, this function shouldnt be called
756 * too many times a month ;-)
758 void SquitServer(TreeServer* Current, CullList* Goners)
760 /* recursively squit the servers attached to 'Current'.
761 * We're going backwards so we don't remove users
762 * while we still need them ;)
764 for (unsigned int q = 0; q < Current->ChildCount(); q++)
766 TreeServer* recursive_server = Current->GetChild(q);
767 this->SquitServer(recursive_server,Goners);
769 /* Now we've whacked the kids, whack self */
771 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
773 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
775 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
776 Goners->AddItem(u->second,qreason);
782 /* This is a wrapper function for SquitServer above, which
783 * does some validation first and passes on the SQUIT to all
784 * other remaining servers.
786 void Squit(TreeServer* Current,std::string reason)
788 if ((Current) && (Current != TreeRoot))
790 std::deque<std::string> params;
791 params.push_back(Current->GetName());
792 params.push_back(":"+reason);
793 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
794 if (Current->GetParent() == TreeRoot)
796 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
800 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
802 num_lost_servers = 0;
804 CullList* Goners = new CullList();
805 SquitServer(Current, Goners);
808 Current->GetParent()->DelChild(Current);
811 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
815 log(DEFAULT,"Squit from unknown server");
820 bool ForceMode(std::string source, std::deque<std::string> params)
822 userrec* who = new userrec;
823 who->fd = FD_MAGIC_NUMBER;
824 if (params.size() < 2)
827 for (unsigned int q = 0; q < params.size(); q++)
829 modelist[q] = (char*)params[q].c_str();
831 Srv->SendMode(modelist,params.size(),who);
832 DoOneToAllButSender(source,"FMODE",params,source);
838 bool ForceTopic(std::string source, std::deque<std::string> params)
840 if (params.size() != 4)
842 std::string channel = params[0];
843 time_t ts = atoi(params[1].c_str());
844 std::string setby = params[2];
845 std::string topic = params[3];
847 chanrec* c = Srv->FindChannel(channel);
850 if ((ts >= c->topicset) || (!*c->topic))
852 std::string oldtopic = c->topic;
853 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
854 strlcpy(c->setby,setby.c_str(),NICKMAX);
856 /* if the topic text is the same as the current topic,
857 * dont bother to send the TOPIC command out, just silently
858 * update the set time and set nick.
860 if (oldtopic != topic)
861 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
866 /* all done, send it on its way */
867 params[3] = ":" + params[3];
868 DoOneToAllButSender(source,"FTOPIC",params,source);
873 /* FJOIN, similar to unreal SJOIN */
874 bool ForceJoin(std::string source, std::deque<std::string> params)
876 if (params.size() < 3)
880 char modestring[MAXBUF];
881 char* mode_users[127];
882 mode_users[0] = first;
883 mode_users[1] = modestring;
884 strcpy(mode_users[1],"+");
885 unsigned int modectr = 2;
888 std::string channel = params[0];
889 time_t TS = atoi(params[1].c_str());
892 chanrec* chan = Srv->FindChannel(channel);
897 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
899 /* default is a high value, which if we dont have this
900 * channel will let the other side apply their modes.
902 time_t ourTS = time(NULL)+600;
903 chanrec* us = Srv->FindChannel(channel);
909 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
911 /* do this first, so our mode reversals are correctly received by other servers
912 * if there is a TS collision.
914 DoOneToAllButSender(source,"FJOIN",params,source);
916 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
918 /* process one channel at a time, applying modes. */
919 char* usr = (char*)params[usernum].c_str();
920 char permissions = *usr;
925 mode_users[modectr++] = usr;
926 strlcat(modestring,"o",MAXBUF);
930 mode_users[modectr++] = usr;
931 strlcat(modestring,"h",MAXBUF);
935 mode_users[modectr++] = usr;
936 strlcat(modestring,"v",MAXBUF);
939 who = Srv->FindNick(usr);
942 Srv->JoinUserToChannel(who,channel,key);
943 if (modectr >= (MAXMODES-1))
945 /* theres a mode for this user. push them onto the mode queue, and flush it
946 * if there are more than MAXMODES to go.
948 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
950 /* We also always let u-lined clients win, no matter what the TS value */
951 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
952 Srv->SendMode(mode_users,modectr,who);
956 log(DEBUG,"Their channel newer than ours, bouncing their modes");
958 std::deque<std::string> params;
959 /* modes are now being UNSET... */
960 *mode_users[1] = '-';
961 for (unsigned int x = 0; x < modectr; x++)
963 params.push_back(mode_users[x]);
965 // tell everyone to bounce the modes. bad modes, bad!
966 DoOneToMany(Srv->GetServerName(),"FMODE",params);
968 strcpy(mode_users[1],"+");
973 /* there werent enough modes built up to flush it during FJOIN,
974 * or, there are a number left over. flush them out.
976 if ((modectr > 2) && (who))
980 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
981 Srv->SendMode(mode_users,modectr,who);
985 log(DEBUG,"Their channel newer than ours, bouncing their modes");
986 std::deque<std::string> params;
987 *mode_users[1] = '-';
988 for (unsigned int x = 0; x < modectr; x++)
990 params.push_back(mode_users[x]);
992 DoOneToMany(Srv->GetServerName(),"FMODE",params);
999 bool IntroduceClient(std::string source, std::deque<std::string> params)
1001 if (params.size() < 8)
1003 // NICK age nick host dhost ident +modes ip :gecos
1005 std::string nick = params[1];
1006 std::string host = params[2];
1007 std::string dhost = params[3];
1008 std::string ident = params[4];
1009 time_t age = atoi(params[0].c_str());
1010 std::string modes = params[5];
1011 while (*(modes.c_str()) == '+')
1013 char* m = (char*)modes.c_str();
1017 std::string ip = params[6];
1018 std::string gecos = params[7];
1019 char* tempnick = (char*)nick.c_str();
1020 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1022 user_hash::iterator iter;
1023 iter = clientlist.find(tempnick);
1024 if (iter != clientlist.end())
1027 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);
1028 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1032 clientlist[tempnick] = new userrec();
1033 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1034 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1035 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1036 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1037 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1038 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1039 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1040 clientlist[tempnick]->registered = 7;
1041 clientlist[tempnick]->signon = age;
1042 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1043 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1048 for (int i = 0; i < MAXCHANS; i++)
1049 clientlist[tempnick]->chans.push_back(a);
1051 if (!this->bursting)
1053 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1055 params[7] = ":" + params[7];
1056 DoOneToAllButSender(source,"NICK",params,source);
1060 /* Send one or more FJOINs for a channel of users.
1061 * If the length of a single line is more than 480-NICKMAX
1062 * in length, it is split over multiple lines.
1064 void SendFJoins(TreeServer* Current, chanrec* c)
1066 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1068 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1069 std::vector<char*> *ulist = c->GetUsers();
1070 for (unsigned int i = 0; i < ulist->size(); i++)
1072 char* o = (*ulist)[i];
1073 userrec* otheruser = (userrec*)o;
1074 strlcat(list," ",MAXBUF);
1075 strlcat(list,cmode(otheruser,c),MAXBUF);
1076 strlcat(list,otheruser->nick,MAXBUF);
1077 if (strlen(list)>(480-NICKMAX))
1079 log(DEBUG,"FJOIN line wrapped");
1080 this->WriteLine(list);
1081 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1084 if (list[strlen(list)-1] != ':')
1086 log(DEBUG,"Final FJOIN line");
1087 this->WriteLine(list);
1091 /* Send G, Q, Z and E lines */
1092 void SendXLines(TreeServer* Current)
1095 /* Yes, these arent too nice looking, but they get the job done */
1096 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1098 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);
1099 this->WriteLine(data);
1101 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1103 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);
1104 this->WriteLine(data);
1106 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1108 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);
1109 this->WriteLine(data);
1111 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1113 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);
1114 this->WriteLine(data);
1116 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1118 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);
1119 this->WriteLine(data);
1121 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1123 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);
1124 this->WriteLine(data);
1126 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1128 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);
1129 this->WriteLine(data);
1131 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1133 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);
1134 this->WriteLine(data);
1138 /* Send channel modes and topics */
1139 void SendChannelModes(TreeServer* Current)
1142 std::deque<std::string> list;
1143 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1145 SendFJoins(Current, c->second);
1146 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1147 this->WriteLine(data);
1148 if (*c->second->topic)
1150 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);
1151 this->WriteLine(data);
1153 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1155 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1156 this->WriteLine(data);
1158 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1160 c->second->GetExtList(list);
1161 for (unsigned int j = 0; j < list.size(); j++)
1163 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1168 /* send all users and their oper state/modes */
1169 void SendUsers(TreeServer* Current)
1172 std::deque<std::string> list;
1173 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1175 if (u->second->registered == 7)
1177 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);
1178 this->WriteLine(data);
1179 if (strchr(u->second->modes,'o'))
1181 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1183 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1185 u->second->GetExtList(list);
1186 for (unsigned int j = 0; j < list.size(); j++)
1188 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1194 /* This function is called when we want to send a netburst to a local
1195 * server. There is a set order we must do this, because for example
1196 * users require their servers to exist, and channels require their
1197 * users to exist. You get the idea.
1199 void DoBurst(TreeServer* s)
1201 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1202 this->WriteLine("BURST");
1203 /* send our version string */
1204 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1205 /* Send server tree */
1206 this->SendServers(TreeRoot,s,1);
1207 /* Send users and their oper status */
1209 /* Send everything else (channel modes, xlines etc) */
1210 this->SendChannelModes(s);
1211 this->SendXLines(s);
1212 this->WriteLine("ENDBURST");
1213 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1216 /* This function is called when we receive data from a remote
1217 * server. We buffer the data in a std::string (it doesnt stay
1218 * there for long), reading using InspSocket::Read() which can
1219 * read up to 16 kilobytes in one operation.
1221 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1222 * THE SOCKET OBJECT FOR US.
1224 virtual bool OnDataReady()
1226 char* data = this->Read();
1229 this->in_buffer += data;
1230 /* While there is at least one new line in the buffer,
1231 * do something useful (we hope!) with it.
1233 while (in_buffer.find("\n") != std::string::npos)
1235 char* line = (char*)in_buffer.c_str();
1236 std::string ret = "";
1237 while ((*line != '\n') && (strlen(line)))
1239 if ((*line != '\r') && (*line != '\n'))
1243 if ((*line == '\n') || (*line == '\r'))
1246 /* Process this one, abort if it
1247 * didnt return true.
1253 memset(result,0,1024);
1255 log(DEBUG,"Original string '%s'",ret.c_str());
1256 /* ERROR + CAPAB is still allowed unencryped */
1257 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1259 int nbytes = from64tobits(out, ret.c_str(), 1024);
1260 if ((nbytes > 0) && (nbytes < 1024))
1262 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1263 ctx_in->Decrypt(out, result, nbytes, 1);
1264 for (int t = 0; t < nbytes; t++)
1265 if (result[t] == '\7') result[t] = 0;
1270 if (!this->ProcessLine(ret))
1276 return (data != NULL);
1279 int WriteLine(std::string line)
1281 log(DEBUG,"OUT: %s",line.c_str());
1284 log(DEBUG,"AES context");
1286 char result64[10240];
1287 if (this->keylength)
1289 while (line.length() % this->keylength != 0)
1291 // pad it to be a multiple of the key length
1295 unsigned int ll = line.length();
1296 log(DEBUG,"Plaintext line with padding = %d chars",ll);
1297 ctx_out->Encrypt(line.c_str(), result, ll, 1);
1298 log(DEBUG,"Encrypted.");
1299 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1301 log(DEBUG,"Encrypted: %s",line.c_str());
1302 //int from64tobits(char *out, const char *in, int maxlen);
1304 return this->Write(line + "\r\n");
1307 /* Handle ERROR command */
1308 bool Error(std::deque<std::string> params)
1310 if (params.size() < 1)
1312 std::string Errmsg = params[0];
1313 std::string SName = myhost;
1314 if (InboundServerName != "")
1316 SName = InboundServerName;
1318 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1319 /* we will return false to cause the socket to close.
1324 /* Because the core won't let users or even SERVERS set +o,
1325 * we use the OPERTYPE command to do this.
1327 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1329 if (params.size() != 1)
1331 std::string opertype = params[0];
1332 userrec* u = Srv->FindNick(prefix);
1335 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1336 if (!strchr(u->modes,'o'))
1338 strcat(u->modes,"o");
1340 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1345 /* Because Andy insists that services-compatible servers must
1346 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1348 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1350 if (params.size() < 3)
1352 userrec* u = Srv->FindNick(params[0]);
1355 Srv->ChangeUserNick(u,params[1]);
1356 u->age = atoi(params[2].c_str());
1357 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1362 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1364 if (params.size() < 2)
1366 userrec* u = Srv->FindNick(params[0]);
1369 Srv->JoinUserToChannel(u,params[1],"");
1370 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1375 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1377 if (params.size() < 1)
1379 std::string servermask = params[0];
1380 if (Srv->MatchText(Srv->GetServerName(),servermask))
1382 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1383 Srv->RehashServer();
1384 ReadConfiguration(false);
1386 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1390 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1392 if (params.size() != 2)
1394 std::string nick = params[0];
1395 userrec* u = Srv->FindNick(prefix);
1396 userrec* who = Srv->FindNick(nick);
1399 /* Prepend kill source, if we don't have one */
1400 std::string sourceserv = prefix;
1403 sourceserv = u->server;
1405 if (*(params[1].c_str()) != '[')
1407 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1409 std::string reason = params[1];
1410 params[1] = ":" + params[1];
1411 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1412 Srv->QuitUser(who,reason);
1417 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1419 if (params.size() < 1)
1421 TreeServer* ServerSource = FindServer(prefix);
1424 ServerSource->SetPingFlag();
1429 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1431 if (params.size() < 3)
1433 TreeServer* ServerSource = FindServer(prefix);
1436 if (*(params[0].c_str()) == '#')
1438 chanrec* c = Srv->FindChannel(params[0]);
1441 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1446 userrec* u = Srv->FindNick(params[0]);
1449 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1453 params[2] = ":" + params[2];
1454 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1458 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1460 if (params.size() < 1)
1462 TreeServer* ServerSource = FindServer(prefix);
1465 ServerSource->SetVersion(params[0]);
1467 params[0] = ":" + params[0];
1468 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1472 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1474 if (params.size() < 1)
1476 userrec* u = Srv->FindNick(prefix);
1479 Srv->ChangeHost(u,params[0]);
1480 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1485 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1487 if (params.size() < 6)
1489 std::string linetype = params[0]; /* Z, Q, E, G, K */
1490 std::string mask = params[1]; /* Line type dependent */
1491 std::string source = params[2]; /* may not be online or may be a server */
1492 std::string settime = params[3]; /* EPOCH time set */
1493 std::string duration = params[4]; /* Duration secs */
1494 std::string reason = params[5];
1496 switch (*(linetype.c_str()))
1499 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1500 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1503 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1504 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1507 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1508 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1511 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1512 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1515 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1518 /* Just in case... */
1519 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1522 /* Send it on its way */
1523 params[5] = ":" + params[5];
1524 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1528 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1530 if (params.size() < 1)
1532 userrec* u = Srv->FindNick(prefix);
1535 Srv->ChangeGECOS(u,params[0]);
1536 params[0] = ":" + params[0];
1537 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1542 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1544 if (params.size() < 1)
1546 log(DEBUG,"In IDLE command");
1547 userrec* u = Srv->FindNick(prefix);
1550 log(DEBUG,"USER EXISTS: %s",u->nick);
1551 // an incoming request
1552 if (params.size() == 1)
1554 userrec* x = Srv->FindNick(params[0]);
1557 userrec* x = Srv->FindNick(params[0]);
1558 log(DEBUG,"Got IDLE");
1559 char signon[MAXBUF];
1561 log(DEBUG,"Sending back IDLE 3");
1562 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1563 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1564 std::deque<std::string> par;
1565 par.push_back(prefix);
1566 par.push_back(signon);
1567 par.push_back(idle);
1568 // ours, we're done, pass it BACK
1569 DoOneToOne(params[0],"IDLE",par,u->server);
1573 // not ours pass it on
1574 DoOneToOne(prefix,"IDLE",params,x->server);
1577 else if (params.size() == 3)
1579 std::string who_did_the_whois = params[0];
1580 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1581 if (who_to_send_to->fd > -1)
1583 log(DEBUG,"Got final IDLE");
1584 // an incoming reply to a whois we sent out
1585 std::string nick_whoised = prefix;
1586 unsigned long signon = atoi(params[1].c_str());
1587 unsigned long idle = atoi(params[2].c_str());
1588 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1589 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1593 // not ours, pass it on
1594 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1601 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1603 if (params.size() < 1)
1605 std::string stufftobounce = params[0];
1606 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1610 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1612 if (params.size() < 4)
1614 std::string servername = params[0];
1615 std::string password = params[1];
1616 // hopcount is not used for a remote server, we calculate this ourselves
1617 std::string description = params[3];
1618 TreeServer* ParentOfThis = FindServer(prefix);
1621 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1624 TreeServer* CheckDupe = FindServer(servername);
1627 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1628 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1631 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1632 ParentOfThis->AddChild(Node);
1633 params[3] = ":" + params[3];
1634 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1635 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1639 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1641 if (params.size() < 4)
1643 std::string servername = params[0];
1644 std::string password = params[1];
1645 int hops = atoi(params[2].c_str());
1648 this->WriteLine("ERROR :Server too far away for authentication");
1649 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1652 std::string description = params[3];
1653 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1655 if ((x->Name == servername) && (x->RecvPass == password))
1657 TreeServer* CheckDupe = FindServer(servername);
1660 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1661 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1664 // Begin the sync here. this kickstarts the
1665 // other side, waiting in WAIT_AUTH_2 state,
1666 // into starting their burst, as it shows
1667 // that we're happy.
1668 this->LinkState = CONNECTED;
1669 // we should add the details of this server now
1670 // to the servers tree, as a child of the root
1672 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1673 TreeRoot->AddChild(Node);
1674 params[3] = ":" + params[3];
1675 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1676 this->bursting = true;
1677 this->DoBurst(Node);
1681 this->WriteLine("ERROR :Invalid credentials");
1682 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1686 bool Inbound_Server(std::deque<std::string> ¶ms)
1688 if (params.size() < 4)
1690 std::string servername = params[0];
1691 std::string password = params[1];
1692 int hops = atoi(params[2].c_str());
1695 this->WriteLine("ERROR :Server too far away for authentication");
1696 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1699 std::string description = params[3];
1700 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1702 if ((x->Name == servername) && (x->RecvPass == password))
1704 TreeServer* CheckDupe = FindServer(servername);
1707 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1708 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1711 /* If the config says this link is encrypted, but the remote side
1712 * hasnt bothered to send the AES command before SERVER, then we
1713 * boot them off as we MUST have this connection encrypted.
1715 if ((x->EncryptionKey != "") && (!this->ctx_in))
1717 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1718 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1721 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1722 this->InboundServerName = servername;
1723 this->InboundDescription = description;
1724 // this is good. Send our details: Our server name and description and hopcount of 0,
1725 // along with the sendpass from this block.
1726 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1727 // move to the next state, we are now waiting for THEM.
1728 this->LinkState = WAIT_AUTH_2;
1732 this->WriteLine("ERROR :Invalid credentials");
1733 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1737 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1739 if (!strchr(line.c_str(),' '))
1744 std::stringstream s(line);
1745 std::string param = "";
1764 if ((param == ":") && (item > 0))
1787 bool ProcessLine(std::string line)
1789 char* l = (char*)line.c_str();
1790 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1791 l[strlen(l)-1] = '\0';
1795 Srv->Log(DEBUG,"IN: "+line);
1796 std::deque<std::string> params;
1797 this->Split(line,true,params);
1798 std::string command = "";
1799 std::string prefix = "";
1800 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1803 command = params[1];
1804 char* pref = (char*)prefix.c_str();
1812 command = params[0];
1816 if ((!this->ctx_in) && (command == "AES"))
1818 std::string sserv = params[0];
1819 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1821 if ((x->EncryptionKey != "") && (x->Name == sserv))
1823 this->InitAES(x->EncryptionKey,sserv);
1828 else if ((this->ctx_in) && (command == "AES"))
1830 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1833 switch (this->LinkState)
1838 // Waiting for SERVER command from remote server. Server initiating
1839 // the connection sends the first SERVER command, listening server
1840 // replies with theirs if its happy, then if the initiator is happy,
1841 // it starts to send its net sync, which starts the merge, otherwise
1842 // it sends an ERROR.
1843 if (command == "PASS")
1845 /* Silently ignored */
1847 else if (command == "SERVER")
1849 return this->Inbound_Server(params);
1851 else if (command == "ERROR")
1853 return this->Error(params);
1855 else if (command == "USER")
1857 this->WriteLine("ERROR :Client connections to this port are prohibited.");
1860 else if (command == "CAPAB")
1862 return this->Capab(params);
1866 this->WriteLine("ERROR :Invalid command in negotiation phase.");
1871 // Waiting for start of other side's netmerge to say they liked our
1873 if (command == "SERVER")
1875 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1879 else if (command == "BURST")
1881 this->LinkState = CONNECTED;
1882 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1883 TreeRoot->AddChild(Node);
1885 params.push_back(InboundServerName);
1886 params.push_back("*");
1887 params.push_back("1");
1888 params.push_back(":"+InboundDescription);
1889 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1890 this->bursting = true;
1891 this->DoBurst(Node);
1893 else if (command == "ERROR")
1895 return this->Error(params);
1897 else if (command == "CAPAB")
1899 return this->Capab(params);
1904 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1908 if (command == "SERVER")
1910 // another server we connected to, which was in WAIT_AUTH_1 state,
1911 // has just sent us their credentials. If we get this far, theyre
1912 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1913 // if we're happy with this, we should send our netburst which
1914 // kickstarts the merge.
1915 return this->Outbound_Reply_Server(params);
1917 else if (command == "ERROR")
1919 return this->Error(params);
1923 // This is the 'authenticated' state, when all passwords
1924 // have been exchanged and anything past this point is taken
1929 std::string direction = prefix;
1930 userrec* t = Srv->FindNick(prefix);
1933 direction = t->server;
1935 TreeServer* route_back_again = BestRouteTo(direction);
1936 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1938 if (route_back_again)
1939 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1944 if (command == "SVSMODE")
1946 /* Services expects us to implement
1947 * SVSMODE. In inspircd its the same as
1952 std::string target = "";
1953 /* Yes, know, this is a mess. Its reasonably fast though as we're
1954 * working with std::string here.
1956 if ((command == "NICK") && (params.size() > 1))
1958 return this->IntroduceClient(prefix,params);
1960 else if (command == "FJOIN")
1962 return this->ForceJoin(prefix,params);
1964 else if (command == "SERVER")
1966 return this->RemoteServer(prefix,params);
1968 else if (command == "ERROR")
1970 return this->Error(params);
1972 else if (command == "OPERTYPE")
1974 return this->OperType(prefix,params);
1976 else if (command == "FMODE")
1978 return this->ForceMode(prefix,params);
1980 else if (command == "KILL")
1982 return this->RemoteKill(prefix,params);
1984 else if (command == "FTOPIC")
1986 return this->ForceTopic(prefix,params);
1988 else if (command == "REHASH")
1990 return this->RemoteRehash(prefix,params);
1992 else if (command == "METADATA")
1994 return this->MetaData(prefix,params);
1996 else if (command == "PING")
1998 return this->LocalPing(prefix,params);
2000 else if (command == "PONG")
2002 return this->LocalPong(prefix,params);
2004 else if (command == "VERSION")
2006 return this->ServerVersion(prefix,params);
2008 else if (command == "FHOST")
2010 return this->ChangeHost(prefix,params);
2012 else if (command == "FNAME")
2014 return this->ChangeName(prefix,params);
2016 else if (command == "ADDLINE")
2018 return this->AddLine(prefix,params);
2020 else if (command == "SVSNICK")
2024 prefix = this->GetName();
2026 return this->ForceNick(prefix,params);
2028 else if (command == "IDLE")
2030 return this->Whois(prefix,params);
2032 else if (command == "SVSJOIN")
2036 prefix = this->GetName();
2038 return this->ServiceJoin(prefix,params);
2040 else if (command == "SQUIT")
2042 if (params.size() == 2)
2044 this->Squit(FindServer(params[0]),params[1]);
2048 else if (command == "ENDBURST")
2050 this->bursting = false;
2055 // not a special inter-server command.
2056 // Emulate the actual user doing the command,
2057 // this saves us having a huge ugly parser.
2058 userrec* who = Srv->FindNick(prefix);
2059 std::string sourceserv = this->myhost;
2060 if (this->InboundServerName != "")
2062 sourceserv = this->InboundServerName;
2067 target = who->server;
2068 char* strparams[127];
2069 for (unsigned int q = 0; q < params.size(); q++)
2071 strparams[q] = (char*)params[q].c_str();
2073 Srv->CallCommandHandler(command, strparams, params.size(), who);
2077 // its not a user. Its either a server, or somethings screwed up.
2078 if (IsServer(prefix))
2080 target = Srv->GetServerName();
2084 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2088 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2097 virtual std::string GetName()
2099 std::string sourceserv = this->myhost;
2100 if (this->InboundServerName != "")
2102 sourceserv = this->InboundServerName;
2107 virtual void OnTimeout()
2109 if (this->LinkState == CONNECTING)
2111 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2115 virtual void OnClose()
2117 // Connection closed.
2118 // If the connection is fully up (state CONNECTED)
2119 // then propogate a netsplit to all peers.
2120 std::string quitserver = this->myhost;
2121 if (this->InboundServerName != "")
2123 quitserver = this->InboundServerName;
2125 TreeServer* s = FindServer(quitserver);
2128 Squit(s,"Remote host closed the connection");
2130 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2133 virtual int OnIncomingConnection(int newsock, char* ip)
2135 TreeSocket* s = new TreeSocket(newsock, ip);
2141 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2143 for (unsigned int c = 0; c < list.size(); c++)
2145 if (list[c] == server)
2150 list.push_back(server);
2153 // returns a list of DIRECT servernames for a specific channel
2154 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2156 std::vector<char*> *ulist = c->GetUsers();
2157 unsigned int ucount = ulist->size();
2158 for (unsigned int i = 0; i < ucount; i++)
2160 char* o = (*ulist)[i];
2161 userrec* otheruser = (userrec*)o;
2162 if (otheruser->fd < 0)
2164 TreeServer* best = BestRouteTo(otheruser->server);
2166 AddThisServer(best,list);
2172 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2174 TreeServer* omitroute = BestRouteTo(omit);
2175 if ((command == "NOTICE") || (command == "PRIVMSG"))
2177 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2179 if (*(params[0].c_str()) != '#')
2181 // special routing for private messages/notices
2182 userrec* d = Srv->FindNick(params[0]);
2185 std::deque<std::string> par;
2186 par.push_back(params[0]);
2187 par.push_back(":"+params[1]);
2188 DoOneToOne(prefix,command,par,d->server);
2194 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2195 chanrec* c = Srv->FindChannel(params[0]);
2198 std::deque<TreeServer*> list;
2199 GetListOfServersForChannel(c,list);
2200 log(DEBUG,"Got a list of %d servers",list.size());
2201 unsigned int lsize = list.size();
2202 for (unsigned int i = 0; i < lsize; i++)
2204 TreeSocket* Sock = list[i]->GetSocket();
2205 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2207 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2208 Sock->WriteLine(data);
2216 unsigned int items = TreeRoot->ChildCount();
2217 for (unsigned int x = 0; x < items; x++)
2219 TreeServer* Route = TreeRoot->GetChild(x);
2220 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2222 TreeSocket* Sock = Route->GetSocket();
2223 Sock->WriteLine(data);
2229 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2231 TreeServer* omitroute = BestRouteTo(omit);
2232 std::string FullLine = ":" + prefix + " " + command;
2233 unsigned int words = params.size();
2234 for (unsigned int x = 0; x < words; x++)
2236 FullLine = FullLine + " " + params[x];
2238 unsigned int items = TreeRoot->ChildCount();
2239 for (unsigned int x = 0; x < items; x++)
2241 TreeServer* Route = TreeRoot->GetChild(x);
2242 // Send the line IF:
2243 // The route has a socket (its a direct connection)
2244 // The route isnt the one to be omitted
2245 // The route isnt the path to the one to be omitted
2246 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2248 TreeSocket* Sock = Route->GetSocket();
2249 Sock->WriteLine(FullLine);
2255 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2257 std::string FullLine = ":" + prefix + " " + command;
2258 unsigned int words = params.size();
2259 for (unsigned int x = 0; x < words; x++)
2261 FullLine = FullLine + " " + params[x];
2263 unsigned int items = TreeRoot->ChildCount();
2264 for (unsigned int x = 0; x < items; x++)
2266 TreeServer* Route = TreeRoot->GetChild(x);
2267 if (Route->GetSocket())
2269 TreeSocket* Sock = Route->GetSocket();
2270 Sock->WriteLine(FullLine);
2276 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2278 TreeServer* Route = BestRouteTo(target);
2281 std::string FullLine = ":" + prefix + " " + command;
2282 unsigned int words = params.size();
2283 for (unsigned int x = 0; x < words; x++)
2285 FullLine = FullLine + " " + params[x];
2287 if (Route->GetSocket())
2289 TreeSocket* Sock = Route->GetSocket();
2290 Sock->WriteLine(FullLine);
2300 std::vector<TreeSocket*> Bindings;
2302 void ReadConfiguration(bool rebind)
2304 Conf = new ConfigReader;
2307 for (int j =0; j < Conf->Enumerate("bind"); j++)
2309 std::string Type = Conf->ReadValue("bind","type",j);
2310 std::string IP = Conf->ReadValue("bind","address",j);
2311 long Port = Conf->ReadInteger("bind","port",j,true);
2312 if (Type == "servers")
2318 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2319 if (listener->GetState() == I_LISTENING)
2321 Srv->AddSocket(listener);
2322 Bindings.push_back(listener);
2326 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2334 for (int j =0; j < Conf->Enumerate("link"); j++)
2337 L.Name = Conf->ReadValue("link","name",j);
2338 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2339 L.Port = Conf->ReadInteger("link","port",j,true);
2340 L.SendPass = Conf->ReadValue("link","sendpass",j);
2341 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2342 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2343 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2344 L.NextConnectTime = time(NULL) + L.AutoConnect;
2345 /* Bugfix by brain, do not allow people to enter bad configurations */
2346 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2348 LinkBlocks.push_back(L);
2349 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2353 log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2360 class ModuleSpanningTree : public Module
2362 std::vector<TreeSocket*> Bindings;
2368 ModuleSpanningTree(Server* Me)
2369 : Module::Module(Me)
2374 // Create the root of the tree
2375 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2377 ReadConfiguration(true);
2380 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2382 std::string Parent = TreeRoot->GetName();
2383 if (Current->GetParent())
2385 Parent = Current->GetParent()->GetName();
2387 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2389 ShowLinks(Current->GetChild(q),user,hops+1);
2391 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2394 int CountLocalServs()
2396 return TreeRoot->ChildCount();
2401 return serverlist.size();
2404 void HandleLinks(char** parameters, int pcnt, userrec* user)
2406 ShowLinks(TreeRoot,user,0);
2407 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2411 void HandleLusers(char** parameters, int pcnt, userrec* user)
2413 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2414 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2415 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2416 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2417 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2421 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2423 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2427 for (int t = 0; t < depth; t++)
2429 matrix[line][t] = ' ';
2431 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2433 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2435 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2440 // Ok, prepare to be confused.
2441 // After much mulling over how to approach this, it struck me that
2442 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2443 // keeping track of a ton of ascii characters, and line by line
2444 // under recursion working out where to place them using multiplications
2445 // and divisons, we instead render the map onto a backplane of characters
2446 // (a character matrix), then draw the branches as a series of "L" shapes
2447 // from the nodes. This is not only friendlier on CPU it uses less stack.
2449 void HandleMap(char** parameters, int pcnt, userrec* user)
2451 // This array represents a virtual screen which we will
2452 // "scratch" draw to, as the console device of an irc
2453 // client does not provide for a proper terminal.
2454 char matrix[128][80];
2455 for (unsigned int t = 0; t < 128; t++)
2457 matrix[t][0] = '\0';
2460 // The only recursive bit is called here.
2461 ShowMap(TreeRoot,user,0,matrix);
2462 // Process each line one by one. The algorithm has a limit of
2463 // 128 servers (which is far more than a spanning tree should have
2464 // anyway, so we're ok). This limit can be raised simply by making
2465 // the character matrix deeper, 128 rows taking 10k of memory.
2466 for (int l = 1; l < line; l++)
2468 // scan across the line looking for the start of the
2469 // servername (the recursive part of the algorithm has placed
2470 // the servers at indented positions depending on what they
2472 int first_nonspace = 0;
2473 while (matrix[l][first_nonspace] == ' ')
2478 // Draw the `- (corner) section: this may be overwritten by
2479 // another L shape passing along the same vertical pane, becoming
2480 // a |- (branch) section instead.
2481 matrix[l][first_nonspace] = '-';
2482 matrix[l][first_nonspace-1] = '`';
2484 // Draw upwards until we hit the parent server, causing possibly
2485 // other corners (`-) to become branches (|-)
2486 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2488 matrix[l2][first_nonspace-1] = '|';
2492 // dump the whole lot to the user. This is the easy bit, honest.
2493 for (int t = 0; t < line; t++)
2495 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2497 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2501 int HandleSquit(char** parameters, int pcnt, userrec* user)
2503 TreeServer* s = FindServerMask(parameters[0]);
2508 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2511 TreeSocket* sock = s->GetSocket();
2514 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2515 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2516 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2521 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2526 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2531 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2533 if ((user->fd > -1) && (pcnt > 1))
2535 userrec* remote = Srv->FindNick(parameters[1]);
2536 if ((remote) && (remote->fd < 0))
2538 std::deque<std::string> params;
2539 params.push_back(parameters[1]);
2540 DoOneToOne(user->nick,"IDLE",params,remote->server);
2545 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2546 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2553 void DoPingChecks(time_t curtime)
2555 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2557 TreeServer* serv = TreeRoot->GetChild(j);
2558 TreeSocket* sock = serv->GetSocket();
2561 if (curtime >= serv->NextPingTime())
2563 if (serv->AnsweredLastPing())
2565 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2566 serv->SetNextPingTime(curtime + 60);
2570 // they didnt answer, boot them
2571 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2572 sock->Squit(serv,"Ping timeout");
2581 void AutoConnectServers(time_t curtime)
2583 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2585 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2587 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2588 x->NextConnectTime = curtime + x->AutoConnect;
2589 TreeServer* CheckDupe = FindServer(x->Name);
2592 // an autoconnected server is not connected. Check if its time to connect it
2593 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2594 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2595 Srv->AddSocket(newsocket);
2601 int HandleVersion(char** parameters, int pcnt, userrec* user)
2603 // we've already checked if pcnt > 0, so this is safe
2604 TreeServer* found = FindServerMask(parameters[0]);
2607 std::string Version = found->GetVersion();
2608 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2612 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2617 int HandleConnect(char** parameters, int pcnt, userrec* user)
2619 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2621 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2623 TreeServer* CheckDupe = FindServer(x->Name);
2626 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);
2627 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2628 Srv->AddSocket(newsocket);
2633 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());
2638 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2642 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2644 if (*parameters[0] == 'c')
2646 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2648 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"));
2649 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2651 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2652 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2658 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2660 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2664 if (command == "CONNECT")
2666 return this->HandleConnect(parameters,pcnt,user);
2668 else if (command == "SQUIT")
2670 return this->HandleSquit(parameters,pcnt,user);
2672 else if (command == "STATS")
2674 return this->HandleStats(parameters,pcnt,user);
2676 else if (command == "MAP")
2678 this->HandleMap(parameters,pcnt,user);
2681 else if (command == "LUSERS")
2683 this->HandleLusers(parameters,pcnt,user);
2686 else if (command == "LINKS")
2688 this->HandleLinks(parameters,pcnt,user);
2691 else if (command == "WHOIS")
2696 return this->HandleRemoteWhois(parameters,pcnt,user);
2699 else if ((command == "VERSION") && (pcnt > 0))
2701 this->HandleVersion(parameters,pcnt,user);
2704 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2706 // this bit of code cleverly routes all module commands
2707 // to all remote severs *automatically* so that modules
2708 // can just handle commands locally, without having
2709 // to have any special provision in place for remote
2710 // commands and linking protocols.
2711 std::deque<std::string> params;
2713 for (int j = 0; j < pcnt; j++)
2715 if (strchr(parameters[j],' '))
2717 params.push_back(":" + std::string(parameters[j]));
2721 params.push_back(std::string(parameters[j]));
2724 DoOneToMany(user->nick,command,params);
2729 virtual void OnGetServerDescription(std::string servername,std::string &description)
2731 TreeServer* s = FindServer(servername);
2734 description = s->GetDesc();
2738 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2740 if (source->fd > -1)
2742 std::deque<std::string> params;
2743 params.push_back(dest->nick);
2744 params.push_back(channel->name);
2745 DoOneToMany(source->nick,"INVITE",params);
2749 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2751 std::deque<std::string> params;
2752 params.push_back(chan->name);
2753 params.push_back(":"+topic);
2754 DoOneToMany(user->nick,"TOPIC",params);
2757 virtual void OnWallops(userrec* user, std::string text)
2761 std::deque<std::string> params;
2762 params.push_back(":"+text);
2763 DoOneToMany(user->nick,"WALLOPS",params);
2767 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2769 if (target_type == TYPE_USER)
2771 userrec* d = (userrec*)dest;
2772 if ((d->fd < 0) && (user->fd > -1))
2774 std::deque<std::string> params;
2776 params.push_back(d->nick);
2777 params.push_back(":"+text);
2778 DoOneToOne(user->nick,"NOTICE",params,d->server);
2785 chanrec *c = (chanrec*)dest;
2786 std::deque<TreeServer*> list;
2787 GetListOfServersForChannel(c,list);
2788 unsigned int ucount = list.size();
2789 for (unsigned int i = 0; i < ucount; i++)
2791 TreeSocket* Sock = list[i]->GetSocket();
2793 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2799 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2801 if (target_type == TYPE_USER)
2803 // route private messages which are targetted at clients only to the server
2804 // which needs to receive them
2805 userrec* d = (userrec*)dest;
2806 if ((d->fd < 0) && (user->fd > -1))
2808 std::deque<std::string> params;
2810 params.push_back(d->nick);
2811 params.push_back(":"+text);
2812 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2819 chanrec *c = (chanrec*)dest;
2820 std::deque<TreeServer*> list;
2821 GetListOfServersForChannel(c,list);
2822 unsigned int ucount = list.size();
2823 for (unsigned int i = 0; i < ucount; i++)
2825 TreeSocket* Sock = list[i]->GetSocket();
2827 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2833 virtual void OnBackgroundTimer(time_t curtime)
2835 AutoConnectServers(curtime);
2836 DoPingChecks(curtime);
2839 virtual void OnUserJoin(userrec* user, chanrec* channel)
2841 // Only do this for local users
2844 std::deque<std::string> params;
2846 params.push_back(channel->name);
2849 // if the channel has a key, force the join by emulating the key.
2850 params.push_back(channel->key);
2852 if (channel->GetUserCounter() > 1)
2854 // not the first in the channel
2855 DoOneToMany(user->nick,"JOIN",params);
2859 // first in the channel, set up their permissions
2860 // and the channel TS with FJOIN.
2862 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2864 params.push_back(channel->name);
2865 params.push_back(ts);
2866 params.push_back("@"+std::string(user->nick));
2867 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2872 virtual void OnChangeHost(userrec* user, std::string newhost)
2874 // only occurs for local clients
2875 if (user->registered != 7)
2877 std::deque<std::string> params;
2878 params.push_back(newhost);
2879 DoOneToMany(user->nick,"FHOST",params);
2882 virtual void OnChangeName(userrec* user, std::string gecos)
2884 // only occurs for local clients
2885 if (user->registered != 7)
2887 std::deque<std::string> params;
2888 params.push_back(gecos);
2889 DoOneToMany(user->nick,"FNAME",params);
2892 virtual void OnUserPart(userrec* user, chanrec* channel)
2896 std::deque<std::string> params;
2897 params.push_back(channel->name);
2898 DoOneToMany(user->nick,"PART",params);
2902 virtual void OnUserConnect(userrec* user)
2904 char agestr[MAXBUF];
2907 std::deque<std::string> params;
2908 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2909 params.push_back(agestr);
2910 params.push_back(user->nick);
2911 params.push_back(user->host);
2912 params.push_back(user->dhost);
2913 params.push_back(user->ident);
2914 params.push_back("+"+std::string(user->modes));
2915 params.push_back(user->ip);
2916 params.push_back(":"+std::string(user->fullname));
2917 DoOneToMany(Srv->GetServerName(),"NICK",params);
2921 virtual void OnUserQuit(userrec* user, std::string reason)
2923 if ((user->fd > -1) && (user->registered == 7))
2925 std::deque<std::string> params;
2926 params.push_back(":"+reason);
2927 DoOneToMany(user->nick,"QUIT",params);
2931 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2935 std::deque<std::string> params;
2936 params.push_back(user->nick);
2937 DoOneToMany(oldnick,"NICK",params);
2941 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2943 if (source->fd > -1)
2945 std::deque<std::string> params;
2946 params.push_back(chan->name);
2947 params.push_back(user->nick);
2948 params.push_back(":"+reason);
2949 DoOneToMany(source->nick,"KICK",params);
2953 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2955 std::deque<std::string> params;
2956 params.push_back(dest->nick);
2957 params.push_back(":"+reason);
2958 DoOneToMany(source->nick,"KILL",params);
2961 virtual void OnRehash(std::string parameter)
2963 if (parameter != "")
2965 std::deque<std::string> params;
2966 params.push_back(parameter);
2967 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2969 if (Srv->MatchText(Srv->GetServerName(),parameter))
2971 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2972 Srv->RehashServer();
2975 ReadConfiguration(false);
2978 // note: the protocol does not allow direct umode +o except
2979 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2981 virtual void OnOper(userrec* user, std::string opertype)
2985 std::deque<std::string> params;
2986 params.push_back(opertype);
2987 DoOneToMany(user->nick,"OPERTYPE",params);
2991 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2993 if (source->fd > -1)
2996 snprintf(type,8,"%cLINE",linetype);
2997 std::string stype = type;
3000 char sduration[MAXBUF];
3001 snprintf(sduration,MAXBUF,"%ld",duration);
3002 std::deque<std::string> params;
3003 params.push_back(host);
3004 params.push_back(sduration);
3005 params.push_back(":"+reason);
3006 DoOneToMany(source->nick,stype,params);
3010 std::deque<std::string> params;
3011 params.push_back(host);
3012 DoOneToMany(source->nick,stype,params);
3017 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3019 OnLine(source,hostmask,true,'G',duration,reason);
3022 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3024 OnLine(source,ipmask,true,'Z',duration,reason);
3027 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3029 OnLine(source,nickmask,true,'Q',duration,reason);
3032 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3034 OnLine(source,hostmask,true,'E',duration,reason);
3037 virtual void OnDelGLine(userrec* source, std::string hostmask)
3039 OnLine(source,hostmask,false,'G',0,"");
3042 virtual void OnDelZLine(userrec* source, std::string ipmask)
3044 OnLine(source,ipmask,false,'Z',0,"");
3047 virtual void OnDelQLine(userrec* source, std::string nickmask)
3049 OnLine(source,nickmask,false,'Q',0,"");
3052 virtual void OnDelELine(userrec* source, std::string hostmask)
3054 OnLine(source,hostmask,false,'E',0,"");
3057 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3059 if ((user->fd > -1) && (user->registered == 7))
3061 if (target_type == TYPE_USER)
3063 userrec* u = (userrec*)dest;
3064 std::deque<std::string> params;
3065 params.push_back(u->nick);
3066 params.push_back(text);
3067 DoOneToMany(user->nick,"MODE",params);
3071 chanrec* c = (chanrec*)dest;
3072 std::deque<std::string> params;
3073 params.push_back(c->name);
3074 params.push_back(text);
3075 DoOneToMany(user->nick,"MODE",params);
3080 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3082 TreeSocket* s = (TreeSocket*)opaque;
3085 if (target_type == TYPE_USER)
3087 userrec* u = (userrec*)target;
3088 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3092 chanrec* c = (chanrec*)target;
3093 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3098 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3100 TreeSocket* s = (TreeSocket*)opaque;
3103 if (target_type == TYPE_USER)
3105 userrec* u = (userrec*)target;
3106 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3110 chanrec* c = (chanrec*)target;
3111 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3116 virtual ~ModuleSpanningTree()
3120 virtual Version GetVersion()
3122 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3125 void Implements(char* List)
3127 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3128 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3129 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3130 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3131 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3132 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3133 List[I_ProtoSendMetaData] = 1;
3138 class ModuleSpanningTreeFactory : public ModuleFactory
3141 ModuleSpanningTreeFactory()
3145 ~ModuleSpanningTreeFactory()
3149 virtual Module * CreateModule(Server* Me)
3151 TreeProtocolModule = new ModuleSpanningTree(Me);
3152 return TreeProtocolModule;
3158 extern "C" void * init_module( void )
3160 return new ModuleSpanningTreeFactory;