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 std::vector<Module*> modules;
77 extern std::vector<ircd_module*> factory;
80 /* Any socket can have one of five states at any one time.
81 * The LISTENER state indicates a socket which is listening
82 * for connections. It cannot receive data itself, only incoming
84 * The CONNECTING state indicates an outbound socket which is
85 * waiting to be writeable.
86 * The WAIT_AUTH_1 state indicates the socket is outbound and
87 * has successfully connected, but has not yet sent and received
89 * The WAIT_AUTH_2 state indicates that the socket is inbound
90 * (allocated by a LISTENER) but has not yet sent and received
92 * The CONNECTED state represents a fully authorized, fully
95 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
97 /* We need to import these from the core for use in netbursts */
98 extern user_hash clientlist;
99 extern chan_hash chanlist;
101 /* Foward declarations */
105 /* This variable represents the root of the server tree
106 * (for all intents and purposes, it's us)
108 TreeServer *TreeRoot;
112 /* This hash_map holds the hash equivalent of the server
113 * tree, used for rapid linear lookups.
115 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
116 server_hash serverlist;
118 /* More forward declarations */
119 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
121 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
122 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
123 void ReadConfiguration(bool rebind);
125 /* Imported from xline.cpp for use during netburst */
126 extern std::vector<KLine> klines;
127 extern std::vector<GLine> glines;
128 extern std::vector<ZLine> zlines;
129 extern std::vector<QLine> qlines;
130 extern std::vector<ELine> elines;
131 extern std::vector<KLine> pklines;
132 extern std::vector<GLine> pglines;
133 extern std::vector<ZLine> pzlines;
134 extern std::vector<QLine> pqlines;
135 extern std::vector<ELine> pelines;
137 /* Each server in the tree is represented by one class of
138 * type TreeServer. A locally connected TreeServer can
139 * have a class of type TreeSocket associated with it, for
140 * remote servers, the TreeSocket entry will be NULL.
141 * Each server also maintains a pointer to its parent
142 * (NULL if this server is ours, at the top of the tree)
143 * and a pointer to its "Route" (see the comments in the
144 * constructors below), and also a dynamic list of pointers
145 * to its children which can be iterated recursively
146 * if required. Creating or deleting objects of type
147 * TreeServer automatically maintains the hash_map of
148 * TreeServer items, deleting and inserting them as they
149 * are created and destroyed.
154 TreeServer* Parent; /* Parent entry */
155 TreeServer* Route; /* Route entry */
156 std::vector<TreeServer*> Children; /* List of child objects */
157 std::string ServerName; /* Server's name */
158 std::string ServerDesc; /* Server's description */
159 std::string VersionString; /* Version string or empty string */
160 int UserCount; /* Not used in this version */
161 int OperCount; /* Not used in this version */
162 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
163 time_t NextPing; /* After this time, the server should be PINGed*/
164 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
168 /* We don't use this constructor. Its a dummy, and won't cause any insertion
169 * of the TreeServer into the hash_map. See below for the two we DO use.
177 UserCount = OperCount = 0;
178 VersionString = Srv->GetVersion();
181 /* We use this constructor only to create the 'root' item, TreeRoot, which
182 * represents our own server. Therefore, it has no route, no parent, and
183 * no socket associated with it. Its version string is our own local version.
185 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
189 UserCount = OperCount = 0;
190 VersionString = Srv->GetVersion();
192 Socket = NULL; /* Fix by brain */
196 /* When we create a new server, we call this constructor to initialize it.
197 * This constructor initializes the server's Route and Parent, and sets up
198 * its ping counters so that it will be pinged one minute from now.
200 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
203 UserCount = OperCount = 0;
204 this->SetNextPingTime(time(NULL) + 60);
207 /* find the 'route' for this server (e.g. the one directly connected
208 * to the local server, which we can use to reach it)
210 * In the following example, consider we have just added a TreeServer
211 * class for server G on our network, of which we are server A.
212 * To route traffic to G (marked with a *) we must send the data to
213 * B (marked with a +) so this algorithm initializes the 'Route'
214 * value to point at whichever server traffic must be routed through
215 * to get here. If we were to try this algorithm with server B,
216 * the Route pointer would point at its own object ('this').
226 * We only run this algorithm when a server is created, as
227 * the routes remain constant while ever the server exists, and
228 * do not need to be re-calculated.
232 if (Route == TreeRoot)
238 while (this->Route->GetParent() != TreeRoot)
240 this->Route = Route->GetParent();
244 /* Because recursive code is slow and takes a lot of resources,
245 * we store two representations of the server tree. The first
246 * is a recursive structure where each server references its
247 * children and its parent, which is used for netbursts and
248 * netsplits to dump the whole dataset to the other server,
249 * and the second is used for very fast lookups when routing
250 * messages and is instead a hash_map, where each item can
251 * be referenced by its server name. The AddHashEntry()
252 * call below automatically inserts each TreeServer class
253 * into the hash_map as it is created. There is a similar
254 * maintainance call in the destructor to tidy up deleted
258 this->AddHashEntry();
261 /* This method is used to add the structure to the
262 * hash_map for linear searches. It is only called
263 * by the constructors.
267 server_hash::iterator iter;
268 iter = serverlist.find(this->ServerName);
269 if (iter == serverlist.end())
270 serverlist[this->ServerName] = this;
273 /* This method removes the reference to this object
274 * from the hash_map which is used for linear searches.
275 * It is only called by the default destructor.
279 server_hash::iterator iter;
280 iter = serverlist.find(this->ServerName);
281 if (iter != serverlist.end())
282 serverlist.erase(iter);
285 /* These accessors etc should be pretty self-
289 TreeServer* GetRoute()
294 std::string GetName()
299 std::string GetDesc()
304 std::string GetVersion()
306 return VersionString;
309 void SetNextPingTime(time_t t)
312 LastPingWasGood = false;
315 time_t NextPingTime()
320 bool AnsweredLastPing()
322 return LastPingWasGood;
327 LastPingWasGood = true;
340 TreeSocket* GetSocket()
345 TreeServer* GetParent()
350 void SetVersion(std::string Version)
352 VersionString = Version;
355 unsigned int ChildCount()
357 return Children.size();
360 TreeServer* GetChild(unsigned int n)
362 if (n < Children.size())
364 /* Make sure they cant request
365 * an out-of-range object. After
366 * all we know what these programmer
367 * types are like *grin*.
377 void AddChild(TreeServer* Child)
379 Children.push_back(Child);
382 bool DelChild(TreeServer* Child)
384 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
395 /* Removes child nodes of this node, and of that node, etc etc.
396 * This is used during netsplits to automatically tidy up the
397 * server tree. It is slow, we don't use it for much else.
401 bool stillchildren = true;
402 while (stillchildren)
404 stillchildren = false;
405 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
407 TreeServer* s = (TreeServer*)*a;
411 stillchildren = true;
420 /* We'd better tidy up after ourselves, eh? */
421 this->DelHashEntry();
425 /* The Link class might as well be a struct,
426 * but this is C++ and we don't believe in structs (!).
427 * It holds the entire information of one <link>
428 * tag from the main config file. We maintain a list
429 * of them, and populate the list on rehash/load.
438 std::string SendPass;
439 std::string RecvPass;
440 unsigned long AutoConnect;
441 time_t NextConnectTime;
442 std::string EncryptionKey;
445 /* The usual stuff for inspircd modules,
446 * plus the vector of Link classes which we
447 * use to store the <link> tags from the config
451 std::vector<Link> LinkBlocks;
453 /* Yay for fast searches!
454 * This is hundreds of times faster than recursion
455 * or even scanning a linked list, especially when
456 * there are more than a few servers to deal with.
459 TreeServer* FindServer(std::string ServerName)
461 server_hash::iterator iter;
462 iter = serverlist.find(ServerName);
463 if (iter != serverlist.end())
473 /* Returns the locally connected server we must route a
474 * message through to reach server 'ServerName'. This
475 * only applies to one-to-one and not one-to-many routing.
476 * See the comments for the constructor of TreeServer
479 TreeServer* BestRouteTo(std::string ServerName)
481 if (ServerName.c_str() == TreeRoot->GetName())
483 TreeServer* Found = FindServer(ServerName);
486 return Found->GetRoute();
494 /* Find the first server matching a given glob mask.
495 * Theres no find-using-glob method of hash_map [awwww :-(]
496 * so instead, we iterate over the list using an iterator
497 * and match each one until we get a hit. Yes its slow,
500 TreeServer* FindServerMask(std::string ServerName)
502 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
504 if (Srv->MatchText(i->first,ServerName))
510 /* A convenient wrapper that returns true if a server exists */
511 bool IsServer(std::string ServerName)
513 return (FindServer(ServerName) != NULL);
516 /* Every SERVER connection inbound or outbound is represented by
517 * an object of type TreeSocket.
518 * TreeSockets, being inherited from InspSocket, can be tied into
519 * the core socket engine, and we cn therefore receive activity events
520 * for them, just like activex objects on speed. (yes really, that
521 * is a technical term!) Each of these which relates to a locally
522 * connected server is assocated with it, by hooking it onto a
523 * TreeSocket class using its constructor. In this way, we can
524 * maintain a list of servers, some of which are directly connected,
525 * some of which are not.
528 class TreeSocket : public InspSocket
531 std::string in_buffer;
532 ServerState LinkState;
533 std::string InboundServerName;
534 std::string InboundDescription;
536 int num_lost_servers;
538 bool LastPingWasGood;
541 unsigned int keylength;
545 /* Because most of the I/O gubbins are encapsulated within
546 * InspSocket, we just call the superclass constructor for
547 * most of the action, and append a few of our own values
550 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
551 : InspSocket(host, port, listening, maxtime)
554 this->LinkState = LISTENER;
557 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
558 : InspSocket(host, port, listening, maxtime)
561 this->LinkState = CONNECTING;
564 /* When a listening socket gives us a new file descriptor,
565 * we must associate it with a socket without creating a new
566 * connection. This constructor is used for this purpose.
568 TreeSocket(int newfd, char* ip)
569 : InspSocket(newfd, ip)
571 this->LinkState = WAIT_AUTH_1;
572 this->SendCapabilities();
575 void InitAES(std::string key,std::string SName)
581 log(DEBUG,"Initialized AES key %s",key.c_str());
582 // key must be 16, 24, 32 etc bytes (multiple of 8)
583 keylength = key.length();
584 if (!(keylength == 16 || keylength == 24 || keylength == 32))
586 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
587 log(DEBUG,"Key length not 16, 24 or 32 characters!");
591 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
592 ctx->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
593 \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);
597 /* When an outbound connection finishes connecting, we receive
598 * this event, and must send our SERVER string to the other
599 * side. If the other side is happy, as outlined in the server
600 * to server docs on the inspircd.org site, the other side
601 * will then send back its own server string.
603 virtual bool OnConnected()
605 if (this->LinkState == CONNECTING)
607 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
608 /* we do not need to change state here. */
609 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
611 if (x->Name == this->myhost)
613 if (x->EncryptionKey != "")
615 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
617 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
621 this->WriteLine("AES "+Srv->GetServerName());
622 this->InitAES(x->EncryptionKey,x->Name);
625 this->SendCapabilities();
626 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
627 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
632 /* There is a (remote) chance that between the /CONNECT and the connection
633 * being accepted, some muppet has removed the <link> block and rehashed.
634 * If that happens the connection hangs here until it's closed. Unlikely
635 * and rather harmless.
640 virtual void OnError(InspSocketError e)
642 /* We don't handle this method, because all our
643 * dirty work is done in OnClose() (see below)
644 * which is still called on error conditions too.
648 virtual int OnDisconnect()
650 /* For the same reason as above, we don't
651 * handle OnDisconnect()
656 /* Recursively send the server tree with distances as hops.
657 * This is used during network burst to inform the other server
658 * (and any of ITS servers too) of what servers we know about.
659 * If at any point any of these servers already exist on the other
660 * end, our connection may be terminated. The hopcounts given
661 * by this function are relative, this doesn't matter so long as
662 * they are all >1, as all the remote servers re-calculate them
663 * to be relative too, with themselves as hop 0.
665 void SendServers(TreeServer* Current, TreeServer* s, int hops)
668 for (unsigned int q = 0; q < Current->ChildCount(); q++)
670 TreeServer* recursive_server = Current->GetChild(q);
671 if (recursive_server != s)
673 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
674 this->WriteLine(command);
675 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
676 /* down to next level */
677 this->SendServers(recursive_server, s, hops+1);
682 std::string MyCapabilities()
684 ServerConfig* Config = Srv->GetConfig();
685 std::vector<std::string> modlist;
686 std::string capabilities = "";
688 for (int i = 0; i <= MODCOUNT; i++)
690 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
691 modlist.push_back(Config->module_names[i]);
693 sort(modlist.begin(),modlist.end());
694 for (unsigned int i = 0; i < modlist.size(); i++)
697 capabilities = capabilities + ",";
698 capabilities = capabilities + modlist[i];
703 void SendCapabilities()
705 this->WriteLine("CAPAB "+MyCapabilities());
708 bool Capab(std::deque<std::string> params)
710 if (params.size() != 1)
712 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
715 if (params[0] != this->MyCapabilities())
717 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!");
718 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
719 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
720 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
721 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
727 /* This function forces this server to quit, removing this server
728 * and any users on it (and servers and users below that, etc etc).
729 * It's very slow and pretty clunky, but luckily unless your network
730 * is having a REAL bad hair day, this function shouldnt be called
731 * too many times a month ;-)
733 void SquitServer(TreeServer* Current, CullList* Goners)
735 /* recursively squit the servers attached to 'Current'.
736 * We're going backwards so we don't remove users
737 * while we still need them ;)
739 for (unsigned int q = 0; q < Current->ChildCount(); q++)
741 TreeServer* recursive_server = Current->GetChild(q);
742 this->SquitServer(recursive_server,Goners);
744 /* Now we've whacked the kids, whack self */
746 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
748 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
750 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
751 Goners->AddItem(u->second,qreason);
757 /* This is a wrapper function for SquitServer above, which
758 * does some validation first and passes on the SQUIT to all
759 * other remaining servers.
761 void Squit(TreeServer* Current,std::string reason)
763 if ((Current) && (Current != TreeRoot))
765 std::deque<std::string> params;
766 params.push_back(Current->GetName());
767 params.push_back(":"+reason);
768 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
769 if (Current->GetParent() == TreeRoot)
771 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
775 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
777 num_lost_servers = 0;
779 CullList* Goners = new CullList();
780 SquitServer(Current, Goners);
783 Current->GetParent()->DelChild(Current);
786 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
790 log(DEFAULT,"Squit from unknown server");
795 bool ForceMode(std::string source, std::deque<std::string> params)
797 userrec* who = new userrec;
798 who->fd = FD_MAGIC_NUMBER;
799 if (params.size() < 2)
802 for (unsigned int q = 0; q < params.size(); q++)
804 modelist[q] = (char*)params[q].c_str();
806 Srv->SendMode(modelist,params.size(),who);
807 DoOneToAllButSender(source,"FMODE",params,source);
813 bool ForceTopic(std::string source, std::deque<std::string> params)
815 if (params.size() != 4)
817 std::string channel = params[0];
818 time_t ts = atoi(params[1].c_str());
819 std::string setby = params[2];
820 std::string topic = params[3];
822 chanrec* c = Srv->FindChannel(channel);
825 if ((ts >= c->topicset) || (!*c->topic))
827 std::string oldtopic = c->topic;
828 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
829 strlcpy(c->setby,setby.c_str(),NICKMAX);
831 /* if the topic text is the same as the current topic,
832 * dont bother to send the TOPIC command out, just silently
833 * update the set time and set nick.
835 if (oldtopic != topic)
836 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
841 /* all done, send it on its way */
842 params[3] = ":" + params[3];
843 DoOneToAllButSender(source,"FTOPIC",params,source);
848 /* FJOIN, similar to unreal SJOIN */
849 bool ForceJoin(std::string source, std::deque<std::string> params)
851 if (params.size() < 3)
855 char modestring[MAXBUF];
856 char* mode_users[127];
857 mode_users[0] = first;
858 mode_users[1] = modestring;
859 strcpy(mode_users[1],"+");
860 unsigned int modectr = 2;
863 std::string channel = params[0];
864 time_t TS = atoi(params[1].c_str());
867 chanrec* chan = Srv->FindChannel(channel);
872 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
874 /* default is a high value, which if we dont have this
875 * channel will let the other side apply their modes.
877 time_t ourTS = time(NULL)+600;
878 chanrec* us = Srv->FindChannel(channel);
884 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
886 /* do this first, so our mode reversals are correctly received by other servers
887 * if there is a TS collision.
889 DoOneToAllButSender(source,"FJOIN",params,source);
891 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
893 /* process one channel at a time, applying modes. */
894 char* usr = (char*)params[usernum].c_str();
895 char permissions = *usr;
900 mode_users[modectr++] = usr;
901 strlcat(modestring,"o",MAXBUF);
905 mode_users[modectr++] = usr;
906 strlcat(modestring,"h",MAXBUF);
910 mode_users[modectr++] = usr;
911 strlcat(modestring,"v",MAXBUF);
914 who = Srv->FindNick(usr);
917 Srv->JoinUserToChannel(who,channel,key);
918 if (modectr >= (MAXMODES-1))
920 /* theres a mode for this user. push them onto the mode queue, and flush it
921 * if there are more than MAXMODES to go.
923 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
925 /* We also always let u-lined clients win, no matter what the TS value */
926 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
927 Srv->SendMode(mode_users,modectr,who);
931 log(DEBUG,"Their channel newer than ours, bouncing their modes");
933 std::deque<std::string> params;
934 /* modes are now being UNSET... */
935 *mode_users[1] = '-';
936 for (unsigned int x = 0; x < modectr; x++)
938 params.push_back(mode_users[x]);
940 // tell everyone to bounce the modes. bad modes, bad!
941 DoOneToMany(Srv->GetServerName(),"FMODE",params);
943 strcpy(mode_users[1],"+");
948 /* there werent enough modes built up to flush it during FJOIN,
949 * or, there are a number left over. flush them out.
951 if ((modectr > 2) && (who))
955 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
956 Srv->SendMode(mode_users,modectr,who);
960 log(DEBUG,"Their channel newer than ours, bouncing their modes");
961 std::deque<std::string> params;
962 *mode_users[1] = '-';
963 for (unsigned int x = 0; x < modectr; x++)
965 params.push_back(mode_users[x]);
967 DoOneToMany(Srv->GetServerName(),"FMODE",params);
974 bool IntroduceClient(std::string source, std::deque<std::string> params)
976 if (params.size() < 8)
978 // NICK age nick host dhost ident +modes ip :gecos
980 std::string nick = params[1];
981 std::string host = params[2];
982 std::string dhost = params[3];
983 std::string ident = params[4];
984 time_t age = atoi(params[0].c_str());
985 std::string modes = params[5];
986 while (*(modes.c_str()) == '+')
988 char* m = (char*)modes.c_str();
992 std::string ip = params[6];
993 std::string gecos = params[7];
994 char* tempnick = (char*)nick.c_str();
995 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
997 user_hash::iterator iter;
998 iter = clientlist.find(tempnick);
999 if (iter != clientlist.end())
1002 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);
1003 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1007 clientlist[tempnick] = new userrec();
1008 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1009 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1010 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1011 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1012 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1013 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1014 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1015 clientlist[tempnick]->registered = 7;
1016 clientlist[tempnick]->signon = age;
1017 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1018 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1023 for (int i = 0; i < MAXCHANS; i++)
1024 clientlist[tempnick]->chans.push_back(a);
1026 if (!this->bursting)
1028 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1030 params[7] = ":" + params[7];
1031 DoOneToAllButSender(source,"NICK",params,source);
1035 /* Send one or more FJOINs for a channel of users.
1036 * If the length of a single line is more than 480-NICKMAX
1037 * in length, it is split over multiple lines.
1039 void SendFJoins(TreeServer* Current, chanrec* c)
1041 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1043 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1044 std::vector<char*> *ulist = c->GetUsers();
1045 for (unsigned int i = 0; i < ulist->size(); i++)
1047 char* o = (*ulist)[i];
1048 userrec* otheruser = (userrec*)o;
1049 strlcat(list," ",MAXBUF);
1050 strlcat(list,cmode(otheruser,c),MAXBUF);
1051 strlcat(list,otheruser->nick,MAXBUF);
1052 if (strlen(list)>(480-NICKMAX))
1054 log(DEBUG,"FJOIN line wrapped");
1055 this->WriteLine(list);
1056 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1059 if (list[strlen(list)-1] != ':')
1061 log(DEBUG,"Final FJOIN line");
1062 this->WriteLine(list);
1066 /* Send G, Q, Z and E lines */
1067 void SendXLines(TreeServer* Current)
1070 /* Yes, these arent too nice looking, but they get the job done */
1071 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1073 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);
1074 this->WriteLine(data);
1076 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1078 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);
1079 this->WriteLine(data);
1081 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1083 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);
1084 this->WriteLine(data);
1086 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1088 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);
1089 this->WriteLine(data);
1091 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1093 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);
1094 this->WriteLine(data);
1096 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1098 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);
1099 this->WriteLine(data);
1101 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1103 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);
1104 this->WriteLine(data);
1106 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1108 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);
1109 this->WriteLine(data);
1113 /* Send channel modes and topics */
1114 void SendChannelModes(TreeServer* Current)
1117 std::deque<std::string> list;
1118 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1120 SendFJoins(Current, c->second);
1121 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1122 this->WriteLine(data);
1123 if (*c->second->topic)
1125 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);
1126 this->WriteLine(data);
1128 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1130 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1131 this->WriteLine(data);
1133 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1135 c->second->GetExtList(list);
1136 for (unsigned int j = 0; j < list.size(); j++)
1138 FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1143 /* send all users and their oper state/modes */
1144 void SendUsers(TreeServer* Current)
1147 std::deque<std::string> list;
1148 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1150 if (u->second->registered == 7)
1152 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);
1153 this->WriteLine(data);
1154 if (strchr(u->second->modes,'o'))
1156 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1158 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1160 u->second->GetExtList(list);
1161 for (unsigned int j = 0; j < list.size(); j++)
1163 FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1169 /* This function is called when we want to send a netburst to a local
1170 * server. There is a set order we must do this, because for example
1171 * users require their servers to exist, and channels require their
1172 * users to exist. You get the idea.
1174 void DoBurst(TreeServer* s)
1176 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1177 this->WriteLine("BURST");
1178 /* send our version string */
1179 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1180 /* Send server tree */
1181 this->SendServers(TreeRoot,s,1);
1182 /* Send users and their oper status */
1184 /* Send everything else (channel modes, xlines etc) */
1185 this->SendChannelModes(s);
1186 this->SendXLines(s);
1187 this->WriteLine("ENDBURST");
1188 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1191 /* This function is called when we receive data from a remote
1192 * server. We buffer the data in a std::string (it doesnt stay
1193 * there for long), reading using InspSocket::Read() which can
1194 * read up to 16 kilobytes in one operation.
1196 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1197 * THE SOCKET OBJECT FOR US.
1199 virtual bool OnDataReady()
1201 char* data = this->Read();
1204 this->in_buffer += data;
1205 /* While there is at least one new line in the buffer,
1206 * do something useful (we hope!) with it.
1208 while (in_buffer.find("\n") != std::string::npos)
1210 char* line = (char*)in_buffer.c_str();
1211 std::string ret = "";
1212 while ((*line != '\n') && (strlen(line)))
1217 if ((*line == '\n') || (*line == '\r'))
1220 /* Process this one, abort if it
1221 * didnt return true.
1227 log(DEBUG,"Original string '%s'",ret.c_str());
1228 int nbytes = from64tobits(out, ret.c_str(), 1024);
1229 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1230 ctx->Decrypt(out, result, nbytes, 0);
1231 for (int t = 0; t < nbytes; t++)
1232 if (result[t] == '\7') result[t] = 0;
1235 if (!this->ProcessLine(ret))
1241 return (data != NULL);
1244 int WriteLine(std::string line)
1246 log(DEBUG,"OUT: %s",line.c_str());
1249 log(DEBUG,"AES context");
1251 char result64[1024];
1252 if (this->keylength)
1254 while (line.length() % this->keylength != 0)
1256 // pad it to be a multiple of the key length
1260 ctx->Encrypt(line.c_str(), result, line.length(),0);
1261 to64frombits((unsigned char*)result64,
1262 (unsigned char*)result,
1265 log(DEBUG,"Encrypted: %s",line.c_str());
1266 //int from64tobits(char *out, const char *in, int maxlen);
1268 return this->Write(line + "\r\n");
1271 /* Handle ERROR command */
1272 bool Error(std::deque<std::string> params)
1274 if (params.size() < 1)
1276 std::string Errmsg = params[0];
1277 std::string SName = myhost;
1278 if (InboundServerName != "")
1280 SName = InboundServerName;
1282 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1283 /* we will return false to cause the socket to close.
1288 /* Because the core won't let users or even SERVERS set +o,
1289 * we use the OPERTYPE command to do this.
1291 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1293 if (params.size() != 1)
1295 std::string opertype = params[0];
1296 userrec* u = Srv->FindNick(prefix);
1299 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1300 if (!strchr(u->modes,'o'))
1302 strcat(u->modes,"o");
1304 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1309 /* Because Andy insists that services-compatible servers must
1310 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1312 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1314 if (params.size() < 3)
1316 userrec* u = Srv->FindNick(params[0]);
1319 Srv->ChangeUserNick(u,params[1]);
1320 u->age = atoi(params[2].c_str());
1321 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1326 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1328 if (params.size() < 2)
1330 userrec* u = Srv->FindNick(params[0]);
1333 Srv->JoinUserToChannel(u,params[1],"");
1334 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1339 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1341 if (params.size() < 1)
1343 std::string servermask = params[0];
1344 if (Srv->MatchText(Srv->GetServerName(),servermask))
1346 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1347 Srv->RehashServer();
1348 ReadConfiguration(false);
1350 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1354 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1356 if (params.size() != 2)
1358 std::string nick = params[0];
1359 userrec* u = Srv->FindNick(prefix);
1360 userrec* who = Srv->FindNick(nick);
1363 /* Prepend kill source, if we don't have one */
1364 std::string sourceserv = prefix;
1367 sourceserv = u->server;
1369 if (*(params[1].c_str()) != '[')
1371 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1373 std::string reason = params[1];
1374 params[1] = ":" + params[1];
1375 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1376 Srv->QuitUser(who,reason);
1381 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1383 if (params.size() < 1)
1385 TreeServer* ServerSource = FindServer(prefix);
1388 ServerSource->SetPingFlag();
1393 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1395 if (params.size() < 3)
1397 TreeServer* ServerSource = FindServer(prefix);
1400 if (*(params[0].c_str()) == '#')
1402 chanrec* c = Srv->FindChannel(params[0]);
1405 FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1410 userrec* u = Srv->FindNick(params[0]);
1413 FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1417 params[2] = ":" + params[2];
1418 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1422 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1424 if (params.size() < 1)
1426 TreeServer* ServerSource = FindServer(prefix);
1429 ServerSource->SetVersion(params[0]);
1431 params[0] = ":" + params[0];
1432 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1436 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1438 if (params.size() < 1)
1440 userrec* u = Srv->FindNick(prefix);
1443 Srv->ChangeHost(u,params[0]);
1444 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1449 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1451 if (params.size() < 6)
1453 std::string linetype = params[0]; /* Z, Q, E, G, K */
1454 std::string mask = params[1]; /* Line type dependent */
1455 std::string source = params[2]; /* may not be online or may be a server */
1456 std::string settime = params[3]; /* EPOCH time set */
1457 std::string duration = params[4]; /* Duration secs */
1458 std::string reason = params[5];
1460 switch (*(linetype.c_str()))
1463 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1464 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1467 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1468 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1471 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1472 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1475 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1476 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1479 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1482 /* Just in case... */
1483 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1486 /* Send it on its way */
1487 params[5] = ":" + params[5];
1488 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1492 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1494 if (params.size() < 1)
1496 userrec* u = Srv->FindNick(prefix);
1499 Srv->ChangeGECOS(u,params[0]);
1500 params[0] = ":" + params[0];
1501 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1506 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1508 if (params.size() < 1)
1510 log(DEBUG,"In IDLE command");
1511 userrec* u = Srv->FindNick(prefix);
1514 log(DEBUG,"USER EXISTS: %s",u->nick);
1515 // an incoming request
1516 if (params.size() == 1)
1518 userrec* x = Srv->FindNick(params[0]);
1521 userrec* x = Srv->FindNick(params[0]);
1522 log(DEBUG,"Got IDLE");
1523 char signon[MAXBUF];
1525 log(DEBUG,"Sending back IDLE 3");
1526 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1527 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1528 std::deque<std::string> par;
1529 par.push_back(prefix);
1530 par.push_back(signon);
1531 par.push_back(idle);
1532 // ours, we're done, pass it BACK
1533 DoOneToOne(params[0],"IDLE",par,u->server);
1537 // not ours pass it on
1538 DoOneToOne(prefix,"IDLE",params,x->server);
1541 else if (params.size() == 3)
1543 std::string who_did_the_whois = params[0];
1544 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1545 if (who_to_send_to->fd > -1)
1547 log(DEBUG,"Got final IDLE");
1548 // an incoming reply to a whois we sent out
1549 std::string nick_whoised = prefix;
1550 unsigned long signon = atoi(params[1].c_str());
1551 unsigned long idle = atoi(params[2].c_str());
1552 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1553 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1557 // not ours, pass it on
1558 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1565 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1567 if (params.size() < 1)
1569 std::string stufftobounce = params[0];
1570 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1574 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1576 if (params.size() < 4)
1578 std::string servername = params[0];
1579 std::string password = params[1];
1580 // hopcount is not used for a remote server, we calculate this ourselves
1581 std::string description = params[3];
1582 TreeServer* ParentOfThis = FindServer(prefix);
1585 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1588 TreeServer* CheckDupe = FindServer(servername);
1591 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1592 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1595 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1596 ParentOfThis->AddChild(Node);
1597 params[3] = ":" + params[3];
1598 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1599 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1603 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1605 if (params.size() < 4)
1607 std::string servername = params[0];
1608 std::string password = params[1];
1609 int hops = atoi(params[2].c_str());
1612 this->WriteLine("ERROR :Server too far away for authentication");
1613 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1616 std::string description = params[3];
1617 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1619 if ((x->Name == servername) && (x->RecvPass == password))
1621 TreeServer* CheckDupe = FindServer(servername);
1624 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1625 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1628 // Begin the sync here. this kickstarts the
1629 // other side, waiting in WAIT_AUTH_2 state,
1630 // into starting their burst, as it shows
1631 // that we're happy.
1632 this->LinkState = CONNECTED;
1633 // we should add the details of this server now
1634 // to the servers tree, as a child of the root
1636 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1637 TreeRoot->AddChild(Node);
1638 params[3] = ":" + params[3];
1639 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1640 this->bursting = true;
1641 this->DoBurst(Node);
1645 this->WriteLine("ERROR :Invalid credentials");
1646 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1650 bool Inbound_Server(std::deque<std::string> ¶ms)
1652 if (params.size() < 4)
1654 std::string servername = params[0];
1655 std::string password = params[1];
1656 int hops = atoi(params[2].c_str());
1659 this->WriteLine("ERROR :Server too far away for authentication");
1660 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1663 std::string description = params[3];
1664 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1666 if ((x->Name == servername) && (x->RecvPass == password))
1668 TreeServer* CheckDupe = FindServer(servername);
1671 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1672 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1675 /* If the config says this link is encrypted, but the remote side
1676 * hasnt bothered to send the AES command before SERVER, then we
1677 * boot them off as we MUST have this connection encrypted.
1679 if ((x->EncryptionKey != "") && (!this->ctx))
1681 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1682 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1685 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1686 this->InboundServerName = servername;
1687 this->InboundDescription = description;
1688 // this is good. Send our details: Our server name and description and hopcount of 0,
1689 // along with the sendpass from this block.
1690 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1691 // move to the next state, we are now waiting for THEM.
1692 this->LinkState = WAIT_AUTH_2;
1696 this->WriteLine("ERROR :Invalid credentials");
1697 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1701 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1703 if (!strchr(line.c_str(),' '))
1708 std::stringstream s(line);
1709 std::string param = "";
1728 if ((param == ":") && (item > 0))
1751 bool ProcessLine(std::string line)
1753 char* l = (char*)line.c_str();
1754 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1755 l[strlen(l)-1] = '\0';
1759 Srv->Log(DEBUG,"IN: "+line);
1760 std::deque<std::string> params;
1761 this->Split(line,true,params);
1762 std::string command = "";
1763 std::string prefix = "";
1764 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1767 command = params[1];
1768 char* pref = (char*)prefix.c_str();
1776 command = params[0];
1780 if ((!this->ctx) && (command == "AES"))
1782 std::string sserv = params[0];
1783 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1785 if ((x->EncryptionKey != "") && (x->Name == sserv))
1787 this->InitAES(x->EncryptionKey,sserv);
1792 else if ((this->ctx) && (command == "AES"))
1794 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1797 switch (this->LinkState)
1802 // Waiting for SERVER command from remote server. Server initiating
1803 // the connection sends the first SERVER command, listening server
1804 // replies with theirs if its happy, then if the initiator is happy,
1805 // it starts to send its net sync, which starts the merge, otherwise
1806 // it sends an ERROR.
1807 if (command == "PASS")
1809 /* Silently ignored */
1811 else if (command == "SERVER")
1813 return this->Inbound_Server(params);
1815 else if (command == "ERROR")
1817 return this->Error(params);
1819 else if (command == "USER")
1821 this->WriteLine("ERROR :Client connections to this port are prohibited.");
1824 else if (command == "CAPAB")
1826 return this->Capab(params);
1830 this->WriteLine("ERROR :Invalid command in negotiation phase.");
1835 // Waiting for start of other side's netmerge to say they liked our
1837 if (command == "SERVER")
1839 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1843 else if (command == "BURST")
1845 this->LinkState = CONNECTED;
1846 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1847 TreeRoot->AddChild(Node);
1849 params.push_back(InboundServerName);
1850 params.push_back("*");
1851 params.push_back("1");
1852 params.push_back(":"+InboundDescription);
1853 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1854 this->bursting = true;
1855 this->DoBurst(Node);
1857 else if (command == "ERROR")
1859 return this->Error(params);
1861 else if (command == "CAPAB")
1863 return this->Capab(params);
1868 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1872 if (command == "SERVER")
1874 // another server we connected to, which was in WAIT_AUTH_1 state,
1875 // has just sent us their credentials. If we get this far, theyre
1876 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1877 // if we're happy with this, we should send our netburst which
1878 // kickstarts the merge.
1879 return this->Outbound_Reply_Server(params);
1881 else if (command == "ERROR")
1883 return this->Error(params);
1887 // This is the 'authenticated' state, when all passwords
1888 // have been exchanged and anything past this point is taken
1893 std::string direction = prefix;
1894 userrec* t = Srv->FindNick(prefix);
1897 direction = t->server;
1899 TreeServer* route_back_again = BestRouteTo(direction);
1900 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1902 if (route_back_again)
1904 WriteOpers("*** Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1908 WriteOpers("*** Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1915 if (command == "SVSMODE")
1917 /* Services expects us to implement
1918 * SVSMODE. In inspircd its the same as
1923 std::string target = "";
1924 /* Yes, know, this is a mess. Its reasonably fast though as we're
1925 * working with std::string here.
1927 if ((command == "NICK") && (params.size() > 1))
1929 return this->IntroduceClient(prefix,params);
1931 else if (command == "FJOIN")
1933 return this->ForceJoin(prefix,params);
1935 else if (command == "SERVER")
1937 return this->RemoteServer(prefix,params);
1939 else if (command == "ERROR")
1941 return this->Error(params);
1943 else if (command == "OPERTYPE")
1945 return this->OperType(prefix,params);
1947 else if (command == "FMODE")
1949 return this->ForceMode(prefix,params);
1951 else if (command == "KILL")
1953 return this->RemoteKill(prefix,params);
1955 else if (command == "FTOPIC")
1957 return this->ForceTopic(prefix,params);
1959 else if (command == "REHASH")
1961 return this->RemoteRehash(prefix,params);
1963 else if (command == "METADATA")
1965 return this->MetaData(prefix,params);
1967 else if (command == "PING")
1969 return this->LocalPing(prefix,params);
1971 else if (command == "PONG")
1973 return this->LocalPong(prefix,params);
1975 else if (command == "VERSION")
1977 return this->ServerVersion(prefix,params);
1979 else if (command == "FHOST")
1981 return this->ChangeHost(prefix,params);
1983 else if (command == "FNAME")
1985 return this->ChangeName(prefix,params);
1987 else if (command == "ADDLINE")
1989 return this->AddLine(prefix,params);
1991 else if (command == "SVSNICK")
1995 prefix = this->GetName();
1997 return this->ForceNick(prefix,params);
1999 else if (command == "IDLE")
2001 return this->Whois(prefix,params);
2003 else if (command == "SVSJOIN")
2007 prefix = this->GetName();
2009 return this->ServiceJoin(prefix,params);
2011 else if (command == "SQUIT")
2013 if (params.size() == 2)
2015 this->Squit(FindServer(params[0]),params[1]);
2019 else if (command == "ENDBURST")
2021 this->bursting = false;
2026 // not a special inter-server command.
2027 // Emulate the actual user doing the command,
2028 // this saves us having a huge ugly parser.
2029 userrec* who = Srv->FindNick(prefix);
2030 std::string sourceserv = this->myhost;
2031 if (this->InboundServerName != "")
2033 sourceserv = this->InboundServerName;
2038 target = who->server;
2039 char* strparams[127];
2040 for (unsigned int q = 0; q < params.size(); q++)
2042 strparams[q] = (char*)params[q].c_str();
2044 Srv->CallCommandHandler(command, strparams, params.size(), who);
2048 // its not a user. Its either a server, or somethings screwed up.
2049 if (IsServer(prefix))
2051 target = Srv->GetServerName();
2055 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2059 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2068 virtual std::string GetName()
2070 std::string sourceserv = this->myhost;
2071 if (this->InboundServerName != "")
2073 sourceserv = this->InboundServerName;
2078 virtual void OnTimeout()
2080 if (this->LinkState == CONNECTING)
2082 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2086 virtual void OnClose()
2088 // Connection closed.
2089 // If the connection is fully up (state CONNECTED)
2090 // then propogate a netsplit to all peers.
2091 std::string quitserver = this->myhost;
2092 if (this->InboundServerName != "")
2094 quitserver = this->InboundServerName;
2096 TreeServer* s = FindServer(quitserver);
2099 Squit(s,"Remote host closed the connection");
2103 virtual int OnIncomingConnection(int newsock, char* ip)
2105 TreeSocket* s = new TreeSocket(newsock, ip);
2111 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2113 for (unsigned int c = 0; c < list.size(); c++)
2115 if (list[c] == server)
2120 list.push_back(server);
2123 // returns a list of DIRECT servernames for a specific channel
2124 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2126 std::vector<char*> *ulist = c->GetUsers();
2127 unsigned int ucount = ulist->size();
2128 for (unsigned int i = 0; i < ucount; i++)
2130 char* o = (*ulist)[i];
2131 userrec* otheruser = (userrec*)o;
2132 if (otheruser->fd < 0)
2134 TreeServer* best = BestRouteTo(otheruser->server);
2136 AddThisServer(best,list);
2142 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2144 TreeServer* omitroute = BestRouteTo(omit);
2145 if ((command == "NOTICE") || (command == "PRIVMSG"))
2147 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2149 if (*(params[0].c_str()) != '#')
2151 // special routing for private messages/notices
2152 userrec* d = Srv->FindNick(params[0]);
2155 std::deque<std::string> par;
2156 par.push_back(params[0]);
2157 par.push_back(":"+params[1]);
2158 DoOneToOne(prefix,command,par,d->server);
2164 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2165 chanrec* c = Srv->FindChannel(params[0]);
2168 std::deque<TreeServer*> list;
2169 GetListOfServersForChannel(c,list);
2170 log(DEBUG,"Got a list of %d servers",list.size());
2171 unsigned int lsize = list.size();
2172 for (unsigned int i = 0; i < lsize; i++)
2174 TreeSocket* Sock = list[i]->GetSocket();
2175 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2177 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2178 Sock->WriteLine(data);
2186 unsigned int items = TreeRoot->ChildCount();
2187 for (unsigned int x = 0; x < items; x++)
2189 TreeServer* Route = TreeRoot->GetChild(x);
2190 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2192 TreeSocket* Sock = Route->GetSocket();
2193 Sock->WriteLine(data);
2199 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2201 TreeServer* omitroute = BestRouteTo(omit);
2202 std::string FullLine = ":" + prefix + " " + command;
2203 unsigned int words = params.size();
2204 for (unsigned int x = 0; x < words; x++)
2206 FullLine = FullLine + " " + params[x];
2208 unsigned int items = TreeRoot->ChildCount();
2209 for (unsigned int x = 0; x < items; x++)
2211 TreeServer* Route = TreeRoot->GetChild(x);
2212 // Send the line IF:
2213 // The route has a socket (its a direct connection)
2214 // The route isnt the one to be omitted
2215 // The route isnt the path to the one to be omitted
2216 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2218 TreeSocket* Sock = Route->GetSocket();
2219 Sock->WriteLine(FullLine);
2225 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2227 std::string FullLine = ":" + prefix + " " + command;
2228 unsigned int words = params.size();
2229 for (unsigned int x = 0; x < words; x++)
2231 FullLine = FullLine + " " + params[x];
2233 unsigned int items = TreeRoot->ChildCount();
2234 for (unsigned int x = 0; x < items; x++)
2236 TreeServer* Route = TreeRoot->GetChild(x);
2237 if (Route->GetSocket())
2239 TreeSocket* Sock = Route->GetSocket();
2240 Sock->WriteLine(FullLine);
2246 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2248 TreeServer* Route = BestRouteTo(target);
2251 std::string FullLine = ":" + prefix + " " + command;
2252 unsigned int words = params.size();
2253 for (unsigned int x = 0; x < words; x++)
2255 FullLine = FullLine + " " + params[x];
2257 if (Route->GetSocket())
2259 TreeSocket* Sock = Route->GetSocket();
2260 Sock->WriteLine(FullLine);
2270 std::vector<TreeSocket*> Bindings;
2272 void ReadConfiguration(bool rebind)
2274 Conf = new ConfigReader;
2277 for (int j =0; j < Conf->Enumerate("bind"); j++)
2279 std::string Type = Conf->ReadValue("bind","type",j);
2280 std::string IP = Conf->ReadValue("bind","address",j);
2281 long Port = Conf->ReadInteger("bind","port",j,true);
2282 if (Type == "servers")
2288 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2289 if (listener->GetState() == I_LISTENING)
2291 Srv->AddSocket(listener);
2292 Bindings.push_back(listener);
2296 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2304 for (int j =0; j < Conf->Enumerate("link"); j++)
2307 L.Name = Conf->ReadValue("link","name",j);
2308 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2309 L.Port = Conf->ReadInteger("link","port",j,true);
2310 L.SendPass = Conf->ReadValue("link","sendpass",j);
2311 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2312 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2313 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2314 L.NextConnectTime = time(NULL) + L.AutoConnect;
2315 /* Bugfix by brain, do not allow people to enter bad configurations */
2316 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2318 LinkBlocks.push_back(L);
2319 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2323 log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2330 class ModuleSpanningTree : public Module
2332 std::vector<TreeSocket*> Bindings;
2338 ModuleSpanningTree(Server* Me)
2339 : Module::Module(Me)
2344 // Create the root of the tree
2345 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2347 ReadConfiguration(true);
2350 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2352 std::string Parent = TreeRoot->GetName();
2353 if (Current->GetParent())
2355 Parent = Current->GetParent()->GetName();
2357 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2359 ShowLinks(Current->GetChild(q),user,hops+1);
2361 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2364 int CountLocalServs()
2366 return TreeRoot->ChildCount();
2371 return serverlist.size();
2374 void HandleLinks(char** parameters, int pcnt, userrec* user)
2376 ShowLinks(TreeRoot,user,0);
2377 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2381 void HandleLusers(char** parameters, int pcnt, userrec* user)
2383 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2384 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2385 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2386 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2387 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2391 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2393 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2397 for (int t = 0; t < depth; t++)
2399 matrix[line][t] = ' ';
2401 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2403 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2405 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2410 // Ok, prepare to be confused.
2411 // After much mulling over how to approach this, it struck me that
2412 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2413 // keeping track of a ton of ascii characters, and line by line
2414 // under recursion working out where to place them using multiplications
2415 // and divisons, we instead render the map onto a backplane of characters
2416 // (a character matrix), then draw the branches as a series of "L" shapes
2417 // from the nodes. This is not only friendlier on CPU it uses less stack.
2419 void HandleMap(char** parameters, int pcnt, userrec* user)
2421 // This array represents a virtual screen which we will
2422 // "scratch" draw to, as the console device of an irc
2423 // client does not provide for a proper terminal.
2424 char matrix[128][80];
2425 for (unsigned int t = 0; t < 128; t++)
2427 matrix[t][0] = '\0';
2430 // The only recursive bit is called here.
2431 ShowMap(TreeRoot,user,0,matrix);
2432 // Process each line one by one. The algorithm has a limit of
2433 // 128 servers (which is far more than a spanning tree should have
2434 // anyway, so we're ok). This limit can be raised simply by making
2435 // the character matrix deeper, 128 rows taking 10k of memory.
2436 for (int l = 1; l < line; l++)
2438 // scan across the line looking for the start of the
2439 // servername (the recursive part of the algorithm has placed
2440 // the servers at indented positions depending on what they
2442 int first_nonspace = 0;
2443 while (matrix[l][first_nonspace] == ' ')
2448 // Draw the `- (corner) section: this may be overwritten by
2449 // another L shape passing along the same vertical pane, becoming
2450 // a |- (branch) section instead.
2451 matrix[l][first_nonspace] = '-';
2452 matrix[l][first_nonspace-1] = '`';
2454 // Draw upwards until we hit the parent server, causing possibly
2455 // other corners (`-) to become branches (|-)
2456 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2458 matrix[l2][first_nonspace-1] = '|';
2462 // dump the whole lot to the user. This is the easy bit, honest.
2463 for (int t = 0; t < line; t++)
2465 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2467 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2471 int HandleSquit(char** parameters, int pcnt, userrec* user)
2473 TreeServer* s = FindServerMask(parameters[0]);
2478 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2481 TreeSocket* sock = s->GetSocket();
2484 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2485 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2486 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2491 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2496 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2501 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2503 if ((user->fd > -1) && (pcnt > 1))
2505 userrec* remote = Srv->FindNick(parameters[1]);
2506 if ((remote) && (remote->fd < 0))
2508 std::deque<std::string> params;
2509 params.push_back(parameters[1]);
2510 DoOneToOne(user->nick,"IDLE",params,remote->server);
2515 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2516 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2523 void DoPingChecks(time_t curtime)
2525 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2527 TreeServer* serv = TreeRoot->GetChild(j);
2528 TreeSocket* sock = serv->GetSocket();
2531 if (curtime >= serv->NextPingTime())
2533 if (serv->AnsweredLastPing())
2535 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2536 serv->SetNextPingTime(curtime + 60);
2540 // they didnt answer, boot them
2541 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2542 sock->Squit(serv,"Ping timeout");
2551 void AutoConnectServers(time_t curtime)
2553 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2555 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2557 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2558 x->NextConnectTime = curtime + x->AutoConnect;
2559 TreeServer* CheckDupe = FindServer(x->Name);
2562 // an autoconnected server is not connected. Check if its time to connect it
2563 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2564 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2565 Srv->AddSocket(newsocket);
2571 int HandleVersion(char** parameters, int pcnt, userrec* user)
2573 // we've already checked if pcnt > 0, so this is safe
2574 TreeServer* found = FindServerMask(parameters[0]);
2577 std::string Version = found->GetVersion();
2578 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2582 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2587 int HandleConnect(char** parameters, int pcnt, userrec* user)
2589 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2591 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2593 TreeServer* CheckDupe = FindServer(x->Name);
2596 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);
2597 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2598 Srv->AddSocket(newsocket);
2603 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());
2608 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2612 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2614 if (*parameters[0] == 'c')
2616 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2618 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %s",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? "es" : " s"));
2619 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2621 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2622 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2628 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2630 if (command == "CONNECT")
2632 return this->HandleConnect(parameters,pcnt,user);
2634 else if (command == "SQUIT")
2636 return this->HandleSquit(parameters,pcnt,user);
2638 else if (command == "STATS")
2640 return this->HandleStats(parameters,pcnt,user);
2642 else if (command == "MAP")
2644 this->HandleMap(parameters,pcnt,user);
2647 else if (command == "LUSERS")
2649 this->HandleLusers(parameters,pcnt,user);
2652 else if (command == "LINKS")
2654 this->HandleLinks(parameters,pcnt,user);
2657 else if (command == "WHOIS")
2662 return this->HandleRemoteWhois(parameters,pcnt,user);
2665 else if ((command == "VERSION") && (pcnt > 0))
2667 this->HandleVersion(parameters,pcnt,user);
2670 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2672 // this bit of code cleverly routes all module commands
2673 // to all remote severs *automatically* so that modules
2674 // can just handle commands locally, without having
2675 // to have any special provision in place for remote
2676 // commands and linking protocols.
2677 std::deque<std::string> params;
2679 for (int j = 0; j < pcnt; j++)
2681 if (strchr(parameters[j],' '))
2683 params.push_back(":" + std::string(parameters[j]));
2687 params.push_back(std::string(parameters[j]));
2690 DoOneToMany(user->nick,command,params);
2695 virtual void OnGetServerDescription(std::string servername,std::string &description)
2697 TreeServer* s = FindServer(servername);
2700 description = s->GetDesc();
2704 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2706 if (source->fd > -1)
2708 std::deque<std::string> params;
2709 params.push_back(dest->nick);
2710 params.push_back(channel->name);
2711 DoOneToMany(source->nick,"INVITE",params);
2715 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2717 std::deque<std::string> params;
2718 params.push_back(chan->name);
2719 params.push_back(":"+topic);
2720 DoOneToMany(user->nick,"TOPIC",params);
2723 virtual void OnWallops(userrec* user, std::string text)
2727 std::deque<std::string> params;
2728 params.push_back(":"+text);
2729 DoOneToMany(user->nick,"WALLOPS",params);
2733 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2735 if (target_type == TYPE_USER)
2737 userrec* d = (userrec*)dest;
2738 if ((d->fd < 0) && (user->fd > -1))
2740 std::deque<std::string> params;
2742 params.push_back(d->nick);
2743 params.push_back(":"+text);
2744 DoOneToOne(user->nick,"NOTICE",params,d->server);
2751 chanrec *c = (chanrec*)dest;
2752 std::deque<TreeServer*> list;
2753 GetListOfServersForChannel(c,list);
2754 unsigned int ucount = list.size();
2755 for (unsigned int i = 0; i < ucount; i++)
2757 TreeSocket* Sock = list[i]->GetSocket();
2759 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2765 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2767 if (target_type == TYPE_USER)
2769 // route private messages which are targetted at clients only to the server
2770 // which needs to receive them
2771 userrec* d = (userrec*)dest;
2772 if ((d->fd < 0) && (user->fd > -1))
2774 std::deque<std::string> params;
2776 params.push_back(d->nick);
2777 params.push_back(":"+text);
2778 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2785 chanrec *c = (chanrec*)dest;
2786 std::deque<TreeServer*> list;
2787 GetListOfServersForChannel(c,list);
2788 unsigned int ucount = list.size();
2789 for (unsigned int i = 0; i < ucount; i++)
2791 TreeSocket* Sock = list[i]->GetSocket();
2793 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2799 virtual void OnBackgroundTimer(time_t curtime)
2801 AutoConnectServers(curtime);
2802 DoPingChecks(curtime);
2805 virtual void OnUserJoin(userrec* user, chanrec* channel)
2807 // Only do this for local users
2810 std::deque<std::string> params;
2812 params.push_back(channel->name);
2815 // if the channel has a key, force the join by emulating the key.
2816 params.push_back(channel->key);
2818 if (channel->GetUserCounter() > 1)
2820 // not the first in the channel
2821 DoOneToMany(user->nick,"JOIN",params);
2825 // first in the channel, set up their permissions
2826 // and the channel TS with FJOIN.
2828 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2830 params.push_back(channel->name);
2831 params.push_back(ts);
2832 params.push_back("@"+std::string(user->nick));
2833 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2838 virtual void OnChangeHost(userrec* user, std::string newhost)
2840 // only occurs for local clients
2841 if (user->registered != 7)
2843 std::deque<std::string> params;
2844 params.push_back(newhost);
2845 DoOneToMany(user->nick,"FHOST",params);
2848 virtual void OnChangeName(userrec* user, std::string gecos)
2850 // only occurs for local clients
2851 if (user->registered != 7)
2853 std::deque<std::string> params;
2854 params.push_back(gecos);
2855 DoOneToMany(user->nick,"FNAME",params);
2858 virtual void OnUserPart(userrec* user, chanrec* channel)
2862 std::deque<std::string> params;
2863 params.push_back(channel->name);
2864 DoOneToMany(user->nick,"PART",params);
2868 virtual void OnUserConnect(userrec* user)
2870 char agestr[MAXBUF];
2873 std::deque<std::string> params;
2874 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2875 params.push_back(agestr);
2876 params.push_back(user->nick);
2877 params.push_back(user->host);
2878 params.push_back(user->dhost);
2879 params.push_back(user->ident);
2880 params.push_back("+"+std::string(user->modes));
2881 params.push_back(user->ip);
2882 params.push_back(":"+std::string(user->fullname));
2883 DoOneToMany(Srv->GetServerName(),"NICK",params);
2887 virtual void OnUserQuit(userrec* user, std::string reason)
2889 if ((user->fd > -1) && (user->registered == 7))
2891 std::deque<std::string> params;
2892 params.push_back(":"+reason);
2893 DoOneToMany(user->nick,"QUIT",params);
2897 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2901 std::deque<std::string> params;
2902 params.push_back(user->nick);
2903 DoOneToMany(oldnick,"NICK",params);
2907 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2909 if (source->fd > -1)
2911 std::deque<std::string> params;
2912 params.push_back(chan->name);
2913 params.push_back(user->nick);
2914 params.push_back(":"+reason);
2915 DoOneToMany(source->nick,"KICK",params);
2919 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2921 std::deque<std::string> params;
2922 params.push_back(dest->nick);
2923 params.push_back(":"+reason);
2924 DoOneToMany(source->nick,"KILL",params);
2927 virtual void OnRehash(std::string parameter)
2929 if (parameter != "")
2931 std::deque<std::string> params;
2932 params.push_back(parameter);
2933 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2935 if (Srv->MatchText(Srv->GetServerName(),parameter))
2937 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2938 Srv->RehashServer();
2941 ReadConfiguration(false);
2944 // note: the protocol does not allow direct umode +o except
2945 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2947 virtual void OnOper(userrec* user, std::string opertype)
2951 std::deque<std::string> params;
2952 params.push_back(opertype);
2953 DoOneToMany(user->nick,"OPERTYPE",params);
2957 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2959 if (source->fd > -1)
2962 snprintf(type,8,"%cLINE",linetype);
2963 std::string stype = type;
2966 char sduration[MAXBUF];
2967 snprintf(sduration,MAXBUF,"%ld",duration);
2968 std::deque<std::string> params;
2969 params.push_back(host);
2970 params.push_back(sduration);
2971 params.push_back(":"+reason);
2972 DoOneToMany(source->nick,stype,params);
2976 std::deque<std::string> params;
2977 params.push_back(host);
2978 DoOneToMany(source->nick,stype,params);
2983 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2985 OnLine(source,hostmask,true,'G',duration,reason);
2988 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2990 OnLine(source,ipmask,true,'Z',duration,reason);
2993 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2995 OnLine(source,nickmask,true,'Q',duration,reason);
2998 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3000 OnLine(source,hostmask,true,'E',duration,reason);
3003 virtual void OnDelGLine(userrec* source, std::string hostmask)
3005 OnLine(source,hostmask,false,'G',0,"");
3008 virtual void OnDelZLine(userrec* source, std::string ipmask)
3010 OnLine(source,ipmask,false,'Z',0,"");
3013 virtual void OnDelQLine(userrec* source, std::string nickmask)
3015 OnLine(source,nickmask,false,'Q',0,"");
3018 virtual void OnDelELine(userrec* source, std::string hostmask)
3020 OnLine(source,hostmask,false,'E',0,"");
3023 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3025 if ((user->fd > -1) && (user->registered == 7))
3027 if (target_type == TYPE_USER)
3029 userrec* u = (userrec*)dest;
3030 std::deque<std::string> params;
3031 params.push_back(u->nick);
3032 params.push_back(text);
3033 DoOneToMany(user->nick,"MODE",params);
3037 chanrec* c = (chanrec*)dest;
3038 std::deque<std::string> params;
3039 params.push_back(c->name);
3040 params.push_back(text);
3041 DoOneToMany(user->nick,"MODE",params);
3046 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3048 TreeSocket* s = (TreeSocket*)opaque;
3051 if (target_type == TYPE_USER)
3053 userrec* u = (userrec*)target;
3054 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3058 chanrec* c = (chanrec*)target;
3059 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3064 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3066 TreeSocket* s = (TreeSocket*)opaque;
3069 if (target_type == TYPE_USER)
3071 userrec* u = (userrec*)target;
3072 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3076 chanrec* c = (chanrec*)target;
3077 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3082 virtual ~ModuleSpanningTree()
3086 virtual Version GetVersion()
3088 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3093 class ModuleSpanningTreeFactory : public ModuleFactory
3096 ModuleSpanningTreeFactory()
3100 ~ModuleSpanningTreeFactory()
3104 virtual Module * CreateModule(Server* Me)
3106 TreeProtocolModule = new ModuleSpanningTree(Me);
3107 return TreeProtocolModule;
3113 extern "C" void * init_module( void )
3115 return new ModuleSpanningTreeFactory;