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 * ---------------------------------------------------
23 #include "inspircd_config.h"
25 #include <ext/hash_map>
33 #include "helperfuncs.h"
35 #include "inspstring.h"
40 #define nspace __gnu_cxx
45 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
47 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
48 extern user_hash clientlist;
56 std::vector<TreeServer*> Children;
57 std::string ServerName;
58 std::string ServerDesc;
59 std::string VersionString;
62 TreeSocket* Socket; // for directly connected servers this points at the socket object
72 UserCount = OperCount = 0;
75 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
79 UserCount = OperCount = 0;
82 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
85 UserCount = OperCount = 0;
90 return this->ServerName;
95 return this->ServerDesc;
98 std::string GetVersion()
100 return this->VersionString;
105 return this->UserCount;
110 return this->OperCount;
113 TreeSocket* GetSocket()
118 TreeServer* GetParent()
123 unsigned int ChildCount()
125 return Children.size();
128 TreeServer* GetChild(unsigned int n)
130 if (n < Children.size())
140 void AddChild(TreeServer* Child)
142 Children.push_back(Child);
145 bool DelChild(TreeServer* Child)
147 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
165 std::string SendPass;
166 std::string RecvPass;
169 /* $ModDesc: Povides a spanning tree server link protocol */
173 TreeServer *TreeRoot;
174 std::vector<Link> LinkBlocks;
176 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
178 if (Current->GetName() == ServerName)
180 for (unsigned int q = 0; q < Current->ChildCount(); q++)
182 TreeServer* found = RouteEnumerate(Current->GetChild(),ServerName);
191 // Returns the locally connected server we must route a
192 // message through to reach server 'ServerName'. This
193 // only applies to one-to-one and not one-to-many routing.
194 TreeServer* BestRouteTo(std::string ServerName)
196 log(DEBUG,"Finding best route to %s",ServerName.c_str());
197 // first, find the server by recursively walking the tree
198 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
199 // did we find it? If not, they did something wrong, abort.
202 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
207 // The server exists, follow its parent nodes until
208 // the parent of the current is 'TreeRoot', we know
209 // then that this is a directly-connected server.
210 while ((Found) && (Found->GetParent() != TreeRoot))
212 Found = Found->GetParent();
214 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
219 class TreeSocket : public InspSocket
222 std::string in_buffer;
223 ServerState LinkState;
224 std::string InboundServerName;
225 std::string InboundDescription;
229 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
230 : InspSocket(host, port, listening, maxtime)
232 Srv->Log(DEBUG,"Create new listening");
234 this->LinkState = LISTENER;
237 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
238 : InspSocket(host, port, listening, maxtime)
240 Srv->Log(DEBUG,"Create new outbound");
242 this->LinkState = CONNECTING;
245 TreeSocket(int newfd, char* ip)
246 : InspSocket(newfd, ip)
248 Srv->Log(DEBUG,"Associate new inbound");
249 this->LinkState = WAIT_AUTH_1;
252 virtual bool OnConnected()
254 if (this->LinkState == CONNECTING)
256 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
257 // we should send our details here.
258 // if the other side is satisfied, they send theirs.
259 // we do not need to change state here.
260 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
262 if (x->Name == this->myhost)
264 // found who we're supposed to be connecting to, send the neccessary gubbins.
265 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
270 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
274 virtual void OnError(InspSocketError e)
278 virtual int OnDisconnect()
283 // recursively send the server tree with distances as hops
284 void SendServers(TreeServer* Current, TreeServer* s, int hops)
287 for (unsigned int q = 0; q < Current->ChildCount(); q++)
289 TreeServer* recursive_server = Current->GetChild(q);
290 if (recursive_server != s)
292 // :source.server SERVER server.name hops :Description
293 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
294 this->WriteLine(command);
295 // down to next level
296 this->SendServers(recursive_server, s, hops+1);
301 // send all users and their channels
302 void SendUsers(TreeServer* Current)
305 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
307 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);
308 this->WriteLine(data);
309 if (strchr(u->second->modes,'o'))
311 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
313 char* chl = chlist(u->second,u->second);
316 this->WriteLine(":"+std::string(u->second->nick)+" JOIN "+std::string(chl));
321 void DoBurst(TreeServer* s)
323 log(DEBUG,"Beginning network burst");
324 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
325 this->WriteLine("BURST");
327 this->SendServers(TreeRoot,s,1);
328 // Send users and their channels
330 // TODO: Send everything else
331 this->WriteLine("ENDBURST");
334 virtual bool OnDataReady()
336 char* data = this->Read();
339 this->in_buffer += data;
340 while (in_buffer.find("\n") != std::string::npos)
342 char* line = (char*)in_buffer.c_str();
343 std::string ret = "";
344 while ((*line != '\n') && (strlen(line)))
349 if ((*line == '\n') || (*line == '\r'))
352 if (!this->ProcessLine(ret))
358 return (data != NULL);
361 int WriteLine(std::string line)
363 return this->Write(line + "\r\n");
366 bool Error(std::deque<std::string> params)
368 if (params.size() < 1)
370 std::string Errmsg = params[0];
371 std::string SName = myhost;
372 if (InboundServerName != "")
374 SName = InboundServerName;
376 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
377 // we will return false to cause the socket to close.
381 bool Outbound_Reply_Server(std::deque<std::string> params)
383 if (params.size() < 4)
385 std::string servername = params[0];
386 std::string password = params[1];
387 int hops = atoi(params[2].c_str());
390 this->WriteLine("ERROR :Server too far away for authentication");
393 std::string description = params[3];
394 Srv->SendToModeMask("o",WM_AND,"outbound-server-replied: name='"+servername+"' pass='"+password+"' description='"+description+"'");
395 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
397 if ((x->Name == servername) && (x->RecvPass == password))
399 // Begin the sync here. this kickstarts the
400 // other side, waiting in WAIT_AUTH_2 state,
401 // into starting their burst, as it shows
403 this->LinkState = CONNECTED;
404 // we should add the details of this server now
405 // to the servers tree, as a child of the root
407 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
408 TreeRoot->AddChild(Node);
413 this->WriteLine("ERROR :Invalid credentials");
417 bool Inbound_Server(std::deque<std::string> params)
419 if (params.size() < 4)
421 std::string servername = params[0];
422 std::string password = params[1];
423 int hops = atoi(params[2].c_str());
426 this->WriteLine("ERROR :Server too far away for authentication");
429 std::string description = params[3];
430 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
432 if ((x->Name == servername) && (x->RecvPass == password))
434 Srv->SendOpers("*** Verified incoming server connection from "+servername+"["+this->GetIP()+"] ("+description+")");
435 this->InboundServerName = servername;
436 this->InboundDescription = description;
437 // this is good. Send our details: Our server name and description and hopcount of 0,
438 // along with the sendpass from this block.
439 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
440 // move to the next state, we are now waiting for THEM.
441 this->LinkState = WAIT_AUTH_2;
445 this->WriteLine("ERROR :Invalid credentials");
449 std::deque<std::string> Split(std::string line)
451 std::deque<std::string> n;
452 std::stringstream s(line);
453 std::string param = "";
459 if ((param.c_str()[0] == ':') && (item))
461 char* str = (char*)param.c_str();
471 param = param + " " + append;
481 bool ProcessLine(std::string line)
483 Srv->SendToModeMask("o",WM_AND,"inbound-line: '"+line+"'");
485 std::deque<std::string> params = this->Split(line);
486 std::string command = "";
487 std::string prefix = "";
488 if ((params[0].c_str())[0] == ':')
502 switch (this->LinkState)
507 // Waiting for SERVER command from remote server. Server initiating
508 // the connection sends the first SERVER command, listening server
509 // replies with theirs if its happy, then if the initiator is happy,
510 // it starts to send its net sync, which starts the merge, otherwise
511 // it sends an ERROR.
512 if (command == "SERVER")
514 return this->Inbound_Server(params);
516 else if (command == "ERROR")
518 return this->Error(params);
522 // Waiting for start of other side's netmerge to say they liked our
524 if (command == "SERVER")
526 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
530 else if (command == "BURST")
532 this->LinkState = CONNECTED;
533 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
534 TreeRoot->AddChild(Node);
537 else if (command == "ERROR")
539 return this->Error(params);
544 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
548 if (command == "SERVER")
550 // another server we connected to, which was in WAIT_AUTH_1 state,
551 // has just sent us their credentials. If we get this far, theyre
552 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
553 // if we're happy with this, we should send our netburst which
554 // kickstarts the merge.
555 return this->Outbound_Reply_Server(params);
559 // This is the 'authenticated' state, when all passwords
560 // have been exchanged and anything past this point is taken
568 virtual void OnTimeout()
570 if (this->LinkState = CONNECTING)
572 Srv->SendOpers("*** CONNECT: Connection to "+myhost+" timed out.");
576 virtual void OnClose()
580 virtual int OnIncomingConnection(int newsock, char* ip)
582 TreeSocket* s = new TreeSocket(newsock, ip);
588 class ModuleSpanningTree : public Module
590 std::vector<TreeSocket*> Bindings;
594 void ReadConfiguration(bool rebind)
598 for (int j =0; j < Conf->Enumerate("bind"); j++)
600 std::string Type = Conf->ReadValue("bind","type",j);
601 std::string IP = Conf->ReadValue("bind","address",j);
602 long Port = Conf->ReadInteger("bind","port",j,true);
603 if (Type == "servers")
609 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
610 if (listener->GetState() == I_LISTENING)
612 Srv->AddSocket(listener);
613 Bindings.push_back(listener);
617 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
625 for (int j =0; j < Conf->Enumerate("link"); j++)
628 L.Name = Conf->ReadValue("link","name",j);
629 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
630 L.Port = Conf->ReadInteger("link","port",j,true);
631 L.SendPass = Conf->ReadValue("link","sendpass",j);
632 L.RecvPass = Conf->ReadValue("link","recvpass",j);
633 LinkBlocks.push_back(L);
634 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
641 Conf = new ConfigReader;
644 // Create the root of the tree
645 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
647 ReadConfiguration(true);
650 void HandleLinks(char** parameters, int pcnt, userrec* user)
655 void HandleLusers(char** parameters, int pcnt, userrec* user)
660 void HandleMap(char** parameters, int pcnt, userrec* user)
665 int HandleSquit(char** parameters, int pcnt, userrec* user)
670 int HandleConnect(char** parameters, int pcnt, userrec* user)
672 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
674 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
676 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
677 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
678 Srv->AddSocket(newsocket);
682 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
686 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
688 if (command == "CONNECT")
690 return this->HandleConnect(parameters,pcnt,user);
692 else if (command == "SQUIT")
694 return this->HandleSquit(parameters,pcnt,user);
696 else if (command == "MAP")
698 this->HandleMap(parameters,pcnt,user);
701 else if (command == "LUSERS")
703 this->HandleLusers(parameters,pcnt,user);
706 else if (command == "LINKS")
708 this->HandleLinks(parameters,pcnt,user);
714 virtual ~ModuleSpanningTree()
719 virtual Version GetVersion()
721 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
726 class ModuleSpanningTreeFactory : public ModuleFactory
729 ModuleSpanningTreeFactory()
733 ~ModuleSpanningTreeFactory()
737 virtual Module * CreateModule()
739 return new ModuleSpanningTree;
745 extern "C" void * init_module( void )
747 return new ModuleSpanningTreeFactory;