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 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
47 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
48 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
50 extern user_hash clientlist;
51 extern chan_hash chanlist;
56 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
57 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
58 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
59 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
64 std::vector<TreeServer*> Children;
65 std::string ServerName;
66 std::string ServerDesc;
67 std::string VersionString;
70 TreeSocket* Socket; // for directly connected servers this points at the socket object
80 UserCount = OperCount = 0;
83 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
87 UserCount = OperCount = 0;
90 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
93 UserCount = OperCount = 0;
98 return this->ServerName;
101 std::string GetDesc()
103 return this->ServerDesc;
106 std::string GetVersion()
108 return this->VersionString;
113 return this->UserCount;
118 return this->OperCount;
121 TreeSocket* GetSocket()
126 TreeServer* GetParent()
131 unsigned int ChildCount()
133 return Children.size();
136 TreeServer* GetChild(unsigned int n)
138 if (n < Children.size())
148 void AddChild(TreeServer* Child)
150 Children.push_back(Child);
153 bool DelChild(TreeServer* Child)
155 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
166 // removes child nodes of this node, and of that node, etc etc
169 bool stillchildren = true;
170 while (stillchildren)
172 stillchildren = false;
173 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
175 TreeServer* s = (TreeServer*)*a;
179 stillchildren = true;
193 std::string SendPass;
194 std::string RecvPass;
197 /* $ModDesc: Povides a spanning tree server link protocol */
201 TreeServer *TreeRoot;
202 std::vector<Link> LinkBlocks;
204 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
206 if (Current->GetName() == ServerName)
208 for (unsigned int q = 0; q < Current->ChildCount(); q++)
210 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
219 // Returns the locally connected server we must route a
220 // message through to reach server 'ServerName'. This
221 // only applies to one-to-one and not one-to-many routing.
222 TreeServer* BestRouteTo(std::string ServerName)
224 log(DEBUG,"Finding best route to %s",ServerName.c_str());
225 // first, find the server by recursively walking the tree
226 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
227 // did we find it? If not, they did something wrong, abort.
230 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
235 // The server exists, follow its parent nodes until
236 // the parent of the current is 'TreeRoot', we know
237 // then that this is a directly-connected server.
238 while ((Found) && (Found->GetParent() != TreeRoot))
240 Found = Found->GetParent();
242 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
247 bool LookForServer(TreeServer* Current, std::string ServerName)
249 if (ServerName == Current->GetName())
251 for (unsigned int q = 0; q < Current->ChildCount(); q++)
253 if (LookForServer(Current->GetChild(q),ServerName))
261 void RFindServer(TreeServer* Current, std::string ServerName)
263 if ((ServerName == Current->GetName()) && (!Found))
266 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
271 for (unsigned int q = 0; q < Current->ChildCount(); q++)
274 RFindServer(Current->GetChild(q),ServerName);
280 TreeServer* FindServer(std::string ServerName)
283 RFindServer(TreeRoot,ServerName);
287 bool IsServer(std::string ServerName)
289 return LookForServer(TreeRoot,ServerName);
292 class TreeSocket : public InspSocket
295 std::string in_buffer;
296 ServerState LinkState;
297 std::string InboundServerName;
298 std::string InboundDescription;
300 int num_lost_servers;
304 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
305 : InspSocket(host, port, listening, maxtime)
307 Srv->Log(DEBUG,"Create new listening");
309 this->LinkState = LISTENER;
312 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
313 : InspSocket(host, port, listening, maxtime)
315 Srv->Log(DEBUG,"Create new outbound");
317 this->LinkState = CONNECTING;
320 TreeSocket(int newfd, char* ip)
321 : InspSocket(newfd, ip)
323 Srv->Log(DEBUG,"Associate new inbound");
324 this->LinkState = WAIT_AUTH_1;
327 virtual bool OnConnected()
329 if (this->LinkState == CONNECTING)
331 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
332 // we should send our details here.
333 // if the other side is satisfied, they send theirs.
334 // we do not need to change state here.
335 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
337 if (x->Name == this->myhost)
339 // found who we're supposed to be connecting to, send the neccessary gubbins.
340 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
345 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
349 virtual void OnError(InspSocketError e)
353 virtual int OnDisconnect()
358 // recursively send the server tree with distances as hops
359 void SendServers(TreeServer* Current, TreeServer* s, int hops)
362 for (unsigned int q = 0; q < Current->ChildCount(); q++)
364 TreeServer* recursive_server = Current->GetChild(q);
365 if (recursive_server != s)
367 // :source.server SERVER server.name hops :Description
368 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
369 this->WriteLine(command);
370 // down to next level
371 this->SendServers(recursive_server, s, hops+1);
376 void SquitServer(TreeServer* Current)
378 // recursively squit the servers attached to 'Current'
379 for (unsigned int q = 0; q < Current->ChildCount(); q++)
381 TreeServer* recursive_server = Current->GetChild(q);
382 this->SquitServer(recursive_server);
384 // Now we've whacked the kids, whack self
385 log(DEBUG,"Deleted %s",Current->GetName().c_str());
387 bool quittingpeople = true;
388 while (quittingpeople)
390 quittingpeople = false;
391 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
393 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
395 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
396 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
398 quittingpeople = true;
405 void Squit(TreeServer* Current,std::string reason)
409 std::deque<std::string> params;
410 params.push_back(Current->GetName());
411 params.push_back(":"+reason);
412 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
413 if (Current->GetParent() == TreeRoot)
415 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
419 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
421 num_lost_servers = 0;
423 SquitServer(Current);
425 Current->GetParent()->DelChild(Current);
427 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
431 log(DEBUG,"Squit from unknown server");
435 bool ForceMode(std::string source, std::deque<std::string> params)
437 userrec* who = new userrec;
438 who->fd = FD_MAGIC_NUMBER;
439 if (params.size() < 2)
442 for (unsigned int q = 0; q < params.size(); q++)
444 modelist[q] = (char*)params[q].c_str();
446 Srv->SendMode(modelist,params.size(),who);
447 DoOneToAllButSender(source,"FMODE",params,source);
452 bool ForceTopic(std::string source, std::deque<std::string> params)
454 // FTOPIC %s %lu %s :%s
455 if (params.size() != 4)
457 std::string channel = params[0];
458 time_t ts = atoi(params[1].c_str());
459 std::string setby = params[2];
460 std::string topic = params[3];
462 chanrec* c = Srv->FindChannel(channel);
465 if ((ts >= c->topicset) || (!*c->topic))
467 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
468 strlcpy(c->setby,setby.c_str(),NICKMAX);
470 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
475 // all done, send it on its way
476 params[3] = ":" + params[3];
477 DoOneToAllButSender(source,"FTOPIC",params,source);
482 bool ForceJoin(std::string source, std::deque<std::string> params)
484 if (params.size() < 1)
486 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
488 // process one channel at a time, applying modes.
489 char* channel = (char*)params[channelnum].c_str();
490 char permissions = *channel;
507 userrec* who = Srv->FindNick(source);
511 chanrec* chan = Srv->FindChannel(channel);
512 if ((chan) && (*chan->key))
516 Srv->JoinUserToChannel(who,channel,key);
520 modelist[0] = channel;
522 modelist[2] = who->nick;
523 Srv->SendMode(modelist,3,who);
525 DoOneToAllButSender(source,"FJOIN",params,who->server);
531 bool IntroduceClient(std::string source, std::deque<std::string> params)
533 if (params.size() < 8)
535 // NICK age nick host dhost ident +modes ip :gecos
537 std::string nick = params[1];
538 std::string host = params[2];
539 std::string dhost = params[3];
540 std::string ident = params[4];
541 time_t age = atoi(params[0].c_str());
542 std::string modes = params[5];
543 if (*(modes.c_str()) == '+')
545 char* m = (char*)modes.c_str();
549 std::string ip = params[6];
550 std::string gecos = params[7];
551 char* tempnick = (char*)nick.c_str();
552 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
554 user_hash::iterator iter;
555 iter = clientlist.find(tempnick);
556 if (iter != clientlist.end())
559 log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
560 if (age <= iter->second->age)
562 // remote client is older
563 // if hosts are identical, kill the remote,
564 // else kill the local. We must send KILL for
565 // removal of remote users.
566 if (!strcmp(iter->second->host,host.c_str()))
568 // kill the remote by sending KILL,
569 // and ABORT to stop it being introduced here.
570 log(DEBUG,"**** LOCATION ONE");
571 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Killed (Nickname collision from "+Srv->GetServerName()+")");
576 log(DEBUG,"*** LOCATION TWO");
577 // kill our local and continue to let the remote be introduced
578 Srv->QuitUser(iter->second,"Killed (Nickname collision from "+source+")");
583 log(DEBUG,"*** LOCATION THREE");
584 // remote is newer, kill it and bail to stop it being introduced
585 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Killed (Nickname collision from "+Srv->GetServerName()+")");
590 clientlist[tempnick] = new userrec();
591 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
592 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
593 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
594 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
595 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
596 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
597 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
598 clientlist[tempnick]->registered = 7;
599 clientlist[tempnick]->signon = age;
600 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
601 for (int i = 0; i < MAXCHANS; i++)
603 clientlist[tempnick]->chans[i].channel = NULL;
604 clientlist[tempnick]->chans[i].uc_modes = 0;
606 params[7] = ":" + params[7];
607 DoOneToAllButSender(source,"NICK",params,source);
611 void SendChannelModes(TreeServer* Current)
614 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
616 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
617 this->WriteLine(data);
618 if (*c->second->topic)
620 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);
621 this->WriteLine(data);
623 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
625 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
626 this->WriteLine(data);
631 // send all users and their channels
632 void SendUsers(TreeServer* Current)
635 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
637 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);
638 this->WriteLine(data);
639 if (strchr(u->second->modes,'o'))
641 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
643 char* chl = chlist(u->second,u->second);
646 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
651 void DoBurst(TreeServer* s)
653 log(DEBUG,"Beginning network burst");
654 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
655 this->WriteLine("BURST");
657 this->SendServers(TreeRoot,s,1);
658 // Send users and their channels
660 // TODO: Send everything else (channel modes etc)
661 this->SendChannelModes(s);
662 this->WriteLine("ENDBURST");
665 virtual bool OnDataReady()
667 char* data = this->Read();
670 this->in_buffer += data;
671 while (in_buffer.find("\n") != std::string::npos)
673 char* line = (char*)in_buffer.c_str();
674 std::string ret = "";
675 while ((*line != '\n') && (strlen(line)))
680 if ((*line == '\n') || (*line == '\r'))
683 if (!this->ProcessLine(ret))
689 return (data != NULL);
692 int WriteLine(std::string line)
694 return this->Write(line + "\r\n");
697 bool Error(std::deque<std::string> params)
699 if (params.size() < 1)
701 std::string Errmsg = params[0];
702 std::string SName = myhost;
703 if (InboundServerName != "")
705 SName = InboundServerName;
707 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
708 // we will return false to cause the socket to close.
712 bool OperType(std::string prefix, std::deque<std::string> params)
714 if (params.size() != 1)
716 std::string opertype = params[0];
717 userrec* u = Srv->FindNick(prefix);
720 strlcpy(u->oper,opertype.c_str(),NICKMAX);
721 if (!strchr(u->modes,'o'))
723 strcat(u->modes,"o");
725 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
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 int hops = atoi(params[2].c_str());
759 std::string description = params[3];
762 this->WriteLine("ERROR :Protocol error - Introduced remote server with incorrect hopcount!");
765 TreeServer* ParentOfThis = FindServer(prefix);
768 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
771 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
772 ParentOfThis->AddChild(Node);
773 params[3] = ":" + params[3];
774 DoOneToAllButSender(prefix,"SERVER",params,prefix);
775 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
779 bool Outbound_Reply_Server(std::deque<std::string> params)
781 if (params.size() < 4)
783 std::string servername = params[0];
784 std::string password = params[1];
785 int hops = atoi(params[2].c_str());
788 this->WriteLine("ERROR :Server too far away for authentication");
791 std::string description = params[3];
792 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
794 if ((x->Name == servername) && (x->RecvPass == password))
796 // Begin the sync here. this kickstarts the
797 // other side, waiting in WAIT_AUTH_2 state,
798 // into starting their burst, as it shows
800 this->LinkState = CONNECTED;
801 // we should add the details of this server now
802 // to the servers tree, as a child of the root
804 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
805 TreeRoot->AddChild(Node);
806 params[3] = ":" + params[3];
807 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
812 this->WriteLine("ERROR :Invalid credentials");
816 bool Inbound_Server(std::deque<std::string> params)
818 if (params.size() < 4)
820 std::string servername = params[0];
821 std::string password = params[1];
822 int hops = atoi(params[2].c_str());
825 this->WriteLine("ERROR :Server too far away for authentication");
828 std::string description = params[3];
829 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
831 if ((x->Name == servername) && (x->RecvPass == password))
833 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
834 this->InboundServerName = servername;
835 this->InboundDescription = description;
836 // this is good. Send our details: Our server name and description and hopcount of 0,
837 // along with the sendpass from this block.
838 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
839 // move to the next state, we are now waiting for THEM.
840 this->LinkState = WAIT_AUTH_2;
844 this->WriteLine("ERROR :Invalid credentials");
848 std::deque<std::string> Split(std::string line, bool stripcolon)
850 std::deque<std::string> n;
851 std::stringstream s(line);
852 std::string param = "";
858 if ((param != "") && (param != "\n"))
860 if ((param.c_str()[0] == ':') && (item))
862 char* str = (char*)param.c_str();
872 param = param + " " + append;
883 bool ProcessLine(std::string line)
885 char* l = (char*)line.c_str();
886 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
887 l[strlen(l)-1] = '\0';
891 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
892 std::deque<std::string> params = this->Split(line,true);
893 std::string command = "";
894 std::string prefix = "";
895 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
899 char* pref = (char*)prefix.c_str();
911 switch (this->LinkState)
916 // Waiting for SERVER command from remote server. Server initiating
917 // the connection sends the first SERVER command, listening server
918 // replies with theirs if its happy, then if the initiator is happy,
919 // it starts to send its net sync, which starts the merge, otherwise
920 // it sends an ERROR.
921 if (command == "SERVER")
923 return this->Inbound_Server(params);
925 else if (command == "ERROR")
927 return this->Error(params);
931 // Waiting for start of other side's netmerge to say they liked our
933 if (command == "SERVER")
935 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
939 else if (command == "BURST")
941 this->LinkState = CONNECTED;
942 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
943 TreeRoot->AddChild(Node);
945 params.push_back(InboundServerName);
946 params.push_back("*");
947 params.push_back("1");
948 params.push_back(":"+InboundDescription);
949 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
952 else if (command == "ERROR")
954 return this->Error(params);
959 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
963 if (command == "SERVER")
965 // another server we connected to, which was in WAIT_AUTH_1 state,
966 // has just sent us their credentials. If we get this far, theyre
967 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
968 // if we're happy with this, we should send our netburst which
969 // kickstarts the merge.
970 return this->Outbound_Reply_Server(params);
974 // This is the 'authenticated' state, when all passwords
975 // have been exchanged and anything past this point is taken
977 std::string target = "";
978 if ((command == "NICK") && (params.size() > 1))
980 return this->IntroduceClient(prefix,params);
982 else if (command == "FJOIN")
984 return this->ForceJoin(prefix,params);
986 else if (command == "SERVER")
988 return this->RemoteServer(prefix,params);
990 else if (command == "OPERTYPE")
992 return this->OperType(prefix,params);
994 else if (command == "FMODE")
996 return this->ForceMode(prefix,params);
998 else if (command == "KILL")
1000 return this->RemoteKill(prefix,params);
1002 else if (command == "FTOPIC")
1004 return this->ForceTopic(prefix,params);
1006 else if (command == "SQUIT")
1008 if (params.size() == 2)
1010 this->Squit(FindServer(params[0]),params[1]);
1016 // not a special inter-server command.
1017 // Emulate the actual user doing the command,
1018 // this saves us having a huge ugly parser.
1019 userrec* who = Srv->FindNick(prefix);
1020 std::string sourceserv = this->myhost;
1021 if (this->InboundServerName != "")
1023 sourceserv = this->InboundServerName;
1028 target = who->server;
1029 char* strparams[127];
1030 for (unsigned int q = 0; q < params.size(); q++)
1032 strparams[q] = (char*)params[q].c_str();
1034 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1035 Srv->CallCommandHandler(command, strparams, params.size(), who);
1039 // its not a user. Its either a server, or somethings screwed up.
1040 if (IsServer(prefix))
1042 target = Srv->GetServerName();
1046 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1050 return DoOneToAllButSenderRaw(line,sourceserv);
1059 virtual void OnTimeout()
1061 if (this->LinkState == CONNECTING)
1063 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1067 virtual void OnClose()
1069 // Connection closed.
1070 // If the connection is fully up (state CONNECTED)
1071 // then propogate a netsplit to all peers.
1072 std::string quitserver = this->myhost;
1073 if (this->InboundServerName != "")
1075 quitserver = this->InboundServerName;
1077 TreeServer* s = FindServer(quitserver);
1080 Squit(s,"Remote host closed the connection");
1084 virtual int OnIncomingConnection(int newsock, char* ip)
1086 TreeSocket* s = new TreeSocket(newsock, ip);
1092 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1094 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1096 TreeServer* Route = TreeRoot->GetChild(x);
1097 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1099 TreeSocket* Sock = Route->GetSocket();
1100 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1101 Sock->WriteLine(data);
1107 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1109 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1110 // TODO: Special stuff with privmsg and notice
1111 std::string FullLine = ":" + prefix + " " + command;
1112 for (unsigned int x = 0; x < params.size(); x++)
1114 FullLine = FullLine + " " + params[x];
1116 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1118 TreeServer* Route = TreeRoot->GetChild(x);
1119 // Send the line IF:
1120 // The route has a socket (its a direct connection)
1121 // The route isnt the one to be omitted
1122 // The route isnt the path to the one to be omitted
1123 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1125 TreeSocket* Sock = Route->GetSocket();
1126 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1127 Sock->WriteLine(FullLine);
1133 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1135 std::string FullLine = ":" + prefix + " " + command;
1136 for (unsigned int x = 0; x < params.size(); x++)
1138 FullLine = FullLine + " " + params[x];
1140 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1142 TreeServer* Route = TreeRoot->GetChild(x);
1143 if (Route->GetSocket())
1145 TreeSocket* Sock = Route->GetSocket();
1146 Sock->WriteLine(FullLine);
1152 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1154 TreeServer* Route = BestRouteTo(target);
1157 std::string FullLine = ":" + prefix + " " + command;
1158 for (unsigned int x = 0; x < params.size(); x++)
1160 FullLine = FullLine + " " + params[x];
1162 if (Route->GetSocket())
1164 TreeSocket* Sock = Route->GetSocket();
1165 Sock->WriteLine(FullLine);
1171 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1177 class ModuleSpanningTree : public Module
1179 std::vector<TreeSocket*> Bindings;
1184 void ReadConfiguration(bool rebind)
1188 for (int j =0; j < Conf->Enumerate("bind"); j++)
1190 std::string Type = Conf->ReadValue("bind","type",j);
1191 std::string IP = Conf->ReadValue("bind","address",j);
1192 long Port = Conf->ReadInteger("bind","port",j,true);
1193 if (Type == "servers")
1199 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1200 if (listener->GetState() == I_LISTENING)
1202 Srv->AddSocket(listener);
1203 Bindings.push_back(listener);
1207 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1215 for (int j =0; j < Conf->Enumerate("link"); j++)
1218 L.Name = Conf->ReadValue("link","name",j);
1219 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1220 L.Port = Conf->ReadInteger("link","port",j,true);
1221 L.SendPass = Conf->ReadValue("link","sendpass",j);
1222 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1223 LinkBlocks.push_back(L);
1224 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1228 ModuleSpanningTree()
1231 Conf = new ConfigReader;
1234 // Create the root of the tree
1235 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1237 ReadConfiguration(true);
1240 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1242 std::string Parent = TreeRoot->GetName();
1243 if (Current->GetParent())
1245 Parent = Current->GetParent()->GetName();
1247 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1249 ShowLinks(Current->GetChild(q),user,hops+1);
1251 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1254 void HandleLinks(char** parameters, int pcnt, userrec* user)
1256 ShowLinks(TreeRoot,user,0);
1257 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1261 void HandleLusers(char** parameters, int pcnt, userrec* user)
1266 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1268 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1272 for (int t = 0; t < depth; t++)
1274 matrix[line][t] = ' ';
1276 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1278 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1280 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1285 // Ok, prepare to be confused.
1286 // After much mulling over how to approach this, it struck me that
1287 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1288 // keeping track of a ton of ascii characters, and line by line
1289 // under recursion working out where to place them using multiplications
1290 // and divisons, we instead render the map onto a backplane of characters
1291 // (a character matrix), then draw the branches as a series of "L" shapes
1292 // from the nodes. This is not only friendlier on CPU it uses less stack.
1294 void HandleMap(char** parameters, int pcnt, userrec* user)
1296 // This array represents a virtual screen which we will
1297 // "scratch" draw to, as the console device of an irc
1298 // client does not provide for a proper terminal.
1299 char matrix[128][80];
1300 for (unsigned int t = 0; t < 128; t++)
1302 matrix[t][0] = '\0';
1305 // The only recursive bit is called here.
1306 ShowMap(TreeRoot,user,0,matrix);
1307 // Process each line one by one. The algorithm has a limit of
1308 // 128 servers (which is far more than a spanning tree should have
1309 // anyway, so we're ok). This limit can be raised simply by making
1310 // the character matrix deeper, 128 rows taking 10k of memory.
1311 for (int l = 1; l < line; l++)
1313 // scan across the line looking for the start of the
1314 // servername (the recursive part of the algorithm has placed
1315 // the servers at indented positions depending on what they
1317 int first_nonspace = 0;
1318 while (matrix[l][first_nonspace] == ' ')
1323 // Draw the `- (corner) section: this may be overwritten by
1324 // another L shape passing along the same vertical pane, becoming
1325 // a |- (branch) section instead.
1326 matrix[l][first_nonspace] = '-';
1327 matrix[l][first_nonspace-1] = '`';
1329 // Draw upwards until we hit the parent server, causing possibly
1330 // other corners (`-) to become branches (|-)
1331 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1333 matrix[l2][first_nonspace-1] = '|';
1337 // dump the whole lot to the user. This is the easy bit, honest.
1338 for (int t = 0; t < line; t++)
1340 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1342 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1346 int HandleSquit(char** parameters, int pcnt, userrec* user)
1351 int HandleConnect(char** parameters, int pcnt, userrec* user)
1353 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1355 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1357 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1358 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1359 Srv->AddSocket(newsocket);
1363 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1367 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1369 if (command == "CONNECT")
1371 return this->HandleConnect(parameters,pcnt,user);
1373 else if (command == "SQUIT")
1375 return this->HandleSquit(parameters,pcnt,user);
1377 else if (command == "MAP")
1379 this->HandleMap(parameters,pcnt,user);
1382 else if (command == "LUSERS")
1384 this->HandleLusers(parameters,pcnt,user);
1387 else if (command == "LINKS")
1389 this->HandleLinks(parameters,pcnt,user);
1395 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1397 if (std::string(source->server) == Srv->GetServerName())
1399 std::deque<std::string> params;
1400 params.push_back(dest->nick);
1401 params.push_back(channel->name);
1402 DoOneToMany(source->nick,"INVITE",params);
1406 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1408 std::deque<std::string> params;
1409 params.push_back(chan->name);
1410 params.push_back(":"+topic);
1411 DoOneToMany(user->nick,"TOPIC",params);
1414 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1416 if (target_type == TYPE_USER)
1418 userrec* d = (userrec*)dest;
1419 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1421 std::deque<std::string> params;
1423 params.push_back(d->nick);
1424 params.push_back(":"+text);
1425 DoOneToOne(user->nick,"NOTICE",params,d->server);
1430 if (std::string(user->server) == Srv->GetServerName())
1432 chanrec *c = (chanrec*)dest;
1433 std::deque<std::string> params;
1434 params.push_back(c->name);
1435 params.push_back(":"+text);
1436 DoOneToMany(user->nick,"NOTICE",params);
1441 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1443 if (target_type == TYPE_USER)
1445 // route private messages which are targetted at clients only to the server
1446 // which needs to receive them
1447 userrec* d = (userrec*)dest;
1448 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1450 std::deque<std::string> params;
1452 params.push_back(d->nick);
1453 params.push_back(":"+text);
1454 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1459 if (std::string(user->server) == Srv->GetServerName())
1461 chanrec *c = (chanrec*)dest;
1462 std::deque<std::string> params;
1463 params.push_back(c->name);
1464 params.push_back(":"+text);
1465 DoOneToMany(user->nick,"PRIVMSG",params);
1470 virtual void OnUserJoin(userrec* user, chanrec* channel)
1472 // Only do this for local users
1473 if (std::string(user->server) == Srv->GetServerName())
1475 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1476 std::deque<std::string> params;
1478 params.push_back(channel->name);
1481 log(DEBUG,"**** With key %s",channel->key);
1482 // if the channel has a key, force the join by emulating the key.
1483 params.push_back(channel->key);
1485 DoOneToMany(user->nick,"JOIN",params);
1489 virtual void OnUserPart(userrec* user, chanrec* channel)
1491 if (std::string(user->server) == Srv->GetServerName())
1493 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1494 std::deque<std::string> params;
1496 params.push_back(channel->name);
1497 DoOneToMany(user->nick,"PART",params);
1501 virtual void OnUserConnect(userrec* user)
1503 char agestr[MAXBUF];
1504 if (std::string(user->server) == Srv->GetServerName())
1506 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1507 std::deque<std::string> params;
1508 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1510 params.push_back(agestr);
1511 params.push_back(user->nick);
1512 params.push_back(user->host);
1513 params.push_back(user->dhost);
1514 params.push_back(user->ident);
1515 params.push_back("+"+std::string(user->modes));
1516 params.push_back(user->ip);
1517 params.push_back(":"+std::string(user->fullname));
1518 DoOneToMany(Srv->GetServerName(),"NICK",params);
1522 virtual void OnUserQuit(userrec* user, std::string reason)
1524 if (std::string(user->server) == Srv->GetServerName())
1526 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1527 std::deque<std::string> params;
1528 params.push_back(":"+reason);
1529 DoOneToMany(user->nick,"QUIT",params);
1533 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1535 if (std::string(user->server) == Srv->GetServerName())
1537 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1538 std::deque<std::string> params;
1539 params.push_back(user->nick);
1540 DoOneToMany(oldnick,"NICK",params);
1544 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1546 if (std::string(source->server) == Srv->GetServerName())
1548 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1549 std::deque<std::string> params;
1550 params.push_back(chan->name);
1551 params.push_back(user->nick);
1552 params.push_back(":"+reason);
1553 DoOneToMany(source->nick,"KICK",params);
1557 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1559 std::deque<std::string> params;
1560 params.push_back(dest->nick);
1561 params.push_back(":"+reason);
1562 DoOneToMany(source->nick,"KILL",params);
1565 // note: the protocol does not allow direct umode +o except
1566 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1568 virtual void OnOper(userrec* user, std::string opertype)
1570 if (std::string(user->server) == Srv->GetServerName())
1572 std::deque<std::string> params;
1573 params.push_back(opertype);
1574 DoOneToMany(user->nick,"OPERTYPE",params);
1578 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1580 log(DEBUG,"*** ONMODE TRIGGER");
1581 if (std::string(user->server) == Srv->GetServerName())
1583 log(DEBUG,"*** LOCAL");
1584 if (target_type == TYPE_USER)
1586 userrec* u = (userrec*)dest;
1587 std::deque<std::string> params;
1588 params.push_back(u->nick);
1589 params.push_back(text);
1590 DoOneToMany(user->nick,"MODE",params);
1594 chanrec* c = (chanrec*)dest;
1595 std::deque<std::string> params;
1596 params.push_back(c->name);
1597 params.push_back(text);
1598 DoOneToMany(user->nick,"MODE",params);
1603 virtual ~ModuleSpanningTree()
1608 virtual Version GetVersion()
1610 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1615 class ModuleSpanningTreeFactory : public ModuleFactory
1618 ModuleSpanningTreeFactory()
1622 ~ModuleSpanningTreeFactory()
1626 virtual Module * CreateModule()
1628 return new ModuleSpanningTree;
1634 extern "C" void * init_module( void )
1636 return new ModuleSpanningTreeFactory;