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 class ModuleSpanningTree;
46 static ModuleSpanningTree* TreeProtocolModule;
48 extern std::vector<Module*> modules;
49 extern std::vector<ircd_module*> factory;
52 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
54 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
55 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
57 extern user_hash clientlist;
58 extern chan_hash chanlist;
63 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
64 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
65 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
66 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
71 std::vector<TreeServer*> Children;
72 std::string ServerName;
73 std::string ServerDesc;
74 std::string VersionString;
77 TreeSocket* Socket; // for directly connected servers this points at the socket object
87 UserCount = OperCount = 0;
90 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
94 UserCount = OperCount = 0;
97 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
100 UserCount = OperCount = 0;
103 std::string GetName()
105 return this->ServerName;
108 std::string GetDesc()
110 return this->ServerDesc;
113 std::string GetVersion()
115 return this->VersionString;
120 return this->UserCount;
125 return this->OperCount;
128 TreeSocket* GetSocket()
133 TreeServer* GetParent()
138 unsigned int ChildCount()
140 return Children.size();
143 TreeServer* GetChild(unsigned int n)
145 if (n < Children.size())
155 void AddChild(TreeServer* Child)
157 Children.push_back(Child);
160 bool DelChild(TreeServer* Child)
162 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
173 // removes child nodes of this node, and of that node, etc etc
176 bool stillchildren = true;
177 while (stillchildren)
179 stillchildren = false;
180 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
182 TreeServer* s = (TreeServer*)*a;
186 stillchildren = true;
200 std::string SendPass;
201 std::string RecvPass;
204 /* $ModDesc: Povides a spanning tree server link protocol */
208 TreeServer *TreeRoot;
209 std::vector<Link> LinkBlocks;
211 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
213 if (Current->GetName() == ServerName)
215 for (unsigned int q = 0; q < Current->ChildCount(); q++)
217 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
226 // Returns the locally connected server we must route a
227 // message through to reach server 'ServerName'. This
228 // only applies to one-to-one and not one-to-many routing.
229 TreeServer* BestRouteTo(std::string ServerName)
231 log(DEBUG,"Finding best route to %s",ServerName.c_str());
232 if (ServerName.c_str() == TreeRoot->GetName())
234 log(DEBUG,"Cant route to myself!!!");
237 // first, find the server by recursively walking the tree
238 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
239 // did we find it? If not, they did something wrong, abort.
242 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
247 // The server exists, follow its parent nodes until
248 // the parent of the current is 'TreeRoot', we know
249 // then that this is a directly-connected server.
250 while ((Found) && (Found->GetParent() != TreeRoot))
252 Found = Found->GetParent();
254 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
259 bool LookForServer(TreeServer* Current, std::string ServerName)
261 if (ServerName == Current->GetName())
263 for (unsigned int q = 0; q < Current->ChildCount(); q++)
265 if (LookForServer(Current->GetChild(q),ServerName))
273 void RFindServer(TreeServer* Current, std::string ServerName)
275 if ((ServerName == Current->GetName()) && (!Found))
278 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
283 for (unsigned int q = 0; q < Current->ChildCount(); q++)
286 RFindServer(Current->GetChild(q),ServerName);
292 TreeServer* FindServer(std::string ServerName)
295 RFindServer(TreeRoot,ServerName);
299 bool IsServer(std::string ServerName)
301 return LookForServer(TreeRoot,ServerName);
304 class TreeSocket : public InspSocket
307 std::string in_buffer;
308 ServerState LinkState;
309 std::string InboundServerName;
310 std::string InboundDescription;
312 int num_lost_servers;
316 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
317 : InspSocket(host, port, listening, maxtime)
319 Srv->Log(DEBUG,"Create new listening");
321 this->LinkState = LISTENER;
324 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
325 : InspSocket(host, port, listening, maxtime)
327 Srv->Log(DEBUG,"Create new outbound");
329 this->LinkState = CONNECTING;
332 TreeSocket(int newfd, char* ip)
333 : InspSocket(newfd, ip)
335 Srv->Log(DEBUG,"Associate new inbound");
336 this->LinkState = WAIT_AUTH_1;
339 virtual bool OnConnected()
341 if (this->LinkState == CONNECTING)
343 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
344 // we should send our details here.
345 // if the other side is satisfied, they send theirs.
346 // we do not need to change state here.
347 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
349 if (x->Name == this->myhost)
351 // found who we're supposed to be connecting to, send the neccessary gubbins.
352 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
357 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
361 virtual void OnError(InspSocketError e)
365 virtual int OnDisconnect()
370 // recursively send the server tree with distances as hops
371 void SendServers(TreeServer* Current, TreeServer* s, int hops)
374 for (unsigned int q = 0; q < Current->ChildCount(); q++)
376 TreeServer* recursive_server = Current->GetChild(q);
377 if (recursive_server != s)
379 // :source.server SERVER server.name hops :Description
380 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
381 this->WriteLine(command);
382 // down to next level
383 this->SendServers(recursive_server, s, hops+1);
388 void SquitServer(TreeServer* Current)
390 // recursively squit the servers attached to 'Current'
391 for (unsigned int q = 0; q < Current->ChildCount(); q++)
393 TreeServer* recursive_server = Current->GetChild(q);
394 this->SquitServer(recursive_server);
396 // Now we've whacked the kids, whack self
397 log(DEBUG,"Deleted %s",Current->GetName().c_str());
399 bool quittingpeople = true;
400 while (quittingpeople)
402 quittingpeople = false;
403 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
405 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
407 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
408 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
410 quittingpeople = true;
417 void Squit(TreeServer* Current,std::string reason)
421 std::deque<std::string> params;
422 params.push_back(Current->GetName());
423 params.push_back(":"+reason);
424 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
425 if (Current->GetParent() == TreeRoot)
427 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
431 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
433 num_lost_servers = 0;
435 SquitServer(Current);
437 Current->GetParent()->DelChild(Current);
439 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
443 log(DEBUG,"Squit from unknown server");
447 bool ForceMode(std::string source, std::deque<std::string> params)
449 userrec* who = new userrec;
450 who->fd = FD_MAGIC_NUMBER;
451 if (params.size() < 2)
454 for (unsigned int q = 0; q < params.size(); q++)
456 modelist[q] = (char*)params[q].c_str();
458 Srv->SendMode(modelist,params.size(),who);
459 DoOneToAllButSender(source,"FMODE",params,source);
464 bool ForceTopic(std::string source, std::deque<std::string> params)
466 // FTOPIC %s %lu %s :%s
467 if (params.size() != 4)
469 std::string channel = params[0];
470 time_t ts = atoi(params[1].c_str());
471 std::string setby = params[2];
472 std::string topic = params[3];
474 chanrec* c = Srv->FindChannel(channel);
477 if ((ts >= c->topicset) || (!*c->topic))
479 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
480 strlcpy(c->setby,setby.c_str(),NICKMAX);
482 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
487 // all done, send it on its way
488 params[3] = ":" + params[3];
489 DoOneToAllButSender(source,"FTOPIC",params,source);
494 bool ForceJoin(std::string source, std::deque<std::string> params)
496 if (params.size() < 1)
498 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
500 // process one channel at a time, applying modes.
501 char* channel = (char*)params[channelnum].c_str();
502 char permissions = *channel;
519 userrec* who = Srv->FindNick(source);
523 chanrec* chan = Srv->FindChannel(channel);
524 if ((chan) && (*chan->key))
528 Srv->JoinUserToChannel(who,channel,key);
532 modelist[0] = channel;
534 modelist[2] = who->nick;
535 Srv->SendMode(modelist,3,who);
537 DoOneToAllButSender(source,"FJOIN",params,who->server);
543 bool IntroduceClient(std::string source, std::deque<std::string> params)
545 if (params.size() < 8)
547 // NICK age nick host dhost ident +modes ip :gecos
549 std::string nick = params[1];
550 std::string host = params[2];
551 std::string dhost = params[3];
552 std::string ident = params[4];
553 time_t age = atoi(params[0].c_str());
554 std::string modes = params[5];
555 if (*(modes.c_str()) == '+')
557 char* m = (char*)modes.c_str();
561 std::string ip = params[6];
562 std::string gecos = params[7];
563 char* tempnick = (char*)nick.c_str();
564 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
566 user_hash::iterator iter;
567 iter = clientlist.find(tempnick);
568 if (iter != clientlist.end())
571 log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,ident.c_str(),host.c_str(),(unsigned long)age,(unsigned long)iter->second->age);
572 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
576 clientlist[tempnick] = new userrec();
577 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
578 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
579 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
580 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
581 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
582 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
583 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
584 clientlist[tempnick]->registered = 7;
585 clientlist[tempnick]->signon = age;
586 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
587 for (int i = 0; i < MAXCHANS; i++)
589 clientlist[tempnick]->chans[i].channel = NULL;
590 clientlist[tempnick]->chans[i].uc_modes = 0;
592 params[7] = ":" + params[7];
593 DoOneToAllButSender(source,"NICK",params,source);
597 void SendChannelModes(TreeServer* Current)
600 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
602 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
603 this->WriteLine(data);
604 if (*c->second->topic)
606 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);
607 this->WriteLine(data);
609 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
611 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
612 this->WriteLine(data);
614 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
618 // send all users and their channels
619 void SendUsers(TreeServer* Current)
622 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
624 if (u->second->registered == 7)
626 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);
627 this->WriteLine(data);
628 if (strchr(u->second->modes,'o'))
630 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
632 char* chl = chlist(u->second,u->second);
635 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
637 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
642 void DoBurst(TreeServer* s)
644 log(DEBUG,"Beginning network burst");
645 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
646 this->WriteLine("BURST");
648 this->SendServers(TreeRoot,s,1);
649 // Send users and their channels
651 // TODO: Send everything else (channel modes etc)
652 this->SendChannelModes(s);
653 this->WriteLine("ENDBURST");
656 virtual bool OnDataReady()
658 char* data = this->Read();
661 this->in_buffer += data;
662 while (in_buffer.find("\n") != std::string::npos)
664 char* line = (char*)in_buffer.c_str();
665 std::string ret = "";
666 while ((*line != '\n') && (strlen(line)))
671 if ((*line == '\n') || (*line == '\r'))
674 if (!this->ProcessLine(ret))
680 return (data != NULL);
683 int WriteLine(std::string line)
685 return this->Write(line + "\r\n");
688 bool Error(std::deque<std::string> params)
690 if (params.size() < 1)
692 std::string Errmsg = params[0];
693 std::string SName = myhost;
694 if (InboundServerName != "")
696 SName = InboundServerName;
698 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
699 // we will return false to cause the socket to close.
703 bool OperType(std::string prefix, std::deque<std::string> params)
705 if (params.size() != 1)
707 std::string opertype = params[0];
708 userrec* u = Srv->FindNick(prefix);
711 strlcpy(u->oper,opertype.c_str(),NICKMAX);
712 if (!strchr(u->modes,'o'))
714 strcat(u->modes,"o");
716 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
721 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
723 if (params.size() < 1)
725 std::string servermask = params[0];
726 if (Srv->MatchText(Srv->GetServerName(),servermask))
728 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
730 TreeProtocolModule->ReadConfiguration(false);
732 DoOneToAllButSender(prefix,"REHASH",params,prefix);
736 bool RemoteKill(std::string prefix, std::deque<std::string> params)
738 if (params.size() != 2)
740 std::string nick = params[0];
741 std::string reason = params[1];
742 userrec* u = Srv->FindNick(prefix);
743 userrec* who = Srv->FindNick(nick);
746 std::string sourceserv = prefix;
749 sourceserv = u->server;
751 params[1] = ":" + params[1];
752 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
753 Srv->QuitUser(who,reason);
758 bool RemoteServer(std::string prefix, std::deque<std::string> params)
760 if (params.size() < 4)
762 std::string servername = params[0];
763 std::string password = params[1];
764 // hopcount is not used for a remote server, we calculate this ourselves
765 std::string description = params[3];
766 TreeServer* ParentOfThis = FindServer(prefix);
769 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
772 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
773 ParentOfThis->AddChild(Node);
774 params[3] = ":" + params[3];
775 DoOneToAllButSender(prefix,"SERVER",params,prefix);
776 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
780 bool Outbound_Reply_Server(std::deque<std::string> params)
782 if (params.size() < 4)
784 std::string servername = params[0];
785 std::string password = params[1];
786 int hops = atoi(params[2].c_str());
789 this->WriteLine("ERROR :Server too far away for authentication");
792 std::string description = params[3];
793 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
795 if ((x->Name == servername) && (x->RecvPass == password))
797 // Begin the sync here. this kickstarts the
798 // other side, waiting in WAIT_AUTH_2 state,
799 // into starting their burst, as it shows
801 this->LinkState = CONNECTED;
802 // we should add the details of this server now
803 // to the servers tree, as a child of the root
805 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
806 TreeRoot->AddChild(Node);
807 params[3] = ":" + params[3];
808 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
813 this->WriteLine("ERROR :Invalid credentials");
817 bool Inbound_Server(std::deque<std::string> params)
819 if (params.size() < 4)
821 std::string servername = params[0];
822 std::string password = params[1];
823 int hops = atoi(params[2].c_str());
826 this->WriteLine("ERROR :Server too far away for authentication");
829 std::string description = params[3];
830 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
832 if ((x->Name == servername) && (x->RecvPass == password))
834 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
835 this->InboundServerName = servername;
836 this->InboundDescription = description;
837 // this is good. Send our details: Our server name and description and hopcount of 0,
838 // along with the sendpass from this block.
839 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
840 // move to the next state, we are now waiting for THEM.
841 this->LinkState = WAIT_AUTH_2;
845 this->WriteLine("ERROR :Invalid credentials");
849 std::deque<std::string> Split(std::string line, bool stripcolon)
851 std::deque<std::string> n;
852 std::stringstream s(line);
853 std::string param = "";
859 //if ((param != "") && (param != "\n"))
861 if ((param.c_str()[0] == ':') && (item))
863 char* str = (char*)param.c_str();
873 param = param + " " + append;
884 bool ProcessLine(std::string line)
886 char* l = (char*)line.c_str();
887 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
888 l[strlen(l)-1] = '\0';
892 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
893 std::deque<std::string> params = this->Split(line,true);
894 std::string command = "";
895 std::string prefix = "";
896 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
900 char* pref = (char*)prefix.c_str();
912 switch (this->LinkState)
917 // Waiting for SERVER command from remote server. Server initiating
918 // the connection sends the first SERVER command, listening server
919 // replies with theirs if its happy, then if the initiator is happy,
920 // it starts to send its net sync, which starts the merge, otherwise
921 // it sends an ERROR.
922 if (command == "SERVER")
924 return this->Inbound_Server(params);
926 else if (command == "ERROR")
928 return this->Error(params);
932 // Waiting for start of other side's netmerge to say they liked our
934 if (command == "SERVER")
936 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
940 else if (command == "BURST")
942 this->LinkState = CONNECTED;
943 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
944 TreeRoot->AddChild(Node);
946 params.push_back(InboundServerName);
947 params.push_back("*");
948 params.push_back("1");
949 params.push_back(":"+InboundDescription);
950 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
953 else if (command == "ERROR")
955 return this->Error(params);
960 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
964 if (command == "SERVER")
966 // another server we connected to, which was in WAIT_AUTH_1 state,
967 // has just sent us their credentials. If we get this far, theyre
968 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
969 // if we're happy with this, we should send our netburst which
970 // kickstarts the merge.
971 return this->Outbound_Reply_Server(params);
973 else if (command == "ERROR")
975 return this->Error(params);
979 // This is the 'authenticated' state, when all passwords
980 // have been exchanged and anything past this point is taken
982 std::string target = "";
983 if ((command == "NICK") && (params.size() > 1))
985 return this->IntroduceClient(prefix,params);
987 else if (command == "FJOIN")
989 return this->ForceJoin(prefix,params);
991 else if (command == "SERVER")
993 return this->RemoteServer(prefix,params);
995 else if (command == "ERROR")
997 return this->Error(params);
999 else if (command == "OPERTYPE")
1001 return this->OperType(prefix,params);
1003 else if (command == "FMODE")
1005 return this->ForceMode(prefix,params);
1007 else if (command == "KILL")
1009 return this->RemoteKill(prefix,params);
1011 else if (command == "FTOPIC")
1013 return this->ForceTopic(prefix,params);
1015 else if (command == "REHASH")
1017 return this->RemoteRehash(prefix,params);
1019 else if (command == "SQUIT")
1021 if (params.size() == 2)
1023 this->Squit(FindServer(params[0]),params[1]);
1029 // not a special inter-server command.
1030 // Emulate the actual user doing the command,
1031 // this saves us having a huge ugly parser.
1032 userrec* who = Srv->FindNick(prefix);
1033 std::string sourceserv = this->myhost;
1034 if (this->InboundServerName != "")
1036 sourceserv = this->InboundServerName;
1041 target = who->server;
1042 char* strparams[127];
1043 for (unsigned int q = 0; q < params.size(); q++)
1045 strparams[q] = (char*)params[q].c_str();
1047 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1048 Srv->CallCommandHandler(command, strparams, params.size(), who);
1052 // its not a user. Its either a server, or somethings screwed up.
1053 if (IsServer(prefix))
1055 target = Srv->GetServerName();
1059 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1063 return DoOneToAllButSenderRaw(line,sourceserv);
1072 virtual std::string GetName()
1074 std::string sourceserv = this->myhost;
1075 if (this->InboundServerName != "")
1077 sourceserv = this->InboundServerName;
1082 virtual void OnTimeout()
1084 if (this->LinkState == CONNECTING)
1086 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1090 virtual void OnClose()
1092 // Connection closed.
1093 // If the connection is fully up (state CONNECTED)
1094 // then propogate a netsplit to all peers.
1095 std::string quitserver = this->myhost;
1096 if (this->InboundServerName != "")
1098 quitserver = this->InboundServerName;
1100 TreeServer* s = FindServer(quitserver);
1103 Squit(s,"Remote host closed the connection");
1107 virtual int OnIncomingConnection(int newsock, char* ip)
1109 TreeSocket* s = new TreeSocket(newsock, ip);
1115 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1117 TreeServer* omitroute = BestRouteTo(omit);
1118 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1120 TreeServer* Route = TreeRoot->GetChild(x);
1121 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1123 TreeSocket* Sock = Route->GetSocket();
1124 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1125 Sock->WriteLine(data);
1131 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1133 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1134 TreeServer* omitroute = BestRouteTo(omit);
1135 // TODO: Special stuff with privmsg and notice
1136 std::string FullLine = ":" + prefix + " " + command;
1137 for (unsigned int x = 0; x < params.size(); x++)
1139 FullLine = FullLine + " " + params[x];
1141 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1143 TreeServer* Route = TreeRoot->GetChild(x);
1144 // Send the line IF:
1145 // The route has a socket (its a direct connection)
1146 // The route isnt the one to be omitted
1147 // The route isnt the path to the one to be omitted
1148 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1150 TreeSocket* Sock = Route->GetSocket();
1151 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1152 Sock->WriteLine(FullLine);
1158 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1160 Srv->Log(DEBUG,"ONETOMANY: "+command);
1161 std::string FullLine = ":" + prefix + " " + command;
1162 for (unsigned int x = 0; x < params.size(); x++)
1164 FullLine = FullLine + " " + params[x];
1166 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1168 TreeServer* Route = TreeRoot->GetChild(x);
1169 if (Route->GetSocket())
1171 TreeSocket* Sock = Route->GetSocket();
1172 Sock->WriteLine(FullLine);
1178 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1180 TreeServer* Route = BestRouteTo(target);
1183 std::string FullLine = ":" + prefix + " " + command;
1184 for (unsigned int x = 0; x < params.size(); x++)
1186 FullLine = FullLine + " " + params[x];
1188 if (Route->GetSocket())
1190 TreeSocket* Sock = Route->GetSocket();
1191 Sock->WriteLine(FullLine);
1197 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1203 class ModuleSpanningTree : public Module
1205 std::vector<TreeSocket*> Bindings;
1210 void ReadConfiguration(bool rebind)
1214 for (int j =0; j < Conf->Enumerate("bind"); j++)
1216 std::string Type = Conf->ReadValue("bind","type",j);
1217 std::string IP = Conf->ReadValue("bind","address",j);
1218 long Port = Conf->ReadInteger("bind","port",j,true);
1219 if (Type == "servers")
1225 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1226 if (listener->GetState() == I_LISTENING)
1228 Srv->AddSocket(listener);
1229 Bindings.push_back(listener);
1233 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1241 for (int j =0; j < Conf->Enumerate("link"); j++)
1244 L.Name = Conf->ReadValue("link","name",j);
1245 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1246 L.Port = Conf->ReadInteger("link","port",j,true);
1247 L.SendPass = Conf->ReadValue("link","sendpass",j);
1248 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1249 LinkBlocks.push_back(L);
1250 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1254 ModuleSpanningTree()
1257 Conf = new ConfigReader;
1260 // Create the root of the tree
1261 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1263 ReadConfiguration(true);
1266 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1268 std::string Parent = TreeRoot->GetName();
1269 if (Current->GetParent())
1271 Parent = Current->GetParent()->GetName();
1273 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1275 ShowLinks(Current->GetChild(q),user,hops+1);
1277 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1280 void HandleLinks(char** parameters, int pcnt, userrec* user)
1282 ShowLinks(TreeRoot,user,0);
1283 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1287 void HandleLusers(char** parameters, int pcnt, userrec* user)
1292 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1294 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1298 for (int t = 0; t < depth; t++)
1300 matrix[line][t] = ' ';
1302 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1304 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1306 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1311 // Ok, prepare to be confused.
1312 // After much mulling over how to approach this, it struck me that
1313 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1314 // keeping track of a ton of ascii characters, and line by line
1315 // under recursion working out where to place them using multiplications
1316 // and divisons, we instead render the map onto a backplane of characters
1317 // (a character matrix), then draw the branches as a series of "L" shapes
1318 // from the nodes. This is not only friendlier on CPU it uses less stack.
1320 void HandleMap(char** parameters, int pcnt, userrec* user)
1322 // This array represents a virtual screen which we will
1323 // "scratch" draw to, as the console device of an irc
1324 // client does not provide for a proper terminal.
1325 char matrix[128][80];
1326 for (unsigned int t = 0; t < 128; t++)
1328 matrix[t][0] = '\0';
1331 // The only recursive bit is called here.
1332 ShowMap(TreeRoot,user,0,matrix);
1333 // Process each line one by one. The algorithm has a limit of
1334 // 128 servers (which is far more than a spanning tree should have
1335 // anyway, so we're ok). This limit can be raised simply by making
1336 // the character matrix deeper, 128 rows taking 10k of memory.
1337 for (int l = 1; l < line; l++)
1339 // scan across the line looking for the start of the
1340 // servername (the recursive part of the algorithm has placed
1341 // the servers at indented positions depending on what they
1343 int first_nonspace = 0;
1344 while (matrix[l][first_nonspace] == ' ')
1349 // Draw the `- (corner) section: this may be overwritten by
1350 // another L shape passing along the same vertical pane, becoming
1351 // a |- (branch) section instead.
1352 matrix[l][first_nonspace] = '-';
1353 matrix[l][first_nonspace-1] = '`';
1355 // Draw upwards until we hit the parent server, causing possibly
1356 // other corners (`-) to become branches (|-)
1357 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1359 matrix[l2][first_nonspace-1] = '|';
1363 // dump the whole lot to the user. This is the easy bit, honest.
1364 for (int t = 0; t < line; t++)
1366 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1368 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1372 int HandleSquit(char** parameters, int pcnt, userrec* user)
1377 int HandleConnect(char** parameters, int pcnt, userrec* user)
1379 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1381 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1383 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1384 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1385 Srv->AddSocket(newsocket);
1389 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1393 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1395 if (command == "CONNECT")
1397 return this->HandleConnect(parameters,pcnt,user);
1399 else if (command == "SQUIT")
1401 return this->HandleSquit(parameters,pcnt,user);
1403 else if (command == "MAP")
1405 this->HandleMap(parameters,pcnt,user);
1408 else if (command == "LUSERS")
1410 this->HandleLusers(parameters,pcnt,user);
1413 else if (command == "LINKS")
1415 this->HandleLinks(parameters,pcnt,user);
1421 virtual void OnGetServerDescription(std::string servername,std::string &description)
1423 TreeServer* s = FindServer(servername);
1426 description = s->GetDesc();
1430 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1432 if (std::string(source->server) == Srv->GetServerName())
1434 std::deque<std::string> params;
1435 params.push_back(dest->nick);
1436 params.push_back(channel->name);
1437 DoOneToMany(source->nick,"INVITE",params);
1441 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1443 std::deque<std::string> params;
1444 params.push_back(chan->name);
1445 params.push_back(":"+topic);
1446 DoOneToMany(user->nick,"TOPIC",params);
1449 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1451 if (target_type == TYPE_USER)
1453 userrec* d = (userrec*)dest;
1454 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1456 std::deque<std::string> params;
1458 params.push_back(d->nick);
1459 params.push_back(":"+text);
1460 DoOneToOne(user->nick,"NOTICE",params,d->server);
1465 if (std::string(user->server) == Srv->GetServerName())
1467 chanrec *c = (chanrec*)dest;
1468 std::deque<std::string> params;
1469 params.push_back(c->name);
1470 params.push_back(":"+text);
1471 DoOneToMany(user->nick,"NOTICE",params);
1476 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1478 if (target_type == TYPE_USER)
1480 // route private messages which are targetted at clients only to the server
1481 // which needs to receive them
1482 userrec* d = (userrec*)dest;
1483 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1485 std::deque<std::string> params;
1487 params.push_back(d->nick);
1488 params.push_back(":"+text);
1489 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1494 if (std::string(user->server) == Srv->GetServerName())
1496 chanrec *c = (chanrec*)dest;
1497 std::deque<std::string> params;
1498 params.push_back(c->name);
1499 params.push_back(":"+text);
1500 DoOneToMany(user->nick,"PRIVMSG",params);
1505 virtual void OnUserJoin(userrec* user, chanrec* channel)
1507 // Only do this for local users
1508 if (std::string(user->server) == Srv->GetServerName())
1510 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1511 std::deque<std::string> params;
1513 params.push_back(channel->name);
1516 log(DEBUG,"**** With key %s",channel->key);
1517 // if the channel has a key, force the join by emulating the key.
1518 params.push_back(channel->key);
1520 DoOneToMany(user->nick,"JOIN",params);
1524 virtual void OnUserPart(userrec* user, chanrec* channel)
1526 if (std::string(user->server) == Srv->GetServerName())
1528 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1529 std::deque<std::string> params;
1531 params.push_back(channel->name);
1532 DoOneToMany(user->nick,"PART",params);
1536 virtual void OnUserConnect(userrec* user)
1538 char agestr[MAXBUF];
1539 if (std::string(user->server) == Srv->GetServerName())
1541 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1542 std::deque<std::string> params;
1543 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1545 params.push_back(agestr);
1546 params.push_back(user->nick);
1547 params.push_back(user->host);
1548 params.push_back(user->dhost);
1549 params.push_back(user->ident);
1550 params.push_back("+"+std::string(user->modes));
1551 params.push_back(user->ip);
1552 params.push_back(":"+std::string(user->fullname));
1553 DoOneToMany(Srv->GetServerName(),"NICK",params);
1557 virtual void OnUserQuit(userrec* user, std::string reason)
1559 if (std::string(user->server) == Srv->GetServerName())
1561 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1562 std::deque<std::string> params;
1563 params.push_back(":"+reason);
1564 DoOneToMany(user->nick,"QUIT",params);
1568 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1570 if (std::string(user->server) == Srv->GetServerName())
1572 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1573 std::deque<std::string> params;
1574 params.push_back(user->nick);
1575 DoOneToMany(oldnick,"NICK",params);
1579 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1581 if (std::string(source->server) == Srv->GetServerName())
1583 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1584 std::deque<std::string> params;
1585 params.push_back(chan->name);
1586 params.push_back(user->nick);
1587 params.push_back(":"+reason);
1588 DoOneToMany(source->nick,"KICK",params);
1592 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1594 std::deque<std::string> params;
1595 params.push_back(dest->nick);
1596 params.push_back(":"+reason);
1597 DoOneToMany(source->nick,"KILL",params);
1600 virtual void OnRehash(std::string parameter)
1602 if (parameter != "")
1604 std::deque<std::string> params;
1605 params.push_back(parameter);
1606 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1608 if (Srv->MatchText(Srv->GetServerName(),parameter))
1610 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1611 Srv->RehashServer();
1614 this->ReadConfiguration(false);
1617 // note: the protocol does not allow direct umode +o except
1618 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1620 virtual void OnOper(userrec* user, std::string opertype)
1622 if (std::string(user->server) == Srv->GetServerName())
1624 std::deque<std::string> params;
1625 params.push_back(opertype);
1626 DoOneToMany(user->nick,"OPERTYPE",params);
1630 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1632 log(DEBUG,"*** ONMODE TRIGGER");
1633 if (std::string(user->server) == Srv->GetServerName())
1635 log(DEBUG,"*** LOCAL");
1636 if (target_type == TYPE_USER)
1638 userrec* u = (userrec*)dest;
1639 std::deque<std::string> params;
1640 params.push_back(u->nick);
1641 params.push_back(text);
1642 DoOneToMany(user->nick,"MODE",params);
1646 chanrec* c = (chanrec*)dest;
1647 std::deque<std::string> params;
1648 params.push_back(c->name);
1649 params.push_back(text);
1650 DoOneToMany(user->nick,"MODE",params);
1655 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1657 TreeSocket* s = (TreeSocket*)opaque;
1660 if (target_type == TYPE_USER)
1662 userrec* u = (userrec*)target;
1663 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1667 chanrec* c = (chanrec*)target;
1668 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1673 virtual ~ModuleSpanningTree()
1678 virtual Version GetVersion()
1680 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1685 class ModuleSpanningTreeFactory : public ModuleFactory
1688 ModuleSpanningTreeFactory()
1692 ~ModuleSpanningTreeFactory()
1696 virtual Module * CreateModule()
1698 TreeProtocolModule = new ModuleSpanningTree;
1699 return TreeProtocolModule;
1705 extern "C" void * init_module( void )
1707 return new ModuleSpanningTreeFactory;