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;
53 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
54 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
55 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
60 std::vector<TreeServer*> Children;
61 std::string ServerName;
62 std::string ServerDesc;
63 std::string VersionString;
66 TreeSocket* Socket; // for directly connected servers this points at the socket object
76 UserCount = OperCount = 0;
79 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
83 UserCount = OperCount = 0;
86 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
89 UserCount = OperCount = 0;
94 return this->ServerName;
99 return this->ServerDesc;
102 std::string GetVersion()
104 return this->VersionString;
109 return this->UserCount;
114 return this->OperCount;
117 TreeSocket* GetSocket()
122 TreeServer* GetParent()
127 unsigned int ChildCount()
129 return Children.size();
132 TreeServer* GetChild(unsigned int n)
134 if (n < Children.size())
144 void AddChild(TreeServer* Child)
146 Children.push_back(Child);
149 bool DelChild(TreeServer* Child)
151 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
162 // removes child nodes of this node, and of that node, etc etc
165 bool stillchildren = true;
166 while (stillchildren)
168 stillchildren = false;
169 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
171 TreeServer* s = (TreeServer*)*a;
175 stillchildren = true;
189 std::string SendPass;
190 std::string RecvPass;
193 /* $ModDesc: Povides a spanning tree server link protocol */
197 TreeServer *TreeRoot;
198 std::vector<Link> LinkBlocks;
200 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
202 if (Current->GetName() == ServerName)
204 for (unsigned int q = 0; q < Current->ChildCount(); q++)
206 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
215 // Returns the locally connected server we must route a
216 // message through to reach server 'ServerName'. This
217 // only applies to one-to-one and not one-to-many routing.
218 TreeServer* BestRouteTo(std::string ServerName)
220 log(DEBUG,"Finding best route to %s",ServerName.c_str());
221 // first, find the server by recursively walking the tree
222 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
223 // did we find it? If not, they did something wrong, abort.
226 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
231 // The server exists, follow its parent nodes until
232 // the parent of the current is 'TreeRoot', we know
233 // then that this is a directly-connected server.
234 while ((Found) && (Found->GetParent() != TreeRoot))
236 Found = Found->GetParent();
238 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
243 bool LookForServer(TreeServer* Current, std::string ServerName)
245 if (ServerName == Current->GetName())
247 for (unsigned int q = 0; q < Current->ChildCount(); q++)
249 if (LookForServer(Current->GetChild(q),ServerName))
257 void RFindServer(TreeServer* Current, std::string ServerName)
259 if ((ServerName == Current->GetName()) && (!Found))
262 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
267 for (unsigned int q = 0; q < Current->ChildCount(); q++)
270 RFindServer(Current->GetChild(q),ServerName);
276 TreeServer* FindServer(std::string ServerName)
279 RFindServer(TreeRoot,ServerName);
283 bool IsServer(std::string ServerName)
285 return LookForServer(TreeRoot,ServerName);
288 class TreeSocket : public InspSocket
291 std::string in_buffer;
292 ServerState LinkState;
293 std::string InboundServerName;
294 std::string InboundDescription;
296 int num_lost_servers;
300 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
301 : InspSocket(host, port, listening, maxtime)
303 Srv->Log(DEBUG,"Create new listening");
305 this->LinkState = LISTENER;
308 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
309 : InspSocket(host, port, listening, maxtime)
311 Srv->Log(DEBUG,"Create new outbound");
313 this->LinkState = CONNECTING;
316 TreeSocket(int newfd, char* ip)
317 : InspSocket(newfd, ip)
319 Srv->Log(DEBUG,"Associate new inbound");
320 this->LinkState = WAIT_AUTH_1;
323 virtual bool OnConnected()
325 if (this->LinkState == CONNECTING)
327 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
328 // we should send our details here.
329 // if the other side is satisfied, they send theirs.
330 // we do not need to change state here.
331 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
333 if (x->Name == this->myhost)
335 // found who we're supposed to be connecting to, send the neccessary gubbins.
336 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
341 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
345 virtual void OnError(InspSocketError e)
349 virtual int OnDisconnect()
354 // recursively send the server tree with distances as hops
355 void SendServers(TreeServer* Current, TreeServer* s, int hops)
358 for (unsigned int q = 0; q < Current->ChildCount(); q++)
360 TreeServer* recursive_server = Current->GetChild(q);
361 if (recursive_server != s)
363 // :source.server SERVER server.name hops :Description
364 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
365 this->WriteLine(command);
366 // down to next level
367 this->SendServers(recursive_server, s, hops+1);
372 void SquitServer(TreeServer* Current)
374 // recursively squit the servers attached to 'Current'
375 for (unsigned int q = 0; q < Current->ChildCount(); q++)
377 TreeServer* recursive_server = Current->GetChild(q);
378 this->SquitServer(recursive_server);
380 // Now we've whacked the kids, whack self
381 log(DEBUG,"Deleted %s",Current->GetName().c_str());
383 bool quittingpeople = true;
384 while (quittingpeople)
386 quittingpeople = false;
387 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
389 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
391 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
392 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
394 quittingpeople = true;
401 void Squit(TreeServer* Current,std::string reason)
405 std::deque<std::string> params;
406 params.push_back(Current->GetName());
407 params.push_back(":"+reason);
408 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
409 if (Current->GetParent() == TreeRoot)
411 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
415 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
417 num_lost_servers = 0;
419 SquitServer(Current);
421 Current->GetParent()->DelChild(Current);
423 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
427 log(DEBUG,"Squit from unknown server");
431 bool ForceJoin(std::string source, std::deque<std::string> params)
433 if (params.size() < 1)
435 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
437 // process one channel at a time, applying modes.
438 char* channel = (char*)params[channelnum].c_str();
439 char permissions = *channel;
456 userrec* who = Srv->FindNick(source);
460 chanrec* chan = Srv->FindChannel(channel);
461 if ((chan) && (*chan->key))
465 Srv->JoinUserToChannel(who,channel,key);
469 modelist[0] = channel;
471 modelist[2] = who->nick;
472 Srv->SendMode(modelist,3,who);
474 DoOneToAllButSender(source,"FJOIN",params,who->server);
480 bool IntroduceClient(std::string source, std::deque<std::string> params)
482 if (params.size() < 8)
484 // NICK age nick host dhost ident +modes ip :gecos
486 std::string nick = params[1];
487 std::string host = params[2];
488 std::string dhost = params[3];
489 std::string ident = params[4];
490 time_t age = atoi(params[0].c_str());
491 std::string modes = params[5];
492 std::string ip = params[6];
493 std::string gecos = params[7];
494 char* tempnick = (char*)nick.c_str();
495 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
497 user_hash::iterator iter;
498 iter = clientlist.find(tempnick);
499 if (iter != clientlist.end())
502 log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
506 clientlist[tempnick] = new userrec();
507 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
508 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
509 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
510 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
511 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
512 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
513 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
514 clientlist[tempnick]->registered = 7;
515 clientlist[tempnick]->signon = age;
516 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
517 for (int i = 0; i < MAXCHANS; i++)
519 clientlist[tempnick]->chans[i].channel = NULL;
520 clientlist[tempnick]->chans[i].uc_modes = 0;
522 DoOneToAllButSender(source,"NICK",params,source);
526 // send all users and their channels
527 void SendUsers(TreeServer* Current)
530 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
532 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);
533 this->WriteLine(data);
534 if (strchr(u->second->modes,'o'))
536 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
538 char* chl = chlist(u->second,u->second);
541 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
546 void DoBurst(TreeServer* s)
548 log(DEBUG,"Beginning network burst");
549 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
550 this->WriteLine("BURST");
552 this->SendServers(TreeRoot,s,1);
553 // Send users and their channels
555 // TODO: Send everything else (channel modes etc)
556 this->WriteLine("ENDBURST");
559 virtual bool OnDataReady()
561 char* data = this->Read();
564 this->in_buffer += data;
565 while (in_buffer.find("\n") != std::string::npos)
567 char* line = (char*)in_buffer.c_str();
568 std::string ret = "";
569 while ((*line != '\n') && (strlen(line)))
574 if ((*line == '\n') || (*line == '\r'))
577 if (!this->ProcessLine(ret))
583 return (data != NULL);
586 int WriteLine(std::string line)
588 return this->Write(line + "\r\n");
591 bool Error(std::deque<std::string> params)
593 if (params.size() < 1)
595 std::string Errmsg = params[0];
596 std::string SName = myhost;
597 if (InboundServerName != "")
599 SName = InboundServerName;
601 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
602 // we will return false to cause the socket to close.
606 bool RemoteServer(std::string prefix, std::deque<std::string> params)
608 if (params.size() < 4)
610 std::string servername = params[0];
611 std::string password = params[1];
612 int hops = atoi(params[2].c_str());
613 std::string description = params[3];
616 this->WriteLine("ERROR :Protocol error - Introduced remote server with incorrect hopcount!");
619 TreeServer* ParentOfThis = FindServer(prefix);
622 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
625 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
626 ParentOfThis->AddChild(Node);
627 DoOneToAllButSender(prefix,"SERVER",params,prefix);
628 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
632 bool Outbound_Reply_Server(std::deque<std::string> params)
634 if (params.size() < 4)
636 std::string servername = params[0];
637 std::string password = params[1];
638 int hops = atoi(params[2].c_str());
641 this->WriteLine("ERROR :Server too far away for authentication");
644 std::string description = params[3];
645 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
647 if ((x->Name == servername) && (x->RecvPass == password))
649 // Begin the sync here. this kickstarts the
650 // other side, waiting in WAIT_AUTH_2 state,
651 // into starting their burst, as it shows
653 this->LinkState = CONNECTED;
654 // we should add the details of this server now
655 // to the servers tree, as a child of the root
657 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
658 TreeRoot->AddChild(Node);
659 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
664 this->WriteLine("ERROR :Invalid credentials");
668 bool Inbound_Server(std::deque<std::string> params)
670 if (params.size() < 4)
672 std::string servername = params[0];
673 std::string password = params[1];
674 int hops = atoi(params[2].c_str());
677 this->WriteLine("ERROR :Server too far away for authentication");
680 std::string description = params[3];
681 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
683 if ((x->Name == servername) && (x->RecvPass == password))
685 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
686 this->InboundServerName = servername;
687 this->InboundDescription = description;
688 // this is good. Send our details: Our server name and description and hopcount of 0,
689 // along with the sendpass from this block.
690 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
691 // move to the next state, we are now waiting for THEM.
692 this->LinkState = WAIT_AUTH_2;
696 this->WriteLine("ERROR :Invalid credentials");
700 std::deque<std::string> Split(std::string line)
702 std::deque<std::string> n;
703 std::stringstream s(line);
704 std::string param = "";
710 if ((param.c_str()[0] == ':') && (item))
712 char* str = (char*)param.c_str();
722 param = param + " " + append;
732 bool ProcessLine(std::string line)
734 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
736 std::deque<std::string> params = this->Split(line);
737 std::string command = "";
738 std::string prefix = "";
739 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
743 char* pref = (char*)prefix.c_str();
755 switch (this->LinkState)
760 // Waiting for SERVER command from remote server. Server initiating
761 // the connection sends the first SERVER command, listening server
762 // replies with theirs if its happy, then if the initiator is happy,
763 // it starts to send its net sync, which starts the merge, otherwise
764 // it sends an ERROR.
765 if (command == "SERVER")
767 return this->Inbound_Server(params);
769 else if (command == "ERROR")
771 return this->Error(params);
775 // Waiting for start of other side's netmerge to say they liked our
777 if (command == "SERVER")
779 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
783 else if (command == "BURST")
785 this->LinkState = CONNECTED;
786 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
787 TreeRoot->AddChild(Node);
789 params.push_back(InboundServerName);
790 params.push_back("*");
791 params.push_back("1");
792 params.push_back(":"+InboundDescription);
793 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
796 else if (command == "ERROR")
798 return this->Error(params);
803 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
807 if (command == "SERVER")
809 // another server we connected to, which was in WAIT_AUTH_1 state,
810 // has just sent us their credentials. If we get this far, theyre
811 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
812 // if we're happy with this, we should send our netburst which
813 // kickstarts the merge.
814 return this->Outbound_Reply_Server(params);
818 // This is the 'authenticated' state, when all passwords
819 // have been exchanged and anything past this point is taken
821 std::string target = "";
822 if ((command == "NICK") && (params.size() > 1))
824 return this->IntroduceClient(prefix,params);
826 else if (command == "FJOIN")
828 return this->ForceJoin(prefix,params);
830 else if (command == "SERVER")
832 return this->RemoteServer(prefix,params);
834 else if (command == "SQUIT")
836 if (params.size() == 2)
838 this->Squit(FindServer(params[0]),params[1]);
844 // not a special inter-server command.
845 // Emulate the actual user doing the command,
846 // this saves us having a huge ugly parser.
847 userrec* who = Srv->FindNick(prefix);
848 std::string sourceserv = this->myhost;
849 if (this->InboundServerName != "")
851 sourceserv = this->InboundServerName;
856 target = who->server;
857 char* strparams[127];
858 for (unsigned int q = 0; q < params.size(); q++)
860 strparams[q] = (char*)params[q].c_str();
862 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
863 Srv->CallCommandHandler(command, strparams, params.size(), who);
867 // its not a user. Its either a server, or somethings screwed up.
868 if (IsServer(prefix))
870 target = Srv->GetServerName();
874 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
878 return DoOneToAllButSender(prefix,command,params,sourceserv);
887 virtual void OnTimeout()
889 if (this->LinkState == CONNECTING)
891 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
895 virtual void OnClose()
897 // Connection closed.
898 // If the connection is fully up (state CONNECTED)
899 // then propogate a netsplit to all peers.
900 std::string quitserver = this->myhost;
901 if (this->InboundServerName != "")
903 quitserver = this->InboundServerName;
905 TreeServer* s = FindServer(quitserver);
908 std::deque<std::string> params;
909 params.push_back(quitserver);
910 params.push_back(":Remote host closed the connection");
911 DoOneToAllButSender(Srv->GetServerName(),"SQUIT",params,quitserver);
912 Squit(s,"Remote host closed the connection");
916 virtual int OnIncomingConnection(int newsock, char* ip)
918 TreeSocket* s = new TreeSocket(newsock, ip);
924 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
926 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
927 // TODO: Special stuff with privmsg and notice
928 std::string FullLine = ":" + prefix + " " + command;
929 for (unsigned int x = 0; x < params.size(); x++)
931 FullLine = FullLine + " " + params[x];
933 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
935 TreeServer* Route = TreeRoot->GetChild(x);
937 // The route has a socket (its a direct connection)
938 // The route isnt the one to be omitted
939 // The route isnt the path to the one to be omitted
940 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
942 TreeSocket* Sock = Route->GetSocket();
943 log(DEBUG,"Sending to %s",Route->GetName().c_str());
944 Sock->WriteLine(FullLine);
950 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
952 std::string FullLine = ":" + prefix + " " + command;
953 for (unsigned int x = 0; x < params.size(); x++)
955 FullLine = FullLine + " " + params[x];
957 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
959 TreeServer* Route = TreeRoot->GetChild(x);
960 if (Route->GetSocket())
962 TreeSocket* Sock = Route->GetSocket();
963 Sock->WriteLine(FullLine);
969 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
971 TreeServer* Route = BestRouteTo(target);
974 std::string FullLine = ":" + prefix + " " + command;
975 for (unsigned int x = 0; x < params.size(); x++)
977 FullLine = FullLine + " " + params[x];
979 if (Route->GetSocket())
981 TreeSocket* Sock = Route->GetSocket();
982 Sock->WriteLine(FullLine);
988 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
994 class ModuleSpanningTree : public Module
996 std::vector<TreeSocket*> Bindings;
1001 void ReadConfiguration(bool rebind)
1005 for (int j =0; j < Conf->Enumerate("bind"); j++)
1007 std::string Type = Conf->ReadValue("bind","type",j);
1008 std::string IP = Conf->ReadValue("bind","address",j);
1009 long Port = Conf->ReadInteger("bind","port",j,true);
1010 if (Type == "servers")
1016 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1017 if (listener->GetState() == I_LISTENING)
1019 Srv->AddSocket(listener);
1020 Bindings.push_back(listener);
1024 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1032 for (int j =0; j < Conf->Enumerate("link"); j++)
1035 L.Name = Conf->ReadValue("link","name",j);
1036 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1037 L.Port = Conf->ReadInteger("link","port",j,true);
1038 L.SendPass = Conf->ReadValue("link","sendpass",j);
1039 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1040 LinkBlocks.push_back(L);
1041 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1045 ModuleSpanningTree()
1048 Conf = new ConfigReader;
1051 // Create the root of the tree
1052 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1054 ReadConfiguration(true);
1057 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1059 std::string Parent = TreeRoot->GetName();
1060 if (Current->GetParent())
1062 Parent = Current->GetParent()->GetName();
1064 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1066 ShowLinks(Current->GetChild(q),user,hops+1);
1068 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1071 void HandleLinks(char** parameters, int pcnt, userrec* user)
1073 ShowLinks(TreeRoot,user,0);
1074 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1078 void HandleLusers(char** parameters, int pcnt, userrec* user)
1083 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1085 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1089 for (int t = 0; t < depth; t++)
1091 matrix[line][t] = ' ';
1093 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1095 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1097 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1102 // Ok, prepare to be confused.
1103 // After much mulling over how to approach this, it struck me that
1104 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1105 // keeping track of a ton of ascii characters, and line by line
1106 // under recursion working out where to place them using multiplications
1107 // and divisons, we instead render the map onto a backplane of characters
1108 // (a character matrix), then draw the branches as a series of "L" shapes
1109 // from the nodes. This is not only friendlier on CPU it uses less stack.
1111 void HandleMap(char** parameters, int pcnt, userrec* user)
1113 // This array represents a virtual screen which we will
1114 // "scratch" draw to, as the console device of an irc
1115 // client does not provide for a proper terminal.
1116 char matrix[128][80];
1117 for (unsigned int t = 0; t < 128; t++)
1119 matrix[t][0] = '\0';
1122 // The only recursive bit is called here.
1123 ShowMap(TreeRoot,user,0,matrix);
1124 // Process each line one by one. The algorithm has a limit of
1125 // 128 servers (which is far more than a spanning tree should have
1126 // anyway, so we're ok). This limit can be raised simply by making
1127 // the character matrix deeper, 128 rows taking 10k of memory.
1128 for (int l = 1; l < line; l++)
1130 // scan across the line looking for the start of the
1131 // servername (the recursive part of the algorithm has placed
1132 // the servers at indented positions depending on what they
1134 int first_nonspace = 0;
1135 while (matrix[l][first_nonspace] == ' ')
1140 // Draw the `- (corner) section: this may be overwritten by
1141 // another L shape passing along the same vertical pane, becoming
1142 // a |- (branch) section instead.
1143 matrix[l][first_nonspace] = '-';
1144 matrix[l][first_nonspace-1] = '`';
1146 // Draw upwards until we hit the parent server, causing possibly
1147 // other corners (`-) to become branches (|-)
1148 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1150 matrix[l2][first_nonspace-1] = '|';
1154 // dump the whole lot to the user. This is the easy bit, honest.
1155 for (int t = 0; t < line; t++)
1157 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1159 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1163 int HandleSquit(char** parameters, int pcnt, userrec* user)
1168 int HandleConnect(char** parameters, int pcnt, userrec* user)
1170 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1172 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1174 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1175 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1176 Srv->AddSocket(newsocket);
1180 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1184 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1186 if (command == "CONNECT")
1188 return this->HandleConnect(parameters,pcnt,user);
1190 else if (command == "SQUIT")
1192 return this->HandleSquit(parameters,pcnt,user);
1194 else if (command == "MAP")
1196 this->HandleMap(parameters,pcnt,user);
1199 else if (command == "LUSERS")
1201 this->HandleLusers(parameters,pcnt,user);
1204 else if (command == "LINKS")
1206 this->HandleLinks(parameters,pcnt,user);
1212 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1214 if (target_type == TYPE_USER)
1216 // route private messages which are targetted at clients only to the server
1217 // which needs to receive them
1218 userrec* d = (userrec*)dest;
1219 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1221 std::deque<std::string> params;
1223 params.push_back(d->nick);
1224 params.push_back(":"+text);
1225 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1230 chanrec* c = (chanrec*)dest;
1231 std::deque<std::string> params;
1232 std::vector<std::string> wlist;
1235 params.push_back(c->name);
1236 params.push_back(":"+text);
1237 std::vector<char*> *ulist = c->GetUsers();
1238 for (unsigned int j = 0; j < ulist->size(); j++)
1240 char* o = (*ulist)[j];
1241 userrec* otheruser = (userrec*)o;
1242 if (!strcasecmp(otheruser->server,Srv->GetServerName().c_str()))
1244 // this user is on another server.
1245 // Write that server, then mark that server so we dont write to it again.
1246 if (find(wlist.begin(),wlist.end(),otheruser->server) == wlist.end())
1248 DoOneToOne(user->nick,"PRIVMSG",params,otheruser->server);
1249 wlist.push_back(otheruser->server);
1256 virtual void OnUserJoin(userrec* user, chanrec* channel)
1258 // Only do this for local users
1259 if (std::string(user->server) == Srv->GetServerName())
1261 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1262 std::deque<std::string> params;
1264 params.push_back(channel->name);
1267 log(DEBUG,"**** With key %s",channel->key);
1268 // if the channel has a key, force the join by emulating the key.
1269 params.push_back(channel->key);
1271 DoOneToMany(user->nick,"JOIN",params);
1275 virtual void OnUserPart(userrec* user, chanrec* channel)
1277 if (std::string(user->server) == Srv->GetServerName())
1279 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1280 std::deque<std::string> params;
1282 params.push_back(channel->name);
1283 DoOneToMany(user->nick,"PART",params);
1287 virtual ~ModuleSpanningTree()
1292 virtual Version GetVersion()
1294 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1299 class ModuleSpanningTreeFactory : public ModuleFactory
1302 ModuleSpanningTreeFactory()
1306 ~ModuleSpanningTreeFactory()
1310 virtual Module * CreateModule()
1312 return new ModuleSpanningTree;
1318 extern "C" void * init_module( void )
1320 return new ModuleSpanningTreeFactory;