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);
56 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
61 std::vector<TreeServer*> Children;
62 std::string ServerName;
63 std::string ServerDesc;
64 std::string VersionString;
67 TreeSocket* Socket; // for directly connected servers this points at the socket object
77 UserCount = OperCount = 0;
80 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
84 UserCount = OperCount = 0;
87 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
90 UserCount = OperCount = 0;
95 return this->ServerName;
100 return this->ServerDesc;
103 std::string GetVersion()
105 return this->VersionString;
110 return this->UserCount;
115 return this->OperCount;
118 TreeSocket* GetSocket()
123 TreeServer* GetParent()
128 unsigned int ChildCount()
130 return Children.size();
133 TreeServer* GetChild(unsigned int n)
135 if (n < Children.size())
145 void AddChild(TreeServer* Child)
147 Children.push_back(Child);
150 bool DelChild(TreeServer* Child)
152 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
163 // removes child nodes of this node, and of that node, etc etc
166 bool stillchildren = true;
167 while (stillchildren)
169 stillchildren = false;
170 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
172 TreeServer* s = (TreeServer*)*a;
176 stillchildren = true;
190 std::string SendPass;
191 std::string RecvPass;
194 /* $ModDesc: Povides a spanning tree server link protocol */
198 TreeServer *TreeRoot;
199 std::vector<Link> LinkBlocks;
201 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
203 if (Current->GetName() == ServerName)
205 for (unsigned int q = 0; q < Current->ChildCount(); q++)
207 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
216 // Returns the locally connected server we must route a
217 // message through to reach server 'ServerName'. This
218 // only applies to one-to-one and not one-to-many routing.
219 TreeServer* BestRouteTo(std::string ServerName)
221 log(DEBUG,"Finding best route to %s",ServerName.c_str());
222 // first, find the server by recursively walking the tree
223 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
224 // did we find it? If not, they did something wrong, abort.
227 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
232 // The server exists, follow its parent nodes until
233 // the parent of the current is 'TreeRoot', we know
234 // then that this is a directly-connected server.
235 while ((Found) && (Found->GetParent() != TreeRoot))
237 Found = Found->GetParent();
239 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
244 bool LookForServer(TreeServer* Current, std::string ServerName)
246 if (ServerName == Current->GetName())
248 for (unsigned int q = 0; q < Current->ChildCount(); q++)
250 if (LookForServer(Current->GetChild(q),ServerName))
258 void RFindServer(TreeServer* Current, std::string ServerName)
260 if ((ServerName == Current->GetName()) && (!Found))
263 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
268 for (unsigned int q = 0; q < Current->ChildCount(); q++)
271 RFindServer(Current->GetChild(q),ServerName);
277 TreeServer* FindServer(std::string ServerName)
280 RFindServer(TreeRoot,ServerName);
284 bool IsServer(std::string ServerName)
286 return LookForServer(TreeRoot,ServerName);
289 class TreeSocket : public InspSocket
292 std::string in_buffer;
293 ServerState LinkState;
294 std::string InboundServerName;
295 std::string InboundDescription;
297 int num_lost_servers;
301 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
302 : InspSocket(host, port, listening, maxtime)
304 Srv->Log(DEBUG,"Create new listening");
306 this->LinkState = LISTENER;
309 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
310 : InspSocket(host, port, listening, maxtime)
312 Srv->Log(DEBUG,"Create new outbound");
314 this->LinkState = CONNECTING;
317 TreeSocket(int newfd, char* ip)
318 : InspSocket(newfd, ip)
320 Srv->Log(DEBUG,"Associate new inbound");
321 this->LinkState = WAIT_AUTH_1;
324 virtual bool OnConnected()
326 if (this->LinkState == CONNECTING)
328 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
329 // we should send our details here.
330 // if the other side is satisfied, they send theirs.
331 // we do not need to change state here.
332 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
334 if (x->Name == this->myhost)
336 // found who we're supposed to be connecting to, send the neccessary gubbins.
337 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
342 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
346 virtual void OnError(InspSocketError e)
350 virtual int OnDisconnect()
355 // recursively send the server tree with distances as hops
356 void SendServers(TreeServer* Current, TreeServer* s, int hops)
359 for (unsigned int q = 0; q < Current->ChildCount(); q++)
361 TreeServer* recursive_server = Current->GetChild(q);
362 if (recursive_server != s)
364 // :source.server SERVER server.name hops :Description
365 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
366 this->WriteLine(command);
367 // down to next level
368 this->SendServers(recursive_server, s, hops+1);
373 void SquitServer(TreeServer* Current)
375 // recursively squit the servers attached to 'Current'
376 for (unsigned int q = 0; q < Current->ChildCount(); q++)
378 TreeServer* recursive_server = Current->GetChild(q);
379 this->SquitServer(recursive_server);
381 // Now we've whacked the kids, whack self
382 log(DEBUG,"Deleted %s",Current->GetName().c_str());
384 bool quittingpeople = true;
385 while (quittingpeople)
387 quittingpeople = false;
388 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
390 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
392 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
393 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
395 quittingpeople = true;
402 void Squit(TreeServer* Current,std::string reason)
406 std::deque<std::string> params;
407 params.push_back(Current->GetName());
408 params.push_back(":"+reason);
409 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
410 if (Current->GetParent() == TreeRoot)
412 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
416 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
418 num_lost_servers = 0;
420 SquitServer(Current);
422 Current->GetParent()->DelChild(Current);
424 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
428 log(DEBUG,"Squit from unknown server");
432 bool ForceJoin(std::string source, std::deque<std::string> params)
434 if (params.size() < 1)
436 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
438 // process one channel at a time, applying modes.
439 char* channel = (char*)params[channelnum].c_str();
440 char permissions = *channel;
457 userrec* who = Srv->FindNick(source);
461 chanrec* chan = Srv->FindChannel(channel);
462 if ((chan) && (*chan->key))
466 Srv->JoinUserToChannel(who,channel,key);
470 modelist[0] = channel;
472 modelist[2] = who->nick;
473 Srv->SendMode(modelist,3,who);
475 DoOneToAllButSender(source,"FJOIN",params,who->server);
481 bool IntroduceClient(std::string source, std::deque<std::string> params)
483 if (params.size() < 8)
485 // NICK age nick host dhost ident +modes ip :gecos
487 std::string nick = params[1];
488 std::string host = params[2];
489 std::string dhost = params[3];
490 std::string ident = params[4];
491 time_t age = atoi(params[0].c_str());
492 std::string modes = params[5];
493 std::string ip = params[6];
494 std::string gecos = params[7];
495 char* tempnick = (char*)nick.c_str();
496 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
498 user_hash::iterator iter;
499 iter = clientlist.find(tempnick);
500 if (iter != clientlist.end())
503 log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
507 clientlist[tempnick] = new userrec();
508 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
509 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
510 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
511 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
512 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
513 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
514 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
515 clientlist[tempnick]->registered = 7;
516 clientlist[tempnick]->signon = age;
517 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
518 for (int i = 0; i < MAXCHANS; i++)
520 clientlist[tempnick]->chans[i].channel = NULL;
521 clientlist[tempnick]->chans[i].uc_modes = 0;
523 DoOneToAllButSender(source,"NICK",params,source);
527 // send all users and their channels
528 void SendUsers(TreeServer* Current)
531 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
533 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);
534 this->WriteLine(data);
535 if (strchr(u->second->modes,'o'))
537 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
539 char* chl = chlist(u->second,u->second);
542 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
547 void DoBurst(TreeServer* s)
549 log(DEBUG,"Beginning network burst");
550 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
551 this->WriteLine("BURST");
553 this->SendServers(TreeRoot,s,1);
554 // Send users and their channels
556 // TODO: Send everything else (channel modes etc)
557 this->WriteLine("ENDBURST");
560 virtual bool OnDataReady()
562 char* data = this->Read();
565 this->in_buffer += data;
566 while (in_buffer.find("\n") != std::string::npos)
568 char* line = (char*)in_buffer.c_str();
569 std::string ret = "";
570 while ((*line != '\n') && (strlen(line)))
575 if ((*line == '\n') || (*line == '\r'))
578 if (!this->ProcessLine(ret))
584 return (data != NULL);
587 int WriteLine(std::string line)
589 return this->Write(line + "\r\n");
592 bool Error(std::deque<std::string> params)
594 if (params.size() < 1)
596 std::string Errmsg = params[0];
597 std::string SName = myhost;
598 if (InboundServerName != "")
600 SName = InboundServerName;
602 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
603 // we will return false to cause the socket to close.
607 bool OperType(std::string prefix, std::deque<std::string> params)
609 if (params.size() != 1)
611 std::string opertype = params[0];
612 userrec* u = Srv->FindNick(prefix);
615 strlcpy(u->oper,opertype.c_str(),NICKMAX);
616 if (!strchr(u->modes,"o"))
618 strcat(u->modes,"o");
620 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
625 bool RemoteServer(std::string prefix, std::deque<std::string> params)
627 if (params.size() < 4)
629 std::string servername = params[0];
630 std::string password = params[1];
631 int hops = atoi(params[2].c_str());
632 std::string description = params[3];
635 this->WriteLine("ERROR :Protocol error - Introduced remote server with incorrect hopcount!");
638 TreeServer* ParentOfThis = FindServer(prefix);
641 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
644 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
645 ParentOfThis->AddChild(Node);
646 params[3] = ":" + params[3];
647 DoOneToAllButSender(prefix,"SERVER",params,prefix);
648 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
652 bool Outbound_Reply_Server(std::deque<std::string> params)
654 if (params.size() < 4)
656 std::string servername = params[0];
657 std::string password = params[1];
658 int hops = atoi(params[2].c_str());
661 this->WriteLine("ERROR :Server too far away for authentication");
664 std::string description = params[3];
665 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
667 if ((x->Name == servername) && (x->RecvPass == password))
669 // Begin the sync here. this kickstarts the
670 // other side, waiting in WAIT_AUTH_2 state,
671 // into starting their burst, as it shows
673 this->LinkState = CONNECTED;
674 // we should add the details of this server now
675 // to the servers tree, as a child of the root
677 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
678 TreeRoot->AddChild(Node);
679 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
684 this->WriteLine("ERROR :Invalid credentials");
688 bool Inbound_Server(std::deque<std::string> params)
690 if (params.size() < 4)
692 std::string servername = params[0];
693 std::string password = params[1];
694 int hops = atoi(params[2].c_str());
697 this->WriteLine("ERROR :Server too far away for authentication");
700 std::string description = params[3];
701 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
703 if ((x->Name == servername) && (x->RecvPass == password))
705 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
706 this->InboundServerName = servername;
707 this->InboundDescription = description;
708 // this is good. Send our details: Our server name and description and hopcount of 0,
709 // along with the sendpass from this block.
710 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
711 // move to the next state, we are now waiting for THEM.
712 this->LinkState = WAIT_AUTH_2;
716 this->WriteLine("ERROR :Invalid credentials");
720 std::deque<std::string> Split(std::string line, bool stripcolon)
722 std::deque<std::string> n;
723 std::stringstream s(line);
724 std::string param = "";
730 if ((param.c_str()[0] == ':') && (item))
732 char* str = (char*)param.c_str();
742 param = param + " " + append;
752 bool ProcessLine(std::string line)
754 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
755 std::deque<std::string> params = this->Split(line,true);
756 std::string command = "";
757 std::string prefix = "";
758 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
762 char* pref = (char*)prefix.c_str();
774 switch (this->LinkState)
779 // Waiting for SERVER command from remote server. Server initiating
780 // the connection sends the first SERVER command, listening server
781 // replies with theirs if its happy, then if the initiator is happy,
782 // it starts to send its net sync, which starts the merge, otherwise
783 // it sends an ERROR.
784 if (command == "SERVER")
786 return this->Inbound_Server(params);
788 else if (command == "ERROR")
790 return this->Error(params);
794 // Waiting for start of other side's netmerge to say they liked our
796 if (command == "SERVER")
798 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
802 else if (command == "BURST")
804 this->LinkState = CONNECTED;
805 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
806 TreeRoot->AddChild(Node);
808 params.push_back(InboundServerName);
809 params.push_back("*");
810 params.push_back("1");
811 params.push_back(":"+InboundDescription);
812 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
815 else if (command == "ERROR")
817 return this->Error(params);
822 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
826 if (command == "SERVER")
828 // another server we connected to, which was in WAIT_AUTH_1 state,
829 // has just sent us their credentials. If we get this far, theyre
830 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
831 // if we're happy with this, we should send our netburst which
832 // kickstarts the merge.
833 return this->Outbound_Reply_Server(params);
837 // This is the 'authenticated' state, when all passwords
838 // have been exchanged and anything past this point is taken
840 std::string target = "";
841 if ((command == "NICK") && (params.size() > 1))
843 return this->IntroduceClient(prefix,params);
845 else if (command == "FJOIN")
847 return this->ForceJoin(prefix,params);
849 else if (command == "SERVER")
851 return this->RemoteServer(prefix,params);
853 else if (command == "OPERTYPE")
855 return this->OperType(prefix,params);
857 else if (command == "SQUIT")
859 if (params.size() == 2)
861 this->Squit(FindServer(params[0]),params[1]);
867 // not a special inter-server command.
868 // Emulate the actual user doing the command,
869 // this saves us having a huge ugly parser.
870 userrec* who = Srv->FindNick(prefix);
871 std::string sourceserv = this->myhost;
872 if (this->InboundServerName != "")
874 sourceserv = this->InboundServerName;
879 target = who->server;
880 char* strparams[127];
881 for (unsigned int q = 0; q < params.size(); q++)
883 strparams[q] = (char*)params[q].c_str();
885 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
886 Srv->CallCommandHandler(command, strparams, params.size(), who);
890 // its not a user. Its either a server, or somethings screwed up.
891 if (IsServer(prefix))
893 target = Srv->GetServerName();
897 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
901 return DoOneToAllButSenderRaw(line,sourceserv);
910 virtual void OnTimeout()
912 if (this->LinkState == CONNECTING)
914 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
918 virtual void OnClose()
920 // Connection closed.
921 // If the connection is fully up (state CONNECTED)
922 // then propogate a netsplit to all peers.
923 std::string quitserver = this->myhost;
924 if (this->InboundServerName != "")
926 quitserver = this->InboundServerName;
928 TreeServer* s = FindServer(quitserver);
931 std::deque<std::string> params;
932 params.push_back(quitserver);
933 params.push_back(":Remote host closed the connection");
934 DoOneToAllButSender(Srv->GetServerName(),"SQUIT",params,quitserver);
935 Squit(s,"Remote host closed the connection");
939 virtual int OnIncomingConnection(int newsock, char* ip)
941 TreeSocket* s = new TreeSocket(newsock, ip);
947 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
949 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
951 TreeServer* Route = TreeRoot->GetChild(x);
952 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
954 TreeSocket* Sock = Route->GetSocket();
955 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
956 Sock->WriteLine(data);
962 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
964 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
965 // TODO: Special stuff with privmsg and notice
966 std::string FullLine = ":" + prefix + " " + command;
967 for (unsigned int x = 0; x < params.size(); x++)
969 FullLine = FullLine + " " + params[x];
971 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
973 TreeServer* Route = TreeRoot->GetChild(x);
975 // The route has a socket (its a direct connection)
976 // The route isnt the one to be omitted
977 // The route isnt the path to the one to be omitted
978 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
980 TreeSocket* Sock = Route->GetSocket();
981 log(DEBUG,"Sending to %s",Route->GetName().c_str());
982 Sock->WriteLine(FullLine);
988 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
990 std::string FullLine = ":" + prefix + " " + command;
991 for (unsigned int x = 0; x < params.size(); x++)
993 FullLine = FullLine + " " + params[x];
995 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
997 TreeServer* Route = TreeRoot->GetChild(x);
998 if (Route->GetSocket())
1000 TreeSocket* Sock = Route->GetSocket();
1001 Sock->WriteLine(FullLine);
1007 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1009 TreeServer* Route = BestRouteTo(target);
1012 std::string FullLine = ":" + prefix + " " + command;
1013 for (unsigned int x = 0; x < params.size(); x++)
1015 FullLine = FullLine + " " + params[x];
1017 if (Route->GetSocket())
1019 TreeSocket* Sock = Route->GetSocket();
1020 Sock->WriteLine(FullLine);
1026 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1032 class ModuleSpanningTree : public Module
1034 std::vector<TreeSocket*> Bindings;
1039 void ReadConfiguration(bool rebind)
1043 for (int j =0; j < Conf->Enumerate("bind"); j++)
1045 std::string Type = Conf->ReadValue("bind","type",j);
1046 std::string IP = Conf->ReadValue("bind","address",j);
1047 long Port = Conf->ReadInteger("bind","port",j,true);
1048 if (Type == "servers")
1054 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1055 if (listener->GetState() == I_LISTENING)
1057 Srv->AddSocket(listener);
1058 Bindings.push_back(listener);
1062 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1070 for (int j =0; j < Conf->Enumerate("link"); j++)
1073 L.Name = Conf->ReadValue("link","name",j);
1074 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1075 L.Port = Conf->ReadInteger("link","port",j,true);
1076 L.SendPass = Conf->ReadValue("link","sendpass",j);
1077 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1078 LinkBlocks.push_back(L);
1079 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1083 ModuleSpanningTree()
1086 Conf = new ConfigReader;
1089 // Create the root of the tree
1090 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1092 ReadConfiguration(true);
1095 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1097 std::string Parent = TreeRoot->GetName();
1098 if (Current->GetParent())
1100 Parent = Current->GetParent()->GetName();
1102 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1104 ShowLinks(Current->GetChild(q),user,hops+1);
1106 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1109 void HandleLinks(char** parameters, int pcnt, userrec* user)
1111 ShowLinks(TreeRoot,user,0);
1112 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1116 void HandleLusers(char** parameters, int pcnt, userrec* user)
1121 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1123 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1127 for (int t = 0; t < depth; t++)
1129 matrix[line][t] = ' ';
1131 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1133 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1135 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1140 // Ok, prepare to be confused.
1141 // After much mulling over how to approach this, it struck me that
1142 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1143 // keeping track of a ton of ascii characters, and line by line
1144 // under recursion working out where to place them using multiplications
1145 // and divisons, we instead render the map onto a backplane of characters
1146 // (a character matrix), then draw the branches as a series of "L" shapes
1147 // from the nodes. This is not only friendlier on CPU it uses less stack.
1149 void HandleMap(char** parameters, int pcnt, userrec* user)
1151 // This array represents a virtual screen which we will
1152 // "scratch" draw to, as the console device of an irc
1153 // client does not provide for a proper terminal.
1154 char matrix[128][80];
1155 for (unsigned int t = 0; t < 128; t++)
1157 matrix[t][0] = '\0';
1160 // The only recursive bit is called here.
1161 ShowMap(TreeRoot,user,0,matrix);
1162 // Process each line one by one. The algorithm has a limit of
1163 // 128 servers (which is far more than a spanning tree should have
1164 // anyway, so we're ok). This limit can be raised simply by making
1165 // the character matrix deeper, 128 rows taking 10k of memory.
1166 for (int l = 1; l < line; l++)
1168 // scan across the line looking for the start of the
1169 // servername (the recursive part of the algorithm has placed
1170 // the servers at indented positions depending on what they
1172 int first_nonspace = 0;
1173 while (matrix[l][first_nonspace] == ' ')
1178 // Draw the `- (corner) section: this may be overwritten by
1179 // another L shape passing along the same vertical pane, becoming
1180 // a |- (branch) section instead.
1181 matrix[l][first_nonspace] = '-';
1182 matrix[l][first_nonspace-1] = '`';
1184 // Draw upwards until we hit the parent server, causing possibly
1185 // other corners (`-) to become branches (|-)
1186 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1188 matrix[l2][first_nonspace-1] = '|';
1192 // dump the whole lot to the user. This is the easy bit, honest.
1193 for (int t = 0; t < line; t++)
1195 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1197 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1201 int HandleSquit(char** parameters, int pcnt, userrec* user)
1206 int HandleConnect(char** parameters, int pcnt, userrec* user)
1208 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1210 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1212 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1213 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1214 Srv->AddSocket(newsocket);
1218 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1222 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1224 if (command == "CONNECT")
1226 return this->HandleConnect(parameters,pcnt,user);
1228 else if (command == "SQUIT")
1230 return this->HandleSquit(parameters,pcnt,user);
1232 else if (command == "MAP")
1234 this->HandleMap(parameters,pcnt,user);
1237 else if (command == "LUSERS")
1239 this->HandleLusers(parameters,pcnt,user);
1242 else if (command == "LINKS")
1244 this->HandleLinks(parameters,pcnt,user);
1250 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1252 if (target_type == TYPE_USER)
1254 userrec* d = (userrec*)dest;
1255 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1257 std::deque<std::string> params;
1259 params.push_back(d->nick);
1260 params.push_back(":"+text);
1261 DoOneToOne(user->nick,"NOTICE",params,d->server);
1266 if (std::string(user->server) == Srv->GetServerName())
1268 chanrec *c = (chanrec*)dest;
1269 std::deque<std::string> params;
1270 params.push_back(c->name);
1271 params.push_back(":"+text);
1272 DoOneToMany(user->nick,"NOTICE",params);
1277 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1279 if (target_type == TYPE_USER)
1281 // route private messages which are targetted at clients only to the server
1282 // which needs to receive them
1283 userrec* d = (userrec*)dest;
1284 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1286 std::deque<std::string> params;
1288 params.push_back(d->nick);
1289 params.push_back(":"+text);
1290 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1295 if (std::string(user->server) == Srv->GetServerName())
1297 chanrec *c = (chanrec*)dest;
1298 std::deque<std::string> params;
1299 params.push_back(c->name);
1300 params.push_back(":"+text);
1301 DoOneToMany(user->nick,"PRIVMSG",params);
1306 virtual void OnUserJoin(userrec* user, chanrec* channel)
1308 // Only do this for local users
1309 if (std::string(user->server) == Srv->GetServerName())
1311 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1312 std::deque<std::string> params;
1314 params.push_back(channel->name);
1317 log(DEBUG,"**** With key %s",channel->key);
1318 // if the channel has a key, force the join by emulating the key.
1319 params.push_back(channel->key);
1321 DoOneToMany(user->nick,"JOIN",params);
1325 virtual void OnUserPart(userrec* user, chanrec* channel)
1327 if (std::string(user->server) == Srv->GetServerName())
1329 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1330 std::deque<std::string> params;
1332 params.push_back(channel->name);
1333 DoOneToMany(user->nick,"PART",params);
1337 virtual void OnUserConnect(userrec* user)
1339 char agestr[MAXBUF];
1340 if (std::string(user->server) == Srv->GetServerName())
1342 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1343 std::deque<std::string> params;
1344 snprintf(agestr,MAXBUF,"%d",user->age);
1346 params.push_back(agestr);
1347 params.push_back(user->nick);
1348 params.push_back(user->host);
1349 params.push_back(user->dhost);
1350 params.push_back(user->ident);
1351 params.push_back("+"+std::string(user->modes));
1352 params.push_back(user->ip);
1353 params.push_back(":"+std::string(user->fullname));
1354 DoOneToMany(Srv->GetServerName(),"NICK",params);
1358 virtual void OnUserQuit(userrec* user, std::string reason)
1360 if (std::string(user->server) == Srv->GetServerName())
1362 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1363 std::deque<std::string> params;
1364 params.push_back(":"+reason);
1365 DoOneToMany(user->nick,"QUIT",params);
1369 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1371 if (std::string(user->server) == Srv->GetServerName())
1373 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1374 std::deque<std::string> params;
1375 params.push_back(user->nick);
1376 DoOneToMany(oldnick,"NICK",params);
1380 // note: the protocol does not allow direct umode +o except
1381 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1383 virtual void OnOper(userrec* user, std::string opertype)
1385 if (std::string(user->server) == Srv->GetServerName())
1387 std::deque<std::string> params;
1388 params.push_back(opertype);
1389 DoOneToMany(user->nick,"OPERTYPE",params);
1393 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1395 if (std::string(user->server) == Srv->GetServerName())
1397 if (target_type == TYPE_USER)
1399 userrec* u = (userrec*)dest;
1400 std::deque<std::string> params;
1401 params.push_back(u->nick);
1402 params.push_back(text);
1403 DoOneToMany(user->nick,"MODE",params);
1407 chanrec* c = (chanrec*)dest;
1408 std::deque<std::string> params;
1409 params.push_back(c->name);
1410 params.push_back(text);
1411 DoOneToMany(user->nick,"MODE",params);
1416 virtual ~ModuleSpanningTree()
1421 virtual Version GetVersion()
1423 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1428 class ModuleSpanningTreeFactory : public ModuleFactory
1431 ModuleSpanningTreeFactory()
1435 ~ModuleSpanningTreeFactory()
1439 virtual Module * CreateModule()
1441 return new ModuleSpanningTree;
1447 extern "C" void * init_module( void )
1449 return new ModuleSpanningTreeFactory;