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;
50 const char* OneToEither[] = { "PRIVMSG", "NOTICE", NULL };
51 const char* OneToMany[] = { "NICK", "QUIT", "JOIN", "PART", "MODE", "INVITE", "KICK", "KILL", NULL };
52 const char* OneToOne[] = { "REHASH", "DIE", "TRACE", "WHOIS", NULL };
57 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
58 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
59 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
64 std::vector<TreeServer*> Children;
65 std::string ServerName;
66 std::string ServerDesc;
67 std::string VersionString;
70 TreeSocket* Socket; // for directly connected servers this points at the socket object
80 UserCount = OperCount = 0;
83 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
87 UserCount = OperCount = 0;
90 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
93 UserCount = OperCount = 0;
98 return this->ServerName;
101 std::string GetDesc()
103 return this->ServerDesc;
106 std::string GetVersion()
108 return this->VersionString;
113 return this->UserCount;
118 return this->OperCount;
121 TreeSocket* GetSocket()
126 TreeServer* GetParent()
131 unsigned int ChildCount()
133 return Children.size();
136 TreeServer* GetChild(unsigned int n)
138 if (n < Children.size())
148 void AddChild(TreeServer* Child)
150 Children.push_back(Child);
153 bool DelChild(TreeServer* Child)
155 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
173 std::string SendPass;
174 std::string RecvPass;
177 /* $ModDesc: Povides a spanning tree server link protocol */
181 TreeServer *TreeRoot;
182 std::vector<Link> LinkBlocks;
184 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
186 if (Current->GetName() == ServerName)
188 for (unsigned int q = 0; q < Current->ChildCount(); q++)
190 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
199 // Returns the locally connected server we must route a
200 // message through to reach server 'ServerName'. This
201 // only applies to one-to-one and not one-to-many routing.
202 TreeServer* BestRouteTo(std::string ServerName)
204 log(DEBUG,"Finding best route to %s",ServerName.c_str());
205 // first, find the server by recursively walking the tree
206 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
207 // did we find it? If not, they did something wrong, abort.
210 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
215 // The server exists, follow its parent nodes until
216 // the parent of the current is 'TreeRoot', we know
217 // then that this is a directly-connected server.
218 while ((Found) && (Found->GetParent() != TreeRoot))
220 Found = Found->GetParent();
222 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
227 bool LookForServer(TreeServer* Current, std::string ServerName)
229 if (ServerName == Current->GetName())
231 for (unsigned int q = 0; q < Current->ChildCount(); q++)
233 if (LookForServer(Current->GetChild(q),ServerName))
239 bool IsServer(std::string ServerName)
241 return LookForServer(TreeRoot,ServerName);
244 class TreeSocket : public InspSocket
247 std::string in_buffer;
248 ServerState LinkState;
249 std::string InboundServerName;
250 std::string InboundDescription;
254 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
255 : InspSocket(host, port, listening, maxtime)
257 Srv->Log(DEBUG,"Create new listening");
259 this->LinkState = LISTENER;
262 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
263 : InspSocket(host, port, listening, maxtime)
265 Srv->Log(DEBUG,"Create new outbound");
267 this->LinkState = CONNECTING;
270 TreeSocket(int newfd, char* ip)
271 : InspSocket(newfd, ip)
273 Srv->Log(DEBUG,"Associate new inbound");
274 this->LinkState = WAIT_AUTH_1;
277 virtual bool OnConnected()
279 if (this->LinkState == CONNECTING)
281 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
282 // we should send our details here.
283 // if the other side is satisfied, they send theirs.
284 // we do not need to change state here.
285 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
287 if (x->Name == this->myhost)
289 // found who we're supposed to be connecting to, send the neccessary gubbins.
290 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
295 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
299 virtual void OnError(InspSocketError e)
303 virtual int OnDisconnect()
308 // recursively send the server tree with distances as hops
309 void SendServers(TreeServer* Current, TreeServer* s, int hops)
312 for (unsigned int q = 0; q < Current->ChildCount(); q++)
314 TreeServer* recursive_server = Current->GetChild(q);
315 if (recursive_server != s)
317 // :source.server SERVER server.name hops :Description
318 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
319 this->WriteLine(command);
320 // down to next level
321 this->SendServers(recursive_server, s, hops+1);
326 bool IntroduceClient(std::string source, std::deque<std::string> params)
328 // NICK age nick host dhost ident +modes ip :gecos
330 std::string nick = params[1];
331 std::string host = params[2];
332 std::string dhost = params[3];
333 std::string ident = params[4];
334 time_t age = atoi(params[0].c_str());
335 std::string modes = params[5];
336 std::string ip = params[6];
337 std::string gecos = params[7];
338 char* tempnick = (char*)nick.c_str();
339 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
341 user_hash::iterator iter;
342 iter = clientlist.find(tempnick);
343 if (iter != clientlist.end())
346 log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
350 clientlist[tempnick] = new userrec();
351 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
352 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
353 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
354 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
355 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
356 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
357 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
358 clientlist[tempnick]->registered = 7;
359 clientlist[tempnick]->signon = age;
360 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
361 for (int i = 0; i < MAXCHANS; i++)
363 clientlist[tempnick]->chans[i].channel = NULL;
364 clientlist[tempnick]->chans[i].uc_modes = 0;
366 DoOneToAllButSender(source,"NICK",params,source);
370 // send all users and their channels
371 void SendUsers(TreeServer* Current)
374 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
376 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);
377 this->WriteLine(data);
378 if (strchr(u->second->modes,'o'))
380 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
382 char* chl = chlist(u->second,u->second);
385 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
390 void DoBurst(TreeServer* s)
392 log(DEBUG,"Beginning network burst");
393 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
394 this->WriteLine("BURST");
396 this->SendServers(TreeRoot,s,1);
397 // Send users and their channels
399 // TODO: Send everything else (channel modes etc)
400 this->WriteLine("ENDBURST");
403 virtual bool OnDataReady()
405 char* data = this->Read();
408 this->in_buffer += data;
409 while (in_buffer.find("\n") != std::string::npos)
411 char* line = (char*)in_buffer.c_str();
412 std::string ret = "";
413 while ((*line != '\n') && (strlen(line)))
418 if ((*line == '\n') || (*line == '\r'))
421 if (!this->ProcessLine(ret))
427 return (data != NULL);
430 int WriteLine(std::string line)
432 return this->Write(line + "\r\n");
435 bool Error(std::deque<std::string> params)
437 if (params.size() < 1)
439 std::string Errmsg = params[0];
440 std::string SName = myhost;
441 if (InboundServerName != "")
443 SName = InboundServerName;
445 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
446 // we will return false to cause the socket to close.
450 bool Outbound_Reply_Server(std::deque<std::string> params)
452 if (params.size() < 4)
454 std::string servername = params[0];
455 std::string password = params[1];
456 int hops = atoi(params[2].c_str());
459 this->WriteLine("ERROR :Server too far away for authentication");
462 std::string description = params[3];
463 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
465 if ((x->Name == servername) && (x->RecvPass == password))
467 // Begin the sync here. this kickstarts the
468 // other side, waiting in WAIT_AUTH_2 state,
469 // into starting their burst, as it shows
471 this->LinkState = CONNECTED;
472 // we should add the details of this server now
473 // to the servers tree, as a child of the root
475 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
476 TreeRoot->AddChild(Node);
481 this->WriteLine("ERROR :Invalid credentials");
485 bool Inbound_Server(std::deque<std::string> params)
487 if (params.size() < 4)
489 std::string servername = params[0];
490 std::string password = params[1];
491 int hops = atoi(params[2].c_str());
494 this->WriteLine("ERROR :Server too far away for authentication");
497 std::string description = params[3];
498 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
500 if ((x->Name == servername) && (x->RecvPass == password))
502 Srv->SendOpers("*** Verified incoming server connection from "+servername+"["+this->GetIP()+"] ("+description+")");
503 this->InboundServerName = servername;
504 this->InboundDescription = description;
505 // this is good. Send our details: Our server name and description and hopcount of 0,
506 // along with the sendpass from this block.
507 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
508 // move to the next state, we are now waiting for THEM.
509 this->LinkState = WAIT_AUTH_2;
513 this->WriteLine("ERROR :Invalid credentials");
517 std::deque<std::string> Split(std::string line)
519 std::deque<std::string> n;
520 std::stringstream s(line);
521 std::string param = "";
527 if ((param.c_str()[0] == ':') && (item))
529 char* str = (char*)param.c_str();
539 param = param + " " + append;
549 bool ProcessLine(std::string line)
551 Srv->SendToModeMask("o",WM_AND,"inbound-line: '"+line+"'");
553 std::deque<std::string> params = this->Split(line);
554 std::string command = "";
555 std::string prefix = "";
556 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
560 char* pref = (char*)prefix.c_str();
572 switch (this->LinkState)
577 // Waiting for SERVER command from remote server. Server initiating
578 // the connection sends the first SERVER command, listening server
579 // replies with theirs if its happy, then if the initiator is happy,
580 // it starts to send its net sync, which starts the merge, otherwise
581 // it sends an ERROR.
582 if (command == "SERVER")
584 return this->Inbound_Server(params);
586 else if (command == "ERROR")
588 return this->Error(params);
592 // Waiting for start of other side's netmerge to say they liked our
594 if (command == "SERVER")
596 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
600 else if (command == "BURST")
602 this->LinkState = CONNECTED;
603 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
604 TreeRoot->AddChild(Node);
607 else if (command == "ERROR")
609 return this->Error(params);
614 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
618 if (command == "SERVER")
620 // another server we connected to, which was in WAIT_AUTH_1 state,
621 // has just sent us their credentials. If we get this far, theyre
622 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
623 // if we're happy with this, we should send our netburst which
624 // kickstarts the merge.
625 return this->Outbound_Reply_Server(params);
629 // This is the 'authenticated' state, when all passwords
630 // have been exchanged and anything past this point is taken
632 std::string target = "";
633 if ((command == "NICK") && (params.size() > 1))
635 return this->IntroduceClient(prefix,params);
639 // not a special inter-server command.
640 // Emulate the actual user doing the command,
641 // this saves us having a huge ugly parser.
642 userrec* who = Srv->FindNick(prefix);
643 std::string sourceserv = this->myhost;
644 if (this->InboundServerName != "")
646 sourceserv = this->InboundServerName;
651 target = who->server;
652 char* strparams[127];
653 for (unsigned int q = 0; q < params.size(); q++)
655 strparams[q] = (char*)params[q].c_str();
657 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
658 Srv->CallCommandHandler(command, strparams, params.size(), who);
662 // its not a user. Its either a server, or somethings screwed up.
663 if (IsServer(prefix))
665 target = Srv->GetServerName();
669 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
673 return DoOneToAllButSender(prefix,command,params,sourceserv);
682 virtual void OnTimeout()
684 if (this->LinkState = CONNECTING)
686 Srv->SendOpers("*** CONNECT: Connection to "+myhost+" timed out.");
690 virtual void OnClose()
694 virtual int OnIncomingConnection(int newsock, char* ip)
696 TreeSocket* s = new TreeSocket(newsock, ip);
702 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
704 // TODO: Special stuff with privmsg and notice
705 std::string FullLine = ":" + prefix + " " + command;
706 for (unsigned int x = 0; x < params.size(); x++)
708 FullLine = FullLine + " " + params[x];
710 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
712 TreeServer* Route = TreeRoot->GetChild(x);
713 if ((Route->GetSocket()) && (Route->GetName() != omit))
715 TreeSocket* Sock = Route->GetSocket();
716 Sock->WriteLine(FullLine);
722 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
724 std::string FullLine = ":" + prefix + " " + command;
725 for (unsigned int x = 0; x < params.size(); x++)
727 FullLine = FullLine + " " + params[x];
729 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
731 TreeServer* Route = TreeRoot->GetChild(x);
732 if (Route->GetSocket())
734 TreeSocket* Sock = Route->GetSocket();
735 Sock->WriteLine(FullLine);
741 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
743 TreeServer* Route = BestRouteTo(target);
746 std::string FullLine = ":" + prefix + " " + command;
747 for (unsigned int x = 0; x < params.size(); x++)
749 FullLine = FullLine + " " + params[x];
751 if (Route->GetSocket())
753 TreeSocket* Sock = Route->GetSocket();
754 Sock->WriteLine(FullLine);
760 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
766 class ModuleSpanningTree : public Module
768 std::vector<TreeSocket*> Bindings;
772 void ReadConfiguration(bool rebind)
776 for (int j =0; j < Conf->Enumerate("bind"); j++)
778 std::string Type = Conf->ReadValue("bind","type",j);
779 std::string IP = Conf->ReadValue("bind","address",j);
780 long Port = Conf->ReadInteger("bind","port",j,true);
781 if (Type == "servers")
787 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
788 if (listener->GetState() == I_LISTENING)
790 Srv->AddSocket(listener);
791 Bindings.push_back(listener);
795 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
803 for (int j =0; j < Conf->Enumerate("link"); j++)
806 L.Name = Conf->ReadValue("link","name",j);
807 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
808 L.Port = Conf->ReadInteger("link","port",j,true);
809 L.SendPass = Conf->ReadValue("link","sendpass",j);
810 L.RecvPass = Conf->ReadValue("link","recvpass",j);
811 LinkBlocks.push_back(L);
812 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
819 Conf = new ConfigReader;
822 // Create the root of the tree
823 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
825 ReadConfiguration(true);
828 void HandleLinks(char** parameters, int pcnt, userrec* user)
833 void HandleLusers(char** parameters, int pcnt, userrec* user)
838 void HandleMap(char** parameters, int pcnt, userrec* user)
843 int HandleSquit(char** parameters, int pcnt, userrec* user)
848 int HandleConnect(char** parameters, int pcnt, userrec* user)
850 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
852 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
854 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
855 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
856 Srv->AddSocket(newsocket);
860 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
864 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
866 if (command == "CONNECT")
868 return this->HandleConnect(parameters,pcnt,user);
870 else if (command == "SQUIT")
872 return this->HandleSquit(parameters,pcnt,user);
874 else if (command == "MAP")
876 this->HandleMap(parameters,pcnt,user);
879 else if (command == "LUSERS")
881 this->HandleLusers(parameters,pcnt,user);
884 else if (command == "LINKS")
886 this->HandleLinks(parameters,pcnt,user);
892 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
894 if (target_type == TYPE_USER)
896 // route private messages which are targetted at clients only to the server
897 // which needs to receive them
898 userrec* d = (userrec*)dest;
899 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
901 std::deque<std::string> params;
903 params.push_back(d->nick);
904 params.push_back(":"+text);
905 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
910 virtual void OnUserJoin(userrec* user, chanrec* channel)
912 // Only do this for local users
913 if (std::string(user->server) == Srv->GetServerName())
915 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
916 std::deque<std::string> params;
918 params.push_back(channel->name);
921 log(DEBUG,"**** With key %s",channel->key);
922 // if the channel has a key, force the join by emulating the key.
923 params.push_back(channel->key);
925 DoOneToMany(user->nick,"JOIN",params);
929 virtual ~ModuleSpanningTree()
934 virtual Version GetVersion()
936 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
941 class ModuleSpanningTreeFactory : public ModuleFactory
944 ModuleSpanningTreeFactory()
948 ~ModuleSpanningTreeFactory()
952 virtual Module * CreateModule()
954 return new ModuleSpanningTree;
960 extern "C" void * init_module( void )
962 return new ModuleSpanningTreeFactory;