1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
23 #include "inspircd_config.h"
25 #include <ext/hash_map>
33 #include "helperfuncs.h"
35 #include "inspstring.h"
40 #define nspace __gnu_cxx
45 class ModuleSpanningTree;
46 static ModuleSpanningTree* TreeProtocolModule;
48 extern std::vector<Module*> modules;
49 extern std::vector<ircd_module*> factory;
52 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
54 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
55 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
57 extern user_hash clientlist;
58 extern chan_hash chanlist;
63 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
64 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
65 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
66 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
67 void ReadConfiguration(bool rebind);
72 std::vector<TreeServer*> Children;
73 std::string ServerName;
74 std::string ServerDesc;
75 std::string VersionString;
78 TreeSocket* Socket; // for directly connected servers this points at the socket object
88 UserCount = OperCount = 0;
91 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
95 UserCount = OperCount = 0;
98 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
101 UserCount = OperCount = 0;
104 std::string GetName()
106 return this->ServerName;
109 std::string GetDesc()
111 return this->ServerDesc;
114 std::string GetVersion()
116 return this->VersionString;
121 return this->UserCount;
126 return this->OperCount;
129 TreeSocket* GetSocket()
134 TreeServer* GetParent()
139 unsigned int ChildCount()
141 return Children.size();
144 TreeServer* GetChild(unsigned int n)
146 if (n < Children.size())
156 void AddChild(TreeServer* Child)
158 Children.push_back(Child);
161 bool DelChild(TreeServer* Child)
163 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
174 // removes child nodes of this node, and of that node, etc etc
177 bool stillchildren = true;
178 while (stillchildren)
180 stillchildren = false;
181 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
183 TreeServer* s = (TreeServer*)*a;
187 stillchildren = true;
201 std::string SendPass;
202 std::string RecvPass;
205 /* $ModDesc: Povides a spanning tree server link protocol */
209 TreeServer *TreeRoot;
210 std::vector<Link> LinkBlocks;
212 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
214 if (Current->GetName() == ServerName)
216 for (unsigned int q = 0; q < Current->ChildCount(); q++)
218 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
227 // Returns the locally connected server we must route a
228 // message through to reach server 'ServerName'. This
229 // only applies to one-to-one and not one-to-many routing.
230 TreeServer* BestRouteTo(std::string ServerName)
232 if (ServerName.c_str() == TreeRoot->GetName())
236 // first, find the server by recursively walking the tree
237 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
238 // did we find it? If not, they did something wrong, abort.
245 // The server exists, follow its parent nodes until
246 // the parent of the current is 'TreeRoot', we know
247 // then that this is a directly-connected server.
248 while ((Found) && (Found->GetParent() != TreeRoot))
250 Found = Found->GetParent();
256 bool LookForServer(TreeServer* Current, std::string ServerName)
258 if (ServerName == Current->GetName())
260 for (unsigned int q = 0; q < Current->ChildCount(); q++)
262 if (LookForServer(Current->GetChild(q),ServerName))
270 void RFindServer(TreeServer* Current, std::string ServerName)
272 if ((ServerName == Current->GetName()) && (!Found))
279 for (unsigned int q = 0; q < Current->ChildCount(); q++)
282 RFindServer(Current->GetChild(q),ServerName);
288 TreeServer* FindServer(std::string ServerName)
291 RFindServer(TreeRoot,ServerName);
295 bool IsServer(std::string ServerName)
297 return LookForServer(TreeRoot,ServerName);
300 class TreeSocket : public InspSocket
303 std::string in_buffer;
304 ServerState LinkState;
305 std::string InboundServerName;
306 std::string InboundDescription;
308 int num_lost_servers;
312 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
313 : InspSocket(host, port, listening, maxtime)
316 this->LinkState = LISTENER;
319 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
320 : InspSocket(host, port, listening, maxtime)
323 this->LinkState = CONNECTING;
326 TreeSocket(int newfd, char* ip)
327 : InspSocket(newfd, ip)
329 this->LinkState = WAIT_AUTH_1;
332 virtual bool OnConnected()
334 if (this->LinkState == CONNECTING)
336 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
337 // we should send our details here.
338 // if the other side is satisfied, they send theirs.
339 // we do not need to change state here.
340 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
342 if (x->Name == this->myhost)
344 // found who we're supposed to be connecting to, send the neccessary gubbins.
345 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
353 virtual void OnError(InspSocketError e)
357 virtual int OnDisconnect()
362 // recursively send the server tree with distances as hops
363 void SendServers(TreeServer* Current, TreeServer* s, int hops)
366 for (unsigned int q = 0; q < Current->ChildCount(); q++)
368 TreeServer* recursive_server = Current->GetChild(q);
369 if (recursive_server != s)
371 // :source.server SERVER server.name hops :Description
372 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
373 this->WriteLine(command);
374 // down to next level
375 this->SendServers(recursive_server, s, hops+1);
380 void SquitServer(TreeServer* Current)
382 // recursively squit the servers attached to 'Current'
383 for (unsigned int q = 0; q < Current->ChildCount(); q++)
385 TreeServer* recursive_server = Current->GetChild(q);
386 this->SquitServer(recursive_server);
388 // Now we've whacked the kids, whack self
390 bool quittingpeople = true;
391 while (quittingpeople)
393 quittingpeople = false;
394 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
396 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
398 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
400 quittingpeople = true;
407 void Squit(TreeServer* Current,std::string reason)
411 std::deque<std::string> params;
412 params.push_back(Current->GetName());
413 params.push_back(":"+reason);
414 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
415 if (Current->GetParent() == TreeRoot)
417 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
421 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
423 num_lost_servers = 0;
425 SquitServer(Current);
427 Current->GetParent()->DelChild(Current);
429 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
433 log(DEFAULT,"Squit from unknown server");
437 bool ForceMode(std::string source, std::deque<std::string> params)
439 userrec* who = new userrec;
440 who->fd = FD_MAGIC_NUMBER;
441 if (params.size() < 2)
444 for (unsigned int q = 0; q < params.size(); q++)
446 modelist[q] = (char*)params[q].c_str();
448 Srv->SendMode(modelist,params.size(),who);
449 DoOneToAllButSender(source,"FMODE",params,source);
454 bool ForceTopic(std::string source, std::deque<std::string> params)
456 // FTOPIC %s %lu %s :%s
457 if (params.size() != 4)
459 std::string channel = params[0];
460 time_t ts = atoi(params[1].c_str());
461 std::string setby = params[2];
462 std::string topic = params[3];
464 chanrec* c = Srv->FindChannel(channel);
467 if ((ts >= c->topicset) || (!*c->topic))
469 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
470 strlcpy(c->setby,setby.c_str(),NICKMAX);
472 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
477 // all done, send it on its way
478 params[3] = ":" + params[3];
479 DoOneToAllButSender(source,"FTOPIC",params,source);
484 bool ForceJoin(std::string source, std::deque<std::string> params)
486 if (params.size() < 3)
490 char modestring[MAXBUF];
491 char* mode_users[127];
492 mode_users[0] = first;
493 mode_users[1] = modestring;
494 strcpy(mode_users[1],"+");
495 unsigned int modectr = 2;
498 std::string channel = params[0];
499 time_t TS = atoi(params[1].c_str());
502 chanrec* chan = Srv->FindChannel(channel);
507 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
509 // default is a high value, which if we dont have this
510 // channel will let the other side apply their modes.
511 time_t ourTS = time(NULL)+20;
512 chanrec* us = Srv->FindChannel(channel);
518 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
520 // do this first, so our mode reversals are correctly received by other servers
521 // if there is a TS collision.
522 DoOneToAllButSender(source,"FJOIN",params,source);
524 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
526 // process one channel at a time, applying modes.
527 char* usr = (char*)params[usernum].c_str();
528 char permissions = *usr;
533 mode_users[modectr++] = usr;
534 strlcat(modestring,"o",MAXBUF);
538 mode_users[modectr++] = usr;
539 strlcat(modestring,"h",MAXBUF);
543 mode_users[modectr++] = usr;
544 strlcat(modestring,"v",MAXBUF);
547 who = Srv->FindNick(usr);
550 Srv->JoinUserToChannel(who,channel,key);
551 if (modectr >= (MAXMODES-1))
553 // theres a mode for this user. push them onto the mode queue, and flush it
554 // if there are more than MAXMODES to go.
557 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
558 Srv->SendMode(mode_users,modectr,who);
562 log(DEBUG,"Their channel newer than ours, bouncing their modes");
564 std::deque<std::string> params;
565 // modes are now being UNSET...
566 *mode_users[1] = '-';
567 for (unsigned int x = 0; x < modectr; x++)
569 params.push_back(mode_users[x]);
571 // tell everyone to bounce the modes. bad modes, bad!
572 DoOneToMany(Srv->GetServerName(),"FMODE",params);
574 strcpy(mode_users[1],"+");
579 // there werent enough modes built up to flush it during FJOIN,
580 // or, there are a number left over. flush them out.
581 if ((modectr > 2) && (who))
585 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
586 Srv->SendMode(mode_users,modectr,who);
590 log(DEBUG,"Their channel newer than ours, bouncing their modes");
591 std::deque<std::string> params;
592 *mode_users[1] = '-';
593 for (unsigned int x = 0; x < modectr; x++)
595 params.push_back(mode_users[x]);
597 DoOneToMany(Srv->GetServerName(),"FMODE",params);
603 bool IntroduceClient(std::string source, std::deque<std::string> params)
605 if (params.size() < 8)
607 // NICK age nick host dhost ident +modes ip :gecos
609 std::string nick = params[1];
610 std::string host = params[2];
611 std::string dhost = params[3];
612 std::string ident = params[4];
613 time_t age = atoi(params[0].c_str());
614 std::string modes = params[5];
615 if (*(modes.c_str()) == '+')
617 char* m = (char*)modes.c_str();
621 std::string ip = params[6];
622 std::string gecos = params[7];
623 char* tempnick = (char*)nick.c_str();
624 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
626 user_hash::iterator iter;
627 iter = clientlist.find(tempnick);
628 if (iter != clientlist.end())
631 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);
632 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
636 clientlist[tempnick] = new userrec();
637 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
638 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
639 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
640 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
641 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
642 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
643 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
644 clientlist[tempnick]->registered = 7;
645 clientlist[tempnick]->signon = age;
646 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
647 for (int i = 0; i < MAXCHANS; i++)
649 clientlist[tempnick]->chans[i].channel = NULL;
650 clientlist[tempnick]->chans[i].uc_modes = 0;
652 params[7] = ":" + params[7];
653 DoOneToAllButSender(source,"NICK",params,source);
657 void SendFJoins(TreeServer* Current, chanrec* c)
660 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
661 std::vector<char*> *ulist = c->GetUsers();
662 for (unsigned int i = 0; i < ulist->size(); i++)
664 char* o = (*ulist)[i];
665 userrec* otheruser = (userrec*)o;
666 strlcat(list," ",MAXBUF);
667 strlcat(list,cmode(otheruser,c),MAXBUF);
668 strlcat(list,otheruser->nick,MAXBUF);
669 if (strlen(list)>(480-NICKMAX))
671 this->WriteLine(list);
672 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
675 if (list[strlen(list)-1] != ':')
677 this->WriteLine(list);
681 void SendChannelModes(TreeServer* Current)
684 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
686 SendFJoins(Current, c->second);
687 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
688 this->WriteLine(data);
689 if (*c->second->topic)
691 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);
692 this->WriteLine(data);
694 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
696 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
697 this->WriteLine(data);
699 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
703 // send all users and their channels
704 void SendUsers(TreeServer* Current)
707 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
709 if (u->second->registered == 7)
711 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);
712 this->WriteLine(data);
713 if (strchr(u->second->modes,'o'))
715 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
717 //char* chl = chlist(u->second,u->second);
720 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
722 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
727 void DoBurst(TreeServer* s)
729 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
730 this->WriteLine("BURST");
732 this->SendServers(TreeRoot,s,1);
733 // Send users and their channels
735 // TODO: Send everything else (channel modes etc)
736 this->SendChannelModes(s);
737 this->WriteLine("ENDBURST");
740 virtual bool OnDataReady()
742 char* data = this->Read();
745 this->in_buffer += data;
746 while (in_buffer.find("\n") != std::string::npos)
748 char* line = (char*)in_buffer.c_str();
749 std::string ret = "";
750 while ((*line != '\n') && (strlen(line)))
755 if ((*line == '\n') || (*line == '\r'))
758 if (!this->ProcessLine(ret))
764 return (data != NULL);
767 int WriteLine(std::string line)
769 return this->Write(line + "\r\n");
772 bool Error(std::deque<std::string> params)
774 if (params.size() < 1)
776 std::string Errmsg = params[0];
777 std::string SName = myhost;
778 if (InboundServerName != "")
780 SName = InboundServerName;
782 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
783 // we will return false to cause the socket to close.
787 bool OperType(std::string prefix, std::deque<std::string> params)
789 if (params.size() != 1)
791 std::string opertype = params[0];
792 userrec* u = Srv->FindNick(prefix);
795 strlcpy(u->oper,opertype.c_str(),NICKMAX);
796 if (!strchr(u->modes,'o'))
798 strcat(u->modes,"o");
800 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
805 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
807 if (params.size() < 1)
809 std::string servermask = params[0];
810 if (Srv->MatchText(Srv->GetServerName(),servermask))
812 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
814 ReadConfiguration(false);
816 DoOneToAllButSender(prefix,"REHASH",params,prefix);
820 bool RemoteKill(std::string prefix, std::deque<std::string> params)
822 if (params.size() != 2)
824 std::string nick = params[0];
825 std::string reason = params[1];
826 userrec* u = Srv->FindNick(prefix);
827 userrec* who = Srv->FindNick(nick);
830 std::string sourceserv = prefix;
833 sourceserv = u->server;
835 params[1] = ":" + params[1];
836 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
837 Srv->QuitUser(who,reason);
842 bool RemoteServer(std::string prefix, std::deque<std::string> params)
844 if (params.size() < 4)
846 std::string servername = params[0];
847 std::string password = params[1];
848 // hopcount is not used for a remote server, we calculate this ourselves
849 std::string description = params[3];
850 TreeServer* ParentOfThis = FindServer(prefix);
853 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
856 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
857 ParentOfThis->AddChild(Node);
858 params[3] = ":" + params[3];
859 DoOneToAllButSender(prefix,"SERVER",params,prefix);
860 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
864 bool Outbound_Reply_Server(std::deque<std::string> params)
866 if (params.size() < 4)
868 std::string servername = params[0];
869 std::string password = params[1];
870 int hops = atoi(params[2].c_str());
873 this->WriteLine("ERROR :Server too far away for authentication");
876 std::string description = params[3];
877 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
879 if ((x->Name == servername) && (x->RecvPass == password))
881 // Begin the sync here. this kickstarts the
882 // other side, waiting in WAIT_AUTH_2 state,
883 // into starting their burst, as it shows
885 this->LinkState = CONNECTED;
886 // we should add the details of this server now
887 // to the servers tree, as a child of the root
889 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
890 TreeRoot->AddChild(Node);
891 params[3] = ":" + params[3];
892 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
897 this->WriteLine("ERROR :Invalid credentials");
901 bool Inbound_Server(std::deque<std::string> params)
903 if (params.size() < 4)
905 std::string servername = params[0];
906 std::string password = params[1];
907 int hops = atoi(params[2].c_str());
910 this->WriteLine("ERROR :Server too far away for authentication");
913 std::string description = params[3];
914 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
916 if ((x->Name == servername) && (x->RecvPass == password))
918 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
919 this->InboundServerName = servername;
920 this->InboundDescription = description;
921 // this is good. Send our details: Our server name and description and hopcount of 0,
922 // along with the sendpass from this block.
923 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
924 // move to the next state, we are now waiting for THEM.
925 this->LinkState = WAIT_AUTH_2;
929 this->WriteLine("ERROR :Invalid credentials");
933 std::deque<std::string> Split(std::string line, bool stripcolon)
935 std::deque<std::string> n;
936 if (!strchr(line.c_str(),' '))
941 std::stringstream s(line);
942 std::string param = "";
961 if ((param == ":") && (item > 0))
984 bool ProcessLine(std::string line)
986 char* l = (char*)line.c_str();
987 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
988 l[strlen(l)-1] = '\0';
992 Srv->Log(DEBUG,"IN: '"+line+"'");
993 std::deque<std::string> params = this->Split(line,true);
994 std::string command = "";
995 std::string prefix = "";
996 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1000 char* pref = (char*)prefix.c_str();
1008 command = params[0];
1012 switch (this->LinkState)
1017 // Waiting for SERVER command from remote server. Server initiating
1018 // the connection sends the first SERVER command, listening server
1019 // replies with theirs if its happy, then if the initiator is happy,
1020 // it starts to send its net sync, which starts the merge, otherwise
1021 // it sends an ERROR.
1022 if (command == "SERVER")
1024 return this->Inbound_Server(params);
1026 else if (command == "ERROR")
1028 return this->Error(params);
1032 // Waiting for start of other side's netmerge to say they liked our
1034 if (command == "SERVER")
1036 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1040 else if (command == "BURST")
1042 this->LinkState = CONNECTED;
1043 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1044 TreeRoot->AddChild(Node);
1046 params.push_back(InboundServerName);
1047 params.push_back("*");
1048 params.push_back("1");
1049 params.push_back(":"+InboundDescription);
1050 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1051 this->DoBurst(Node);
1053 else if (command == "ERROR")
1055 return this->Error(params);
1060 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1064 if (command == "SERVER")
1066 // another server we connected to, which was in WAIT_AUTH_1 state,
1067 // has just sent us their credentials. If we get this far, theyre
1068 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1069 // if we're happy with this, we should send our netburst which
1070 // kickstarts the merge.
1071 return this->Outbound_Reply_Server(params);
1073 else if (command == "ERROR")
1075 return this->Error(params);
1079 // This is the 'authenticated' state, when all passwords
1080 // have been exchanged and anything past this point is taken
1082 std::string target = "";
1083 if ((command == "NICK") && (params.size() > 1))
1085 return this->IntroduceClient(prefix,params);
1087 else if (command == "FJOIN")
1089 return this->ForceJoin(prefix,params);
1091 else if (command == "SERVER")
1093 return this->RemoteServer(prefix,params);
1095 else if (command == "ERROR")
1097 return this->Error(params);
1099 else if (command == "OPERTYPE")
1101 return this->OperType(prefix,params);
1103 else if (command == "FMODE")
1105 return this->ForceMode(prefix,params);
1107 else if (command == "KILL")
1109 return this->RemoteKill(prefix,params);
1111 else if (command == "FTOPIC")
1113 return this->ForceTopic(prefix,params);
1115 else if (command == "REHASH")
1117 return this->RemoteRehash(prefix,params);
1119 else if (command == "SQUIT")
1121 if (params.size() == 2)
1123 this->Squit(FindServer(params[0]),params[1]);
1129 // not a special inter-server command.
1130 // Emulate the actual user doing the command,
1131 // this saves us having a huge ugly parser.
1132 userrec* who = Srv->FindNick(prefix);
1133 std::string sourceserv = this->myhost;
1134 if (this->InboundServerName != "")
1136 sourceserv = this->InboundServerName;
1141 target = who->server;
1142 char* strparams[127];
1143 for (unsigned int q = 0; q < params.size(); q++)
1145 strparams[q] = (char*)params[q].c_str();
1147 Srv->CallCommandHandler(command, strparams, params.size(), who);
1151 // its not a user. Its either a server, or somethings screwed up.
1152 if (IsServer(prefix))
1154 target = Srv->GetServerName();
1158 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1162 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1171 virtual std::string GetName()
1173 std::string sourceserv = this->myhost;
1174 if (this->InboundServerName != "")
1176 sourceserv = this->InboundServerName;
1181 virtual void OnTimeout()
1183 if (this->LinkState == CONNECTING)
1185 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1189 virtual void OnClose()
1191 // Connection closed.
1192 // If the connection is fully up (state CONNECTED)
1193 // then propogate a netsplit to all peers.
1194 std::string quitserver = this->myhost;
1195 if (this->InboundServerName != "")
1197 quitserver = this->InboundServerName;
1199 TreeServer* s = FindServer(quitserver);
1202 Squit(s,"Remote host closed the connection");
1206 virtual int OnIncomingConnection(int newsock, char* ip)
1208 TreeSocket* s = new TreeSocket(newsock, ip);
1214 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1216 for (unsigned int c = 0; c < list.size(); c++)
1218 if (list[c] == server)
1223 list.push_back(server);
1226 // returns a list of DIRECT servernames for a specific channel
1227 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1229 std::deque<TreeServer*> list;
1230 std::vector<char*> *ulist = c->GetUsers();
1231 for (unsigned int i = 0; i < ulist->size(); i++)
1233 char* o = (*ulist)[i];
1234 userrec* otheruser = (userrec*)o;
1235 if (std::string(otheruser->server) != Srv->GetServerName())
1237 TreeServer* best = BestRouteTo(otheruser->server);
1239 AddThisServer(best,list);
1245 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1247 TreeServer* omitroute = BestRouteTo(omit);
1248 if ((command == "NOTICE") || (command == "PRIVMSG"))
1250 if (params.size() >= 2)
1252 if (*(params[0].c_str()) != '#')
1254 // special routing for private messages/notices
1255 userrec* d = Srv->FindNick(params[0]);
1258 std::deque<std::string> par;
1260 par.push_back(params[0]);
1261 par.push_back(":"+params[1]);
1262 DoOneToOne(prefix,command,par,d->server);
1268 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1269 chanrec* c = Srv->FindChannel(params[0]);
1272 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1273 log(DEBUG,"Got a list of %d servers",list.size());
1274 for (unsigned int i = 0; i < list.size(); i++)
1276 TreeSocket* Sock = list[i]->GetSocket();
1277 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1279 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1280 Sock->WriteLine(data);
1288 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1290 TreeServer* Route = TreeRoot->GetChild(x);
1291 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1293 TreeSocket* Sock = Route->GetSocket();
1294 Sock->WriteLine(data);
1300 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1302 TreeServer* omitroute = BestRouteTo(omit);
1303 std::string FullLine = ":" + prefix + " " + command;
1304 for (unsigned int x = 0; x < params.size(); x++)
1306 FullLine = FullLine + " " + params[x];
1308 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1310 TreeServer* Route = TreeRoot->GetChild(x);
1311 // Send the line IF:
1312 // The route has a socket (its a direct connection)
1313 // The route isnt the one to be omitted
1314 // The route isnt the path to the one to be omitted
1315 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1317 TreeSocket* Sock = Route->GetSocket();
1318 Sock->WriteLine(FullLine);
1324 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1326 std::string FullLine = ":" + prefix + " " + command;
1327 for (unsigned int x = 0; x < params.size(); x++)
1329 FullLine = FullLine + " " + params[x];
1331 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1333 TreeServer* Route = TreeRoot->GetChild(x);
1334 if (Route->GetSocket())
1336 TreeSocket* Sock = Route->GetSocket();
1337 Sock->WriteLine(FullLine);
1343 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1345 TreeServer* Route = BestRouteTo(target);
1348 std::string FullLine = ":" + prefix + " " + command;
1349 for (unsigned int x = 0; x < params.size(); x++)
1351 FullLine = FullLine + " " + params[x];
1353 if (Route->GetSocket())
1355 TreeSocket* Sock = Route->GetSocket();
1356 Sock->WriteLine(FullLine);
1366 std::vector<TreeSocket*> Bindings;
1368 void ReadConfiguration(bool rebind)
1372 for (int j =0; j < Conf->Enumerate("bind"); j++)
1374 std::string Type = Conf->ReadValue("bind","type",j);
1375 std::string IP = Conf->ReadValue("bind","address",j);
1376 long Port = Conf->ReadInteger("bind","port",j,true);
1377 if (Type == "servers")
1383 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1384 if (listener->GetState() == I_LISTENING)
1386 Srv->AddSocket(listener);
1387 Bindings.push_back(listener);
1391 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1399 for (int j =0; j < Conf->Enumerate("link"); j++)
1402 L.Name = Conf->ReadValue("link","name",j);
1403 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1404 L.Port = Conf->ReadInteger("link","port",j,true);
1405 L.SendPass = Conf->ReadValue("link","sendpass",j);
1406 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1407 LinkBlocks.push_back(L);
1408 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1413 class ModuleSpanningTree : public Module
1415 std::vector<TreeSocket*> Bindings;
1420 ModuleSpanningTree()
1423 Conf = new ConfigReader;
1426 // Create the root of the tree
1427 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1429 ReadConfiguration(true);
1432 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1434 std::string Parent = TreeRoot->GetName();
1435 if (Current->GetParent())
1437 Parent = Current->GetParent()->GetName();
1439 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1441 ShowLinks(Current->GetChild(q),user,hops+1);
1443 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1446 void HandleLinks(char** parameters, int pcnt, userrec* user)
1448 ShowLinks(TreeRoot,user,0);
1449 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1453 void HandleLusers(char** parameters, int pcnt, userrec* user)
1458 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1460 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1464 for (int t = 0; t < depth; t++)
1466 matrix[line][t] = ' ';
1468 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1470 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1472 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1477 // Ok, prepare to be confused.
1478 // After much mulling over how to approach this, it struck me that
1479 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1480 // keeping track of a ton of ascii characters, and line by line
1481 // under recursion working out where to place them using multiplications
1482 // and divisons, we instead render the map onto a backplane of characters
1483 // (a character matrix), then draw the branches as a series of "L" shapes
1484 // from the nodes. This is not only friendlier on CPU it uses less stack.
1486 void HandleMap(char** parameters, int pcnt, userrec* user)
1488 // This array represents a virtual screen which we will
1489 // "scratch" draw to, as the console device of an irc
1490 // client does not provide for a proper terminal.
1491 char matrix[128][80];
1492 for (unsigned int t = 0; t < 128; t++)
1494 matrix[t][0] = '\0';
1497 // The only recursive bit is called here.
1498 ShowMap(TreeRoot,user,0,matrix);
1499 // Process each line one by one. The algorithm has a limit of
1500 // 128 servers (which is far more than a spanning tree should have
1501 // anyway, so we're ok). This limit can be raised simply by making
1502 // the character matrix deeper, 128 rows taking 10k of memory.
1503 for (int l = 1; l < line; l++)
1505 // scan across the line looking for the start of the
1506 // servername (the recursive part of the algorithm has placed
1507 // the servers at indented positions depending on what they
1509 int first_nonspace = 0;
1510 while (matrix[l][first_nonspace] == ' ')
1515 // Draw the `- (corner) section: this may be overwritten by
1516 // another L shape passing along the same vertical pane, becoming
1517 // a |- (branch) section instead.
1518 matrix[l][first_nonspace] = '-';
1519 matrix[l][first_nonspace-1] = '`';
1521 // Draw upwards until we hit the parent server, causing possibly
1522 // other corners (`-) to become branches (|-)
1523 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1525 matrix[l2][first_nonspace-1] = '|';
1529 // dump the whole lot to the user. This is the easy bit, honest.
1530 for (int t = 0; t < line; t++)
1532 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1534 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1538 int HandleSquit(char** parameters, int pcnt, userrec* user)
1543 int HandleConnect(char** parameters, int pcnt, userrec* user)
1545 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1547 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1549 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1550 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1551 Srv->AddSocket(newsocket);
1555 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1559 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1561 if (command == "CONNECT")
1563 return this->HandleConnect(parameters,pcnt,user);
1565 else if (command == "SQUIT")
1567 return this->HandleSquit(parameters,pcnt,user);
1569 else if (command == "MAP")
1571 this->HandleMap(parameters,pcnt,user);
1574 else if (command == "LUSERS")
1576 this->HandleLusers(parameters,pcnt,user);
1579 else if (command == "LINKS")
1581 this->HandleLinks(parameters,pcnt,user);
1584 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1586 // this bit of code cleverly routes all module commands
1587 // to all remote severs *automatically* so that modules
1588 // can just handle commands locally, without having
1589 // to have any special provision in place for remote
1590 // commands and linking protocols.
1591 std::deque<std::string> params;
1593 for (int j = 0; j < pcnt; j++)
1595 if (strchr(parameters[j],' '))
1597 params.push_back(":" + std::string(parameters[j]));
1601 params.push_back(std::string(parameters[j]));
1604 DoOneToMany(user->nick,command,params);
1609 virtual void OnGetServerDescription(std::string servername,std::string &description)
1611 TreeServer* s = FindServer(servername);
1614 description = s->GetDesc();
1618 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1620 if (std::string(source->server) == Srv->GetServerName())
1622 std::deque<std::string> params;
1623 params.push_back(dest->nick);
1624 params.push_back(channel->name);
1625 DoOneToMany(source->nick,"INVITE",params);
1629 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1631 std::deque<std::string> params;
1632 params.push_back(chan->name);
1633 params.push_back(":"+topic);
1634 DoOneToMany(user->nick,"TOPIC",params);
1637 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1639 if (target_type == TYPE_USER)
1641 userrec* d = (userrec*)dest;
1642 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1644 std::deque<std::string> params;
1646 params.push_back(d->nick);
1647 params.push_back(":"+text);
1648 DoOneToOne(user->nick,"NOTICE",params,d->server);
1653 if (std::string(user->server) == Srv->GetServerName())
1655 chanrec *c = (chanrec*)dest;
1656 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1657 for (unsigned int i = 0; i < list.size(); i++)
1659 TreeSocket* Sock = list[i]->GetSocket();
1661 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1667 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1669 if (target_type == TYPE_USER)
1671 // route private messages which are targetted at clients only to the server
1672 // which needs to receive them
1673 userrec* d = (userrec*)dest;
1674 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1676 std::deque<std::string> params;
1678 params.push_back(d->nick);
1679 params.push_back(":"+text);
1680 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1685 if (std::string(user->server) == Srv->GetServerName())
1687 chanrec *c = (chanrec*)dest;
1688 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1689 for (unsigned int i = 0; i < list.size(); i++)
1691 TreeSocket* Sock = list[i]->GetSocket();
1693 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
1699 virtual void OnUserJoin(userrec* user, chanrec* channel)
1701 // Only do this for local users
1702 if (std::string(user->server) == Srv->GetServerName())
1704 std::deque<std::string> params;
1706 params.push_back(channel->name);
1709 // if the channel has a key, force the join by emulating the key.
1710 params.push_back(channel->key);
1712 if (channel->GetUserCounter() > 1)
1714 // not the first in the channel
1715 DoOneToMany(user->nick,"JOIN",params);
1719 // first in the channel, set up their permissions
1720 // and the channel TS with FJOIN.
1722 params.push_back(channel->name);
1723 params.push_back(channel->age);
1724 params.push_back("@"+std::string(user->nick));
1725 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
1730 virtual void OnUserPart(userrec* user, chanrec* channel)
1732 if (std::string(user->server) == Srv->GetServerName())
1734 std::deque<std::string> params;
1736 params.push_back(channel->name);
1737 DoOneToMany(user->nick,"PART",params);
1741 virtual void OnUserConnect(userrec* user)
1743 char agestr[MAXBUF];
1744 if (std::string(user->server) == Srv->GetServerName())
1746 std::deque<std::string> params;
1747 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1749 params.push_back(agestr);
1750 params.push_back(user->nick);
1751 params.push_back(user->host);
1752 params.push_back(user->dhost);
1753 params.push_back(user->ident);
1754 params.push_back("+"+std::string(user->modes));
1755 params.push_back(user->ip);
1756 params.push_back(":"+std::string(user->fullname));
1757 DoOneToMany(Srv->GetServerName(),"NICK",params);
1761 virtual void OnUserQuit(userrec* user, std::string reason)
1763 if (std::string(user->server) == Srv->GetServerName())
1765 std::deque<std::string> params;
1766 params.push_back(":"+reason);
1767 DoOneToMany(user->nick,"QUIT",params);
1771 virtual void OnUserPostNick(userrec* user, std::string oldnick)
1773 if (std::string(user->server) == Srv->GetServerName())
1775 std::deque<std::string> params;
1776 params.push_back(user->nick);
1777 DoOneToMany(oldnick,"NICK",params);
1781 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1783 if (std::string(source->server) == Srv->GetServerName())
1785 std::deque<std::string> params;
1786 params.push_back(chan->name);
1787 params.push_back(user->nick);
1788 params.push_back(":"+reason);
1789 DoOneToMany(source->nick,"KICK",params);
1793 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1795 std::deque<std::string> params;
1796 params.push_back(dest->nick);
1797 params.push_back(":"+reason);
1798 DoOneToMany(source->nick,"KILL",params);
1801 virtual void OnRehash(std::string parameter)
1803 if (parameter != "")
1805 std::deque<std::string> params;
1806 params.push_back(parameter);
1807 DoOneToMany(Srv->GetServerName(),"REHASH",params);
1809 if (Srv->MatchText(Srv->GetServerName(),parameter))
1811 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1812 Srv->RehashServer();
1815 ReadConfiguration(false);
1818 // note: the protocol does not allow direct umode +o except
1819 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1821 virtual void OnOper(userrec* user, std::string opertype)
1823 if (std::string(user->server) == Srv->GetServerName())
1825 std::deque<std::string> params;
1826 params.push_back(opertype);
1827 DoOneToMany(user->nick,"OPERTYPE",params);
1831 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1833 if (std::string(user->server) == Srv->GetServerName())
1835 if (target_type == TYPE_USER)
1837 userrec* u = (userrec*)dest;
1838 std::deque<std::string> params;
1839 params.push_back(u->nick);
1840 params.push_back(text);
1841 DoOneToMany(user->nick,"MODE",params);
1845 chanrec* c = (chanrec*)dest;
1846 std::deque<std::string> params;
1847 params.push_back(c->name);
1848 params.push_back(text);
1849 DoOneToMany(user->nick,"MODE",params);
1854 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1856 TreeSocket* s = (TreeSocket*)opaque;
1859 if (target_type == TYPE_USER)
1861 userrec* u = (userrec*)target;
1862 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1866 chanrec* c = (chanrec*)target;
1867 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1872 virtual ~ModuleSpanningTree()
1877 virtual Version GetVersion()
1879 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1884 class ModuleSpanningTreeFactory : public ModuleFactory
1887 ModuleSpanningTreeFactory()
1891 ~ModuleSpanningTreeFactory()
1895 virtual Module * CreateModule()
1897 TreeProtocolModule = new ModuleSpanningTree;
1898 return TreeProtocolModule;
1904 extern "C" void * init_module( void )
1906 return new ModuleSpanningTreeFactory;