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) + 300);
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;
352 TreeSocket* GetSocket()
357 TreeServer* GetParent()
362 void SetVersion(std::string Version)
364 VersionString = Version;
367 unsigned int ChildCount()
369 return Children.size();
372 TreeServer* GetChild(unsigned int n)
374 if (n < Children.size())
376 /* Make sure they cant request
377 * an out-of-range object. After
378 * all we know what these programmer
379 * types are like *grin*.
389 void AddChild(TreeServer* Child)
391 Children.push_back(Child);
394 bool DelChild(TreeServer* Child)
396 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
407 /* Removes child nodes of this node, and of that node, etc etc.
408 * This is used during netsplits to automatically tidy up the
409 * server tree. It is slow, we don't use it for much else.
413 bool stillchildren = true;
414 while (stillchildren)
416 stillchildren = false;
417 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
419 TreeServer* s = (TreeServer*)*a;
423 stillchildren = true;
432 /* We'd better tidy up after ourselves, eh? */
433 this->DelHashEntry();
437 /* The Link class might as well be a struct,
438 * but this is C++ and we don't believe in structs (!).
439 * It holds the entire information of one <link>
440 * tag from the main config file. We maintain a list
441 * of them, and populate the list on rehash/load.
450 std::string SendPass;
451 std::string RecvPass;
452 unsigned long AutoConnect;
453 time_t NextConnectTime;
454 std::string EncryptionKey;
457 /* The usual stuff for inspircd modules,
458 * plus the vector of Link classes which we
459 * use to store the <link> tags from the config
463 std::vector<Link> LinkBlocks;
465 /* Yay for fast searches!
466 * This is hundreds of times faster than recursion
467 * or even scanning a linked list, especially when
468 * there are more than a few servers to deal with.
471 TreeServer* FindServer(std::string ServerName)
473 server_hash::iterator iter;
474 iter = serverlist.find(ServerName);
475 if (iter != serverlist.end())
485 /* Returns the locally connected server we must route a
486 * message through to reach server 'ServerName'. This
487 * only applies to one-to-one and not one-to-many routing.
488 * See the comments for the constructor of TreeServer
491 TreeServer* BestRouteTo(std::string ServerName)
493 if (ServerName.c_str() == TreeRoot->GetName())
495 TreeServer* Found = FindServer(ServerName);
498 return Found->GetRoute();
506 /* Find the first server matching a given glob mask.
507 * Theres no find-using-glob method of hash_map [awwww :-(]
508 * so instead, we iterate over the list using an iterator
509 * and match each one until we get a hit. Yes its slow,
512 TreeServer* FindServerMask(std::string ServerName)
514 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
516 if (Srv->MatchText(i->first,ServerName))
522 /* A convenient wrapper that returns true if a server exists */
523 bool IsServer(std::string ServerName)
525 return (FindServer(ServerName) != NULL);
528 /* Every SERVER connection inbound or outbound is represented by
529 * an object of type TreeSocket.
530 * TreeSockets, being inherited from InspSocket, can be tied into
531 * the core socket engine, and we cn therefore receive activity events
532 * for them, just like activex objects on speed. (yes really, that
533 * is a technical term!) Each of these which relates to a locally
534 * connected server is assocated with it, by hooking it onto a
535 * TreeSocket class using its constructor. In this way, we can
536 * maintain a list of servers, some of which are directly connected,
537 * some of which are not.
540 class TreeSocket : public InspSocket
543 std::string in_buffer;
544 ServerState LinkState;
545 std::string InboundServerName;
546 std::string InboundDescription;
548 int num_lost_servers;
550 bool LastPingWasGood;
554 unsigned int keylength;
558 /* Because most of the I/O gubbins are encapsulated within
559 * InspSocket, we just call the superclass constructor for
560 * most of the action, and append a few of our own values
563 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
564 : InspSocket(host, port, listening, maxtime)
567 this->LinkState = LISTENER;
569 this->ctx_out = NULL;
572 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
573 : InspSocket(host, port, listening, maxtime)
576 this->LinkState = CONNECTING;
578 this->ctx_out = NULL;
581 /* When a listening socket gives us a new file descriptor,
582 * we must associate it with a socket without creating a new
583 * connection. This constructor is used for this purpose.
585 TreeSocket(int newfd, char* ip)
586 : InspSocket(newfd, ip)
588 this->LinkState = WAIT_AUTH_1;
590 this->ctx_out = NULL;
591 this->SendCapabilities();
602 void InitAES(std::string key,std::string SName)
609 log(DEBUG,"Initialized AES key %s",key.c_str());
610 // key must be 16, 24, 32 etc bytes (multiple of 8)
611 keylength = key.length();
612 if (!(keylength == 16 || keylength == 24 || keylength == 32))
614 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
615 log(DEBUG,"Key length not 16, 24 or 32 characters!");
619 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
620 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\
621 \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);
622 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\
623 \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);
627 /* When an outbound connection finishes connecting, we receive
628 * this event, and must send our SERVER string to the other
629 * side. If the other side is happy, as outlined in the server
630 * to server docs on the inspircd.org site, the other side
631 * will then send back its own server string.
633 virtual bool OnConnected()
635 if (this->LinkState == CONNECTING)
637 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
638 /* we do not need to change state here. */
639 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
641 if (x->Name == this->myhost)
643 this->SendCapabilities();
644 if (x->EncryptionKey != "")
646 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
648 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
652 this->WriteLine("AES "+Srv->GetServerName());
653 this->InitAES(x->EncryptionKey,x->Name);
656 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
657 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
662 /* There is a (remote) chance that between the /CONNECT and the connection
663 * being accepted, some muppet has removed the <link> block and rehashed.
664 * If that happens the connection hangs here until it's closed. Unlikely
665 * and rather harmless.
670 virtual void OnError(InspSocketError e)
672 /* We don't handle this method, because all our
673 * dirty work is done in OnClose() (see below)
674 * which is still called on error conditions too.
678 virtual int OnDisconnect()
680 /* For the same reason as above, we don't
681 * handle OnDisconnect()
686 /* Recursively send the server tree with distances as hops.
687 * This is used during network burst to inform the other server
688 * (and any of ITS servers too) of what servers we know about.
689 * If at any point any of these servers already exist on the other
690 * end, our connection may be terminated. The hopcounts given
691 * by this function are relative, this doesn't matter so long as
692 * they are all >1, as all the remote servers re-calculate them
693 * to be relative too, with themselves as hop 0.
695 void SendServers(TreeServer* Current, TreeServer* s, int hops)
698 for (unsigned int q = 0; q < Current->ChildCount(); q++)
700 TreeServer* recursive_server = Current->GetChild(q);
701 if (recursive_server != s)
703 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
704 this->WriteLine(command);
705 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
706 /* down to next level */
707 this->SendServers(recursive_server, s, hops+1);
712 std::string MyCapabilities()
714 ServerConfig* Config = Srv->GetConfig();
715 std::vector<std::string> modlist;
716 std::string capabilities = "";
718 for (int i = 0; i <= MODCOUNT; i++)
720 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
721 modlist.push_back(Config->module_names[i]);
723 sort(modlist.begin(),modlist.end());
724 for (unsigned int i = 0; i < modlist.size(); i++)
727 capabilities = capabilities + ",";
728 capabilities = capabilities + modlist[i];
733 void SendCapabilities()
735 this->WriteLine("CAPAB "+MyCapabilities());
738 bool Capab(std::deque<std::string> params)
740 if (params.size() != 1)
742 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
745 if (params[0] != this->MyCapabilities())
747 std::string quitserver = this->myhost;
748 if (this->InboundServerName != "")
750 quitserver = this->InboundServerName;
752 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
753 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
754 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
755 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
756 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
762 /* This function forces this server to quit, removing this server
763 * and any users on it (and servers and users below that, etc etc).
764 * It's very slow and pretty clunky, but luckily unless your network
765 * is having a REAL bad hair day, this function shouldnt be called
766 * too many times a month ;-)
768 void SquitServer(TreeServer* Current, CullList* Goners)
770 /* recursively squit the servers attached to 'Current'.
771 * We're going backwards so we don't remove users
772 * while we still need them ;)
774 for (unsigned int q = 0; q < Current->ChildCount(); q++)
776 TreeServer* recursive_server = Current->GetChild(q);
777 this->SquitServer(recursive_server,Goners);
779 /* Now we've whacked the kids, whack self */
781 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
783 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
785 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
786 Goners->AddItem(u->second,qreason);
792 /* This is a wrapper function for SquitServer above, which
793 * does some validation first and passes on the SQUIT to all
794 * other remaining servers.
796 void Squit(TreeServer* Current,std::string reason)
798 if ((Current) && (Current != TreeRoot))
800 std::deque<std::string> params;
801 params.push_back(Current->GetName());
802 params.push_back(":"+reason);
803 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
804 if (Current->GetParent() == TreeRoot)
806 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
810 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
812 num_lost_servers = 0;
814 CullList* Goners = new CullList();
815 SquitServer(Current, Goners);
818 Current->GetParent()->DelChild(Current);
821 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
825 log(DEFAULT,"Squit from unknown server");
830 bool ForceMode(std::string source, std::deque<std::string> params)
832 userrec* who = new userrec;
833 who->fd = FD_MAGIC_NUMBER;
834 if (params.size() < 2)
837 for (unsigned int q = 0; q < params.size(); q++)
839 modelist[q] = (char*)params[q].c_str();
841 Srv->SendMode(modelist,params.size(),who);
842 DoOneToAllButSender(source,"FMODE",params,source);
848 bool ForceTopic(std::string source, std::deque<std::string> params)
850 if (params.size() != 4)
852 std::string channel = params[0];
853 time_t ts = atoi(params[1].c_str());
854 std::string setby = params[2];
855 std::string topic = params[3];
857 chanrec* c = Srv->FindChannel(channel);
860 if ((ts >= c->topicset) || (!*c->topic))
862 std::string oldtopic = c->topic;
863 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
864 strlcpy(c->setby,setby.c_str(),NICKMAX);
866 /* if the topic text is the same as the current topic,
867 * dont bother to send the TOPIC command out, just silently
868 * update the set time and set nick.
870 if (oldtopic != topic)
871 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
876 /* all done, send it on its way */
877 params[3] = ":" + params[3];
878 DoOneToAllButSender(source,"FTOPIC",params,source);
883 /* FJOIN, similar to unreal SJOIN */
884 bool ForceJoin(std::string source, std::deque<std::string> params)
886 if (params.size() < 3)
890 char modestring[MAXBUF];
891 char* mode_users[127];
892 mode_users[0] = first;
893 mode_users[1] = modestring;
894 strcpy(mode_users[1],"+");
895 unsigned int modectr = 2;
898 std::string channel = params[0];
899 time_t TS = atoi(params[1].c_str());
902 chanrec* chan = Srv->FindChannel(channel);
907 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
909 /* default is a high value, which if we dont have this
910 * channel will let the other side apply their modes.
912 time_t ourTS = time(NULL)+600;
913 chanrec* us = Srv->FindChannel(channel);
919 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
921 /* do this first, so our mode reversals are correctly received by other servers
922 * if there is a TS collision.
924 DoOneToAllButSender(source,"FJOIN",params,source);
926 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
928 /* process one channel at a time, applying modes. */
929 char* usr = (char*)params[usernum].c_str();
930 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
931 * (is this even possible?) */
934 char permissions = *usr;
939 mode_users[modectr++] = usr;
940 strlcat(modestring,"o",MAXBUF);
944 mode_users[modectr++] = usr;
945 strlcat(modestring,"h",MAXBUF);
949 mode_users[modectr++] = usr;
950 strlcat(modestring,"v",MAXBUF);
953 who = Srv->FindNick(usr);
956 Srv->JoinUserToChannel(who,channel,key);
957 if (modectr >= (MAXMODES-1))
959 /* theres a mode for this user. push them onto the mode queue, and flush it
960 * if there are more than MAXMODES to go.
962 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
964 /* We also always let u-lined clients win, no matter what the TS value */
965 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
966 Srv->SendMode(mode_users,modectr,who);
970 log(DEBUG,"Their channel newer than ours, bouncing their modes");
972 std::deque<std::string> params;
973 /* modes are now being UNSET... */
974 *mode_users[1] = '-';
975 for (unsigned int x = 0; x < modectr; x++)
977 params.push_back(mode_users[x]);
979 // tell everyone to bounce the modes. bad modes, bad!
980 DoOneToMany(Srv->GetServerName(),"FMODE",params);
982 strcpy(mode_users[1],"+");
988 /* there werent enough modes built up to flush it during FJOIN,
989 * or, there are a number left over. flush them out.
991 if ((modectr > 2) && (who))
995 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
996 Srv->SendMode(mode_users,modectr,who);
1000 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1001 std::deque<std::string> params;
1002 *mode_users[1] = '-';
1003 for (unsigned int x = 0; x < modectr; x++)
1005 params.push_back(mode_users[x]);
1007 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1014 bool IntroduceClient(std::string source, std::deque<std::string> params)
1016 if (params.size() < 8)
1018 // NICK age nick host dhost ident +modes ip :gecos
1020 std::string nick = params[1];
1021 std::string host = params[2];
1022 std::string dhost = params[3];
1023 std::string ident = params[4];
1024 time_t age = atoi(params[0].c_str());
1025 std::string modes = params[5];
1026 while (*(modes.c_str()) == '+')
1028 char* m = (char*)modes.c_str();
1032 std::string ip = params[6];
1033 std::string gecos = params[7];
1034 char* tempnick = (char*)nick.c_str();
1035 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1037 user_hash::iterator iter;
1038 iter = clientlist.find(tempnick);
1039 if (iter != clientlist.end())
1042 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);
1043 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1047 clientlist[tempnick] = new userrec();
1048 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1049 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1050 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1051 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1052 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1053 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1054 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1055 clientlist[tempnick]->registered = 7;
1056 clientlist[tempnick]->signon = age;
1057 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1058 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1063 for (int i = 0; i < MAXCHANS; i++)
1064 clientlist[tempnick]->chans.push_back(a);
1066 if (!this->bursting)
1068 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1070 params[7] = ":" + params[7];
1071 DoOneToAllButSender(source,"NICK",params,source);
1073 // Increment the Source Servers User Count..
1074 TreeServer* SourceServer = FindServer(source);
1076 SourceServer->AddUserCount();
1082 /* Send one or more FJOINs for a channel of users.
1083 * If the length of a single line is more than 480-NICKMAX
1084 * in length, it is split over multiple lines.
1086 void SendFJoins(TreeServer* Current, chanrec* c)
1088 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1090 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1091 std::map<char*,char*> *ulist = c->GetUsers();
1092 for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
1094 char* o = i->second;
1095 userrec* otheruser = (userrec*)o;
1096 strlcat(list," ",MAXBUF);
1097 strlcat(list,cmode(otheruser,c),MAXBUF);
1098 strlcat(list,otheruser->nick,MAXBUF);
1099 if (strlen(list)>(480-NICKMAX))
1101 log(DEBUG,"FJOIN line wrapped");
1102 this->WriteLine(list);
1103 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1106 if (list[strlen(list)-1] != ':')
1108 log(DEBUG,"Final FJOIN line");
1109 this->WriteLine(list);
1113 /* Send G, Q, Z and E lines */
1114 void SendXLines(TreeServer* Current)
1117 /* Yes, these arent too nice looking, but they get the job done */
1118 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1120 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);
1121 this->WriteLine(data);
1123 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1125 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);
1126 this->WriteLine(data);
1128 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1130 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);
1131 this->WriteLine(data);
1133 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1135 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);
1136 this->WriteLine(data);
1138 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1140 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);
1141 this->WriteLine(data);
1143 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1145 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);
1146 this->WriteLine(data);
1148 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1150 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);
1151 this->WriteLine(data);
1153 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1155 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);
1156 this->WriteLine(data);
1160 /* Send channel modes and topics */
1161 void SendChannelModes(TreeServer* Current)
1164 std::deque<std::string> list;
1165 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1167 SendFJoins(Current, c->second);
1168 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1169 this->WriteLine(data);
1170 if (*c->second->topic)
1172 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);
1173 this->WriteLine(data);
1175 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1177 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1178 this->WriteLine(data);
1180 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1182 c->second->GetExtList(list);
1183 for (unsigned int j = 0; j < list.size(); j++)
1185 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1190 /* send all users and their oper state/modes */
1191 void SendUsers(TreeServer* Current)
1194 std::deque<std::string> list;
1195 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1197 if (u->second->registered == 7)
1199 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);
1200 this->WriteLine(data);
1201 if (strchr(u->second->modes,'o'))
1203 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1205 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1207 u->second->GetExtList(list);
1208 for (unsigned int j = 0; j < list.size(); j++)
1210 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1216 /* This function is called when we want to send a netburst to a local
1217 * server. There is a set order we must do this, because for example
1218 * users require their servers to exist, and channels require their
1219 * users to exist. You get the idea.
1221 void DoBurst(TreeServer* s)
1223 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1224 this->WriteLine("BURST");
1225 /* send our version string */
1226 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1227 /* Send server tree */
1228 this->SendServers(TreeRoot,s,1);
1229 /* Send users and their oper status */
1231 /* Send everything else (channel modes, xlines etc) */
1232 this->SendChannelModes(s);
1233 this->SendXLines(s);
1234 this->WriteLine("ENDBURST");
1235 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1238 /* This function is called when we receive data from a remote
1239 * server. We buffer the data in a std::string (it doesnt stay
1240 * there for long), reading using InspSocket::Read() which can
1241 * read up to 16 kilobytes in one operation.
1243 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1244 * THE SOCKET OBJECT FOR US.
1246 virtual bool OnDataReady()
1248 char* data = this->Read();
1251 this->in_buffer += data;
1252 /* While there is at least one new line in the buffer,
1253 * do something useful (we hope!) with it.
1255 while (in_buffer.find("\n") != std::string::npos)
1257 char* line = (char*)in_buffer.c_str();
1258 std::string ret = "";
1259 while ((*line != '\n') && (strlen(line)))
1261 if ((*line != '\r') && (*line != '\n'))
1265 if ((*line == '\n') || (*line == '\r'))
1268 /* Process this one, abort if it
1269 * didnt return true.
1275 memset(result,0,1024);
1277 log(DEBUG,"Original string '%s'",ret.c_str());
1278 /* ERROR + CAPAB is still allowed unencryped */
1279 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1281 int nbytes = from64tobits(out, ret.c_str(), 1024);
1282 if ((nbytes > 0) && (nbytes < 1024))
1284 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1285 ctx_in->Decrypt(out, result, nbytes, 1);
1286 for (int t = 0; t < nbytes; t++)
1287 if (result[t] == '\7') result[t] = 0;
1292 if (!this->ProcessLine(ret))
1298 return (data != NULL);
1301 int WriteLine(std::string line)
1303 log(DEBUG,"OUT: %s",line.c_str());
1306 log(DEBUG,"AES context");
1308 char result64[10240];
1309 if (this->keylength)
1311 while (line.length() % this->keylength != 0)
1313 // pad it to be a multiple of the key length
1317 unsigned int ll = line.length();
1318 log(DEBUG,"Plaintext line with padding = %d chars",ll);
1319 ctx_out->Encrypt(line.c_str(), result, ll, 1);
1320 log(DEBUG,"Encrypted.");
1321 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1323 log(DEBUG,"Encrypted: %s",line.c_str());
1324 //int from64tobits(char *out, const char *in, int maxlen);
1326 return this->Write(line + "\r\n");
1329 /* Handle ERROR command */
1330 bool Error(std::deque<std::string> params)
1332 if (params.size() < 1)
1334 std::string Errmsg = params[0];
1335 std::string SName = myhost;
1336 if (InboundServerName != "")
1338 SName = InboundServerName;
1340 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1341 /* we will return false to cause the socket to close.
1346 /* Because the core won't let users or even SERVERS set +o,
1347 * we use the OPERTYPE command to do this.
1349 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1351 if (params.size() != 1)
1353 std::string opertype = params[0];
1354 userrec* u = Srv->FindNick(prefix);
1357 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1358 if (!strchr(u->modes,'o'))
1360 strcat(u->modes,"o");
1362 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1367 /* Because Andy insists that services-compatible servers must
1368 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1370 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1372 if (params.size() < 3)
1374 userrec* u = Srv->FindNick(params[0]);
1377 Srv->ChangeUserNick(u,params[1]);
1378 u->age = atoi(params[2].c_str());
1379 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1384 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1386 if (params.size() < 2)
1388 userrec* u = Srv->FindNick(params[0]);
1391 Srv->JoinUserToChannel(u,params[1],"");
1392 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1397 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1399 if (params.size() < 1)
1401 std::string servermask = params[0];
1402 if (Srv->MatchText(Srv->GetServerName(),servermask))
1404 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1405 Srv->RehashServer();
1406 ReadConfiguration(false);
1408 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1412 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1414 if (params.size() != 2)
1416 std::string nick = params[0];
1417 userrec* u = Srv->FindNick(prefix);
1418 userrec* who = Srv->FindNick(nick);
1421 /* Prepend kill source, if we don't have one */
1422 std::string sourceserv = prefix;
1425 sourceserv = u->server;
1427 if (*(params[1].c_str()) != '[')
1429 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1431 std::string reason = params[1];
1432 params[1] = ":" + params[1];
1433 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1434 Srv->QuitUser(who,reason);
1439 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1441 if (params.size() < 1)
1443 TreeServer* ServerSource = FindServer(prefix);
1446 ServerSource->SetPingFlag();
1451 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1453 if (params.size() < 3)
1455 TreeServer* ServerSource = FindServer(prefix);
1458 if (*(params[0].c_str()) == '#')
1460 chanrec* c = Srv->FindChannel(params[0]);
1463 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1468 userrec* u = Srv->FindNick(params[0]);
1471 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1475 params[2] = ":" + params[2];
1476 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1480 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1482 if (params.size() < 1)
1484 TreeServer* ServerSource = FindServer(prefix);
1487 ServerSource->SetVersion(params[0]);
1489 params[0] = ":" + params[0];
1490 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1494 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1496 if (params.size() < 1)
1498 userrec* u = Srv->FindNick(prefix);
1501 Srv->ChangeHost(u,params[0]);
1502 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1507 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1509 if (params.size() < 6)
1511 std::string linetype = params[0]; /* Z, Q, E, G, K */
1512 std::string mask = params[1]; /* Line type dependent */
1513 std::string source = params[2]; /* may not be online or may be a server */
1514 std::string settime = params[3]; /* EPOCH time set */
1515 std::string duration = params[4]; /* Duration secs */
1516 std::string reason = params[5];
1518 switch (*(linetype.c_str()))
1521 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1522 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1525 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1526 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1529 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1530 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1533 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1534 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1537 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1540 /* Just in case... */
1541 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1544 /* Send it on its way */
1545 params[5] = ":" + params[5];
1546 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1550 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1552 if (params.size() < 1)
1554 userrec* u = Srv->FindNick(prefix);
1557 Srv->ChangeGECOS(u,params[0]);
1558 params[0] = ":" + params[0];
1559 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1564 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1566 if (params.size() < 1)
1568 log(DEBUG,"In IDLE command");
1569 userrec* u = Srv->FindNick(prefix);
1572 log(DEBUG,"USER EXISTS: %s",u->nick);
1573 // an incoming request
1574 if (params.size() == 1)
1576 userrec* x = Srv->FindNick(params[0]);
1577 if ((x) && (x->fd > -1))
1579 userrec* x = Srv->FindNick(params[0]);
1580 log(DEBUG,"Got IDLE");
1581 char signon[MAXBUF];
1583 log(DEBUG,"Sending back IDLE 3");
1584 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1585 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1586 std::deque<std::string> par;
1587 par.push_back(prefix);
1588 par.push_back(signon);
1589 par.push_back(idle);
1590 // ours, we're done, pass it BACK
1591 DoOneToOne(params[0],"IDLE",par,u->server);
1595 // not ours pass it on
1596 DoOneToOne(prefix,"IDLE",params,x->server);
1599 else if (params.size() == 3)
1601 std::string who_did_the_whois = params[0];
1602 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1603 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1605 log(DEBUG,"Got final IDLE");
1606 // an incoming reply to a whois we sent out
1607 std::string nick_whoised = prefix;
1608 unsigned long signon = atoi(params[1].c_str());
1609 unsigned long idle = atoi(params[2].c_str());
1610 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1611 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1615 // not ours, pass it on
1616 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1623 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1625 if (params.size() < 1)
1627 std::string stufftobounce = params[0];
1628 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1632 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1634 if (params.size() < 4)
1636 std::string servername = params[0];
1637 std::string password = params[1];
1638 // hopcount is not used for a remote server, we calculate this ourselves
1639 std::string description = params[3];
1640 TreeServer* ParentOfThis = FindServer(prefix);
1643 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1646 TreeServer* CheckDupe = FindServer(servername);
1649 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1650 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1653 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1654 ParentOfThis->AddChild(Node);
1655 params[3] = ":" + params[3];
1656 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1657 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1661 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1663 if (params.size() < 4)
1665 std::string servername = params[0];
1666 std::string password = params[1];
1667 int hops = atoi(params[2].c_str());
1670 this->WriteLine("ERROR :Server too far away for authentication");
1671 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1674 std::string description = params[3];
1675 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1677 if ((x->Name == servername) && (x->RecvPass == password))
1679 TreeServer* CheckDupe = FindServer(servername);
1682 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1683 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1686 // Begin the sync here. this kickstarts the
1687 // other side, waiting in WAIT_AUTH_2 state,
1688 // into starting their burst, as it shows
1689 // that we're happy.
1690 this->LinkState = CONNECTED;
1691 // we should add the details of this server now
1692 // to the servers tree, as a child of the root
1694 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1695 TreeRoot->AddChild(Node);
1696 params[3] = ":" + params[3];
1697 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1698 this->bursting = true;
1699 this->DoBurst(Node);
1703 this->WriteLine("ERROR :Invalid credentials");
1704 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1708 bool Inbound_Server(std::deque<std::string> ¶ms)
1710 if (params.size() < 4)
1712 std::string servername = params[0];
1713 std::string password = params[1];
1714 int hops = atoi(params[2].c_str());
1717 this->WriteLine("ERROR :Server too far away for authentication");
1718 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1721 std::string description = params[3];
1722 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1724 if ((x->Name == servername) && (x->RecvPass == password))
1726 TreeServer* CheckDupe = FindServer(servername);
1729 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1730 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1733 /* If the config says this link is encrypted, but the remote side
1734 * hasnt bothered to send the AES command before SERVER, then we
1735 * boot them off as we MUST have this connection encrypted.
1737 if ((x->EncryptionKey != "") && (!this->ctx_in))
1739 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1740 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1743 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1744 this->InboundServerName = servername;
1745 this->InboundDescription = description;
1746 // this is good. Send our details: Our server name and description and hopcount of 0,
1747 // along with the sendpass from this block.
1748 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1749 // move to the next state, we are now waiting for THEM.
1750 this->LinkState = WAIT_AUTH_2;
1754 this->WriteLine("ERROR :Invalid credentials");
1755 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1759 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1761 if (!strchr(line.c_str(),' '))
1766 std::stringstream s(line);
1767 std::string param = "";
1786 if ((param == ":") && (item > 0))
1809 bool ProcessLine(std::string line)
1811 char* l = (char*)line.c_str();
1812 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1813 l[strlen(l)-1] = '\0';
1817 Srv->Log(DEBUG,"IN: "+line);
1819 std::deque<std::string> params;
1820 this->Split(line,true,params);
1821 std::string command = "";
1822 std::string prefix = "";
1823 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1826 command = params[1];
1827 char* pref = (char*)prefix.c_str();
1835 command = params[0];
1839 if ((!this->ctx_in) && (command == "AES"))
1841 std::string sserv = params[0];
1842 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1844 if ((x->EncryptionKey != "") && (x->Name == sserv))
1846 this->InitAES(x->EncryptionKey,sserv);
1851 else if ((this->ctx_in) && (command == "AES"))
1853 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1856 switch (this->LinkState)
1861 // Waiting for SERVER command from remote server. Server initiating
1862 // the connection sends the first SERVER command, listening server
1863 // replies with theirs if its happy, then if the initiator is happy,
1864 // it starts to send its net sync, which starts the merge, otherwise
1865 // it sends an ERROR.
1866 if (command == "PASS")
1868 /* Silently ignored */
1870 else if (command == "SERVER")
1872 return this->Inbound_Server(params);
1874 else if (command == "ERROR")
1876 return this->Error(params);
1878 else if (command == "USER")
1880 this->WriteLine("ERROR :Client connections to this port are prohibited.");
1883 else if (command == "CAPAB")
1885 return this->Capab(params);
1887 else if ((command == "U") || (command == "S"))
1889 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1894 this->WriteLine("ERROR :Invalid command in negotiation phase.");
1899 // Waiting for start of other side's netmerge to say they liked our
1901 if (command == "SERVER")
1903 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1907 else if ((command == "U") || (command == "S"))
1909 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1912 else if (command == "BURST")
1914 this->LinkState = CONNECTED;
1915 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1916 TreeRoot->AddChild(Node);
1918 params.push_back(InboundServerName);
1919 params.push_back("*");
1920 params.push_back("1");
1921 params.push_back(":"+InboundDescription);
1922 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1923 this->bursting = true;
1924 this->DoBurst(Node);
1926 else if (command == "ERROR")
1928 return this->Error(params);
1930 else if (command == "CAPAB")
1932 return this->Capab(params);
1937 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1941 if (command == "SERVER")
1943 // another server we connected to, which was in WAIT_AUTH_1 state,
1944 // has just sent us their credentials. If we get this far, theyre
1945 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1946 // if we're happy with this, we should send our netburst which
1947 // kickstarts the merge.
1948 return this->Outbound_Reply_Server(params);
1950 else if (command == "ERROR")
1952 return this->Error(params);
1956 // This is the 'authenticated' state, when all passwords
1957 // have been exchanged and anything past this point is taken
1962 std::string direction = prefix;
1963 userrec* t = Srv->FindNick(prefix);
1966 direction = t->server;
1968 TreeServer* route_back_again = BestRouteTo(direction);
1969 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1971 if (route_back_again)
1972 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1977 * When there is activity on the socket, reset the ping counter so
1978 * that we're not wasting bandwidth pinging an active server.
1980 route_back_again->SetNextPingTime(time(NULL) + 300);
1981 route_back_again->SetPingFlag();
1984 if (command == "SVSMODE")
1986 /* Services expects us to implement
1987 * SVSMODE. In inspircd its the same as
1992 std::string target = "";
1993 /* Yes, know, this is a mess. Its reasonably fast though as we're
1994 * working with std::string here.
1996 if ((command == "NICK") && (params.size() > 1))
1998 return this->IntroduceClient(prefix,params);
2000 else if (command == "FJOIN")
2002 return this->ForceJoin(prefix,params);
2004 else if (command == "SERVER")
2006 return this->RemoteServer(prefix,params);
2008 else if (command == "ERROR")
2010 return this->Error(params);
2012 else if (command == "OPERTYPE")
2014 return this->OperType(prefix,params);
2016 else if (command == "FMODE")
2018 return this->ForceMode(prefix,params);
2020 else if (command == "KILL")
2022 return this->RemoteKill(prefix,params);
2024 else if (command == "FTOPIC")
2026 return this->ForceTopic(prefix,params);
2028 else if (command == "REHASH")
2030 return this->RemoteRehash(prefix,params);
2032 else if (command == "METADATA")
2034 return this->MetaData(prefix,params);
2036 else if (command == "PING")
2038 return this->LocalPing(prefix,params);
2040 else if (command == "PONG")
2042 return this->LocalPong(prefix,params);
2044 else if (command == "VERSION")
2046 return this->ServerVersion(prefix,params);
2048 else if (command == "FHOST")
2050 return this->ChangeHost(prefix,params);
2052 else if (command == "FNAME")
2054 return this->ChangeName(prefix,params);
2056 else if (command == "ADDLINE")
2058 return this->AddLine(prefix,params);
2060 else if (command == "SVSNICK")
2064 prefix = this->GetName();
2066 return this->ForceNick(prefix,params);
2068 else if (command == "IDLE")
2070 return this->Whois(prefix,params);
2072 else if (command == "SVSJOIN")
2076 prefix = this->GetName();
2078 return this->ServiceJoin(prefix,params);
2080 else if (command == "SQUIT")
2082 if (params.size() == 2)
2084 this->Squit(FindServer(params[0]),params[1]);
2088 else if (command == "ENDBURST")
2090 this->bursting = false;
2095 // not a special inter-server command.
2096 // Emulate the actual user doing the command,
2097 // this saves us having a huge ugly parser.
2098 userrec* who = Srv->FindNick(prefix);
2099 std::string sourceserv = this->myhost;
2100 if (this->InboundServerName != "")
2102 sourceserv = this->InboundServerName;
2107 target = who->server;
2108 char* strparams[127];
2109 for (unsigned int q = 0; q < params.size(); q++)
2111 strparams[q] = (char*)params[q].c_str();
2113 Srv->CallCommandHandler(command, strparams, params.size(), who);
2117 // its not a user. Its either a server, or somethings screwed up.
2118 if (IsServer(prefix))
2120 target = Srv->GetServerName();
2124 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2128 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2137 virtual std::string GetName()
2139 std::string sourceserv = this->myhost;
2140 if (this->InboundServerName != "")
2142 sourceserv = this->InboundServerName;
2147 virtual void OnTimeout()
2149 if (this->LinkState == CONNECTING)
2151 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2155 virtual void OnClose()
2157 // Connection closed.
2158 // If the connection is fully up (state CONNECTED)
2159 // then propogate a netsplit to all peers.
2160 std::string quitserver = this->myhost;
2161 if (this->InboundServerName != "")
2163 quitserver = this->InboundServerName;
2165 TreeServer* s = FindServer(quitserver);
2168 Squit(s,"Remote host closed the connection");
2170 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2173 virtual int OnIncomingConnection(int newsock, char* ip)
2175 TreeSocket* s = new TreeSocket(newsock, ip);
2181 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2183 for (unsigned int c = 0; c < list.size(); c++)
2185 if (list[c] == server)
2190 list.push_back(server);
2193 // returns a list of DIRECT servernames for a specific channel
2194 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2196 std::map<char*,char*> *ulist = c->GetUsers();
2197 for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
2199 char* o = i->second;
2200 userrec* otheruser = (userrec*)o;
2201 if (otheruser->fd < 0)
2203 TreeServer* best = BestRouteTo(otheruser->server);
2205 AddThisServer(best,list);
2211 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2213 TreeServer* omitroute = BestRouteTo(omit);
2214 if ((command == "NOTICE") || (command == "PRIVMSG"))
2216 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2218 if (*(params[0].c_str()) != '#')
2220 // special routing for private messages/notices
2221 userrec* d = Srv->FindNick(params[0]);
2224 std::deque<std::string> par;
2225 par.push_back(params[0]);
2226 par.push_back(":"+params[1]);
2227 DoOneToOne(prefix,command,par,d->server);
2233 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2234 chanrec* c = Srv->FindChannel(params[0]);
2237 std::deque<TreeServer*> list;
2238 GetListOfServersForChannel(c,list);
2239 log(DEBUG,"Got a list of %d servers",list.size());
2240 unsigned int lsize = list.size();
2241 for (unsigned int i = 0; i < lsize; i++)
2243 TreeSocket* Sock = list[i]->GetSocket();
2244 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2246 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2247 Sock->WriteLine(data);
2255 unsigned int items = TreeRoot->ChildCount();
2256 for (unsigned int x = 0; x < items; x++)
2258 TreeServer* Route = TreeRoot->GetChild(x);
2259 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2261 TreeSocket* Sock = Route->GetSocket();
2262 Sock->WriteLine(data);
2268 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2270 TreeServer* omitroute = BestRouteTo(omit);
2271 std::string FullLine = ":" + prefix + " " + command;
2272 unsigned int words = params.size();
2273 for (unsigned int x = 0; x < words; x++)
2275 FullLine = FullLine + " " + params[x];
2277 unsigned int items = TreeRoot->ChildCount();
2278 for (unsigned int x = 0; x < items; x++)
2280 TreeServer* Route = TreeRoot->GetChild(x);
2281 // Send the line IF:
2282 // The route has a socket (its a direct connection)
2283 // The route isnt the one to be omitted
2284 // The route isnt the path to the one to be omitted
2285 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2287 TreeSocket* Sock = Route->GetSocket();
2288 Sock->WriteLine(FullLine);
2294 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2296 std::string FullLine = ":" + prefix + " " + command;
2297 unsigned int words = params.size();
2298 for (unsigned int x = 0; x < words; x++)
2300 FullLine = FullLine + " " + params[x];
2302 unsigned int items = TreeRoot->ChildCount();
2303 for (unsigned int x = 0; x < items; x++)
2305 TreeServer* Route = TreeRoot->GetChild(x);
2306 if (Route->GetSocket())
2308 TreeSocket* Sock = Route->GetSocket();
2309 Sock->WriteLine(FullLine);
2315 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2317 TreeServer* Route = BestRouteTo(target);
2320 std::string FullLine = ":" + prefix + " " + command;
2321 unsigned int words = params.size();
2322 for (unsigned int x = 0; x < words; x++)
2324 FullLine = FullLine + " " + params[x];
2326 if (Route->GetSocket())
2328 TreeSocket* Sock = Route->GetSocket();
2329 Sock->WriteLine(FullLine);
2339 std::vector<TreeSocket*> Bindings;
2341 void ReadConfiguration(bool rebind)
2343 Conf = new ConfigReader;
2346 for (int j =0; j < Conf->Enumerate("bind"); j++)
2348 std::string Type = Conf->ReadValue("bind","type",j);
2349 std::string IP = Conf->ReadValue("bind","address",j);
2350 long Port = Conf->ReadInteger("bind","port",j,true);
2351 if (Type == "servers")
2357 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2358 if (listener->GetState() == I_LISTENING)
2360 Srv->AddSocket(listener);
2361 Bindings.push_back(listener);
2365 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2373 for (int j =0; j < Conf->Enumerate("link"); j++)
2376 L.Name = Conf->ReadValue("link","name",j);
2377 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2378 L.Port = Conf->ReadInteger("link","port",j,true);
2379 L.SendPass = Conf->ReadValue("link","sendpass",j);
2380 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2381 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2382 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2383 L.NextConnectTime = time(NULL) + L.AutoConnect;
2384 /* Bugfix by brain, do not allow people to enter bad configurations */
2385 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2387 LinkBlocks.push_back(L);
2388 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2392 if (L.RecvPass == "")
2394 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
2396 else if (L.SendPass == "")
2398 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
2400 else if (L.Name == "")
2402 log(DEFAULT,"Invalid configuration, link tag without a name!");
2406 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
2414 class ModuleSpanningTree : public Module
2416 std::vector<TreeSocket*> Bindings;
2422 ModuleSpanningTree(Server* Me)
2423 : Module::Module(Me)
2428 // Create the root of the tree
2429 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2431 ReadConfiguration(true);
2434 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2436 std::string Parent = TreeRoot->GetName();
2437 if (Current->GetParent())
2439 Parent = Current->GetParent()->GetName();
2441 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2443 ShowLinks(Current->GetChild(q),user,hops+1);
2445 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2448 int CountLocalServs()
2450 return TreeRoot->ChildCount();
2455 return serverlist.size();
2458 void HandleLinks(char** parameters, int pcnt, userrec* user)
2460 ShowLinks(TreeRoot,user,0);
2461 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2465 void HandleLusers(char** parameters, int pcnt, userrec* user)
2467 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2468 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2469 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2470 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2471 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2475 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2477 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2481 for (int t = 0; t < depth; t++)
2483 matrix[line][t] = ' ';
2486 // For Aligning, we need to work out exactly how deep this thing is, and produce
2487 // a 'Spacer' String to compensate.
2490 memset(spacer,' ',40);
2491 if ((40 - Current->GetName().length() - depth) > 1) {
2492 spacer[40 - Current->GetName().length() - depth] = '\0';
2501 if (clientlist.size() == 0) {
2502 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
2507 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
2509 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
2510 strlcpy(&matrix[line][depth],text,80);
2512 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2514 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2519 // Ok, prepare to be confused.
2520 // After much mulling over how to approach this, it struck me that
2521 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2522 // keeping track of a ton of ascii characters, and line by line
2523 // under recursion working out where to place them using multiplications
2524 // and divisons, we instead render the map onto a backplane of characters
2525 // (a character matrix), then draw the branches as a series of "L" shapes
2526 // from the nodes. This is not only friendlier on CPU it uses less stack.
2528 void HandleMap(char** parameters, int pcnt, userrec* user)
2530 // This array represents a virtual screen which we will
2531 // "scratch" draw to, as the console device of an irc
2532 // client does not provide for a proper terminal.
2533 char matrix[128][80];
2534 for (unsigned int t = 0; t < 128; t++)
2536 matrix[t][0] = '\0';
2539 // The only recursive bit is called here.
2540 ShowMap(TreeRoot,user,0,matrix);
2541 // Process each line one by one. The algorithm has a limit of
2542 // 128 servers (which is far more than a spanning tree should have
2543 // anyway, so we're ok). This limit can be raised simply by making
2544 // the character matrix deeper, 128 rows taking 10k of memory.
2545 for (int l = 1; l < line; l++)
2547 // scan across the line looking for the start of the
2548 // servername (the recursive part of the algorithm has placed
2549 // the servers at indented positions depending on what they
2551 int first_nonspace = 0;
2552 while (matrix[l][first_nonspace] == ' ')
2557 // Draw the `- (corner) section: this may be overwritten by
2558 // another L shape passing along the same vertical pane, becoming
2559 // a |- (branch) section instead.
2560 matrix[l][first_nonspace] = '-';
2561 matrix[l][first_nonspace-1] = '`';
2563 // Draw upwards until we hit the parent server, causing possibly
2564 // other corners (`-) to become branches (|-)
2565 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2567 matrix[l2][first_nonspace-1] = '|';
2571 // dump the whole lot to the user. This is the easy bit, honest.
2572 for (int t = 0; t < line; t++)
2574 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2576 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2580 int HandleSquit(char** parameters, int pcnt, userrec* user)
2582 TreeServer* s = FindServerMask(parameters[0]);
2587 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2590 TreeSocket* sock = s->GetSocket();
2593 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2594 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2595 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2600 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2605 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2610 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2612 if ((user->fd > -1) && (pcnt > 1))
2614 userrec* remote = Srv->FindNick(parameters[1]);
2615 if ((remote) && (remote->fd < 0))
2617 std::deque<std::string> params;
2618 params.push_back(parameters[1]);
2619 DoOneToOne(user->nick,"IDLE",params,remote->server);
2624 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2625 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2632 void DoPingChecks(time_t curtime)
2634 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2636 TreeServer* serv = TreeRoot->GetChild(j);
2637 TreeSocket* sock = serv->GetSocket();
2640 if (curtime >= serv->NextPingTime())
2642 if (serv->AnsweredLastPing())
2644 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2645 serv->SetNextPingTime(curtime + 300);
2649 // they didnt answer, boot them
2650 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2651 sock->Squit(serv,"Ping timeout");
2660 void AutoConnectServers(time_t curtime)
2662 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2664 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2666 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2667 x->NextConnectTime = curtime + x->AutoConnect;
2668 TreeServer* CheckDupe = FindServer(x->Name);
2671 // an autoconnected server is not connected. Check if its time to connect it
2672 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2673 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2674 Srv->AddSocket(newsocket);
2680 int HandleVersion(char** parameters, int pcnt, userrec* user)
2682 // we've already checked if pcnt > 0, so this is safe
2683 TreeServer* found = FindServerMask(parameters[0]);
2686 std::string Version = found->GetVersion();
2687 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2688 if (found == TreeRoot)
2690 std::stringstream out(Config->data005);
2691 std::string token = "";
2692 std::string line5 = "";
2693 int token_counter = 0;
2697 line5 = line5 + token + " ";
2699 if ((token_counter >= 13) || (out.eof() == true))
2701 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2710 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2715 int HandleConnect(char** parameters, int pcnt, userrec* user)
2717 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2719 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2721 TreeServer* CheckDupe = FindServer(x->Name);
2724 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);
2725 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2726 Srv->AddSocket(newsocket);
2731 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());
2736 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2740 virtual int OnStats(char statschar, userrec* user)
2742 if (statschar == 'c')
2744 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2746 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %c%c%c",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-'),(LinkBlocks[i].AutoConnect ? 'a' : '-'),'s');
2747 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2749 WriteServ(user->fd,"219 %s %c :End of /STATS report",user->nick,statschar);
2750 WriteOpers("*** Notice: Stats '%c' requested by %s (%s@%s)",statschar,user->nick,user->ident,user->host);
2756 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2758 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2762 if (command == "CONNECT")
2764 return this->HandleConnect(parameters,pcnt,user);
2766 else if (command == "SQUIT")
2768 return this->HandleSquit(parameters,pcnt,user);
2770 else if (command == "MAP")
2772 this->HandleMap(parameters,pcnt,user);
2775 else if (command == "LUSERS")
2777 this->HandleLusers(parameters,pcnt,user);
2780 else if (command == "LINKS")
2782 this->HandleLinks(parameters,pcnt,user);
2785 else if (command == "WHOIS")
2790 return this->HandleRemoteWhois(parameters,pcnt,user);
2793 else if ((command == "VERSION") && (pcnt > 0))
2795 this->HandleVersion(parameters,pcnt,user);
2798 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2800 // this bit of code cleverly routes all module commands
2801 // to all remote severs *automatically* so that modules
2802 // can just handle commands locally, without having
2803 // to have any special provision in place for remote
2804 // commands and linking protocols.
2805 std::deque<std::string> params;
2807 for (int j = 0; j < pcnt; j++)
2809 if (strchr(parameters[j],' '))
2811 params.push_back(":" + std::string(parameters[j]));
2815 params.push_back(std::string(parameters[j]));
2818 DoOneToMany(user->nick,command,params);
2823 virtual void OnGetServerDescription(std::string servername,std::string &description)
2825 TreeServer* s = FindServer(servername);
2828 description = s->GetDesc();
2832 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2834 if (source->fd > -1)
2836 std::deque<std::string> params;
2837 params.push_back(dest->nick);
2838 params.push_back(channel->name);
2839 DoOneToMany(source->nick,"INVITE",params);
2843 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2845 std::deque<std::string> params;
2846 params.push_back(chan->name);
2847 params.push_back(":"+topic);
2848 DoOneToMany(user->nick,"TOPIC",params);
2851 virtual void OnWallops(userrec* user, std::string text)
2855 std::deque<std::string> params;
2856 params.push_back(":"+text);
2857 DoOneToMany(user->nick,"WALLOPS",params);
2861 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2863 if (target_type == TYPE_USER)
2865 userrec* d = (userrec*)dest;
2866 if ((d->fd < 0) && (user->fd > -1))
2868 std::deque<std::string> params;
2870 params.push_back(d->nick);
2871 params.push_back(":"+text);
2872 DoOneToOne(user->nick,"NOTICE",params,d->server);
2879 chanrec *c = (chanrec*)dest;
2880 std::deque<TreeServer*> list;
2881 GetListOfServersForChannel(c,list);
2882 unsigned int ucount = list.size();
2883 for (unsigned int i = 0; i < ucount; i++)
2885 TreeSocket* Sock = list[i]->GetSocket();
2887 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2893 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2895 if (target_type == TYPE_USER)
2897 // route private messages which are targetted at clients only to the server
2898 // which needs to receive them
2899 userrec* d = (userrec*)dest;
2900 if ((d->fd < 0) && (user->fd > -1))
2902 std::deque<std::string> params;
2904 params.push_back(d->nick);
2905 params.push_back(":"+text);
2906 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2913 chanrec *c = (chanrec*)dest;
2914 std::deque<TreeServer*> list;
2915 GetListOfServersForChannel(c,list);
2916 unsigned int ucount = list.size();
2917 for (unsigned int i = 0; i < ucount; i++)
2919 TreeSocket* Sock = list[i]->GetSocket();
2921 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2927 virtual void OnBackgroundTimer(time_t curtime)
2929 AutoConnectServers(curtime);
2930 DoPingChecks(curtime);
2933 virtual void OnUserJoin(userrec* user, chanrec* channel)
2935 // Only do this for local users
2938 std::deque<std::string> params;
2940 params.push_back(channel->name);
2943 // if the channel has a key, force the join by emulating the key.
2944 params.push_back(channel->key);
2946 if (channel->GetUserCounter() > 1)
2948 // not the first in the channel
2949 DoOneToMany(user->nick,"JOIN",params);
2953 // first in the channel, set up their permissions
2954 // and the channel TS with FJOIN.
2956 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2958 params.push_back(channel->name);
2959 params.push_back(ts);
2960 params.push_back("@"+std::string(user->nick));
2961 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2966 virtual void OnChangeHost(userrec* user, std::string newhost)
2968 // only occurs for local clients
2969 if (user->registered != 7)
2971 std::deque<std::string> params;
2972 params.push_back(newhost);
2973 DoOneToMany(user->nick,"FHOST",params);
2976 virtual void OnChangeName(userrec* user, std::string gecos)
2978 // only occurs for local clients
2979 if (user->registered != 7)
2981 std::deque<std::string> params;
2982 params.push_back(gecos);
2983 DoOneToMany(user->nick,"FNAME",params);
2986 virtual void OnUserPart(userrec* user, chanrec* channel)
2990 std::deque<std::string> params;
2991 params.push_back(channel->name);
2992 DoOneToMany(user->nick,"PART",params);
2996 virtual void OnUserConnect(userrec* user)
2998 char agestr[MAXBUF];
3001 std::deque<std::string> params;
3002 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
3003 params.push_back(agestr);
3004 params.push_back(user->nick);
3005 params.push_back(user->host);
3006 params.push_back(user->dhost);
3007 params.push_back(user->ident);
3008 params.push_back("+"+std::string(user->modes));
3009 params.push_back(user->ip);
3010 params.push_back(":"+std::string(user->fullname));
3011 DoOneToMany(Srv->GetServerName(),"NICK",params);
3013 // User is Local, change needs to be reflected!
3014 TreeServer* SourceServer = FindServer(user->server);
3016 SourceServer->AddUserCount();
3022 virtual void OnUserQuit(userrec* user, std::string reason)
3024 if ((user->fd > -1) && (user->registered == 7))
3026 std::deque<std::string> params;
3027 params.push_back(":"+reason);
3028 DoOneToMany(user->nick,"QUIT",params);
3030 // Regardless, We need to modify the user Counts..
3031 TreeServer* SourceServer = FindServer(user->server);
3033 SourceServer->DelUserCount();
3038 virtual void OnUserPostNick(userrec* user, std::string oldnick)
3042 std::deque<std::string> params;
3043 params.push_back(user->nick);
3044 DoOneToMany(oldnick,"NICK",params);
3048 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
3050 if (source->fd > -1)
3052 std::deque<std::string> params;
3053 params.push_back(chan->name);
3054 params.push_back(user->nick);
3055 params.push_back(":"+reason);
3056 DoOneToMany(source->nick,"KICK",params);
3060 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
3062 std::deque<std::string> params;
3063 params.push_back(dest->nick);
3064 params.push_back(":"+reason);
3065 DoOneToMany(source->nick,"KILL",params);
3068 virtual void OnRehash(std::string parameter)
3070 if (parameter != "")
3072 std::deque<std::string> params;
3073 params.push_back(parameter);
3074 DoOneToMany(Srv->GetServerName(),"REHASH",params);
3076 if (Srv->MatchText(Srv->GetServerName(),parameter))
3078 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
3079 Srv->RehashServer();
3082 ReadConfiguration(false);
3085 // note: the protocol does not allow direct umode +o except
3086 // via NICK with 8 params. sending OPERTYPE infers +o modechange
3088 virtual void OnOper(userrec* user, std::string opertype)
3092 std::deque<std::string> params;
3093 params.push_back(opertype);
3094 DoOneToMany(user->nick,"OPERTYPE",params);
3098 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
3100 if (source->fd > -1)
3103 snprintf(type,8,"%cLINE",linetype);
3104 std::string stype = type;
3107 char sduration[MAXBUF];
3108 snprintf(sduration,MAXBUF,"%ld",duration);
3109 std::deque<std::string> params;
3110 params.push_back(host);
3111 params.push_back(sduration);
3112 params.push_back(":"+reason);
3113 DoOneToMany(source->nick,stype,params);
3117 std::deque<std::string> params;
3118 params.push_back(host);
3119 DoOneToMany(source->nick,stype,params);
3124 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3126 OnLine(source,hostmask,true,'G',duration,reason);
3129 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3131 OnLine(source,ipmask,true,'Z',duration,reason);
3134 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3136 OnLine(source,nickmask,true,'Q',duration,reason);
3139 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3141 OnLine(source,hostmask,true,'E',duration,reason);
3144 virtual void OnDelGLine(userrec* source, std::string hostmask)
3146 OnLine(source,hostmask,false,'G',0,"");
3149 virtual void OnDelZLine(userrec* source, std::string ipmask)
3151 OnLine(source,ipmask,false,'Z',0,"");
3154 virtual void OnDelQLine(userrec* source, std::string nickmask)
3156 OnLine(source,nickmask,false,'Q',0,"");
3159 virtual void OnDelELine(userrec* source, std::string hostmask)
3161 OnLine(source,hostmask,false,'E',0,"");
3164 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3166 if ((user->fd > -1) && (user->registered == 7))
3168 if (target_type == TYPE_USER)
3170 userrec* u = (userrec*)dest;
3171 std::deque<std::string> params;
3172 params.push_back(u->nick);
3173 params.push_back(text);
3174 DoOneToMany(user->nick,"MODE",params);
3178 chanrec* c = (chanrec*)dest;
3179 std::deque<std::string> params;
3180 params.push_back(c->name);
3181 params.push_back(text);
3182 DoOneToMany(user->nick,"MODE",params);
3187 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3189 TreeSocket* s = (TreeSocket*)opaque;
3192 if (target_type == TYPE_USER)
3194 userrec* u = (userrec*)target;
3195 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3199 chanrec* c = (chanrec*)target;
3200 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3205 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3207 TreeSocket* s = (TreeSocket*)opaque;
3210 if (target_type == TYPE_USER)
3212 userrec* u = (userrec*)target;
3213 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3217 chanrec* c = (chanrec*)target;
3218 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3223 virtual ~ModuleSpanningTree()
3227 virtual Version GetVersion()
3229 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3232 void Implements(char* List)
3234 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3235 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3236 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3237 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3238 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3239 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3240 List[I_OnStats] = List[I_ProtoSendMetaData] = 1;
3243 /* It is IMPORTANT that m_spanningtree is the last module in the chain
3244 * so that any activity it sees is FINAL, e.g. we arent going to send out
3245 * a NICK message before m_cloaking has finished putting the +x on the user,
3247 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
3248 * the module call queue.
3250 Priority Prioritize()
3252 return PRIORITY_LAST;
3257 class ModuleSpanningTreeFactory : public ModuleFactory
3260 ModuleSpanningTreeFactory()
3264 ~ModuleSpanningTreeFactory()
3268 virtual Module * CreateModule(Server* Me)
3270 TreeProtocolModule = new ModuleSpanningTree(Me);
3271 return TreeProtocolModule;
3277 extern "C" void * init_module( void )
3279 return new ModuleSpanningTreeFactory;