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.");
731 DoOneToAllButSender(prefix,"REHASH",params,prefix);
735 bool RemoteKill(std::string prefix, std::deque<std::string> params)
737 if (params.size() != 2)
739 std::string nick = params[0];
740 std::string reason = params[1];
741 userrec* u = Srv->FindNick(prefix);
742 userrec* who = Srv->FindNick(nick);
745 std::string sourceserv = prefix;
748 sourceserv = u->server;
750 params[1] = ":" + params[1];
751 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
752 Srv->QuitUser(who,reason);
757 bool RemoteServer(std::string prefix, std::deque<std::string> params)
759 if (params.size() < 4)
761 std::string servername = params[0];
762 std::string password = params[1];
763 // hopcount is not used for a remote server, we calculate this ourselves
764 std::string description = params[3];
765 TreeServer* ParentOfThis = FindServer(prefix);
768 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
771 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
772 ParentOfThis->AddChild(Node);
773 params[3] = ":" + params[3];
774 DoOneToAllButSender(prefix,"SERVER",params,prefix);
775 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
779 bool Outbound_Reply_Server(std::deque<std::string> params)
781 if (params.size() < 4)
783 std::string servername = params[0];
784 std::string password = params[1];
785 int hops = atoi(params[2].c_str());
788 this->WriteLine("ERROR :Server too far away for authentication");
791 std::string description = params[3];
792 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
794 if ((x->Name == servername) && (x->RecvPass == password))
796 // Begin the sync here. this kickstarts the
797 // other side, waiting in WAIT_AUTH_2 state,
798 // into starting their burst, as it shows
800 this->LinkState = CONNECTED;
801 // we should add the details of this server now
802 // to the servers tree, as a child of the root
804 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
805 TreeRoot->AddChild(Node);
806 params[3] = ":" + params[3];
807 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
812 this->WriteLine("ERROR :Invalid credentials");
816 bool Inbound_Server(std::deque<std::string> params)
818 if (params.size() < 4)
820 std::string servername = params[0];
821 std::string password = params[1];
822 int hops = atoi(params[2].c_str());
825 this->WriteLine("ERROR :Server too far away for authentication");
828 std::string description = params[3];
829 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
831 if ((x->Name == servername) && (x->RecvPass == password))
833 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
834 this->InboundServerName = servername;
835 this->InboundDescription = description;
836 // this is good. Send our details: Our server name and description and hopcount of 0,
837 // along with the sendpass from this block.
838 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
839 // move to the next state, we are now waiting for THEM.
840 this->LinkState = WAIT_AUTH_2;
844 this->WriteLine("ERROR :Invalid credentials");
848 std::deque<std::string> Split(std::string line, bool stripcolon)
850 std::deque<std::string> n;
851 std::stringstream s(line);
852 std::string param = "";
858 if ((param != "") && (param != "\n"))
860 if ((param.c_str()[0] == ':') && (item))
862 char* str = (char*)param.c_str();
872 param = param + " " + append;
883 bool ProcessLine(std::string line)
885 char* l = (char*)line.c_str();
886 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
887 l[strlen(l)-1] = '\0';
891 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
892 std::deque<std::string> params = this->Split(line,true);
893 std::string command = "";
894 std::string prefix = "";
895 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
899 char* pref = (char*)prefix.c_str();
911 switch (this->LinkState)
916 // Waiting for SERVER command from remote server. Server initiating
917 // the connection sends the first SERVER command, listening server
918 // replies with theirs if its happy, then if the initiator is happy,
919 // it starts to send its net sync, which starts the merge, otherwise
920 // it sends an ERROR.
921 if (command == "SERVER")
923 return this->Inbound_Server(params);
925 else if (command == "ERROR")
927 return this->Error(params);
931 // Waiting for start of other side's netmerge to say they liked our
933 if (command == "SERVER")
935 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
939 else if (command == "BURST")
941 this->LinkState = CONNECTED;
942 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
943 TreeRoot->AddChild(Node);
945 params.push_back(InboundServerName);
946 params.push_back("*");
947 params.push_back("1");
948 params.push_back(":"+InboundDescription);
949 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
952 else if (command == "ERROR")
954 return this->Error(params);
959 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
963 if (command == "SERVER")
965 // another server we connected to, which was in WAIT_AUTH_1 state,
966 // has just sent us their credentials. If we get this far, theyre
967 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
968 // if we're happy with this, we should send our netburst which
969 // kickstarts the merge.
970 return this->Outbound_Reply_Server(params);
974 // This is the 'authenticated' state, when all passwords
975 // have been exchanged and anything past this point is taken
977 std::string target = "";
978 if ((command == "NICK") && (params.size() > 1))
980 return this->IntroduceClient(prefix,params);
982 else if (command == "FJOIN")
984 return this->ForceJoin(prefix,params);
986 else if (command == "SERVER")
988 return this->RemoteServer(prefix,params);
990 else if (command == "OPERTYPE")
992 return this->OperType(prefix,params);
994 else if (command == "FMODE")
996 return this->ForceMode(prefix,params);
998 else if (command == "KILL")
1000 return this->RemoteKill(prefix,params);
1002 else if (command == "FTOPIC")
1004 return this->ForceTopic(prefix,params);
1006 else if (command == "REHASH")
1008 return this->RemoteRehash(prefix,params);
1010 else if (command == "SQUIT")
1012 if (params.size() == 2)
1014 this->Squit(FindServer(params[0]),params[1]);
1020 // not a special inter-server command.
1021 // Emulate the actual user doing the command,
1022 // this saves us having a huge ugly parser.
1023 userrec* who = Srv->FindNick(prefix);
1024 std::string sourceserv = this->myhost;
1025 if (this->InboundServerName != "")
1027 sourceserv = this->InboundServerName;
1032 target = who->server;
1033 char* strparams[127];
1034 for (unsigned int q = 0; q < params.size(); q++)
1036 strparams[q] = (char*)params[q].c_str();
1038 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1039 Srv->CallCommandHandler(command, strparams, params.size(), who);
1043 // its not a user. Its either a server, or somethings screwed up.
1044 if (IsServer(prefix))
1046 target = Srv->GetServerName();
1050 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1054 return DoOneToAllButSenderRaw(line,sourceserv);
1063 virtual std::string GetName()
1065 std::string sourceserv = this->myhost;
1066 if (this->InboundServerName != "")
1068 sourceserv = this->InboundServerName;
1073 virtual void OnTimeout()
1075 if (this->LinkState == CONNECTING)
1077 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1081 virtual void OnClose()
1083 // Connection closed.
1084 // If the connection is fully up (state CONNECTED)
1085 // then propogate a netsplit to all peers.
1086 std::string quitserver = this->myhost;
1087 if (this->InboundServerName != "")
1089 quitserver = this->InboundServerName;
1091 TreeServer* s = FindServer(quitserver);
1094 Squit(s,"Remote host closed the connection");
1098 virtual int OnIncomingConnection(int newsock, char* ip)
1100 TreeSocket* s = new TreeSocket(newsock, ip);
1106 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1108 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1110 TreeServer* Route = TreeRoot->GetChild(x);
1111 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1113 TreeSocket* Sock = Route->GetSocket();
1114 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1115 Sock->WriteLine(data);
1121 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1123 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1124 // TODO: Special stuff with privmsg and notice
1125 std::string FullLine = ":" + prefix + " " + command;
1126 for (unsigned int x = 0; x < params.size(); x++)
1128 FullLine = FullLine + " " + params[x];
1130 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1132 TreeServer* Route = TreeRoot->GetChild(x);
1133 // Send the line IF:
1134 // The route has a socket (its a direct connection)
1135 // The route isnt the one to be omitted
1136 // The route isnt the path to the one to be omitted
1137 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1139 TreeSocket* Sock = Route->GetSocket();
1140 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1141 Sock->WriteLine(FullLine);
1147 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1149 Srv->Log(DEBUG,"ONETOMANY: "+command);
1150 std::string FullLine = ":" + prefix + " " + command;
1151 for (unsigned int x = 0; x < params.size(); x++)
1153 FullLine = FullLine + " " + params[x];
1155 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1157 TreeServer* Route = TreeRoot->GetChild(x);
1158 if (Route->GetSocket())
1160 TreeSocket* Sock = Route->GetSocket();
1161 Sock->WriteLine(FullLine);
1167 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1169 TreeServer* Route = BestRouteTo(target);
1172 std::string FullLine = ":" + prefix + " " + command;
1173 for (unsigned int x = 0; x < params.size(); x++)
1175 FullLine = FullLine + " " + params[x];
1177 if (Route->GetSocket())
1179 TreeSocket* Sock = Route->GetSocket();
1180 Sock->WriteLine(FullLine);
1186 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1192 class ModuleSpanningTree : public Module
1194 std::vector<TreeSocket*> Bindings;
1199 void ReadConfiguration(bool rebind)
1203 for (int j =0; j < Conf->Enumerate("bind"); j++)
1205 std::string Type = Conf->ReadValue("bind","type",j);
1206 std::string IP = Conf->ReadValue("bind","address",j);
1207 long Port = Conf->ReadInteger("bind","port",j,true);
1208 if (Type == "servers")
1214 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1215 if (listener->GetState() == I_LISTENING)
1217 Srv->AddSocket(listener);
1218 Bindings.push_back(listener);
1222 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1230 for (int j =0; j < Conf->Enumerate("link"); j++)
1233 L.Name = Conf->ReadValue("link","name",j);
1234 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1235 L.Port = Conf->ReadInteger("link","port",j,true);
1236 L.SendPass = Conf->ReadValue("link","sendpass",j);
1237 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1238 LinkBlocks.push_back(L);
1239 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1243 ModuleSpanningTree()
1246 Conf = new ConfigReader;
1249 // Create the root of the tree
1250 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1252 ReadConfiguration(true);
1255 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1257 std::string Parent = TreeRoot->GetName();
1258 if (Current->GetParent())
1260 Parent = Current->GetParent()->GetName();
1262 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1264 ShowLinks(Current->GetChild(q),user,hops+1);
1266 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1269 void HandleLinks(char** parameters, int pcnt, userrec* user)
1271 ShowLinks(TreeRoot,user,0);
1272 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1276 void HandleLusers(char** parameters, int pcnt, userrec* user)
1281 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1283 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1287 for (int t = 0; t < depth; t++)
1289 matrix[line][t] = ' ';
1291 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1293 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1295 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1300 // Ok, prepare to be confused.
1301 // After much mulling over how to approach this, it struck me that
1302 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1303 // keeping track of a ton of ascii characters, and line by line
1304 // under recursion working out where to place them using multiplications
1305 // and divisons, we instead render the map onto a backplane of characters
1306 // (a character matrix), then draw the branches as a series of "L" shapes
1307 // from the nodes. This is not only friendlier on CPU it uses less stack.
1309 void HandleMap(char** parameters, int pcnt, userrec* user)
1311 // This array represents a virtual screen which we will
1312 // "scratch" draw to, as the console device of an irc
1313 // client does not provide for a proper terminal.
1314 char matrix[128][80];
1315 for (unsigned int t = 0; t < 128; t++)
1317 matrix[t][0] = '\0';
1320 // The only recursive bit is called here.
1321 ShowMap(TreeRoot,user,0,matrix);
1322 // Process each line one by one. The algorithm has a limit of
1323 // 128 servers (which is far more than a spanning tree should have
1324 // anyway, so we're ok). This limit can be raised simply by making
1325 // the character matrix deeper, 128 rows taking 10k of memory.
1326 for (int l = 1; l < line; l++)
1328 // scan across the line looking for the start of the
1329 // servername (the recursive part of the algorithm has placed
1330 // the servers at indented positions depending on what they
1332 int first_nonspace = 0;
1333 while (matrix[l][first_nonspace] == ' ')
1338 // Draw the `- (corner) section: this may be overwritten by
1339 // another L shape passing along the same vertical pane, becoming
1340 // a |- (branch) section instead.
1341 matrix[l][first_nonspace] = '-';
1342 matrix[l][first_nonspace-1] = '`';
1344 // Draw upwards until we hit the parent server, causing possibly
1345 // other corners (`-) to become branches (|-)
1346 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1348 matrix[l2][first_nonspace-1] = '|';
1352 // dump the whole lot to the user. This is the easy bit, honest.
1353 for (int t = 0; t < line; t++)
1355 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1357 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1361 int HandleSquit(char** parameters, int pcnt, userrec* user)
1366 int HandleConnect(char** parameters, int pcnt, userrec* user)
1368 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1370 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1372 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1373 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1374 Srv->AddSocket(newsocket);
1378 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1382 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1384 if (command == "CONNECT")
1386 return this->HandleConnect(parameters,pcnt,user);
1388 else if (command == "SQUIT")
1390 return this->HandleSquit(parameters,pcnt,user);
1392 else if (command == "MAP")
1394 this->HandleMap(parameters,pcnt,user);
1397 else if (command == "LUSERS")
1399 this->HandleLusers(parameters,pcnt,user);
1402 else if (command == "LINKS")
1404 this->HandleLinks(parameters,pcnt,user);
1410 virtual void OnGetServerDescription(std::string servername,std::string &description)
1412 TreeServer* s = FindServer(servername);
1415 description = s->GetDesc();
1419 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1421 if (std::string(source->server) == Srv->GetServerName())
1423 std::deque<std::string> params;
1424 params.push_back(dest->nick);
1425 params.push_back(channel->name);
1426 DoOneToMany(source->nick,"INVITE",params);
1430 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1432 std::deque<std::string> params;
1433 params.push_back(chan->name);
1434 params.push_back(":"+topic);
1435 DoOneToMany(user->nick,"TOPIC",params);
1438 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1440 if (target_type == TYPE_USER)
1442 userrec* d = (userrec*)dest;
1443 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1445 std::deque<std::string> params;
1447 params.push_back(d->nick);
1448 params.push_back(":"+text);
1449 DoOneToOne(user->nick,"NOTICE",params,d->server);
1454 if (std::string(user->server) == Srv->GetServerName())
1456 chanrec *c = (chanrec*)dest;
1457 std::deque<std::string> params;
1458 params.push_back(c->name);
1459 params.push_back(":"+text);
1460 DoOneToMany(user->nick,"NOTICE",params);
1465 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1467 if (target_type == TYPE_USER)
1469 // route private messages which are targetted at clients only to the server
1470 // which needs to receive them
1471 userrec* d = (userrec*)dest;
1472 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1474 std::deque<std::string> params;
1476 params.push_back(d->nick);
1477 params.push_back(":"+text);
1478 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1483 if (std::string(user->server) == Srv->GetServerName())
1485 chanrec *c = (chanrec*)dest;
1486 std::deque<std::string> params;
1487 params.push_back(c->name);
1488 params.push_back(":"+text);
1489 DoOneToMany(user->nick,"PRIVMSG",params);
1494 virtual void OnUserJoin(userrec* user, chanrec* channel)
1496 // Only do this for local users
1497 if (std::string(user->server) == Srv->GetServerName())
1499 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1500 std::deque<std::string> params;
1502 params.push_back(channel->name);
1505 log(DEBUG,"**** With key %s",channel->key);
1506 // if the channel has a key, force the join by emulating the key.
1507 params.push_back(channel->key);
1509 DoOneToMany(user->nick,"JOIN",params);
1513 virtual void OnUserPart(userrec* user, chanrec* channel)
1515 if (std::string(user->server) == Srv->GetServerName())
1517 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1518 std::deque<std::string> params;
1520 params.push_back(channel->name);
1521 DoOneToMany(user->nick,"PART",params);
1525 virtual void OnUserConnect(userrec* user)
1527 char agestr[MAXBUF];
1528 if (std::string(user->server) == Srv->GetServerName())
1530 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1531 std::deque<std::string> params;
1532 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1534 params.push_back(agestr);
1535 params.push_back(user->nick);
1536 params.push_back(user->host);
1537 params.push_back(user->dhost);
1538 params.push_back(user->ident);
1539 params.push_back("+"+std::string(user->modes));
1540 params.push_back(user->ip);
1541 params.push_back(":"+std::string(user->fullname));
1542 DoOneToMany(Srv->GetServerName(),"NICK",params);
1546 virtual void OnUserQuit(userrec* user, std::string reason)
1548 if (std::string(user->server) == Srv->GetServerName())
1550 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1551 std::deque<std::string> params;
1552 params.push_back(":"+reason);
1553 DoOneToMany(user->nick,"QUIT",params);
1557 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1559 if (std::string(user->server) == Srv->GetServerName())
1561 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1562 std::deque<std::string> params;
1563 params.push_back(user->nick);
1564 DoOneToMany(oldnick,"NICK",params);
1568 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1570 if (std::string(source->server) == Srv->GetServerName())
1572 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1573 std::deque<std::string> params;
1574 params.push_back(chan->name);
1575 params.push_back(user->nick);
1576 params.push_back(":"+reason);
1577 DoOneToMany(source->nick,"KICK",params);
1581 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1583 std::deque<std::string> params;
1584 params.push_back(dest->nick);
1585 params.push_back(":"+reason);
1586 DoOneToMany(source->nick,"KILL",params);
1589 virtual void OnRehash(std::string parameter)
1591 if (parameter != "")
1593 std::deque<std::string> params;
1594 params.push_back(parameter);
1595 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1597 if (Srv->MatchText(Srv->GetServerName(),parameter))
1599 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1600 Srv->RehashServer();
1605 // note: the protocol does not allow direct umode +o except
1606 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1608 virtual void OnOper(userrec* user, std::string opertype)
1610 if (std::string(user->server) == Srv->GetServerName())
1612 std::deque<std::string> params;
1613 params.push_back(opertype);
1614 DoOneToMany(user->nick,"OPERTYPE",params);
1618 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1620 log(DEBUG,"*** ONMODE TRIGGER");
1621 if (std::string(user->server) == Srv->GetServerName())
1623 log(DEBUG,"*** LOCAL");
1624 if (target_type == TYPE_USER)
1626 userrec* u = (userrec*)dest;
1627 std::deque<std::string> params;
1628 params.push_back(u->nick);
1629 params.push_back(text);
1630 DoOneToMany(user->nick,"MODE",params);
1634 chanrec* c = (chanrec*)dest;
1635 std::deque<std::string> params;
1636 params.push_back(c->name);
1637 params.push_back(text);
1638 DoOneToMany(user->nick,"MODE",params);
1643 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1645 TreeSocket* s = (TreeSocket*)opaque;
1648 if (target_type == TYPE_USER)
1650 userrec* u = (userrec*)target;
1651 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1655 chanrec* c = (chanrec*)target;
1656 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1661 virtual ~ModuleSpanningTree()
1666 virtual Version GetVersion()
1668 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1673 class ModuleSpanningTreeFactory : public ModuleFactory
1676 ModuleSpanningTreeFactory()
1680 ~ModuleSpanningTreeFactory()
1684 virtual Module * CreateModule()
1686 TreeProtocolModule = new ModuleSpanningTree;
1687 return TreeProtocolModule;
1693 extern "C" void * init_module( void )
1695 return new ModuleSpanningTreeFactory;