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 if (ServerName.c_str() == TreeRoot->GetName())
227 log(DEBUG,"Cant route to myself!!!");
230 // first, find the server by recursively walking the tree
231 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
232 // did we find it? If not, they did something wrong, abort.
235 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
240 // The server exists, follow its parent nodes until
241 // the parent of the current is 'TreeRoot', we know
242 // then that this is a directly-connected server.
243 while ((Found) && (Found->GetParent() != TreeRoot))
245 Found = Found->GetParent();
247 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
252 bool LookForServer(TreeServer* Current, std::string ServerName)
254 if (ServerName == Current->GetName())
256 for (unsigned int q = 0; q < Current->ChildCount(); q++)
258 if (LookForServer(Current->GetChild(q),ServerName))
266 void RFindServer(TreeServer* Current, std::string ServerName)
268 if ((ServerName == Current->GetName()) && (!Found))
271 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
276 for (unsigned int q = 0; q < Current->ChildCount(); q++)
279 RFindServer(Current->GetChild(q),ServerName);
285 TreeServer* FindServer(std::string ServerName)
288 RFindServer(TreeRoot,ServerName);
292 bool IsServer(std::string ServerName)
294 return LookForServer(TreeRoot,ServerName);
297 class TreeSocket : public InspSocket
300 std::string in_buffer;
301 ServerState LinkState;
302 std::string InboundServerName;
303 std::string InboundDescription;
305 int num_lost_servers;
309 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
310 : InspSocket(host, port, listening, maxtime)
312 Srv->Log(DEBUG,"Create new listening");
314 this->LinkState = LISTENER;
317 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
318 : InspSocket(host, port, listening, maxtime)
320 Srv->Log(DEBUG,"Create new outbound");
322 this->LinkState = CONNECTING;
325 TreeSocket(int newfd, char* ip)
326 : InspSocket(newfd, ip)
328 Srv->Log(DEBUG,"Associate new inbound");
329 this->LinkState = WAIT_AUTH_1;
332 virtual bool OnConnected()
334 if (this->LinkState == CONNECTING)
336 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
337 // we should send our details here.
338 // if the other side is satisfied, they send theirs.
339 // we do not need to change state here.
340 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
342 if (x->Name == this->myhost)
344 // found who we're supposed to be connecting to, send the neccessary gubbins.
345 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
350 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
354 virtual void OnError(InspSocketError e)
358 virtual int OnDisconnect()
363 // recursively send the server tree with distances as hops
364 void SendServers(TreeServer* Current, TreeServer* s, int hops)
367 for (unsigned int q = 0; q < Current->ChildCount(); q++)
369 TreeServer* recursive_server = Current->GetChild(q);
370 if (recursive_server != s)
372 // :source.server SERVER server.name hops :Description
373 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
374 this->WriteLine(command);
375 // down to next level
376 this->SendServers(recursive_server, s, hops+1);
381 void SquitServer(TreeServer* Current)
383 // recursively squit the servers attached to 'Current'
384 for (unsigned int q = 0; q < Current->ChildCount(); q++)
386 TreeServer* recursive_server = Current->GetChild(q);
387 this->SquitServer(recursive_server);
389 // Now we've whacked the kids, whack self
390 log(DEBUG,"Deleted %s",Current->GetName().c_str());
392 bool quittingpeople = true;
393 while (quittingpeople)
395 quittingpeople = false;
396 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
398 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
400 log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
401 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
403 quittingpeople = true;
410 void Squit(TreeServer* Current,std::string reason)
414 std::deque<std::string> params;
415 params.push_back(Current->GetName());
416 params.push_back(":"+reason);
417 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
418 if (Current->GetParent() == TreeRoot)
420 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
424 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
426 num_lost_servers = 0;
428 SquitServer(Current);
430 Current->GetParent()->DelChild(Current);
432 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
436 log(DEBUG,"Squit from unknown server");
440 bool ForceMode(std::string source, std::deque<std::string> params)
442 userrec* who = new userrec;
443 who->fd = FD_MAGIC_NUMBER;
444 if (params.size() < 2)
447 for (unsigned int q = 0; q < params.size(); q++)
449 modelist[q] = (char*)params[q].c_str();
451 Srv->SendMode(modelist,params.size(),who);
452 DoOneToAllButSender(source,"FMODE",params,source);
457 bool ForceTopic(std::string source, std::deque<std::string> params)
459 // FTOPIC %s %lu %s :%s
460 if (params.size() != 4)
462 std::string channel = params[0];
463 time_t ts = atoi(params[1].c_str());
464 std::string setby = params[2];
465 std::string topic = params[3];
467 chanrec* c = Srv->FindChannel(channel);
470 if ((ts >= c->topicset) || (!*c->topic))
472 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
473 strlcpy(c->setby,setby.c_str(),NICKMAX);
475 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
480 // all done, send it on its way
481 params[3] = ":" + params[3];
482 DoOneToAllButSender(source,"FTOPIC",params,source);
487 bool ForceJoin(std::string source, std::deque<std::string> params)
489 if (params.size() < 1)
491 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
493 // process one channel at a time, applying modes.
494 char* channel = (char*)params[channelnum].c_str();
495 char permissions = *channel;
512 userrec* who = Srv->FindNick(source);
516 chanrec* chan = Srv->FindChannel(channel);
517 if ((chan) && (*chan->key))
521 Srv->JoinUserToChannel(who,channel,key);
525 modelist[0] = channel;
527 modelist[2] = who->nick;
528 Srv->SendMode(modelist,3,who);
530 DoOneToAllButSender(source,"FJOIN",params,who->server);
536 bool IntroduceClient(std::string source, std::deque<std::string> params)
538 if (params.size() < 8)
540 // NICK age nick host dhost ident +modes ip :gecos
542 std::string nick = params[1];
543 std::string host = params[2];
544 std::string dhost = params[3];
545 std::string ident = params[4];
546 time_t age = atoi(params[0].c_str());
547 std::string modes = params[5];
548 if (*(modes.c_str()) == '+')
550 char* m = (char*)modes.c_str();
554 std::string ip = params[6];
555 std::string gecos = params[7];
556 char* tempnick = (char*)nick.c_str();
557 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
559 user_hash::iterator iter;
560 iter = clientlist.find(tempnick);
561 if (iter != clientlist.end())
564 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);
565 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
569 clientlist[tempnick] = new userrec();
570 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
571 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
572 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
573 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
574 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
575 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
576 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
577 clientlist[tempnick]->registered = 7;
578 clientlist[tempnick]->signon = age;
579 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
580 for (int i = 0; i < MAXCHANS; i++)
582 clientlist[tempnick]->chans[i].channel = NULL;
583 clientlist[tempnick]->chans[i].uc_modes = 0;
585 params[7] = ":" + params[7];
586 DoOneToAllButSender(source,"NICK",params,source);
590 void SendChannelModes(TreeServer* Current)
593 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
595 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
596 this->WriteLine(data);
597 if (*c->second->topic)
599 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);
600 this->WriteLine(data);
602 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
604 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
605 this->WriteLine(data);
610 // send all users and their channels
611 void SendUsers(TreeServer* Current)
614 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
616 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);
617 this->WriteLine(data);
618 if (strchr(u->second->modes,'o'))
620 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
622 char* chl = chlist(u->second,u->second);
625 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
630 void DoBurst(TreeServer* s)
632 log(DEBUG,"Beginning network burst");
633 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
634 this->WriteLine("BURST");
636 this->SendServers(TreeRoot,s,1);
637 // Send users and their channels
639 // TODO: Send everything else (channel modes etc)
640 this->SendChannelModes(s);
641 this->WriteLine("ENDBURST");
644 virtual bool OnDataReady()
646 char* data = this->Read();
649 this->in_buffer += data;
650 while (in_buffer.find("\n") != std::string::npos)
652 char* line = (char*)in_buffer.c_str();
653 std::string ret = "";
654 while ((*line != '\n') && (strlen(line)))
659 if ((*line == '\n') || (*line == '\r'))
662 if (!this->ProcessLine(ret))
668 return (data != NULL);
671 int WriteLine(std::string line)
673 return this->Write(line + "\r\n");
676 bool Error(std::deque<std::string> params)
678 if (params.size() < 1)
680 std::string Errmsg = params[0];
681 std::string SName = myhost;
682 if (InboundServerName != "")
684 SName = InboundServerName;
686 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
687 // we will return false to cause the socket to close.
691 bool OperType(std::string prefix, std::deque<std::string> params)
693 if (params.size() != 1)
695 std::string opertype = params[0];
696 userrec* u = Srv->FindNick(prefix);
699 strlcpy(u->oper,opertype.c_str(),NICKMAX);
700 if (!strchr(u->modes,'o'))
702 strcat(u->modes,"o");
704 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
709 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
711 if (params.size() < 1)
713 std::string servermask = params[0];
714 if (Srv->MatchText(Srv->GetServerName(),servermask))
716 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
719 DoOneToAllButSender(prefix,"REHASH",params,prefix);
723 bool RemoteKill(std::string prefix, std::deque<std::string> params)
725 if (params.size() != 2)
727 std::string nick = params[0];
728 std::string reason = params[1];
729 userrec* u = Srv->FindNick(prefix);
730 userrec* who = Srv->FindNick(nick);
733 std::string sourceserv = prefix;
736 sourceserv = u->server;
738 params[1] = ":" + params[1];
739 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
740 Srv->QuitUser(who,reason);
745 bool RemoteServer(std::string prefix, std::deque<std::string> params)
747 if (params.size() < 4)
749 std::string servername = params[0];
750 std::string password = params[1];
751 int hops = atoi(params[2].c_str());
752 std::string description = params[3];
755 this->WriteLine("ERROR :Protocol error - Introduced remote server with incorrect hopcount!");
758 TreeServer* ParentOfThis = FindServer(prefix);
761 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
764 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
765 ParentOfThis->AddChild(Node);
766 params[3] = ":" + params[3];
767 DoOneToAllButSender(prefix,"SERVER",params,prefix);
768 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
772 bool Outbound_Reply_Server(std::deque<std::string> params)
774 if (params.size() < 4)
776 std::string servername = params[0];
777 std::string password = params[1];
778 int hops = atoi(params[2].c_str());
781 this->WriteLine("ERROR :Server too far away for authentication");
784 std::string description = params[3];
785 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
787 if ((x->Name == servername) && (x->RecvPass == password))
789 // Begin the sync here. this kickstarts the
790 // other side, waiting in WAIT_AUTH_2 state,
791 // into starting their burst, as it shows
793 this->LinkState = CONNECTED;
794 // we should add the details of this server now
795 // to the servers tree, as a child of the root
797 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
798 TreeRoot->AddChild(Node);
799 params[3] = ":" + params[3];
800 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
805 this->WriteLine("ERROR :Invalid credentials");
809 bool Inbound_Server(std::deque<std::string> params)
811 if (params.size() < 4)
813 std::string servername = params[0];
814 std::string password = params[1];
815 int hops = atoi(params[2].c_str());
818 this->WriteLine("ERROR :Server too far away for authentication");
821 std::string description = params[3];
822 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
824 if ((x->Name == servername) && (x->RecvPass == password))
826 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
827 this->InboundServerName = servername;
828 this->InboundDescription = description;
829 // this is good. Send our details: Our server name and description and hopcount of 0,
830 // along with the sendpass from this block.
831 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
832 // move to the next state, we are now waiting for THEM.
833 this->LinkState = WAIT_AUTH_2;
837 this->WriteLine("ERROR :Invalid credentials");
841 std::deque<std::string> Split(std::string line, bool stripcolon)
843 std::deque<std::string> n;
844 std::stringstream s(line);
845 std::string param = "";
851 if ((param != "") && (param != "\n"))
853 if ((param.c_str()[0] == ':') && (item))
855 char* str = (char*)param.c_str();
865 param = param + " " + append;
876 bool ProcessLine(std::string line)
878 char* l = (char*)line.c_str();
879 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
880 l[strlen(l)-1] = '\0';
884 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
885 std::deque<std::string> params = this->Split(line,true);
886 std::string command = "";
887 std::string prefix = "";
888 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
892 char* pref = (char*)prefix.c_str();
904 switch (this->LinkState)
909 // Waiting for SERVER command from remote server. Server initiating
910 // the connection sends the first SERVER command, listening server
911 // replies with theirs if its happy, then if the initiator is happy,
912 // it starts to send its net sync, which starts the merge, otherwise
913 // it sends an ERROR.
914 if (command == "SERVER")
916 return this->Inbound_Server(params);
918 else if (command == "ERROR")
920 return this->Error(params);
924 // Waiting for start of other side's netmerge to say they liked our
926 if (command == "SERVER")
928 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
932 else if (command == "BURST")
934 this->LinkState = CONNECTED;
935 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
936 TreeRoot->AddChild(Node);
938 params.push_back(InboundServerName);
939 params.push_back("*");
940 params.push_back("1");
941 params.push_back(":"+InboundDescription);
942 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
945 else if (command == "ERROR")
947 return this->Error(params);
952 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
956 if (command == "SERVER")
958 // another server we connected to, which was in WAIT_AUTH_1 state,
959 // has just sent us their credentials. If we get this far, theyre
960 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
961 // if we're happy with this, we should send our netburst which
962 // kickstarts the merge.
963 return this->Outbound_Reply_Server(params);
967 // This is the 'authenticated' state, when all passwords
968 // have been exchanged and anything past this point is taken
970 std::string target = "";
971 if ((command == "NICK") && (params.size() > 1))
973 return this->IntroduceClient(prefix,params);
975 else if (command == "FJOIN")
977 return this->ForceJoin(prefix,params);
979 else if (command == "SERVER")
981 return this->RemoteServer(prefix,params);
983 else if (command == "OPERTYPE")
985 return this->OperType(prefix,params);
987 else if (command == "FMODE")
989 return this->ForceMode(prefix,params);
991 else if (command == "KILL")
993 return this->RemoteKill(prefix,params);
995 else if (command == "FTOPIC")
997 return this->ForceTopic(prefix,params);
999 else if (command == "REHASH")
1001 return this->RemoteRehash(prefix,params);
1003 else if (command == "SQUIT")
1005 if (params.size() == 2)
1007 this->Squit(FindServer(params[0]),params[1]);
1013 // not a special inter-server command.
1014 // Emulate the actual user doing the command,
1015 // this saves us having a huge ugly parser.
1016 userrec* who = Srv->FindNick(prefix);
1017 std::string sourceserv = this->myhost;
1018 if (this->InboundServerName != "")
1020 sourceserv = this->InboundServerName;
1025 target = who->server;
1026 char* strparams[127];
1027 for (unsigned int q = 0; q < params.size(); q++)
1029 strparams[q] = (char*)params[q].c_str();
1031 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1032 Srv->CallCommandHandler(command, strparams, params.size(), who);
1036 // its not a user. Its either a server, or somethings screwed up.
1037 if (IsServer(prefix))
1039 target = Srv->GetServerName();
1043 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1047 return DoOneToAllButSenderRaw(line,sourceserv);
1056 virtual void OnTimeout()
1058 if (this->LinkState == CONNECTING)
1060 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1064 virtual void OnClose()
1066 // Connection closed.
1067 // If the connection is fully up (state CONNECTED)
1068 // then propogate a netsplit to all peers.
1069 std::string quitserver = this->myhost;
1070 if (this->InboundServerName != "")
1072 quitserver = this->InboundServerName;
1074 TreeServer* s = FindServer(quitserver);
1077 Squit(s,"Remote host closed the connection");
1081 virtual int OnIncomingConnection(int newsock, char* ip)
1083 TreeSocket* s = new TreeSocket(newsock, ip);
1089 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1091 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1093 TreeServer* Route = TreeRoot->GetChild(x);
1094 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1096 TreeSocket* Sock = Route->GetSocket();
1097 log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1098 Sock->WriteLine(data);
1104 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1106 log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1107 // TODO: Special stuff with privmsg and notice
1108 std::string FullLine = ":" + prefix + " " + command;
1109 for (unsigned int x = 0; x < params.size(); x++)
1111 FullLine = FullLine + " " + params[x];
1113 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1115 TreeServer* Route = TreeRoot->GetChild(x);
1116 // Send the line IF:
1117 // The route has a socket (its a direct connection)
1118 // The route isnt the one to be omitted
1119 // The route isnt the path to the one to be omitted
1120 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1122 TreeSocket* Sock = Route->GetSocket();
1123 log(DEBUG,"Sending to %s",Route->GetName().c_str());
1124 Sock->WriteLine(FullLine);
1130 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1132 Srv->Log(DEBUG,"ONETOMANY: "+command);
1133 std::string FullLine = ":" + prefix + " " + command;
1134 for (unsigned int x = 0; x < params.size(); x++)
1136 FullLine = FullLine + " " + params[x];
1138 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1140 TreeServer* Route = TreeRoot->GetChild(x);
1141 if (Route->GetSocket())
1143 TreeSocket* Sock = Route->GetSocket();
1144 Sock->WriteLine(FullLine);
1150 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1152 TreeServer* Route = BestRouteTo(target);
1155 std::string FullLine = ":" + prefix + " " + command;
1156 for (unsigned int x = 0; x < params.size(); x++)
1158 FullLine = FullLine + " " + params[x];
1160 if (Route->GetSocket())
1162 TreeSocket* Sock = Route->GetSocket();
1163 Sock->WriteLine(FullLine);
1169 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1175 class ModuleSpanningTree : public Module
1177 std::vector<TreeSocket*> Bindings;
1182 void ReadConfiguration(bool rebind)
1186 for (int j =0; j < Conf->Enumerate("bind"); j++)
1188 std::string Type = Conf->ReadValue("bind","type",j);
1189 std::string IP = Conf->ReadValue("bind","address",j);
1190 long Port = Conf->ReadInteger("bind","port",j,true);
1191 if (Type == "servers")
1197 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1198 if (listener->GetState() == I_LISTENING)
1200 Srv->AddSocket(listener);
1201 Bindings.push_back(listener);
1205 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1213 for (int j =0; j < Conf->Enumerate("link"); j++)
1216 L.Name = Conf->ReadValue("link","name",j);
1217 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1218 L.Port = Conf->ReadInteger("link","port",j,true);
1219 L.SendPass = Conf->ReadValue("link","sendpass",j);
1220 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1221 LinkBlocks.push_back(L);
1222 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1226 ModuleSpanningTree()
1229 Conf = new ConfigReader;
1232 // Create the root of the tree
1233 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1235 ReadConfiguration(true);
1238 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1240 std::string Parent = TreeRoot->GetName();
1241 if (Current->GetParent())
1243 Parent = Current->GetParent()->GetName();
1245 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1247 ShowLinks(Current->GetChild(q),user,hops+1);
1249 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1252 void HandleLinks(char** parameters, int pcnt, userrec* user)
1254 ShowLinks(TreeRoot,user,0);
1255 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1259 void HandleLusers(char** parameters, int pcnt, userrec* user)
1264 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1266 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1270 for (int t = 0; t < depth; t++)
1272 matrix[line][t] = ' ';
1274 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1276 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1278 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1283 // Ok, prepare to be confused.
1284 // After much mulling over how to approach this, it struck me that
1285 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1286 // keeping track of a ton of ascii characters, and line by line
1287 // under recursion working out where to place them using multiplications
1288 // and divisons, we instead render the map onto a backplane of characters
1289 // (a character matrix), then draw the branches as a series of "L" shapes
1290 // from the nodes. This is not only friendlier on CPU it uses less stack.
1292 void HandleMap(char** parameters, int pcnt, userrec* user)
1294 // This array represents a virtual screen which we will
1295 // "scratch" draw to, as the console device of an irc
1296 // client does not provide for a proper terminal.
1297 char matrix[128][80];
1298 for (unsigned int t = 0; t < 128; t++)
1300 matrix[t][0] = '\0';
1303 // The only recursive bit is called here.
1304 ShowMap(TreeRoot,user,0,matrix);
1305 // Process each line one by one. The algorithm has a limit of
1306 // 128 servers (which is far more than a spanning tree should have
1307 // anyway, so we're ok). This limit can be raised simply by making
1308 // the character matrix deeper, 128 rows taking 10k of memory.
1309 for (int l = 1; l < line; l++)
1311 // scan across the line looking for the start of the
1312 // servername (the recursive part of the algorithm has placed
1313 // the servers at indented positions depending on what they
1315 int first_nonspace = 0;
1316 while (matrix[l][first_nonspace] == ' ')
1321 // Draw the `- (corner) section: this may be overwritten by
1322 // another L shape passing along the same vertical pane, becoming
1323 // a |- (branch) section instead.
1324 matrix[l][first_nonspace] = '-';
1325 matrix[l][first_nonspace-1] = '`';
1327 // Draw upwards until we hit the parent server, causing possibly
1328 // other corners (`-) to become branches (|-)
1329 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1331 matrix[l2][first_nonspace-1] = '|';
1335 // dump the whole lot to the user. This is the easy bit, honest.
1336 for (int t = 0; t < line; t++)
1338 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1340 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1344 int HandleSquit(char** parameters, int pcnt, userrec* user)
1349 int HandleConnect(char** parameters, int pcnt, userrec* user)
1351 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1353 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1355 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1356 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1357 Srv->AddSocket(newsocket);
1361 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1365 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1367 if (command == "CONNECT")
1369 return this->HandleConnect(parameters,pcnt,user);
1371 else if (command == "SQUIT")
1373 return this->HandleSquit(parameters,pcnt,user);
1375 else if (command == "MAP")
1377 this->HandleMap(parameters,pcnt,user);
1380 else if (command == "LUSERS")
1382 this->HandleLusers(parameters,pcnt,user);
1385 else if (command == "LINKS")
1387 this->HandleLinks(parameters,pcnt,user);
1393 virtual void OnGetServerDescription(std::string servername,std::string &description)
1395 TreeServer* s = FindServer(servername);
1398 description = s->GetDesc();
1402 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1404 if (std::string(source->server) == Srv->GetServerName())
1406 std::deque<std::string> params;
1407 params.push_back(dest->nick);
1408 params.push_back(channel->name);
1409 DoOneToMany(source->nick,"INVITE",params);
1413 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1415 std::deque<std::string> params;
1416 params.push_back(chan->name);
1417 params.push_back(":"+topic);
1418 DoOneToMany(user->nick,"TOPIC",params);
1421 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1423 if (target_type == TYPE_USER)
1425 userrec* d = (userrec*)dest;
1426 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1428 std::deque<std::string> params;
1430 params.push_back(d->nick);
1431 params.push_back(":"+text);
1432 DoOneToOne(user->nick,"NOTICE",params,d->server);
1437 if (std::string(user->server) == Srv->GetServerName())
1439 chanrec *c = (chanrec*)dest;
1440 std::deque<std::string> params;
1441 params.push_back(c->name);
1442 params.push_back(":"+text);
1443 DoOneToMany(user->nick,"NOTICE",params);
1448 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1450 if (target_type == TYPE_USER)
1452 // route private messages which are targetted at clients only to the server
1453 // which needs to receive them
1454 userrec* d = (userrec*)dest;
1455 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1457 std::deque<std::string> params;
1459 params.push_back(d->nick);
1460 params.push_back(":"+text);
1461 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1466 if (std::string(user->server) == Srv->GetServerName())
1468 chanrec *c = (chanrec*)dest;
1469 std::deque<std::string> params;
1470 params.push_back(c->name);
1471 params.push_back(":"+text);
1472 DoOneToMany(user->nick,"PRIVMSG",params);
1477 virtual void OnUserJoin(userrec* user, chanrec* channel)
1479 // Only do this for local users
1480 if (std::string(user->server) == Srv->GetServerName())
1482 log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1483 std::deque<std::string> params;
1485 params.push_back(channel->name);
1488 log(DEBUG,"**** With key %s",channel->key);
1489 // if the channel has a key, force the join by emulating the key.
1490 params.push_back(channel->key);
1492 DoOneToMany(user->nick,"JOIN",params);
1496 virtual void OnUserPart(userrec* user, chanrec* channel)
1498 if (std::string(user->server) == Srv->GetServerName())
1500 log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1501 std::deque<std::string> params;
1503 params.push_back(channel->name);
1504 DoOneToMany(user->nick,"PART",params);
1508 virtual void OnUserConnect(userrec* user)
1510 char agestr[MAXBUF];
1511 if (std::string(user->server) == Srv->GetServerName())
1513 log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1514 std::deque<std::string> params;
1515 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1517 params.push_back(agestr);
1518 params.push_back(user->nick);
1519 params.push_back(user->host);
1520 params.push_back(user->dhost);
1521 params.push_back(user->ident);
1522 params.push_back("+"+std::string(user->modes));
1523 params.push_back(user->ip);
1524 params.push_back(":"+std::string(user->fullname));
1525 DoOneToMany(Srv->GetServerName(),"NICK",params);
1529 virtual void OnUserQuit(userrec* user, std::string reason)
1531 if (std::string(user->server) == Srv->GetServerName())
1533 log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1534 std::deque<std::string> params;
1535 params.push_back(":"+reason);
1536 DoOneToMany(user->nick,"QUIT",params);
1540 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1542 if (std::string(user->server) == Srv->GetServerName())
1544 log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1545 std::deque<std::string> params;
1546 params.push_back(user->nick);
1547 DoOneToMany(oldnick,"NICK",params);
1551 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1553 if (std::string(source->server) == Srv->GetServerName())
1555 log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1556 std::deque<std::string> params;
1557 params.push_back(chan->name);
1558 params.push_back(user->nick);
1559 params.push_back(":"+reason);
1560 DoOneToMany(source->nick,"KICK",params);
1564 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1566 std::deque<std::string> params;
1567 params.push_back(dest->nick);
1568 params.push_back(":"+reason);
1569 DoOneToMany(source->nick,"KILL",params);
1572 virtual void OnRehash(std::string parameter)
1574 if (parameter != "")
1576 std::deque<std::string> params;
1577 params.push_back(parameter);
1578 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1580 if (Srv->MatchText(Srv->GetServerName(),parameter))
1582 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1583 Srv->RehashServer();
1588 // note: the protocol does not allow direct umode +o except
1589 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1591 virtual void OnOper(userrec* user, std::string opertype)
1593 if (std::string(user->server) == Srv->GetServerName())
1595 std::deque<std::string> params;
1596 params.push_back(opertype);
1597 DoOneToMany(user->nick,"OPERTYPE",params);
1601 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1603 log(DEBUG,"*** ONMODE TRIGGER");
1604 if (std::string(user->server) == Srv->GetServerName())
1606 log(DEBUG,"*** LOCAL");
1607 if (target_type == TYPE_USER)
1609 userrec* u = (userrec*)dest;
1610 std::deque<std::string> params;
1611 params.push_back(u->nick);
1612 params.push_back(text);
1613 DoOneToMany(user->nick,"MODE",params);
1617 chanrec* c = (chanrec*)dest;
1618 std::deque<std::string> params;
1619 params.push_back(c->name);
1620 params.push_back(text);
1621 DoOneToMany(user->nick,"MODE",params);
1626 virtual ~ModuleSpanningTree()
1631 virtual Version GetVersion()
1633 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1638 class ModuleSpanningTreeFactory : public ModuleFactory
1641 ModuleSpanningTreeFactory()
1645 ~ModuleSpanningTreeFactory()
1649 virtual Module * CreateModule()
1651 return new ModuleSpanningTree;
1657 extern "C" void * init_module( void )
1659 return new ModuleSpanningTreeFactory;