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 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
49 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
50 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
52 extern user_hash clientlist;
53 extern chan_hash chanlist;
58 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
59 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
60 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
61 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
66 std::vector<TreeServer*> Children;
67 std::string ServerName;
68 std::string ServerDesc;
69 std::string VersionString;
72 TreeSocket* Socket; // for directly connected servers this points at the socket object
82 UserCount = OperCount = 0;
85 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
89 UserCount = OperCount = 0;
92 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
95 UserCount = OperCount = 0;
100 return this->ServerName;
103 std::string GetDesc()
105 return this->ServerDesc;
108 std::string GetVersion()
110 return this->VersionString;
115 return this->UserCount;
120 return this->OperCount;
123 TreeSocket* GetSocket()
128 TreeServer* GetParent()
133 unsigned int ChildCount()
135 return Children.size();
138 TreeServer* GetChild(unsigned int n)
140 if (n < Children.size())
150 void AddChild(TreeServer* Child)
152 Children.push_back(Child);
155 bool DelChild(TreeServer* Child)
157 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
168 // removes child nodes of this node, and of that node, etc etc
171 bool stillchildren = true;
172 while (stillchildren)
174 stillchildren = false;
175 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
177 TreeServer* s = (TreeServer*)*a;
181 stillchildren = true;
195 std::string SendPass;
196 std::string RecvPass;
199 /* $ModDesc: Povides a spanning tree server link protocol */
203 TreeServer *TreeRoot;
204 std::vector<Link> LinkBlocks;
206 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
208 if (Current->GetName() == ServerName)
210 for (unsigned int q = 0; q < Current->ChildCount(); q++)
212 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
221 // Returns the locally connected server we must route a
222 // message through to reach server 'ServerName'. This
223 // only applies to one-to-one and not one-to-many routing.
224 TreeServer* BestRouteTo(std::string ServerName)
226 log(DEBUG,"Finding best route to %s",ServerName.c_str());
227 if (ServerName.c_str() == TreeRoot->GetName())
229 log(DEBUG,"Cant route to myself!!!");
232 // first, find the server by recursively walking the tree
233 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
234 // did we find it? If not, they did something wrong, abort.
237 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
242 // The server exists, follow its parent nodes until
243 // the parent of the current is 'TreeRoot', we know
244 // then that this is a directly-connected server.
245 while ((Found) && (Found->GetParent() != TreeRoot))
247 Found = Found->GetParent();
249 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
254 bool LookForServer(TreeServer* Current, std::string ServerName)
256 if (ServerName == Current->GetName())
258 for (unsigned int q = 0; q < Current->ChildCount(); q++)
260 if (LookForServer(Current->GetChild(q),ServerName))
268 void RFindServer(TreeServer* Current, std::string ServerName)
270 if ((ServerName == Current->GetName()) && (!Found))
273 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
278 for (unsigned int q = 0; q < Current->ChildCount(); q++)
281 RFindServer(Current->GetChild(q),ServerName);
287 TreeServer* FindServer(std::string ServerName)
290 RFindServer(TreeRoot,ServerName);
294 bool IsServer(std::string ServerName)
296 return LookForServer(TreeRoot,ServerName);
299 class TreeSocket : public InspSocket
302 std::string in_buffer;
303 ServerState LinkState;
304 std::string InboundServerName;
305 std::string InboundDescription;
307 int num_lost_servers;
311 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
312 : InspSocket(host, port, listening, maxtime)
314 Srv->Log(DEBUG,"Create new listening");
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)
322 Srv->Log(DEBUG,"Create new outbound");
324 this->LinkState = CONNECTING;
327 TreeSocket(int newfd, char* ip)
328 : InspSocket(newfd, ip)
330 Srv->Log(DEBUG,"Associate new inbound");
331 this->LinkState = WAIT_AUTH_1;
334 virtual bool OnConnected()
336 if (this->LinkState == CONNECTING)
338 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
339 // we should send our details here.
340 // if the other side is satisfied, they send theirs.
341 // we do not need to change state here.
342 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
344 if (x->Name == this->myhost)
346 // found who we're supposed to be connecting to, send the neccessary gubbins.
347 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
352 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
356 virtual void OnError(InspSocketError e)
360 virtual int OnDisconnect()
365 // recursively send the server tree with distances as hops
366 void SendServers(TreeServer* Current, TreeServer* s, int hops)
369 for (unsigned int q = 0; q < Current->ChildCount(); q++)
371 TreeServer* recursive_server = Current->GetChild(q);
372 if (recursive_server != s)
374 // :source.server SERVER server.name hops :Description
375 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
376 this->WriteLine(command);
377 // down to next level
378 this->SendServers(recursive_server, s, hops+1);
383 void SquitServer(TreeServer* Current)
385 // recursively squit the servers attached to 'Current'
386 for (unsigned int q = 0; q < Current->ChildCount(); q++)
388 TreeServer* recursive_server = Current->GetChild(q);
389 this->SquitServer(recursive_server);
391 // Now we've whacked the kids, whack self
392 log(DEBUG,"Deleted %s",Current->GetName().c_str());
394 bool quittingpeople = true;
395 while (quittingpeople)
397 quittingpeople = false;
398 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
400 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
402 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
403 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
405 quittingpeople = true;
412 void Squit(TreeServer* Current,std::string reason)
416 std::deque<std::string> params;
417 params.push_back(Current->GetName());
418 params.push_back(":"+reason);
419 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
420 if (Current->GetParent() == TreeRoot)
422 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
426 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
428 num_lost_servers = 0;
430 SquitServer(Current);
432 Current->GetParent()->DelChild(Current);
434 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
438 log(DEBUG,"Squit from unknown server");
442 bool ForceMode(std::string source, std::deque<std::string> params)
444 userrec* who = new userrec;
445 who->fd = FD_MAGIC_NUMBER;
446 if (params.size() < 2)
449 for (unsigned int q = 0; q < params.size(); q++)
451 modelist[q] = (char*)params[q].c_str();
453 Srv->SendMode(modelist,params.size(),who);
454 DoOneToAllButSender(source,"FMODE",params,source);
459 bool ForceTopic(std::string source, std::deque<std::string> params)
461 // FTOPIC %s %lu %s :%s
462 if (params.size() != 4)
464 std::string channel = params[0];
465 time_t ts = atoi(params[1].c_str());
466 std::string setby = params[2];
467 std::string topic = params[3];
469 chanrec* c = Srv->FindChannel(channel);
472 if ((ts >= c->topicset) || (!*c->topic))
474 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
475 strlcpy(c->setby,setby.c_str(),NICKMAX);
477 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
482 // all done, send it on its way
483 params[3] = ":" + params[3];
484 DoOneToAllButSender(source,"FTOPIC",params,source);
489 bool ForceJoin(std::string source, std::deque<std::string> params)
491 if (params.size() < 1)
493 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
495 // process one channel at a time, applying modes.
496 char* channel = (char*)params[channelnum].c_str();
497 char permissions = *channel;
514 userrec* who = Srv->FindNick(source);
518 chanrec* chan = Srv->FindChannel(channel);
519 if ((chan) && (*chan->key))
523 Srv->JoinUserToChannel(who,channel,key);
527 modelist[0] = channel;
529 modelist[2] = who->nick;
530 Srv->SendMode(modelist,3,who);
532 DoOneToAllButSender(source,"FJOIN",params,who->server);
538 bool IntroduceClient(std::string source, std::deque<std::string> params)
540 if (params.size() < 8)
542 // NICK age nick host dhost ident +modes ip :gecos
544 std::string nick = params[1];
545 std::string host = params[2];
546 std::string dhost = params[3];
547 std::string ident = params[4];
548 time_t age = atoi(params[0].c_str());
549 std::string modes = params[5];
550 if (*(modes.c_str()) == '+')
552 char* m = (char*)modes.c_str();
556 std::string ip = params[6];
557 std::string gecos = params[7];
558 char* tempnick = (char*)nick.c_str();
559 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
561 user_hash::iterator iter;
562 iter = clientlist.find(tempnick);
563 if (iter != clientlist.end())
566 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);
567 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
571 clientlist[tempnick] = new userrec();
572 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
573 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
574 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
575 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
576 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
577 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
578 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
579 clientlist[tempnick]->registered = 7;
580 clientlist[tempnick]->signon = age;
581 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
582 for (int i = 0; i < MAXCHANS; i++)
584 clientlist[tempnick]->chans[i].channel = NULL;
585 clientlist[tempnick]->chans[i].uc_modes = 0;
587 params[7] = ":" + params[7];
588 DoOneToAllButSender(source,"NICK",params,source);
592 void SendChannelModes(TreeServer* Current)
595 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
597 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
598 this->WriteLine(data);
599 if (*c->second->topic)
601 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);
602 this->WriteLine(data);
604 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
606 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
607 this->WriteLine(data);
609 FOREACH_MOD OnSyncChannel(c->second,TreeProtocolModule,this);
613 // send all users and their channels
614 void SendUsers(TreeServer* Current)
617 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
619 if (u->second->registered == 7)
621 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);
622 this->WriteLine(data);
623 if (strchr(u->second->modes,'o'))
625 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
627 char* chl = chlist(u->second,u->second);
630 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
632 FOREACH_MOD OnSyncUser(u->second,TreeProtocolModule,this);
637 void DoBurst(TreeServer* s)
639 log(DEBUG,"Beginning network burst");
640 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
641 this->WriteLine("BURST");
643 this->SendServers(TreeRoot,s,1);
644 // Send users and their channels
646 // TODO: Send everything else (channel modes etc)
647 this->SendChannelModes(s);
648 this->WriteLine("ENDBURST");
651 virtual bool OnDataReady()
653 char* data = this->Read();
656 this->in_buffer += data;
657 while (in_buffer.find("\n") != std::string::npos)
659 char* line = (char*)in_buffer.c_str();
660 std::string ret = "";
661 while ((*line != '\n') && (strlen(line)))
666 if ((*line == '\n') || (*line == '\r'))
669 if (!this->ProcessLine(ret))
675 return (data != NULL);
678 int WriteLine(std::string line)
680 return this->Write(line + "\r\n");
683 bool Error(std::deque<std::string> params)
685 if (params.size() < 1)
687 std::string Errmsg = params[0];
688 std::string SName = myhost;
689 if (InboundServerName != "")
691 SName = InboundServerName;
693 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
694 // we will return false to cause the socket to close.
698 bool OperType(std::string prefix, std::deque<std::string> params)
700 if (params.size() != 1)
702 std::string opertype = params[0];
703 userrec* u = Srv->FindNick(prefix);
706 strlcpy(u->oper,opertype.c_str(),NICKMAX);
707 if (!strchr(u->modes,'o'))
709 strcat(u->modes,"o");
711 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
716 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
718 if (params.size() < 1)
720 std::string servermask = params[0];
721 if (Srv->MatchText(Srv->GetServerName(),servermask))
723 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
726 DoOneToAllButSender(prefix,"REHASH",params,prefix);
730 bool RemoteKill(std::string prefix, std::deque<std::string> params)
732 if (params.size() != 2)
734 std::string nick = params[0];
735 std::string reason = params[1];
736 userrec* u = Srv->FindNick(prefix);
737 userrec* who = Srv->FindNick(nick);
740 std::string sourceserv = prefix;
743 sourceserv = u->server;
745 params[1] = ":" + params[1];
746 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
747 Srv->QuitUser(who,reason);
752 bool RemoteServer(std::string prefix, std::deque<std::string> params)
754 if (params.size() < 4)
756 std::string servername = params[0];
757 std::string password = params[1];
758 // hopcount is not used for a remote server, we calculate this ourselves
759 std::string description = params[3];
760 TreeServer* ParentOfThis = FindServer(prefix);
763 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
766 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
767 ParentOfThis->AddChild(Node);
768 params[3] = ":" + params[3];
769 DoOneToAllButSender(prefix,"SERVER",params,prefix);
770 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
774 bool Outbound_Reply_Server(std::deque<std::string> params)
776 if (params.size() < 4)
778 std::string servername = params[0];
779 std::string password = params[1];
780 int hops = atoi(params[2].c_str());
783 this->WriteLine("ERROR :Server too far away for authentication");
786 std::string description = params[3];
787 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
789 if ((x->Name == servername) && (x->RecvPass == password))
791 // Begin the sync here. this kickstarts the
792 // other side, waiting in WAIT_AUTH_2 state,
793 // into starting their burst, as it shows
795 this->LinkState = CONNECTED;
796 // we should add the details of this server now
797 // to the servers tree, as a child of the root
799 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
800 TreeRoot->AddChild(Node);
801 params[3] = ":" + params[3];
802 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
807 this->WriteLine("ERROR :Invalid credentials");
811 bool Inbound_Server(std::deque<std::string> params)
813 if (params.size() < 4)
815 std::string servername = params[0];
816 std::string password = params[1];
817 int hops = atoi(params[2].c_str());
820 this->WriteLine("ERROR :Server too far away for authentication");
823 std::string description = params[3];
824 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
826 if ((x->Name == servername) && (x->RecvPass == password))
828 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
829 this->InboundServerName = servername;
830 this->InboundDescription = description;
831 // this is good. Send our details: Our server name and description and hopcount of 0,
832 // along with the sendpass from this block.
833 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
834 // move to the next state, we are now waiting for THEM.
835 this->LinkState = WAIT_AUTH_2;
839 this->WriteLine("ERROR :Invalid credentials");
843 std::deque<std::string> Split(std::string line, bool stripcolon)
845 std::deque<std::string> n;
846 std::stringstream s(line);
847 std::string param = "";
853 if ((param != "") && (param != "\n"))
855 if ((param.c_str()[0] == ':') && (item))
857 char* str = (char*)param.c_str();
867 param = param + " " + append;
878 bool ProcessLine(std::string line)
880 char* l = (char*)line.c_str();
881 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
882 l[strlen(l)-1] = '\0';
886 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
887 std::deque<std::string> params = this->Split(line,true);
888 std::string command = "";
889 std::string prefix = "";
890 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
894 char* pref = (char*)prefix.c_str();
906 switch (this->LinkState)
911 // Waiting for SERVER command from remote server. Server initiating
912 // the connection sends the first SERVER command, listening server
913 // replies with theirs if its happy, then if the initiator is happy,
914 // it starts to send its net sync, which starts the merge, otherwise
915 // it sends an ERROR.
916 if (command == "SERVER")
918 return this->Inbound_Server(params);
920 else if (command == "ERROR")
922 return this->Error(params);
926 // Waiting for start of other side's netmerge to say they liked our
928 if (command == "SERVER")
930 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
934 else if (command == "BURST")
936 this->LinkState = CONNECTED;
937 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
938 TreeRoot->AddChild(Node);
940 params.push_back(InboundServerName);
941 params.push_back("*");
942 params.push_back("1");
943 params.push_back(":"+InboundDescription);
944 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
947 else if (command == "ERROR")
949 return this->Error(params);
954 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
958 if (command == "SERVER")
960 // another server we connected to, which was in WAIT_AUTH_1 state,
961 // has just sent us their credentials. If we get this far, theyre
962 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
963 // if we're happy with this, we should send our netburst which
964 // kickstarts the merge.
965 return this->Outbound_Reply_Server(params);
969 // This is the 'authenticated' state, when all passwords
970 // have been exchanged and anything past this point is taken
972 std::string target = "";
973 if ((command == "NICK") && (params.size() > 1))
975 return this->IntroduceClient(prefix,params);
977 else if (command == "FJOIN")
979 return this->ForceJoin(prefix,params);
981 else if (command == "SERVER")
983 return this->RemoteServer(prefix,params);
985 else if (command == "OPERTYPE")
987 return this->OperType(prefix,params);
989 else if (command == "FMODE")
991 return this->ForceMode(prefix,params);
993 else if (command == "KILL")
995 return this->RemoteKill(prefix,params);
997 else if (command == "FTOPIC")
999 return this->ForceTopic(prefix,params);
1001 else if (command == "REHASH")
1003 return this->RemoteRehash(prefix,params);
1005 else if (command == "SQUIT")
1007 if (params.size() == 2)
1009 this->Squit(FindServer(params[0]),params[1]);
1015 // not a special inter-server command.
1016 // Emulate the actual user doing the command,
1017 // this saves us having a huge ugly parser.
1018 userrec* who = Srv->FindNick(prefix);
1019 std::string sourceserv = this->myhost;
1020 if (this->InboundServerName != "")
1022 sourceserv = this->InboundServerName;
1027 target = who->server;
1028 char* strparams[127];
1029 for (unsigned int q = 0; q < params.size(); q++)
1031 strparams[q] = (char*)params[q].c_str();
1033 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1034 Srv->CallCommandHandler(command, strparams, params.size(), who);
1038 // its not a user. Its either a server, or somethings screwed up.
1039 if (IsServer(prefix))
1041 target = Srv->GetServerName();
1045 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1049 return DoOneToAllButSenderRaw(line,sourceserv);
1058 virtual std::string GetName()
1060 std::string sourceserv = this->myhost;
1061 if (this->InboundServerName != "")
1063 sourceserv = this->InboundServerName;
1068 virtual void OnTimeout()
1070 if (this->LinkState == CONNECTING)
1072 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1076 virtual void OnClose()
1078 // Connection closed.
1079 // If the connection is fully up (state CONNECTED)
1080 // then propogate a netsplit to all peers.
1081 std::string quitserver = this->myhost;
1082 if (this->InboundServerName != "")
1084 quitserver = this->InboundServerName;
1086 TreeServer* s = FindServer(quitserver);
1089 Squit(s,"Remote host closed the connection");
1093 virtual int OnIncomingConnection(int newsock, char* ip)
1095 TreeSocket* s = new TreeSocket(newsock, ip);
1101 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1103 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1105 TreeServer* Route = TreeRoot->GetChild(x);
1106 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1108 TreeSocket* Sock = Route->GetSocket();
1109 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1110 Sock->WriteLine(data);
1116 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1118 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1119 // TODO: Special stuff with privmsg and notice
1120 std::string FullLine = ":" + prefix + " " + command;
1121 for (unsigned int x = 0; x < params.size(); x++)
1123 FullLine = FullLine + " " + params[x];
1125 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1127 TreeServer* Route = TreeRoot->GetChild(x);
1128 // Send the line IF:
1129 // The route has a socket (its a direct connection)
1130 // The route isnt the one to be omitted
1131 // The route isnt the path to the one to be omitted
1132 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1134 TreeSocket* Sock = Route->GetSocket();
1135 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1136 Sock->WriteLine(FullLine);
1142 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1144 Srv->Log(DEBUG,"ONETOMANY: "+command);
1145 std::string FullLine = ":" + prefix + " " + command;
1146 for (unsigned int x = 0; x < params.size(); x++)
1148 FullLine = FullLine + " " + params[x];
1150 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1152 TreeServer* Route = TreeRoot->GetChild(x);
1153 if (Route->GetSocket())
1155 TreeSocket* Sock = Route->GetSocket();
1156 Sock->WriteLine(FullLine);
1162 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1164 TreeServer* Route = BestRouteTo(target);
1167 std::string FullLine = ":" + prefix + " " + command;
1168 for (unsigned int x = 0; x < params.size(); x++)
1170 FullLine = FullLine + " " + params[x];
1172 if (Route->GetSocket())
1174 TreeSocket* Sock = Route->GetSocket();
1175 Sock->WriteLine(FullLine);
1181 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1187 class ModuleSpanningTree : public Module
1189 std::vector<TreeSocket*> Bindings;
1194 void ReadConfiguration(bool rebind)
1198 for (int j =0; j < Conf->Enumerate("bind"); j++)
1200 std::string Type = Conf->ReadValue("bind","type",j);
1201 std::string IP = Conf->ReadValue("bind","address",j);
1202 long Port = Conf->ReadInteger("bind","port",j,true);
1203 if (Type == "servers")
1209 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1210 if (listener->GetState() == I_LISTENING)
1212 Srv->AddSocket(listener);
1213 Bindings.push_back(listener);
1217 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1225 for (int j =0; j < Conf->Enumerate("link"); j++)
1228 L.Name = Conf->ReadValue("link","name",j);
1229 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1230 L.Port = Conf->ReadInteger("link","port",j,true);
1231 L.SendPass = Conf->ReadValue("link","sendpass",j);
1232 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1233 LinkBlocks.push_back(L);
1234 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1238 ModuleSpanningTree()
1241 Conf = new ConfigReader;
1244 // Create the root of the tree
1245 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1247 ReadConfiguration(true);
1250 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1252 std::string Parent = TreeRoot->GetName();
1253 if (Current->GetParent())
1255 Parent = Current->GetParent()->GetName();
1257 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1259 ShowLinks(Current->GetChild(q),user,hops+1);
1261 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1264 void HandleLinks(char** parameters, int pcnt, userrec* user)
1266 ShowLinks(TreeRoot,user,0);
1267 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1271 void HandleLusers(char** parameters, int pcnt, userrec* user)
1276 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1278 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1282 for (int t = 0; t < depth; t++)
1284 matrix[line][t] = ' ';
1286 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1288 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1290 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1295 // Ok, prepare to be confused.
1296 // After much mulling over how to approach this, it struck me that
1297 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1298 // keeping track of a ton of ascii characters, and line by line
1299 // under recursion working out where to place them using multiplications
1300 // and divisons, we instead render the map onto a backplane of characters
1301 // (a character matrix), then draw the branches as a series of "L" shapes
1302 // from the nodes. This is not only friendlier on CPU it uses less stack.
1304 void HandleMap(char** parameters, int pcnt, userrec* user)
1306 // This array represents a virtual screen which we will
1307 // "scratch" draw to, as the console device of an irc
1308 // client does not provide for a proper terminal.
1309 char matrix[128][80];
1310 for (unsigned int t = 0; t < 128; t++)
1312 matrix[t][0] = '\0';
1315 // The only recursive bit is called here.
1316 ShowMap(TreeRoot,user,0,matrix);
1317 // Process each line one by one. The algorithm has a limit of
1318 // 128 servers (which is far more than a spanning tree should have
1319 // anyway, so we're ok). This limit can be raised simply by making
1320 // the character matrix deeper, 128 rows taking 10k of memory.
1321 for (int l = 1; l < line; l++)
1323 // scan across the line looking for the start of the
1324 // servername (the recursive part of the algorithm has placed
1325 // the servers at indented positions depending on what they
1327 int first_nonspace = 0;
1328 while (matrix[l][first_nonspace] == ' ')
1333 // Draw the `- (corner) section: this may be overwritten by
1334 // another L shape passing along the same vertical pane, becoming
1335 // a |- (branch) section instead.
1336 matrix[l][first_nonspace] = '-';
1337 matrix[l][first_nonspace-1] = '`';
1339 // Draw upwards until we hit the parent server, causing possibly
1340 // other corners (`-) to become branches (|-)
1341 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1343 matrix[l2][first_nonspace-1] = '|';
1347 // dump the whole lot to the user. This is the easy bit, honest.
1348 for (int t = 0; t < line; t++)
1350 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1352 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1356 int HandleSquit(char** parameters, int pcnt, userrec* user)
1361 int HandleConnect(char** parameters, int pcnt, userrec* user)
1363 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1365 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1367 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1368 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1369 Srv->AddSocket(newsocket);
1373 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1377 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1379 if (command == "CONNECT")
1381 return this->HandleConnect(parameters,pcnt,user);
1383 else if (command == "SQUIT")
1385 return this->HandleSquit(parameters,pcnt,user);
1387 else if (command == "MAP")
1389 this->HandleMap(parameters,pcnt,user);
1392 else if (command == "LUSERS")
1394 this->HandleLusers(parameters,pcnt,user);
1397 else if (command == "LINKS")
1399 this->HandleLinks(parameters,pcnt,user);
1405 virtual void OnGetServerDescription(std::string servername,std::string &description)
1407 TreeServer* s = FindServer(servername);
1410 description = s->GetDesc();
1414 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1416 if (std::string(source->server) == Srv->GetServerName())
1418 std::deque<std::string> params;
1419 params.push_back(dest->nick);
1420 params.push_back(channel->name);
1421 DoOneToMany(source->nick,"INVITE",params);
1425 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1427 std::deque<std::string> params;
1428 params.push_back(chan->name);
1429 params.push_back(":"+topic);
1430 DoOneToMany(user->nick,"TOPIC",params);
1433 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1435 if (target_type == TYPE_USER)
1437 userrec* d = (userrec*)dest;
1438 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1440 std::deque<std::string> params;
1442 params.push_back(d->nick);
1443 params.push_back(":"+text);
1444 DoOneToOne(user->nick,"NOTICE",params,d->server);
1449 if (std::string(user->server) == Srv->GetServerName())
1451 chanrec *c = (chanrec*)dest;
1452 std::deque<std::string> params;
1453 params.push_back(c->name);
1454 params.push_back(":"+text);
1455 DoOneToMany(user->nick,"NOTICE",params);
1460 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1462 if (target_type == TYPE_USER)
1464 // route private messages which are targetted at clients only to the server
1465 // which needs to receive them
1466 userrec* d = (userrec*)dest;
1467 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1469 std::deque<std::string> params;
1471 params.push_back(d->nick);
1472 params.push_back(":"+text);
1473 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1478 if (std::string(user->server) == Srv->GetServerName())
1480 chanrec *c = (chanrec*)dest;
1481 std::deque<std::string> params;
1482 params.push_back(c->name);
1483 params.push_back(":"+text);
1484 DoOneToMany(user->nick,"PRIVMSG",params);
1489 virtual void OnUserJoin(userrec* user, chanrec* channel)
1491 // Only do this for local users
1492 if (std::string(user->server) == Srv->GetServerName())
1494 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1495 std::deque<std::string> params;
1497 params.push_back(channel->name);
1500 log(DEBUG,"**** With key %s",channel->key);
1501 // if the channel has a key, force the join by emulating the key.
1502 params.push_back(channel->key);
1504 DoOneToMany(user->nick,"JOIN",params);
1508 virtual void OnUserPart(userrec* user, chanrec* channel)
1510 if (std::string(user->server) == Srv->GetServerName())
1512 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1513 std::deque<std::string> params;
1515 params.push_back(channel->name);
1516 DoOneToMany(user->nick,"PART",params);
1520 virtual void OnUserConnect(userrec* user)
1522 char agestr[MAXBUF];
1523 if (std::string(user->server) == Srv->GetServerName())
1525 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1526 std::deque<std::string> params;
1527 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1529 params.push_back(agestr);
1530 params.push_back(user->nick);
1531 params.push_back(user->host);
1532 params.push_back(user->dhost);
1533 params.push_back(user->ident);
1534 params.push_back("+"+std::string(user->modes));
1535 params.push_back(user->ip);
1536 params.push_back(":"+std::string(user->fullname));
1537 DoOneToMany(Srv->GetServerName(),"NICK",params);
1541 virtual void OnUserQuit(userrec* user, std::string reason)
1543 if (std::string(user->server) == Srv->GetServerName())
1545 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1546 std::deque<std::string> params;
1547 params.push_back(":"+reason);
1548 DoOneToMany(user->nick,"QUIT",params);
1552 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1554 if (std::string(user->server) == Srv->GetServerName())
1556 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1557 std::deque<std::string> params;
1558 params.push_back(user->nick);
1559 DoOneToMany(oldnick,"NICK",params);
1563 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1565 if (std::string(source->server) == Srv->GetServerName())
1567 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1568 std::deque<std::string> params;
1569 params.push_back(chan->name);
1570 params.push_back(user->nick);
1571 params.push_back(":"+reason);
1572 DoOneToMany(source->nick,"KICK",params);
1576 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1578 std::deque<std::string> params;
1579 params.push_back(dest->nick);
1580 params.push_back(":"+reason);
1581 DoOneToMany(source->nick,"KILL",params);
1584 virtual void OnRehash(std::string parameter)
1586 if (parameter != "")
1588 std::deque<std::string> params;
1589 params.push_back(parameter);
1590 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1592 if (Srv->MatchText(Srv->GetServerName(),parameter))
1594 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1595 Srv->RehashServer();
1600 // note: the protocol does not allow direct umode +o except
1601 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1603 virtual void OnOper(userrec* user, std::string opertype)
1605 if (std::string(user->server) == Srv->GetServerName())
1607 std::deque<std::string> params;
1608 params.push_back(opertype);
1609 DoOneToMany(user->nick,"OPERTYPE",params);
1613 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1615 log(DEBUG,"*** ONMODE TRIGGER");
1616 if (std::string(user->server) == Srv->GetServerName())
1618 log(DEBUG,"*** LOCAL");
1619 if (target_type == TYPE_USER)
1621 userrec* u = (userrec*)dest;
1622 std::deque<std::string> params;
1623 params.push_back(u->nick);
1624 params.push_back(text);
1625 DoOneToMany(user->nick,"MODE",params);
1629 chanrec* c = (chanrec*)dest;
1630 std::deque<std::string> params;
1631 params.push_back(c->name);
1632 params.push_back(text);
1633 DoOneToMany(user->nick,"MODE",params);
1638 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline);
1640 TreeSocket* s = (TreeSocket*)opaque;
1643 if (target_type == TYPE_USER)
1645 userrec* u = (userrec*)target;
1646 opaque->WriteLine(":"+opaque->GetName()+" FMODE "+u->nick+" "+modeline);
1648 else (target_type == TYPE_CHANNEL)
1650 chanrec* c = (chanrec*)target;
1651 opaque->WriteLine(":"+opaque->GetName()+" FMODE "+c->name+" "+modeline);
1656 virtual ~ModuleSpanningTree()
1661 virtual Version GetVersion()
1663 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1668 class ModuleSpanningTreeFactory : public ModuleFactory
1671 ModuleSpanningTreeFactory()
1675 ~ModuleSpanningTreeFactory()
1679 virtual Module * CreateModule()
1681 return new ModuleSpanningTree;
1687 extern "C" void * init_module( void )
1689 TreeProtocolModule = new ModuleSpanningTreeFactory;
1690 return TreeProtocolModule;