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 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
25 #include "inspircd_config.h"
27 #include <ext/hash_map>
35 #include "helperfuncs.h"
37 #include "inspstring.h"
43 #define nspace __gnu_cxx
48 class ModuleSpanningTree;
49 static ModuleSpanningTree* TreeProtocolModule;
51 extern std::vector<Module*> modules;
52 extern std::vector<ircd_module*> factory;
55 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
57 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
58 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
60 extern user_hash clientlist;
61 extern chan_hash chanlist;
68 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
69 server_hash serverlist;
71 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
72 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
73 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
74 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
75 void ReadConfiguration(bool rebind);
77 extern std::vector<KLine> klines;
78 extern std::vector<GLine> glines;
79 extern std::vector<ZLine> zlines;
80 extern std::vector<QLine> qlines;
81 extern std::vector<ELine> elines;
87 std::vector<TreeServer*> Children;
88 std::string ServerName;
89 std::string ServerDesc;
90 std::string VersionString;
93 TreeSocket* Socket; // for directly connected servers this points at the socket object
105 UserCount = OperCount = 0;
106 VersionString = GetVersionString();
109 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
113 UserCount = OperCount = 0;
114 VersionString = GetVersionString();
119 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
122 UserCount = OperCount = 0;
123 this->SetNextPingTime(time(NULL) + 60);
126 /* find the 'route' for this server (e.g. the one directly connected
127 * to the local server, which we can use to reach it)
129 * In the following example, consider we have just added a TreeServer
130 * class for server G on our network, of which we are server A.
131 * To route traffic to G (marked with a *) we must send the data to
132 * B (marked with a +) so this algorithm initializes the 'Route'
133 * value to point at whichever server traffic must be routed through
134 * to get here. If we were to try this algorithm with server B,
135 * the Route pointer would point at its own object ('this').
145 * We only run this algorithm when a server is created, as
146 * the routes remain constant while ever the server exists, and
147 * do not need to be re-calculated.
151 if (Route == TreeRoot)
157 while (this->Route->GetParent() != TreeRoot)
159 this->Route = Route->GetParent();
163 /* Because recursive code is slow and takes a lot of resources,
164 * we store two representations of the server tree. The first
165 * is a recursive structure where each server references its
166 * children and its parent, which is used for netbursts and
167 * netsplits to dump the whole dataset to the other server,
168 * and the second is used for very fast lookups when routing
169 * messages and is instead a hash_map, where each item can
170 * be referenced by its server name. The AddHashEntry()
171 * call below automatically inserts each TreeServer class
172 * into the hash_map as it is created. There is a similar
173 * maintainance call in the destructor to tidy up deleted
177 this->AddHashEntry();
182 server_hash::iterator iter;
183 iter = serverlist.find(this->ServerName);
184 if (iter == serverlist.end())
185 serverlist[this->ServerName] = this;
190 server_hash::iterator iter;
191 iter = serverlist.find(this->ServerName);
192 if (iter != serverlist.end())
193 serverlist.erase(iter);
196 TreeServer* GetRoute()
201 std::string GetName()
203 return this->ServerName;
206 std::string GetDesc()
208 return this->ServerDesc;
211 std::string GetVersion()
213 return this->VersionString;
216 void SetNextPingTime(time_t t)
219 LastPingWasGood = false;
222 time_t NextPingTime()
224 return this->NextPing;
227 bool AnsweredLastPing()
229 return LastPingWasGood;
234 LastPingWasGood = true;
239 return this->UserCount;
244 return this->OperCount;
247 TreeSocket* GetSocket()
252 TreeServer* GetParent()
257 void SetVersion(std::string Version)
259 VersionString = Version;
262 unsigned int ChildCount()
264 return Children.size();
267 TreeServer* GetChild(unsigned int n)
269 if (n < Children.size())
279 void AddChild(TreeServer* Child)
281 Children.push_back(Child);
284 bool DelChild(TreeServer* Child)
286 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
297 /* Removes child nodes of this node, and of that node, etc etc.
298 * This is used during netsplits to automatically tidy up the
299 * server tree. It is slow, we don't use it for much else.
303 bool stillchildren = true;
304 while (stillchildren)
306 stillchildren = false;
307 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
309 TreeServer* s = (TreeServer*)*a;
313 stillchildren = true;
322 this->DelHashEntry();
332 std::string SendPass;
333 std::string RecvPass;
334 unsigned long AutoConnect;
335 time_t NextConnectTime;
340 std::vector<Link> LinkBlocks;
342 TreeServer* FindServer(std::string ServerName)
344 server_hash::iterator iter;
345 iter = serverlist.find(ServerName);
346 if (iter != serverlist.end())
356 /* Returns the locally connected server we must route a
357 * message through to reach server 'ServerName'. This
358 * only applies to one-to-one and not one-to-many routing.
359 * See the comments for the constructor of TreeServer
362 TreeServer* BestRouteTo(std::string ServerName)
364 if (ServerName.c_str() == TreeRoot->GetName())
366 TreeServer* Found = FindServer(ServerName);
369 return Found->GetRoute();
379 /* TODO: These need optimizing to use an iterator of serverlist
381 void RFindServerMask(TreeServer* Current, std::string ServerName)
383 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
390 for (unsigned int q = 0; q < Current->ChildCount(); q++)
393 RFindServerMask(Current->GetChild(q),ServerName);
398 TreeServer* FindServerMask(std::string ServerName)
401 RFindServerMask(TreeRoot,ServerName);
405 bool IsServer(std::string ServerName)
407 return (FindServer(ServerName) != NULL);
410 class TreeSocket : public InspSocket
413 std::string in_buffer;
414 ServerState LinkState;
415 std::string InboundServerName;
416 std::string InboundDescription;
418 int num_lost_servers;
420 bool LastPingWasGood;
424 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
425 : InspSocket(host, port, listening, maxtime)
428 this->LinkState = LISTENER;
431 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
432 : InspSocket(host, port, listening, maxtime)
435 this->LinkState = CONNECTING;
438 TreeSocket(int newfd, char* ip)
439 : InspSocket(newfd, ip)
441 this->LinkState = WAIT_AUTH_1;
444 virtual bool OnConnected()
446 if (this->LinkState == CONNECTING)
448 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
449 // we should send our details here.
450 // if the other side is satisfied, they send theirs.
451 // we do not need to change state here.
452 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
454 if (x->Name == this->myhost)
456 // found who we're supposed to be connecting to, send the neccessary gubbins.
457 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
465 virtual void OnError(InspSocketError e)
469 virtual int OnDisconnect()
474 // recursively send the server tree with distances as hops
475 void SendServers(TreeServer* Current, TreeServer* s, int hops)
478 for (unsigned int q = 0; q < Current->ChildCount(); q++)
480 TreeServer* recursive_server = Current->GetChild(q);
481 if (recursive_server != s)
483 // :source.server SERVER server.name hops :Description
484 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
485 this->WriteLine(command);
486 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
487 // down to next level
488 this->SendServers(recursive_server, s, hops+1);
493 void SquitServer(TreeServer* Current)
495 // recursively squit the servers attached to 'Current'
496 for (unsigned int q = 0; q < Current->ChildCount(); q++)
498 TreeServer* recursive_server = Current->GetChild(q);
499 this->SquitServer(recursive_server);
501 // Now we've whacked the kids, whack self
503 bool quittingpeople = true;
504 while (quittingpeople)
506 quittingpeople = false;
507 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
509 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
511 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
513 quittingpeople = true;
520 void Squit(TreeServer* Current,std::string reason)
524 std::deque<std::string> params;
525 params.push_back(Current->GetName());
526 params.push_back(":"+reason);
527 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
528 if (Current->GetParent() == TreeRoot)
530 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
534 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
536 num_lost_servers = 0;
538 SquitServer(Current);
540 Current->GetParent()->DelChild(Current);
542 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
546 log(DEFAULT,"Squit from unknown server");
550 bool ForceMode(std::string source, std::deque<std::string> params)
552 userrec* who = new userrec;
553 who->fd = FD_MAGIC_NUMBER;
554 if (params.size() < 2)
557 for (unsigned int q = 0; q < params.size(); q++)
559 modelist[q] = (char*)params[q].c_str();
561 Srv->SendMode(modelist,params.size(),who);
562 DoOneToAllButSender(source,"FMODE",params,source);
567 bool ForceTopic(std::string source, std::deque<std::string> params)
569 // FTOPIC %s %lu %s :%s
570 if (params.size() != 4)
572 std::string channel = params[0];
573 time_t ts = atoi(params[1].c_str());
574 std::string setby = params[2];
575 std::string topic = params[3];
577 chanrec* c = Srv->FindChannel(channel);
580 if ((ts >= c->topicset) || (!*c->topic))
582 std::string oldtopic = c->topic;
583 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
584 strlcpy(c->setby,setby.c_str(),NICKMAX);
586 // if the topic text is the same as the current topic,
587 // dont bother to send the TOPIC command out, just silently
588 // update the set time and set nick.
589 if (oldtopic != topic)
590 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
595 // all done, send it on its way
596 params[3] = ":" + params[3];
597 DoOneToAllButSender(source,"FTOPIC",params,source);
602 bool ForceJoin(std::string source, std::deque<std::string> params)
604 if (params.size() < 3)
608 char modestring[MAXBUF];
609 char* mode_users[127];
610 mode_users[0] = first;
611 mode_users[1] = modestring;
612 strcpy(mode_users[1],"+");
613 unsigned int modectr = 2;
616 std::string channel = params[0];
617 time_t TS = atoi(params[1].c_str());
620 chanrec* chan = Srv->FindChannel(channel);
625 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
627 // default is a high value, which if we dont have this
628 // channel will let the other side apply their modes.
629 time_t ourTS = time(NULL)+600;
630 chanrec* us = Srv->FindChannel(channel);
636 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
638 // do this first, so our mode reversals are correctly received by other servers
639 // if there is a TS collision.
640 DoOneToAllButSender(source,"FJOIN",params,source);
642 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
644 // process one channel at a time, applying modes.
645 char* usr = (char*)params[usernum].c_str();
646 char permissions = *usr;
651 mode_users[modectr++] = usr;
652 strlcat(modestring,"o",MAXBUF);
656 mode_users[modectr++] = usr;
657 strlcat(modestring,"h",MAXBUF);
661 mode_users[modectr++] = usr;
662 strlcat(modestring,"v",MAXBUF);
665 who = Srv->FindNick(usr);
668 Srv->JoinUserToChannel(who,channel,key);
669 if (modectr >= (MAXMODES-1))
671 // theres a mode for this user. push them onto the mode queue, and flush it
672 // if there are more than MAXMODES to go.
675 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
676 Srv->SendMode(mode_users,modectr,who);
680 log(DEBUG,"Their channel newer than ours, bouncing their modes");
682 std::deque<std::string> params;
683 // modes are now being UNSET...
684 *mode_users[1] = '-';
685 for (unsigned int x = 0; x < modectr; x++)
687 params.push_back(mode_users[x]);
689 // tell everyone to bounce the modes. bad modes, bad!
690 DoOneToMany(Srv->GetServerName(),"FMODE",params);
692 strcpy(mode_users[1],"+");
697 // there werent enough modes built up to flush it during FJOIN,
698 // or, there are a number left over. flush them out.
699 if ((modectr > 2) && (who))
703 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
704 Srv->SendMode(mode_users,modectr,who);
708 log(DEBUG,"Their channel newer than ours, bouncing their modes");
709 std::deque<std::string> params;
710 *mode_users[1] = '-';
711 for (unsigned int x = 0; x < modectr; x++)
713 params.push_back(mode_users[x]);
715 DoOneToMany(Srv->GetServerName(),"FMODE",params);
721 bool IntroduceClient(std::string source, std::deque<std::string> params)
723 if (params.size() < 8)
725 // NICK age nick host dhost ident +modes ip :gecos
727 std::string nick = params[1];
728 std::string host = params[2];
729 std::string dhost = params[3];
730 std::string ident = params[4];
731 time_t age = atoi(params[0].c_str());
732 std::string modes = params[5];
733 while (*(modes.c_str()) == '+')
735 char* m = (char*)modes.c_str();
739 std::string ip = params[6];
740 std::string gecos = params[7];
741 char* tempnick = (char*)nick.c_str();
742 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
744 user_hash::iterator iter;
745 iter = clientlist.find(tempnick);
746 if (iter != clientlist.end())
749 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);
750 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
754 clientlist[tempnick] = new userrec();
755 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
756 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
757 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
758 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
759 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
760 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
761 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
762 clientlist[tempnick]->registered = 7;
763 clientlist[tempnick]->signon = age;
764 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
765 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
766 for (int i = 0; i < MAXCHANS; i++)
768 clientlist[tempnick]->chans[i].channel = NULL;
769 clientlist[tempnick]->chans[i].uc_modes = 0;
771 params[7] = ":" + params[7];
772 DoOneToAllButSender(source,"NICK",params,source);
776 void SendFJoins(TreeServer* Current, chanrec* c)
779 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
780 std::vector<char*> *ulist = c->GetUsers();
781 for (unsigned int i = 0; i < ulist->size(); i++)
783 char* o = (*ulist)[i];
784 userrec* otheruser = (userrec*)o;
785 strlcat(list," ",MAXBUF);
786 strlcat(list,cmode(otheruser,c),MAXBUF);
787 strlcat(list,otheruser->nick,MAXBUF);
788 if (strlen(list)>(480-NICKMAX))
790 this->WriteLine(list);
791 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
794 if (list[strlen(list)-1] != ':')
796 this->WriteLine(list);
800 void SendXLines(TreeServer* Current)
803 // for zlines and qlines, we should first check if theyre global...
804 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
806 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
807 this->WriteLine(data);
809 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
811 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
812 this->WriteLine(data);
814 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
816 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
817 this->WriteLine(data);
819 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
821 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
822 this->WriteLine(data);
826 void SendChannelModes(TreeServer* Current)
829 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
831 SendFJoins(Current, c->second);
832 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
833 this->WriteLine(data);
834 if (*c->second->topic)
836 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);
837 this->WriteLine(data);
839 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
841 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
842 this->WriteLine(data);
844 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
848 // send all users and their channels
849 void SendUsers(TreeServer* Current)
852 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
854 if (u->second->registered == 7)
856 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);
857 this->WriteLine(data);
858 if (strchr(u->second->modes,'o'))
860 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
862 //char* chl = chlist(u->second,u->second);
865 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
867 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
872 void DoBurst(TreeServer* s)
874 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
875 this->WriteLine("BURST");
876 // send our version string
877 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
879 this->SendServers(TreeRoot,s,1);
880 // Send users and their channels
882 // Send everything else (channel modes etc)
883 this->SendChannelModes(s);
885 this->WriteLine("ENDBURST");
888 virtual bool OnDataReady()
890 char* data = this->Read();
893 this->in_buffer += data;
894 while (in_buffer.find("\n") != std::string::npos)
896 char* line = (char*)in_buffer.c_str();
897 std::string ret = "";
898 while ((*line != '\n') && (strlen(line)))
903 if ((*line == '\n') || (*line == '\r'))
906 if (!this->ProcessLine(ret))
912 return (data != NULL);
915 int WriteLine(std::string line)
917 return this->Write(line + "\r\n");
920 bool Error(std::deque<std::string> params)
922 if (params.size() < 1)
924 std::string Errmsg = params[0];
925 std::string SName = myhost;
926 if (InboundServerName != "")
928 SName = InboundServerName;
930 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
931 // we will return false to cause the socket to close.
935 bool OperType(std::string prefix, std::deque<std::string> params)
937 if (params.size() != 1)
939 std::string opertype = params[0];
940 userrec* u = Srv->FindNick(prefix);
943 strlcpy(u->oper,opertype.c_str(),NICKMAX);
944 if (!strchr(u->modes,'o'))
946 strcat(u->modes,"o");
948 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
953 bool ForceNick(std::string prefix, std::deque<std::string> params)
955 if (params.size() < 3)
957 userrec* u = Srv->FindNick(params[0]);
960 Srv->ChangeUserNick(u,params[1]);
961 u->age = atoi(params[2]);
962 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
967 bool ServiceJoin(std::string prefix, std::deque<std::string> params)
969 if (params.size() < 2)
971 userrec* u = Srv->FindNick(params[0]);
974 Srv->JoinUserToChannel(u,params[1],"");
975 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
980 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
982 if (params.size() < 1)
984 std::string servermask = params[0];
985 if (Srv->MatchText(Srv->GetServerName(),servermask))
987 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
989 ReadConfiguration(false);
991 DoOneToAllButSender(prefix,"REHASH",params,prefix);
995 bool RemoteKill(std::string prefix, std::deque<std::string> params)
997 if (params.size() != 2)
999 std::string nick = params[0];
1000 std::string reason = params[1];
1001 userrec* u = Srv->FindNick(prefix);
1002 userrec* who = Srv->FindNick(nick);
1005 std::string sourceserv = prefix;
1008 sourceserv = u->server;
1010 params[1] = ":" + params[1];
1011 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1012 Srv->QuitUser(who,reason);
1017 bool LocalPong(std::string prefix, std::deque<std::string> params)
1019 if (params.size() < 1)
1021 TreeServer* ServerSource = FindServer(prefix);
1024 ServerSource->SetPingFlag();
1029 bool ServerVersion(std::string prefix, std::deque<std::string> params)
1031 if (params.size() < 1)
1033 TreeServer* ServerSource = FindServer(prefix);
1036 ServerSource->SetVersion(params[0]);
1038 params[0] = ":" + params[0];
1039 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1043 bool ChangeHost(std::string prefix, std::deque<std::string> params)
1045 if (params.size() < 1)
1047 userrec* u = Srv->FindNick(prefix);
1050 Srv->ChangeHost(u,params[0]);
1051 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1056 bool AddLine(std::string prefix, std::deque<std::string> params)
1058 if (params.size() < 6)
1060 std::string linetype = params[0]; /* Z, Q, E, G, K */
1061 std::string mask = params[1]; /* Line type dependent */
1062 std::string source = params[2]; /* may not be online or may be a server */
1063 std::string settime = params[3]; /* EPOCH time set */
1064 std::string duration = params[4]; /* Duration secs */
1065 std::string reason = params[5];
1067 switch (*(linetype.c_str()))
1070 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1073 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1076 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1079 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1082 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1085 /* Just in case... */
1086 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1089 /* Send it on its way */
1090 params[5] = ":" + params[5];
1091 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1095 bool ChangeName(std::string prefix, std::deque<std::string> params)
1097 if (params.size() < 1)
1099 userrec* u = Srv->FindNick(prefix);
1102 Srv->ChangeGECOS(u,params[0]);
1103 params[0] = ":" + params[0];
1104 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1109 bool LocalPing(std::string prefix, std::deque<std::string> params)
1111 if (params.size() < 1)
1113 std::string stufftobounce = params[0];
1114 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1118 bool RemoteServer(std::string prefix, std::deque<std::string> params)
1120 if (params.size() < 4)
1122 std::string servername = params[0];
1123 std::string password = params[1];
1124 // hopcount is not used for a remote server, we calculate this ourselves
1125 std::string description = params[3];
1126 TreeServer* ParentOfThis = FindServer(prefix);
1129 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1132 TreeServer* CheckDupe = FindServer(servername);
1135 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1138 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1139 ParentOfThis->AddChild(Node);
1140 params[3] = ":" + params[3];
1141 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1142 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1146 bool Outbound_Reply_Server(std::deque<std::string> params)
1148 if (params.size() < 4)
1150 std::string servername = params[0];
1151 std::string password = params[1];
1152 int hops = atoi(params[2].c_str());
1155 this->WriteLine("ERROR :Server too far away for authentication");
1158 std::string description = params[3];
1159 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1161 if ((x->Name == servername) && (x->RecvPass == password))
1163 TreeServer* CheckDupe = FindServer(servername);
1166 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1169 // Begin the sync here. this kickstarts the
1170 // other side, waiting in WAIT_AUTH_2 state,
1171 // into starting their burst, as it shows
1172 // that we're happy.
1173 this->LinkState = CONNECTED;
1174 // we should add the details of this server now
1175 // to the servers tree, as a child of the root
1177 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1178 TreeRoot->AddChild(Node);
1179 params[3] = ":" + params[3];
1180 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1181 this->DoBurst(Node);
1185 this->WriteLine("ERROR :Invalid credentials");
1189 bool Inbound_Server(std::deque<std::string> params)
1191 if (params.size() < 4)
1193 std::string servername = params[0];
1194 std::string password = params[1];
1195 int hops = atoi(params[2].c_str());
1198 this->WriteLine("ERROR :Server too far away for authentication");
1201 std::string description = params[3];
1202 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1204 if ((x->Name == servername) && (x->RecvPass == password))
1206 TreeServer* CheckDupe = FindServer(servername);
1209 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1212 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1213 this->InboundServerName = servername;
1214 this->InboundDescription = description;
1215 // this is good. Send our details: Our server name and description and hopcount of 0,
1216 // along with the sendpass from this block.
1217 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1218 // move to the next state, we are now waiting for THEM.
1219 this->LinkState = WAIT_AUTH_2;
1223 this->WriteLine("ERROR :Invalid credentials");
1227 std::deque<std::string> Split(std::string line, bool stripcolon)
1229 std::deque<std::string> n;
1230 if (!strchr(line.c_str(),' '))
1235 std::stringstream s(line);
1236 std::string param = "";
1255 if ((param == ":") && (item > 0))
1278 bool ProcessLine(std::string line)
1280 char* l = (char*)line.c_str();
1281 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1282 l[strlen(l)-1] = '\0';
1286 Srv->Log(DEBUG,"IN: '"+line+"'");
1287 std::deque<std::string> params = this->Split(line,true);
1288 std::string command = "";
1289 std::string prefix = "";
1290 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1293 command = params[1];
1294 char* pref = (char*)prefix.c_str();
1302 command = params[0];
1306 switch (this->LinkState)
1311 // Waiting for SERVER command from remote server. Server initiating
1312 // the connection sends the first SERVER command, listening server
1313 // replies with theirs if its happy, then if the initiator is happy,
1314 // it starts to send its net sync, which starts the merge, otherwise
1315 // it sends an ERROR.
1316 if (command == "SERVER")
1318 return this->Inbound_Server(params);
1320 else if (command == "ERROR")
1322 return this->Error(params);
1326 // Waiting for start of other side's netmerge to say they liked our
1328 if (command == "SERVER")
1330 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1334 else if (command == "BURST")
1336 this->LinkState = CONNECTED;
1337 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1338 TreeRoot->AddChild(Node);
1340 params.push_back(InboundServerName);
1341 params.push_back("*");
1342 params.push_back("1");
1343 params.push_back(":"+InboundDescription);
1344 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1345 this->DoBurst(Node);
1347 else if (command == "ERROR")
1349 return this->Error(params);
1354 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1358 if (command == "SERVER")
1360 // another server we connected to, which was in WAIT_AUTH_1 state,
1361 // has just sent us their credentials. If we get this far, theyre
1362 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1363 // if we're happy with this, we should send our netburst which
1364 // kickstarts the merge.
1365 return this->Outbound_Reply_Server(params);
1367 else if (command == "ERROR")
1369 return this->Error(params);
1373 // This is the 'authenticated' state, when all passwords
1374 // have been exchanged and anything past this point is taken
1376 std::string target = "";
1377 if ((command == "NICK") && (params.size() > 1))
1379 return this->IntroduceClient(prefix,params);
1381 else if (command == "FJOIN")
1383 return this->ForceJoin(prefix,params);
1385 else if (command == "SERVER")
1387 return this->RemoteServer(prefix,params);
1389 else if (command == "ERROR")
1391 return this->Error(params);
1393 else if (command == "OPERTYPE")
1395 return this->OperType(prefix,params);
1397 else if (command == "FMODE")
1399 return this->ForceMode(prefix,params);
1401 else if (command == "KILL")
1403 return this->RemoteKill(prefix,params);
1405 else if (command == "FTOPIC")
1407 return this->ForceTopic(prefix,params);
1409 else if (command == "REHASH")
1411 return this->RemoteRehash(prefix,params);
1413 else if (command == "PING")
1415 return this->LocalPing(prefix,params);
1417 else if (command == "PONG")
1419 return this->LocalPong(prefix,params);
1421 else if (command == "VERSION")
1423 return this->ServerVersion(prefix,params);
1425 else if (command == "FHOST")
1427 return this->ChangeHost(prefix,params);
1429 else if (command == "FNAME")
1431 return this->ChangeName(prefix,params);
1433 else if (command == "ADDLINE")
1435 return this->AddLine(prefix,params);
1437 else if (command == "SVSNICK")
1441 prefix = this->GetName();
1443 return this->ForceNick(prefix,params);
1445 else if (command == "SVSJOIN")
1449 prefix = this->GetName();
1451 return this->ServiceJoin(prefix,params);
1453 else if (command == "SQUIT")
1455 if (params.size() == 2)
1457 this->Squit(FindServer(params[0]),params[1]);
1463 // not a special inter-server command.
1464 // Emulate the actual user doing the command,
1465 // this saves us having a huge ugly parser.
1466 userrec* who = Srv->FindNick(prefix);
1467 std::string sourceserv = this->myhost;
1468 if (this->InboundServerName != "")
1470 sourceserv = this->InboundServerName;
1475 target = who->server;
1476 char* strparams[127];
1477 for (unsigned int q = 0; q < params.size(); q++)
1479 strparams[q] = (char*)params[q].c_str();
1481 Srv->CallCommandHandler(command, strparams, params.size(), who);
1485 // its not a user. Its either a server, or somethings screwed up.
1486 if (IsServer(prefix))
1488 target = Srv->GetServerName();
1492 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1496 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1505 virtual std::string GetName()
1507 std::string sourceserv = this->myhost;
1508 if (this->InboundServerName != "")
1510 sourceserv = this->InboundServerName;
1515 virtual void OnTimeout()
1517 if (this->LinkState == CONNECTING)
1519 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1523 virtual void OnClose()
1525 // Connection closed.
1526 // If the connection is fully up (state CONNECTED)
1527 // then propogate a netsplit to all peers.
1528 std::string quitserver = this->myhost;
1529 if (this->InboundServerName != "")
1531 quitserver = this->InboundServerName;
1533 TreeServer* s = FindServer(quitserver);
1536 Squit(s,"Remote host closed the connection");
1540 virtual int OnIncomingConnection(int newsock, char* ip)
1542 TreeSocket* s = new TreeSocket(newsock, ip);
1548 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1550 for (unsigned int c = 0; c < list.size(); c++)
1552 if (list[c] == server)
1557 list.push_back(server);
1560 // returns a list of DIRECT servernames for a specific channel
1561 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
1563 std::vector<char*> *ulist = c->GetUsers();
1564 unsigned int ucount = ulist->size();
1565 for (unsigned int i = 0; i < ucount; i++)
1567 char* o = (*ulist)[i];
1568 userrec* otheruser = (userrec*)o;
1569 if (std::string(otheruser->server) != Srv->GetServerName())
1571 TreeServer* best = BestRouteTo(otheruser->server);
1573 AddThisServer(best,list);
1579 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1581 TreeServer* omitroute = BestRouteTo(omit);
1582 if ((command == "NOTICE") || (command == "PRIVMSG"))
1584 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1586 if (*(params[0].c_str()) != '#')
1588 // special routing for private messages/notices
1589 userrec* d = Srv->FindNick(params[0]);
1592 std::deque<std::string> par;
1593 par.push_back(params[0]);
1594 par.push_back(":"+params[1]);
1595 DoOneToOne(prefix,command,par,d->server);
1601 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1602 chanrec* c = Srv->FindChannel(params[0]);
1605 std::deque<TreeServer*> list;
1606 GetListOfServersForChannel(c,list);
1607 log(DEBUG,"Got a list of %d servers",list.size());
1608 unsigned int lsize = list.size();
1609 for (unsigned int i = 0; i < lsize; i++)
1611 TreeSocket* Sock = list[i]->GetSocket();
1612 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1614 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1615 Sock->WriteLine(data);
1623 unsigned int items = TreeRoot->ChildCount();
1624 for (unsigned int x = 0; x < items; x++)
1626 TreeServer* Route = TreeRoot->GetChild(x);
1627 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1629 TreeSocket* Sock = Route->GetSocket();
1630 Sock->WriteLine(data);
1636 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1638 TreeServer* omitroute = BestRouteTo(omit);
1639 std::string FullLine = ":" + prefix + " " + command;
1640 unsigned int words = params.size();
1641 for (unsigned int x = 0; x < words; x++)
1643 FullLine = FullLine + " " + params[x];
1645 unsigned int items = TreeRoot->ChildCount();
1646 for (unsigned int x = 0; x < items; x++)
1648 TreeServer* Route = TreeRoot->GetChild(x);
1649 // Send the line IF:
1650 // The route has a socket (its a direct connection)
1651 // The route isnt the one to be omitted
1652 // The route isnt the path to the one to be omitted
1653 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1655 TreeSocket* Sock = Route->GetSocket();
1656 Sock->WriteLine(FullLine);
1662 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1664 std::string FullLine = ":" + prefix + " " + command;
1665 unsigned int words = params.size();
1666 for (unsigned int x = 0; x < words; x++)
1668 FullLine = FullLine + " " + params[x];
1670 unsigned int items = TreeRoot->ChildCount();
1671 for (unsigned int x = 0; x < items; x++)
1673 TreeServer* Route = TreeRoot->GetChild(x);
1674 if (Route->GetSocket())
1676 TreeSocket* Sock = Route->GetSocket();
1677 Sock->WriteLine(FullLine);
1683 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1685 TreeServer* Route = BestRouteTo(target);
1688 std::string FullLine = ":" + prefix + " " + command;
1689 unsigned int words = params.size();
1690 for (unsigned int x = 0; x < words; x++)
1692 FullLine = FullLine + " " + params[x];
1694 if (Route->GetSocket())
1696 TreeSocket* Sock = Route->GetSocket();
1697 Sock->WriteLine(FullLine);
1707 std::vector<TreeSocket*> Bindings;
1709 void ReadConfiguration(bool rebind)
1713 for (int j =0; j < Conf->Enumerate("bind"); j++)
1715 std::string Type = Conf->ReadValue("bind","type",j);
1716 std::string IP = Conf->ReadValue("bind","address",j);
1717 long Port = Conf->ReadInteger("bind","port",j,true);
1718 if (Type == "servers")
1724 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1725 if (listener->GetState() == I_LISTENING)
1727 Srv->AddSocket(listener);
1728 Bindings.push_back(listener);
1732 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1740 for (int j =0; j < Conf->Enumerate("link"); j++)
1743 L.Name = Conf->ReadValue("link","name",j);
1744 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1745 L.Port = Conf->ReadInteger("link","port",j,true);
1746 L.SendPass = Conf->ReadValue("link","sendpass",j);
1747 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1748 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1749 L.NextConnectTime = time(NULL) + L.AutoConnect;
1750 LinkBlocks.push_back(L);
1751 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1756 class ModuleSpanningTree : public Module
1758 std::vector<TreeSocket*> Bindings;
1764 ModuleSpanningTree()
1767 Conf = new ConfigReader;
1770 // Create the root of the tree
1771 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1773 ReadConfiguration(true);
1776 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1778 std::string Parent = TreeRoot->GetName();
1779 if (Current->GetParent())
1781 Parent = Current->GetParent()->GetName();
1783 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1785 ShowLinks(Current->GetChild(q),user,hops+1);
1787 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1790 int CountLocalServs()
1792 return TreeRoot->ChildCount();
1795 void CountServsRecursive(TreeServer* Current)
1798 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1800 CountServsRecursive(Current->GetChild(q));
1807 CountServsRecursive(TreeRoot);
1811 void HandleLinks(char** parameters, int pcnt, userrec* user)
1813 ShowLinks(TreeRoot,user,0);
1814 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1818 void HandleLusers(char** parameters, int pcnt, userrec* user)
1820 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1821 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1822 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1823 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1824 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1828 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1830 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1834 for (int t = 0; t < depth; t++)
1836 matrix[line][t] = ' ';
1838 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1840 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1842 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1847 // Ok, prepare to be confused.
1848 // After much mulling over how to approach this, it struck me that
1849 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1850 // keeping track of a ton of ascii characters, and line by line
1851 // under recursion working out where to place them using multiplications
1852 // and divisons, we instead render the map onto a backplane of characters
1853 // (a character matrix), then draw the branches as a series of "L" shapes
1854 // from the nodes. This is not only friendlier on CPU it uses less stack.
1856 void HandleMap(char** parameters, int pcnt, userrec* user)
1858 // This array represents a virtual screen which we will
1859 // "scratch" draw to, as the console device of an irc
1860 // client does not provide for a proper terminal.
1861 char matrix[128][80];
1862 for (unsigned int t = 0; t < 128; t++)
1864 matrix[t][0] = '\0';
1867 // The only recursive bit is called here.
1868 ShowMap(TreeRoot,user,0,matrix);
1869 // Process each line one by one. The algorithm has a limit of
1870 // 128 servers (which is far more than a spanning tree should have
1871 // anyway, so we're ok). This limit can be raised simply by making
1872 // the character matrix deeper, 128 rows taking 10k of memory.
1873 for (int l = 1; l < line; l++)
1875 // scan across the line looking for the start of the
1876 // servername (the recursive part of the algorithm has placed
1877 // the servers at indented positions depending on what they
1879 int first_nonspace = 0;
1880 while (matrix[l][first_nonspace] == ' ')
1885 // Draw the `- (corner) section: this may be overwritten by
1886 // another L shape passing along the same vertical pane, becoming
1887 // a |- (branch) section instead.
1888 matrix[l][first_nonspace] = '-';
1889 matrix[l][first_nonspace-1] = '`';
1891 // Draw upwards until we hit the parent server, causing possibly
1892 // other corners (`-) to become branches (|-)
1893 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1895 matrix[l2][first_nonspace-1] = '|';
1899 // dump the whole lot to the user. This is the easy bit, honest.
1900 for (int t = 0; t < line; t++)
1902 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1904 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1908 int HandleSquit(char** parameters, int pcnt, userrec* user)
1910 TreeServer* s = FindServerMask(parameters[0]);
1913 TreeSocket* sock = s->GetSocket();
1916 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1917 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1922 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1927 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1932 void DoPingChecks(time_t curtime)
1934 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1936 TreeServer* serv = TreeRoot->GetChild(j);
1937 TreeSocket* sock = serv->GetSocket();
1940 if (curtime >= serv->NextPingTime())
1942 if (serv->AnsweredLastPing())
1944 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1945 serv->SetNextPingTime(curtime + 60);
1949 // they didnt answer, boot them
1950 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1951 sock->Squit(serv,"Ping timeout");
1960 void AutoConnectServers(time_t curtime)
1962 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1964 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1966 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1967 x->NextConnectTime = curtime + x->AutoConnect;
1968 TreeServer* CheckDupe = FindServer(x->Name);
1971 // an autoconnected server is not connected. Check if its time to connect it
1972 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1973 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1974 Srv->AddSocket(newsocket);
1980 int HandleVersion(char** parameters, int pcnt, userrec* user)
1982 // we've already checked if pcnt > 0, so this is safe
1983 TreeServer* found = FindServerMask(parameters[0]);
1986 std::string Version = found->GetVersion();
1987 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1991 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1996 int HandleConnect(char** parameters, int pcnt, userrec* user)
1998 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2000 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2002 TreeServer* CheckDupe = FindServer(x->Name);
2005 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
2006 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2007 Srv->AddSocket(newsocket);
2012 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
2017 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2021 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2023 if (command == "CONNECT")
2025 return this->HandleConnect(parameters,pcnt,user);
2027 else if (command == "SQUIT")
2029 return this->HandleSquit(parameters,pcnt,user);
2031 else if (command == "MAP")
2033 this->HandleMap(parameters,pcnt,user);
2036 else if (command == "LUSERS")
2038 this->HandleLusers(parameters,pcnt,user);
2041 else if (command == "LINKS")
2043 this->HandleLinks(parameters,pcnt,user);
2046 else if ((command == "VERSION") && (pcnt > 0))
2048 this->HandleVersion(parameters,pcnt,user);
2051 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2053 // this bit of code cleverly routes all module commands
2054 // to all remote severs *automatically* so that modules
2055 // can just handle commands locally, without having
2056 // to have any special provision in place for remote
2057 // commands and linking protocols.
2058 std::deque<std::string> params;
2060 for (int j = 0; j < pcnt; j++)
2062 if (strchr(parameters[j],' '))
2064 params.push_back(":" + std::string(parameters[j]));
2068 params.push_back(std::string(parameters[j]));
2071 DoOneToMany(user->nick,command,params);
2076 virtual void OnGetServerDescription(std::string servername,std::string &description)
2078 TreeServer* s = FindServer(servername);
2081 description = s->GetDesc();
2085 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2087 if (std::string(source->server) == Srv->GetServerName())
2089 std::deque<std::string> params;
2090 params.push_back(dest->nick);
2091 params.push_back(channel->name);
2092 DoOneToMany(source->nick,"INVITE",params);
2096 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2098 std::deque<std::string> params;
2099 params.push_back(chan->name);
2100 params.push_back(":"+topic);
2101 DoOneToMany(user->nick,"TOPIC",params);
2104 virtual void OnWallops(userrec* user, std::string text)
2106 if (std::string(user->server) == Srv->GetServerName())
2108 std::deque<std::string> params;
2109 params.push_back(":"+text);
2110 DoOneToMany(user->nick,"WALLOPS",params);
2114 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2116 if (target_type == TYPE_USER)
2118 userrec* d = (userrec*)dest;
2119 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2121 std::deque<std::string> params;
2123 params.push_back(d->nick);
2124 params.push_back(":"+text);
2125 DoOneToOne(user->nick,"NOTICE",params,d->server);
2130 if (std::string(user->server) == Srv->GetServerName())
2132 chanrec *c = (chanrec*)dest;
2133 std::deque<TreeServer*> list;
2134 GetListOfServersForChannel(c,list);
2135 unsigned int ucount = list.size();
2136 for (unsigned int i = 0; i < ucount; i++)
2138 TreeSocket* Sock = list[i]->GetSocket();
2140 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2146 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2148 if (target_type == TYPE_USER)
2150 // route private messages which are targetted at clients only to the server
2151 // which needs to receive them
2152 userrec* d = (userrec*)dest;
2153 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2155 std::deque<std::string> params;
2157 params.push_back(d->nick);
2158 params.push_back(":"+text);
2159 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2164 if (std::string(user->server) == Srv->GetServerName())
2166 chanrec *c = (chanrec*)dest;
2167 std::deque<TreeServer*> list;
2168 GetListOfServersForChannel(c,list);
2169 unsigned int ucount = list.size();
2170 for (unsigned int i = 0; i < ucount; i++)
2172 TreeSocket* Sock = list[i]->GetSocket();
2174 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2180 virtual void OnBackgroundTimer(time_t curtime)
2182 AutoConnectServers(curtime);
2183 DoPingChecks(curtime);
2186 virtual void OnUserJoin(userrec* user, chanrec* channel)
2188 // Only do this for local users
2189 if (std::string(user->server) == Srv->GetServerName())
2191 std::deque<std::string> params;
2193 params.push_back(channel->name);
2196 // if the channel has a key, force the join by emulating the key.
2197 params.push_back(channel->key);
2199 if (channel->GetUserCounter() > 1)
2201 // not the first in the channel
2202 DoOneToMany(user->nick,"JOIN",params);
2206 // first in the channel, set up their permissions
2207 // and the channel TS with FJOIN.
2209 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2211 params.push_back(channel->name);
2212 params.push_back(ts);
2213 params.push_back("@"+std::string(user->nick));
2214 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2219 virtual void OnChangeHost(userrec* user, std::string newhost)
2221 // only occurs for local clients
2222 std::deque<std::string> params;
2223 params.push_back(newhost);
2224 DoOneToMany(user->nick,"FHOST",params);
2227 virtual void OnChangeName(userrec* user, std::string gecos)
2229 // only occurs for local clients
2230 std::deque<std::string> params;
2231 params.push_back(gecos);
2232 DoOneToMany(user->nick,"FNAME",params);
2235 virtual void OnUserPart(userrec* user, chanrec* channel)
2237 if (std::string(user->server) == Srv->GetServerName())
2239 std::deque<std::string> params;
2240 params.push_back(channel->name);
2241 DoOneToMany(user->nick,"PART",params);
2245 virtual void OnUserConnect(userrec* user)
2247 char agestr[MAXBUF];
2248 if (std::string(user->server) == Srv->GetServerName())
2250 std::deque<std::string> params;
2251 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2252 params.push_back(agestr);
2253 params.push_back(user->nick);
2254 params.push_back(user->host);
2255 params.push_back(user->dhost);
2256 params.push_back(user->ident);
2257 params.push_back("+"+std::string(user->modes));
2258 params.push_back(user->ip);
2259 params.push_back(":"+std::string(user->fullname));
2260 DoOneToMany(Srv->GetServerName(),"NICK",params);
2264 virtual void OnUserQuit(userrec* user, std::string reason)
2266 if (std::string(user->server) == Srv->GetServerName())
2268 std::deque<std::string> params;
2269 params.push_back(":"+reason);
2270 DoOneToMany(user->nick,"QUIT",params);
2274 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2276 if (std::string(user->server) == Srv->GetServerName())
2278 std::deque<std::string> params;
2279 params.push_back(user->nick);
2280 DoOneToMany(oldnick,"NICK",params);
2284 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2286 if (std::string(source->server) == Srv->GetServerName())
2288 std::deque<std::string> params;
2289 params.push_back(chan->name);
2290 params.push_back(user->nick);
2291 params.push_back(":"+reason);
2292 DoOneToMany(source->nick,"KICK",params);
2296 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2298 std::deque<std::string> params;
2299 params.push_back(dest->nick);
2300 params.push_back(":"+reason);
2301 DoOneToMany(source->nick,"KILL",params);
2304 virtual void OnRehash(std::string parameter)
2306 if (parameter != "")
2308 std::deque<std::string> params;
2309 params.push_back(parameter);
2310 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2312 if (Srv->MatchText(Srv->GetServerName(),parameter))
2314 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2315 Srv->RehashServer();
2318 ReadConfiguration(false);
2321 // note: the protocol does not allow direct umode +o except
2322 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2324 virtual void OnOper(userrec* user, std::string opertype)
2326 if (std::string(user->server) == Srv->GetServerName())
2328 std::deque<std::string> params;
2329 params.push_back(opertype);
2330 DoOneToMany(user->nick,"OPERTYPE",params);
2334 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2336 if (std::string(source->server) == Srv->GetServerName())
2339 snprintf(type,8,"%cLINE",linetype);
2340 std::string stype = type;
2343 char sduration[MAXBUF];
2344 snprintf(sduration,MAXBUF,"%ld",duration);
2345 std::deque<std::string> params;
2346 params.push_back(host);
2347 params.push_back(sduration);
2348 params.push_back(":"+reason);
2349 DoOneToMany(source->nick,stype,params);
2353 std::deque<std::string> params;
2354 params.push_back(host);
2355 DoOneToMany(source->nick,stype,params);
2360 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2362 OnLine(source,hostmask,true,'G',duration,reason);
2365 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2367 OnLine(source,ipmask,true,'Z',duration,reason);
2370 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2372 OnLine(source,nickmask,true,'Q',duration,reason);
2375 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2377 OnLine(source,hostmask,true,'E',duration,reason);
2380 virtual void OnDelGLine(userrec* source, std::string hostmask)
2382 OnLine(source,hostmask,false,'G',0,"");
2385 virtual void OnDelZLine(userrec* source, std::string ipmask)
2387 OnLine(source,ipmask,false,'Z',0,"");
2390 virtual void OnDelQLine(userrec* source, std::string nickmask)
2392 OnLine(source,nickmask,false,'Q',0,"");
2395 virtual void OnDelELine(userrec* source, std::string hostmask)
2397 OnLine(source,hostmask,false,'E',0,"");
2400 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2402 if (std::string(user->server) == Srv->GetServerName())
2404 if (target_type == TYPE_USER)
2406 userrec* u = (userrec*)dest;
2407 std::deque<std::string> params;
2408 params.push_back(u->nick);
2409 params.push_back(text);
2410 DoOneToMany(user->nick,"MODE",params);
2414 chanrec* c = (chanrec*)dest;
2415 std::deque<std::string> params;
2416 params.push_back(c->name);
2417 params.push_back(text);
2418 DoOneToMany(user->nick,"MODE",params);
2423 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2425 TreeSocket* s = (TreeSocket*)opaque;
2428 if (target_type == TYPE_USER)
2430 userrec* u = (userrec*)target;
2431 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2435 chanrec* c = (chanrec*)target;
2436 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2441 virtual ~ModuleSpanningTree()
2446 virtual Version GetVersion()
2448 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2453 class ModuleSpanningTreeFactory : public ModuleFactory
2456 ModuleSpanningTreeFactory()
2460 ~ModuleSpanningTreeFactory()
2464 virtual Module * CreateModule()
2466 TreeProtocolModule = new ModuleSpanningTree;
2467 return TreeProtocolModule;
2473 extern "C" void * init_module( void )
2475 return new ModuleSpanningTreeFactory;