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, std::string prefix,std::string command,std::deque<std::string> params);
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 if (ServerName.c_str() == TreeRoot->GetName())
236 // first, find the server by recursively walking the tree
237 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
238 // did we find it? If not, they did something wrong, abort.
245 // The server exists, follow its parent nodes until
246 // the parent of the current is 'TreeRoot', we know
247 // then that this is a directly-connected server.
248 while ((Found) && (Found->GetParent() != TreeRoot))
250 Found = Found->GetParent();
256 bool LookForServer(TreeServer* Current, std::string ServerName)
258 if (ServerName == Current->GetName())
260 for (unsigned int q = 0; q < Current->ChildCount(); q++)
262 if (LookForServer(Current->GetChild(q),ServerName))
270 void RFindServer(TreeServer* Current, std::string ServerName)
272 if ((ServerName == Current->GetName()) && (!Found))
279 for (unsigned int q = 0; q < Current->ChildCount(); q++)
282 RFindServer(Current->GetChild(q),ServerName);
288 TreeServer* FindServer(std::string ServerName)
291 RFindServer(TreeRoot,ServerName);
295 bool IsServer(std::string ServerName)
297 return LookForServer(TreeRoot,ServerName);
300 class TreeSocket : public InspSocket
303 std::string in_buffer;
304 ServerState LinkState;
305 std::string InboundServerName;
306 std::string InboundDescription;
308 int num_lost_servers;
312 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
313 : InspSocket(host, port, listening, maxtime)
316 this->LinkState = LISTENER;
319 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
320 : InspSocket(host, port, listening, maxtime)
323 this->LinkState = CONNECTING;
326 TreeSocket(int newfd, char* ip)
327 : InspSocket(newfd, ip)
329 this->LinkState = WAIT_AUTH_1;
332 virtual bool OnConnected()
334 if (this->LinkState == CONNECTING)
336 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
337 // we should send our details here.
338 // if the other side is satisfied, they send theirs.
339 // we do not need to change state here.
340 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
342 if (x->Name == this->myhost)
344 // found who we're supposed to be connecting to, send the neccessary gubbins.
345 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
353 virtual void OnError(InspSocketError e)
357 virtual int OnDisconnect()
362 // recursively send the server tree with distances as hops
363 void SendServers(TreeServer* Current, TreeServer* s, int hops)
366 for (unsigned int q = 0; q < Current->ChildCount(); q++)
368 TreeServer* recursive_server = Current->GetChild(q);
369 if (recursive_server != s)
371 // :source.server SERVER server.name hops :Description
372 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
373 this->WriteLine(command);
374 // down to next level
375 this->SendServers(recursive_server, s, hops+1);
380 void SquitServer(TreeServer* Current)
382 // recursively squit the servers attached to 'Current'
383 for (unsigned int q = 0; q < Current->ChildCount(); q++)
385 TreeServer* recursive_server = Current->GetChild(q);
386 this->SquitServer(recursive_server);
388 // Now we've whacked the kids, whack self
390 bool quittingpeople = true;
391 while (quittingpeople)
393 quittingpeople = false;
394 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
396 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
398 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
400 quittingpeople = true;
407 void Squit(TreeServer* Current,std::string reason)
411 std::deque<std::string> params;
412 params.push_back(Current->GetName());
413 params.push_back(":"+reason);
414 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
415 if (Current->GetParent() == TreeRoot)
417 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
421 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
423 num_lost_servers = 0;
425 SquitServer(Current);
427 Current->GetParent()->DelChild(Current);
429 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
433 log(DEFAULT,"Squit from unknown server");
437 bool ForceMode(std::string source, std::deque<std::string> params)
439 userrec* who = new userrec;
440 who->fd = FD_MAGIC_NUMBER;
441 if (params.size() < 2)
444 for (unsigned int q = 0; q < params.size(); q++)
446 modelist[q] = (char*)params[q].c_str();
448 Srv->SendMode(modelist,params.size(),who);
449 DoOneToAllButSender(source,"FMODE",params,source);
454 bool ForceTopic(std::string source, std::deque<std::string> params)
456 // FTOPIC %s %lu %s :%s
457 if (params.size() != 4)
459 std::string channel = params[0];
460 time_t ts = atoi(params[1].c_str());
461 std::string setby = params[2];
462 std::string topic = params[3];
464 chanrec* c = Srv->FindChannel(channel);
467 if ((ts >= c->topicset) || (!*c->topic))
469 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
470 strlcpy(c->setby,setby.c_str(),NICKMAX);
472 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
477 // all done, send it on its way
478 params[3] = ":" + params[3];
479 DoOneToAllButSender(source,"FTOPIC",params,source);
484 bool ForceJoin(std::string source, std::deque<std::string> params)
486 if (params.size() < 2)
490 char modestring[MAXBUF];
491 char* mode_users[127];
492 mode_users[0] = first;
493 mode_users[1] = modestring;
494 strcpy(mode_users[1],"+");
495 unsigned int modectr = 2;
498 std::string channel = params[0];
500 chanrec* chan = Srv->FindChannel(channel);
505 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
506 for (unsigned int usernum = 1; usernum < params.size(); usernum++)
508 // process one channel at a time, applying modes.
509 char* usr = (char*)params[usernum].c_str();
510 char permissions = *usr;
515 mode_users[modectr++] = usr;
516 strlcat(modestring,"o",MAXBUF);
520 mode_users[modectr++] = usr;
521 strlcat(modestring,"h",MAXBUF);
525 mode_users[modectr++] = usr;
526 strlcat(modestring,"v",MAXBUF);
529 who = Srv->FindNick(usr);
532 Srv->JoinUserToChannel(who,channel,key);
533 if (modectr >= (MAXMODES-1))
535 // theres a mode for this user. push them onto the mode queue, and flush it
536 // if there are more than MAXMODES to go.
537 Srv->SendMode(mode_users,modectr,who);
538 strcpy(mode_users[1],"+");
543 // there werent enough modes built up to flush it during FJOIN,
544 // or, there are a number left over. flush them out.
545 if ((modectr > 2) && (who))
547 Srv->SendMode(mode_users,modectr,who);
549 DoOneToAllButSender(source,"FJOIN",params,source);
553 bool IntroduceClient(std::string source, std::deque<std::string> params)
555 if (params.size() < 8)
557 // NICK age nick host dhost ident +modes ip :gecos
559 std::string nick = params[1];
560 std::string host = params[2];
561 std::string dhost = params[3];
562 std::string ident = params[4];
563 time_t age = atoi(params[0].c_str());
564 std::string modes = params[5];
565 if (*(modes.c_str()) == '+')
567 char* m = (char*)modes.c_str();
571 std::string ip = params[6];
572 std::string gecos = params[7];
573 char* tempnick = (char*)nick.c_str();
574 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
576 user_hash::iterator iter;
577 iter = clientlist.find(tempnick);
578 if (iter != clientlist.end())
581 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);
582 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
586 clientlist[tempnick] = new userrec();
587 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
588 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
589 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
590 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
591 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
592 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
593 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
594 clientlist[tempnick]->registered = 7;
595 clientlist[tempnick]->signon = age;
596 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
597 for (int i = 0; i < MAXCHANS; i++)
599 clientlist[tempnick]->chans[i].channel = NULL;
600 clientlist[tempnick]->chans[i].uc_modes = 0;
602 params[7] = ":" + params[7];
603 DoOneToAllButSender(source,"NICK",params,source);
607 void SendFJoins(TreeServer* Current, chanrec* c)
610 snprintf(list,MAXBUF,":%s FJOIN %s",Srv->GetServerName().c_str(),c->name);
611 std::vector<char*> *ulist = c->GetUsers();
612 for (unsigned int i = 0; i < ulist->size(); i++)
614 char* o = (*ulist)[i];
615 userrec* otheruser = (userrec*)o;
616 strlcat(list," ",MAXBUF);
617 strlcat(list,cmode(otheruser,c),MAXBUF);
618 strlcat(list,otheruser->nick,MAXBUF);
619 if (strlen(list)>(480-NICKMAX))
621 this->WriteLine(list);
622 snprintf(list,MAXBUF,":%s FJOIN %s",Srv->GetServerName().c_str(),c->name);
625 if (list[strlen(list)-1] != ':')
627 this->WriteLine(list);
631 void SendChannelModes(TreeServer* Current)
634 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
636 SendFJoins(Current, c->second);
637 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
638 this->WriteLine(data);
639 if (*c->second->topic)
641 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);
642 this->WriteLine(data);
644 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
646 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
647 this->WriteLine(data);
649 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
653 // send all users and their channels
654 void SendUsers(TreeServer* Current)
657 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
659 if (u->second->registered == 7)
661 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);
662 this->WriteLine(data);
663 if (strchr(u->second->modes,'o'))
665 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
667 //char* chl = chlist(u->second,u->second);
670 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
672 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
677 void DoBurst(TreeServer* s)
679 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
680 this->WriteLine("BURST");
682 this->SendServers(TreeRoot,s,1);
683 // Send users and their channels
685 // TODO: Send everything else (channel modes etc)
686 this->SendChannelModes(s);
687 this->WriteLine("ENDBURST");
690 virtual bool OnDataReady()
692 char* data = this->Read();
695 this->in_buffer += data;
696 while (in_buffer.find("\n") != std::string::npos)
698 char* line = (char*)in_buffer.c_str();
699 std::string ret = "";
700 while ((*line != '\n') && (strlen(line)))
705 if ((*line == '\n') || (*line == '\r'))
708 if (!this->ProcessLine(ret))
714 return (data != NULL);
717 int WriteLine(std::string line)
719 return this->Write(line + "\r\n");
722 bool Error(std::deque<std::string> params)
724 if (params.size() < 1)
726 std::string Errmsg = params[0];
727 std::string SName = myhost;
728 if (InboundServerName != "")
730 SName = InboundServerName;
732 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
733 // we will return false to cause the socket to close.
737 bool OperType(std::string prefix, std::deque<std::string> params)
739 if (params.size() != 1)
741 std::string opertype = params[0];
742 userrec* u = Srv->FindNick(prefix);
745 strlcpy(u->oper,opertype.c_str(),NICKMAX);
746 if (!strchr(u->modes,'o'))
748 strcat(u->modes,"o");
750 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
755 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
757 if (params.size() < 1)
759 std::string servermask = params[0];
760 if (Srv->MatchText(Srv->GetServerName(),servermask))
762 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
764 ReadConfiguration(false);
766 DoOneToAllButSender(prefix,"REHASH",params,prefix);
770 bool RemoteKill(std::string prefix, std::deque<std::string> params)
772 if (params.size() != 2)
774 std::string nick = params[0];
775 std::string reason = params[1];
776 userrec* u = Srv->FindNick(prefix);
777 userrec* who = Srv->FindNick(nick);
780 std::string sourceserv = prefix;
783 sourceserv = u->server;
785 params[1] = ":" + params[1];
786 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
787 Srv->QuitUser(who,reason);
792 bool RemoteServer(std::string prefix, std::deque<std::string> params)
794 if (params.size() < 4)
796 std::string servername = params[0];
797 std::string password = params[1];
798 // hopcount is not used for a remote server, we calculate this ourselves
799 std::string description = params[3];
800 TreeServer* ParentOfThis = FindServer(prefix);
803 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
806 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
807 ParentOfThis->AddChild(Node);
808 params[3] = ":" + params[3];
809 DoOneToAllButSender(prefix,"SERVER",params,prefix);
810 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
814 bool Outbound_Reply_Server(std::deque<std::string> params)
816 if (params.size() < 4)
818 std::string servername = params[0];
819 std::string password = params[1];
820 int hops = atoi(params[2].c_str());
823 this->WriteLine("ERROR :Server too far away for authentication");
826 std::string description = params[3];
827 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
829 if ((x->Name == servername) && (x->RecvPass == password))
831 // Begin the sync here. this kickstarts the
832 // other side, waiting in WAIT_AUTH_2 state,
833 // into starting their burst, as it shows
835 this->LinkState = CONNECTED;
836 // we should add the details of this server now
837 // to the servers tree, as a child of the root
839 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
840 TreeRoot->AddChild(Node);
841 params[3] = ":" + params[3];
842 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
847 this->WriteLine("ERROR :Invalid credentials");
851 bool Inbound_Server(std::deque<std::string> params)
853 if (params.size() < 4)
855 std::string servername = params[0];
856 std::string password = params[1];
857 int hops = atoi(params[2].c_str());
860 this->WriteLine("ERROR :Server too far away for authentication");
863 std::string description = params[3];
864 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
866 if ((x->Name == servername) && (x->RecvPass == password))
868 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
869 this->InboundServerName = servername;
870 this->InboundDescription = description;
871 // this is good. Send our details: Our server name and description and hopcount of 0,
872 // along with the sendpass from this block.
873 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
874 // move to the next state, we are now waiting for THEM.
875 this->LinkState = WAIT_AUTH_2;
879 this->WriteLine("ERROR :Invalid credentials");
883 std::deque<std::string> Split(std::string line, bool stripcolon)
885 std::deque<std::string> n;
886 if (!strchr(line.c_str(),' '))
891 std::stringstream s(line);
892 std::string param = "";
911 if ((param == ":") && (item > 0))
934 bool ProcessLine(std::string line)
936 char* l = (char*)line.c_str();
937 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
938 l[strlen(l)-1] = '\0';
942 Srv->Log(DEBUG,"IN: '"+line+"'");
943 std::deque<std::string> params = this->Split(line,true);
944 std::string command = "";
945 std::string prefix = "";
946 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
950 char* pref = (char*)prefix.c_str();
962 switch (this->LinkState)
967 // Waiting for SERVER command from remote server. Server initiating
968 // the connection sends the first SERVER command, listening server
969 // replies with theirs if its happy, then if the initiator is happy,
970 // it starts to send its net sync, which starts the merge, otherwise
971 // it sends an ERROR.
972 if (command == "SERVER")
974 return this->Inbound_Server(params);
976 else if (command == "ERROR")
978 return this->Error(params);
982 // Waiting for start of other side's netmerge to say they liked our
984 if (command == "SERVER")
986 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
990 else if (command == "BURST")
992 this->LinkState = CONNECTED;
993 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
994 TreeRoot->AddChild(Node);
996 params.push_back(InboundServerName);
997 params.push_back("*");
998 params.push_back("1");
999 params.push_back(":"+InboundDescription);
1000 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1001 this->DoBurst(Node);
1003 else if (command == "ERROR")
1005 return this->Error(params);
1010 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1014 if (command == "SERVER")
1016 // another server we connected to, which was in WAIT_AUTH_1 state,
1017 // has just sent us their credentials. If we get this far, theyre
1018 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1019 // if we're happy with this, we should send our netburst which
1020 // kickstarts the merge.
1021 return this->Outbound_Reply_Server(params);
1023 else if (command == "ERROR")
1025 return this->Error(params);
1029 // This is the 'authenticated' state, when all passwords
1030 // have been exchanged and anything past this point is taken
1032 std::string target = "";
1033 if ((command == "NICK") && (params.size() > 1))
1035 return this->IntroduceClient(prefix,params);
1037 else if (command == "FJOIN")
1039 return this->ForceJoin(prefix,params);
1041 else if (command == "SERVER")
1043 return this->RemoteServer(prefix,params);
1045 else if (command == "ERROR")
1047 return this->Error(params);
1049 else if (command == "OPERTYPE")
1051 return this->OperType(prefix,params);
1053 else if (command == "FMODE")
1055 return this->ForceMode(prefix,params);
1057 else if (command == "KILL")
1059 return this->RemoteKill(prefix,params);
1061 else if (command == "FTOPIC")
1063 return this->ForceTopic(prefix,params);
1065 else if (command == "REHASH")
1067 return this->RemoteRehash(prefix,params);
1069 else if (command == "SQUIT")
1071 if (params.size() == 2)
1073 this->Squit(FindServer(params[0]),params[1]);
1079 // not a special inter-server command.
1080 // Emulate the actual user doing the command,
1081 // this saves us having a huge ugly parser.
1082 userrec* who = Srv->FindNick(prefix);
1083 std::string sourceserv = this->myhost;
1084 if (this->InboundServerName != "")
1086 sourceserv = this->InboundServerName;
1091 target = who->server;
1092 char* strparams[127];
1093 for (unsigned int q = 0; q < params.size(); q++)
1095 strparams[q] = (char*)params[q].c_str();
1097 Srv->CallCommandHandler(command, strparams, params.size(), who);
1101 // its not a user. Its either a server, or somethings screwed up.
1102 if (IsServer(prefix))
1104 target = Srv->GetServerName();
1108 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1112 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1121 virtual std::string GetName()
1123 std::string sourceserv = this->myhost;
1124 if (this->InboundServerName != "")
1126 sourceserv = this->InboundServerName;
1131 virtual void OnTimeout()
1133 if (this->LinkState == CONNECTING)
1135 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1139 virtual void OnClose()
1141 // Connection closed.
1142 // If the connection is fully up (state CONNECTED)
1143 // then propogate a netsplit to all peers.
1144 std::string quitserver = this->myhost;
1145 if (this->InboundServerName != "")
1147 quitserver = this->InboundServerName;
1149 TreeServer* s = FindServer(quitserver);
1152 Squit(s,"Remote host closed the connection");
1156 virtual int OnIncomingConnection(int newsock, char* ip)
1158 TreeSocket* s = new TreeSocket(newsock, ip);
1164 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1166 if ((command == "NOTICE") || (command == "PRIVMSG"))
1168 if (params.size() >= 2)
1170 if (*(params[0].c_str()) != '#')
1172 userrec* d = Srv->FindNick(params[0]);
1175 std::deque<std::string> par;
1177 par.push_back(params[0]);
1178 par.push_back(":"+params[1]);
1179 DoOneToOne(prefix,command,par,d->server);
1185 TreeServer* omitroute = BestRouteTo(omit);
1186 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1188 TreeServer* Route = TreeRoot->GetChild(x);
1189 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1191 TreeSocket* Sock = Route->GetSocket();
1192 Sock->WriteLine(data);
1198 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1200 TreeServer* omitroute = BestRouteTo(omit);
1201 std::string FullLine = ":" + prefix + " " + command;
1202 for (unsigned int x = 0; x < params.size(); x++)
1204 FullLine = FullLine + " " + params[x];
1206 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1208 TreeServer* Route = TreeRoot->GetChild(x);
1209 // Send the line IF:
1210 // The route has a socket (its a direct connection)
1211 // The route isnt the one to be omitted
1212 // The route isnt the path to the one to be omitted
1213 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1215 TreeSocket* Sock = Route->GetSocket();
1216 Sock->WriteLine(FullLine);
1222 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1224 std::string FullLine = ":" + prefix + " " + command;
1225 for (unsigned int x = 0; x < params.size(); x++)
1227 FullLine = FullLine + " " + params[x];
1229 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1231 TreeServer* Route = TreeRoot->GetChild(x);
1232 if (Route->GetSocket())
1234 TreeSocket* Sock = Route->GetSocket();
1235 Sock->WriteLine(FullLine);
1241 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1243 TreeServer* Route = BestRouteTo(target);
1246 std::string FullLine = ":" + prefix + " " + command;
1247 for (unsigned int x = 0; x < params.size(); x++)
1249 FullLine = FullLine + " " + params[x];
1251 if (Route->GetSocket())
1253 TreeSocket* Sock = Route->GetSocket();
1254 Sock->WriteLine(FullLine);
1264 std::vector<TreeSocket*> Bindings;
1266 void ReadConfiguration(bool rebind)
1270 for (int j =0; j < Conf->Enumerate("bind"); j++)
1272 std::string Type = Conf->ReadValue("bind","type",j);
1273 std::string IP = Conf->ReadValue("bind","address",j);
1274 long Port = Conf->ReadInteger("bind","port",j,true);
1275 if (Type == "servers")
1281 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1282 if (listener->GetState() == I_LISTENING)
1284 Srv->AddSocket(listener);
1285 Bindings.push_back(listener);
1289 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1297 for (int j =0; j < Conf->Enumerate("link"); j++)
1300 L.Name = Conf->ReadValue("link","name",j);
1301 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1302 L.Port = Conf->ReadInteger("link","port",j,true);
1303 L.SendPass = Conf->ReadValue("link","sendpass",j);
1304 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1305 LinkBlocks.push_back(L);
1306 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1311 class ModuleSpanningTree : public Module
1313 std::vector<TreeSocket*> Bindings;
1318 ModuleSpanningTree()
1321 Conf = new ConfigReader;
1324 // Create the root of the tree
1325 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1327 ReadConfiguration(true);
1330 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1332 std::string Parent = TreeRoot->GetName();
1333 if (Current->GetParent())
1335 Parent = Current->GetParent()->GetName();
1337 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1339 ShowLinks(Current->GetChild(q),user,hops+1);
1341 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1344 void HandleLinks(char** parameters, int pcnt, userrec* user)
1346 ShowLinks(TreeRoot,user,0);
1347 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1351 void HandleLusers(char** parameters, int pcnt, userrec* user)
1356 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1358 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1362 for (int t = 0; t < depth; t++)
1364 matrix[line][t] = ' ';
1366 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1368 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1370 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1375 // Ok, prepare to be confused.
1376 // After much mulling over how to approach this, it struck me that
1377 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1378 // keeping track of a ton of ascii characters, and line by line
1379 // under recursion working out where to place them using multiplications
1380 // and divisons, we instead render the map onto a backplane of characters
1381 // (a character matrix), then draw the branches as a series of "L" shapes
1382 // from the nodes. This is not only friendlier on CPU it uses less stack.
1384 void HandleMap(char** parameters, int pcnt, userrec* user)
1386 // This array represents a virtual screen which we will
1387 // "scratch" draw to, as the console device of an irc
1388 // client does not provide for a proper terminal.
1389 char matrix[128][80];
1390 for (unsigned int t = 0; t < 128; t++)
1392 matrix[t][0] = '\0';
1395 // The only recursive bit is called here.
1396 ShowMap(TreeRoot,user,0,matrix);
1397 // Process each line one by one. The algorithm has a limit of
1398 // 128 servers (which is far more than a spanning tree should have
1399 // anyway, so we're ok). This limit can be raised simply by making
1400 // the character matrix deeper, 128 rows taking 10k of memory.
1401 for (int l = 1; l < line; l++)
1403 // scan across the line looking for the start of the
1404 // servername (the recursive part of the algorithm has placed
1405 // the servers at indented positions depending on what they
1407 int first_nonspace = 0;
1408 while (matrix[l][first_nonspace] == ' ')
1413 // Draw the `- (corner) section: this may be overwritten by
1414 // another L shape passing along the same vertical pane, becoming
1415 // a |- (branch) section instead.
1416 matrix[l][first_nonspace] = '-';
1417 matrix[l][first_nonspace-1] = '`';
1419 // Draw upwards until we hit the parent server, causing possibly
1420 // other corners (`-) to become branches (|-)
1421 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1423 matrix[l2][first_nonspace-1] = '|';
1427 // dump the whole lot to the user. This is the easy bit, honest.
1428 for (int t = 0; t < line; t++)
1430 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1432 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1436 int HandleSquit(char** parameters, int pcnt, userrec* user)
1441 int HandleConnect(char** parameters, int pcnt, userrec* user)
1443 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1445 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1447 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1448 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1449 Srv->AddSocket(newsocket);
1453 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1457 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1459 if (command == "CONNECT")
1461 return this->HandleConnect(parameters,pcnt,user);
1463 else if (command == "SQUIT")
1465 return this->HandleSquit(parameters,pcnt,user);
1467 else if (command == "MAP")
1469 this->HandleMap(parameters,pcnt,user);
1472 else if (command == "LUSERS")
1474 this->HandleLusers(parameters,pcnt,user);
1477 else if (command == "LINKS")
1479 this->HandleLinks(parameters,pcnt,user);
1482 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1484 // this bit of code cleverly routes all module commands
1485 // to all remote severs *automatically* so that modules
1486 // can just handle commands locally, without having
1487 // to have any special provision in place for remote
1488 // commands and linking protocols.
1489 std::deque<std::string> params;
1491 for (int j = 0; j < pcnt; j++)
1493 if (strchr(parameters[j],' '))
1495 params.push_back(":" + std::string(parameters[j]));
1499 params.push_back(std::string(parameters[j]));
1502 DoOneToMany(user->nick,command,params);
1507 virtual void OnGetServerDescription(std::string servername,std::string &description)
1509 TreeServer* s = FindServer(servername);
1512 description = s->GetDesc();
1516 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1518 if (std::string(source->server) == Srv->GetServerName())
1520 std::deque<std::string> params;
1521 params.push_back(dest->nick);
1522 params.push_back(channel->name);
1523 DoOneToMany(source->nick,"INVITE",params);
1527 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1529 std::deque<std::string> params;
1530 params.push_back(chan->name);
1531 params.push_back(":"+topic);
1532 DoOneToMany(user->nick,"TOPIC",params);
1535 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1537 if (target_type == TYPE_USER)
1539 userrec* d = (userrec*)dest;
1540 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1542 std::deque<std::string> params;
1544 params.push_back(d->nick);
1545 params.push_back(":"+text);
1546 DoOneToOne(user->nick,"NOTICE",params,d->server);
1551 if (std::string(user->server) == Srv->GetServerName())
1553 chanrec *c = (chanrec*)dest;
1554 std::deque<std::string> params;
1555 params.push_back(c->name);
1556 params.push_back(":"+text);
1557 DoOneToMany(user->nick,"NOTICE",params);
1562 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1564 if (target_type == TYPE_USER)
1566 // route private messages which are targetted at clients only to the server
1567 // which needs to receive them
1568 userrec* d = (userrec*)dest;
1569 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1571 std::deque<std::string> params;
1573 params.push_back(d->nick);
1574 params.push_back(":"+text);
1575 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1580 if (std::string(user->server) == Srv->GetServerName())
1582 chanrec *c = (chanrec*)dest;
1583 std::deque<std::string> params;
1584 params.push_back(c->name);
1585 params.push_back(":"+text);
1586 DoOneToMany(user->nick,"PRIVMSG",params);
1591 virtual void OnUserJoin(userrec* user, chanrec* channel)
1593 // Only do this for local users
1594 if (std::string(user->server) == Srv->GetServerName())
1596 std::deque<std::string> params;
1598 params.push_back(channel->name);
1601 // if the channel has a key, force the join by emulating the key.
1602 params.push_back(channel->key);
1604 DoOneToMany(user->nick,"JOIN",params);
1608 virtual void OnUserPart(userrec* user, chanrec* channel)
1610 if (std::string(user->server) == Srv->GetServerName())
1612 std::deque<std::string> params;
1614 params.push_back(channel->name);
1615 DoOneToMany(user->nick,"PART",params);
1619 virtual void OnUserConnect(userrec* user)
1621 char agestr[MAXBUF];
1622 if (std::string(user->server) == Srv->GetServerName())
1624 std::deque<std::string> params;
1625 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1627 params.push_back(agestr);
1628 params.push_back(user->nick);
1629 params.push_back(user->host);
1630 params.push_back(user->dhost);
1631 params.push_back(user->ident);
1632 params.push_back("+"+std::string(user->modes));
1633 params.push_back(user->ip);
1634 params.push_back(":"+std::string(user->fullname));
1635 DoOneToMany(Srv->GetServerName(),"NICK",params);
1639 virtual void OnUserQuit(userrec* user, std::string reason)
1641 if (std::string(user->server) == Srv->GetServerName())
1643 std::deque<std::string> params;
1644 params.push_back(":"+reason);
1645 DoOneToMany(user->nick,"QUIT",params);
1649 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1651 if (std::string(user->server) == Srv->GetServerName())
1653 std::deque<std::string> params;
1654 params.push_back(user->nick);
1655 DoOneToMany(oldnick,"NICK",params);
1659 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1661 if (std::string(source->server) == Srv->GetServerName())
1663 std::deque<std::string> params;
1664 params.push_back(chan->name);
1665 params.push_back(user->nick);
1666 params.push_back(":"+reason);
1667 DoOneToMany(source->nick,"KICK",params);
1671 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1673 std::deque<std::string> params;
1674 params.push_back(dest->nick);
1675 params.push_back(":"+reason);
1676 DoOneToMany(source->nick,"KILL",params);
1679 virtual void OnRehash(std::string parameter)
1681 if (parameter != "")
1683 std::deque<std::string> params;
1684 params.push_back(parameter);
1685 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1687 if (Srv->MatchText(Srv->GetServerName(),parameter))
1689 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1690 Srv->RehashServer();
1693 ReadConfiguration(false);
1696 // note: the protocol does not allow direct umode +o except
1697 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1699 virtual void OnOper(userrec* user, std::string opertype)
1701 if (std::string(user->server) == Srv->GetServerName())
1703 std::deque<std::string> params;
1704 params.push_back(opertype);
1705 DoOneToMany(user->nick,"OPERTYPE",params);
1709 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1711 if (std::string(user->server) == Srv->GetServerName())
1713 if (target_type == TYPE_USER)
1715 userrec* u = (userrec*)dest;
1716 std::deque<std::string> params;
1717 params.push_back(u->nick);
1718 params.push_back(text);
1719 DoOneToMany(user->nick,"MODE",params);
1723 chanrec* c = (chanrec*)dest;
1724 std::deque<std::string> params;
1725 params.push_back(c->name);
1726 params.push_back(text);
1727 DoOneToMany(user->nick,"MODE",params);
1732 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1734 TreeSocket* s = (TreeSocket*)opaque;
1737 if (target_type == TYPE_USER)
1739 userrec* u = (userrec*)target;
1740 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1744 chanrec* c = (chanrec*)target;
1745 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1750 virtual ~ModuleSpanningTree()
1755 virtual Version GetVersion()
1757 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1762 class ModuleSpanningTreeFactory : public ModuleFactory
1765 ModuleSpanningTreeFactory()
1769 ~ModuleSpanningTreeFactory()
1773 virtual Module * CreateModule()
1775 TreeProtocolModule = new ModuleSpanningTree;
1776 return TreeProtocolModule;
1782 extern "C" void * init_module( void )
1784 return new ModuleSpanningTreeFactory;