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 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
50 extern user_hash clientlist;
51 extern chan_hash chanlist;
56 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
57 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
58 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
59 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
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++)
166 // removes child nodes of this node, and of that node, etc etc
169 bool stillchildren = true;
170 while (stillchildren)
172 stillchildren = false;
173 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
175 TreeServer* s = (TreeServer*)*a;
179 stillchildren = true;
193 std::string SendPass;
194 std::string RecvPass;
197 /* $ModDesc: Povides a spanning tree server link protocol */
201 TreeServer *TreeRoot;
202 std::vector<Link> LinkBlocks;
204 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
206 if (Current->GetName() == ServerName)
208 for (unsigned int q = 0; q < Current->ChildCount(); q++)
210 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
219 // Returns the locally connected server we must route a
220 // message through to reach server 'ServerName'. This
221 // only applies to one-to-one and not one-to-many routing.
222 TreeServer* BestRouteTo(std::string ServerName)
224 log(DEBUG,"Finding best route to %s",ServerName.c_str());
225 // first, find the server by recursively walking the tree
226 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
227 // did we find it? If not, they did something wrong, abort.
230 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
235 // The server exists, follow its parent nodes until
236 // the parent of the current is 'TreeRoot', we know
237 // then that this is a directly-connected server.
238 while ((Found) && (Found->GetParent() != TreeRoot))
240 Found = Found->GetParent();
242 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
247 bool LookForServer(TreeServer* Current, std::string ServerName)
249 if (ServerName == Current->GetName())
251 for (unsigned int q = 0; q < Current->ChildCount(); q++)
253 if (LookForServer(Current->GetChild(q),ServerName))
261 void RFindServer(TreeServer* Current, std::string ServerName)
263 if ((ServerName == Current->GetName()) && (!Found))
266 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
271 for (unsigned int q = 0; q < Current->ChildCount(); q++)
274 RFindServer(Current->GetChild(q),ServerName);
280 TreeServer* FindServer(std::string ServerName)
283 RFindServer(TreeRoot,ServerName);
287 bool IsServer(std::string ServerName)
289 return LookForServer(TreeRoot,ServerName);
292 class TreeSocket : public InspSocket
295 std::string in_buffer;
296 ServerState LinkState;
297 std::string InboundServerName;
298 std::string InboundDescription;
300 int num_lost_servers;
304 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
305 : InspSocket(host, port, listening, maxtime)
307 Srv->Log(DEBUG,"Create new listening");
309 this->LinkState = LISTENER;
312 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
313 : InspSocket(host, port, listening, maxtime)
315 Srv->Log(DEBUG,"Create new outbound");
317 this->LinkState = CONNECTING;
320 TreeSocket(int newfd, char* ip)
321 : InspSocket(newfd, ip)
323 Srv->Log(DEBUG,"Associate new inbound");
324 this->LinkState = WAIT_AUTH_1;
327 virtual bool OnConnected()
329 if (this->LinkState == CONNECTING)
331 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
332 // we should send our details here.
333 // if the other side is satisfied, they send theirs.
334 // we do not need to change state here.
335 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
337 if (x->Name == this->myhost)
339 // found who we're supposed to be connecting to, send the neccessary gubbins.
340 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
345 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
349 virtual void OnError(InspSocketError e)
353 virtual int OnDisconnect()
358 // recursively send the server tree with distances as hops
359 void SendServers(TreeServer* Current, TreeServer* s, int hops)
362 for (unsigned int q = 0; q < Current->ChildCount(); q++)
364 TreeServer* recursive_server = Current->GetChild(q);
365 if (recursive_server != s)
367 // :source.server SERVER server.name hops :Description
368 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
369 this->WriteLine(command);
370 // down to next level
371 this->SendServers(recursive_server, s, hops+1);
376 void SquitServer(TreeServer* Current)
378 // recursively squit the servers attached to 'Current'
379 for (unsigned int q = 0; q < Current->ChildCount(); q++)
381 TreeServer* recursive_server = Current->GetChild(q);
382 this->SquitServer(recursive_server);
384 // Now we've whacked the kids, whack self
385 log(DEBUG,"Deleted %s",Current->GetName().c_str());
387 bool quittingpeople = true;
388 while (quittingpeople)
390 quittingpeople = false;
391 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
393 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
395 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
396 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
398 quittingpeople = true;
405 void Squit(TreeServer* Current,std::string reason)
409 std::deque<std::string> params;
410 params.push_back(Current->GetName());
411 params.push_back(":"+reason);
412 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
413 if (Current->GetParent() == TreeRoot)
415 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
419 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
421 num_lost_servers = 0;
423 SquitServer(Current);
425 Current->GetParent()->DelChild(Current);
427 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
431 log(DEBUG,"Squit from unknown server");
435 bool ForceMode(std::string source, std::deque<std::string> params)
437 userrec* who = new userrec;
438 who->fd = FD_MAGIC_NUMBER;
439 if (params.size() < 2)
442 for (unsigned int q = 0; q < params.size(); q++)
444 modelist[q] = (char*)params[q].c_str();
446 Srv->SendMode(modelist,params.size(),who);
447 DoOneToAllButSender(source,"FMODE",params,source);
452 bool ForceJoin(std::string source, std::deque<std::string> params)
454 if (params.size() < 1)
456 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
458 // process one channel at a time, applying modes.
459 char* channel = (char*)params[channelnum].c_str();
460 char permissions = *channel;
477 userrec* who = Srv->FindNick(source);
481 chanrec* chan = Srv->FindChannel(channel);
482 if ((chan) && (*chan->key))
486 Srv->JoinUserToChannel(who,channel,key);
490 modelist[0] = channel;
492 modelist[2] = who->nick;
493 Srv->SendMode(modelist,3,who);
495 DoOneToAllButSender(source,"FJOIN",params,who->server);
501 bool IntroduceClient(std::string source, std::deque<std::string> params)
503 if (params.size() < 8)
505 // NICK age nick host dhost ident +modes ip :gecos
507 std::string nick = params[1];
508 std::string host = params[2];
509 std::string dhost = params[3];
510 std::string ident = params[4];
511 time_t age = atoi(params[0].c_str());
512 std::string modes = params[5];
513 if (*(modes.c_str()) == '+')
515 char* m = (char*)modes.c_str();
519 std::string ip = params[6];
520 std::string gecos = params[7];
521 char* tempnick = (char*)nick.c_str();
522 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
524 user_hash::iterator iter;
525 iter = clientlist.find(tempnick);
526 if (iter != clientlist.end())
529 log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
533 clientlist[tempnick] = new userrec();
534 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
535 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
536 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
537 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
538 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
539 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
540 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
541 clientlist[tempnick]->registered = 7;
542 clientlist[tempnick]->signon = age;
543 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
544 for (int i = 0; i < MAXCHANS; i++)
546 clientlist[tempnick]->chans[i].channel = NULL;
547 clientlist[tempnick]->chans[i].uc_modes = 0;
549 params[7] = ":" + params[7];
550 DoOneToAllButSender(source,"NICK",params,source);
554 void SendChannelModes(TreeServer* Current)
557 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
559 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
560 this->WriteLine(data);
561 if (*c->second->topic)
563 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",Srv->GetServerName().c_str(),c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
564 this->WriteLine(data);
566 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
568 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
569 this->WriteLine(data);
574 // send all users and their channels
575 void SendUsers(TreeServer* Current)
578 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
580 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);
581 this->WriteLine(data);
582 if (strchr(u->second->modes,'o'))
584 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
586 char* chl = chlist(u->second,u->second);
589 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
594 void DoBurst(TreeServer* s)
596 log(DEBUG,"Beginning network burst");
597 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
598 this->WriteLine("BURST");
600 this->SendServers(TreeRoot,s,1);
601 // Send users and their channels
603 // TODO: Send everything else (channel modes etc)
604 this->SendChannelModes(s);
605 this->WriteLine("ENDBURST");
608 virtual bool OnDataReady()
610 char* data = this->Read();
613 this->in_buffer += data;
614 while (in_buffer.find("\n") != std::string::npos)
616 char* line = (char*)in_buffer.c_str();
617 std::string ret = "";
618 while ((*line != '\n') && (strlen(line)))
623 if ((*line == '\n') || (*line == '\r'))
626 if (!this->ProcessLine(ret))
632 return (data != NULL);
635 int WriteLine(std::string line)
637 return this->Write(line + "\r\n");
640 bool Error(std::deque<std::string> params)
642 if (params.size() < 1)
644 std::string Errmsg = params[0];
645 std::string SName = myhost;
646 if (InboundServerName != "")
648 SName = InboundServerName;
650 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
651 // we will return false to cause the socket to close.
655 bool OperType(std::string prefix, std::deque<std::string> params)
657 if (params.size() != 1)
659 std::string opertype = params[0];
660 userrec* u = Srv->FindNick(prefix);
663 strlcpy(u->oper,opertype.c_str(),NICKMAX);
664 if (!strchr(u->modes,'o'))
666 strcat(u->modes,"o");
668 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
673 bool RemoteKill(std::string prefix, std::deque<std::string> params)
675 if (params.size() != 2)
677 std::string nick = params[0];
678 std::string reason = params[1];
679 userrec* u = Srv->FindNick(prefix);
680 userrec* who = Srv->FindNick(nick);
683 params[1] = ":" + params[1];
684 DoOneToAllButSender(prefix,"KILL",params,u->server);
685 Srv->QuitUser(who,reason);
690 bool RemoteServer(std::string prefix, std::deque<std::string> params)
692 if (params.size() < 4)
694 std::string servername = params[0];
695 std::string password = params[1];
696 int hops = atoi(params[2].c_str());
697 std::string description = params[3];
700 this->WriteLine("ERROR :Protocol error - Introduced remote server with incorrect hopcount!");
703 TreeServer* ParentOfThis = FindServer(prefix);
706 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
709 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
710 ParentOfThis->AddChild(Node);
711 params[3] = ":" + params[3];
712 DoOneToAllButSender(prefix,"SERVER",params,prefix);
713 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
717 bool Outbound_Reply_Server(std::deque<std::string> params)
719 if (params.size() < 4)
721 std::string servername = params[0];
722 std::string password = params[1];
723 int hops = atoi(params[2].c_str());
726 this->WriteLine("ERROR :Server too far away for authentication");
729 std::string description = params[3];
730 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
732 if ((x->Name == servername) && (x->RecvPass == password))
734 // Begin the sync here. this kickstarts the
735 // other side, waiting in WAIT_AUTH_2 state,
736 // into starting their burst, as it shows
738 this->LinkState = CONNECTED;
739 // we should add the details of this server now
740 // to the servers tree, as a child of the root
742 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
743 TreeRoot->AddChild(Node);
744 params[3] = ":" + params[3];
745 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
750 this->WriteLine("ERROR :Invalid credentials");
754 bool Inbound_Server(std::deque<std::string> params)
756 if (params.size() < 4)
758 std::string servername = params[0];
759 std::string password = params[1];
760 int hops = atoi(params[2].c_str());
763 this->WriteLine("ERROR :Server too far away for authentication");
766 std::string description = params[3];
767 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
769 if ((x->Name == servername) && (x->RecvPass == password))
771 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
772 this->InboundServerName = servername;
773 this->InboundDescription = description;
774 // this is good. Send our details: Our server name and description and hopcount of 0,
775 // along with the sendpass from this block.
776 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
777 // move to the next state, we are now waiting for THEM.
778 this->LinkState = WAIT_AUTH_2;
782 this->WriteLine("ERROR :Invalid credentials");
786 std::deque<std::string> Split(std::string line, bool stripcolon)
788 std::deque<std::string> n;
789 std::stringstream s(line);
790 std::string param = "";
796 if ((param != "") && (param != "\n"))
798 if ((param.c_str()[0] == ':') && (item))
800 char* str = (char*)param.c_str();
810 param = param + " " + append;
821 bool ProcessLine(std::string line)
823 char* l = (char*)line.c_str();
824 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
825 l[strlen(l)-1] = '\0';
829 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
830 std::deque<std::string> params = this->Split(line,true);
831 std::string command = "";
832 std::string prefix = "";
833 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
837 char* pref = (char*)prefix.c_str();
849 switch (this->LinkState)
854 // Waiting for SERVER command from remote server. Server initiating
855 // the connection sends the first SERVER command, listening server
856 // replies with theirs if its happy, then if the initiator is happy,
857 // it starts to send its net sync, which starts the merge, otherwise
858 // it sends an ERROR.
859 if (command == "SERVER")
861 return this->Inbound_Server(params);
863 else if (command == "ERROR")
865 return this->Error(params);
869 // Waiting for start of other side's netmerge to say they liked our
871 if (command == "SERVER")
873 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
877 else if (command == "BURST")
879 this->LinkState = CONNECTED;
880 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
881 TreeRoot->AddChild(Node);
883 params.push_back(InboundServerName);
884 params.push_back("*");
885 params.push_back("1");
886 params.push_back(":"+InboundDescription);
887 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
890 else if (command == "ERROR")
892 return this->Error(params);
897 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
901 if (command == "SERVER")
903 // another server we connected to, which was in WAIT_AUTH_1 state,
904 // has just sent us their credentials. If we get this far, theyre
905 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
906 // if we're happy with this, we should send our netburst which
907 // kickstarts the merge.
908 return this->Outbound_Reply_Server(params);
912 // This is the 'authenticated' state, when all passwords
913 // have been exchanged and anything past this point is taken
915 std::string target = "";
916 if ((command == "NICK") && (params.size() > 1))
918 return this->IntroduceClient(prefix,params);
920 else if (command == "FJOIN")
922 return this->ForceJoin(prefix,params);
924 else if (command == "SERVER")
926 return this->RemoteServer(prefix,params);
928 else if (command == "OPERTYPE")
930 return this->OperType(prefix,params);
932 else if (command == "FMODE")
934 return this->ForceMode(prefix,params);
936 else if (command == "KILL")
938 return this->RemoteKill(prefix,params);
940 else if (command == "SQUIT")
942 if (params.size() == 2)
944 this->Squit(FindServer(params[0]),params[1]);
950 // not a special inter-server command.
951 // Emulate the actual user doing the command,
952 // this saves us having a huge ugly parser.
953 userrec* who = Srv->FindNick(prefix);
954 std::string sourceserv = this->myhost;
955 if (this->InboundServerName != "")
957 sourceserv = this->InboundServerName;
962 target = who->server;
963 char* strparams[127];
964 for (unsigned int q = 0; q < params.size(); q++)
966 strparams[q] = (char*)params[q].c_str();
968 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
969 Srv->CallCommandHandler(command, strparams, params.size(), who);
973 // its not a user. Its either a server, or somethings screwed up.
974 if (IsServer(prefix))
976 target = Srv->GetServerName();
980 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
984 return DoOneToAllButSenderRaw(line,sourceserv);
993 virtual void OnTimeout()
995 if (this->LinkState == CONNECTING)
997 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1001 virtual void OnClose()
1003 // Connection closed.
1004 // If the connection is fully up (state CONNECTED)
1005 // then propogate a netsplit to all peers.
1006 std::string quitserver = this->myhost;
1007 if (this->InboundServerName != "")
1009 quitserver = this->InboundServerName;
1011 TreeServer* s = FindServer(quitserver);
1014 Squit(s,"Remote host closed the connection");
1018 virtual int OnIncomingConnection(int newsock, char* ip)
1020 TreeSocket* s = new TreeSocket(newsock, ip);
1026 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1028 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1030 TreeServer* Route = TreeRoot->GetChild(x);
1031 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1033 TreeSocket* Sock = Route->GetSocket();
1034 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1035 Sock->WriteLine(data);
1041 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1043 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1044 // TODO: Special stuff with privmsg and notice
1045 std::string FullLine = ":" + prefix + " " + command;
1046 for (unsigned int x = 0; x < params.size(); x++)
1048 FullLine = FullLine + " " + params[x];
1050 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1052 TreeServer* Route = TreeRoot->GetChild(x);
1053 // Send the line IF:
1054 // The route has a socket (its a direct connection)
1055 // The route isnt the one to be omitted
1056 // The route isnt the path to the one to be omitted
1057 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1059 TreeSocket* Sock = Route->GetSocket();
1060 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1061 Sock->WriteLine(FullLine);
1067 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1069 std::string FullLine = ":" + prefix + " " + command;
1070 for (unsigned int x = 0; x < params.size(); x++)
1072 FullLine = FullLine + " " + params[x];
1074 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1076 TreeServer* Route = TreeRoot->GetChild(x);
1077 if (Route->GetSocket())
1079 TreeSocket* Sock = Route->GetSocket();
1080 Sock->WriteLine(FullLine);
1086 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1088 TreeServer* Route = BestRouteTo(target);
1091 std::string FullLine = ":" + prefix + " " + command;
1092 for (unsigned int x = 0; x < params.size(); x++)
1094 FullLine = FullLine + " " + params[x];
1096 if (Route->GetSocket())
1098 TreeSocket* Sock = Route->GetSocket();
1099 Sock->WriteLine(FullLine);
1105 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1111 class ModuleSpanningTree : public Module
1113 std::vector<TreeSocket*> Bindings;
1118 void ReadConfiguration(bool rebind)
1122 for (int j =0; j < Conf->Enumerate("bind"); j++)
1124 std::string Type = Conf->ReadValue("bind","type",j);
1125 std::string IP = Conf->ReadValue("bind","address",j);
1126 long Port = Conf->ReadInteger("bind","port",j,true);
1127 if (Type == "servers")
1133 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1134 if (listener->GetState() == I_LISTENING)
1136 Srv->AddSocket(listener);
1137 Bindings.push_back(listener);
1141 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1149 for (int j =0; j < Conf->Enumerate("link"); j++)
1152 L.Name = Conf->ReadValue("link","name",j);
1153 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1154 L.Port = Conf->ReadInteger("link","port",j,true);
1155 L.SendPass = Conf->ReadValue("link","sendpass",j);
1156 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1157 LinkBlocks.push_back(L);
1158 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1162 ModuleSpanningTree()
1165 Conf = new ConfigReader;
1168 // Create the root of the tree
1169 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1171 ReadConfiguration(true);
1174 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1176 std::string Parent = TreeRoot->GetName();
1177 if (Current->GetParent())
1179 Parent = Current->GetParent()->GetName();
1181 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1183 ShowLinks(Current->GetChild(q),user,hops+1);
1185 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1188 void HandleLinks(char** parameters, int pcnt, userrec* user)
1190 ShowLinks(TreeRoot,user,0);
1191 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1195 void HandleLusers(char** parameters, int pcnt, userrec* user)
1200 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1202 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1206 for (int t = 0; t < depth; t++)
1208 matrix[line][t] = ' ';
1210 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1212 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1214 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1219 // Ok, prepare to be confused.
1220 // After much mulling over how to approach this, it struck me that
1221 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1222 // keeping track of a ton of ascii characters, and line by line
1223 // under recursion working out where to place them using multiplications
1224 // and divisons, we instead render the map onto a backplane of characters
1225 // (a character matrix), then draw the branches as a series of "L" shapes
1226 // from the nodes. This is not only friendlier on CPU it uses less stack.
1228 void HandleMap(char** parameters, int pcnt, userrec* user)
1230 // This array represents a virtual screen which we will
1231 // "scratch" draw to, as the console device of an irc
1232 // client does not provide for a proper terminal.
1233 char matrix[128][80];
1234 for (unsigned int t = 0; t < 128; t++)
1236 matrix[t][0] = '\0';
1239 // The only recursive bit is called here.
1240 ShowMap(TreeRoot,user,0,matrix);
1241 // Process each line one by one. The algorithm has a limit of
1242 // 128 servers (which is far more than a spanning tree should have
1243 // anyway, so we're ok). This limit can be raised simply by making
1244 // the character matrix deeper, 128 rows taking 10k of memory.
1245 for (int l = 1; l < line; l++)
1247 // scan across the line looking for the start of the
1248 // servername (the recursive part of the algorithm has placed
1249 // the servers at indented positions depending on what they
1251 int first_nonspace = 0;
1252 while (matrix[l][first_nonspace] == ' ')
1257 // Draw the `- (corner) section: this may be overwritten by
1258 // another L shape passing along the same vertical pane, becoming
1259 // a |- (branch) section instead.
1260 matrix[l][first_nonspace] = '-';
1261 matrix[l][first_nonspace-1] = '`';
1263 // Draw upwards until we hit the parent server, causing possibly
1264 // other corners (`-) to become branches (|-)
1265 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1267 matrix[l2][first_nonspace-1] = '|';
1271 // dump the whole lot to the user. This is the easy bit, honest.
1272 for (int t = 0; t < line; t++)
1274 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1276 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1280 int HandleSquit(char** parameters, int pcnt, userrec* user)
1285 int HandleConnect(char** parameters, int pcnt, userrec* user)
1287 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1289 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1291 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1292 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1293 Srv->AddSocket(newsocket);
1297 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1301 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1303 if (command == "CONNECT")
1305 return this->HandleConnect(parameters,pcnt,user);
1307 else if (command == "SQUIT")
1309 return this->HandleSquit(parameters,pcnt,user);
1311 else if (command == "MAP")
1313 this->HandleMap(parameters,pcnt,user);
1316 else if (command == "LUSERS")
1318 this->HandleLusers(parameters,pcnt,user);
1321 else if (command == "LINKS")
1323 this->HandleLinks(parameters,pcnt,user);
1329 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1331 if (target_type == TYPE_USER)
1333 userrec* d = (userrec*)dest;
1334 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1336 std::deque<std::string> params;
1338 params.push_back(d->nick);
1339 params.push_back(":"+text);
1340 DoOneToOne(user->nick,"NOTICE",params,d->server);
1345 if (std::string(user->server) == Srv->GetServerName())
1347 chanrec *c = (chanrec*)dest;
1348 std::deque<std::string> params;
1349 params.push_back(c->name);
1350 params.push_back(":"+text);
1351 DoOneToMany(user->nick,"NOTICE",params);
1356 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1358 if (target_type == TYPE_USER)
1360 // route private messages which are targetted at clients only to the server
1361 // which needs to receive them
1362 userrec* d = (userrec*)dest;
1363 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1365 std::deque<std::string> params;
1367 params.push_back(d->nick);
1368 params.push_back(":"+text);
1369 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1374 if (std::string(user->server) == Srv->GetServerName())
1376 chanrec *c = (chanrec*)dest;
1377 std::deque<std::string> params;
1378 params.push_back(c->name);
1379 params.push_back(":"+text);
1380 DoOneToMany(user->nick,"PRIVMSG",params);
1385 virtual void OnUserJoin(userrec* user, chanrec* channel)
1387 // Only do this for local users
1388 if (std::string(user->server) == Srv->GetServerName())
1390 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1391 std::deque<std::string> params;
1393 params.push_back(channel->name);
1396 log(DEBUG,"**** With key %s",channel->key);
1397 // if the channel has a key, force the join by emulating the key.
1398 params.push_back(channel->key);
1400 DoOneToMany(user->nick,"JOIN",params);
1404 virtual void OnUserPart(userrec* user, chanrec* channel)
1406 if (std::string(user->server) == Srv->GetServerName())
1408 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1409 std::deque<std::string> params;
1411 params.push_back(channel->name);
1412 DoOneToMany(user->nick,"PART",params);
1416 virtual void OnUserConnect(userrec* user)
1418 char agestr[MAXBUF];
1419 if (std::string(user->server) == Srv->GetServerName())
1421 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1422 std::deque<std::string> params;
1423 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1425 params.push_back(agestr);
1426 params.push_back(user->nick);
1427 params.push_back(user->host);
1428 params.push_back(user->dhost);
1429 params.push_back(user->ident);
1430 params.push_back("+"+std::string(user->modes));
1431 params.push_back(user->ip);
1432 params.push_back(":"+std::string(user->fullname));
1433 DoOneToMany(Srv->GetServerName(),"NICK",params);
1437 virtual void OnUserQuit(userrec* user, std::string reason)
1439 if (std::string(user->server) == Srv->GetServerName())
1441 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1442 std::deque<std::string> params;
1443 params.push_back(":"+reason);
1444 DoOneToMany(user->nick,"QUIT",params);
1448 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1450 if (std::string(user->server) == Srv->GetServerName())
1452 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1453 std::deque<std::string> params;
1454 params.push_back(user->nick);
1455 DoOneToMany(oldnick,"NICK",params);
1459 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1461 if (std::string(source->server) == Srv->GetServerName())
1463 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1464 std::deque<std::string> params;
1465 params.push_back(chan->name);
1466 params.push_back(user->nick);
1467 params.push_back(":"+reason);
1468 DoOneToMany(source->nick,"KICK",params);
1472 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1474 std::deque<std::string> params;
1475 params.push_back(dest->nick);
1476 params.push_back(":"+reason);
1477 DoOneToMany(source->nick,"KILL",params);
1480 // note: the protocol does not allow direct umode +o except
1481 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1483 virtual void OnOper(userrec* user, std::string opertype)
1485 if (std::string(user->server) == Srv->GetServerName())
1487 std::deque<std::string> params;
1488 params.push_back(opertype);
1489 DoOneToMany(user->nick,"OPERTYPE",params);
1493 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1495 log(DEBUG,"*** ONMODE TRIGGER");
1496 if (std::string(user->server) == Srv->GetServerName())
1498 log(DEBUG,"*** LOCAL");
1499 if (target_type == TYPE_USER)
1501 userrec* u = (userrec*)dest;
1502 std::deque<std::string> params;
1503 params.push_back(u->nick);
1504 params.push_back(text);
1505 DoOneToMany(user->nick,"MODE",params);
1509 chanrec* c = (chanrec*)dest;
1510 std::deque<std::string> params;
1511 params.push_back(c->name);
1512 params.push_back(text);
1513 DoOneToMany(user->nick,"MODE",params);
1518 virtual ~ModuleSpanningTree()
1523 virtual Version GetVersion()
1525 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1530 class ModuleSpanningTreeFactory : public ModuleFactory
1533 ModuleSpanningTreeFactory()
1537 ~ModuleSpanningTreeFactory()
1541 virtual Module * CreateModule()
1543 return new ModuleSpanningTree;
1549 extern "C" void * init_module( void )
1551 return new ModuleSpanningTreeFactory;