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(q),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 bool IntroduceClient(std::string source, std::deque<std::string> params)
303 // NICK age nick host dhost ident +modes ip :gecos
305 std::string nick = params[1];
306 std::string host = params[2];
307 std::string dhost = params[3];
308 std::string ident = params[4];
309 time_t age = atoi(params[0].c_str());
310 std::string modes = params[5];
311 std::string ip = params[6];
312 std::string gecos = params[7];
313 char* tempnick = (char*)nick.c_str();
314 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
316 user_hash::iterator iter;
317 iter = clientlist.find(tempnick);
318 if (iter != clientlist.end())
321 log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
325 clientlist[tempnick] = new userrec();
326 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
327 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
328 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
329 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
330 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
331 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
332 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
333 clientlist[tempnick]->registered = 7;
334 clientlist[tempnick]->signon = age;
335 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
336 for (int i = 0; i < MAXCHANS; i++)
338 clientlist[tempnick]->chans[i].channel = NULL;
339 clientlist[tempnick]->chans[i].uc_modes = 0;
344 // send all users and their channels
345 void SendUsers(TreeServer* Current)
348 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
350 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);
351 this->WriteLine(data);
352 if (strchr(u->second->modes,'o'))
354 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
356 char* chl = chlist(u->second,u->second);
359 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
364 void DoBurst(TreeServer* s)
366 log(DEBUG,"Beginning network burst");
367 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
368 this->WriteLine("BURST");
370 this->SendServers(TreeRoot,s,1);
371 // Send users and their channels
373 // TODO: Send everything else (channel modes etc)
374 this->WriteLine("ENDBURST");
377 virtual bool OnDataReady()
379 char* data = this->Read();
382 this->in_buffer += data;
383 while (in_buffer.find("\n") != std::string::npos)
385 char* line = (char*)in_buffer.c_str();
386 std::string ret = "";
387 while ((*line != '\n') && (strlen(line)))
392 if ((*line == '\n') || (*line == '\r'))
395 if (!this->ProcessLine(ret))
401 return (data != NULL);
404 int WriteLine(std::string line)
406 return this->Write(line + "\r\n");
409 bool Error(std::deque<std::string> params)
411 if (params.size() < 1)
413 std::string Errmsg = params[0];
414 std::string SName = myhost;
415 if (InboundServerName != "")
417 SName = InboundServerName;
419 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
420 // we will return false to cause the socket to close.
424 bool Outbound_Reply_Server(std::deque<std::string> params)
426 if (params.size() < 4)
428 std::string servername = params[0];
429 std::string password = params[1];
430 int hops = atoi(params[2].c_str());
433 this->WriteLine("ERROR :Server too far away for authentication");
436 std::string description = params[3];
437 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
439 if ((x->Name == servername) && (x->RecvPass == password))
441 // Begin the sync here. this kickstarts the
442 // other side, waiting in WAIT_AUTH_2 state,
443 // into starting their burst, as it shows
445 this->LinkState = CONNECTED;
446 // we should add the details of this server now
447 // to the servers tree, as a child of the root
449 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
450 TreeRoot->AddChild(Node);
455 this->WriteLine("ERROR :Invalid credentials");
459 bool Inbound_Server(std::deque<std::string> params)
461 if (params.size() < 4)
463 std::string servername = params[0];
464 std::string password = params[1];
465 int hops = atoi(params[2].c_str());
468 this->WriteLine("ERROR :Server too far away for authentication");
471 std::string description = params[3];
472 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
474 if ((x->Name == servername) && (x->RecvPass == password))
476 Srv->SendOpers("*** Verified incoming server connection from "+servername+"["+this->GetIP()+"] ("+description+")");
477 this->InboundServerName = servername;
478 this->InboundDescription = description;
479 // this is good. Send our details: Our server name and description and hopcount of 0,
480 // along with the sendpass from this block.
481 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
482 // move to the next state, we are now waiting for THEM.
483 this->LinkState = WAIT_AUTH_2;
487 this->WriteLine("ERROR :Invalid credentials");
491 std::deque<std::string> Split(std::string line)
493 std::deque<std::string> n;
494 std::stringstream s(line);
495 std::string param = "";
501 if ((param.c_str()[0] == ':') && (item))
503 char* str = (char*)param.c_str();
513 param = param + " " + append;
523 bool ProcessLine(std::string line)
525 Srv->SendToModeMask("o",WM_AND,"inbound-line: '"+line+"'");
527 std::deque<std::string> params = this->Split(line);
528 std::string command = "";
529 std::string prefix = "";
530 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
534 char* pref = (char*)prefix.c_str();
546 switch (this->LinkState)
551 // Waiting for SERVER command from remote server. Server initiating
552 // the connection sends the first SERVER command, listening server
553 // replies with theirs if its happy, then if the initiator is happy,
554 // it starts to send its net sync, which starts the merge, otherwise
555 // it sends an ERROR.
556 if (command == "SERVER")
558 return this->Inbound_Server(params);
560 else if (command == "ERROR")
562 return this->Error(params);
566 // Waiting for start of other side's netmerge to say they liked our
568 if (command == "SERVER")
570 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
574 else if (command == "BURST")
576 this->LinkState = CONNECTED;
577 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
578 TreeRoot->AddChild(Node);
581 else if (command == "ERROR")
583 return this->Error(params);
588 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
592 if (command == "SERVER")
594 // another server we connected to, which was in WAIT_AUTH_1 state,
595 // has just sent us their credentials. If we get this far, theyre
596 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
597 // if we're happy with this, we should send our netburst which
598 // kickstarts the merge.
599 return this->Outbound_Reply_Server(params);
603 // This is the 'authenticated' state, when all passwords
604 // have been exchanged and anything past this point is taken
606 if ((command == "NICK") && (params.size() > 1))
608 return this->IntroduceClient(prefix,params);
616 virtual void OnTimeout()
618 if (this->LinkState = CONNECTING)
620 Srv->SendOpers("*** CONNECT: Connection to "+myhost+" timed out.");
624 virtual void OnClose()
628 virtual int OnIncomingConnection(int newsock, char* ip)
630 TreeSocket* s = new TreeSocket(newsock, ip);
636 class ModuleSpanningTree : public Module
638 std::vector<TreeSocket*> Bindings;
642 void ReadConfiguration(bool rebind)
646 for (int j =0; j < Conf->Enumerate("bind"); j++)
648 std::string Type = Conf->ReadValue("bind","type",j);
649 std::string IP = Conf->ReadValue("bind","address",j);
650 long Port = Conf->ReadInteger("bind","port",j,true);
651 if (Type == "servers")
657 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
658 if (listener->GetState() == I_LISTENING)
660 Srv->AddSocket(listener);
661 Bindings.push_back(listener);
665 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
673 for (int j =0; j < Conf->Enumerate("link"); j++)
676 L.Name = Conf->ReadValue("link","name",j);
677 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
678 L.Port = Conf->ReadInteger("link","port",j,true);
679 L.SendPass = Conf->ReadValue("link","sendpass",j);
680 L.RecvPass = Conf->ReadValue("link","recvpass",j);
681 LinkBlocks.push_back(L);
682 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
689 Conf = new ConfigReader;
692 // Create the root of the tree
693 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
695 ReadConfiguration(true);
698 void HandleLinks(char** parameters, int pcnt, userrec* user)
703 void HandleLusers(char** parameters, int pcnt, userrec* user)
708 void HandleMap(char** parameters, int pcnt, userrec* user)
713 int HandleSquit(char** parameters, int pcnt, userrec* user)
718 int HandleConnect(char** parameters, int pcnt, userrec* user)
720 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
722 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
724 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
725 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
726 Srv->AddSocket(newsocket);
730 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
734 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
736 if (command == "CONNECT")
738 return this->HandleConnect(parameters,pcnt,user);
740 else if (command == "SQUIT")
742 return this->HandleSquit(parameters,pcnt,user);
744 else if (command == "MAP")
746 this->HandleMap(parameters,pcnt,user);
749 else if (command == "LUSERS")
751 this->HandleLusers(parameters,pcnt,user);
754 else if (command == "LINKS")
756 this->HandleLinks(parameters,pcnt,user);
762 virtual ~ModuleSpanningTree()
767 virtual Version GetVersion()
769 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
774 class ModuleSpanningTreeFactory : public ModuleFactory
777 ModuleSpanningTreeFactory()
781 ~ModuleSpanningTreeFactory()
785 virtual Module * CreateModule()
787 return new ModuleSpanningTree;
793 extern "C" void * init_module( void )
795 return new ModuleSpanningTreeFactory;