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 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1166 for (unsigned int c = 0; c < list.size(); c++)
1168 if (list[c] == server)
1173 list.push_back(server);
1176 // returns a list of DIRECT servernames for a specific channel
1177 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1179 std::deque<TreeServer*> list;
1180 std::vector<char*> *ulist = c->GetUsers();
1181 for (unsigned int i = 0; i < ulist->size(); i++)
1183 char* o = (*ulist)[i];
1184 userrec* otheruser = (userrec*)o;
1185 if (std::string(otheruser->server) != Srv->GetServerName())
1187 TreeServer* best = BestRouteTo(otheruser->server);
1189 AddThisServer(best,list);
1195 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1197 TreeServer* omitroute = BestRouteTo(omit);
1198 if ((command == "NOTICE") || (command == "PRIVMSG"))
1200 if (params.size() >= 2)
1202 if (*(params[0].c_str()) != '#')
1204 // special routing for private messages/notices
1205 userrec* d = Srv->FindNick(params[0]);
1208 std::deque<std::string> par;
1210 par.push_back(params[0]);
1211 par.push_back(":"+params[1]);
1212 DoOneToOne(prefix,command,par,d->server);
1218 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1219 chanrec* c = Srv->FindChannel(params[0]);
1222 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1223 log(DEBUG,"Got a list of %d servers",list.size());
1224 for (unsigned int i = 0; i < list.size(); i++)
1226 TreeSocket* Sock = list[i]->GetSocket();
1227 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1229 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1230 Sock->WriteLine(data);
1238 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1240 TreeServer* Route = TreeRoot->GetChild(x);
1241 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1243 TreeSocket* Sock = Route->GetSocket();
1244 Sock->WriteLine(data);
1250 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1252 TreeServer* omitroute = BestRouteTo(omit);
1253 std::string FullLine = ":" + prefix + " " + command;
1254 for (unsigned int x = 0; x < params.size(); x++)
1256 FullLine = FullLine + " " + params[x];
1258 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1260 TreeServer* Route = TreeRoot->GetChild(x);
1261 // Send the line IF:
1262 // The route has a socket (its a direct connection)
1263 // The route isnt the one to be omitted
1264 // The route isnt the path to the one to be omitted
1265 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1267 TreeSocket* Sock = Route->GetSocket();
1268 Sock->WriteLine(FullLine);
1274 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1276 std::string FullLine = ":" + prefix + " " + command;
1277 for (unsigned int x = 0; x < params.size(); x++)
1279 FullLine = FullLine + " " + params[x];
1281 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1283 TreeServer* Route = TreeRoot->GetChild(x);
1284 if (Route->GetSocket())
1286 TreeSocket* Sock = Route->GetSocket();
1287 Sock->WriteLine(FullLine);
1293 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1295 TreeServer* Route = BestRouteTo(target);
1298 std::string FullLine = ":" + prefix + " " + command;
1299 for (unsigned int x = 0; x < params.size(); x++)
1301 FullLine = FullLine + " " + params[x];
1303 if (Route->GetSocket())
1305 TreeSocket* Sock = Route->GetSocket();
1306 Sock->WriteLine(FullLine);
1316 std::vector<TreeSocket*> Bindings;
1318 void ReadConfiguration(bool rebind)
1322 for (int j =0; j < Conf->Enumerate("bind"); j++)
1324 std::string Type = Conf->ReadValue("bind","type",j);
1325 std::string IP = Conf->ReadValue("bind","address",j);
1326 long Port = Conf->ReadInteger("bind","port",j,true);
1327 if (Type == "servers")
1333 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1334 if (listener->GetState() == I_LISTENING)
1336 Srv->AddSocket(listener);
1337 Bindings.push_back(listener);
1341 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1349 for (int j =0; j < Conf->Enumerate("link"); j++)
1352 L.Name = Conf->ReadValue("link","name",j);
1353 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1354 L.Port = Conf->ReadInteger("link","port",j,true);
1355 L.SendPass = Conf->ReadValue("link","sendpass",j);
1356 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1357 LinkBlocks.push_back(L);
1358 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1363 class ModuleSpanningTree : public Module
1365 std::vector<TreeSocket*> Bindings;
1370 ModuleSpanningTree()
1373 Conf = new ConfigReader;
1376 // Create the root of the tree
1377 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1379 ReadConfiguration(true);
1382 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1384 std::string Parent = TreeRoot->GetName();
1385 if (Current->GetParent())
1387 Parent = Current->GetParent()->GetName();
1389 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1391 ShowLinks(Current->GetChild(q),user,hops+1);
1393 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1396 void HandleLinks(char** parameters, int pcnt, userrec* user)
1398 ShowLinks(TreeRoot,user,0);
1399 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1403 void HandleLusers(char** parameters, int pcnt, userrec* user)
1408 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1410 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1414 for (int t = 0; t < depth; t++)
1416 matrix[line][t] = ' ';
1418 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1420 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1422 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1427 // Ok, prepare to be confused.
1428 // After much mulling over how to approach this, it struck me that
1429 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1430 // keeping track of a ton of ascii characters, and line by line
1431 // under recursion working out where to place them using multiplications
1432 // and divisons, we instead render the map onto a backplane of characters
1433 // (a character matrix), then draw the branches as a series of "L" shapes
1434 // from the nodes. This is not only friendlier on CPU it uses less stack.
1436 void HandleMap(char** parameters, int pcnt, userrec* user)
1438 // This array represents a virtual screen which we will
1439 // "scratch" draw to, as the console device of an irc
1440 // client does not provide for a proper terminal.
1441 char matrix[128][80];
1442 for (unsigned int t = 0; t < 128; t++)
1444 matrix[t][0] = '\0';
1447 // The only recursive bit is called here.
1448 ShowMap(TreeRoot,user,0,matrix);
1449 // Process each line one by one. The algorithm has a limit of
1450 // 128 servers (which is far more than a spanning tree should have
1451 // anyway, so we're ok). This limit can be raised simply by making
1452 // the character matrix deeper, 128 rows taking 10k of memory.
1453 for (int l = 1; l < line; l++)
1455 // scan across the line looking for the start of the
1456 // servername (the recursive part of the algorithm has placed
1457 // the servers at indented positions depending on what they
1459 int first_nonspace = 0;
1460 while (matrix[l][first_nonspace] == ' ')
1465 // Draw the `- (corner) section: this may be overwritten by
1466 // another L shape passing along the same vertical pane, becoming
1467 // a |- (branch) section instead.
1468 matrix[l][first_nonspace] = '-';
1469 matrix[l][first_nonspace-1] = '`';
1471 // Draw upwards until we hit the parent server, causing possibly
1472 // other corners (`-) to become branches (|-)
1473 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1475 matrix[l2][first_nonspace-1] = '|';
1479 // dump the whole lot to the user. This is the easy bit, honest.
1480 for (int t = 0; t < line; t++)
1482 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1484 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1488 int HandleSquit(char** parameters, int pcnt, userrec* user)
1493 int HandleConnect(char** parameters, int pcnt, userrec* user)
1495 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1497 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1499 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1500 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1501 Srv->AddSocket(newsocket);
1505 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1509 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1511 if (command == "CONNECT")
1513 return this->HandleConnect(parameters,pcnt,user);
1515 else if (command == "SQUIT")
1517 return this->HandleSquit(parameters,pcnt,user);
1519 else if (command == "MAP")
1521 this->HandleMap(parameters,pcnt,user);
1524 else if (command == "LUSERS")
1526 this->HandleLusers(parameters,pcnt,user);
1529 else if (command == "LINKS")
1531 this->HandleLinks(parameters,pcnt,user);
1534 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1536 // this bit of code cleverly routes all module commands
1537 // to all remote severs *automatically* so that modules
1538 // can just handle commands locally, without having
1539 // to have any special provision in place for remote
1540 // commands and linking protocols.
1541 std::deque<std::string> params;
1543 for (int j = 0; j < pcnt; j++)
1545 if (strchr(parameters[j],' '))
1547 params.push_back(":" + std::string(parameters[j]));
1551 params.push_back(std::string(parameters[j]));
1554 DoOneToMany(user->nick,command,params);
1559 virtual void OnGetServerDescription(std::string servername,std::string &description)
1561 TreeServer* s = FindServer(servername);
1564 description = s->GetDesc();
1568 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1570 if (std::string(source->server) == Srv->GetServerName())
1572 std::deque<std::string> params;
1573 params.push_back(dest->nick);
1574 params.push_back(channel->name);
1575 DoOneToMany(source->nick,"INVITE",params);
1579 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1581 std::deque<std::string> params;
1582 params.push_back(chan->name);
1583 params.push_back(":"+topic);
1584 DoOneToMany(user->nick,"TOPIC",params);
1587 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1589 if (target_type == TYPE_USER)
1591 userrec* d = (userrec*)dest;
1592 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1594 std::deque<std::string> params;
1596 params.push_back(d->nick);
1597 params.push_back(":"+text);
1598 DoOneToOne(user->nick,"NOTICE",params,d->server);
1603 if (std::string(user->server) == Srv->GetServerName())
1605 chanrec *c = (chanrec*)dest;
1606 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1607 for (unsigned int i = 0; i < list.size(); i++)
1609 TreeSocket* Sock = list[i]->GetSocket();
1611 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1617 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1619 if (target_type == TYPE_USER)
1621 // route private messages which are targetted at clients only to the server
1622 // which needs to receive them
1623 userrec* d = (userrec*)dest;
1624 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1626 std::deque<std::string> params;
1628 params.push_back(d->nick);
1629 params.push_back(":"+text);
1630 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1635 if (std::string(user->server) == Srv->GetServerName())
1637 chanrec *c = (chanrec*)dest;
1638 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1639 for (unsigned int i = 0; i < list.size(); i++)
1641 TreeSocket* Sock = list[i]->GetSocket();
1643 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
1649 virtual void OnUserJoin(userrec* user, chanrec* channel)
1651 // Only do this for local users
1652 if (std::string(user->server) == Srv->GetServerName())
1654 std::deque<std::string> params;
1656 params.push_back(channel->name);
1659 // if the channel has a key, force the join by emulating the key.
1660 params.push_back(channel->key);
1662 DoOneToMany(user->nick,"JOIN",params);
1666 virtual void OnUserPart(userrec* user, chanrec* channel)
1668 if (std::string(user->server) == Srv->GetServerName())
1670 std::deque<std::string> params;
1672 params.push_back(channel->name);
1673 DoOneToMany(user->nick,"PART",params);
1677 virtual void OnUserConnect(userrec* user)
1679 char agestr[MAXBUF];
1680 if (std::string(user->server) == Srv->GetServerName())
1682 std::deque<std::string> params;
1683 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1685 params.push_back(agestr);
1686 params.push_back(user->nick);
1687 params.push_back(user->host);
1688 params.push_back(user->dhost);
1689 params.push_back(user->ident);
1690 params.push_back("+"+std::string(user->modes));
1691 params.push_back(user->ip);
1692 params.push_back(":"+std::string(user->fullname));
1693 DoOneToMany(Srv->GetServerName(),"NICK",params);
1697 virtual void OnUserQuit(userrec* user, std::string reason)
1699 if (std::string(user->server) == Srv->GetServerName())
1701 std::deque<std::string> params;
1702 params.push_back(":"+reason);
1703 DoOneToMany(user->nick,"QUIT",params);
1707 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1709 if (std::string(user->server) == Srv->GetServerName())
1711 std::deque<std::string> params;
1712 params.push_back(user->nick);
1713 DoOneToMany(oldnick,"NICK",params);
1717 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1719 if (std::string(source->server) == Srv->GetServerName())
1721 std::deque<std::string> params;
1722 params.push_back(chan->name);
1723 params.push_back(user->nick);
1724 params.push_back(":"+reason);
1725 DoOneToMany(source->nick,"KICK",params);
1729 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1731 std::deque<std::string> params;
1732 params.push_back(dest->nick);
1733 params.push_back(":"+reason);
1734 DoOneToMany(source->nick,"KILL",params);
1737 virtual void OnRehash(std::string parameter)
1739 if (parameter != "")
1741 std::deque<std::string> params;
1742 params.push_back(parameter);
1743 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1745 if (Srv->MatchText(Srv->GetServerName(),parameter))
1747 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1748 Srv->RehashServer();
1751 ReadConfiguration(false);
1754 // note: the protocol does not allow direct umode +o except
1755 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1757 virtual void OnOper(userrec* user, std::string opertype)
1759 if (std::string(user->server) == Srv->GetServerName())
1761 std::deque<std::string> params;
1762 params.push_back(opertype);
1763 DoOneToMany(user->nick,"OPERTYPE",params);
1767 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1769 if (std::string(user->server) == Srv->GetServerName())
1771 if (target_type == TYPE_USER)
1773 userrec* u = (userrec*)dest;
1774 std::deque<std::string> params;
1775 params.push_back(u->nick);
1776 params.push_back(text);
1777 DoOneToMany(user->nick,"MODE",params);
1781 chanrec* c = (chanrec*)dest;
1782 std::deque<std::string> params;
1783 params.push_back(c->name);
1784 params.push_back(text);
1785 DoOneToMany(user->nick,"MODE",params);
1790 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1792 TreeSocket* s = (TreeSocket*)opaque;
1795 if (target_type == TYPE_USER)
1797 userrec* u = (userrec*)target;
1798 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1802 chanrec* c = (chanrec*)target;
1803 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1808 virtual ~ModuleSpanningTree()
1813 virtual Version GetVersion()
1815 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1820 class ModuleSpanningTreeFactory : public ModuleFactory
1823 ModuleSpanningTreeFactory()
1827 ~ModuleSpanningTreeFactory()
1831 virtual Module * CreateModule()
1833 TreeProtocolModule = new ModuleSpanningTree;
1834 return TreeProtocolModule;
1840 extern "C" void * init_module( void )
1842 return new ModuleSpanningTreeFactory;