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);
67 void ReadConfiguration(bool rebind);
72 std::vector<TreeServer*> Children;
73 std::string ServerName;
74 std::string ServerDesc;
75 std::string VersionString;
78 TreeSocket* Socket; // for directly connected servers this points at the socket object
88 UserCount = OperCount = 0;
91 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
95 UserCount = OperCount = 0;
98 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
101 UserCount = OperCount = 0;
104 std::string GetName()
106 return this->ServerName;
109 std::string GetDesc()
111 return this->ServerDesc;
114 std::string GetVersion()
116 return this->VersionString;
121 return this->UserCount;
126 return this->OperCount;
129 TreeSocket* GetSocket()
134 TreeServer* GetParent()
139 unsigned int ChildCount()
141 return Children.size();
144 TreeServer* GetChild(unsigned int n)
146 if (n < Children.size())
156 void AddChild(TreeServer* Child)
158 Children.push_back(Child);
161 bool DelChild(TreeServer* Child)
163 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
174 // removes child nodes of this node, and of that node, etc etc
177 bool stillchildren = true;
178 while (stillchildren)
180 stillchildren = false;
181 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
183 TreeServer* s = (TreeServer*)*a;
187 stillchildren = true;
201 std::string SendPass;
202 std::string RecvPass;
205 /* $ModDesc: Povides a spanning tree server link protocol */
209 TreeServer *TreeRoot;
210 std::vector<Link> LinkBlocks;
212 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
214 if (Current->GetName() == ServerName)
216 for (unsigned int q = 0; q < Current->ChildCount(); q++)
218 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
227 // Returns the locally connected server we must route a
228 // message through to reach server 'ServerName'. This
229 // only applies to one-to-one and not one-to-many routing.
230 TreeServer* BestRouteTo(std::string ServerName)
232 log(DEBUG,"Finding best route to %s",ServerName.c_str());
233 if (ServerName.c_str() == TreeRoot->GetName())
235 log(DEBUG,"Cant route to myself!!!");
238 // first, find the server by recursively walking the tree
239 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
240 // did we find it? If not, they did something wrong, abort.
243 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
248 // The server exists, follow its parent nodes until
249 // the parent of the current is 'TreeRoot', we know
250 // then that this is a directly-connected server.
251 while ((Found) && (Found->GetParent() != TreeRoot))
253 Found = Found->GetParent();
255 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
260 bool LookForServer(TreeServer* Current, std::string ServerName)
262 if (ServerName == Current->GetName())
264 for (unsigned int q = 0; q < Current->ChildCount(); q++)
266 if (LookForServer(Current->GetChild(q),ServerName))
274 void RFindServer(TreeServer* Current, std::string ServerName)
276 if ((ServerName == Current->GetName()) && (!Found))
279 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
284 for (unsigned int q = 0; q < Current->ChildCount(); q++)
287 RFindServer(Current->GetChild(q),ServerName);
293 TreeServer* FindServer(std::string ServerName)
296 RFindServer(TreeRoot,ServerName);
300 bool IsServer(std::string ServerName)
302 return LookForServer(TreeRoot,ServerName);
305 class TreeSocket : public InspSocket
308 std::string in_buffer;
309 ServerState LinkState;
310 std::string InboundServerName;
311 std::string InboundDescription;
313 int num_lost_servers;
317 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
318 : InspSocket(host, port, listening, maxtime)
320 Srv->Log(DEBUG,"Create new listening");
322 this->LinkState = LISTENER;
325 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
326 : InspSocket(host, port, listening, maxtime)
328 Srv->Log(DEBUG,"Create new outbound");
330 this->LinkState = CONNECTING;
333 TreeSocket(int newfd, char* ip)
334 : InspSocket(newfd, ip)
336 Srv->Log(DEBUG,"Associate new inbound");
337 this->LinkState = WAIT_AUTH_1;
340 virtual bool OnConnected()
342 if (this->LinkState == CONNECTING)
344 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
345 // we should send our details here.
346 // if the other side is satisfied, they send theirs.
347 // we do not need to change state here.
348 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
350 if (x->Name == this->myhost)
352 // found who we're supposed to be connecting to, send the neccessary gubbins.
353 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
358 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
362 virtual void OnError(InspSocketError e)
366 virtual int OnDisconnect()
371 // recursively send the server tree with distances as hops
372 void SendServers(TreeServer* Current, TreeServer* s, int hops)
375 for (unsigned int q = 0; q < Current->ChildCount(); q++)
377 TreeServer* recursive_server = Current->GetChild(q);
378 if (recursive_server != s)
380 // :source.server SERVER server.name hops :Description
381 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
382 this->WriteLine(command);
383 // down to next level
384 this->SendServers(recursive_server, s, hops+1);
389 void SquitServer(TreeServer* Current)
391 // recursively squit the servers attached to 'Current'
392 for (unsigned int q = 0; q < Current->ChildCount(); q++)
394 TreeServer* recursive_server = Current->GetChild(q);
395 this->SquitServer(recursive_server);
397 // Now we've whacked the kids, whack self
398 log(DEBUG,"Deleted %s",Current->GetName().c_str());
400 bool quittingpeople = true;
401 while (quittingpeople)
403 quittingpeople = false;
404 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
406 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
408 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
409 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
411 quittingpeople = true;
418 void Squit(TreeServer* Current,std::string reason)
422 std::deque<std::string> params;
423 params.push_back(Current->GetName());
424 params.push_back(":"+reason);
425 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
426 if (Current->GetParent() == TreeRoot)
428 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
432 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
434 num_lost_servers = 0;
436 SquitServer(Current);
438 Current->GetParent()->DelChild(Current);
440 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
444 log(DEBUG,"Squit from unknown server");
448 bool ForceMode(std::string source, std::deque<std::string> params)
450 userrec* who = new userrec;
451 who->fd = FD_MAGIC_NUMBER;
452 if (params.size() < 2)
455 for (unsigned int q = 0; q < params.size(); q++)
457 modelist[q] = (char*)params[q].c_str();
459 Srv->SendMode(modelist,params.size(),who);
460 DoOneToAllButSender(source,"FMODE",params,source);
465 bool ForceTopic(std::string source, std::deque<std::string> params)
467 // FTOPIC %s %lu %s :%s
468 if (params.size() != 4)
470 std::string channel = params[0];
471 time_t ts = atoi(params[1].c_str());
472 std::string setby = params[2];
473 std::string topic = params[3];
475 chanrec* c = Srv->FindChannel(channel);
478 if ((ts >= c->topicset) || (!*c->topic))
480 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
481 strlcpy(c->setby,setby.c_str(),NICKMAX);
483 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
488 // all done, send it on its way
489 params[3] = ":" + params[3];
490 DoOneToAllButSender(source,"FTOPIC",params,source);
495 bool ForceJoin(std::string source, std::deque<std::string> params)
497 if (params.size() < 1)
499 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
501 // process one channel at a time, applying modes.
502 char* channel = (char*)params[channelnum].c_str();
503 char permissions = *channel;
520 userrec* who = Srv->FindNick(source);
524 chanrec* chan = Srv->FindChannel(channel);
525 if ((chan) && (*chan->key))
529 Srv->JoinUserToChannel(who,channel,key);
533 modelist[0] = channel;
535 modelist[2] = who->nick;
536 Srv->SendMode(modelist,3,who);
538 DoOneToAllButSender(source,"FJOIN",params,who->server);
544 bool IntroduceClient(std::string source, std::deque<std::string> params)
546 if (params.size() < 8)
548 // NICK age nick host dhost ident +modes ip :gecos
550 std::string nick = params[1];
551 std::string host = params[2];
552 std::string dhost = params[3];
553 std::string ident = params[4];
554 time_t age = atoi(params[0].c_str());
555 std::string modes = params[5];
556 if (*(modes.c_str()) == '+')
558 char* m = (char*)modes.c_str();
562 std::string ip = params[6];
563 std::string gecos = params[7];
564 char* tempnick = (char*)nick.c_str();
565 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
567 user_hash::iterator iter;
568 iter = clientlist.find(tempnick);
569 if (iter != clientlist.end())
572 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);
573 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
577 clientlist[tempnick] = new userrec();
578 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
579 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
580 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
581 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
582 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
583 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
584 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
585 clientlist[tempnick]->registered = 7;
586 clientlist[tempnick]->signon = age;
587 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
588 for (int i = 0; i < MAXCHANS; i++)
590 clientlist[tempnick]->chans[i].channel = NULL;
591 clientlist[tempnick]->chans[i].uc_modes = 0;
593 params[7] = ":" + params[7];
594 DoOneToAllButSender(source,"NICK",params,source);
598 void SendChannelModes(TreeServer* Current)
601 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
603 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
604 this->WriteLine(data);
605 if (*c->second->topic)
607 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);
608 this->WriteLine(data);
610 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
612 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
613 this->WriteLine(data);
615 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
619 // send all users and their channels
620 void SendUsers(TreeServer* Current)
623 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
625 if (u->second->registered == 7)
627 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);
628 this->WriteLine(data);
629 if (strchr(u->second->modes,'o'))
631 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
633 char* chl = chlist(u->second,u->second);
636 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
638 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
643 void DoBurst(TreeServer* s)
645 log(DEBUG,"Beginning network burst");
646 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
647 this->WriteLine("BURST");
649 this->SendServers(TreeRoot,s,1);
650 // Send users and their channels
652 // TODO: Send everything else (channel modes etc)
653 this->SendChannelModes(s);
654 this->WriteLine("ENDBURST");
657 virtual bool OnDataReady()
659 char* data = this->Read();
662 this->in_buffer += data;
663 while (in_buffer.find("\n") != std::string::npos)
665 char* line = (char*)in_buffer.c_str();
666 std::string ret = "";
667 while ((*line != '\n') && (strlen(line)))
672 if ((*line == '\n') || (*line == '\r'))
675 if (!this->ProcessLine(ret))
681 return (data != NULL);
684 int WriteLine(std::string line)
686 return this->Write(line + "\r\n");
689 bool Error(std::deque<std::string> params)
691 if (params.size() < 1)
693 std::string Errmsg = params[0];
694 std::string SName = myhost;
695 if (InboundServerName != "")
697 SName = InboundServerName;
699 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
700 // we will return false to cause the socket to close.
704 bool OperType(std::string prefix, std::deque<std::string> params)
706 if (params.size() != 1)
708 std::string opertype = params[0];
709 userrec* u = Srv->FindNick(prefix);
712 strlcpy(u->oper,opertype.c_str(),NICKMAX);
713 if (!strchr(u->modes,'o'))
715 strcat(u->modes,"o");
717 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
722 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
724 if (params.size() < 1)
726 std::string servermask = params[0];
727 if (Srv->MatchText(Srv->GetServerName(),servermask))
729 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
731 ReadConfiguration(false);
733 DoOneToAllButSender(prefix,"REHASH",params,prefix);
737 bool RemoteKill(std::string prefix, std::deque<std::string> params)
739 if (params.size() != 2)
741 std::string nick = params[0];
742 std::string reason = params[1];
743 userrec* u = Srv->FindNick(prefix);
744 userrec* who = Srv->FindNick(nick);
747 std::string sourceserv = prefix;
750 sourceserv = u->server;
752 params[1] = ":" + params[1];
753 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
754 Srv->QuitUser(who,reason);
759 bool RemoteServer(std::string prefix, std::deque<std::string> params)
761 if (params.size() < 4)
763 std::string servername = params[0];
764 std::string password = params[1];
765 // hopcount is not used for a remote server, we calculate this ourselves
766 std::string description = params[3];
767 TreeServer* ParentOfThis = FindServer(prefix);
770 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
773 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
774 ParentOfThis->AddChild(Node);
775 params[3] = ":" + params[3];
776 DoOneToAllButSender(prefix,"SERVER",params,prefix);
777 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
781 bool Outbound_Reply_Server(std::deque<std::string> params)
783 if (params.size() < 4)
785 std::string servername = params[0];
786 std::string password = params[1];
787 int hops = atoi(params[2].c_str());
790 this->WriteLine("ERROR :Server too far away for authentication");
793 std::string description = params[3];
794 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
796 if ((x->Name == servername) && (x->RecvPass == password))
798 // Begin the sync here. this kickstarts the
799 // other side, waiting in WAIT_AUTH_2 state,
800 // into starting their burst, as it shows
802 this->LinkState = CONNECTED;
803 // we should add the details of this server now
804 // to the servers tree, as a child of the root
806 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
807 TreeRoot->AddChild(Node);
808 params[3] = ":" + params[3];
809 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
814 this->WriteLine("ERROR :Invalid credentials");
818 bool Inbound_Server(std::deque<std::string> params)
820 if (params.size() < 4)
822 std::string servername = params[0];
823 std::string password = params[1];
824 int hops = atoi(params[2].c_str());
827 this->WriteLine("ERROR :Server too far away for authentication");
830 std::string description = params[3];
831 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
833 if ((x->Name == servername) && (x->RecvPass == password))
835 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
836 this->InboundServerName = servername;
837 this->InboundDescription = description;
838 // this is good. Send our details: Our server name and description and hopcount of 0,
839 // along with the sendpass from this block.
840 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
841 // move to the next state, we are now waiting for THEM.
842 this->LinkState = WAIT_AUTH_2;
846 this->WriteLine("ERROR :Invalid credentials");
850 std::deque<std::string> Split(std::string line, bool stripcolon)
852 std::deque<std::string> n;
853 std::stringstream s(line);
854 std::string param = "";
860 //if ((param != "") && (param != "\n"))
862 if ((param.c_str()[0] == ':') && (item))
864 char* str = (char*)param.c_str();
874 param = param + " " + append;
885 bool ProcessLine(std::string line)
887 char* l = (char*)line.c_str();
888 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
889 l[strlen(l)-1] = '\0';
893 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
894 std::deque<std::string> params = this->Split(line,true);
895 std::string command = "";
896 std::string prefix = "";
897 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
901 char* pref = (char*)prefix.c_str();
913 switch (this->LinkState)
918 // Waiting for SERVER command from remote server. Server initiating
919 // the connection sends the first SERVER command, listening server
920 // replies with theirs if its happy, then if the initiator is happy,
921 // it starts to send its net sync, which starts the merge, otherwise
922 // it sends an ERROR.
923 if (command == "SERVER")
925 return this->Inbound_Server(params);
927 else if (command == "ERROR")
929 return this->Error(params);
933 // Waiting for start of other side's netmerge to say they liked our
935 if (command == "SERVER")
937 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
941 else if (command == "BURST")
943 this->LinkState = CONNECTED;
944 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
945 TreeRoot->AddChild(Node);
947 params.push_back(InboundServerName);
948 params.push_back("*");
949 params.push_back("1");
950 params.push_back(":"+InboundDescription);
951 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
954 else if (command == "ERROR")
956 return this->Error(params);
961 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
965 if (command == "SERVER")
967 // another server we connected to, which was in WAIT_AUTH_1 state,
968 // has just sent us their credentials. If we get this far, theyre
969 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
970 // if we're happy with this, we should send our netburst which
971 // kickstarts the merge.
972 return this->Outbound_Reply_Server(params);
974 else if (command == "ERROR")
976 return this->Error(params);
980 // This is the 'authenticated' state, when all passwords
981 // have been exchanged and anything past this point is taken
983 std::string target = "";
984 if ((command == "NICK") && (params.size() > 1))
986 return this->IntroduceClient(prefix,params);
988 else if (command == "FJOIN")
990 return this->ForceJoin(prefix,params);
992 else if (command == "SERVER")
994 return this->RemoteServer(prefix,params);
996 else if (command == "ERROR")
998 return this->Error(params);
1000 else if (command == "OPERTYPE")
1002 return this->OperType(prefix,params);
1004 else if (command == "FMODE")
1006 return this->ForceMode(prefix,params);
1008 else if (command == "KILL")
1010 return this->RemoteKill(prefix,params);
1012 else if (command == "FTOPIC")
1014 return this->ForceTopic(prefix,params);
1016 else if (command == "REHASH")
1018 return this->RemoteRehash(prefix,params);
1020 else if (command == "SQUIT")
1022 if (params.size() == 2)
1024 this->Squit(FindServer(params[0]),params[1]);
1030 // not a special inter-server command.
1031 // Emulate the actual user doing the command,
1032 // this saves us having a huge ugly parser.
1033 userrec* who = Srv->FindNick(prefix);
1034 std::string sourceserv = this->myhost;
1035 if (this->InboundServerName != "")
1037 sourceserv = this->InboundServerName;
1042 target = who->server;
1043 char* strparams[127];
1044 for (unsigned int q = 0; q < params.size(); q++)
1046 strparams[q] = (char*)params[q].c_str();
1048 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1049 Srv->CallCommandHandler(command, strparams, params.size(), who);
1053 // its not a user. Its either a server, or somethings screwed up.
1054 if (IsServer(prefix))
1056 target = Srv->GetServerName();
1060 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1064 return DoOneToAllButSenderRaw(line,sourceserv);
1073 virtual std::string GetName()
1075 std::string sourceserv = this->myhost;
1076 if (this->InboundServerName != "")
1078 sourceserv = this->InboundServerName;
1083 virtual void OnTimeout()
1085 if (this->LinkState == CONNECTING)
1087 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1091 virtual void OnClose()
1093 // Connection closed.
1094 // If the connection is fully up (state CONNECTED)
1095 // then propogate a netsplit to all peers.
1096 std::string quitserver = this->myhost;
1097 if (this->InboundServerName != "")
1099 quitserver = this->InboundServerName;
1101 TreeServer* s = FindServer(quitserver);
1104 Squit(s,"Remote host closed the connection");
1108 virtual int OnIncomingConnection(int newsock, char* ip)
1110 TreeSocket* s = new TreeSocket(newsock, ip);
1116 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1118 TreeServer* omitroute = BestRouteTo(omit);
1119 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1121 TreeServer* Route = TreeRoot->GetChild(x);
1122 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1124 TreeSocket* Sock = Route->GetSocket();
1125 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1126 Sock->WriteLine(data);
1132 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1134 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1135 TreeServer* omitroute = BestRouteTo(omit);
1136 // TODO: Special stuff with privmsg and notice
1137 std::string FullLine = ":" + prefix + " " + command;
1138 for (unsigned int x = 0; x < params.size(); x++)
1140 FullLine = FullLine + " " + params[x];
1142 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1144 TreeServer* Route = TreeRoot->GetChild(x);
1145 // Send the line IF:
1146 // The route has a socket (its a direct connection)
1147 // The route isnt the one to be omitted
1148 // The route isnt the path to the one to be omitted
1149 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1151 TreeSocket* Sock = Route->GetSocket();
1152 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1153 Sock->WriteLine(FullLine);
1159 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1161 Srv->Log(DEBUG,"ONETOMANY: "+command);
1162 std::string FullLine = ":" + prefix + " " + command;
1163 for (unsigned int x = 0; x < params.size(); x++)
1165 FullLine = FullLine + " " + params[x];
1167 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1169 TreeServer* Route = TreeRoot->GetChild(x);
1170 if (Route->GetSocket())
1172 TreeSocket* Sock = Route->GetSocket();
1173 Sock->WriteLine(FullLine);
1179 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1181 TreeServer* Route = BestRouteTo(target);
1184 std::string FullLine = ":" + prefix + " " + command;
1185 for (unsigned int x = 0; x < params.size(); x++)
1187 FullLine = FullLine + " " + params[x];
1189 if (Route->GetSocket())
1191 TreeSocket* Sock = Route->GetSocket();
1192 Sock->WriteLine(FullLine);
1198 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1203 std::vector<TreeSocket*> Bindings;
1205 void ReadConfiguration(bool rebind)
1209 for (int j =0; j < Conf->Enumerate("bind"); j++)
1211 std::string Type = Conf->ReadValue("bind","type",j);
1212 std::string IP = Conf->ReadValue("bind","address",j);
1213 long Port = Conf->ReadInteger("bind","port",j,true);
1214 if (Type == "servers")
1220 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1221 if (listener->GetState() == I_LISTENING)
1223 Srv->AddSocket(listener);
1224 Bindings.push_back(listener);
1228 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1236 for (int j =0; j < Conf->Enumerate("link"); j++)
1239 L.Name = Conf->ReadValue("link","name",j);
1240 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1241 L.Port = Conf->ReadInteger("link","port",j,true);
1242 L.SendPass = Conf->ReadValue("link","sendpass",j);
1243 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1244 LinkBlocks.push_back(L);
1245 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1250 class ModuleSpanningTree : public Module
1252 std::vector<TreeSocket*> Bindings;
1257 ModuleSpanningTree()
1260 Conf = new ConfigReader;
1263 // Create the root of the tree
1264 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1266 ReadConfiguration(true);
1269 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1271 std::string Parent = TreeRoot->GetName();
1272 if (Current->GetParent())
1274 Parent = Current->GetParent()->GetName();
1276 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1278 ShowLinks(Current->GetChild(q),user,hops+1);
1280 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1283 void HandleLinks(char** parameters, int pcnt, userrec* user)
1285 ShowLinks(TreeRoot,user,0);
1286 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1290 void HandleLusers(char** parameters, int pcnt, userrec* user)
1295 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1297 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1301 for (int t = 0; t < depth; t++)
1303 matrix[line][t] = ' ';
1305 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1307 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1309 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1314 // Ok, prepare to be confused.
1315 // After much mulling over how to approach this, it struck me that
1316 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1317 // keeping track of a ton of ascii characters, and line by line
1318 // under recursion working out where to place them using multiplications
1319 // and divisons, we instead render the map onto a backplane of characters
1320 // (a character matrix), then draw the branches as a series of "L" shapes
1321 // from the nodes. This is not only friendlier on CPU it uses less stack.
1323 void HandleMap(char** parameters, int pcnt, userrec* user)
1325 // This array represents a virtual screen which we will
1326 // "scratch" draw to, as the console device of an irc
1327 // client does not provide for a proper terminal.
1328 char matrix[128][80];
1329 for (unsigned int t = 0; t < 128; t++)
1331 matrix[t][0] = '\0';
1334 // The only recursive bit is called here.
1335 ShowMap(TreeRoot,user,0,matrix);
1336 // Process each line one by one. The algorithm has a limit of
1337 // 128 servers (which is far more than a spanning tree should have
1338 // anyway, so we're ok). This limit can be raised simply by making
1339 // the character matrix deeper, 128 rows taking 10k of memory.
1340 for (int l = 1; l < line; l++)
1342 // scan across the line looking for the start of the
1343 // servername (the recursive part of the algorithm has placed
1344 // the servers at indented positions depending on what they
1346 int first_nonspace = 0;
1347 while (matrix[l][first_nonspace] == ' ')
1352 // Draw the `- (corner) section: this may be overwritten by
1353 // another L shape passing along the same vertical pane, becoming
1354 // a |- (branch) section instead.
1355 matrix[l][first_nonspace] = '-';
1356 matrix[l][first_nonspace-1] = '`';
1358 // Draw upwards until we hit the parent server, causing possibly
1359 // other corners (`-) to become branches (|-)
1360 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1362 matrix[l2][first_nonspace-1] = '|';
1366 // dump the whole lot to the user. This is the easy bit, honest.
1367 for (int t = 0; t < line; t++)
1369 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1371 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1375 int HandleSquit(char** parameters, int pcnt, userrec* user)
1380 int HandleConnect(char** parameters, int pcnt, userrec* user)
1382 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1384 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1386 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1387 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1388 Srv->AddSocket(newsocket);
1392 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1396 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1398 if (command == "CONNECT")
1400 return this->HandleConnect(parameters,pcnt,user);
1402 else if (command == "SQUIT")
1404 return this->HandleSquit(parameters,pcnt,user);
1406 else if (command == "MAP")
1408 this->HandleMap(parameters,pcnt,user);
1411 else if (command == "LUSERS")
1413 this->HandleLusers(parameters,pcnt,user);
1416 else if (command == "LINKS")
1418 this->HandleLinks(parameters,pcnt,user);
1421 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1423 // this bit of code cleverly routes all module commands
1424 // to all remote severs *automatically* so that modules
1425 // can just handle commands locally, without having
1426 // to have any special provision in place for remote
1427 // commands and linking protocols.
1428 std::deque<std::string> params;
1430 for (int j = 0; j < pcnt; j++)
1432 if (strchr(parameters[j],' '))
1434 params.push_back(":" + std::string(parameters[j]));
1438 params.push_back(std::string(parameters[j]));
1441 DoOneToMany(user->nick,command,params);
1446 virtual void OnGetServerDescription(std::string servername,std::string &description)
1448 TreeServer* s = FindServer(servername);
1451 description = s->GetDesc();
1455 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1457 if (std::string(source->server) == Srv->GetServerName())
1459 std::deque<std::string> params;
1460 params.push_back(dest->nick);
1461 params.push_back(channel->name);
1462 DoOneToMany(source->nick,"INVITE",params);
1466 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1468 std::deque<std::string> params;
1469 params.push_back(chan->name);
1470 params.push_back(":"+topic);
1471 DoOneToMany(user->nick,"TOPIC",params);
1474 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1476 if (target_type == TYPE_USER)
1478 userrec* d = (userrec*)dest;
1479 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1481 std::deque<std::string> params;
1483 params.push_back(d->nick);
1484 params.push_back(":"+text);
1485 DoOneToOne(user->nick,"NOTICE",params,d->server);
1490 if (std::string(user->server) == Srv->GetServerName())
1492 chanrec *c = (chanrec*)dest;
1493 std::deque<std::string> params;
1494 params.push_back(c->name);
1495 params.push_back(":"+text);
1496 DoOneToMany(user->nick,"NOTICE",params);
1501 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1503 if (target_type == TYPE_USER)
1505 // route private messages which are targetted at clients only to the server
1506 // which needs to receive them
1507 userrec* d = (userrec*)dest;
1508 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1510 std::deque<std::string> params;
1512 params.push_back(d->nick);
1513 params.push_back(":"+text);
1514 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1519 if (std::string(user->server) == Srv->GetServerName())
1521 chanrec *c = (chanrec*)dest;
1522 std::deque<std::string> params;
1523 params.push_back(c->name);
1524 params.push_back(":"+text);
1525 DoOneToMany(user->nick,"PRIVMSG",params);
1530 virtual void OnUserJoin(userrec* user, chanrec* channel)
1532 // Only do this for local users
1533 if (std::string(user->server) == Srv->GetServerName())
1535 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1536 std::deque<std::string> params;
1538 params.push_back(channel->name);
1541 log(DEBUG,"**** With key %s",channel->key);
1542 // if the channel has a key, force the join by emulating the key.
1543 params.push_back(channel->key);
1545 DoOneToMany(user->nick,"JOIN",params);
1549 virtual void OnUserPart(userrec* user, chanrec* channel)
1551 if (std::string(user->server) == Srv->GetServerName())
1553 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1554 std::deque<std::string> params;
1556 params.push_back(channel->name);
1557 DoOneToMany(user->nick,"PART",params);
1561 virtual void OnUserConnect(userrec* user)
1563 char agestr[MAXBUF];
1564 if (std::string(user->server) == Srv->GetServerName())
1566 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1567 std::deque<std::string> params;
1568 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1570 params.push_back(agestr);
1571 params.push_back(user->nick);
1572 params.push_back(user->host);
1573 params.push_back(user->dhost);
1574 params.push_back(user->ident);
1575 params.push_back("+"+std::string(user->modes));
1576 params.push_back(user->ip);
1577 params.push_back(":"+std::string(user->fullname));
1578 DoOneToMany(Srv->GetServerName(),"NICK",params);
1582 virtual void OnUserQuit(userrec* user, std::string reason)
1584 if (std::string(user->server) == Srv->GetServerName())
1586 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1587 std::deque<std::string> params;
1588 params.push_back(":"+reason);
1589 DoOneToMany(user->nick,"QUIT",params);
1593 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1595 if (std::string(user->server) == Srv->GetServerName())
1597 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1598 std::deque<std::string> params;
1599 params.push_back(user->nick);
1600 DoOneToMany(oldnick,"NICK",params);
1604 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1606 if (std::string(source->server) == Srv->GetServerName())
1608 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1609 std::deque<std::string> params;
1610 params.push_back(chan->name);
1611 params.push_back(user->nick);
1612 params.push_back(":"+reason);
1613 DoOneToMany(source->nick,"KICK",params);
1617 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1619 std::deque<std::string> params;
1620 params.push_back(dest->nick);
1621 params.push_back(":"+reason);
1622 DoOneToMany(source->nick,"KILL",params);
1625 virtual void OnRehash(std::string parameter)
1627 if (parameter != "")
1629 std::deque<std::string> params;
1630 params.push_back(parameter);
1631 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1633 if (Srv->MatchText(Srv->GetServerName(),parameter))
1635 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1636 Srv->RehashServer();
1639 ReadConfiguration(false);
1642 // note: the protocol does not allow direct umode +o except
1643 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1645 virtual void OnOper(userrec* user, std::string opertype)
1647 if (std::string(user->server) == Srv->GetServerName())
1649 std::deque<std::string> params;
1650 params.push_back(opertype);
1651 DoOneToMany(user->nick,"OPERTYPE",params);
1655 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1657 log(DEBUG,"*** ONMODE TRIGGER");
1658 if (std::string(user->server) == Srv->GetServerName())
1660 log(DEBUG,"*** LOCAL");
1661 if (target_type == TYPE_USER)
1663 userrec* u = (userrec*)dest;
1664 std::deque<std::string> params;
1665 params.push_back(u->nick);
1666 params.push_back(text);
1667 DoOneToMany(user->nick,"MODE",params);
1671 chanrec* c = (chanrec*)dest;
1672 std::deque<std::string> params;
1673 params.push_back(c->name);
1674 params.push_back(text);
1675 DoOneToMany(user->nick,"MODE",params);
1680 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1682 TreeSocket* s = (TreeSocket*)opaque;
1685 if (target_type == TYPE_USER)
1687 userrec* u = (userrec*)target;
1688 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1692 chanrec* c = (chanrec*)target;
1693 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1698 virtual ~ModuleSpanningTree()
1703 virtual Version GetVersion()
1705 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1710 class ModuleSpanningTreeFactory : public ModuleFactory
1713 ModuleSpanningTreeFactory()
1717 ~ModuleSpanningTreeFactory()
1721 virtual Module * CreateModule()
1723 TreeProtocolModule = new ModuleSpanningTree;
1724 return TreeProtocolModule;
1730 extern "C" void * init_module( void )
1732 return new ModuleSpanningTreeFactory;