1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
25 #include "inspircd_config.h"
27 #include <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 /* Flatten links and /MAP for non-opers */
130 /* Imported from xline.cpp for use during netburst */
131 extern std::vector<KLine> klines;
132 extern std::vector<GLine> glines;
133 extern std::vector<ZLine> zlines;
134 extern std::vector<QLine> qlines;
135 extern std::vector<ELine> elines;
136 extern std::vector<KLine> pklines;
137 extern std::vector<GLine> pglines;
138 extern std::vector<ZLine> pzlines;
139 extern std::vector<QLine> pqlines;
140 extern std::vector<ELine> pelines;
142 /* Each server in the tree is represented by one class of
143 * type TreeServer. A locally connected TreeServer can
144 * have a class of type TreeSocket associated with it, for
145 * remote servers, the TreeSocket entry will be NULL.
146 * Each server also maintains a pointer to its parent
147 * (NULL if this server is ours, at the top of the tree)
148 * and a pointer to its "Route" (see the comments in the
149 * constructors below), and also a dynamic list of pointers
150 * to its children which can be iterated recursively
151 * if required. Creating or deleting objects of type
152 * TreeServer automatically maintains the hash_map of
153 * TreeServer items, deleting and inserting them as they
154 * are created and destroyed.
159 TreeServer* Parent; /* Parent entry */
160 TreeServer* Route; /* Route entry */
161 std::vector<TreeServer*> Children; /* List of child objects */
162 std::string ServerName; /* Server's name */
163 std::string ServerDesc; /* Server's description */
164 std::string VersionString; /* Version string or empty string */
165 int UserCount; /* Not used in this version */
166 int OperCount; /* Not used in this version */
167 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
168 time_t NextPing; /* After this time, the server should be PINGed*/
169 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
173 /* We don't use this constructor. Its a dummy, and won't cause any insertion
174 * of the TreeServer into the hash_map. See below for the two we DO use.
182 UserCount = OperCount = 0;
183 VersionString = Srv->GetVersion();
186 /* We use this constructor only to create the 'root' item, TreeRoot, which
187 * represents our own server. Therefore, it has no route, no parent, and
188 * no socket associated with it. Its version string is our own local version.
190 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
194 UserCount = OperCount = 0;
195 VersionString = Srv->GetVersion();
197 Socket = NULL; /* Fix by brain */
201 /* When we create a new server, we call this constructor to initialize it.
202 * This constructor initializes the server's Route and Parent, and sets up
203 * its ping counters so that it will be pinged one minute from now.
205 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
208 UserCount = OperCount = 0;
209 this->SetNextPingTime(time(NULL) + 120);
212 /* find the 'route' for this server (e.g. the one directly connected
213 * to the local server, which we can use to reach it)
215 * In the following example, consider we have just added a TreeServer
216 * class for server G on our network, of which we are server A.
217 * To route traffic to G (marked with a *) we must send the data to
218 * B (marked with a +) so this algorithm initializes the 'Route'
219 * value to point at whichever server traffic must be routed through
220 * to get here. If we were to try this algorithm with server B,
221 * the Route pointer would point at its own object ('this').
231 * We only run this algorithm when a server is created, as
232 * the routes remain constant while ever the server exists, and
233 * do not need to be re-calculated.
237 if (Route == TreeRoot)
243 while (this->Route->GetParent() != TreeRoot)
245 this->Route = Route->GetParent();
249 /* Because recursive code is slow and takes a lot of resources,
250 * we store two representations of the server tree. The first
251 * is a recursive structure where each server references its
252 * children and its parent, which is used for netbursts and
253 * netsplits to dump the whole dataset to the other server,
254 * and the second is used for very fast lookups when routing
255 * messages and is instead a hash_map, where each item can
256 * be referenced by its server name. The AddHashEntry()
257 * call below automatically inserts each TreeServer class
258 * into the hash_map as it is created. There is a similar
259 * maintainance call in the destructor to tidy up deleted
263 this->AddHashEntry();
266 /* This method is used to add the structure to the
267 * hash_map for linear searches. It is only called
268 * by the constructors.
272 server_hash::iterator iter;
273 iter = serverlist.find(this->ServerName);
274 if (iter == serverlist.end())
275 serverlist[this->ServerName] = this;
278 /* This method removes the reference to this object
279 * from the hash_map which is used for linear searches.
280 * It is only called by the default destructor.
284 server_hash::iterator iter;
285 iter = serverlist.find(this->ServerName);
286 if (iter != serverlist.end())
287 serverlist.erase(iter);
290 /* These accessors etc should be pretty self-
294 TreeServer* GetRoute()
299 std::string GetName()
304 std::string GetDesc()
309 std::string GetVersion()
311 return VersionString;
314 void SetNextPingTime(time_t t)
317 LastPingWasGood = false;
320 time_t NextPingTime()
325 bool AnsweredLastPing()
327 return LastPingWasGood;
332 LastPingWasGood = true;
355 TreeSocket* GetSocket()
360 TreeServer* GetParent()
365 void SetVersion(std::string Version)
367 VersionString = Version;
370 unsigned int ChildCount()
372 return Children.size();
375 TreeServer* GetChild(unsigned int n)
377 if (n < Children.size())
379 /* Make sure they cant request
380 * an out-of-range object. After
381 * all we know what these programmer
382 * types are like *grin*.
392 void AddChild(TreeServer* Child)
394 Children.push_back(Child);
397 bool DelChild(TreeServer* Child)
399 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
410 /* Removes child nodes of this node, and of that node, etc etc.
411 * This is used during netsplits to automatically tidy up the
412 * server tree. It is slow, we don't use it for much else.
416 bool stillchildren = true;
417 while (stillchildren)
419 stillchildren = false;
420 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
422 TreeServer* s = (TreeServer*)*a;
426 stillchildren = true;
435 /* We'd better tidy up after ourselves, eh? */
436 this->DelHashEntry();
440 /* The Link class might as well be a struct,
441 * but this is C++ and we don't believe in structs (!).
442 * It holds the entire information of one <link>
443 * tag from the main config file. We maintain a list
444 * of them, and populate the list on rehash/load.
453 std::string SendPass;
454 std::string RecvPass;
455 unsigned long AutoConnect;
456 time_t NextConnectTime;
457 std::string EncryptionKey;
458 bool HiddenFromStats;
461 /* The usual stuff for inspircd modules,
462 * plus the vector of Link classes which we
463 * use to store the <link> tags from the config
467 std::vector<Link> LinkBlocks;
469 /* Yay for fast searches!
470 * This is hundreds of times faster than recursion
471 * or even scanning a linked list, especially when
472 * there are more than a few servers to deal with.
475 TreeServer* FindServer(std::string ServerName)
477 server_hash::iterator iter;
478 iter = serverlist.find(ServerName);
479 if (iter != serverlist.end())
489 /* Returns the locally connected server we must route a
490 * message through to reach server 'ServerName'. This
491 * only applies to one-to-one and not one-to-many routing.
492 * See the comments for the constructor of TreeServer
495 TreeServer* BestRouteTo(std::string ServerName)
497 if (ServerName.c_str() == TreeRoot->GetName())
499 TreeServer* Found = FindServer(ServerName);
502 return Found->GetRoute();
510 /* Find the first server matching a given glob mask.
511 * Theres no find-using-glob method of hash_map [awwww :-(]
512 * so instead, we iterate over the list using an iterator
513 * and match each one until we get a hit. Yes its slow,
516 TreeServer* FindServerMask(std::string ServerName)
518 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
520 if (Srv->MatchText(i->first,ServerName))
526 /* A convenient wrapper that returns true if a server exists */
527 bool IsServer(std::string ServerName)
529 return (FindServer(ServerName) != NULL);
532 /* Every SERVER connection inbound or outbound is represented by
533 * an object of type TreeSocket.
534 * TreeSockets, being inherited from InspSocket, can be tied into
535 * the core socket engine, and we cn therefore receive activity events
536 * for them, just like activex objects on speed. (yes really, that
537 * is a technical term!) Each of these which relates to a locally
538 * connected server is assocated with it, by hooking it onto a
539 * TreeSocket class using its constructor. In this way, we can
540 * maintain a list of servers, some of which are directly connected,
541 * some of which are not.
544 class TreeSocket : public InspSocket
547 std::string in_buffer;
548 ServerState LinkState;
549 std::string InboundServerName;
550 std::string InboundDescription;
552 int num_lost_servers;
554 bool LastPingWasGood;
558 unsigned int keylength;
562 /* Because most of the I/O gubbins are encapsulated within
563 * InspSocket, we just call the superclass constructor for
564 * most of the action, and append a few of our own values
567 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
568 : InspSocket(host, port, listening, maxtime)
571 this->LinkState = LISTENER;
573 this->ctx_out = NULL;
576 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
577 : InspSocket(host, port, listening, maxtime)
580 this->LinkState = CONNECTING;
582 this->ctx_out = NULL;
585 /* When a listening socket gives us a new file descriptor,
586 * we must associate it with a socket without creating a new
587 * connection. This constructor is used for this purpose.
589 TreeSocket(int newfd, char* ip)
590 : InspSocket(newfd, ip)
592 this->LinkState = WAIT_AUTH_1;
594 this->ctx_out = NULL;
595 this->SendCapabilities();
606 void InitAES(std::string key,std::string SName)
613 log(DEBUG,"Initialized AES key %s",key.c_str());
614 // key must be 16, 24, 32 etc bytes (multiple of 8)
615 keylength = key.length();
616 if (!(keylength == 16 || keylength == 24 || keylength == 32))
618 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
619 log(DEBUG,"Key length not 16, 24 or 32 characters!");
623 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
624 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\
625 \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);
626 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\
627 \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);
631 /* When an outbound connection finishes connecting, we receive
632 * this event, and must send our SERVER string to the other
633 * side. If the other side is happy, as outlined in the server
634 * to server docs on the inspircd.org site, the other side
635 * will then send back its own server string.
637 virtual bool OnConnected()
639 if (this->LinkState == CONNECTING)
641 /* we do not need to change state here. */
642 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
644 if (x->Name == this->myhost)
646 Srv->SendOpers("*** Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
647 this->SendCapabilities();
648 if (x->EncryptionKey != "")
650 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
652 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
656 this->WriteLine("AES "+Srv->GetServerName());
657 this->InitAES(x->EncryptionKey,x->Name);
660 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
661 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
666 /* There is a (remote) chance that between the /CONNECT and the connection
667 * being accepted, some muppet has removed the <link> block and rehashed.
668 * If that happens the connection hangs here until it's closed. Unlikely
669 * and rather harmless.
671 Srv->SendOpers("*** Connection to \2"+myhost+"\2 lost link tag(!)");
675 virtual void OnError(InspSocketError e)
677 /* We don't handle this method, because all our
678 * dirty work is done in OnClose() (see below)
679 * which is still called on error conditions too.
683 virtual int OnDisconnect()
685 /* For the same reason as above, we don't
686 * handle OnDisconnect()
691 /* Recursively send the server tree with distances as hops.
692 * This is used during network burst to inform the other server
693 * (and any of ITS servers too) of what servers we know about.
694 * If at any point any of these servers already exist on the other
695 * end, our connection may be terminated. The hopcounts given
696 * by this function are relative, this doesn't matter so long as
697 * they are all >1, as all the remote servers re-calculate them
698 * to be relative too, with themselves as hop 0.
700 void SendServers(TreeServer* Current, TreeServer* s, int hops)
703 for (unsigned int q = 0; q < Current->ChildCount(); q++)
705 TreeServer* recursive_server = Current->GetChild(q);
706 if (recursive_server != s)
708 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
709 this->WriteLine(command);
710 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
711 /* down to next level */
712 this->SendServers(recursive_server, s, hops+1);
717 std::string MyCapabilities()
719 ServerConfig* Config = Srv->GetConfig();
720 std::vector<std::string> modlist;
721 std::string capabilities = "";
723 for (int i = 0; i <= MODCOUNT; i++)
725 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
726 modlist.push_back(Config->module_names[i]);
728 sort(modlist.begin(),modlist.end());
729 for (unsigned int i = 0; i < modlist.size(); i++)
732 capabilities = capabilities + ",";
733 capabilities = capabilities + modlist[i];
738 void SendCapabilities()
740 this->WriteLine("CAPAB "+MyCapabilities());
743 bool Capab(std::deque<std::string> params)
745 if (params.size() != 1)
747 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
750 if (params[0] != this->MyCapabilities())
752 std::string quitserver = this->myhost;
753 if (this->InboundServerName != "")
755 quitserver = this->InboundServerName;
757 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
758 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
759 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
760 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
761 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
767 /* This function forces this server to quit, removing this server
768 * and any users on it (and servers and users below that, etc etc).
769 * It's very slow and pretty clunky, but luckily unless your network
770 * is having a REAL bad hair day, this function shouldnt be called
771 * too many times a month ;-)
773 void SquitServer(TreeServer* Current, CullList* Goners)
775 /* recursively squit the servers attached to 'Current'.
776 * We're going backwards so we don't remove users
777 * while we still need them ;)
779 for (unsigned int q = 0; q < Current->ChildCount(); q++)
781 TreeServer* recursive_server = Current->GetChild(q);
782 this->SquitServer(recursive_server,Goners);
784 /* Now we've whacked the kids, whack self */
786 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
788 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
790 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
791 Goners->AddItem(u->second,qreason);
797 /* This is a wrapper function for SquitServer above, which
798 * does some validation first and passes on the SQUIT to all
799 * other remaining servers.
801 void Squit(TreeServer* Current,std::string reason)
803 if ((Current) && (Current != TreeRoot))
805 std::deque<std::string> params;
806 params.push_back(Current->GetName());
807 params.push_back(":"+reason);
808 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
809 if (Current->GetParent() == TreeRoot)
811 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
815 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
817 num_lost_servers = 0;
819 CullList* Goners = new CullList();
820 SquitServer(Current, Goners);
823 Current->GetParent()->DelChild(Current);
826 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
830 log(DEFAULT,"Squit from unknown server");
835 bool ForceMode(std::string source, std::deque<std::string> params)
837 userrec* who = new userrec;
838 who->fd = FD_MAGIC_NUMBER;
839 if (params.size() < 2)
842 for (unsigned int q = 0; q < params.size(); q++)
844 modelist[q] = (char*)params[q].c_str();
846 Srv->SendMode(modelist,params.size(),who);
847 DoOneToAllButSender(source,"FMODE",params,source);
853 bool ForceTopic(std::string source, std::deque<std::string> params)
855 if (params.size() != 4)
857 std::string channel = params[0];
858 time_t ts = atoi(params[1].c_str());
859 std::string setby = params[2];
860 std::string topic = params[3];
861 std::string nsource = source;
863 chanrec* c = Srv->FindChannel(channel);
866 if ((ts >= c->topicset) || (!*c->topic))
868 std::string oldtopic = c->topic;
869 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
870 strlcpy(c->setby,setby.c_str(),NICKMAX);
872 /* if the topic text is the same as the current topic,
873 * dont bother to send the TOPIC command out, just silently
874 * update the set time and set nick.
876 if (oldtopic != topic)
878 userrec* user = Srv->FindNick(source);
881 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
885 WriteChannel(c, user, "TOPIC %s :%s", c->name, c->topic);
886 nsource = user->server;
893 /* all done, send it on its way */
894 params[3] = ":" + params[3];
895 DoOneToAllButSender(source,"FTOPIC",params,nsource);
900 /* FJOIN, similar to unreal SJOIN */
901 bool ForceJoin(std::string source, std::deque<std::string> params)
903 if (params.size() < 3)
907 char modestring[MAXBUF];
908 char* mode_users[127];
909 mode_users[0] = first;
910 mode_users[1] = modestring;
911 strcpy(mode_users[1],"+");
912 unsigned int modectr = 2;
915 std::string channel = params[0];
916 time_t TS = atoi(params[1].c_str());
919 chanrec* chan = Srv->FindChannel(channel);
924 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
926 /* default is a high value, which if we dont have this
927 * channel will let the other side apply their modes.
929 time_t ourTS = time(NULL)+600;
930 chanrec* us = Srv->FindChannel(channel);
936 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
938 /* do this first, so our mode reversals are correctly received by other servers
939 * if there is a TS collision.
941 DoOneToAllButSender(source,"FJOIN",params,source);
943 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
945 /* process one channel at a time, applying modes. */
946 char* usr = (char*)params[usernum].c_str();
947 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
948 * (is this even possible?) */
951 char permissions = *usr;
956 mode_users[modectr++] = usr;
957 strlcat(modestring,"o",MAXBUF);
961 mode_users[modectr++] = usr;
962 strlcat(modestring,"h",MAXBUF);
966 mode_users[modectr++] = usr;
967 strlcat(modestring,"v",MAXBUF);
970 who = Srv->FindNick(usr);
973 Srv->JoinUserToChannel(who,channel,key);
974 if (modectr >= (MAXMODES-1))
976 /* theres a mode for this user. push them onto the mode queue, and flush it
977 * if there are more than MAXMODES to go.
979 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
981 /* We also always let u-lined clients win, no matter what the TS value */
982 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
983 Srv->SendMode(mode_users,modectr,who);
987 log(DEBUG,"Their channel newer than ours, bouncing their modes");
989 std::deque<std::string> params;
990 /* modes are now being UNSET... */
991 *mode_users[1] = '-';
992 for (unsigned int x = 0; x < modectr; x++)
994 params.push_back(mode_users[x]);
996 // tell everyone to bounce the modes. bad modes, bad!
997 DoOneToMany(Srv->GetServerName(),"FMODE",params);
999 strcpy(mode_users[1],"+");
1005 /* there werent enough modes built up to flush it during FJOIN,
1006 * or, there are a number left over. flush them out.
1008 if ((modectr > 2) && (who))
1012 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1013 Srv->SendMode(mode_users,modectr,who);
1017 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1018 std::deque<std::string> params;
1019 *mode_users[1] = '-';
1020 for (unsigned int x = 0; x < modectr; x++)
1022 params.push_back(mode_users[x]);
1024 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1031 bool IntroduceClient(std::string source, std::deque<std::string> params)
1033 if (params.size() < 8)
1035 // NICK age nick host dhost ident +modes ip :gecos
1037 std::string nick = params[1];
1038 std::string host = params[2];
1039 std::string dhost = params[3];
1040 std::string ident = params[4];
1041 time_t age = atoi(params[0].c_str());
1042 std::string modes = params[5];
1043 while (*(modes.c_str()) == '+')
1045 char* m = (char*)modes.c_str();
1049 std::string ip = params[6];
1050 std::string gecos = params[7];
1051 char* tempnick = (char*)nick.c_str();
1052 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1054 user_hash::iterator iter;
1055 iter = clientlist.find(tempnick);
1056 if (iter != clientlist.end())
1059 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);
1060 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1064 clientlist[tempnick] = new userrec();
1065 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1066 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1067 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1068 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1069 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1070 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1071 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1072 clientlist[tempnick]->registered = 7;
1073 clientlist[tempnick]->signon = age;
1074 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1075 inet_aton(ip.c_str(),&clientlist[tempnick]->ip4);
1080 for (int i = 0; i < MAXCHANS; i++)
1081 clientlist[tempnick]->chans.push_back(a);
1083 if (!this->bursting)
1085 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,(char*)inet_ntoa(clientlist[tempnick]->ip4));
1087 params[7] = ":" + params[7];
1088 DoOneToAllButSender(source,"NICK",params,source);
1090 // Increment the Source Servers User Count..
1091 TreeServer* SourceServer = FindServer(source);
1093 SourceServer->AddUserCount();
1099 /* Send one or more FJOINs for a channel of users.
1100 * If the length of a single line is more than 480-NICKMAX
1101 * in length, it is split over multiple lines.
1103 void SendFJoins(TreeServer* Current, chanrec* c)
1105 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1107 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1108 std::map<char*,char*> *ulist = c->GetUsers();
1109 for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
1111 char* o = i->second;
1112 userrec* otheruser = (userrec*)o;
1113 strlcat(list," ",MAXBUF);
1114 strlcat(list,cmode(otheruser,c),MAXBUF);
1115 strlcat(list,otheruser->nick,MAXBUF);
1116 if (strlen(list)>(480-NICKMAX))
1118 log(DEBUG,"FJOIN line wrapped");
1119 this->WriteLine(list);
1120 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1123 if (list[strlen(list)-1] != ':')
1125 log(DEBUG,"Final FJOIN line");
1126 this->WriteLine(list);
1130 /* Send G, Q, Z and E lines */
1131 void SendXLines(TreeServer* Current)
1134 /* Yes, these arent too nice looking, but they get the job done */
1135 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1137 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);
1138 this->WriteLine(data);
1140 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1142 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);
1143 this->WriteLine(data);
1145 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1147 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);
1148 this->WriteLine(data);
1150 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1152 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);
1153 this->WriteLine(data);
1155 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1157 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);
1158 this->WriteLine(data);
1160 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1162 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);
1163 this->WriteLine(data);
1165 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1167 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);
1168 this->WriteLine(data);
1170 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1172 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);
1173 this->WriteLine(data);
1177 /* Send channel modes and topics */
1178 void SendChannelModes(TreeServer* Current)
1181 std::deque<std::string> list;
1182 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1184 SendFJoins(Current, c->second);
1185 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second,true));
1186 this->WriteLine(data);
1187 if (*c->second->topic)
1189 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);
1190 this->WriteLine(data);
1192 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1194 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1195 this->WriteLine(data);
1197 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1199 c->second->GetExtList(list);
1200 for (unsigned int j = 0; j < list.size(); j++)
1202 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1207 /* send all users and their oper state/modes */
1208 void SendUsers(TreeServer* Current)
1211 std::deque<std::string> list;
1212 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1214 if (u->second->registered == 7)
1216 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,(char*)inet_ntoa(u->second->ip4),u->second->fullname);
1217 this->WriteLine(data);
1218 if (strchr(u->second->modes,'o'))
1220 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1222 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1224 u->second->GetExtList(list);
1225 for (unsigned int j = 0; j < list.size(); j++)
1227 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1233 /* This function is called when we want to send a netburst to a local
1234 * server. There is a set order we must do this, because for example
1235 * users require their servers to exist, and channels require their
1236 * users to exist. You get the idea.
1238 void DoBurst(TreeServer* s)
1240 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1241 this->WriteLine("BURST");
1242 /* send our version string */
1243 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1244 /* Send server tree */
1245 this->SendServers(TreeRoot,s,1);
1246 /* Send users and their oper status */
1248 /* Send everything else (channel modes, xlines etc) */
1249 this->SendChannelModes(s);
1250 this->SendXLines(s);
1251 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1252 this->WriteLine("ENDBURST");
1253 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1256 /* This function is called when we receive data from a remote
1257 * server. We buffer the data in a std::string (it doesnt stay
1258 * there for long), reading using InspSocket::Read() which can
1259 * read up to 16 kilobytes in one operation.
1261 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1262 * THE SOCKET OBJECT FOR US.
1264 virtual bool OnDataReady()
1266 char* data = this->Read();
1267 /* Check that the data read is a valid pointer and it has some content */
1270 this->in_buffer += data;
1271 /* While there is at least one new line in the buffer,
1272 * do something useful (we hope!) with it.
1274 while (in_buffer.find("\n") != std::string::npos)
1276 char* line = (char*)in_buffer.c_str();
1277 std::string ret = "";
1278 while ((*line != '\n') && (strlen(line)))
1280 if ((*line != '\r') && (*line != '\n'))
1284 if ((*line == '\n') || (*line == '\r'))
1287 /* Process this one, abort if it
1288 * didnt return true.
1294 memset(result,0,1024);
1296 log(DEBUG,"Original string '%s'",ret.c_str());
1297 /* ERROR + CAPAB is still allowed unencryped */
1298 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1300 int nbytes = from64tobits(out, ret.c_str(), 1024);
1301 if ((nbytes > 0) && (nbytes < 1024))
1303 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1304 ctx_in->Decrypt(out, result, nbytes, 1);
1305 for (int t = 0; t < nbytes; t++)
1306 if (result[t] == '\7') result[t] = 0;
1311 if (!this->ProcessLine(ret))
1317 /* EAGAIN returns an empty but non-NULL string, so this
1318 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1320 return (data != NULL);
1323 int WriteLine(std::string line)
1325 log(DEBUG,"OUT: %s",line.c_str());
1328 log(DEBUG,"AES context");
1330 char result64[10240];
1331 if (this->keylength)
1333 while (line.length() % this->keylength != 0)
1335 // pad it to be a multiple of the key length
1339 unsigned int ll = line.length();
1340 log(DEBUG,"Plaintext line with padding = %d chars",ll);
1341 ctx_out->Encrypt(line.c_str(), result, ll, 1);
1342 log(DEBUG,"Encrypted.");
1343 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1345 log(DEBUG,"Encrypted: %s",line.c_str());
1346 //int from64tobits(char *out, const char *in, int maxlen);
1348 return this->Write(line + "\r\n");
1351 /* Handle ERROR command */
1352 bool Error(std::deque<std::string> params)
1354 if (params.size() < 1)
1356 std::string Errmsg = params[0];
1357 std::string SName = myhost;
1358 if (InboundServerName != "")
1360 SName = InboundServerName;
1362 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1363 /* we will return false to cause the socket to close.
1368 /* Because the core won't let users or even SERVERS set +o,
1369 * we use the OPERTYPE command to do this.
1371 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1373 if (params.size() != 1)
1375 std::string opertype = params[0];
1376 userrec* u = Srv->FindNick(prefix);
1379 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1380 if (!strchr(u->modes,'o'))
1382 strcat(u->modes,"o");
1384 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1389 /* Because Andy insists that services-compatible servers must
1390 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1392 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1394 if (params.size() < 3)
1396 userrec* u = Srv->FindNick(params[0]);
1399 Srv->ChangeUserNick(u,params[1]);
1400 u->age = atoi(params[2].c_str());
1401 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1406 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1408 if (params.size() < 2)
1410 userrec* u = Srv->FindNick(params[0]);
1413 Srv->JoinUserToChannel(u,params[1],"");
1414 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1419 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1421 if (params.size() < 1)
1423 std::string servermask = params[0];
1424 if (Srv->MatchText(Srv->GetServerName(),servermask))
1426 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1427 Srv->RehashServer();
1428 ReadConfiguration(false);
1430 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1434 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1436 if (params.size() != 2)
1438 std::string nick = params[0];
1439 userrec* u = Srv->FindNick(prefix);
1440 userrec* who = Srv->FindNick(nick);
1443 /* Prepend kill source, if we don't have one */
1444 std::string sourceserv = prefix;
1447 sourceserv = u->server;
1449 if (*(params[1].c_str()) != '[')
1451 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1453 std::string reason = params[1];
1454 params[1] = ":" + params[1];
1455 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1456 Srv->QuitUser(who,reason);
1461 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1463 if (params.size() < 1)
1465 TreeServer* ServerSource = FindServer(prefix);
1468 ServerSource->SetPingFlag();
1473 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1475 if (params.size() < 3)
1477 TreeServer* ServerSource = FindServer(prefix);
1480 if (params[0] == "*")
1482 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
1484 else if (*(params[0].c_str()) == '#')
1486 chanrec* c = Srv->FindChannel(params[0]);
1489 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1492 else if (*(params[0].c_str()) != '#')
1494 userrec* u = Srv->FindNick(params[0]);
1497 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1501 params[2] = ":" + params[2];
1502 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1506 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1508 if (params.size() < 1)
1510 TreeServer* ServerSource = FindServer(prefix);
1513 ServerSource->SetVersion(params[0]);
1515 params[0] = ":" + params[0];
1516 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1520 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1522 if (params.size() < 1)
1524 userrec* u = Srv->FindNick(prefix);
1527 Srv->ChangeHost(u,params[0]);
1528 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1533 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1535 if (params.size() < 6)
1537 std::string linetype = params[0]; /* Z, Q, E, G, K */
1538 std::string mask = params[1]; /* Line type dependent */
1539 std::string source = params[2]; /* may not be online or may be a server */
1540 std::string settime = params[3]; /* EPOCH time set */
1541 std::string duration = params[4]; /* Duration secs */
1542 std::string reason = params[5];
1544 switch (*(linetype.c_str()))
1547 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1548 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1551 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1552 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1555 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1556 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1559 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1560 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1563 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1566 /* Just in case... */
1567 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1570 /* Send it on its way */
1571 params[5] = ":" + params[5];
1572 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1576 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1578 if (params.size() < 1)
1580 userrec* u = Srv->FindNick(prefix);
1583 Srv->ChangeGECOS(u,params[0]);
1584 params[0] = ":" + params[0];
1585 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1590 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1592 if (params.size() < 1)
1594 log(DEBUG,"In IDLE command");
1595 userrec* u = Srv->FindNick(prefix);
1598 log(DEBUG,"USER EXISTS: %s",u->nick);
1599 // an incoming request
1600 if (params.size() == 1)
1602 userrec* x = Srv->FindNick(params[0]);
1603 if ((x) && (x->fd > -1))
1605 userrec* x = Srv->FindNick(params[0]);
1606 log(DEBUG,"Got IDLE");
1607 char signon[MAXBUF];
1609 log(DEBUG,"Sending back IDLE 3");
1610 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1611 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1612 std::deque<std::string> par;
1613 par.push_back(prefix);
1614 par.push_back(signon);
1615 par.push_back(idle);
1616 // ours, we're done, pass it BACK
1617 DoOneToOne(params[0],"IDLE",par,u->server);
1621 // not ours pass it on
1622 DoOneToOne(prefix,"IDLE",params,x->server);
1625 else if (params.size() == 3)
1627 std::string who_did_the_whois = params[0];
1628 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1629 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1631 log(DEBUG,"Got final IDLE");
1632 // an incoming reply to a whois we sent out
1633 std::string nick_whoised = prefix;
1634 unsigned long signon = atoi(params[1].c_str());
1635 unsigned long idle = atoi(params[2].c_str());
1636 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1637 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1641 // not ours, pass it on
1642 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1649 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1651 if (params.size() < 1)
1653 std::string stufftobounce = params[0];
1654 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1658 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1660 if (params.size() < 4)
1662 std::string servername = params[0];
1663 std::string password = params[1];
1664 // hopcount is not used for a remote server, we calculate this ourselves
1665 std::string description = params[3];
1666 TreeServer* ParentOfThis = FindServer(prefix);
1669 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1672 TreeServer* CheckDupe = FindServer(servername);
1675 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1676 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1679 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1680 ParentOfThis->AddChild(Node);
1681 params[3] = ":" + params[3];
1682 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1683 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1687 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1689 if (params.size() < 4)
1691 std::string servername = params[0];
1692 std::string password = params[1];
1693 int hops = atoi(params[2].c_str());
1696 this->WriteLine("ERROR :Server too far away for authentication");
1697 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1700 std::string description = params[3];
1701 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1703 if ((x->Name == servername) && (x->RecvPass == password))
1705 TreeServer* CheckDupe = FindServer(servername);
1708 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1709 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1712 // Begin the sync here. this kickstarts the
1713 // other side, waiting in WAIT_AUTH_2 state,
1714 // into starting their burst, as it shows
1715 // that we're happy.
1716 this->LinkState = CONNECTED;
1717 // we should add the details of this server now
1718 // to the servers tree, as a child of the root
1720 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1721 TreeRoot->AddChild(Node);
1722 params[3] = ":" + params[3];
1723 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1724 this->bursting = true;
1725 this->DoBurst(Node);
1729 this->WriteLine("ERROR :Invalid credentials");
1730 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1734 bool Inbound_Server(std::deque<std::string> ¶ms)
1736 if (params.size() < 4)
1738 std::string servername = params[0];
1739 std::string password = params[1];
1740 int hops = atoi(params[2].c_str());
1743 this->WriteLine("ERROR :Server too far away for authentication");
1744 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1747 std::string description = params[3];
1748 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1750 if ((x->Name == servername) && (x->RecvPass == password))
1752 TreeServer* CheckDupe = FindServer(servername);
1755 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1756 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1759 /* If the config says this link is encrypted, but the remote side
1760 * hasnt bothered to send the AES command before SERVER, then we
1761 * boot them off as we MUST have this connection encrypted.
1763 if ((x->EncryptionKey != "") && (!this->ctx_in))
1765 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1766 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1769 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
1770 this->InboundServerName = servername;
1771 this->InboundDescription = description;
1772 // this is good. Send our details: Our server name and description and hopcount of 0,
1773 // along with the sendpass from this block.
1774 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1775 // move to the next state, we are now waiting for THEM.
1776 this->LinkState = WAIT_AUTH_2;
1780 this->WriteLine("ERROR :Invalid credentials");
1781 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1785 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1787 if (!strchr(line.c_str(),' '))
1792 std::stringstream s(line);
1793 std::string param = "";
1812 if ((param == ":") && (item > 0))
1835 bool ProcessLine(std::string line)
1837 char* l = (char*)line.c_str();
1838 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1839 l[strlen(l)-1] = '\0';
1843 Srv->Log(DEBUG,"IN: "+line);
1845 std::deque<std::string> params;
1846 this->Split(line,true,params);
1847 std::string command = "";
1848 std::string prefix = "";
1849 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1852 command = params[1];
1853 char* pref = (char*)prefix.c_str();
1861 command = params[0];
1865 if ((!this->ctx_in) && (command == "AES"))
1867 std::string sserv = params[0];
1868 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1870 if ((x->EncryptionKey != "") && (x->Name == sserv))
1872 this->InitAES(x->EncryptionKey,sserv);
1877 else if ((this->ctx_in) && (command == "AES"))
1879 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1882 switch (this->LinkState)
1887 // Waiting for SERVER command from remote server. Server initiating
1888 // the connection sends the first SERVER command, listening server
1889 // replies with theirs if its happy, then if the initiator is happy,
1890 // it starts to send its net sync, which starts the merge, otherwise
1891 // it sends an ERROR.
1892 if (command == "PASS")
1894 /* Silently ignored */
1896 else if (command == "SERVER")
1898 return this->Inbound_Server(params);
1900 else if (command == "ERROR")
1902 return this->Error(params);
1904 else if (command == "USER")
1906 this->WriteLine("ERROR :Client connections to this port are prohibited.");
1909 else if (command == "CAPAB")
1911 return this->Capab(params);
1913 else if ((command == "U") || (command == "S"))
1915 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1920 this->WriteLine("ERROR :Invalid command in negotiation phase.");
1925 // Waiting for start of other side's netmerge to say they liked our
1927 if (command == "SERVER")
1929 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1933 else if ((command == "U") || (command == "S"))
1935 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1938 else if (command == "BURST")
1940 this->LinkState = CONNECTED;
1941 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1942 TreeRoot->AddChild(Node);
1944 params.push_back(InboundServerName);
1945 params.push_back("*");
1946 params.push_back("1");
1947 params.push_back(":"+InboundDescription);
1948 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1949 this->bursting = true;
1950 this->DoBurst(Node);
1952 else if (command == "ERROR")
1954 return this->Error(params);
1956 else if (command == "CAPAB")
1958 return this->Capab(params);
1963 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1967 if (command == "SERVER")
1969 // another server we connected to, which was in WAIT_AUTH_1 state,
1970 // has just sent us their credentials. If we get this far, theyre
1971 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1972 // if we're happy with this, we should send our netburst which
1973 // kickstarts the merge.
1974 return this->Outbound_Reply_Server(params);
1976 else if (command == "ERROR")
1978 return this->Error(params);
1982 // This is the 'authenticated' state, when all passwords
1983 // have been exchanged and anything past this point is taken
1988 std::string direction = prefix;
1989 userrec* t = Srv->FindNick(prefix);
1992 direction = t->server;
1994 TreeServer* route_back_again = BestRouteTo(direction);
1995 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1997 if (route_back_again)
1998 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2003 * When there is activity on the socket, reset the ping counter so
2004 * that we're not wasting bandwidth pinging an active server.
2006 route_back_again->SetNextPingTime(time(NULL) + 120);
2007 route_back_again->SetPingFlag();
2010 if (command == "SVSMODE")
2012 /* Services expects us to implement
2013 * SVSMODE. In inspircd its the same as
2018 std::string target = "";
2019 /* Yes, know, this is a mess. Its reasonably fast though as we're
2020 * working with std::string here.
2022 if ((command == "NICK") && (params.size() > 1))
2024 return this->IntroduceClient(prefix,params);
2026 else if (command == "FJOIN")
2028 return this->ForceJoin(prefix,params);
2030 else if (command == "SERVER")
2032 return this->RemoteServer(prefix,params);
2034 else if (command == "ERROR")
2036 return this->Error(params);
2038 else if (command == "OPERTYPE")
2040 return this->OperType(prefix,params);
2042 else if (command == "FMODE")
2044 return this->ForceMode(prefix,params);
2046 else if (command == "KILL")
2048 return this->RemoteKill(prefix,params);
2050 else if (command == "FTOPIC")
2052 return this->ForceTopic(prefix,params);
2054 else if (command == "REHASH")
2056 return this->RemoteRehash(prefix,params);
2058 else if (command == "METADATA")
2060 return this->MetaData(prefix,params);
2062 else if (command == "PING")
2064 return this->LocalPing(prefix,params);
2066 else if (command == "PONG")
2068 return this->LocalPong(prefix,params);
2070 else if (command == "VERSION")
2072 return this->ServerVersion(prefix,params);
2074 else if (command == "FHOST")
2076 return this->ChangeHost(prefix,params);
2078 else if (command == "FNAME")
2080 return this->ChangeName(prefix,params);
2082 else if (command == "ADDLINE")
2084 return this->AddLine(prefix,params);
2086 else if (command == "SVSNICK")
2090 prefix = this->GetName();
2092 return this->ForceNick(prefix,params);
2094 else if (command == "IDLE")
2096 return this->Whois(prefix,params);
2098 else if (command == "SVSJOIN")
2102 prefix = this->GetName();
2104 return this->ServiceJoin(prefix,params);
2106 else if (command == "SQUIT")
2108 if (params.size() == 2)
2110 this->Squit(FindServer(params[0]),params[1]);
2114 else if (command == "ENDBURST")
2116 this->bursting = false;
2121 // not a special inter-server command.
2122 // Emulate the actual user doing the command,
2123 // this saves us having a huge ugly parser.
2124 userrec* who = Srv->FindNick(prefix);
2125 std::string sourceserv = this->myhost;
2126 if (this->InboundServerName != "")
2128 sourceserv = this->InboundServerName;
2132 if ((command == "NICK") && (params.size() > 0))
2134 /* On nick messages, check that the nick doesnt
2135 * already exist here. If it does, kill their copy,
2138 userrec* x = Srv->FindNick(params[0]);
2141 std::deque<std::string> p;
2142 p.push_back(params[0]);
2143 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2144 DoOneToMany(Srv->GetServerName(),"KILL",p);
2146 p.push_back(prefix);
2147 p.push_back("Nickname collision");
2148 DoOneToMany(Srv->GetServerName(),"KILL",p);
2149 Srv->QuitUser(x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2150 userrec* y = Srv->FindNick(prefix);
2153 Srv->QuitUser(y,"Nickname collision");
2155 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2159 target = who->server;
2160 char* strparams[127];
2161 for (unsigned int q = 0; q < params.size(); q++)
2163 strparams[q] = (char*)params[q].c_str();
2165 Srv->CallCommandHandler(command, strparams, params.size(), who);
2169 // its not a user. Its either a server, or somethings screwed up.
2170 if (IsServer(prefix))
2172 target = Srv->GetServerName();
2176 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2180 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2189 virtual std::string GetName()
2191 std::string sourceserv = this->myhost;
2192 if (this->InboundServerName != "")
2194 sourceserv = this->InboundServerName;
2199 virtual void OnTimeout()
2201 if (this->LinkState == CONNECTING)
2203 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2207 virtual void OnClose()
2209 // Connection closed.
2210 // If the connection is fully up (state CONNECTED)
2211 // then propogate a netsplit to all peers.
2212 std::string quitserver = this->myhost;
2213 if (this->InboundServerName != "")
2215 quitserver = this->InboundServerName;
2217 TreeServer* s = FindServer(quitserver);
2220 Squit(s,"Remote host closed the connection");
2222 WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
2225 virtual int OnIncomingConnection(int newsock, char* ip)
2227 TreeSocket* s = new TreeSocket(newsock, ip);
2233 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2235 for (unsigned int c = 0; c < list.size(); c++)
2237 if (list[c] == server)
2242 list.push_back(server);
2245 // returns a list of DIRECT servernames for a specific channel
2246 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2248 std::map<char*,char*> *ulist = c->GetUsers();
2249 for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
2251 char* o = i->second;
2252 userrec* otheruser = (userrec*)o;
2253 if (otheruser->fd < 0)
2255 TreeServer* best = BestRouteTo(otheruser->server);
2257 AddThisServer(best,list);
2263 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2265 TreeServer* omitroute = BestRouteTo(omit);
2266 if ((command == "NOTICE") || (command == "PRIVMSG"))
2268 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2270 if (*(params[0].c_str()) != '#')
2272 // special routing for private messages/notices
2273 userrec* d = Srv->FindNick(params[0]);
2276 std::deque<std::string> par;
2277 par.push_back(params[0]);
2278 par.push_back(":"+params[1]);
2279 DoOneToOne(prefix,command,par,d->server);
2285 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2286 chanrec* c = Srv->FindChannel(params[0]);
2289 std::deque<TreeServer*> list;
2290 GetListOfServersForChannel(c,list);
2291 log(DEBUG,"Got a list of %d servers",list.size());
2292 unsigned int lsize = list.size();
2293 for (unsigned int i = 0; i < lsize; i++)
2295 TreeSocket* Sock = list[i]->GetSocket();
2296 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2298 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2299 Sock->WriteLine(data);
2307 unsigned int items = TreeRoot->ChildCount();
2308 for (unsigned int x = 0; x < items; x++)
2310 TreeServer* Route = TreeRoot->GetChild(x);
2311 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2313 TreeSocket* Sock = Route->GetSocket();
2314 Sock->WriteLine(data);
2320 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2322 TreeServer* omitroute = BestRouteTo(omit);
2323 std::string FullLine = ":" + prefix + " " + command;
2324 unsigned int words = params.size();
2325 for (unsigned int x = 0; x < words; x++)
2327 FullLine = FullLine + " " + params[x];
2329 unsigned int items = TreeRoot->ChildCount();
2330 for (unsigned int x = 0; x < items; x++)
2332 TreeServer* Route = TreeRoot->GetChild(x);
2333 // Send the line IF:
2334 // The route has a socket (its a direct connection)
2335 // The route isnt the one to be omitted
2336 // The route isnt the path to the one to be omitted
2337 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2339 TreeSocket* Sock = Route->GetSocket();
2340 Sock->WriteLine(FullLine);
2346 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2348 std::string FullLine = ":" + prefix + " " + command;
2349 unsigned int words = params.size();
2350 for (unsigned int x = 0; x < words; x++)
2352 FullLine = FullLine + " " + params[x];
2354 unsigned int items = TreeRoot->ChildCount();
2355 for (unsigned int x = 0; x < items; x++)
2357 TreeServer* Route = TreeRoot->GetChild(x);
2358 if (Route->GetSocket())
2360 TreeSocket* Sock = Route->GetSocket();
2361 Sock->WriteLine(FullLine);
2367 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2369 TreeServer* Route = BestRouteTo(target);
2372 std::string FullLine = ":" + prefix + " " + command;
2373 unsigned int words = params.size();
2374 for (unsigned int x = 0; x < words; x++)
2376 FullLine = FullLine + " " + params[x];
2378 if (Route->GetSocket())
2380 TreeSocket* Sock = Route->GetSocket();
2381 Sock->WriteLine(FullLine);
2391 std::vector<TreeSocket*> Bindings;
2393 void ReadConfiguration(bool rebind)
2395 Conf = new ConfigReader;
2398 for (int j =0; j < Conf->Enumerate("bind"); j++)
2400 std::string Type = Conf->ReadValue("bind","type",j);
2401 std::string IP = Conf->ReadValue("bind","address",j);
2402 long Port = Conf->ReadInteger("bind","port",j,true);
2403 if (Type == "servers")
2409 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2410 if (listener->GetState() == I_LISTENING)
2412 Srv->AddSocket(listener);
2413 Bindings.push_back(listener);
2417 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2424 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
2426 for (int j =0; j < Conf->Enumerate("link"); j++)
2429 L.Name = Conf->ReadValue("link","name",j);
2430 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2431 L.Port = Conf->ReadInteger("link","port",j,true);
2432 L.SendPass = Conf->ReadValue("link","sendpass",j);
2433 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2434 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2435 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2436 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
2437 L.NextConnectTime = time(NULL) + L.AutoConnect;
2438 /* Bugfix by brain, do not allow people to enter bad configurations */
2439 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2441 LinkBlocks.push_back(L);
2442 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2446 if (L.RecvPass == "")
2448 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
2450 else if (L.SendPass == "")
2452 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
2454 else if (L.Name == "")
2456 log(DEFAULT,"Invalid configuration, link tag without a name!");
2460 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
2468 class ModuleSpanningTree : public Module
2470 std::vector<TreeSocket*> Bindings;
2476 ModuleSpanningTree(Server* Me)
2477 : Module::Module(Me)
2482 // Create the root of the tree
2483 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2485 ReadConfiguration(true);
2488 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2490 std::string Parent = TreeRoot->GetName();
2491 if (Current->GetParent())
2493 Parent = Current->GetParent()->GetName();
2495 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2497 ShowLinks(Current->GetChild(q),user,hops+1);
2499 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),(FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
2502 int CountLocalServs()
2504 return TreeRoot->ChildCount();
2509 return serverlist.size();
2512 void HandleLinks(char** parameters, int pcnt, userrec* user)
2514 ShowLinks(TreeRoot,user,0);
2515 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2519 void HandleLusers(char** parameters, int pcnt, userrec* user)
2521 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2522 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2523 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2524 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2525 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2529 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2531 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2535 for (int t = 0; t < depth; t++)
2537 matrix[line][t] = ' ';
2540 // For Aligning, we need to work out exactly how deep this thing is, and produce
2541 // a 'Spacer' String to compensate.
2544 memset(spacer,' ',40);
2545 if ((40 - Current->GetName().length() - depth) > 1) {
2546 spacer[40 - Current->GetName().length() - depth] = '\0';
2555 if (clientlist.size() == 0) {
2556 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
2561 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
2563 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
2564 strlcpy(&matrix[line][depth],text,80);
2566 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2568 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix);
2573 // Ok, prepare to be confused.
2574 // After much mulling over how to approach this, it struck me that
2575 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2576 // keeping track of a ton of ascii characters, and line by line
2577 // under recursion working out where to place them using multiplications
2578 // and divisons, we instead render the map onto a backplane of characters
2579 // (a character matrix), then draw the branches as a series of "L" shapes
2580 // from the nodes. This is not only friendlier on CPU it uses less stack.
2582 void HandleMap(char** parameters, int pcnt, userrec* user)
2584 // This array represents a virtual screen which we will
2585 // "scratch" draw to, as the console device of an irc
2586 // client does not provide for a proper terminal.
2587 char matrix[128][80];
2588 for (unsigned int t = 0; t < 128; t++)
2590 matrix[t][0] = '\0';
2593 // The only recursive bit is called here.
2594 ShowMap(TreeRoot,user,0,matrix);
2595 // Process each line one by one. The algorithm has a limit of
2596 // 128 servers (which is far more than a spanning tree should have
2597 // anyway, so we're ok). This limit can be raised simply by making
2598 // the character matrix deeper, 128 rows taking 10k of memory.
2599 for (int l = 1; l < line; l++)
2601 // scan across the line looking for the start of the
2602 // servername (the recursive part of the algorithm has placed
2603 // the servers at indented positions depending on what they
2605 int first_nonspace = 0;
2606 while (matrix[l][first_nonspace] == ' ')
2611 // Draw the `- (corner) section: this may be overwritten by
2612 // another L shape passing along the same vertical pane, becoming
2613 // a |- (branch) section instead.
2614 matrix[l][first_nonspace] = '-';
2615 matrix[l][first_nonspace-1] = '`';
2617 // Draw upwards until we hit the parent server, causing possibly
2618 // other corners (`-) to become branches (|-)
2619 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2621 matrix[l2][first_nonspace-1] = '|';
2625 // dump the whole lot to the user. This is the easy bit, honest.
2626 for (int t = 0; t < line; t++)
2628 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2630 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2634 int HandleSquit(char** parameters, int pcnt, userrec* user)
2636 TreeServer* s = FindServerMask(parameters[0]);
2641 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2644 TreeSocket* sock = s->GetSocket();
2647 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2648 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2649 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2650 Srv->RemoveSocket(sock);
2654 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2659 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2664 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2666 if ((user->fd > -1) && (pcnt > 1))
2668 userrec* remote = Srv->FindNick(parameters[1]);
2669 if ((remote) && (remote->fd < 0))
2671 std::deque<std::string> params;
2672 params.push_back(parameters[1]);
2673 DoOneToOne(user->nick,"IDLE",params,remote->server);
2678 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2679 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2686 void DoPingChecks(time_t curtime)
2688 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2690 TreeServer* serv = TreeRoot->GetChild(j);
2691 TreeSocket* sock = serv->GetSocket();
2694 if (curtime >= serv->NextPingTime())
2696 if (serv->AnsweredLastPing())
2698 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2699 serv->SetNextPingTime(curtime + 120);
2703 // they didnt answer, boot them
2704 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2705 sock->Squit(serv,"Ping timeout");
2706 Srv->RemoveSocket(sock);
2715 void AutoConnectServers(time_t curtime)
2717 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2719 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2721 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2722 x->NextConnectTime = curtime + x->AutoConnect;
2723 TreeServer* CheckDupe = FindServer(x->Name);
2726 // an autoconnected server is not connected. Check if its time to connect it
2727 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2728 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2729 if (newsocket->GetState() != I_ERROR)
2731 Srv->AddSocket(newsocket);
2735 WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002.",x->Name.c_str());
2743 int HandleVersion(char** parameters, int pcnt, userrec* user)
2745 // we've already checked if pcnt > 0, so this is safe
2746 TreeServer* found = FindServerMask(parameters[0]);
2749 std::string Version = found->GetVersion();
2750 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2751 if (found == TreeRoot)
2753 std::stringstream out(Config->data005);
2754 std::string token = "";
2755 std::string line5 = "";
2756 int token_counter = 0;
2760 line5 = line5 + token + " ";
2762 if ((token_counter >= 13) || (out.eof() == true))
2764 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2773 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2778 int HandleConnect(char** parameters, int pcnt, userrec* user)
2780 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2782 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2784 TreeServer* CheckDupe = FindServer(x->Name);
2787 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
2788 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2789 if (newsocket->GetState() != I_ERROR)
2791 Srv->AddSocket(newsocket);
2795 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Error connecting \002%s\002.",user->nick,x->Name.c_str());
2802 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());
2807 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2811 virtual int OnStats(char statschar, userrec* user)
2813 if (statschar == 'c')
2815 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2817 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %c%c%c",user->nick,(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr).c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-'),(LinkBlocks[i].AutoConnect ? 'a' : '-'),'s');
2818 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2820 WriteServ(user->fd,"219 %s %c :End of /STATS report",user->nick,statschar);
2821 WriteOpers("*** Notice: Stats '%c' requested by %s (%s@%s)",statschar,user->nick,user->ident,user->host);
2827 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2829 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2833 if (command == "CONNECT")
2835 return this->HandleConnect(parameters,pcnt,user);
2837 else if (command == "SQUIT")
2839 return this->HandleSquit(parameters,pcnt,user);
2841 else if (command == "MAP")
2843 this->HandleMap(parameters,pcnt,user);
2846 else if (command == "LUSERS")
2848 this->HandleLusers(parameters,pcnt,user);
2851 else if (command == "LINKS")
2853 this->HandleLinks(parameters,pcnt,user);
2856 else if (command == "WHOIS")
2861 return this->HandleRemoteWhois(parameters,pcnt,user);
2864 else if ((command == "VERSION") && (pcnt > 0))
2866 this->HandleVersion(parameters,pcnt,user);
2869 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2871 // this bit of code cleverly routes all module commands
2872 // to all remote severs *automatically* so that modules
2873 // can just handle commands locally, without having
2874 // to have any special provision in place for remote
2875 // commands and linking protocols.
2876 std::deque<std::string> params;
2878 for (int j = 0; j < pcnt; j++)
2880 if (strchr(parameters[j],' '))
2882 params.push_back(":" + std::string(parameters[j]));
2886 params.push_back(std::string(parameters[j]));
2889 log(DEBUG,"Globally route '%s'",command.c_str());
2890 DoOneToMany(user->nick,command,params);
2895 virtual void OnGetServerDescription(std::string servername,std::string &description)
2897 TreeServer* s = FindServer(servername);
2900 description = s->GetDesc();
2904 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2906 if (source->fd > -1)
2908 std::deque<std::string> params;
2909 params.push_back(dest->nick);
2910 params.push_back(channel->name);
2911 DoOneToMany(source->nick,"INVITE",params);
2915 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2917 std::deque<std::string> params;
2918 params.push_back(chan->name);
2919 params.push_back(":"+topic);
2920 DoOneToMany(user->nick,"TOPIC",params);
2923 virtual void OnWallops(userrec* user, std::string text)
2927 std::deque<std::string> params;
2928 params.push_back(":"+text);
2929 DoOneToMany(user->nick,"WALLOPS",params);
2933 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2935 if (target_type == TYPE_USER)
2937 userrec* d = (userrec*)dest;
2938 if ((d->fd < 0) && (user->fd > -1))
2940 std::deque<std::string> params;
2942 params.push_back(d->nick);
2943 params.push_back(":"+text);
2944 DoOneToOne(user->nick,"NOTICE",params,d->server);
2951 chanrec *c = (chanrec*)dest;
2952 std::deque<TreeServer*> list;
2953 GetListOfServersForChannel(c,list);
2954 unsigned int ucount = list.size();
2955 for (unsigned int i = 0; i < ucount; i++)
2957 TreeSocket* Sock = list[i]->GetSocket();
2959 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2965 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2967 if (target_type == TYPE_USER)
2969 // route private messages which are targetted at clients only to the server
2970 // which needs to receive them
2971 userrec* d = (userrec*)dest;
2972 if ((d->fd < 0) && (user->fd > -1))
2974 std::deque<std::string> params;
2976 params.push_back(d->nick);
2977 params.push_back(":"+text);
2978 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2985 chanrec *c = (chanrec*)dest;
2986 std::deque<TreeServer*> list;
2987 GetListOfServersForChannel(c,list);
2988 unsigned int ucount = list.size();
2989 for (unsigned int i = 0; i < ucount; i++)
2991 TreeSocket* Sock = list[i]->GetSocket();
2993 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2999 virtual void OnBackgroundTimer(time_t curtime)
3001 AutoConnectServers(curtime);
3002 DoPingChecks(curtime);
3005 virtual void OnUserJoin(userrec* user, chanrec* channel)
3007 // Only do this for local users
3010 std::deque<std::string> params;
3012 params.push_back(channel->name);
3015 // if the channel has a key, force the join by emulating the key.
3016 params.push_back(channel->key);
3018 if (channel->GetUserCounter() > 1)
3020 // not the first in the channel
3021 DoOneToMany(user->nick,"JOIN",params);
3025 // first in the channel, set up their permissions
3026 // and the channel TS with FJOIN.
3028 snprintf(ts,24,"%lu",(unsigned long)channel->age);
3030 params.push_back(channel->name);
3031 params.push_back(ts);
3032 params.push_back("@"+std::string(user->nick));
3033 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
3038 virtual void OnChangeHost(userrec* user, std::string newhost)
3040 // only occurs for local clients
3041 if (user->registered != 7)
3043 std::deque<std::string> params;
3044 params.push_back(newhost);
3045 DoOneToMany(user->nick,"FHOST",params);
3048 virtual void OnChangeName(userrec* user, std::string gecos)
3050 // only occurs for local clients
3051 if (user->registered != 7)
3053 std::deque<std::string> params;
3054 params.push_back(gecos);
3055 DoOneToMany(user->nick,"FNAME",params);
3058 virtual void OnUserPart(userrec* user, chanrec* channel, std::string partmessage)
3062 std::deque<std::string> params;
3063 params.push_back(channel->name);
3064 if (partmessage != "")
3065 params.push_back(":"+partmessage);
3066 DoOneToMany(user->nick,"PART",params);
3070 virtual void OnUserConnect(userrec* user)
3072 char agestr[MAXBUF];
3075 std::deque<std::string> params;
3076 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
3077 params.push_back(agestr);
3078 params.push_back(user->nick);
3079 params.push_back(user->host);
3080 params.push_back(user->dhost);
3081 params.push_back(user->ident);
3082 params.push_back("+"+std::string(user->modes));
3083 params.push_back((char*)inet_ntoa(user->ip4));
3084 params.push_back(":"+std::string(user->fullname));
3085 DoOneToMany(Srv->GetServerName(),"NICK",params);
3087 // User is Local, change needs to be reflected!
3088 TreeServer* SourceServer = FindServer(user->server);
3090 SourceServer->AddUserCount();
3096 virtual void OnUserQuit(userrec* user, std::string reason)
3098 if ((user->fd > -1) && (user->registered == 7))
3100 std::deque<std::string> params;
3101 params.push_back(":"+reason);
3102 DoOneToMany(user->nick,"QUIT",params);
3104 // Regardless, We need to modify the user Counts..
3105 TreeServer* SourceServer = FindServer(user->server);
3107 SourceServer->DelUserCount();
3112 virtual void OnUserPostNick(userrec* user, std::string oldnick)
3116 std::deque<std::string> params;
3117 params.push_back(user->nick);
3118 DoOneToMany(oldnick,"NICK",params);
3122 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
3124 if ((source) && (source->fd > -1))
3126 std::deque<std::string> params;
3127 params.push_back(chan->name);
3128 params.push_back(user->nick);
3129 params.push_back(":"+reason);
3130 DoOneToMany(source->nick,"KICK",params);
3134 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
3136 std::deque<std::string> params;
3137 params.push_back(dest->nick);
3138 params.push_back(":"+reason);
3139 DoOneToMany(source->nick,"KILL",params);
3142 virtual void OnRehash(std::string parameter)
3144 if (parameter != "")
3146 std::deque<std::string> params;
3147 params.push_back(parameter);
3148 DoOneToMany(Srv->GetServerName(),"REHASH",params);
3150 if (Srv->MatchText(Srv->GetServerName(),parameter))
3152 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
3153 Srv->RehashServer();
3156 ReadConfiguration(false);
3159 // note: the protocol does not allow direct umode +o except
3160 // via NICK with 8 params. sending OPERTYPE infers +o modechange
3162 virtual void OnOper(userrec* user, std::string opertype)
3166 std::deque<std::string> params;
3167 params.push_back(opertype);
3168 DoOneToMany(user->nick,"OPERTYPE",params);
3172 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
3174 if (source->fd > -1)
3177 snprintf(type,8,"%cLINE",linetype);
3178 std::string stype = type;
3181 char sduration[MAXBUF];
3182 snprintf(sduration,MAXBUF,"%ld",duration);
3183 std::deque<std::string> params;
3184 params.push_back(host);
3185 params.push_back(sduration);
3186 params.push_back(":"+reason);
3187 DoOneToMany(source->nick,stype,params);
3191 std::deque<std::string> params;
3192 params.push_back(host);
3193 DoOneToMany(source->nick,stype,params);
3198 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3200 OnLine(source,hostmask,true,'G',duration,reason);
3203 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3205 OnLine(source,ipmask,true,'Z',duration,reason);
3208 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3210 OnLine(source,nickmask,true,'Q',duration,reason);
3213 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3215 OnLine(source,hostmask,true,'E',duration,reason);
3218 virtual void OnDelGLine(userrec* source, std::string hostmask)
3220 OnLine(source,hostmask,false,'G',0,"");
3223 virtual void OnDelZLine(userrec* source, std::string ipmask)
3225 OnLine(source,ipmask,false,'Z',0,"");
3228 virtual void OnDelQLine(userrec* source, std::string nickmask)
3230 OnLine(source,nickmask,false,'Q',0,"");
3233 virtual void OnDelELine(userrec* source, std::string hostmask)
3235 OnLine(source,hostmask,false,'E',0,"");
3238 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3240 if ((user->fd > -1) && (user->registered == 7))
3242 if (target_type == TYPE_USER)
3244 userrec* u = (userrec*)dest;
3245 std::deque<std::string> params;
3246 params.push_back(u->nick);
3247 params.push_back(text);
3248 DoOneToMany(user->nick,"MODE",params);
3252 chanrec* c = (chanrec*)dest;
3253 std::deque<std::string> params;
3254 params.push_back(c->name);
3255 params.push_back(text);
3256 DoOneToMany(user->nick,"MODE",params);
3261 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3263 TreeSocket* s = (TreeSocket*)opaque;
3266 if (target_type == TYPE_USER)
3268 userrec* u = (userrec*)target;
3269 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3273 chanrec* c = (chanrec*)target;
3274 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3279 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3281 TreeSocket* s = (TreeSocket*)opaque;
3284 if (target_type == TYPE_USER)
3286 userrec* u = (userrec*)target;
3287 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3289 else if (target_type == TYPE_OTHER)
3291 s->WriteLine(":"+Srv->GetServerName()+" METADATA * "+extname+" :"+extdata);
3293 else if (target_type == TYPE_CHANNEL)
3295 chanrec* c = (chanrec*)target;
3296 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3301 virtual void OnEvent(Event* event)
3303 if (event->GetEventID() == "send_metadata")
3305 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
3306 if (params->size() < 3)
3308 (*params)[2] = ":" + (*params)[2];
3309 DoOneToMany(Srv->GetServerName(),"METADATA",*params);
3313 virtual ~ModuleSpanningTree()
3317 virtual Version GetVersion()
3319 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3322 void Implements(char* List)
3324 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3325 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3326 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3327 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3328 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3329 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3330 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = 1;
3333 /* It is IMPORTANT that m_spanningtree is the last module in the chain
3334 * so that any activity it sees is FINAL, e.g. we arent going to send out
3335 * a NICK message before m_cloaking has finished putting the +x on the user,
3337 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
3338 * the module call queue.
3340 Priority Prioritize()
3342 return PRIORITY_LAST;
3347 class ModuleSpanningTreeFactory : public ModuleFactory
3350 ModuleSpanningTreeFactory()
3354 ~ModuleSpanningTreeFactory()
3358 virtual Module * CreateModule(Server* Me)
3360 TreeProtocolModule = new ModuleSpanningTree(Me);
3361 return TreeProtocolModule;
3367 extern "C" void * init_module( void )
3369 return new ModuleSpanningTreeFactory;