1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
25 #include "inspircd_config.h"
27 #include <ext/hash_map>
36 #include "helperfuncs.h"
38 #include "inspstring.h"
43 #include "cull_list.h"
47 #define nspace __gnu_cxx
53 * The server list in InspIRCd is maintained as two structures
54 * which hold the data in different ways. Most of the time, we
55 * want to very quicky obtain three pieces of information:
57 * (1) The information on a server
58 * (2) The information on the server we must send data through
59 * to actually REACH the server we're after
60 * (3) Potentially, the child/parent objects of this server
62 * The InspIRCd spanning protocol provides easy access to these
63 * by storing the data firstly in a recursive structure, where
64 * each item references its parent item, and a dynamic list
65 * of child items, and another structure which stores the items
66 * hashed, linearly. This means that if we want to find a server
67 * by name quickly, we can look it up in the hash, avoiding
68 * any O(n) lookups. If however, during a split or sync, we want
69 * to apply an operation to a server, and any of its child objects
70 * we can resort to recursion to walk the tree structure.
73 class ModuleSpanningTree;
74 static ModuleSpanningTree* TreeProtocolModule;
76 extern ServerConfig* Config;
78 extern std::vector<Module*> modules;
79 extern std::vector<ircd_module*> factory;
82 /* Any socket can have one of five states at any one time.
83 * The LISTENER state indicates a socket which is listening
84 * for connections. It cannot receive data itself, only incoming
86 * The CONNECTING state indicates an outbound socket which is
87 * waiting to be writeable.
88 * The WAIT_AUTH_1 state indicates the socket is outbound and
89 * has successfully connected, but has not yet sent and received
91 * The WAIT_AUTH_2 state indicates that the socket is inbound
92 * (allocated by a LISTENER) but has not yet sent and received
94 * The CONNECTED state represents a fully authorized, fully
97 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
99 /* We need to import these from the core for use in netbursts */
100 extern user_hash clientlist;
101 extern chan_hash chanlist;
103 /* Foward declarations */
107 /* This variable represents the root of the server tree
108 * (for all intents and purposes, it's us)
110 TreeServer *TreeRoot;
114 /* This hash_map holds the hash equivalent of the server
115 * tree, used for rapid linear lookups.
117 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
118 server_hash serverlist;
120 /* More forward declarations */
121 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
122 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
123 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
124 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
125 void ReadConfiguration(bool rebind);
127 /* Imported from xline.cpp for use during netburst */
128 extern std::vector<KLine> klines;
129 extern std::vector<GLine> glines;
130 extern std::vector<ZLine> zlines;
131 extern std::vector<QLine> qlines;
132 extern std::vector<ELine> elines;
133 extern std::vector<KLine> pklines;
134 extern std::vector<GLine> pglines;
135 extern std::vector<ZLine> pzlines;
136 extern std::vector<QLine> pqlines;
137 extern std::vector<ELine> pelines;
139 /* Each server in the tree is represented by one class of
140 * type TreeServer. A locally connected TreeServer can
141 * have a class of type TreeSocket associated with it, for
142 * remote servers, the TreeSocket entry will be NULL.
143 * Each server also maintains a pointer to its parent
144 * (NULL if this server is ours, at the top of the tree)
145 * and a pointer to its "Route" (see the comments in the
146 * constructors below), and also a dynamic list of pointers
147 * to its children which can be iterated recursively
148 * if required. Creating or deleting objects of type
149 * TreeServer automatically maintains the hash_map of
150 * TreeServer items, deleting and inserting them as they
151 * are created and destroyed.
156 TreeServer* Parent; /* Parent entry */
157 TreeServer* Route; /* Route entry */
158 std::vector<TreeServer*> Children; /* List of child objects */
159 std::string ServerName; /* Server's name */
160 std::string ServerDesc; /* Server's description */
161 std::string VersionString; /* Version string or empty string */
162 int UserCount; /* Not used in this version */
163 int OperCount; /* Not used in this version */
164 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
165 time_t NextPing; /* After this time, the server should be PINGed*/
166 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
170 /* We don't use this constructor. Its a dummy, and won't cause any insertion
171 * of the TreeServer into the hash_map. See below for the two we DO use.
179 UserCount = OperCount = 0;
180 VersionString = Srv->GetVersion();
183 /* We use this constructor only to create the 'root' item, TreeRoot, which
184 * represents our own server. Therefore, it has no route, no parent, and
185 * no socket associated with it. Its version string is our own local version.
187 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
191 UserCount = OperCount = 0;
192 VersionString = Srv->GetVersion();
194 Socket = NULL; /* Fix by brain */
198 /* When we create a new server, we call this constructor to initialize it.
199 * This constructor initializes the server's Route and Parent, and sets up
200 * its ping counters so that it will be pinged one minute from now.
202 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
205 UserCount = OperCount = 0;
206 this->SetNextPingTime(time(NULL) + 60);
209 /* find the 'route' for this server (e.g. the one directly connected
210 * to the local server, which we can use to reach it)
212 * In the following example, consider we have just added a TreeServer
213 * class for server G on our network, of which we are server A.
214 * To route traffic to G (marked with a *) we must send the data to
215 * B (marked with a +) so this algorithm initializes the 'Route'
216 * value to point at whichever server traffic must be routed through
217 * to get here. If we were to try this algorithm with server B,
218 * the Route pointer would point at its own object ('this').
228 * We only run this algorithm when a server is created, as
229 * the routes remain constant while ever the server exists, and
230 * do not need to be re-calculated.
234 if (Route == TreeRoot)
240 while (this->Route->GetParent() != TreeRoot)
242 this->Route = Route->GetParent();
246 /* Because recursive code is slow and takes a lot of resources,
247 * we store two representations of the server tree. The first
248 * is a recursive structure where each server references its
249 * children and its parent, which is used for netbursts and
250 * netsplits to dump the whole dataset to the other server,
251 * and the second is used for very fast lookups when routing
252 * messages and is instead a hash_map, where each item can
253 * be referenced by its server name. The AddHashEntry()
254 * call below automatically inserts each TreeServer class
255 * into the hash_map as it is created. There is a similar
256 * maintainance call in the destructor to tidy up deleted
260 this->AddHashEntry();
263 /* This method is used to add the structure to the
264 * hash_map for linear searches. It is only called
265 * by the constructors.
269 server_hash::iterator iter;
270 iter = serverlist.find(this->ServerName);
271 if (iter == serverlist.end())
272 serverlist[this->ServerName] = this;
275 /* This method removes the reference to this object
276 * from the hash_map which is used for linear searches.
277 * It is only called by the default destructor.
281 server_hash::iterator iter;
282 iter = serverlist.find(this->ServerName);
283 if (iter != serverlist.end())
284 serverlist.erase(iter);
287 /* These accessors etc should be pretty self-
291 TreeServer* GetRoute()
296 std::string GetName()
301 std::string GetDesc()
306 std::string GetVersion()
308 return VersionString;
311 void SetNextPingTime(time_t t)
314 LastPingWasGood = false;
317 time_t NextPingTime()
322 bool AnsweredLastPing()
324 return LastPingWasGood;
329 LastPingWasGood = true;
342 TreeSocket* GetSocket()
347 TreeServer* GetParent()
352 void SetVersion(std::string Version)
354 VersionString = Version;
357 unsigned int ChildCount()
359 return Children.size();
362 TreeServer* GetChild(unsigned int n)
364 if (n < Children.size())
366 /* Make sure they cant request
367 * an out-of-range object. After
368 * all we know what these programmer
369 * types are like *grin*.
379 void AddChild(TreeServer* Child)
381 Children.push_back(Child);
384 bool DelChild(TreeServer* Child)
386 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
397 /* Removes child nodes of this node, and of that node, etc etc.
398 * This is used during netsplits to automatically tidy up the
399 * server tree. It is slow, we don't use it for much else.
403 bool stillchildren = true;
404 while (stillchildren)
406 stillchildren = false;
407 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
409 TreeServer* s = (TreeServer*)*a;
413 stillchildren = true;
422 /* We'd better tidy up after ourselves, eh? */
423 this->DelHashEntry();
427 /* The Link class might as well be a struct,
428 * but this is C++ and we don't believe in structs (!).
429 * It holds the entire information of one <link>
430 * tag from the main config file. We maintain a list
431 * of them, and populate the list on rehash/load.
440 std::string SendPass;
441 std::string RecvPass;
442 unsigned long AutoConnect;
443 time_t NextConnectTime;
444 std::string EncryptionKey;
447 /* The usual stuff for inspircd modules,
448 * plus the vector of Link classes which we
449 * use to store the <link> tags from the config
453 std::vector<Link> LinkBlocks;
455 /* Yay for fast searches!
456 * This is hundreds of times faster than recursion
457 * or even scanning a linked list, especially when
458 * there are more than a few servers to deal with.
461 TreeServer* FindServer(std::string ServerName)
463 server_hash::iterator iter;
464 iter = serverlist.find(ServerName);
465 if (iter != serverlist.end())
475 /* Returns the locally connected server we must route a
476 * message through to reach server 'ServerName'. This
477 * only applies to one-to-one and not one-to-many routing.
478 * See the comments for the constructor of TreeServer
481 TreeServer* BestRouteTo(std::string ServerName)
483 if (ServerName.c_str() == TreeRoot->GetName())
485 TreeServer* Found = FindServer(ServerName);
488 return Found->GetRoute();
496 /* Find the first server matching a given glob mask.
497 * Theres no find-using-glob method of hash_map [awwww :-(]
498 * so instead, we iterate over the list using an iterator
499 * and match each one until we get a hit. Yes its slow,
502 TreeServer* FindServerMask(std::string ServerName)
504 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
506 if (Srv->MatchText(i->first,ServerName))
512 /* A convenient wrapper that returns true if a server exists */
513 bool IsServer(std::string ServerName)
515 return (FindServer(ServerName) != NULL);
518 /* Every SERVER connection inbound or outbound is represented by
519 * an object of type TreeSocket.
520 * TreeSockets, being inherited from InspSocket, can be tied into
521 * the core socket engine, and we cn therefore receive activity events
522 * for them, just like activex objects on speed. (yes really, that
523 * is a technical term!) Each of these which relates to a locally
524 * connected server is assocated with it, by hooking it onto a
525 * TreeSocket class using its constructor. In this way, we can
526 * maintain a list of servers, some of which are directly connected,
527 * some of which are not.
530 class TreeSocket : public InspSocket
533 std::string in_buffer;
534 ServerState LinkState;
535 std::string InboundServerName;
536 std::string InboundDescription;
538 int num_lost_servers;
540 bool LastPingWasGood;
544 unsigned int keylength;
548 /* Because most of the I/O gubbins are encapsulated within
549 * InspSocket, we just call the superclass constructor for
550 * most of the action, and append a few of our own values
553 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
554 : InspSocket(host, port, listening, maxtime)
557 this->LinkState = LISTENER;
559 this->ctx_out = NULL;
562 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
563 : InspSocket(host, port, listening, maxtime)
566 this->LinkState = CONNECTING;
568 this->ctx_out = NULL;
571 /* When a listening socket gives us a new file descriptor,
572 * we must associate it with a socket without creating a new
573 * connection. This constructor is used for this purpose.
575 TreeSocket(int newfd, char* ip)
576 : InspSocket(newfd, ip)
578 this->LinkState = WAIT_AUTH_1;
580 this->ctx_out = NULL;
581 this->SendCapabilities();
592 void InitAES(std::string key,std::string SName)
599 log(DEBUG,"Initialized AES key %s",key.c_str());
600 // key must be 16, 24, 32 etc bytes (multiple of 8)
601 keylength = key.length();
602 if (!(keylength == 16 || keylength == 24 || keylength == 32))
604 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
605 log(DEBUG,"Key length not 16, 24 or 32 characters!");
609 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
610 ctx_in->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
611 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
612 ctx_out->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
613 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
617 /* When an outbound connection finishes connecting, we receive
618 * this event, and must send our SERVER string to the other
619 * side. If the other side is happy, as outlined in the server
620 * to server docs on the inspircd.org site, the other side
621 * will then send back its own server string.
623 virtual bool OnConnected()
625 if (this->LinkState == CONNECTING)
627 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
628 /* we do not need to change state here. */
629 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
631 if (x->Name == this->myhost)
633 this->SendCapabilities();
634 if (x->EncryptionKey != "")
636 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
638 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
642 this->WriteLine("AES "+Srv->GetServerName());
643 this->InitAES(x->EncryptionKey,x->Name);
646 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
647 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
652 /* There is a (remote) chance that between the /CONNECT and the connection
653 * being accepted, some muppet has removed the <link> block and rehashed.
654 * If that happens the connection hangs here until it's closed. Unlikely
655 * and rather harmless.
660 virtual void OnError(InspSocketError e)
662 /* We don't handle this method, because all our
663 * dirty work is done in OnClose() (see below)
664 * which is still called on error conditions too.
668 virtual int OnDisconnect()
670 /* For the same reason as above, we don't
671 * handle OnDisconnect()
676 /* Recursively send the server tree with distances as hops.
677 * This is used during network burst to inform the other server
678 * (and any of ITS servers too) of what servers we know about.
679 * If at any point any of these servers already exist on the other
680 * end, our connection may be terminated. The hopcounts given
681 * by this function are relative, this doesn't matter so long as
682 * they are all >1, as all the remote servers re-calculate them
683 * to be relative too, with themselves as hop 0.
685 void SendServers(TreeServer* Current, TreeServer* s, int hops)
688 for (unsigned int q = 0; q < Current->ChildCount(); q++)
690 TreeServer* recursive_server = Current->GetChild(q);
691 if (recursive_server != s)
693 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
694 this->WriteLine(command);
695 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
696 /* down to next level */
697 this->SendServers(recursive_server, s, hops+1);
702 std::string MyCapabilities()
704 ServerConfig* Config = Srv->GetConfig();
705 std::vector<std::string> modlist;
706 std::string capabilities = "";
708 for (int i = 0; i <= MODCOUNT; i++)
710 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
711 modlist.push_back(Config->module_names[i]);
713 sort(modlist.begin(),modlist.end());
714 for (unsigned int i = 0; i < modlist.size(); i++)
717 capabilities = capabilities + ",";
718 capabilities = capabilities + modlist[i];
723 void SendCapabilities()
725 this->WriteLine("CAPAB "+MyCapabilities());
728 bool Capab(std::deque<std::string> params)
730 if (params.size() != 1)
732 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
735 if (params[0] != this->MyCapabilities())
737 std::string quitserver = this->myhost;
738 if (this->InboundServerName != "")
740 quitserver = this->InboundServerName;
742 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
743 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
744 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
745 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
746 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
752 /* This function forces this server to quit, removing this server
753 * and any users on it (and servers and users below that, etc etc).
754 * It's very slow and pretty clunky, but luckily unless your network
755 * is having a REAL bad hair day, this function shouldnt be called
756 * too many times a month ;-)
758 void SquitServer(TreeServer* Current, CullList* Goners)
760 /* recursively squit the servers attached to 'Current'.
761 * We're going backwards so we don't remove users
762 * while we still need them ;)
764 for (unsigned int q = 0; q < Current->ChildCount(); q++)
766 TreeServer* recursive_server = Current->GetChild(q);
767 this->SquitServer(recursive_server,Goners);
769 /* Now we've whacked the kids, whack self */
771 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
773 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
775 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
776 Goners->AddItem(u->second,qreason);
782 /* This is a wrapper function for SquitServer above, which
783 * does some validation first and passes on the SQUIT to all
784 * other remaining servers.
786 void Squit(TreeServer* Current,std::string reason)
788 if ((Current) && (Current != TreeRoot))
790 std::deque<std::string> params;
791 params.push_back(Current->GetName());
792 params.push_back(":"+reason);
793 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
794 if (Current->GetParent() == TreeRoot)
796 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
800 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
802 num_lost_servers = 0;
804 CullList* Goners = new CullList();
805 SquitServer(Current, Goners);
808 Current->GetParent()->DelChild(Current);
811 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
815 log(DEFAULT,"Squit from unknown server");
820 bool ForceMode(std::string source, std::deque<std::string> params)
822 userrec* who = new userrec;
823 who->fd = FD_MAGIC_NUMBER;
824 if (params.size() < 2)
827 for (unsigned int q = 0; q < params.size(); q++)
829 modelist[q] = (char*)params[q].c_str();
831 Srv->SendMode(modelist,params.size(),who);
832 DoOneToAllButSender(source,"FMODE",params,source);
838 bool ForceTopic(std::string source, std::deque<std::string> params)
840 if (params.size() != 4)
842 std::string channel = params[0];
843 time_t ts = atoi(params[1].c_str());
844 std::string setby = params[2];
845 std::string topic = params[3];
847 chanrec* c = Srv->FindChannel(channel);
850 if ((ts >= c->topicset) || (!*c->topic))
852 std::string oldtopic = c->topic;
853 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
854 strlcpy(c->setby,setby.c_str(),NICKMAX);
856 /* if the topic text is the same as the current topic,
857 * dont bother to send the TOPIC command out, just silently
858 * update the set time and set nick.
860 if (oldtopic != topic)
861 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
866 /* all done, send it on its way */
867 params[3] = ":" + params[3];
868 DoOneToAllButSender(source,"FTOPIC",params,source);
873 /* FJOIN, similar to unreal SJOIN */
874 bool ForceJoin(std::string source, std::deque<std::string> params)
876 if (params.size() < 3)
880 char modestring[MAXBUF];
881 char* mode_users[127];
882 mode_users[0] = first;
883 mode_users[1] = modestring;
884 strcpy(mode_users[1],"+");
885 unsigned int modectr = 2;
888 std::string channel = params[0];
889 time_t TS = atoi(params[1].c_str());
892 chanrec* chan = Srv->FindChannel(channel);
897 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
899 /* default is a high value, which if we dont have this
900 * channel will let the other side apply their modes.
902 time_t ourTS = time(NULL)+600;
903 chanrec* us = Srv->FindChannel(channel);
909 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
911 /* do this first, so our mode reversals are correctly received by other servers
912 * if there is a TS collision.
914 DoOneToAllButSender(source,"FJOIN",params,source);
916 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
918 /* process one channel at a time, applying modes. */
919 char* usr = (char*)params[usernum].c_str();
920 char permissions = *usr;
925 mode_users[modectr++] = usr;
926 strlcat(modestring,"o",MAXBUF);
930 mode_users[modectr++] = usr;
931 strlcat(modestring,"h",MAXBUF);
935 mode_users[modectr++] = usr;
936 strlcat(modestring,"v",MAXBUF);
939 who = Srv->FindNick(usr);
942 Srv->JoinUserToChannel(who,channel,key);
943 if (modectr >= (MAXMODES-1))
945 /* theres a mode for this user. push them onto the mode queue, and flush it
946 * if there are more than MAXMODES to go.
948 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
950 /* We also always let u-lined clients win, no matter what the TS value */
951 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
952 Srv->SendMode(mode_users,modectr,who);
956 log(DEBUG,"Their channel newer than ours, bouncing their modes");
958 std::deque<std::string> params;
959 /* modes are now being UNSET... */
960 *mode_users[1] = '-';
961 for (unsigned int x = 0; x < modectr; x++)
963 params.push_back(mode_users[x]);
965 // tell everyone to bounce the modes. bad modes, bad!
966 DoOneToMany(Srv->GetServerName(),"FMODE",params);
968 strcpy(mode_users[1],"+");
973 /* there werent enough modes built up to flush it during FJOIN,
974 * or, there are a number left over. flush them out.
976 if ((modectr > 2) && (who))
980 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
981 Srv->SendMode(mode_users,modectr,who);
985 log(DEBUG,"Their channel newer than ours, bouncing their modes");
986 std::deque<std::string> params;
987 *mode_users[1] = '-';
988 for (unsigned int x = 0; x < modectr; x++)
990 params.push_back(mode_users[x]);
992 DoOneToMany(Srv->GetServerName(),"FMODE",params);
999 bool IntroduceClient(std::string source, std::deque<std::string> params)
1001 if (params.size() < 8)
1003 // NICK age nick host dhost ident +modes ip :gecos
1005 std::string nick = params[1];
1006 std::string host = params[2];
1007 std::string dhost = params[3];
1008 std::string ident = params[4];
1009 time_t age = atoi(params[0].c_str());
1010 std::string modes = params[5];
1011 while (*(modes.c_str()) == '+')
1013 char* m = (char*)modes.c_str();
1017 std::string ip = params[6];
1018 std::string gecos = params[7];
1019 char* tempnick = (char*)nick.c_str();
1020 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1022 user_hash::iterator iter;
1023 iter = clientlist.find(tempnick);
1024 if (iter != clientlist.end())
1027 log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,ident.c_str(),host.c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1028 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1032 clientlist[tempnick] = new userrec();
1033 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1034 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1035 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1036 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1037 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1038 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1039 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1040 clientlist[tempnick]->registered = 7;
1041 clientlist[tempnick]->signon = age;
1042 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1043 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1048 for (int i = 0; i < MAXCHANS; i++)
1049 clientlist[tempnick]->chans.push_back(a);
1051 if (!this->bursting)
1053 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1055 params[7] = ":" + params[7];
1056 DoOneToAllButSender(source,"NICK",params,source);
1060 /* Send one or more FJOINs for a channel of users.
1061 * If the length of a single line is more than 480-NICKMAX
1062 * in length, it is split over multiple lines.
1064 void SendFJoins(TreeServer* Current, chanrec* c)
1066 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1068 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1069 std::vector<char*> *ulist = c->GetUsers();
1070 for (unsigned int i = 0; i < ulist->size(); i++)
1072 char* o = (*ulist)[i];
1073 userrec* otheruser = (userrec*)o;
1074 strlcat(list," ",MAXBUF);
1075 strlcat(list,cmode(otheruser,c),MAXBUF);
1076 strlcat(list,otheruser->nick,MAXBUF);
1077 if (strlen(list)>(480-NICKMAX))
1079 log(DEBUG,"FJOIN line wrapped");
1080 this->WriteLine(list);
1081 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1084 if (list[strlen(list)-1] != ':')
1086 log(DEBUG,"Final FJOIN line");
1087 this->WriteLine(list);
1091 /* Send G, Q, Z and E lines */
1092 void SendXLines(TreeServer* Current)
1095 /* Yes, these arent too nice looking, but they get the job done */
1096 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1098 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1099 this->WriteLine(data);
1101 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1103 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1104 this->WriteLine(data);
1106 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1108 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1109 this->WriteLine(data);
1111 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1113 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1114 this->WriteLine(data);
1116 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1118 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1119 this->WriteLine(data);
1121 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1123 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1124 this->WriteLine(data);
1126 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1128 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1129 this->WriteLine(data);
1131 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1133 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1134 this->WriteLine(data);
1138 /* Send channel modes and topics */
1139 void SendChannelModes(TreeServer* Current)
1142 std::deque<std::string> list;
1143 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1145 SendFJoins(Current, c->second);
1146 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1147 this->WriteLine(data);
1148 if (*c->second->topic)
1150 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",Srv->GetServerName().c_str(),c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1151 this->WriteLine(data);
1153 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1155 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1156 this->WriteLine(data);
1158 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1160 c->second->GetExtList(list);
1161 for (unsigned int j = 0; j < list.size(); j++)
1163 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1168 /* send all users and their oper state/modes */
1169 void SendUsers(TreeServer* Current)
1172 std::deque<std::string> list;
1173 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1175 if (u->second->registered == 7)
1177 snprintf(data,MAXBUF,":%s NICK %lu %s %s %s %s +%s %s :%s",u->second->server,(unsigned long)u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->fullname);
1178 this->WriteLine(data);
1179 if (strchr(u->second->modes,'o'))
1181 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1183 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1185 u->second->GetExtList(list);
1186 for (unsigned int j = 0; j < list.size(); j++)
1188 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1194 /* This function is called when we want to send a netburst to a local
1195 * server. There is a set order we must do this, because for example
1196 * users require their servers to exist, and channels require their
1197 * users to exist. You get the idea.
1199 void DoBurst(TreeServer* s)
1201 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1202 this->WriteLine("BURST");
1203 /* send our version string */
1204 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1205 /* Send server tree */
1206 this->SendServers(TreeRoot,s,1);
1207 /* Send users and their oper status */
1209 /* Send everything else (channel modes, xlines etc) */
1210 this->SendChannelModes(s);
1211 this->SendXLines(s);
1212 this->WriteLine("ENDBURST");
1213 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1216 /* This function is called when we receive data from a remote
1217 * server. We buffer the data in a std::string (it doesnt stay
1218 * there for long), reading using InspSocket::Read() which can
1219 * read up to 16 kilobytes in one operation.
1221 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1222 * THE SOCKET OBJECT FOR US.
1224 virtual bool OnDataReady()
1226 char* data = this->Read();
1229 this->in_buffer += data;
1230 /* While there is at least one new line in the buffer,
1231 * do something useful (we hope!) with it.
1233 while (in_buffer.find("\n") != std::string::npos)
1235 char* line = (char*)in_buffer.c_str();
1236 std::string ret = "";
1237 while ((*line != '\n') && (strlen(line)))
1242 if ((*line == '\n') || (*line == '\r'))
1245 /* Process this one, abort if it
1246 * didnt return true.
1252 memset(result,0,1024);
1254 log(DEBUG,"Original string '%s'",ret.c_str());
1255 /* ERROR + CAPAB is still allowed unencryped */
1256 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1258 int nbytes = from64tobits(out, ret.c_str(), 1024);
1259 if ((nbytes > 0) && (nbytes < 1024))
1261 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1262 ctx_in->Decrypt(out, result, nbytes, 1);
1263 for (int t = 0; t < nbytes; t++)
1264 if (result[t] == '\7') result[t] = 0;
1269 if (!this->ProcessLine(ret))
1275 return (data != NULL);
1278 int WriteLine(std::string line)
1280 log(DEBUG,"OUT: %s",line.c_str());
1283 log(DEBUG,"AES context");
1285 char result64[10240];
1286 if (this->keylength)
1288 while (line.length() % this->keylength != 0)
1290 // pad it to be a multiple of the key length
1294 unsigned int ll = line.length();
1295 log(DEBUG,"Plaintext line with padding = %d chars",ll);
1296 ctx_out->Encrypt(line.c_str(), result, ll, 1);
1297 log(DEBUG,"Encrypted.");
1298 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1300 log(DEBUG,"Encrypted: %s",line.c_str());
1301 //int from64tobits(char *out, const char *in, int maxlen);
1303 return this->Write(line + "\r\n");
1306 /* Handle ERROR command */
1307 bool Error(std::deque<std::string> params)
1309 if (params.size() < 1)
1311 std::string Errmsg = params[0];
1312 std::string SName = myhost;
1313 if (InboundServerName != "")
1315 SName = InboundServerName;
1317 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1318 /* we will return false to cause the socket to close.
1323 /* Because the core won't let users or even SERVERS set +o,
1324 * we use the OPERTYPE command to do this.
1326 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1328 if (params.size() != 1)
1330 std::string opertype = params[0];
1331 userrec* u = Srv->FindNick(prefix);
1334 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1335 if (!strchr(u->modes,'o'))
1337 strcat(u->modes,"o");
1339 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1344 /* Because Andy insists that services-compatible servers must
1345 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1347 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1349 if (params.size() < 3)
1351 userrec* u = Srv->FindNick(params[0]);
1354 Srv->ChangeUserNick(u,params[1]);
1355 u->age = atoi(params[2].c_str());
1356 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1361 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1363 if (params.size() < 2)
1365 userrec* u = Srv->FindNick(params[0]);
1368 Srv->JoinUserToChannel(u,params[1],"");
1369 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1374 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1376 if (params.size() < 1)
1378 std::string servermask = params[0];
1379 if (Srv->MatchText(Srv->GetServerName(),servermask))
1381 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1382 Srv->RehashServer();
1383 ReadConfiguration(false);
1385 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1389 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1391 if (params.size() != 2)
1393 std::string nick = params[0];
1394 userrec* u = Srv->FindNick(prefix);
1395 userrec* who = Srv->FindNick(nick);
1398 /* Prepend kill source, if we don't have one */
1399 std::string sourceserv = prefix;
1402 sourceserv = u->server;
1404 if (*(params[1].c_str()) != '[')
1406 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1408 std::string reason = params[1];
1409 params[1] = ":" + params[1];
1410 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1411 Srv->QuitUser(who,reason);
1416 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1418 if (params.size() < 1)
1420 TreeServer* ServerSource = FindServer(prefix);
1423 ServerSource->SetPingFlag();
1428 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1430 if (params.size() < 3)
1432 TreeServer* ServerSource = FindServer(prefix);
1435 if (*(params[0].c_str()) == '#')
1437 chanrec* c = Srv->FindChannel(params[0]);
1440 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1445 userrec* u = Srv->FindNick(params[0]);
1448 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1452 params[2] = ":" + params[2];
1453 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1457 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1459 if (params.size() < 1)
1461 TreeServer* ServerSource = FindServer(prefix);
1464 ServerSource->SetVersion(params[0]);
1466 params[0] = ":" + params[0];
1467 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1471 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1473 if (params.size() < 1)
1475 userrec* u = Srv->FindNick(prefix);
1478 Srv->ChangeHost(u,params[0]);
1479 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1484 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1486 if (params.size() < 6)
1488 std::string linetype = params[0]; /* Z, Q, E, G, K */
1489 std::string mask = params[1]; /* Line type dependent */
1490 std::string source = params[2]; /* may not be online or may be a server */
1491 std::string settime = params[3]; /* EPOCH time set */
1492 std::string duration = params[4]; /* Duration secs */
1493 std::string reason = params[5];
1495 switch (*(linetype.c_str()))
1498 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1499 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1502 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1503 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1506 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1507 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1510 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1511 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1514 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1517 /* Just in case... */
1518 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1521 /* Send it on its way */
1522 params[5] = ":" + params[5];
1523 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1527 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1529 if (params.size() < 1)
1531 userrec* u = Srv->FindNick(prefix);
1534 Srv->ChangeGECOS(u,params[0]);
1535 params[0] = ":" + params[0];
1536 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1541 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1543 if (params.size() < 1)
1545 log(DEBUG,"In IDLE command");
1546 userrec* u = Srv->FindNick(prefix);
1549 log(DEBUG,"USER EXISTS: %s",u->nick);
1550 // an incoming request
1551 if (params.size() == 1)
1553 userrec* x = Srv->FindNick(params[0]);
1556 userrec* x = Srv->FindNick(params[0]);
1557 log(DEBUG,"Got IDLE");
1558 char signon[MAXBUF];
1560 log(DEBUG,"Sending back IDLE 3");
1561 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1562 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1563 std::deque<std::string> par;
1564 par.push_back(prefix);
1565 par.push_back(signon);
1566 par.push_back(idle);
1567 // ours, we're done, pass it BACK
1568 DoOneToOne(params[0],"IDLE",par,u->server);
1572 // not ours pass it on
1573 DoOneToOne(prefix,"IDLE",params,x->server);
1576 else if (params.size() == 3)
1578 std::string who_did_the_whois = params[0];
1579 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1580 if (who_to_send_to->fd > -1)
1582 log(DEBUG,"Got final IDLE");
1583 // an incoming reply to a whois we sent out
1584 std::string nick_whoised = prefix;
1585 unsigned long signon = atoi(params[1].c_str());
1586 unsigned long idle = atoi(params[2].c_str());
1587 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1588 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1592 // not ours, pass it on
1593 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1600 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1602 if (params.size() < 1)
1604 std::string stufftobounce = params[0];
1605 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1609 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1611 if (params.size() < 4)
1613 std::string servername = params[0];
1614 std::string password = params[1];
1615 // hopcount is not used for a remote server, we calculate this ourselves
1616 std::string description = params[3];
1617 TreeServer* ParentOfThis = FindServer(prefix);
1620 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1623 TreeServer* CheckDupe = FindServer(servername);
1626 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1627 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1630 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1631 ParentOfThis->AddChild(Node);
1632 params[3] = ":" + params[3];
1633 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1634 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1638 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1640 if (params.size() < 4)
1642 std::string servername = params[0];
1643 std::string password = params[1];
1644 int hops = atoi(params[2].c_str());
1647 this->WriteLine("ERROR :Server too far away for authentication");
1648 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1651 std::string description = params[3];
1652 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1654 if ((x->Name == servername) && (x->RecvPass == password))
1656 TreeServer* CheckDupe = FindServer(servername);
1659 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1660 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1663 // Begin the sync here. this kickstarts the
1664 // other side, waiting in WAIT_AUTH_2 state,
1665 // into starting their burst, as it shows
1666 // that we're happy.
1667 this->LinkState = CONNECTED;
1668 // we should add the details of this server now
1669 // to the servers tree, as a child of the root
1671 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1672 TreeRoot->AddChild(Node);
1673 params[3] = ":" + params[3];
1674 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1675 this->bursting = true;
1676 this->DoBurst(Node);
1680 this->WriteLine("ERROR :Invalid credentials");
1681 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1685 bool Inbound_Server(std::deque<std::string> ¶ms)
1687 if (params.size() < 4)
1689 std::string servername = params[0];
1690 std::string password = params[1];
1691 int hops = atoi(params[2].c_str());
1694 this->WriteLine("ERROR :Server too far away for authentication");
1695 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1698 std::string description = params[3];
1699 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1701 if ((x->Name == servername) && (x->RecvPass == password))
1703 TreeServer* CheckDupe = FindServer(servername);
1706 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1707 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1710 /* If the config says this link is encrypted, but the remote side
1711 * hasnt bothered to send the AES command before SERVER, then we
1712 * boot them off as we MUST have this connection encrypted.
1714 if ((x->EncryptionKey != "") && (!this->ctx_in))
1716 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1717 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1720 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1721 this->InboundServerName = servername;
1722 this->InboundDescription = description;
1723 // this is good. Send our details: Our server name and description and hopcount of 0,
1724 // along with the sendpass from this block.
1725 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1726 // move to the next state, we are now waiting for THEM.
1727 this->LinkState = WAIT_AUTH_2;
1731 this->WriteLine("ERROR :Invalid credentials");
1732 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1736 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1738 if (!strchr(line.c_str(),' '))
1743 std::stringstream s(line);
1744 std::string param = "";
1763 if ((param == ":") && (item > 0))
1786 bool ProcessLine(std::string line)
1788 char* l = (char*)line.c_str();
1789 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1790 l[strlen(l)-1] = '\0';
1794 Srv->Log(DEBUG,"IN: "+line);
1795 std::deque<std::string> params;
1796 this->Split(line,true,params);
1797 std::string command = "";
1798 std::string prefix = "";
1799 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1802 command = params[1];
1803 char* pref = (char*)prefix.c_str();
1811 command = params[0];
1815 if ((!this->ctx_in) && (command == "AES"))
1817 std::string sserv = params[0];
1818 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1820 if ((x->EncryptionKey != "") && (x->Name == sserv))
1822 this->InitAES(x->EncryptionKey,sserv);
1827 else if ((this->ctx_in) && (command == "AES"))
1829 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1832 switch (this->LinkState)
1837 // Waiting for SERVER command from remote server. Server initiating
1838 // the connection sends the first SERVER command, listening server
1839 // replies with theirs if its happy, then if the initiator is happy,
1840 // it starts to send its net sync, which starts the merge, otherwise
1841 // it sends an ERROR.
1842 if (command == "PASS")
1844 /* Silently ignored */
1846 else if (command == "SERVER")
1848 return this->Inbound_Server(params);
1850 else if (command == "ERROR")
1852 return this->Error(params);
1854 else if (command == "USER")
1856 this->WriteLine("ERROR :Client connections to this port are prohibited.");
1859 else if (command == "CAPAB")
1861 return this->Capab(params);
1865 this->WriteLine("ERROR :Invalid command in negotiation phase.");
1870 // Waiting for start of other side's netmerge to say they liked our
1872 if (command == "SERVER")
1874 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1878 else if (command == "BURST")
1880 this->LinkState = CONNECTED;
1881 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1882 TreeRoot->AddChild(Node);
1884 params.push_back(InboundServerName);
1885 params.push_back("*");
1886 params.push_back("1");
1887 params.push_back(":"+InboundDescription);
1888 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1889 this->bursting = true;
1890 this->DoBurst(Node);
1892 else if (command == "ERROR")
1894 return this->Error(params);
1896 else if (command == "CAPAB")
1898 return this->Capab(params);
1903 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1907 if (command == "SERVER")
1909 // another server we connected to, which was in WAIT_AUTH_1 state,
1910 // has just sent us their credentials. If we get this far, theyre
1911 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1912 // if we're happy with this, we should send our netburst which
1913 // kickstarts the merge.
1914 return this->Outbound_Reply_Server(params);
1916 else if (command == "ERROR")
1918 return this->Error(params);
1922 // This is the 'authenticated' state, when all passwords
1923 // have been exchanged and anything past this point is taken
1928 std::string direction = prefix;
1929 userrec* t = Srv->FindNick(prefix);
1932 direction = t->server;
1934 TreeServer* route_back_again = BestRouteTo(direction);
1935 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1937 if (route_back_again)
1938 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1943 if (command == "SVSMODE")
1945 /* Services expects us to implement
1946 * SVSMODE. In inspircd its the same as
1951 std::string target = "";
1952 /* Yes, know, this is a mess. Its reasonably fast though as we're
1953 * working with std::string here.
1955 if ((command == "NICK") && (params.size() > 1))
1957 return this->IntroduceClient(prefix,params);
1959 else if (command == "FJOIN")
1961 return this->ForceJoin(prefix,params);
1963 else if (command == "SERVER")
1965 return this->RemoteServer(prefix,params);
1967 else if (command == "ERROR")
1969 return this->Error(params);
1971 else if (command == "OPERTYPE")
1973 return this->OperType(prefix,params);
1975 else if (command == "FMODE")
1977 return this->ForceMode(prefix,params);
1979 else if (command == "KILL")
1981 return this->RemoteKill(prefix,params);
1983 else if (command == "FTOPIC")
1985 return this->ForceTopic(prefix,params);
1987 else if (command == "REHASH")
1989 return this->RemoteRehash(prefix,params);
1991 else if (command == "METADATA")
1993 return this->MetaData(prefix,params);
1995 else if (command == "PING")
1997 return this->LocalPing(prefix,params);
1999 else if (command == "PONG")
2001 return this->LocalPong(prefix,params);
2003 else if (command == "VERSION")
2005 return this->ServerVersion(prefix,params);
2007 else if (command == "FHOST")
2009 return this->ChangeHost(prefix,params);
2011 else if (command == "FNAME")
2013 return this->ChangeName(prefix,params);
2015 else if (command == "ADDLINE")
2017 return this->AddLine(prefix,params);
2019 else if (command == "SVSNICK")
2023 prefix = this->GetName();
2025 return this->ForceNick(prefix,params);
2027 else if (command == "IDLE")
2029 return this->Whois(prefix,params);
2031 else if (command == "SVSJOIN")
2035 prefix = this->GetName();
2037 return this->ServiceJoin(prefix,params);
2039 else if (command == "SQUIT")
2041 if (params.size() == 2)
2043 this->Squit(FindServer(params[0]),params[1]);
2047 else if (command == "ENDBURST")
2049 this->bursting = false;
2054 // not a special inter-server command.
2055 // Emulate the actual user doing the command,
2056 // this saves us having a huge ugly parser.
2057 userrec* who = Srv->FindNick(prefix);
2058 std::string sourceserv = this->myhost;
2059 if (this->InboundServerName != "")
2061 sourceserv = this->InboundServerName;
2066 target = who->server;
2067 char* strparams[127];
2068 for (unsigned int q = 0; q < params.size(); q++)
2070 strparams[q] = (char*)params[q].c_str();
2072 Srv->CallCommandHandler(command, strparams, params.size(), who);
2076 // its not a user. Its either a server, or somethings screwed up.
2077 if (IsServer(prefix))
2079 target = Srv->GetServerName();
2083 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2087 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2096 virtual std::string GetName()
2098 std::string sourceserv = this->myhost;
2099 if (this->InboundServerName != "")
2101 sourceserv = this->InboundServerName;
2106 virtual void OnTimeout()
2108 if (this->LinkState == CONNECTING)
2110 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2114 virtual void OnClose()
2116 // Connection closed.
2117 // If the connection is fully up (state CONNECTED)
2118 // then propogate a netsplit to all peers.
2119 std::string quitserver = this->myhost;
2120 if (this->InboundServerName != "")
2122 quitserver = this->InboundServerName;
2124 TreeServer* s = FindServer(quitserver);
2127 Squit(s,"Remote host closed the connection");
2129 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2132 virtual int OnIncomingConnection(int newsock, char* ip)
2134 TreeSocket* s = new TreeSocket(newsock, ip);
2140 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2142 for (unsigned int c = 0; c < list.size(); c++)
2144 if (list[c] == server)
2149 list.push_back(server);
2152 // returns a list of DIRECT servernames for a specific channel
2153 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2155 std::vector<char*> *ulist = c->GetUsers();
2156 unsigned int ucount = ulist->size();
2157 for (unsigned int i = 0; i < ucount; i++)
2159 char* o = (*ulist)[i];
2160 userrec* otheruser = (userrec*)o;
2161 if (otheruser->fd < 0)
2163 TreeServer* best = BestRouteTo(otheruser->server);
2165 AddThisServer(best,list);
2171 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2173 TreeServer* omitroute = BestRouteTo(omit);
2174 if ((command == "NOTICE") || (command == "PRIVMSG"))
2176 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2178 if (*(params[0].c_str()) != '#')
2180 // special routing for private messages/notices
2181 userrec* d = Srv->FindNick(params[0]);
2184 std::deque<std::string> par;
2185 par.push_back(params[0]);
2186 par.push_back(":"+params[1]);
2187 DoOneToOne(prefix,command,par,d->server);
2193 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2194 chanrec* c = Srv->FindChannel(params[0]);
2197 std::deque<TreeServer*> list;
2198 GetListOfServersForChannel(c,list);
2199 log(DEBUG,"Got a list of %d servers",list.size());
2200 unsigned int lsize = list.size();
2201 for (unsigned int i = 0; i < lsize; i++)
2203 TreeSocket* Sock = list[i]->GetSocket();
2204 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2206 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2207 Sock->WriteLine(data);
2215 unsigned int items = TreeRoot->ChildCount();
2216 for (unsigned int x = 0; x < items; x++)
2218 TreeServer* Route = TreeRoot->GetChild(x);
2219 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2221 TreeSocket* Sock = Route->GetSocket();
2222 Sock->WriteLine(data);
2228 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2230 TreeServer* omitroute = BestRouteTo(omit);
2231 std::string FullLine = ":" + prefix + " " + command;
2232 unsigned int words = params.size();
2233 for (unsigned int x = 0; x < words; x++)
2235 FullLine = FullLine + " " + params[x];
2237 unsigned int items = TreeRoot->ChildCount();
2238 for (unsigned int x = 0; x < items; x++)
2240 TreeServer* Route = TreeRoot->GetChild(x);
2241 // Send the line IF:
2242 // The route has a socket (its a direct connection)
2243 // The route isnt the one to be omitted
2244 // The route isnt the path to the one to be omitted
2245 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2247 TreeSocket* Sock = Route->GetSocket();
2248 Sock->WriteLine(FullLine);
2254 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2256 std::string FullLine = ":" + prefix + " " + command;
2257 unsigned int words = params.size();
2258 for (unsigned int x = 0; x < words; x++)
2260 FullLine = FullLine + " " + params[x];
2262 unsigned int items = TreeRoot->ChildCount();
2263 for (unsigned int x = 0; x < items; x++)
2265 TreeServer* Route = TreeRoot->GetChild(x);
2266 if (Route->GetSocket())
2268 TreeSocket* Sock = Route->GetSocket();
2269 Sock->WriteLine(FullLine);
2275 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2277 TreeServer* Route = BestRouteTo(target);
2280 std::string FullLine = ":" + prefix + " " + command;
2281 unsigned int words = params.size();
2282 for (unsigned int x = 0; x < words; x++)
2284 FullLine = FullLine + " " + params[x];
2286 if (Route->GetSocket())
2288 TreeSocket* Sock = Route->GetSocket();
2289 Sock->WriteLine(FullLine);
2299 std::vector<TreeSocket*> Bindings;
2301 void ReadConfiguration(bool rebind)
2303 Conf = new ConfigReader;
2306 for (int j =0; j < Conf->Enumerate("bind"); j++)
2308 std::string Type = Conf->ReadValue("bind","type",j);
2309 std::string IP = Conf->ReadValue("bind","address",j);
2310 long Port = Conf->ReadInteger("bind","port",j,true);
2311 if (Type == "servers")
2317 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2318 if (listener->GetState() == I_LISTENING)
2320 Srv->AddSocket(listener);
2321 Bindings.push_back(listener);
2325 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2333 for (int j =0; j < Conf->Enumerate("link"); j++)
2336 L.Name = Conf->ReadValue("link","name",j);
2337 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2338 L.Port = Conf->ReadInteger("link","port",j,true);
2339 L.SendPass = Conf->ReadValue("link","sendpass",j);
2340 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2341 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2342 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2343 L.NextConnectTime = time(NULL) + L.AutoConnect;
2344 /* Bugfix by brain, do not allow people to enter bad configurations */
2345 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2347 LinkBlocks.push_back(L);
2348 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2352 log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2359 class ModuleSpanningTree : public Module
2361 std::vector<TreeSocket*> Bindings;
2367 ModuleSpanningTree(Server* Me)
2368 : Module::Module(Me)
2373 // Create the root of the tree
2374 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2376 ReadConfiguration(true);
2379 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2381 std::string Parent = TreeRoot->GetName();
2382 if (Current->GetParent())
2384 Parent = Current->GetParent()->GetName();
2386 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2388 ShowLinks(Current->GetChild(q),user,hops+1);
2390 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2393 int CountLocalServs()
2395 return TreeRoot->ChildCount();
2400 return serverlist.size();
2403 void HandleLinks(char** parameters, int pcnt, userrec* user)
2405 ShowLinks(TreeRoot,user,0);
2406 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2410 void HandleLusers(char** parameters, int pcnt, userrec* user)
2412 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2413 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2414 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2415 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2416 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2420 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2422 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2426 for (int t = 0; t < depth; t++)
2428 matrix[line][t] = ' ';
2430 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2432 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2434 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2439 // Ok, prepare to be confused.
2440 // After much mulling over how to approach this, it struck me that
2441 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2442 // keeping track of a ton of ascii characters, and line by line
2443 // under recursion working out where to place them using multiplications
2444 // and divisons, we instead render the map onto a backplane of characters
2445 // (a character matrix), then draw the branches as a series of "L" shapes
2446 // from the nodes. This is not only friendlier on CPU it uses less stack.
2448 void HandleMap(char** parameters, int pcnt, userrec* user)
2450 // This array represents a virtual screen which we will
2451 // "scratch" draw to, as the console device of an irc
2452 // client does not provide for a proper terminal.
2453 char matrix[128][80];
2454 for (unsigned int t = 0; t < 128; t++)
2456 matrix[t][0] = '\0';
2459 // The only recursive bit is called here.
2460 ShowMap(TreeRoot,user,0,matrix);
2461 // Process each line one by one. The algorithm has a limit of
2462 // 128 servers (which is far more than a spanning tree should have
2463 // anyway, so we're ok). This limit can be raised simply by making
2464 // the character matrix deeper, 128 rows taking 10k of memory.
2465 for (int l = 1; l < line; l++)
2467 // scan across the line looking for the start of the
2468 // servername (the recursive part of the algorithm has placed
2469 // the servers at indented positions depending on what they
2471 int first_nonspace = 0;
2472 while (matrix[l][first_nonspace] == ' ')
2477 // Draw the `- (corner) section: this may be overwritten by
2478 // another L shape passing along the same vertical pane, becoming
2479 // a |- (branch) section instead.
2480 matrix[l][first_nonspace] = '-';
2481 matrix[l][first_nonspace-1] = '`';
2483 // Draw upwards until we hit the parent server, causing possibly
2484 // other corners (`-) to become branches (|-)
2485 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2487 matrix[l2][first_nonspace-1] = '|';
2491 // dump the whole lot to the user. This is the easy bit, honest.
2492 for (int t = 0; t < line; t++)
2494 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2496 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2500 int HandleSquit(char** parameters, int pcnt, userrec* user)
2502 TreeServer* s = FindServerMask(parameters[0]);
2507 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2510 TreeSocket* sock = s->GetSocket();
2513 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2514 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2515 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2520 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2525 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2530 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2532 if ((user->fd > -1) && (pcnt > 1))
2534 userrec* remote = Srv->FindNick(parameters[1]);
2535 if ((remote) && (remote->fd < 0))
2537 std::deque<std::string> params;
2538 params.push_back(parameters[1]);
2539 DoOneToOne(user->nick,"IDLE",params,remote->server);
2544 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2545 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2552 void DoPingChecks(time_t curtime)
2554 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2556 TreeServer* serv = TreeRoot->GetChild(j);
2557 TreeSocket* sock = serv->GetSocket();
2560 if (curtime >= serv->NextPingTime())
2562 if (serv->AnsweredLastPing())
2564 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2565 serv->SetNextPingTime(curtime + 60);
2569 // they didnt answer, boot them
2570 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2571 sock->Squit(serv,"Ping timeout");
2580 void AutoConnectServers(time_t curtime)
2582 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2584 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2586 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2587 x->NextConnectTime = curtime + x->AutoConnect;
2588 TreeServer* CheckDupe = FindServer(x->Name);
2591 // an autoconnected server is not connected. Check if its time to connect it
2592 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2593 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2594 Srv->AddSocket(newsocket);
2600 int HandleVersion(char** parameters, int pcnt, userrec* user)
2602 // we've already checked if pcnt > 0, so this is safe
2603 TreeServer* found = FindServerMask(parameters[0]);
2606 std::string Version = found->GetVersion();
2607 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2611 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2616 int HandleConnect(char** parameters, int pcnt, userrec* user)
2618 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2620 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2622 TreeServer* CheckDupe = FindServer(x->Name);
2625 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);
2626 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2627 Srv->AddSocket(newsocket);
2632 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());
2637 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2641 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2643 if (*parameters[0] == 'c')
2645 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2647 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"));
2648 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2650 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2651 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2657 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2659 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2663 if (command == "CONNECT")
2665 return this->HandleConnect(parameters,pcnt,user);
2667 else if (command == "SQUIT")
2669 return this->HandleSquit(parameters,pcnt,user);
2671 else if (command == "STATS")
2673 return this->HandleStats(parameters,pcnt,user);
2675 else if (command == "MAP")
2677 this->HandleMap(parameters,pcnt,user);
2680 else if (command == "LUSERS")
2682 this->HandleLusers(parameters,pcnt,user);
2685 else if (command == "LINKS")
2687 this->HandleLinks(parameters,pcnt,user);
2690 else if (command == "WHOIS")
2695 return this->HandleRemoteWhois(parameters,pcnt,user);
2698 else if ((command == "VERSION") && (pcnt > 0))
2700 this->HandleVersion(parameters,pcnt,user);
2703 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2705 // this bit of code cleverly routes all module commands
2706 // to all remote severs *automatically* so that modules
2707 // can just handle commands locally, without having
2708 // to have any special provision in place for remote
2709 // commands and linking protocols.
2710 std::deque<std::string> params;
2712 for (int j = 0; j < pcnt; j++)
2714 if (strchr(parameters[j],' '))
2716 params.push_back(":" + std::string(parameters[j]));
2720 params.push_back(std::string(parameters[j]));
2723 DoOneToMany(user->nick,command,params);
2728 virtual void OnGetServerDescription(std::string servername,std::string &description)
2730 TreeServer* s = FindServer(servername);
2733 description = s->GetDesc();
2737 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2739 if (source->fd > -1)
2741 std::deque<std::string> params;
2742 params.push_back(dest->nick);
2743 params.push_back(channel->name);
2744 DoOneToMany(source->nick,"INVITE",params);
2748 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2750 std::deque<std::string> params;
2751 params.push_back(chan->name);
2752 params.push_back(":"+topic);
2753 DoOneToMany(user->nick,"TOPIC",params);
2756 virtual void OnWallops(userrec* user, std::string text)
2760 std::deque<std::string> params;
2761 params.push_back(":"+text);
2762 DoOneToMany(user->nick,"WALLOPS",params);
2766 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2768 if (target_type == TYPE_USER)
2770 userrec* d = (userrec*)dest;
2771 if ((d->fd < 0) && (user->fd > -1))
2773 std::deque<std::string> params;
2775 params.push_back(d->nick);
2776 params.push_back(":"+text);
2777 DoOneToOne(user->nick,"NOTICE",params,d->server);
2784 chanrec *c = (chanrec*)dest;
2785 std::deque<TreeServer*> list;
2786 GetListOfServersForChannel(c,list);
2787 unsigned int ucount = list.size();
2788 for (unsigned int i = 0; i < ucount; i++)
2790 TreeSocket* Sock = list[i]->GetSocket();
2792 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2798 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2800 if (target_type == TYPE_USER)
2802 // route private messages which are targetted at clients only to the server
2803 // which needs to receive them
2804 userrec* d = (userrec*)dest;
2805 if ((d->fd < 0) && (user->fd > -1))
2807 std::deque<std::string> params;
2809 params.push_back(d->nick);
2810 params.push_back(":"+text);
2811 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2818 chanrec *c = (chanrec*)dest;
2819 std::deque<TreeServer*> list;
2820 GetListOfServersForChannel(c,list);
2821 unsigned int ucount = list.size();
2822 for (unsigned int i = 0; i < ucount; i++)
2824 TreeSocket* Sock = list[i]->GetSocket();
2826 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2832 virtual void OnBackgroundTimer(time_t curtime)
2834 AutoConnectServers(curtime);
2835 DoPingChecks(curtime);
2838 virtual void OnUserJoin(userrec* user, chanrec* channel)
2840 // Only do this for local users
2843 std::deque<std::string> params;
2845 params.push_back(channel->name);
2848 // if the channel has a key, force the join by emulating the key.
2849 params.push_back(channel->key);
2851 if (channel->GetUserCounter() > 1)
2853 // not the first in the channel
2854 DoOneToMany(user->nick,"JOIN",params);
2858 // first in the channel, set up their permissions
2859 // and the channel TS with FJOIN.
2861 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2863 params.push_back(channel->name);
2864 params.push_back(ts);
2865 params.push_back("@"+std::string(user->nick));
2866 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2871 virtual void OnChangeHost(userrec* user, std::string newhost)
2873 // only occurs for local clients
2874 if (user->registered != 7)
2876 std::deque<std::string> params;
2877 params.push_back(newhost);
2878 DoOneToMany(user->nick,"FHOST",params);
2881 virtual void OnChangeName(userrec* user, std::string gecos)
2883 // only occurs for local clients
2884 if (user->registered != 7)
2886 std::deque<std::string> params;
2887 params.push_back(gecos);
2888 DoOneToMany(user->nick,"FNAME",params);
2891 virtual void OnUserPart(userrec* user, chanrec* channel)
2895 std::deque<std::string> params;
2896 params.push_back(channel->name);
2897 DoOneToMany(user->nick,"PART",params);
2901 virtual void OnUserConnect(userrec* user)
2903 char agestr[MAXBUF];
2906 std::deque<std::string> params;
2907 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2908 params.push_back(agestr);
2909 params.push_back(user->nick);
2910 params.push_back(user->host);
2911 params.push_back(user->dhost);
2912 params.push_back(user->ident);
2913 params.push_back("+"+std::string(user->modes));
2914 params.push_back(user->ip);
2915 params.push_back(":"+std::string(user->fullname));
2916 DoOneToMany(Srv->GetServerName(),"NICK",params);
2920 virtual void OnUserQuit(userrec* user, std::string reason)
2922 if ((user->fd > -1) && (user->registered == 7))
2924 std::deque<std::string> params;
2925 params.push_back(":"+reason);
2926 DoOneToMany(user->nick,"QUIT",params);
2930 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2934 std::deque<std::string> params;
2935 params.push_back(user->nick);
2936 DoOneToMany(oldnick,"NICK",params);
2940 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2942 if (source->fd > -1)
2944 std::deque<std::string> params;
2945 params.push_back(chan->name);
2946 params.push_back(user->nick);
2947 params.push_back(":"+reason);
2948 DoOneToMany(source->nick,"KICK",params);
2952 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2954 std::deque<std::string> params;
2955 params.push_back(dest->nick);
2956 params.push_back(":"+reason);
2957 DoOneToMany(source->nick,"KILL",params);
2960 virtual void OnRehash(std::string parameter)
2962 if (parameter != "")
2964 std::deque<std::string> params;
2965 params.push_back(parameter);
2966 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2968 if (Srv->MatchText(Srv->GetServerName(),parameter))
2970 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2971 Srv->RehashServer();
2974 ReadConfiguration(false);
2977 // note: the protocol does not allow direct umode +o except
2978 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2980 virtual void OnOper(userrec* user, std::string opertype)
2984 std::deque<std::string> params;
2985 params.push_back(opertype);
2986 DoOneToMany(user->nick,"OPERTYPE",params);
2990 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2992 if (source->fd > -1)
2995 snprintf(type,8,"%cLINE",linetype);
2996 std::string stype = type;
2999 char sduration[MAXBUF];
3000 snprintf(sduration,MAXBUF,"%ld",duration);
3001 std::deque<std::string> params;
3002 params.push_back(host);
3003 params.push_back(sduration);
3004 params.push_back(":"+reason);
3005 DoOneToMany(source->nick,stype,params);
3009 std::deque<std::string> params;
3010 params.push_back(host);
3011 DoOneToMany(source->nick,stype,params);
3016 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3018 OnLine(source,hostmask,true,'G',duration,reason);
3021 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3023 OnLine(source,ipmask,true,'Z',duration,reason);
3026 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3028 OnLine(source,nickmask,true,'Q',duration,reason);
3031 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3033 OnLine(source,hostmask,true,'E',duration,reason);
3036 virtual void OnDelGLine(userrec* source, std::string hostmask)
3038 OnLine(source,hostmask,false,'G',0,"");
3041 virtual void OnDelZLine(userrec* source, std::string ipmask)
3043 OnLine(source,ipmask,false,'Z',0,"");
3046 virtual void OnDelQLine(userrec* source, std::string nickmask)
3048 OnLine(source,nickmask,false,'Q',0,"");
3051 virtual void OnDelELine(userrec* source, std::string hostmask)
3053 OnLine(source,hostmask,false,'E',0,"");
3056 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3058 if ((user->fd > -1) && (user->registered == 7))
3060 if (target_type == TYPE_USER)
3062 userrec* u = (userrec*)dest;
3063 std::deque<std::string> params;
3064 params.push_back(u->nick);
3065 params.push_back(text);
3066 DoOneToMany(user->nick,"MODE",params);
3070 chanrec* c = (chanrec*)dest;
3071 std::deque<std::string> params;
3072 params.push_back(c->name);
3073 params.push_back(text);
3074 DoOneToMany(user->nick,"MODE",params);
3079 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3081 TreeSocket* s = (TreeSocket*)opaque;
3084 if (target_type == TYPE_USER)
3086 userrec* u = (userrec*)target;
3087 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3091 chanrec* c = (chanrec*)target;
3092 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3097 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3099 TreeSocket* s = (TreeSocket*)opaque;
3102 if (target_type == TYPE_USER)
3104 userrec* u = (userrec*)target;
3105 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3109 chanrec* c = (chanrec*)target;
3110 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3115 virtual ~ModuleSpanningTree()
3119 virtual Version GetVersion()
3121 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3124 void Implements(char* List)
3126 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3127 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3128 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3129 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3130 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3131 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3132 List[I_ProtoSendMetaData] = 1;
3137 class ModuleSpanningTreeFactory : public ModuleFactory
3140 ModuleSpanningTreeFactory()
3144 ~ModuleSpanningTreeFactory()
3148 virtual Module * CreateModule(Server* Me)
3150 TreeProtocolModule = new ModuleSpanningTree(Me);
3151 return TreeProtocolModule;
3157 extern "C" void * init_module( void )
3159 return new ModuleSpanningTreeFactory;