1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
25 #include "inspircd_config.h"
27 #include <ext/hash_map>
36 #include "helperfuncs.h"
38 #include "inspstring.h"
43 #include "cull_list.h"
47 #define nspace __gnu_cxx
53 * The server list in InspIRCd is maintained as two structures
54 * which hold the data in different ways. Most of the time, we
55 * want to very quicky obtain three pieces of information:
57 * (1) The information on a server
58 * (2) The information on the server we must send data through
59 * to actually REACH the server we're after
60 * (3) Potentially, the child/parent objects of this server
62 * The InspIRCd spanning protocol provides easy access to these
63 * by storing the data firstly in a recursive structure, where
64 * each item references its parent item, and a dynamic list
65 * of child items, and another structure which stores the items
66 * hashed, linearly. This means that if we want to find a server
67 * by name quickly, we can look it up in the hash, avoiding
68 * any O(n) lookups. If however, during a split or sync, we want
69 * to apply an operation to a server, and any of its child objects
70 * we can resort to recursion to walk the tree structure.
73 class ModuleSpanningTree;
74 static ModuleSpanningTree* TreeProtocolModule;
76 extern ServerConfig* Config;
78 extern std::vector<Module*> modules;
79 extern std::vector<ircd_module*> factory;
82 /* Any socket can have one of five states at any one time.
83 * The LISTENER state indicates a socket which is listening
84 * for connections. It cannot receive data itself, only incoming
86 * The CONNECTING state indicates an outbound socket which is
87 * waiting to be writeable.
88 * The WAIT_AUTH_1 state indicates the socket is outbound and
89 * has successfully connected, but has not yet sent and received
91 * The WAIT_AUTH_2 state indicates that the socket is inbound
92 * (allocated by a LISTENER) but has not yet sent and received
94 * The CONNECTED state represents a fully authorized, fully
97 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
99 /* We need to import these from the core for use in netbursts */
100 extern user_hash clientlist;
101 extern chan_hash chanlist;
103 /* Foward declarations */
107 /* This variable represents the root of the server tree
108 * (for all intents and purposes, it's us)
110 TreeServer *TreeRoot;
114 /* This hash_map holds the hash equivalent of the server
115 * tree, used for rapid linear lookups.
117 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
118 server_hash serverlist;
120 /* More forward declarations */
121 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
122 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
123 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
124 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
125 void ReadConfiguration(bool rebind);
127 /* 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) + 120);
209 /* find the 'route' for this server (e.g. the one directly connected
210 * to the local server, which we can use to reach it)
212 * In the following example, consider we have just added a TreeServer
213 * class for server G on our network, of which we are server A.
214 * To route traffic to G (marked with a *) we must send the data to
215 * B (marked with a +) so this algorithm initializes the 'Route'
216 * value to point at whichever server traffic must be routed through
217 * to get here. If we were to try this algorithm with server B,
218 * the Route pointer would point at its own object ('this').
228 * We only run this algorithm when a server is created, as
229 * the routes remain constant while ever the server exists, and
230 * do not need to be re-calculated.
234 if (Route == TreeRoot)
240 while (this->Route->GetParent() != TreeRoot)
242 this->Route = Route->GetParent();
246 /* Because recursive code is slow and takes a lot of resources,
247 * we store two representations of the server tree. The first
248 * is a recursive structure where each server references its
249 * children and its parent, which is used for netbursts and
250 * netsplits to dump the whole dataset to the other server,
251 * and the second is used for very fast lookups when routing
252 * messages and is instead a hash_map, where each item can
253 * be referenced by its server name. The AddHashEntry()
254 * call below automatically inserts each TreeServer class
255 * into the hash_map as it is created. There is a similar
256 * maintainance call in the destructor to tidy up deleted
260 this->AddHashEntry();
263 /* This method is used to add the structure to the
264 * hash_map for linear searches. It is only called
265 * by the constructors.
269 server_hash::iterator iter;
270 iter = serverlist.find(this->ServerName);
271 if (iter == serverlist.end())
272 serverlist[this->ServerName] = this;
275 /* This method removes the reference to this object
276 * from the hash_map which is used for linear searches.
277 * It is only called by the default destructor.
281 server_hash::iterator iter;
282 iter = serverlist.find(this->ServerName);
283 if (iter != serverlist.end())
284 serverlist.erase(iter);
287 /* These accessors etc should be pretty self-
291 TreeServer* GetRoute()
296 std::string GetName()
301 std::string GetDesc()
306 std::string GetVersion()
308 return VersionString;
311 void SetNextPingTime(time_t t)
314 LastPingWasGood = false;
317 time_t NextPingTime()
322 bool AnsweredLastPing()
324 return LastPingWasGood;
329 LastPingWasGood = true;
352 TreeSocket* GetSocket()
357 TreeServer* GetParent()
362 void SetVersion(std::string Version)
364 VersionString = Version;
367 unsigned int ChildCount()
369 return Children.size();
372 TreeServer* GetChild(unsigned int n)
374 if (n < Children.size())
376 /* Make sure they cant request
377 * an out-of-range object. After
378 * all we know what these programmer
379 * types are like *grin*.
389 void AddChild(TreeServer* Child)
391 Children.push_back(Child);
394 bool DelChild(TreeServer* Child)
396 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
407 /* Removes child nodes of this node, and of that node, etc etc.
408 * This is used during netsplits to automatically tidy up the
409 * server tree. It is slow, we don't use it for much else.
413 bool stillchildren = true;
414 while (stillchildren)
416 stillchildren = false;
417 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
419 TreeServer* s = (TreeServer*)*a;
423 stillchildren = true;
432 /* We'd better tidy up after ourselves, eh? */
433 this->DelHashEntry();
437 /* The Link class might as well be a struct,
438 * but this is C++ and we don't believe in structs (!).
439 * It holds the entire information of one <link>
440 * tag from the main config file. We maintain a list
441 * of them, and populate the list on rehash/load.
450 std::string SendPass;
451 std::string RecvPass;
452 unsigned long AutoConnect;
453 time_t NextConnectTime;
454 std::string EncryptionKey;
455 bool HiddenFromStats;
458 /* The usual stuff for inspircd modules,
459 * plus the vector of Link classes which we
460 * use to store the <link> tags from the config
464 std::vector<Link> LinkBlocks;
466 /* Yay for fast searches!
467 * This is hundreds of times faster than recursion
468 * or even scanning a linked list, especially when
469 * there are more than a few servers to deal with.
472 TreeServer* FindServer(std::string ServerName)
474 server_hash::iterator iter;
475 iter = serverlist.find(ServerName);
476 if (iter != serverlist.end())
486 /* Returns the locally connected server we must route a
487 * message through to reach server 'ServerName'. This
488 * only applies to one-to-one and not one-to-many routing.
489 * See the comments for the constructor of TreeServer
492 TreeServer* BestRouteTo(std::string ServerName)
494 if (ServerName.c_str() == TreeRoot->GetName())
496 TreeServer* Found = FindServer(ServerName);
499 return Found->GetRoute();
507 /* Find the first server matching a given glob mask.
508 * Theres no find-using-glob method of hash_map [awwww :-(]
509 * so instead, we iterate over the list using an iterator
510 * and match each one until we get a hit. Yes its slow,
513 TreeServer* FindServerMask(std::string ServerName)
515 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
517 if (Srv->MatchText(i->first,ServerName))
523 /* A convenient wrapper that returns true if a server exists */
524 bool IsServer(std::string ServerName)
526 return (FindServer(ServerName) != NULL);
529 /* Every SERVER connection inbound or outbound is represented by
530 * an object of type TreeSocket.
531 * TreeSockets, being inherited from InspSocket, can be tied into
532 * the core socket engine, and we cn therefore receive activity events
533 * for them, just like activex objects on speed. (yes really, that
534 * is a technical term!) Each of these which relates to a locally
535 * connected server is assocated with it, by hooking it onto a
536 * TreeSocket class using its constructor. In this way, we can
537 * maintain a list of servers, some of which are directly connected,
538 * some of which are not.
541 class TreeSocket : public InspSocket
544 std::string in_buffer;
545 ServerState LinkState;
546 std::string InboundServerName;
547 std::string InboundDescription;
549 int num_lost_servers;
551 bool LastPingWasGood;
555 unsigned int keylength;
559 /* Because most of the I/O gubbins are encapsulated within
560 * InspSocket, we just call the superclass constructor for
561 * most of the action, and append a few of our own values
564 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
565 : InspSocket(host, port, listening, maxtime)
568 this->LinkState = LISTENER;
570 this->ctx_out = NULL;
573 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
574 : InspSocket(host, port, listening, maxtime)
577 this->LinkState = CONNECTING;
579 this->ctx_out = NULL;
582 /* When a listening socket gives us a new file descriptor,
583 * we must associate it with a socket without creating a new
584 * connection. This constructor is used for this purpose.
586 TreeSocket(int newfd, char* ip)
587 : InspSocket(newfd, ip)
589 this->LinkState = WAIT_AUTH_1;
591 this->ctx_out = NULL;
592 this->SendCapabilities();
603 void InitAES(std::string key,std::string SName)
610 log(DEBUG,"Initialized AES key %s",key.c_str());
611 // key must be 16, 24, 32 etc bytes (multiple of 8)
612 keylength = key.length();
613 if (!(keylength == 16 || keylength == 24 || keylength == 32))
615 WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
616 log(DEBUG,"Key length not 16, 24 or 32 characters!");
620 WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
621 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\
622 \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);
623 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\
624 \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);
628 /* When an outbound connection finishes connecting, we receive
629 * this event, and must send our SERVER string to the other
630 * side. If the other side is happy, as outlined in the server
631 * to server docs on the inspircd.org site, the other side
632 * will then send back its own server string.
634 virtual bool OnConnected()
636 if (this->LinkState == CONNECTING)
638 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
639 /* we do not need to change state here. */
640 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
642 if (x->Name == this->myhost)
644 this->SendCapabilities();
645 if (x->EncryptionKey != "")
647 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
649 WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
653 this->WriteLine("AES "+Srv->GetServerName());
654 this->InitAES(x->EncryptionKey,x->Name);
657 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
658 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
663 /* There is a (remote) chance that between the /CONNECT and the connection
664 * being accepted, some muppet has removed the <link> block and rehashed.
665 * If that happens the connection hangs here until it's closed. Unlikely
666 * and rather harmless.
671 virtual void OnError(InspSocketError e)
673 /* We don't handle this method, because all our
674 * dirty work is done in OnClose() (see below)
675 * which is still called on error conditions too.
679 virtual int OnDisconnect()
681 /* For the same reason as above, we don't
682 * handle OnDisconnect()
687 /* Recursively send the server tree with distances as hops.
688 * This is used during network burst to inform the other server
689 * (and any of ITS servers too) of what servers we know about.
690 * If at any point any of these servers already exist on the other
691 * end, our connection may be terminated. The hopcounts given
692 * by this function are relative, this doesn't matter so long as
693 * they are all >1, as all the remote servers re-calculate them
694 * to be relative too, with themselves as hop 0.
696 void SendServers(TreeServer* Current, TreeServer* s, int hops)
699 for (unsigned int q = 0; q < Current->ChildCount(); q++)
701 TreeServer* recursive_server = Current->GetChild(q);
702 if (recursive_server != s)
704 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
705 this->WriteLine(command);
706 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
707 /* down to next level */
708 this->SendServers(recursive_server, s, hops+1);
713 std::string MyCapabilities()
715 ServerConfig* Config = Srv->GetConfig();
716 std::vector<std::string> modlist;
717 std::string capabilities = "";
719 for (int i = 0; i <= MODCOUNT; i++)
721 if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
722 modlist.push_back(Config->module_names[i]);
724 sort(modlist.begin(),modlist.end());
725 for (unsigned int i = 0; i < modlist.size(); i++)
728 capabilities = capabilities + ",";
729 capabilities = capabilities + modlist[i];
734 void SendCapabilities()
736 this->WriteLine("CAPAB "+MyCapabilities());
739 bool Capab(std::deque<std::string> params)
741 if (params.size() != 1)
743 this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
746 if (params[0] != this->MyCapabilities())
748 std::string quitserver = this->myhost;
749 if (this->InboundServerName != "")
751 quitserver = this->InboundServerName;
753 WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
754 WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
755 WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
756 WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
757 this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
763 /* This function forces this server to quit, removing this server
764 * and any users on it (and servers and users below that, etc etc).
765 * It's very slow and pretty clunky, but luckily unless your network
766 * is having a REAL bad hair day, this function shouldnt be called
767 * too many times a month ;-)
769 void SquitServer(TreeServer* Current, CullList* Goners)
771 /* recursively squit the servers attached to 'Current'.
772 * We're going backwards so we don't remove users
773 * while we still need them ;)
775 for (unsigned int q = 0; q < Current->ChildCount(); q++)
777 TreeServer* recursive_server = Current->GetChild(q);
778 this->SquitServer(recursive_server,Goners);
780 /* Now we've whacked the kids, whack self */
782 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
784 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
786 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
787 Goners->AddItem(u->second,qreason);
793 /* This is a wrapper function for SquitServer above, which
794 * does some validation first and passes on the SQUIT to all
795 * other remaining servers.
797 void Squit(TreeServer* Current,std::string reason)
799 if ((Current) && (Current != TreeRoot))
801 std::deque<std::string> params;
802 params.push_back(Current->GetName());
803 params.push_back(":"+reason);
804 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
805 if (Current->GetParent() == TreeRoot)
807 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
811 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
813 num_lost_servers = 0;
815 CullList* Goners = new CullList();
816 SquitServer(Current, Goners);
819 Current->GetParent()->DelChild(Current);
822 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
826 log(DEFAULT,"Squit from unknown server");
831 bool ForceMode(std::string source, std::deque<std::string> params)
833 userrec* who = new userrec;
834 who->fd = FD_MAGIC_NUMBER;
835 if (params.size() < 2)
838 for (unsigned int q = 0; q < params.size(); q++)
840 modelist[q] = (char*)params[q].c_str();
842 Srv->SendMode(modelist,params.size(),who);
843 DoOneToAllButSender(source,"FMODE",params,source);
849 bool ForceTopic(std::string source, std::deque<std::string> params)
851 if (params.size() != 4)
853 std::string channel = params[0];
854 time_t ts = atoi(params[1].c_str());
855 std::string setby = params[2];
856 std::string topic = params[3];
857 std::string nsource = source;
859 chanrec* c = Srv->FindChannel(channel);
862 if ((ts >= c->topicset) || (!*c->topic))
864 std::string oldtopic = c->topic;
865 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
866 strlcpy(c->setby,setby.c_str(),NICKMAX);
868 /* if the topic text is the same as the current topic,
869 * dont bother to send the TOPIC command out, just silently
870 * update the set time and set nick.
872 if (oldtopic != topic)
874 userrec* user = Srv->FindNick(source);
877 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
881 WriteChannel(c, user, "TOPIC %s :%s", c->name, c->topic);
882 nsource = user->server;
889 /* all done, send it on its way */
890 params[3] = ":" + params[3];
891 DoOneToAllButSender(source,"FTOPIC",params,nsource);
896 /* FJOIN, similar to unreal SJOIN */
897 bool ForceJoin(std::string source, std::deque<std::string> params)
899 if (params.size() < 3)
903 char modestring[MAXBUF];
904 char* mode_users[127];
905 mode_users[0] = first;
906 mode_users[1] = modestring;
907 strcpy(mode_users[1],"+");
908 unsigned int modectr = 2;
911 std::string channel = params[0];
912 time_t TS = atoi(params[1].c_str());
915 chanrec* chan = Srv->FindChannel(channel);
920 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
922 /* default is a high value, which if we dont have this
923 * channel will let the other side apply their modes.
925 time_t ourTS = time(NULL)+600;
926 chanrec* us = Srv->FindChannel(channel);
932 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
934 /* do this first, so our mode reversals are correctly received by other servers
935 * if there is a TS collision.
937 DoOneToAllButSender(source,"FJOIN",params,source);
939 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
941 /* process one channel at a time, applying modes. */
942 char* usr = (char*)params[usernum].c_str();
943 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
944 * (is this even possible?) */
947 char permissions = *usr;
952 mode_users[modectr++] = usr;
953 strlcat(modestring,"o",MAXBUF);
957 mode_users[modectr++] = usr;
958 strlcat(modestring,"h",MAXBUF);
962 mode_users[modectr++] = usr;
963 strlcat(modestring,"v",MAXBUF);
966 who = Srv->FindNick(usr);
969 Srv->JoinUserToChannel(who,channel,key);
970 if (modectr >= (MAXMODES-1))
972 /* theres a mode for this user. push them onto the mode queue, and flush it
973 * if there are more than MAXMODES to go.
975 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
977 /* We also always let u-lined clients win, no matter what the TS value */
978 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
979 Srv->SendMode(mode_users,modectr,who);
983 log(DEBUG,"Their channel newer than ours, bouncing their modes");
985 std::deque<std::string> params;
986 /* modes are now being UNSET... */
987 *mode_users[1] = '-';
988 for (unsigned int x = 0; x < modectr; x++)
990 params.push_back(mode_users[x]);
992 // tell everyone to bounce the modes. bad modes, bad!
993 DoOneToMany(Srv->GetServerName(),"FMODE",params);
995 strcpy(mode_users[1],"+");
1001 /* there werent enough modes built up to flush it during FJOIN,
1002 * or, there are a number left over. flush them out.
1004 if ((modectr > 2) && (who))
1008 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1009 Srv->SendMode(mode_users,modectr,who);
1013 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1014 std::deque<std::string> params;
1015 *mode_users[1] = '-';
1016 for (unsigned int x = 0; x < modectr; x++)
1018 params.push_back(mode_users[x]);
1020 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1027 bool IntroduceClient(std::string source, std::deque<std::string> params)
1029 if (params.size() < 8)
1031 // NICK age nick host dhost ident +modes ip :gecos
1033 std::string nick = params[1];
1034 std::string host = params[2];
1035 std::string dhost = params[3];
1036 std::string ident = params[4];
1037 time_t age = atoi(params[0].c_str());
1038 std::string modes = params[5];
1039 while (*(modes.c_str()) == '+')
1041 char* m = (char*)modes.c_str();
1045 std::string ip = params[6];
1046 std::string gecos = params[7];
1047 char* tempnick = (char*)nick.c_str();
1048 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1050 user_hash::iterator iter;
1051 iter = clientlist.find(tempnick);
1052 if (iter != clientlist.end())
1055 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);
1056 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1060 clientlist[tempnick] = new userrec();
1061 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1062 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1063 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1064 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1065 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1066 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1067 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1068 clientlist[tempnick]->registered = 7;
1069 clientlist[tempnick]->signon = age;
1070 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1071 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1076 for (int i = 0; i < MAXCHANS; i++)
1077 clientlist[tempnick]->chans.push_back(a);
1079 if (!this->bursting)
1081 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1083 params[7] = ":" + params[7];
1084 DoOneToAllButSender(source,"NICK",params,source);
1086 // Increment the Source Servers User Count..
1087 TreeServer* SourceServer = FindServer(source);
1089 SourceServer->AddUserCount();
1095 /* Send one or more FJOINs for a channel of users.
1096 * If the length of a single line is more than 480-NICKMAX
1097 * in length, it is split over multiple lines.
1099 void SendFJoins(TreeServer* Current, chanrec* c)
1101 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1103 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1104 std::map<char*,char*> *ulist = c->GetUsers();
1105 for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
1107 char* o = i->second;
1108 userrec* otheruser = (userrec*)o;
1109 strlcat(list," ",MAXBUF);
1110 strlcat(list,cmode(otheruser,c),MAXBUF);
1111 strlcat(list,otheruser->nick,MAXBUF);
1112 if (strlen(list)>(480-NICKMAX))
1114 log(DEBUG,"FJOIN line wrapped");
1115 this->WriteLine(list);
1116 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1119 if (list[strlen(list)-1] != ':')
1121 log(DEBUG,"Final FJOIN line");
1122 this->WriteLine(list);
1126 /* Send G, Q, Z and E lines */
1127 void SendXLines(TreeServer* Current)
1130 /* Yes, these arent too nice looking, but they get the job done */
1131 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1133 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);
1134 this->WriteLine(data);
1136 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1138 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);
1139 this->WriteLine(data);
1141 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1143 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);
1144 this->WriteLine(data);
1146 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1148 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);
1149 this->WriteLine(data);
1151 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1153 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);
1154 this->WriteLine(data);
1156 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1158 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);
1159 this->WriteLine(data);
1161 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1163 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);
1164 this->WriteLine(data);
1166 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1168 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);
1169 this->WriteLine(data);
1173 /* Send channel modes and topics */
1174 void SendChannelModes(TreeServer* Current)
1177 std::deque<std::string> list;
1178 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1180 SendFJoins(Current, c->second);
1181 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1182 this->WriteLine(data);
1183 if (*c->second->topic)
1185 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);
1186 this->WriteLine(data);
1188 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1190 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1191 this->WriteLine(data);
1193 FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1195 c->second->GetExtList(list);
1196 for (unsigned int j = 0; j < list.size(); j++)
1198 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1203 /* send all users and their oper state/modes */
1204 void SendUsers(TreeServer* Current)
1207 std::deque<std::string> list;
1208 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1210 if (u->second->registered == 7)
1212 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);
1213 this->WriteLine(data);
1214 if (strchr(u->second->modes,'o'))
1216 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1218 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1220 u->second->GetExtList(list);
1221 for (unsigned int j = 0; j < list.size(); j++)
1223 FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1229 /* This function is called when we want to send a netburst to a local
1230 * server. There is a set order we must do this, because for example
1231 * users require their servers to exist, and channels require their
1232 * users to exist. You get the idea.
1234 void DoBurst(TreeServer* s)
1236 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1237 this->WriteLine("BURST");
1238 /* send our version string */
1239 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1240 /* Send server tree */
1241 this->SendServers(TreeRoot,s,1);
1242 /* Send users and their oper status */
1244 /* Send everything else (channel modes, xlines etc) */
1245 this->SendChannelModes(s);
1246 this->SendXLines(s);
1247 this->WriteLine("ENDBURST");
1248 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1251 /* This function is called when we receive data from a remote
1252 * server. We buffer the data in a std::string (it doesnt stay
1253 * there for long), reading using InspSocket::Read() which can
1254 * read up to 16 kilobytes in one operation.
1256 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1257 * THE SOCKET OBJECT FOR US.
1259 virtual bool OnDataReady()
1261 char* data = this->Read();
1262 /* Check that the data read is a valid pointer and it has some content */
1265 this->in_buffer += data;
1266 /* While there is at least one new line in the buffer,
1267 * do something useful (we hope!) with it.
1269 while (in_buffer.find("\n") != std::string::npos)
1271 char* line = (char*)in_buffer.c_str();
1272 std::string ret = "";
1273 while ((*line != '\n') && (strlen(line)))
1275 if ((*line != '\r') && (*line != '\n'))
1279 if ((*line == '\n') || (*line == '\r'))
1282 /* Process this one, abort if it
1283 * didnt return true.
1289 memset(result,0,1024);
1291 log(DEBUG,"Original string '%s'",ret.c_str());
1292 /* ERROR + CAPAB is still allowed unencryped */
1293 if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1295 int nbytes = from64tobits(out, ret.c_str(), 1024);
1296 if ((nbytes > 0) && (nbytes < 1024))
1298 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1299 ctx_in->Decrypt(out, result, nbytes, 1);
1300 for (int t = 0; t < nbytes; t++)
1301 if (result[t] == '\7') result[t] = 0;
1306 if (!this->ProcessLine(ret))
1312 /* EAGAIN returns an empty but non-NULL string, so this
1313 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1315 return (data != NULL);
1318 int WriteLine(std::string line)
1320 log(DEBUG,"OUT: %s",line.c_str());
1323 log(DEBUG,"AES context");
1325 char result64[10240];
1326 if (this->keylength)
1328 while (line.length() % this->keylength != 0)
1330 // pad it to be a multiple of the key length
1334 unsigned int ll = line.length();
1335 log(DEBUG,"Plaintext line with padding = %d chars",ll);
1336 ctx_out->Encrypt(line.c_str(), result, ll, 1);
1337 log(DEBUG,"Encrypted.");
1338 to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1340 log(DEBUG,"Encrypted: %s",line.c_str());
1341 //int from64tobits(char *out, const char *in, int maxlen);
1343 return this->Write(line + "\r\n");
1346 /* Handle ERROR command */
1347 bool Error(std::deque<std::string> params)
1349 if (params.size() < 1)
1351 std::string Errmsg = params[0];
1352 std::string SName = myhost;
1353 if (InboundServerName != "")
1355 SName = InboundServerName;
1357 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1358 /* we will return false to cause the socket to close.
1363 /* Because the core won't let users or even SERVERS set +o,
1364 * we use the OPERTYPE command to do this.
1366 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1368 if (params.size() != 1)
1370 std::string opertype = params[0];
1371 userrec* u = Srv->FindNick(prefix);
1374 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1375 if (!strchr(u->modes,'o'))
1377 strcat(u->modes,"o");
1379 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1384 /* Because Andy insists that services-compatible servers must
1385 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1387 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1389 if (params.size() < 3)
1391 userrec* u = Srv->FindNick(params[0]);
1394 Srv->ChangeUserNick(u,params[1]);
1395 u->age = atoi(params[2].c_str());
1396 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1401 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1403 if (params.size() < 2)
1405 userrec* u = Srv->FindNick(params[0]);
1408 Srv->JoinUserToChannel(u,params[1],"");
1409 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1414 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1416 if (params.size() < 1)
1418 std::string servermask = params[0];
1419 if (Srv->MatchText(Srv->GetServerName(),servermask))
1421 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1422 Srv->RehashServer();
1423 ReadConfiguration(false);
1425 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1429 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1431 if (params.size() != 2)
1433 std::string nick = params[0];
1434 userrec* u = Srv->FindNick(prefix);
1435 userrec* who = Srv->FindNick(nick);
1438 /* Prepend kill source, if we don't have one */
1439 std::string sourceserv = prefix;
1442 sourceserv = u->server;
1444 if (*(params[1].c_str()) != '[')
1446 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1448 std::string reason = params[1];
1449 params[1] = ":" + params[1];
1450 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1451 Srv->QuitUser(who,reason);
1456 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1458 if (params.size() < 1)
1460 TreeServer* ServerSource = FindServer(prefix);
1463 ServerSource->SetPingFlag();
1468 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1470 if (params.size() < 3)
1472 TreeServer* ServerSource = FindServer(prefix);
1475 if (*(params[0].c_str()) == '#')
1477 chanrec* c = Srv->FindChannel(params[0]);
1480 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1485 userrec* u = Srv->FindNick(params[0]);
1488 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1492 params[2] = ":" + params[2];
1493 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1497 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1499 if (params.size() < 1)
1501 TreeServer* ServerSource = FindServer(prefix);
1504 ServerSource->SetVersion(params[0]);
1506 params[0] = ":" + params[0];
1507 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1511 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1513 if (params.size() < 1)
1515 userrec* u = Srv->FindNick(prefix);
1518 Srv->ChangeHost(u,params[0]);
1519 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1524 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1526 if (params.size() < 6)
1528 std::string linetype = params[0]; /* Z, Q, E, G, K */
1529 std::string mask = params[1]; /* Line type dependent */
1530 std::string source = params[2]; /* may not be online or may be a server */
1531 std::string settime = params[3]; /* EPOCH time set */
1532 std::string duration = params[4]; /* Duration secs */
1533 std::string reason = params[5];
1535 switch (*(linetype.c_str()))
1538 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1539 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1542 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1543 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1546 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1547 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1550 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1551 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1554 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1557 /* Just in case... */
1558 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1561 /* Send it on its way */
1562 params[5] = ":" + params[5];
1563 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1567 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1569 if (params.size() < 1)
1571 userrec* u = Srv->FindNick(prefix);
1574 Srv->ChangeGECOS(u,params[0]);
1575 params[0] = ":" + params[0];
1576 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1581 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1583 if (params.size() < 1)
1585 log(DEBUG,"In IDLE command");
1586 userrec* u = Srv->FindNick(prefix);
1589 log(DEBUG,"USER EXISTS: %s",u->nick);
1590 // an incoming request
1591 if (params.size() == 1)
1593 userrec* x = Srv->FindNick(params[0]);
1594 if ((x) && (x->fd > -1))
1596 userrec* x = Srv->FindNick(params[0]);
1597 log(DEBUG,"Got IDLE");
1598 char signon[MAXBUF];
1600 log(DEBUG,"Sending back IDLE 3");
1601 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1602 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1603 std::deque<std::string> par;
1604 par.push_back(prefix);
1605 par.push_back(signon);
1606 par.push_back(idle);
1607 // ours, we're done, pass it BACK
1608 DoOneToOne(params[0],"IDLE",par,u->server);
1612 // not ours pass it on
1613 DoOneToOne(prefix,"IDLE",params,x->server);
1616 else if (params.size() == 3)
1618 std::string who_did_the_whois = params[0];
1619 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1620 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1622 log(DEBUG,"Got final IDLE");
1623 // an incoming reply to a whois we sent out
1624 std::string nick_whoised = prefix;
1625 unsigned long signon = atoi(params[1].c_str());
1626 unsigned long idle = atoi(params[2].c_str());
1627 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1628 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1632 // not ours, pass it on
1633 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1640 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1642 if (params.size() < 1)
1644 std::string stufftobounce = params[0];
1645 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1649 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1651 if (params.size() < 4)
1653 std::string servername = params[0];
1654 std::string password = params[1];
1655 // hopcount is not used for a remote server, we calculate this ourselves
1656 std::string description = params[3];
1657 TreeServer* ParentOfThis = FindServer(prefix);
1660 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1663 TreeServer* CheckDupe = FindServer(servername);
1666 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1667 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1670 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1671 ParentOfThis->AddChild(Node);
1672 params[3] = ":" + params[3];
1673 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1674 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1678 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1680 if (params.size() < 4)
1682 std::string servername = params[0];
1683 std::string password = params[1];
1684 int hops = atoi(params[2].c_str());
1687 this->WriteLine("ERROR :Server too far away for authentication");
1688 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1691 std::string description = params[3];
1692 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1694 if ((x->Name == servername) && (x->RecvPass == password))
1696 TreeServer* CheckDupe = FindServer(servername);
1699 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1700 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1703 // Begin the sync here. this kickstarts the
1704 // other side, waiting in WAIT_AUTH_2 state,
1705 // into starting their burst, as it shows
1706 // that we're happy.
1707 this->LinkState = CONNECTED;
1708 // we should add the details of this server now
1709 // to the servers tree, as a child of the root
1711 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1712 TreeRoot->AddChild(Node);
1713 params[3] = ":" + params[3];
1714 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1715 this->bursting = true;
1716 this->DoBurst(Node);
1720 this->WriteLine("ERROR :Invalid credentials");
1721 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1725 bool Inbound_Server(std::deque<std::string> ¶ms)
1727 if (params.size() < 4)
1729 std::string servername = params[0];
1730 std::string password = params[1];
1731 int hops = atoi(params[2].c_str());
1734 this->WriteLine("ERROR :Server too far away for authentication");
1735 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1738 std::string description = params[3];
1739 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1741 if ((x->Name == servername) && (x->RecvPass == password))
1743 TreeServer* CheckDupe = FindServer(servername);
1746 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1747 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1750 /* If the config says this link is encrypted, but the remote side
1751 * hasnt bothered to send the AES command before SERVER, then we
1752 * boot them off as we MUST have this connection encrypted.
1754 if ((x->EncryptionKey != "") && (!this->ctx_in))
1756 this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1757 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1760 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
1761 this->InboundServerName = servername;
1762 this->InboundDescription = description;
1763 // this is good. Send our details: Our server name and description and hopcount of 0,
1764 // along with the sendpass from this block.
1765 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1766 // move to the next state, we are now waiting for THEM.
1767 this->LinkState = WAIT_AUTH_2;
1771 this->WriteLine("ERROR :Invalid credentials");
1772 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1776 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1778 if (!strchr(line.c_str(),' '))
1783 std::stringstream s(line);
1784 std::string param = "";
1803 if ((param == ":") && (item > 0))
1826 bool ProcessLine(std::string line)
1828 char* l = (char*)line.c_str();
1829 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1830 l[strlen(l)-1] = '\0';
1834 Srv->Log(DEBUG,"IN: "+line);
1836 std::deque<std::string> params;
1837 this->Split(line,true,params);
1838 std::string command = "";
1839 std::string prefix = "";
1840 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1843 command = params[1];
1844 char* pref = (char*)prefix.c_str();
1852 command = params[0];
1856 if ((!this->ctx_in) && (command == "AES"))
1858 std::string sserv = params[0];
1859 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1861 if ((x->EncryptionKey != "") && (x->Name == sserv))
1863 this->InitAES(x->EncryptionKey,sserv);
1868 else if ((this->ctx_in) && (command == "AES"))
1870 WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1873 switch (this->LinkState)
1878 // Waiting for SERVER command from remote server. Server initiating
1879 // the connection sends the first SERVER command, listening server
1880 // replies with theirs if its happy, then if the initiator is happy,
1881 // it starts to send its net sync, which starts the merge, otherwise
1882 // it sends an ERROR.
1883 if (command == "PASS")
1885 /* Silently ignored */
1887 else if (command == "SERVER")
1889 return this->Inbound_Server(params);
1891 else if (command == "ERROR")
1893 return this->Error(params);
1895 else if (command == "USER")
1897 this->WriteLine("ERROR :Client connections to this port are prohibited.");
1900 else if (command == "CAPAB")
1902 return this->Capab(params);
1904 else if ((command == "U") || (command == "S"))
1906 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1911 this->WriteLine("ERROR :Invalid command in negotiation phase.");
1916 // Waiting for start of other side's netmerge to say they liked our
1918 if (command == "SERVER")
1920 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1924 else if ((command == "U") || (command == "S"))
1926 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1929 else if (command == "BURST")
1931 this->LinkState = CONNECTED;
1932 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1933 TreeRoot->AddChild(Node);
1935 params.push_back(InboundServerName);
1936 params.push_back("*");
1937 params.push_back("1");
1938 params.push_back(":"+InboundDescription);
1939 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1940 this->bursting = true;
1941 this->DoBurst(Node);
1943 else if (command == "ERROR")
1945 return this->Error(params);
1947 else if (command == "CAPAB")
1949 return this->Capab(params);
1954 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1958 if (command == "SERVER")
1960 // another server we connected to, which was in WAIT_AUTH_1 state,
1961 // has just sent us their credentials. If we get this far, theyre
1962 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1963 // if we're happy with this, we should send our netburst which
1964 // kickstarts the merge.
1965 return this->Outbound_Reply_Server(params);
1967 else if (command == "ERROR")
1969 return this->Error(params);
1973 // This is the 'authenticated' state, when all passwords
1974 // have been exchanged and anything past this point is taken
1979 std::string direction = prefix;
1980 userrec* t = Srv->FindNick(prefix);
1983 direction = t->server;
1985 TreeServer* route_back_again = BestRouteTo(direction);
1986 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1988 if (route_back_again)
1989 log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1994 * When there is activity on the socket, reset the ping counter so
1995 * that we're not wasting bandwidth pinging an active server.
1997 route_back_again->SetNextPingTime(time(NULL) + 120);
1998 route_back_again->SetPingFlag();
2001 if (command == "SVSMODE")
2003 /* Services expects us to implement
2004 * SVSMODE. In inspircd its the same as
2009 std::string target = "";
2010 /* Yes, know, this is a mess. Its reasonably fast though as we're
2011 * working with std::string here.
2013 if ((command == "NICK") && (params.size() > 1))
2015 return this->IntroduceClient(prefix,params);
2017 else if (command == "FJOIN")
2019 return this->ForceJoin(prefix,params);
2021 else if (command == "SERVER")
2023 return this->RemoteServer(prefix,params);
2025 else if (command == "ERROR")
2027 return this->Error(params);
2029 else if (command == "OPERTYPE")
2031 return this->OperType(prefix,params);
2033 else if (command == "FMODE")
2035 return this->ForceMode(prefix,params);
2037 else if (command == "KILL")
2039 return this->RemoteKill(prefix,params);
2041 else if (command == "FTOPIC")
2043 return this->ForceTopic(prefix,params);
2045 else if (command == "REHASH")
2047 return this->RemoteRehash(prefix,params);
2049 else if (command == "METADATA")
2051 return this->MetaData(prefix,params);
2053 else if (command == "PING")
2055 return this->LocalPing(prefix,params);
2057 else if (command == "PONG")
2059 return this->LocalPong(prefix,params);
2061 else if (command == "VERSION")
2063 return this->ServerVersion(prefix,params);
2065 else if (command == "FHOST")
2067 return this->ChangeHost(prefix,params);
2069 else if (command == "FNAME")
2071 return this->ChangeName(prefix,params);
2073 else if (command == "ADDLINE")
2075 return this->AddLine(prefix,params);
2077 else if (command == "SVSNICK")
2081 prefix = this->GetName();
2083 return this->ForceNick(prefix,params);
2085 else if (command == "IDLE")
2087 return this->Whois(prefix,params);
2089 else if (command == "SVSJOIN")
2093 prefix = this->GetName();
2095 return this->ServiceJoin(prefix,params);
2097 else if (command == "SQUIT")
2099 if (params.size() == 2)
2101 this->Squit(FindServer(params[0]),params[1]);
2105 else if (command == "ENDBURST")
2107 this->bursting = false;
2112 // not a special inter-server command.
2113 // Emulate the actual user doing the command,
2114 // this saves us having a huge ugly parser.
2115 userrec* who = Srv->FindNick(prefix);
2116 std::string sourceserv = this->myhost;
2117 if (this->InboundServerName != "")
2119 sourceserv = this->InboundServerName;
2124 target = who->server;
2125 char* strparams[127];
2126 for (unsigned int q = 0; q < params.size(); q++)
2128 strparams[q] = (char*)params[q].c_str();
2130 Srv->CallCommandHandler(command, strparams, params.size(), who);
2134 // its not a user. Its either a server, or somethings screwed up.
2135 if (IsServer(prefix))
2137 target = Srv->GetServerName();
2141 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2145 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2154 virtual std::string GetName()
2156 std::string sourceserv = this->myhost;
2157 if (this->InboundServerName != "")
2159 sourceserv = this->InboundServerName;
2164 virtual void OnTimeout()
2166 if (this->LinkState == CONNECTING)
2168 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2172 virtual void OnClose()
2174 // Connection closed.
2175 // If the connection is fully up (state CONNECTED)
2176 // then propogate a netsplit to all peers.
2177 std::string quitserver = this->myhost;
2178 if (this->InboundServerName != "")
2180 quitserver = this->InboundServerName;
2182 TreeServer* s = FindServer(quitserver);
2185 Squit(s,"Remote host closed the connection");
2187 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2190 virtual int OnIncomingConnection(int newsock, char* ip)
2192 TreeSocket* s = new TreeSocket(newsock, ip);
2198 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2200 for (unsigned int c = 0; c < list.size(); c++)
2202 if (list[c] == server)
2207 list.push_back(server);
2210 // returns a list of DIRECT servernames for a specific channel
2211 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2213 std::map<char*,char*> *ulist = c->GetUsers();
2214 for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
2216 char* o = i->second;
2217 userrec* otheruser = (userrec*)o;
2218 if (otheruser->fd < 0)
2220 TreeServer* best = BestRouteTo(otheruser->server);
2222 AddThisServer(best,list);
2228 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2230 TreeServer* omitroute = BestRouteTo(omit);
2231 if ((command == "NOTICE") || (command == "PRIVMSG"))
2233 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2235 if (*(params[0].c_str()) != '#')
2237 // special routing for private messages/notices
2238 userrec* d = Srv->FindNick(params[0]);
2241 std::deque<std::string> par;
2242 par.push_back(params[0]);
2243 par.push_back(":"+params[1]);
2244 DoOneToOne(prefix,command,par,d->server);
2250 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2251 chanrec* c = Srv->FindChannel(params[0]);
2254 std::deque<TreeServer*> list;
2255 GetListOfServersForChannel(c,list);
2256 log(DEBUG,"Got a list of %d servers",list.size());
2257 unsigned int lsize = list.size();
2258 for (unsigned int i = 0; i < lsize; i++)
2260 TreeSocket* Sock = list[i]->GetSocket();
2261 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2263 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2264 Sock->WriteLine(data);
2272 unsigned int items = TreeRoot->ChildCount();
2273 for (unsigned int x = 0; x < items; x++)
2275 TreeServer* Route = TreeRoot->GetChild(x);
2276 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2278 TreeSocket* Sock = Route->GetSocket();
2279 Sock->WriteLine(data);
2285 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2287 TreeServer* omitroute = BestRouteTo(omit);
2288 std::string FullLine = ":" + prefix + " " + command;
2289 unsigned int words = params.size();
2290 for (unsigned int x = 0; x < words; x++)
2292 FullLine = FullLine + " " + params[x];
2294 unsigned int items = TreeRoot->ChildCount();
2295 for (unsigned int x = 0; x < items; x++)
2297 TreeServer* Route = TreeRoot->GetChild(x);
2298 // Send the line IF:
2299 // The route has a socket (its a direct connection)
2300 // The route isnt the one to be omitted
2301 // The route isnt the path to the one to be omitted
2302 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2304 TreeSocket* Sock = Route->GetSocket();
2305 Sock->WriteLine(FullLine);
2311 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2313 std::string FullLine = ":" + prefix + " " + command;
2314 unsigned int words = params.size();
2315 for (unsigned int x = 0; x < words; x++)
2317 FullLine = FullLine + " " + params[x];
2319 unsigned int items = TreeRoot->ChildCount();
2320 for (unsigned int x = 0; x < items; x++)
2322 TreeServer* Route = TreeRoot->GetChild(x);
2323 if (Route->GetSocket())
2325 TreeSocket* Sock = Route->GetSocket();
2326 Sock->WriteLine(FullLine);
2332 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2334 TreeServer* Route = BestRouteTo(target);
2337 std::string FullLine = ":" + prefix + " " + command;
2338 unsigned int words = params.size();
2339 for (unsigned int x = 0; x < words; x++)
2341 FullLine = FullLine + " " + params[x];
2343 if (Route->GetSocket())
2345 TreeSocket* Sock = Route->GetSocket();
2346 Sock->WriteLine(FullLine);
2356 std::vector<TreeSocket*> Bindings;
2358 void ReadConfiguration(bool rebind)
2360 Conf = new ConfigReader;
2363 for (int j =0; j < Conf->Enumerate("bind"); j++)
2365 std::string Type = Conf->ReadValue("bind","type",j);
2366 std::string IP = Conf->ReadValue("bind","address",j);
2367 long Port = Conf->ReadInteger("bind","port",j,true);
2368 if (Type == "servers")
2374 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2375 if (listener->GetState() == I_LISTENING)
2377 Srv->AddSocket(listener);
2378 Bindings.push_back(listener);
2382 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2390 for (int j =0; j < Conf->Enumerate("link"); j++)
2393 L.Name = Conf->ReadValue("link","name",j);
2394 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2395 L.Port = Conf->ReadInteger("link","port",j,true);
2396 L.SendPass = Conf->ReadValue("link","sendpass",j);
2397 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2398 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2399 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2400 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
2401 L.NextConnectTime = time(NULL) + L.AutoConnect;
2402 /* Bugfix by brain, do not allow people to enter bad configurations */
2403 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2405 LinkBlocks.push_back(L);
2406 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2410 if (L.RecvPass == "")
2412 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
2414 else if (L.SendPass == "")
2416 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
2418 else if (L.Name == "")
2420 log(DEFAULT,"Invalid configuration, link tag without a name!");
2424 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
2432 class ModuleSpanningTree : public Module
2434 std::vector<TreeSocket*> Bindings;
2440 ModuleSpanningTree(Server* Me)
2441 : Module::Module(Me)
2446 // Create the root of the tree
2447 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2449 ReadConfiguration(true);
2452 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2454 std::string Parent = TreeRoot->GetName();
2455 if (Current->GetParent())
2457 Parent = Current->GetParent()->GetName();
2459 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2461 ShowLinks(Current->GetChild(q),user,hops+1);
2463 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2466 int CountLocalServs()
2468 return TreeRoot->ChildCount();
2473 return serverlist.size();
2476 void HandleLinks(char** parameters, int pcnt, userrec* user)
2478 ShowLinks(TreeRoot,user,0);
2479 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2483 void HandleLusers(char** parameters, int pcnt, userrec* user)
2485 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2486 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2487 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2488 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2489 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2493 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2495 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2499 for (int t = 0; t < depth; t++)
2501 matrix[line][t] = ' ';
2504 // For Aligning, we need to work out exactly how deep this thing is, and produce
2505 // a 'Spacer' String to compensate.
2508 memset(spacer,' ',40);
2509 if ((40 - Current->GetName().length() - depth) > 1) {
2510 spacer[40 - Current->GetName().length() - depth] = '\0';
2519 if (clientlist.size() == 0) {
2520 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
2525 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
2527 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
2528 strlcpy(&matrix[line][depth],text,80);
2530 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2532 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2537 // Ok, prepare to be confused.
2538 // After much mulling over how to approach this, it struck me that
2539 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2540 // keeping track of a ton of ascii characters, and line by line
2541 // under recursion working out where to place them using multiplications
2542 // and divisons, we instead render the map onto a backplane of characters
2543 // (a character matrix), then draw the branches as a series of "L" shapes
2544 // from the nodes. This is not only friendlier on CPU it uses less stack.
2546 void HandleMap(char** parameters, int pcnt, userrec* user)
2548 // This array represents a virtual screen which we will
2549 // "scratch" draw to, as the console device of an irc
2550 // client does not provide for a proper terminal.
2551 char matrix[128][80];
2552 for (unsigned int t = 0; t < 128; t++)
2554 matrix[t][0] = '\0';
2557 // The only recursive bit is called here.
2558 ShowMap(TreeRoot,user,0,matrix);
2559 // Process each line one by one. The algorithm has a limit of
2560 // 128 servers (which is far more than a spanning tree should have
2561 // anyway, so we're ok). This limit can be raised simply by making
2562 // the character matrix deeper, 128 rows taking 10k of memory.
2563 for (int l = 1; l < line; l++)
2565 // scan across the line looking for the start of the
2566 // servername (the recursive part of the algorithm has placed
2567 // the servers at indented positions depending on what they
2569 int first_nonspace = 0;
2570 while (matrix[l][first_nonspace] == ' ')
2575 // Draw the `- (corner) section: this may be overwritten by
2576 // another L shape passing along the same vertical pane, becoming
2577 // a |- (branch) section instead.
2578 matrix[l][first_nonspace] = '-';
2579 matrix[l][first_nonspace-1] = '`';
2581 // Draw upwards until we hit the parent server, causing possibly
2582 // other corners (`-) to become branches (|-)
2583 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2585 matrix[l2][first_nonspace-1] = '|';
2589 // dump the whole lot to the user. This is the easy bit, honest.
2590 for (int t = 0; t < line; t++)
2592 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2594 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2598 int HandleSquit(char** parameters, int pcnt, userrec* user)
2600 TreeServer* s = FindServerMask(parameters[0]);
2605 WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2608 TreeSocket* sock = s->GetSocket();
2611 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2612 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2613 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2614 Srv->RemoveSocket(sock);
2618 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2623 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2628 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2630 if ((user->fd > -1) && (pcnt > 1))
2632 userrec* remote = Srv->FindNick(parameters[1]);
2633 if ((remote) && (remote->fd < 0))
2635 std::deque<std::string> params;
2636 params.push_back(parameters[1]);
2637 DoOneToOne(user->nick,"IDLE",params,remote->server);
2642 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2643 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2650 void DoPingChecks(time_t curtime)
2652 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2654 TreeServer* serv = TreeRoot->GetChild(j);
2655 TreeSocket* sock = serv->GetSocket();
2658 if (curtime >= serv->NextPingTime())
2660 if (serv->AnsweredLastPing())
2662 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2663 serv->SetNextPingTime(curtime + 120);
2667 // they didnt answer, boot them
2668 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2669 sock->Squit(serv,"Ping timeout");
2670 Srv->RemoveSocket(sock);
2679 void AutoConnectServers(time_t curtime)
2681 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2683 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2685 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2686 x->NextConnectTime = curtime + x->AutoConnect;
2687 TreeServer* CheckDupe = FindServer(x->Name);
2690 // an autoconnected server is not connected. Check if its time to connect it
2691 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2692 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2693 Srv->AddSocket(newsocket);
2699 int HandleVersion(char** parameters, int pcnt, userrec* user)
2701 // we've already checked if pcnt > 0, so this is safe
2702 TreeServer* found = FindServerMask(parameters[0]);
2705 std::string Version = found->GetVersion();
2706 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2707 if (found == TreeRoot)
2709 std::stringstream out(Config->data005);
2710 std::string token = "";
2711 std::string line5 = "";
2712 int token_counter = 0;
2716 line5 = line5 + token + " ";
2718 if ((token_counter >= 13) || (out.eof() == true))
2720 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2729 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2734 int HandleConnect(char** parameters, int pcnt, userrec* user)
2736 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2738 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2740 TreeServer* CheckDupe = FindServer(x->Name);
2743 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
2744 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2745 Srv->AddSocket(newsocket);
2750 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());
2755 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2759 virtual int OnStats(char statschar, userrec* user)
2761 if (statschar == 'c')
2763 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2765 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %c%c%c",user->nick,(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr).c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-'),(LinkBlocks[i].AutoConnect ? 'a' : '-'),'s');
2766 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2768 WriteServ(user->fd,"219 %s %c :End of /STATS report",user->nick,statschar);
2769 WriteOpers("*** Notice: Stats '%c' requested by %s (%s@%s)",statschar,user->nick,user->ident,user->host);
2775 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2777 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2781 if (command == "CONNECT")
2783 return this->HandleConnect(parameters,pcnt,user);
2785 else if (command == "SQUIT")
2787 return this->HandleSquit(parameters,pcnt,user);
2789 else if (command == "MAP")
2791 this->HandleMap(parameters,pcnt,user);
2794 else if (command == "LUSERS")
2796 this->HandleLusers(parameters,pcnt,user);
2799 else if (command == "LINKS")
2801 this->HandleLinks(parameters,pcnt,user);
2804 else if (command == "WHOIS")
2809 return this->HandleRemoteWhois(parameters,pcnt,user);
2812 else if ((command == "VERSION") && (pcnt > 0))
2814 this->HandleVersion(parameters,pcnt,user);
2817 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2819 // this bit of code cleverly routes all module commands
2820 // to all remote severs *automatically* so that modules
2821 // can just handle commands locally, without having
2822 // to have any special provision in place for remote
2823 // commands and linking protocols.
2824 std::deque<std::string> params;
2826 for (int j = 0; j < pcnt; j++)
2828 if (strchr(parameters[j],' '))
2830 params.push_back(":" + std::string(parameters[j]));
2834 params.push_back(std::string(parameters[j]));
2837 DoOneToMany(user->nick,command,params);
2842 virtual void OnGetServerDescription(std::string servername,std::string &description)
2844 TreeServer* s = FindServer(servername);
2847 description = s->GetDesc();
2851 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2853 if (source->fd > -1)
2855 std::deque<std::string> params;
2856 params.push_back(dest->nick);
2857 params.push_back(channel->name);
2858 DoOneToMany(source->nick,"INVITE",params);
2862 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2864 std::deque<std::string> params;
2865 params.push_back(chan->name);
2866 params.push_back(":"+topic);
2867 DoOneToMany(user->nick,"TOPIC",params);
2870 virtual void OnWallops(userrec* user, std::string text)
2874 std::deque<std::string> params;
2875 params.push_back(":"+text);
2876 DoOneToMany(user->nick,"WALLOPS",params);
2880 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2882 if (target_type == TYPE_USER)
2884 userrec* d = (userrec*)dest;
2885 if ((d->fd < 0) && (user->fd > -1))
2887 std::deque<std::string> params;
2889 params.push_back(d->nick);
2890 params.push_back(":"+text);
2891 DoOneToOne(user->nick,"NOTICE",params,d->server);
2898 chanrec *c = (chanrec*)dest;
2899 std::deque<TreeServer*> list;
2900 GetListOfServersForChannel(c,list);
2901 unsigned int ucount = list.size();
2902 for (unsigned int i = 0; i < ucount; i++)
2904 TreeSocket* Sock = list[i]->GetSocket();
2906 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2912 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2914 if (target_type == TYPE_USER)
2916 // route private messages which are targetted at clients only to the server
2917 // which needs to receive them
2918 userrec* d = (userrec*)dest;
2919 if ((d->fd < 0) && (user->fd > -1))
2921 std::deque<std::string> params;
2923 params.push_back(d->nick);
2924 params.push_back(":"+text);
2925 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2932 chanrec *c = (chanrec*)dest;
2933 std::deque<TreeServer*> list;
2934 GetListOfServersForChannel(c,list);
2935 unsigned int ucount = list.size();
2936 for (unsigned int i = 0; i < ucount; i++)
2938 TreeSocket* Sock = list[i]->GetSocket();
2940 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2946 virtual void OnBackgroundTimer(time_t curtime)
2948 AutoConnectServers(curtime);
2949 DoPingChecks(curtime);
2952 virtual void OnUserJoin(userrec* user, chanrec* channel)
2954 // Only do this for local users
2957 std::deque<std::string> params;
2959 params.push_back(channel->name);
2962 // if the channel has a key, force the join by emulating the key.
2963 params.push_back(channel->key);
2965 if (channel->GetUserCounter() > 1)
2967 // not the first in the channel
2968 DoOneToMany(user->nick,"JOIN",params);
2972 // first in the channel, set up their permissions
2973 // and the channel TS with FJOIN.
2975 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2977 params.push_back(channel->name);
2978 params.push_back(ts);
2979 params.push_back("@"+std::string(user->nick));
2980 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2985 virtual void OnChangeHost(userrec* user, std::string newhost)
2987 // only occurs for local clients
2988 if (user->registered != 7)
2990 std::deque<std::string> params;
2991 params.push_back(newhost);
2992 DoOneToMany(user->nick,"FHOST",params);
2995 virtual void OnChangeName(userrec* user, std::string gecos)
2997 // only occurs for local clients
2998 if (user->registered != 7)
3000 std::deque<std::string> params;
3001 params.push_back(gecos);
3002 DoOneToMany(user->nick,"FNAME",params);
3005 virtual void OnUserPart(userrec* user, chanrec* channel, std::string partmessage)
3009 std::deque<std::string> params;
3010 params.push_back(channel->name);
3011 if (partmessage != "")
3012 params.push_back(":"+partmessage);
3013 DoOneToMany(user->nick,"PART",params);
3017 virtual void OnUserConnect(userrec* user)
3019 char agestr[MAXBUF];
3022 std::deque<std::string> params;
3023 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
3024 params.push_back(agestr);
3025 params.push_back(user->nick);
3026 params.push_back(user->host);
3027 params.push_back(user->dhost);
3028 params.push_back(user->ident);
3029 params.push_back("+"+std::string(user->modes));
3030 params.push_back(user->ip);
3031 params.push_back(":"+std::string(user->fullname));
3032 DoOneToMany(Srv->GetServerName(),"NICK",params);
3034 // User is Local, change needs to be reflected!
3035 TreeServer* SourceServer = FindServer(user->server);
3037 SourceServer->AddUserCount();
3043 virtual void OnUserQuit(userrec* user, std::string reason)
3045 if ((user->fd > -1) && (user->registered == 7))
3047 std::deque<std::string> params;
3048 params.push_back(":"+reason);
3049 DoOneToMany(user->nick,"QUIT",params);
3051 // Regardless, We need to modify the user Counts..
3052 TreeServer* SourceServer = FindServer(user->server);
3054 SourceServer->DelUserCount();
3059 virtual void OnUserPostNick(userrec* user, std::string oldnick)
3063 std::deque<std::string> params;
3064 params.push_back(user->nick);
3065 DoOneToMany(oldnick,"NICK",params);
3069 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
3071 if ((source) && (source->fd > -1))
3073 std::deque<std::string> params;
3074 params.push_back(chan->name);
3075 params.push_back(user->nick);
3076 params.push_back(":"+reason);
3077 DoOneToMany(source->nick,"KICK",params);
3081 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
3083 std::deque<std::string> params;
3084 params.push_back(dest->nick);
3085 params.push_back(":"+reason);
3086 DoOneToMany(source->nick,"KILL",params);
3089 virtual void OnRehash(std::string parameter)
3091 if (parameter != "")
3093 std::deque<std::string> params;
3094 params.push_back(parameter);
3095 DoOneToMany(Srv->GetServerName(),"REHASH",params);
3097 if (Srv->MatchText(Srv->GetServerName(),parameter))
3099 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
3100 Srv->RehashServer();
3103 ReadConfiguration(false);
3106 // note: the protocol does not allow direct umode +o except
3107 // via NICK with 8 params. sending OPERTYPE infers +o modechange
3109 virtual void OnOper(userrec* user, std::string opertype)
3113 std::deque<std::string> params;
3114 params.push_back(opertype);
3115 DoOneToMany(user->nick,"OPERTYPE",params);
3119 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
3121 if (source->fd > -1)
3124 snprintf(type,8,"%cLINE",linetype);
3125 std::string stype = type;
3128 char sduration[MAXBUF];
3129 snprintf(sduration,MAXBUF,"%ld",duration);
3130 std::deque<std::string> params;
3131 params.push_back(host);
3132 params.push_back(sduration);
3133 params.push_back(":"+reason);
3134 DoOneToMany(source->nick,stype,params);
3138 std::deque<std::string> params;
3139 params.push_back(host);
3140 DoOneToMany(source->nick,stype,params);
3145 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3147 OnLine(source,hostmask,true,'G',duration,reason);
3150 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3152 OnLine(source,ipmask,true,'Z',duration,reason);
3155 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3157 OnLine(source,nickmask,true,'Q',duration,reason);
3160 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3162 OnLine(source,hostmask,true,'E',duration,reason);
3165 virtual void OnDelGLine(userrec* source, std::string hostmask)
3167 OnLine(source,hostmask,false,'G',0,"");
3170 virtual void OnDelZLine(userrec* source, std::string ipmask)
3172 OnLine(source,ipmask,false,'Z',0,"");
3175 virtual void OnDelQLine(userrec* source, std::string nickmask)
3177 OnLine(source,nickmask,false,'Q',0,"");
3180 virtual void OnDelELine(userrec* source, std::string hostmask)
3182 OnLine(source,hostmask,false,'E',0,"");
3185 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3187 if ((user->fd > -1) && (user->registered == 7))
3189 if (target_type == TYPE_USER)
3191 userrec* u = (userrec*)dest;
3192 std::deque<std::string> params;
3193 params.push_back(u->nick);
3194 params.push_back(text);
3195 DoOneToMany(user->nick,"MODE",params);
3199 chanrec* c = (chanrec*)dest;
3200 std::deque<std::string> params;
3201 params.push_back(c->name);
3202 params.push_back(text);
3203 DoOneToMany(user->nick,"MODE",params);
3208 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3210 TreeSocket* s = (TreeSocket*)opaque;
3213 if (target_type == TYPE_USER)
3215 userrec* u = (userrec*)target;
3216 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3220 chanrec* c = (chanrec*)target;
3221 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3226 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3228 TreeSocket* s = (TreeSocket*)opaque;
3231 if (target_type == TYPE_USER)
3233 userrec* u = (userrec*)target;
3234 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3238 chanrec* c = (chanrec*)target;
3239 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3244 virtual ~ModuleSpanningTree()
3248 virtual Version GetVersion()
3250 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3253 void Implements(char* List)
3255 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3256 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3257 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3258 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3259 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3260 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3261 List[I_OnStats] = List[I_ProtoSendMetaData] = 1;
3264 /* It is IMPORTANT that m_spanningtree is the last module in the chain
3265 * so that any activity it sees is FINAL, e.g. we arent going to send out
3266 * a NICK message before m_cloaking has finished putting the +x on the user,
3268 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
3269 * the module call queue.
3271 Priority Prioritize()
3273 return PRIORITY_LAST;
3278 class ModuleSpanningTreeFactory : public ModuleFactory
3281 ModuleSpanningTreeFactory()
3285 ~ModuleSpanningTreeFactory()
3289 virtual Module * CreateModule(Server* Me)
3291 TreeProtocolModule = new ModuleSpanningTree(Me);
3292 return TreeProtocolModule;
3298 extern "C" void * init_module( void )
3300 return new ModuleSpanningTreeFactory;