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 static Module* TreeProtocolModule;
47 extern std::vector<Module*> modules;
48 extern std::vector<ircd_module*> factory;
51 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
53 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
54 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
56 extern user_hash clientlist;
57 extern chan_hash chanlist;
62 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
63 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
64 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
65 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
70 std::vector<TreeServer*> Children;
71 std::string ServerName;
72 std::string ServerDesc;
73 std::string VersionString;
76 TreeSocket* Socket; // for directly connected servers this points at the socket object
86 UserCount = OperCount = 0;
89 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
93 UserCount = OperCount = 0;
96 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
99 UserCount = OperCount = 0;
102 std::string GetName()
104 return this->ServerName;
107 std::string GetDesc()
109 return this->ServerDesc;
112 std::string GetVersion()
114 return this->VersionString;
119 return this->UserCount;
124 return this->OperCount;
127 TreeSocket* GetSocket()
132 TreeServer* GetParent()
137 unsigned int ChildCount()
139 return Children.size();
142 TreeServer* GetChild(unsigned int n)
144 if (n < Children.size())
154 void AddChild(TreeServer* Child)
156 Children.push_back(Child);
159 bool DelChild(TreeServer* Child)
161 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
172 // removes child nodes of this node, and of that node, etc etc
175 bool stillchildren = true;
176 while (stillchildren)
178 stillchildren = false;
179 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
181 TreeServer* s = (TreeServer*)*a;
185 stillchildren = true;
199 std::string SendPass;
200 std::string RecvPass;
203 /* $ModDesc: Povides a spanning tree server link protocol */
207 TreeServer *TreeRoot;
208 std::vector<Link> LinkBlocks;
210 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
212 if (Current->GetName() == ServerName)
214 for (unsigned int q = 0; q < Current->ChildCount(); q++)
216 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
225 // Returns the locally connected server we must route a
226 // message through to reach server 'ServerName'. This
227 // only applies to one-to-one and not one-to-many routing.
228 TreeServer* BestRouteTo(std::string ServerName)
230 log(DEBUG,"Finding best route to %s",ServerName.c_str());
231 if (ServerName.c_str() == TreeRoot->GetName())
233 log(DEBUG,"Cant route to myself!!!");
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.
241 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
246 // The server exists, follow its parent nodes until
247 // the parent of the current is 'TreeRoot', we know
248 // then that this is a directly-connected server.
249 while ((Found) && (Found->GetParent() != TreeRoot))
251 Found = Found->GetParent();
253 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
258 bool LookForServer(TreeServer* Current, std::string ServerName)
260 if (ServerName == Current->GetName())
262 for (unsigned int q = 0; q < Current->ChildCount(); q++)
264 if (LookForServer(Current->GetChild(q),ServerName))
272 void RFindServer(TreeServer* Current, std::string ServerName)
274 if ((ServerName == Current->GetName()) && (!Found))
277 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
282 for (unsigned int q = 0; q < Current->ChildCount(); q++)
285 RFindServer(Current->GetChild(q),ServerName);
291 TreeServer* FindServer(std::string ServerName)
294 RFindServer(TreeRoot,ServerName);
298 bool IsServer(std::string ServerName)
300 return LookForServer(TreeRoot,ServerName);
303 class TreeSocket : public InspSocket
306 std::string in_buffer;
307 ServerState LinkState;
308 std::string InboundServerName;
309 std::string InboundDescription;
311 int num_lost_servers;
315 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
316 : InspSocket(host, port, listening, maxtime)
318 Srv->Log(DEBUG,"Create new listening");
320 this->LinkState = LISTENER;
323 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
324 : InspSocket(host, port, listening, maxtime)
326 Srv->Log(DEBUG,"Create new outbound");
328 this->LinkState = CONNECTING;
331 TreeSocket(int newfd, char* ip)
332 : InspSocket(newfd, ip)
334 Srv->Log(DEBUG,"Associate new inbound");
335 this->LinkState = WAIT_AUTH_1;
338 virtual bool OnConnected()
340 if (this->LinkState == CONNECTING)
342 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
343 // we should send our details here.
344 // if the other side is satisfied, they send theirs.
345 // we do not need to change state here.
346 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
348 if (x->Name == this->myhost)
350 // found who we're supposed to be connecting to, send the neccessary gubbins.
351 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
356 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
360 virtual void OnError(InspSocketError e)
364 virtual int OnDisconnect()
369 // recursively send the server tree with distances as hops
370 void SendServers(TreeServer* Current, TreeServer* s, int hops)
373 for (unsigned int q = 0; q < Current->ChildCount(); q++)
375 TreeServer* recursive_server = Current->GetChild(q);
376 if (recursive_server != s)
378 // :source.server SERVER server.name hops :Description
379 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
380 this->WriteLine(command);
381 // down to next level
382 this->SendServers(recursive_server, s, hops+1);
387 void SquitServer(TreeServer* Current)
389 // recursively squit the servers attached to 'Current'
390 for (unsigned int q = 0; q < Current->ChildCount(); q++)
392 TreeServer* recursive_server = Current->GetChild(q);
393 this->SquitServer(recursive_server);
395 // Now we've whacked the kids, whack self
396 log(DEBUG,"Deleted %s",Current->GetName().c_str());
398 bool quittingpeople = true;
399 while (quittingpeople)
401 quittingpeople = false;
402 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
404 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
406 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
407 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
409 quittingpeople = true;
416 void Squit(TreeServer* Current,std::string reason)
420 std::deque<std::string> params;
421 params.push_back(Current->GetName());
422 params.push_back(":"+reason);
423 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
424 if (Current->GetParent() == TreeRoot)
426 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
430 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
432 num_lost_servers = 0;
434 SquitServer(Current);
436 Current->GetParent()->DelChild(Current);
438 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
442 log(DEBUG,"Squit from unknown server");
446 bool ForceMode(std::string source, std::deque<std::string> params)
448 userrec* who = new userrec;
449 who->fd = FD_MAGIC_NUMBER;
450 if (params.size() < 2)
453 for (unsigned int q = 0; q < params.size(); q++)
455 modelist[q] = (char*)params[q].c_str();
457 Srv->SendMode(modelist,params.size(),who);
458 DoOneToAllButSender(source,"FMODE",params,source);
463 bool ForceTopic(std::string source, std::deque<std::string> params)
465 // FTOPIC %s %lu %s :%s
466 if (params.size() != 4)
468 std::string channel = params[0];
469 time_t ts = atoi(params[1].c_str());
470 std::string setby = params[2];
471 std::string topic = params[3];
473 chanrec* c = Srv->FindChannel(channel);
476 if ((ts >= c->topicset) || (!*c->topic))
478 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
479 strlcpy(c->setby,setby.c_str(),NICKMAX);
481 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
486 // all done, send it on its way
487 params[3] = ":" + params[3];
488 DoOneToAllButSender(source,"FTOPIC",params,source);
493 bool ForceJoin(std::string source, std::deque<std::string> params)
495 if (params.size() < 1)
497 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
499 // process one channel at a time, applying modes.
500 char* channel = (char*)params[channelnum].c_str();
501 char permissions = *channel;
518 userrec* who = Srv->FindNick(source);
522 chanrec* chan = Srv->FindChannel(channel);
523 if ((chan) && (*chan->key))
527 Srv->JoinUserToChannel(who,channel,key);
531 modelist[0] = channel;
533 modelist[2] = who->nick;
534 Srv->SendMode(modelist,3,who);
536 DoOneToAllButSender(source,"FJOIN",params,who->server);
542 bool IntroduceClient(std::string source, std::deque<std::string> params)
544 if (params.size() < 8)
546 // NICK age nick host dhost ident +modes ip :gecos
548 std::string nick = params[1];
549 std::string host = params[2];
550 std::string dhost = params[3];
551 std::string ident = params[4];
552 time_t age = atoi(params[0].c_str());
553 std::string modes = params[5];
554 if (*(modes.c_str()) == '+')
556 char* m = (char*)modes.c_str();
560 std::string ip = params[6];
561 std::string gecos = params[7];
562 char* tempnick = (char*)nick.c_str();
563 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
565 user_hash::iterator iter;
566 iter = clientlist.find(tempnick);
567 if (iter != clientlist.end())
570 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);
571 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
575 clientlist[tempnick] = new userrec();
576 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
577 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
578 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
579 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
580 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
581 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
582 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
583 clientlist[tempnick]->registered = 7;
584 clientlist[tempnick]->signon = age;
585 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
586 for (int i = 0; i < MAXCHANS; i++)
588 clientlist[tempnick]->chans[i].channel = NULL;
589 clientlist[tempnick]->chans[i].uc_modes = 0;
591 params[7] = ":" + params[7];
592 DoOneToAllButSender(source,"NICK",params,source);
596 void SendChannelModes(TreeServer* Current)
599 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
601 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
602 this->WriteLine(data);
603 if (*c->second->topic)
605 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);
606 this->WriteLine(data);
608 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
610 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
611 this->WriteLine(data);
613 FOREACH_MOD OnSyncChannel(c->second,TreeProtocolModule,this);
617 // send all users and their channels
618 void SendUsers(TreeServer* Current)
621 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
623 if (u->second->registered == 7)
625 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);
626 this->WriteLine(data);
627 if (strchr(u->second->modes,'o'))
629 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
631 char* chl = chlist(u->second,u->second);
634 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
636 FOREACH_MOD OnSyncUser(u->second,TreeProtocolModule,this);
641 void DoBurst(TreeServer* s)
643 log(DEBUG,"Beginning network burst");
644 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
645 this->WriteLine("BURST");
647 this->SendServers(TreeRoot,s,1);
648 // Send users and their channels
650 // TODO: Send everything else (channel modes etc)
651 this->SendChannelModes(s);
652 this->WriteLine("ENDBURST");
655 virtual bool OnDataReady()
657 char* data = this->Read();
660 this->in_buffer += data;
661 while (in_buffer.find("\n") != std::string::npos)
663 char* line = (char*)in_buffer.c_str();
664 std::string ret = "";
665 while ((*line != '\n') && (strlen(line)))
670 if ((*line == '\n') || (*line == '\r'))
673 if (!this->ProcessLine(ret))
679 return (data != NULL);
682 int WriteLine(std::string line)
684 return this->Write(line + "\r\n");
687 bool Error(std::deque<std::string> params)
689 if (params.size() < 1)
691 std::string Errmsg = params[0];
692 std::string SName = myhost;
693 if (InboundServerName != "")
695 SName = InboundServerName;
697 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
698 // we will return false to cause the socket to close.
702 bool OperType(std::string prefix, std::deque<std::string> params)
704 if (params.size() != 1)
706 std::string opertype = params[0];
707 userrec* u = Srv->FindNick(prefix);
710 strlcpy(u->oper,opertype.c_str(),NICKMAX);
711 if (!strchr(u->modes,'o'))
713 strcat(u->modes,"o");
715 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
720 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
722 if (params.size() < 1)
724 std::string servermask = params[0];
725 if (Srv->MatchText(Srv->GetServerName(),servermask))
727 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
730 DoOneToAllButSender(prefix,"REHASH",params,prefix);
734 bool RemoteKill(std::string prefix, std::deque<std::string> params)
736 if (params.size() != 2)
738 std::string nick = params[0];
739 std::string reason = params[1];
740 userrec* u = Srv->FindNick(prefix);
741 userrec* who = Srv->FindNick(nick);
744 std::string sourceserv = prefix;
747 sourceserv = u->server;
749 params[1] = ":" + params[1];
750 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
751 Srv->QuitUser(who,reason);
756 bool RemoteServer(std::string prefix, std::deque<std::string> params)
758 if (params.size() < 4)
760 std::string servername = params[0];
761 std::string password = params[1];
762 // hopcount is not used for a remote server, we calculate this ourselves
763 std::string description = params[3];
764 TreeServer* ParentOfThis = FindServer(prefix);
767 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
770 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
771 ParentOfThis->AddChild(Node);
772 params[3] = ":" + params[3];
773 DoOneToAllButSender(prefix,"SERVER",params,prefix);
774 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
778 bool Outbound_Reply_Server(std::deque<std::string> params)
780 if (params.size() < 4)
782 std::string servername = params[0];
783 std::string password = params[1];
784 int hops = atoi(params[2].c_str());
787 this->WriteLine("ERROR :Server too far away for authentication");
790 std::string description = params[3];
791 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
793 if ((x->Name == servername) && (x->RecvPass == password))
795 // Begin the sync here. this kickstarts the
796 // other side, waiting in WAIT_AUTH_2 state,
797 // into starting their burst, as it shows
799 this->LinkState = CONNECTED;
800 // we should add the details of this server now
801 // to the servers tree, as a child of the root
803 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
804 TreeRoot->AddChild(Node);
805 params[3] = ":" + params[3];
806 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
811 this->WriteLine("ERROR :Invalid credentials");
815 bool Inbound_Server(std::deque<std::string> params)
817 if (params.size() < 4)
819 std::string servername = params[0];
820 std::string password = params[1];
821 int hops = atoi(params[2].c_str());
824 this->WriteLine("ERROR :Server too far away for authentication");
827 std::string description = params[3];
828 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
830 if ((x->Name == servername) && (x->RecvPass == password))
832 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
833 this->InboundServerName = servername;
834 this->InboundDescription = description;
835 // this is good. Send our details: Our server name and description and hopcount of 0,
836 // along with the sendpass from this block.
837 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
838 // move to the next state, we are now waiting for THEM.
839 this->LinkState = WAIT_AUTH_2;
843 this->WriteLine("ERROR :Invalid credentials");
847 std::deque<std::string> Split(std::string line, bool stripcolon)
849 std::deque<std::string> n;
850 std::stringstream s(line);
851 std::string param = "";
857 if ((param != "") && (param != "\n"))
859 if ((param.c_str()[0] == ':') && (item))
861 char* str = (char*)param.c_str();
871 param = param + " " + append;
882 bool ProcessLine(std::string line)
884 char* l = (char*)line.c_str();
885 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
886 l[strlen(l)-1] = '\0';
890 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
891 std::deque<std::string> params = this->Split(line,true);
892 std::string command = "";
893 std::string prefix = "";
894 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
898 char* pref = (char*)prefix.c_str();
910 switch (this->LinkState)
915 // Waiting for SERVER command from remote server. Server initiating
916 // the connection sends the first SERVER command, listening server
917 // replies with theirs if its happy, then if the initiator is happy,
918 // it starts to send its net sync, which starts the merge, otherwise
919 // it sends an ERROR.
920 if (command == "SERVER")
922 return this->Inbound_Server(params);
924 else if (command == "ERROR")
926 return this->Error(params);
930 // Waiting for start of other side's netmerge to say they liked our
932 if (command == "SERVER")
934 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
938 else if (command == "BURST")
940 this->LinkState = CONNECTED;
941 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
942 TreeRoot->AddChild(Node);
944 params.push_back(InboundServerName);
945 params.push_back("*");
946 params.push_back("1");
947 params.push_back(":"+InboundDescription);
948 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
951 else if (command == "ERROR")
953 return this->Error(params);
958 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
962 if (command == "SERVER")
964 // another server we connected to, which was in WAIT_AUTH_1 state,
965 // has just sent us their credentials. If we get this far, theyre
966 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
967 // if we're happy with this, we should send our netburst which
968 // kickstarts the merge.
969 return this->Outbound_Reply_Server(params);
973 // This is the 'authenticated' state, when all passwords
974 // have been exchanged and anything past this point is taken
976 std::string target = "";
977 if ((command == "NICK") && (params.size() > 1))
979 return this->IntroduceClient(prefix,params);
981 else if (command == "FJOIN")
983 return this->ForceJoin(prefix,params);
985 else if (command == "SERVER")
987 return this->RemoteServer(prefix,params);
989 else if (command == "OPERTYPE")
991 return this->OperType(prefix,params);
993 else if (command == "FMODE")
995 return this->ForceMode(prefix,params);
997 else if (command == "KILL")
999 return this->RemoteKill(prefix,params);
1001 else if (command == "FTOPIC")
1003 return this->ForceTopic(prefix,params);
1005 else if (command == "REHASH")
1007 return this->RemoteRehash(prefix,params);
1009 else if (command == "SQUIT")
1011 if (params.size() == 2)
1013 this->Squit(FindServer(params[0]),params[1]);
1019 // not a special inter-server command.
1020 // Emulate the actual user doing the command,
1021 // this saves us having a huge ugly parser.
1022 userrec* who = Srv->FindNick(prefix);
1023 std::string sourceserv = this->myhost;
1024 if (this->InboundServerName != "")
1026 sourceserv = this->InboundServerName;
1031 target = who->server;
1032 char* strparams[127];
1033 for (unsigned int q = 0; q < params.size(); q++)
1035 strparams[q] = (char*)params[q].c_str();
1037 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1038 Srv->CallCommandHandler(command, strparams, params.size(), who);
1042 // its not a user. Its either a server, or somethings screwed up.
1043 if (IsServer(prefix))
1045 target = Srv->GetServerName();
1049 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1053 return DoOneToAllButSenderRaw(line,sourceserv);
1062 virtual std::string GetName()
1064 std::string sourceserv = this->myhost;
1065 if (this->InboundServerName != "")
1067 sourceserv = this->InboundServerName;
1072 virtual void OnTimeout()
1074 if (this->LinkState == CONNECTING)
1076 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1080 virtual void OnClose()
1082 // Connection closed.
1083 // If the connection is fully up (state CONNECTED)
1084 // then propogate a netsplit to all peers.
1085 std::string quitserver = this->myhost;
1086 if (this->InboundServerName != "")
1088 quitserver = this->InboundServerName;
1090 TreeServer* s = FindServer(quitserver);
1093 Squit(s,"Remote host closed the connection");
1097 virtual int OnIncomingConnection(int newsock, char* ip)
1099 TreeSocket* s = new TreeSocket(newsock, ip);
1105 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1107 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1109 TreeServer* Route = TreeRoot->GetChild(x);
1110 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1112 TreeSocket* Sock = Route->GetSocket();
1113 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1114 Sock->WriteLine(data);
1120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1122 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1123 // TODO: Special stuff with privmsg and notice
1124 std::string FullLine = ":" + prefix + " " + command;
1125 for (unsigned int x = 0; x < params.size(); x++)
1127 FullLine = FullLine + " " + params[x];
1129 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1131 TreeServer* Route = TreeRoot->GetChild(x);
1132 // Send the line IF:
1133 // The route has a socket (its a direct connection)
1134 // The route isnt the one to be omitted
1135 // The route isnt the path to the one to be omitted
1136 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1138 TreeSocket* Sock = Route->GetSocket();
1139 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1140 Sock->WriteLine(FullLine);
1146 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1148 Srv->Log(DEBUG,"ONETOMANY: "+command);
1149 std::string FullLine = ":" + prefix + " " + command;
1150 for (unsigned int x = 0; x < params.size(); x++)
1152 FullLine = FullLine + " " + params[x];
1154 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1156 TreeServer* Route = TreeRoot->GetChild(x);
1157 if (Route->GetSocket())
1159 TreeSocket* Sock = Route->GetSocket();
1160 Sock->WriteLine(FullLine);
1166 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1168 TreeServer* Route = BestRouteTo(target);
1171 std::string FullLine = ":" + prefix + " " + command;
1172 for (unsigned int x = 0; x < params.size(); x++)
1174 FullLine = FullLine + " " + params[x];
1176 if (Route->GetSocket())
1178 TreeSocket* Sock = Route->GetSocket();
1179 Sock->WriteLine(FullLine);
1185 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1191 class ModuleSpanningTree : public Module
1193 std::vector<TreeSocket*> Bindings;
1198 void ReadConfiguration(bool rebind)
1202 for (int j =0; j < Conf->Enumerate("bind"); j++)
1204 std::string Type = Conf->ReadValue("bind","type",j);
1205 std::string IP = Conf->ReadValue("bind","address",j);
1206 long Port = Conf->ReadInteger("bind","port",j,true);
1207 if (Type == "servers")
1213 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1214 if (listener->GetState() == I_LISTENING)
1216 Srv->AddSocket(listener);
1217 Bindings.push_back(listener);
1221 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1229 for (int j =0; j < Conf->Enumerate("link"); j++)
1232 L.Name = Conf->ReadValue("link","name",j);
1233 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1234 L.Port = Conf->ReadInteger("link","port",j,true);
1235 L.SendPass = Conf->ReadValue("link","sendpass",j);
1236 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1237 LinkBlocks.push_back(L);
1238 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1242 ModuleSpanningTree()
1245 Conf = new ConfigReader;
1248 // Create the root of the tree
1249 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1251 ReadConfiguration(true);
1254 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1256 std::string Parent = TreeRoot->GetName();
1257 if (Current->GetParent())
1259 Parent = Current->GetParent()->GetName();
1261 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1263 ShowLinks(Current->GetChild(q),user,hops+1);
1265 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1268 void HandleLinks(char** parameters, int pcnt, userrec* user)
1270 ShowLinks(TreeRoot,user,0);
1271 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1275 void HandleLusers(char** parameters, int pcnt, userrec* user)
1280 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1282 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1286 for (int t = 0; t < depth; t++)
1288 matrix[line][t] = ' ';
1290 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1292 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1294 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1299 // Ok, prepare to be confused.
1300 // After much mulling over how to approach this, it struck me that
1301 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1302 // keeping track of a ton of ascii characters, and line by line
1303 // under recursion working out where to place them using multiplications
1304 // and divisons, we instead render the map onto a backplane of characters
1305 // (a character matrix), then draw the branches as a series of "L" shapes
1306 // from the nodes. This is not only friendlier on CPU it uses less stack.
1308 void HandleMap(char** parameters, int pcnt, userrec* user)
1310 // This array represents a virtual screen which we will
1311 // "scratch" draw to, as the console device of an irc
1312 // client does not provide for a proper terminal.
1313 char matrix[128][80];
1314 for (unsigned int t = 0; t < 128; t++)
1316 matrix[t][0] = '\0';
1319 // The only recursive bit is called here.
1320 ShowMap(TreeRoot,user,0,matrix);
1321 // Process each line one by one. The algorithm has a limit of
1322 // 128 servers (which is far more than a spanning tree should have
1323 // anyway, so we're ok). This limit can be raised simply by making
1324 // the character matrix deeper, 128 rows taking 10k of memory.
1325 for (int l = 1; l < line; l++)
1327 // scan across the line looking for the start of the
1328 // servername (the recursive part of the algorithm has placed
1329 // the servers at indented positions depending on what they
1331 int first_nonspace = 0;
1332 while (matrix[l][first_nonspace] == ' ')
1337 // Draw the `- (corner) section: this may be overwritten by
1338 // another L shape passing along the same vertical pane, becoming
1339 // a |- (branch) section instead.
1340 matrix[l][first_nonspace] = '-';
1341 matrix[l][first_nonspace-1] = '`';
1343 // Draw upwards until we hit the parent server, causing possibly
1344 // other corners (`-) to become branches (|-)
1345 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1347 matrix[l2][first_nonspace-1] = '|';
1351 // dump the whole lot to the user. This is the easy bit, honest.
1352 for (int t = 0; t < line; t++)
1354 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1356 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1360 int HandleSquit(char** parameters, int pcnt, userrec* user)
1365 int HandleConnect(char** parameters, int pcnt, userrec* user)
1367 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1369 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1371 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1372 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1373 Srv->AddSocket(newsocket);
1377 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1381 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1383 if (command == "CONNECT")
1385 return this->HandleConnect(parameters,pcnt,user);
1387 else if (command == "SQUIT")
1389 return this->HandleSquit(parameters,pcnt,user);
1391 else if (command == "MAP")
1393 this->HandleMap(parameters,pcnt,user);
1396 else if (command == "LUSERS")
1398 this->HandleLusers(parameters,pcnt,user);
1401 else if (command == "LINKS")
1403 this->HandleLinks(parameters,pcnt,user);
1409 virtual void OnGetServerDescription(std::string servername,std::string &description)
1411 TreeServer* s = FindServer(servername);
1414 description = s->GetDesc();
1418 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1420 if (std::string(source->server) == Srv->GetServerName())
1422 std::deque<std::string> params;
1423 params.push_back(dest->nick);
1424 params.push_back(channel->name);
1425 DoOneToMany(source->nick,"INVITE",params);
1429 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1431 std::deque<std::string> params;
1432 params.push_back(chan->name);
1433 params.push_back(":"+topic);
1434 DoOneToMany(user->nick,"TOPIC",params);
1437 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1439 if (target_type == TYPE_USER)
1441 userrec* d = (userrec*)dest;
1442 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1444 std::deque<std::string> params;
1446 params.push_back(d->nick);
1447 params.push_back(":"+text);
1448 DoOneToOne(user->nick,"NOTICE",params,d->server);
1453 if (std::string(user->server) == Srv->GetServerName())
1455 chanrec *c = (chanrec*)dest;
1456 std::deque<std::string> params;
1457 params.push_back(c->name);
1458 params.push_back(":"+text);
1459 DoOneToMany(user->nick,"NOTICE",params);
1464 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1466 if (target_type == TYPE_USER)
1468 // route private messages which are targetted at clients only to the server
1469 // which needs to receive them
1470 userrec* d = (userrec*)dest;
1471 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1473 std::deque<std::string> params;
1475 params.push_back(d->nick);
1476 params.push_back(":"+text);
1477 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1482 if (std::string(user->server) == Srv->GetServerName())
1484 chanrec *c = (chanrec*)dest;
1485 std::deque<std::string> params;
1486 params.push_back(c->name);
1487 params.push_back(":"+text);
1488 DoOneToMany(user->nick,"PRIVMSG",params);
1493 virtual void OnUserJoin(userrec* user, chanrec* channel)
1495 // Only do this for local users
1496 if (std::string(user->server) == Srv->GetServerName())
1498 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1499 std::deque<std::string> params;
1501 params.push_back(channel->name);
1504 log(DEBUG,"**** With key %s",channel->key);
1505 // if the channel has a key, force the join by emulating the key.
1506 params.push_back(channel->key);
1508 DoOneToMany(user->nick,"JOIN",params);
1512 virtual void OnUserPart(userrec* user, chanrec* channel)
1514 if (std::string(user->server) == Srv->GetServerName())
1516 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1517 std::deque<std::string> params;
1519 params.push_back(channel->name);
1520 DoOneToMany(user->nick,"PART",params);
1524 virtual void OnUserConnect(userrec* user)
1526 char agestr[MAXBUF];
1527 if (std::string(user->server) == Srv->GetServerName())
1529 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1530 std::deque<std::string> params;
1531 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1533 params.push_back(agestr);
1534 params.push_back(user->nick);
1535 params.push_back(user->host);
1536 params.push_back(user->dhost);
1537 params.push_back(user->ident);
1538 params.push_back("+"+std::string(user->modes));
1539 params.push_back(user->ip);
1540 params.push_back(":"+std::string(user->fullname));
1541 DoOneToMany(Srv->GetServerName(),"NICK",params);
1545 virtual void OnUserQuit(userrec* user, std::string reason)
1547 if (std::string(user->server) == Srv->GetServerName())
1549 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1550 std::deque<std::string> params;
1551 params.push_back(":"+reason);
1552 DoOneToMany(user->nick,"QUIT",params);
1556 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1558 if (std::string(user->server) == Srv->GetServerName())
1560 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1561 std::deque<std::string> params;
1562 params.push_back(user->nick);
1563 DoOneToMany(oldnick,"NICK",params);
1567 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1569 if (std::string(source->server) == Srv->GetServerName())
1571 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1572 std::deque<std::string> params;
1573 params.push_back(chan->name);
1574 params.push_back(user->nick);
1575 params.push_back(":"+reason);
1576 DoOneToMany(source->nick,"KICK",params);
1580 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1582 std::deque<std::string> params;
1583 params.push_back(dest->nick);
1584 params.push_back(":"+reason);
1585 DoOneToMany(source->nick,"KILL",params);
1588 virtual void OnRehash(std::string parameter)
1590 if (parameter != "")
1592 std::deque<std::string> params;
1593 params.push_back(parameter);
1594 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1596 if (Srv->MatchText(Srv->GetServerName(),parameter))
1598 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1599 Srv->RehashServer();
1604 // note: the protocol does not allow direct umode +o except
1605 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1607 virtual void OnOper(userrec* user, std::string opertype)
1609 if (std::string(user->server) == Srv->GetServerName())
1611 std::deque<std::string> params;
1612 params.push_back(opertype);
1613 DoOneToMany(user->nick,"OPERTYPE",params);
1617 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1619 log(DEBUG,"*** ONMODE TRIGGER");
1620 if (std::string(user->server) == Srv->GetServerName())
1622 log(DEBUG,"*** LOCAL");
1623 if (target_type == TYPE_USER)
1625 userrec* u = (userrec*)dest;
1626 std::deque<std::string> params;
1627 params.push_back(u->nick);
1628 params.push_back(text);
1629 DoOneToMany(user->nick,"MODE",params);
1633 chanrec* c = (chanrec*)dest;
1634 std::deque<std::string> params;
1635 params.push_back(c->name);
1636 params.push_back(text);
1637 DoOneToMany(user->nick,"MODE",params);
1642 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1644 TreeSocket* s = (TreeSocket*)opaque;
1647 if (target_type == TYPE_USER)
1649 userrec* u = (userrec*)target;
1650 opaque->WriteLine(":"+opaque->GetName()+" FMODE "+u->nick+" "+modeline);
1652 else (target_type == TYPE_CHANNEL)
1654 chanrec* c = (chanrec*)target;
1655 opaque->WriteLine(":"+opaque->GetName()+" FMODE "+c->name+" "+modeline);
1660 virtual ~ModuleSpanningTree()
1665 virtual Version GetVersion()
1667 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1672 class ModuleSpanningTreeFactory : public ModuleFactory
1675 ModuleSpanningTreeFactory()
1679 ~ModuleSpanningTreeFactory()
1683 virtual Module * CreateModule()
1685 return new ModuleSpanningTree;
1691 extern "C" void * init_module( void )
1693 TreeProtocolModule = new ModuleSpanningTreeFactory;
1694 return TreeProtocolModule;