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"
42 #define nspace __gnu_cxx
47 class ModuleSpanningTree;
48 static ModuleSpanningTree* TreeProtocolModule;
50 extern std::vector<Module*> modules;
51 extern std::vector<ircd_module*> factory;
54 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
56 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
57 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
59 extern user_hash clientlist;
60 extern chan_hash chanlist;
67 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
68 server_hash serverlist;
70 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
71 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
72 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
73 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
74 void ReadConfiguration(bool rebind);
80 std::vector<TreeServer*> Children;
81 std::string ServerName;
82 std::string ServerDesc;
83 std::string VersionString;
86 TreeSocket* Socket; // for directly connected servers this points at the socket object
98 UserCount = OperCount = 0;
99 VersionString = GetVersionString();
102 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
106 UserCount = OperCount = 0;
107 VersionString = GetVersionString();
112 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
115 UserCount = OperCount = 0;
116 this->SetNextPingTime(time(NULL) + 60);
119 /* find the 'route' for this server (e.g. the one directly connected
120 * to the local server, which we can use to reach it)
122 * In the following example, consider we have just added a TreeServer
123 * class for server G on our network, of which we are server A.
124 * To route traffic to G (marked with a *) we must send the data to
125 * B (marked with a +) so this algorithm initializes the 'Route'
126 * value to point at whichever server traffic must be routed through
127 * to get here. If we were to try this algorithm with server B,
128 * the Route pointer would point at its own object ('this').
138 * We only run this algorithm when a server is created, as
139 * the routes remain constant while ever the server exists, and
140 * do not need to be re-calculated.
144 if (Route == TreeRoot)
150 while (this->Route->GetParent() != TreeRoot)
152 this->Route = Route->GetParent();
156 /* Because recursive code is slow and takes a lot of resources,
157 * we store two representations of the server tree. The first
158 * is a recursive structure where each server references its
159 * children and its parent, which is used for netbursts and
160 * netsplits to dump the whole dataset to the other server,
161 * and the second is used for very fast lookups when routing
162 * messages and is instead a hash_map, where each item can
163 * be referenced by its server name. The AddHashEntry()
164 * call below automatically inserts each TreeServer class
165 * into the hash_map as it is created. There is a similar
166 * maintainance call in the destructor to tidy up deleted
170 this->AddHashEntry();
175 server_hash::iterator iter;
176 iter = serverlist.find(this->ServerName);
177 if (iter == serverlist.end())
178 serverlist[this->ServerName] = this;
183 server_hash::iterator iter;
184 iter = serverlist.find(this->ServerName);
185 if (iter != serverlist.end())
186 serverlist.erase(iter);
189 TreeServer* GetRoute()
194 std::string GetName()
196 return this->ServerName;
199 std::string GetDesc()
201 return this->ServerDesc;
204 std::string GetVersion()
206 return this->VersionString;
209 void SetNextPingTime(time_t t)
212 LastPingWasGood = false;
215 time_t NextPingTime()
217 return this->NextPing;
220 bool AnsweredLastPing()
222 return LastPingWasGood;
227 LastPingWasGood = true;
232 return this->UserCount;
237 return this->OperCount;
240 TreeSocket* GetSocket()
245 TreeServer* GetParent()
250 void SetVersion(std::string Version)
252 VersionString = Version;
255 unsigned int ChildCount()
257 return Children.size();
260 TreeServer* GetChild(unsigned int n)
262 if (n < Children.size())
272 void AddChild(TreeServer* Child)
274 Children.push_back(Child);
277 bool DelChild(TreeServer* Child)
279 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
290 /* Removes child nodes of this node, and of that node, etc etc.
291 * This is used during netsplits to automatically tidy up the
292 * server tree. It is slow, we don't use it for much else.
296 bool stillchildren = true;
297 while (stillchildren)
299 stillchildren = false;
300 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
302 TreeServer* s = (TreeServer*)*a;
306 stillchildren = true;
315 this->DelHashEntry();
325 std::string SendPass;
326 std::string RecvPass;
327 unsigned long AutoConnect;
328 time_t NextConnectTime;
333 std::vector<Link> LinkBlocks;
335 TreeServer* FindServer(std::string ServerName)
337 server_hash::iterator iter;
338 iter = serverlist.find(ServerName);
339 if (iter != serverlist.end())
349 /* Returns the locally connected server we must route a
350 * message through to reach server 'ServerName'. This
351 * only applies to one-to-one and not one-to-many routing.
352 * See the comments for the constructor of TreeServer
355 TreeServer* BestRouteTo(std::string ServerName)
357 if (ServerName.c_str() == TreeRoot->GetName())
359 TreeServer* Found = FindServer(ServerName);
362 return Found->GetRoute();
372 /* TODO: These need optimizing to use an iterator of serverlist
374 void RFindServerMask(TreeServer* Current, std::string ServerName)
376 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
383 for (unsigned int q = 0; q < Current->ChildCount(); q++)
386 RFindServerMask(Current->GetChild(q),ServerName);
391 TreeServer* FindServerMask(std::string ServerName)
394 RFindServerMask(TreeRoot,ServerName);
398 bool IsServer(std::string ServerName)
400 return (FindServer(ServerName) != NULL);
403 class TreeSocket : public InspSocket
406 std::string in_buffer;
407 ServerState LinkState;
408 std::string InboundServerName;
409 std::string InboundDescription;
411 int num_lost_servers;
413 bool LastPingWasGood;
417 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
418 : InspSocket(host, port, listening, maxtime)
421 this->LinkState = LISTENER;
424 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
425 : InspSocket(host, port, listening, maxtime)
428 this->LinkState = CONNECTING;
431 TreeSocket(int newfd, char* ip)
432 : InspSocket(newfd, ip)
434 this->LinkState = WAIT_AUTH_1;
437 virtual bool OnConnected()
439 if (this->LinkState == CONNECTING)
441 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
442 // we should send our details here.
443 // if the other side is satisfied, they send theirs.
444 // we do not need to change state here.
445 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
447 if (x->Name == this->myhost)
449 // found who we're supposed to be connecting to, send the neccessary gubbins.
450 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
458 virtual void OnError(InspSocketError e)
462 virtual int OnDisconnect()
467 // recursively send the server tree with distances as hops
468 void SendServers(TreeServer* Current, TreeServer* s, int hops)
471 for (unsigned int q = 0; q < Current->ChildCount(); q++)
473 TreeServer* recursive_server = Current->GetChild(q);
474 if (recursive_server != s)
476 // :source.server SERVER server.name hops :Description
477 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
478 this->WriteLine(command);
479 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
480 // down to next level
481 this->SendServers(recursive_server, s, hops+1);
486 void SquitServer(TreeServer* Current)
488 // recursively squit the servers attached to 'Current'
489 for (unsigned int q = 0; q < Current->ChildCount(); q++)
491 TreeServer* recursive_server = Current->GetChild(q);
492 this->SquitServer(recursive_server);
494 // Now we've whacked the kids, whack self
496 bool quittingpeople = true;
497 while (quittingpeople)
499 quittingpeople = false;
500 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
502 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
504 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
506 quittingpeople = true;
513 void Squit(TreeServer* Current,std::string reason)
517 std::deque<std::string> params;
518 params.push_back(Current->GetName());
519 params.push_back(":"+reason);
520 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
521 if (Current->GetParent() == TreeRoot)
523 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
527 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
529 num_lost_servers = 0;
531 SquitServer(Current);
533 Current->GetParent()->DelChild(Current);
535 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
539 log(DEFAULT,"Squit from unknown server");
543 bool ForceMode(std::string source, std::deque<std::string> params)
545 userrec* who = new userrec;
546 who->fd = FD_MAGIC_NUMBER;
547 if (params.size() < 2)
550 for (unsigned int q = 0; q < params.size(); q++)
552 modelist[q] = (char*)params[q].c_str();
554 Srv->SendMode(modelist,params.size(),who);
555 DoOneToAllButSender(source,"FMODE",params,source);
560 bool ForceTopic(std::string source, std::deque<std::string> params)
562 // FTOPIC %s %lu %s :%s
563 if (params.size() != 4)
565 std::string channel = params[0];
566 time_t ts = atoi(params[1].c_str());
567 std::string setby = params[2];
568 std::string topic = params[3];
570 chanrec* c = Srv->FindChannel(channel);
573 if ((ts >= c->topicset) || (!*c->topic))
575 std::string oldtopic = c->topic;
576 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
577 strlcpy(c->setby,setby.c_str(),NICKMAX);
579 // if the topic text is the same as the current topic,
580 // dont bother to send the TOPIC command out, just silently
581 // update the set time and set nick.
582 if (oldtopic != topic)
583 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
588 // all done, send it on its way
589 params[3] = ":" + params[3];
590 DoOneToAllButSender(source,"FTOPIC",params,source);
595 bool ForceJoin(std::string source, std::deque<std::string> params)
597 if (params.size() < 3)
601 char modestring[MAXBUF];
602 char* mode_users[127];
603 mode_users[0] = first;
604 mode_users[1] = modestring;
605 strcpy(mode_users[1],"+");
606 unsigned int modectr = 2;
609 std::string channel = params[0];
610 time_t TS = atoi(params[1].c_str());
613 chanrec* chan = Srv->FindChannel(channel);
618 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
620 // default is a high value, which if we dont have this
621 // channel will let the other side apply their modes.
622 time_t ourTS = time(NULL)+600;
623 chanrec* us = Srv->FindChannel(channel);
629 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
631 // do this first, so our mode reversals are correctly received by other servers
632 // if there is a TS collision.
633 DoOneToAllButSender(source,"FJOIN",params,source);
635 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
637 // process one channel at a time, applying modes.
638 char* usr = (char*)params[usernum].c_str();
639 char permissions = *usr;
644 mode_users[modectr++] = usr;
645 strlcat(modestring,"o",MAXBUF);
649 mode_users[modectr++] = usr;
650 strlcat(modestring,"h",MAXBUF);
654 mode_users[modectr++] = usr;
655 strlcat(modestring,"v",MAXBUF);
658 who = Srv->FindNick(usr);
661 Srv->JoinUserToChannel(who,channel,key);
662 if (modectr >= (MAXMODES-1))
664 // theres a mode for this user. push them onto the mode queue, and flush it
665 // if there are more than MAXMODES to go.
668 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
669 Srv->SendMode(mode_users,modectr,who);
673 log(DEBUG,"Their channel newer than ours, bouncing their modes");
675 std::deque<std::string> params;
676 // modes are now being UNSET...
677 *mode_users[1] = '-';
678 for (unsigned int x = 0; x < modectr; x++)
680 params.push_back(mode_users[x]);
682 // tell everyone to bounce the modes. bad modes, bad!
683 DoOneToMany(Srv->GetServerName(),"FMODE",params);
685 strcpy(mode_users[1],"+");
690 // there werent enough modes built up to flush it during FJOIN,
691 // or, there are a number left over. flush them out.
692 if ((modectr > 2) && (who))
696 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
697 Srv->SendMode(mode_users,modectr,who);
701 log(DEBUG,"Their channel newer than ours, bouncing their modes");
702 std::deque<std::string> params;
703 *mode_users[1] = '-';
704 for (unsigned int x = 0; x < modectr; x++)
706 params.push_back(mode_users[x]);
708 DoOneToMany(Srv->GetServerName(),"FMODE",params);
714 bool IntroduceClient(std::string source, std::deque<std::string> params)
716 if (params.size() < 8)
718 // NICK age nick host dhost ident +modes ip :gecos
720 std::string nick = params[1];
721 std::string host = params[2];
722 std::string dhost = params[3];
723 std::string ident = params[4];
724 time_t age = atoi(params[0].c_str());
725 std::string modes = params[5];
726 while (*(modes.c_str()) == '+')
728 char* m = (char*)modes.c_str();
732 std::string ip = params[6];
733 std::string gecos = params[7];
734 char* tempnick = (char*)nick.c_str();
735 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
737 user_hash::iterator iter;
738 iter = clientlist.find(tempnick);
739 if (iter != clientlist.end())
742 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);
743 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
747 clientlist[tempnick] = new userrec();
748 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
749 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
750 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
751 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
752 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
753 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
754 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
755 clientlist[tempnick]->registered = 7;
756 clientlist[tempnick]->signon = age;
757 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
758 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
759 for (int i = 0; i < MAXCHANS; i++)
761 clientlist[tempnick]->chans[i].channel = NULL;
762 clientlist[tempnick]->chans[i].uc_modes = 0;
764 params[7] = ":" + params[7];
765 DoOneToAllButSender(source,"NICK",params,source);
769 void SendFJoins(TreeServer* Current, chanrec* c)
772 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
773 std::vector<char*> *ulist = c->GetUsers();
774 for (unsigned int i = 0; i < ulist->size(); i++)
776 char* o = (*ulist)[i];
777 userrec* otheruser = (userrec*)o;
778 strlcat(list," ",MAXBUF);
779 strlcat(list,cmode(otheruser,c),MAXBUF);
780 strlcat(list,otheruser->nick,MAXBUF);
781 if (strlen(list)>(480-NICKMAX))
783 this->WriteLine(list);
784 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
787 if (list[strlen(list)-1] != ':')
789 this->WriteLine(list);
793 void SendChannelModes(TreeServer* Current)
796 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
798 SendFJoins(Current, c->second);
799 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
800 this->WriteLine(data);
801 if (*c->second->topic)
803 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);
804 this->WriteLine(data);
806 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
808 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
809 this->WriteLine(data);
811 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
815 // send all users and their channels
816 void SendUsers(TreeServer* Current)
819 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
821 if (u->second->registered == 7)
823 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);
824 this->WriteLine(data);
825 if (strchr(u->second->modes,'o'))
827 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
829 //char* chl = chlist(u->second,u->second);
832 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
834 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
839 void DoBurst(TreeServer* s)
841 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
842 this->WriteLine("BURST");
843 // send our version string
844 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
846 this->SendServers(TreeRoot,s,1);
847 // Send users and their channels
849 // Send everything else (channel modes etc)
850 this->SendChannelModes(s);
851 this->WriteLine("ENDBURST");
854 virtual bool OnDataReady()
856 char* data = this->Read();
859 this->in_buffer += data;
860 while (in_buffer.find("\n") != std::string::npos)
862 char* line = (char*)in_buffer.c_str();
863 std::string ret = "";
864 while ((*line != '\n') && (strlen(line)))
869 if ((*line == '\n') || (*line == '\r'))
872 if (!this->ProcessLine(ret))
878 return (data != NULL);
881 int WriteLine(std::string line)
883 return this->Write(line + "\r\n");
886 bool Error(std::deque<std::string> params)
888 if (params.size() < 1)
890 std::string Errmsg = params[0];
891 std::string SName = myhost;
892 if (InboundServerName != "")
894 SName = InboundServerName;
896 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
897 // we will return false to cause the socket to close.
901 bool OperType(std::string prefix, std::deque<std::string> params)
903 if (params.size() != 1)
905 std::string opertype = params[0];
906 userrec* u = Srv->FindNick(prefix);
909 strlcpy(u->oper,opertype.c_str(),NICKMAX);
910 if (!strchr(u->modes,'o'))
912 strcat(u->modes,"o");
914 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
919 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
921 if (params.size() < 1)
923 std::string servermask = params[0];
924 if (Srv->MatchText(Srv->GetServerName(),servermask))
926 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
928 ReadConfiguration(false);
930 DoOneToAllButSender(prefix,"REHASH",params,prefix);
934 bool RemoteKill(std::string prefix, std::deque<std::string> params)
936 if (params.size() != 2)
938 std::string nick = params[0];
939 std::string reason = params[1];
940 userrec* u = Srv->FindNick(prefix);
941 userrec* who = Srv->FindNick(nick);
944 std::string sourceserv = prefix;
947 sourceserv = u->server;
949 params[1] = ":" + params[1];
950 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
951 Srv->QuitUser(who,reason);
956 bool LocalPong(std::string prefix, std::deque<std::string> params)
958 if (params.size() < 1)
960 TreeServer* ServerSource = FindServer(prefix);
963 ServerSource->SetPingFlag();
968 bool ServerVersion(std::string prefix, std::deque<std::string> params)
970 if (params.size() < 1)
972 TreeServer* ServerSource = FindServer(prefix);
975 ServerSource->SetVersion(params[0]);
977 params[0] = ":" + params[0];
978 DoOneToAllButSender(prefix,"VERSION",params,prefix);
982 bool ChangeHost(std::string prefix, std::deque<std::string> params)
984 if (params.size() < 1)
986 userrec* u = Srv->FindNick(prefix);
989 Srv->ChangeHost(u,params[0]);
990 DoOneToAllButSender(prefix,"FHOST",params,u->server);
995 bool ChangeName(std::string prefix, std::deque<std::string> params)
997 if (params.size() < 1)
999 userrec* u = Srv->FindNick(prefix);
1002 Srv->ChangeGECOS(u,params[0]);
1003 params[0] = ":" + params[0];
1004 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1009 bool LocalPing(std::string prefix, std::deque<std::string> params)
1011 if (params.size() < 1)
1013 std::string stufftobounce = params[0];
1014 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1018 bool RemoteServer(std::string prefix, std::deque<std::string> params)
1020 if (params.size() < 4)
1022 std::string servername = params[0];
1023 std::string password = params[1];
1024 // hopcount is not used for a remote server, we calculate this ourselves
1025 std::string description = params[3];
1026 TreeServer* ParentOfThis = FindServer(prefix);
1029 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1032 TreeServer* CheckDupe = FindServer(servername);
1035 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1038 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1039 ParentOfThis->AddChild(Node);
1040 params[3] = ":" + params[3];
1041 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1042 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1046 bool Outbound_Reply_Server(std::deque<std::string> params)
1048 if (params.size() < 4)
1050 std::string servername = params[0];
1051 std::string password = params[1];
1052 int hops = atoi(params[2].c_str());
1055 this->WriteLine("ERROR :Server too far away for authentication");
1058 std::string description = params[3];
1059 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1061 if ((x->Name == servername) && (x->RecvPass == password))
1063 TreeServer* CheckDupe = FindServer(servername);
1066 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1069 // Begin the sync here. this kickstarts the
1070 // other side, waiting in WAIT_AUTH_2 state,
1071 // into starting their burst, as it shows
1072 // that we're happy.
1073 this->LinkState = CONNECTED;
1074 // we should add the details of this server now
1075 // to the servers tree, as a child of the root
1077 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1078 TreeRoot->AddChild(Node);
1079 params[3] = ":" + params[3];
1080 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1081 this->DoBurst(Node);
1085 this->WriteLine("ERROR :Invalid credentials");
1089 bool Inbound_Server(std::deque<std::string> params)
1091 if (params.size() < 4)
1093 std::string servername = params[0];
1094 std::string password = params[1];
1095 int hops = atoi(params[2].c_str());
1098 this->WriteLine("ERROR :Server too far away for authentication");
1101 std::string description = params[3];
1102 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1104 if ((x->Name == servername) && (x->RecvPass == password))
1106 TreeServer* CheckDupe = FindServer(servername);
1109 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1112 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1113 this->InboundServerName = servername;
1114 this->InboundDescription = description;
1115 // this is good. Send our details: Our server name and description and hopcount of 0,
1116 // along with the sendpass from this block.
1117 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1118 // move to the next state, we are now waiting for THEM.
1119 this->LinkState = WAIT_AUTH_2;
1123 this->WriteLine("ERROR :Invalid credentials");
1127 std::deque<std::string> Split(std::string line, bool stripcolon)
1129 std::deque<std::string> n;
1130 if (!strchr(line.c_str(),' '))
1135 std::stringstream s(line);
1136 std::string param = "";
1155 if ((param == ":") && (item > 0))
1178 bool ProcessLine(std::string line)
1180 char* l = (char*)line.c_str();
1181 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1182 l[strlen(l)-1] = '\0';
1186 Srv->Log(DEBUG,"IN: '"+line+"'");
1187 std::deque<std::string> params = this->Split(line,true);
1188 std::string command = "";
1189 std::string prefix = "";
1190 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1193 command = params[1];
1194 char* pref = (char*)prefix.c_str();
1202 command = params[0];
1206 switch (this->LinkState)
1211 // Waiting for SERVER command from remote server. Server initiating
1212 // the connection sends the first SERVER command, listening server
1213 // replies with theirs if its happy, then if the initiator is happy,
1214 // it starts to send its net sync, which starts the merge, otherwise
1215 // it sends an ERROR.
1216 if (command == "SERVER")
1218 return this->Inbound_Server(params);
1220 else if (command == "ERROR")
1222 return this->Error(params);
1226 // Waiting for start of other side's netmerge to say they liked our
1228 if (command == "SERVER")
1230 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1234 else if (command == "BURST")
1236 this->LinkState = CONNECTED;
1237 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1238 TreeRoot->AddChild(Node);
1240 params.push_back(InboundServerName);
1241 params.push_back("*");
1242 params.push_back("1");
1243 params.push_back(":"+InboundDescription);
1244 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1245 this->DoBurst(Node);
1247 else if (command == "ERROR")
1249 return this->Error(params);
1254 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1258 if (command == "SERVER")
1260 // another server we connected to, which was in WAIT_AUTH_1 state,
1261 // has just sent us their credentials. If we get this far, theyre
1262 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1263 // if we're happy with this, we should send our netburst which
1264 // kickstarts the merge.
1265 return this->Outbound_Reply_Server(params);
1267 else if (command == "ERROR")
1269 return this->Error(params);
1273 // This is the 'authenticated' state, when all passwords
1274 // have been exchanged and anything past this point is taken
1276 std::string target = "";
1277 if ((command == "NICK") && (params.size() > 1))
1279 return this->IntroduceClient(prefix,params);
1281 else if (command == "FJOIN")
1283 return this->ForceJoin(prefix,params);
1285 else if (command == "SERVER")
1287 return this->RemoteServer(prefix,params);
1289 else if (command == "ERROR")
1291 return this->Error(params);
1293 else if (command == "OPERTYPE")
1295 return this->OperType(prefix,params);
1297 else if (command == "FMODE")
1299 return this->ForceMode(prefix,params);
1301 else if (command == "KILL")
1303 return this->RemoteKill(prefix,params);
1305 else if (command == "FTOPIC")
1307 return this->ForceTopic(prefix,params);
1309 else if (command == "REHASH")
1311 return this->RemoteRehash(prefix,params);
1313 else if (command == "PING")
1315 return this->LocalPing(prefix,params);
1317 else if (command == "PONG")
1319 return this->LocalPong(prefix,params);
1321 else if (command == "VERSION")
1323 return this->ServerVersion(prefix,params);
1325 else if (command == "FHOST")
1327 return this->ChangeHost(prefix,params);
1329 else if (command == "FNAME")
1331 return this->ChangeName(prefix,params);
1333 else if (command == "SQUIT")
1335 if (params.size() == 2)
1337 this->Squit(FindServer(params[0]),params[1]);
1343 // not a special inter-server command.
1344 // Emulate the actual user doing the command,
1345 // this saves us having a huge ugly parser.
1346 userrec* who = Srv->FindNick(prefix);
1347 std::string sourceserv = this->myhost;
1348 if (this->InboundServerName != "")
1350 sourceserv = this->InboundServerName;
1355 target = who->server;
1356 char* strparams[127];
1357 for (unsigned int q = 0; q < params.size(); q++)
1359 strparams[q] = (char*)params[q].c_str();
1361 Srv->CallCommandHandler(command, strparams, params.size(), who);
1365 // its not a user. Its either a server, or somethings screwed up.
1366 if (IsServer(prefix))
1368 target = Srv->GetServerName();
1372 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1376 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1385 virtual std::string GetName()
1387 std::string sourceserv = this->myhost;
1388 if (this->InboundServerName != "")
1390 sourceserv = this->InboundServerName;
1395 virtual void OnTimeout()
1397 if (this->LinkState == CONNECTING)
1399 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1403 virtual void OnClose()
1405 // Connection closed.
1406 // If the connection is fully up (state CONNECTED)
1407 // then propogate a netsplit to all peers.
1408 std::string quitserver = this->myhost;
1409 if (this->InboundServerName != "")
1411 quitserver = this->InboundServerName;
1413 TreeServer* s = FindServer(quitserver);
1416 Squit(s,"Remote host closed the connection");
1420 virtual int OnIncomingConnection(int newsock, char* ip)
1422 TreeSocket* s = new TreeSocket(newsock, ip);
1428 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1430 for (unsigned int c = 0; c < list.size(); c++)
1432 if (list[c] == server)
1437 list.push_back(server);
1440 // returns a list of DIRECT servernames for a specific channel
1441 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
1443 std::vector<char*> *ulist = c->GetUsers();
1444 unsigned int ucount = ulist->size();
1445 for (unsigned int i = 0; i < ucount; i++)
1447 char* o = (*ulist)[i];
1448 userrec* otheruser = (userrec*)o;
1449 if (std::string(otheruser->server) != Srv->GetServerName())
1451 TreeServer* best = BestRouteTo(otheruser->server);
1453 AddThisServer(best,list);
1459 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1461 TreeServer* omitroute = BestRouteTo(omit);
1462 if ((command == "NOTICE") || (command == "PRIVMSG"))
1464 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1466 if (*(params[0].c_str()) != '#')
1468 // special routing for private messages/notices
1469 userrec* d = Srv->FindNick(params[0]);
1472 std::deque<std::string> par;
1473 par.push_back(params[0]);
1474 par.push_back(":"+params[1]);
1475 DoOneToOne(prefix,command,par,d->server);
1481 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1482 chanrec* c = Srv->FindChannel(params[0]);
1485 std::deque<TreeServer*> list;
1486 GetListOfServersForChannel(c,list);
1487 log(DEBUG,"Got a list of %d servers",list.size());
1488 unsigned int lsize = list.size();
1489 for (unsigned int i = 0; i < lsize; i++)
1491 TreeSocket* Sock = list[i]->GetSocket();
1492 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1494 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1495 Sock->WriteLine(data);
1503 unsigned int items = TreeRoot->ChildCount();
1504 for (unsigned int x = 0; x < items; x++)
1506 TreeServer* Route = TreeRoot->GetChild(x);
1507 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1509 TreeSocket* Sock = Route->GetSocket();
1510 Sock->WriteLine(data);
1516 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1518 TreeServer* omitroute = BestRouteTo(omit);
1519 std::string FullLine = ":" + prefix + " " + command;
1520 unsigned int words = params.size();
1521 for (unsigned int x = 0; x < words; x++)
1523 FullLine = FullLine + " " + params[x];
1525 unsigned int items = TreeRoot->ChildCount();
1526 for (unsigned int x = 0; x < items; x++)
1528 TreeServer* Route = TreeRoot->GetChild(x);
1529 // Send the line IF:
1530 // The route has a socket (its a direct connection)
1531 // The route isnt the one to be omitted
1532 // The route isnt the path to the one to be omitted
1533 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1535 TreeSocket* Sock = Route->GetSocket();
1536 Sock->WriteLine(FullLine);
1542 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1544 std::string FullLine = ":" + prefix + " " + command;
1545 unsigned int words = params.size();
1546 for (unsigned int x = 0; x < words; x++)
1548 FullLine = FullLine + " " + params[x];
1550 unsigned int items = TreeRoot->ChildCount();
1551 for (unsigned int x = 0; x < items; x++)
1553 TreeServer* Route = TreeRoot->GetChild(x);
1554 if (Route->GetSocket())
1556 TreeSocket* Sock = Route->GetSocket();
1557 Sock->WriteLine(FullLine);
1563 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1565 TreeServer* Route = BestRouteTo(target);
1568 std::string FullLine = ":" + prefix + " " + command;
1569 unsigned int words = params.size();
1570 for (unsigned int x = 0; x < words; x++)
1572 FullLine = FullLine + " " + params[x];
1574 if (Route->GetSocket())
1576 TreeSocket* Sock = Route->GetSocket();
1577 Sock->WriteLine(FullLine);
1587 std::vector<TreeSocket*> Bindings;
1589 void ReadConfiguration(bool rebind)
1593 for (int j =0; j < Conf->Enumerate("bind"); j++)
1595 std::string Type = Conf->ReadValue("bind","type",j);
1596 std::string IP = Conf->ReadValue("bind","address",j);
1597 long Port = Conf->ReadInteger("bind","port",j,true);
1598 if (Type == "servers")
1604 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1605 if (listener->GetState() == I_LISTENING)
1607 Srv->AddSocket(listener);
1608 Bindings.push_back(listener);
1612 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1620 for (int j =0; j < Conf->Enumerate("link"); j++)
1623 L.Name = Conf->ReadValue("link","name",j);
1624 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1625 L.Port = Conf->ReadInteger("link","port",j,true);
1626 L.SendPass = Conf->ReadValue("link","sendpass",j);
1627 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1628 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1629 L.NextConnectTime = time(NULL) + L.AutoConnect;
1630 LinkBlocks.push_back(L);
1631 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1636 class ModuleSpanningTree : public Module
1638 std::vector<TreeSocket*> Bindings;
1644 ModuleSpanningTree()
1647 Conf = new ConfigReader;
1650 // Create the root of the tree
1651 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1653 ReadConfiguration(true);
1656 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1658 std::string Parent = TreeRoot->GetName();
1659 if (Current->GetParent())
1661 Parent = Current->GetParent()->GetName();
1663 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1665 ShowLinks(Current->GetChild(q),user,hops+1);
1667 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1670 int CountLocalServs()
1672 return TreeRoot->ChildCount();
1675 void CountServsRecursive(TreeServer* Current)
1678 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1680 CountServsRecursive(Current->GetChild(q));
1687 CountServsRecursive(TreeRoot);
1691 void HandleLinks(char** parameters, int pcnt, userrec* user)
1693 ShowLinks(TreeRoot,user,0);
1694 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1698 void HandleLusers(char** parameters, int pcnt, userrec* user)
1700 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1701 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1702 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1703 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1704 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1708 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1710 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1714 for (int t = 0; t < depth; t++)
1716 matrix[line][t] = ' ';
1718 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1720 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1722 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1727 // Ok, prepare to be confused.
1728 // After much mulling over how to approach this, it struck me that
1729 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1730 // keeping track of a ton of ascii characters, and line by line
1731 // under recursion working out where to place them using multiplications
1732 // and divisons, we instead render the map onto a backplane of characters
1733 // (a character matrix), then draw the branches as a series of "L" shapes
1734 // from the nodes. This is not only friendlier on CPU it uses less stack.
1736 void HandleMap(char** parameters, int pcnt, userrec* user)
1738 // This array represents a virtual screen which we will
1739 // "scratch" draw to, as the console device of an irc
1740 // client does not provide for a proper terminal.
1741 char matrix[128][80];
1742 for (unsigned int t = 0; t < 128; t++)
1744 matrix[t][0] = '\0';
1747 // The only recursive bit is called here.
1748 ShowMap(TreeRoot,user,0,matrix);
1749 // Process each line one by one. The algorithm has a limit of
1750 // 128 servers (which is far more than a spanning tree should have
1751 // anyway, so we're ok). This limit can be raised simply by making
1752 // the character matrix deeper, 128 rows taking 10k of memory.
1753 for (int l = 1; l < line; l++)
1755 // scan across the line looking for the start of the
1756 // servername (the recursive part of the algorithm has placed
1757 // the servers at indented positions depending on what they
1759 int first_nonspace = 0;
1760 while (matrix[l][first_nonspace] == ' ')
1765 // Draw the `- (corner) section: this may be overwritten by
1766 // another L shape passing along the same vertical pane, becoming
1767 // a |- (branch) section instead.
1768 matrix[l][first_nonspace] = '-';
1769 matrix[l][first_nonspace-1] = '`';
1771 // Draw upwards until we hit the parent server, causing possibly
1772 // other corners (`-) to become branches (|-)
1773 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1775 matrix[l2][first_nonspace-1] = '|';
1779 // dump the whole lot to the user. This is the easy bit, honest.
1780 for (int t = 0; t < line; t++)
1782 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1784 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1788 int HandleSquit(char** parameters, int pcnt, userrec* user)
1790 TreeServer* s = FindServerMask(parameters[0]);
1793 TreeSocket* sock = s->GetSocket();
1796 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1797 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1802 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1807 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1812 void DoPingChecks(time_t curtime)
1814 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1816 TreeServer* serv = TreeRoot->GetChild(j);
1817 TreeSocket* sock = serv->GetSocket();
1820 if (curtime >= serv->NextPingTime())
1822 if (serv->AnsweredLastPing())
1824 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1825 serv->SetNextPingTime(curtime + 60);
1829 // they didnt answer, boot them
1830 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1831 sock->Squit(serv,"Ping timeout");
1840 void AutoConnectServers(time_t curtime)
1842 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1844 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1846 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1847 x->NextConnectTime = curtime + x->AutoConnect;
1848 TreeServer* CheckDupe = FindServer(x->Name);
1851 // an autoconnected server is not connected. Check if its time to connect it
1852 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1853 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1854 Srv->AddSocket(newsocket);
1860 int HandleVersion(char** parameters, int pcnt, userrec* user)
1862 // we've already checked if pcnt > 0, so this is safe
1863 TreeServer* found = FindServerMask(parameters[0]);
1866 std::string Version = found->GetVersion();
1867 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1871 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1876 int HandleConnect(char** parameters, int pcnt, userrec* user)
1878 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1880 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1882 TreeServer* CheckDupe = FindServer(x->Name);
1885 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);
1886 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1887 Srv->AddSocket(newsocket);
1892 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());
1897 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1901 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1903 if (command == "CONNECT")
1905 return this->HandleConnect(parameters,pcnt,user);
1907 else if (command == "SQUIT")
1909 return this->HandleSquit(parameters,pcnt,user);
1911 else if (command == "MAP")
1913 this->HandleMap(parameters,pcnt,user);
1916 else if (command == "LUSERS")
1918 this->HandleLusers(parameters,pcnt,user);
1921 else if (command == "LINKS")
1923 this->HandleLinks(parameters,pcnt,user);
1926 else if ((command == "VERSION") && (pcnt > 0))
1928 this->HandleVersion(parameters,pcnt,user);
1931 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1933 // this bit of code cleverly routes all module commands
1934 // to all remote severs *automatically* so that modules
1935 // can just handle commands locally, without having
1936 // to have any special provision in place for remote
1937 // commands and linking protocols.
1938 std::deque<std::string> params;
1940 for (int j = 0; j < pcnt; j++)
1942 if (strchr(parameters[j],' '))
1944 params.push_back(":" + std::string(parameters[j]));
1948 params.push_back(std::string(parameters[j]));
1951 DoOneToMany(user->nick,command,params);
1956 virtual void OnGetServerDescription(std::string servername,std::string &description)
1958 TreeServer* s = FindServer(servername);
1961 description = s->GetDesc();
1965 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1967 if (std::string(source->server) == Srv->GetServerName())
1969 std::deque<std::string> params;
1970 params.push_back(dest->nick);
1971 params.push_back(channel->name);
1972 DoOneToMany(source->nick,"INVITE",params);
1976 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1978 std::deque<std::string> params;
1979 params.push_back(chan->name);
1980 params.push_back(":"+topic);
1981 DoOneToMany(user->nick,"TOPIC",params);
1984 virtual void OnWallops(userrec* user, std::string text)
1986 if (std::string(user->server) == Srv->GetServerName())
1988 std::deque<std::string> params;
1989 params.push_back(":"+text);
1990 DoOneToMany(user->nick,"WALLOPS",params);
1994 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1996 if (target_type == TYPE_USER)
1998 userrec* d = (userrec*)dest;
1999 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2001 std::deque<std::string> params;
2003 params.push_back(d->nick);
2004 params.push_back(":"+text);
2005 DoOneToOne(user->nick,"NOTICE",params,d->server);
2010 if (std::string(user->server) == Srv->GetServerName())
2012 chanrec *c = (chanrec*)dest;
2013 std::deque<TreeServer*> list;
2014 GetListOfServersForChannel(c,list);
2015 unsigned int ucount = list.size();
2016 for (unsigned int i = 0; i < ucount; i++)
2018 TreeSocket* Sock = list[i]->GetSocket();
2020 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2026 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2028 if (target_type == TYPE_USER)
2030 // route private messages which are targetted at clients only to the server
2031 // which needs to receive them
2032 userrec* d = (userrec*)dest;
2033 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2035 std::deque<std::string> params;
2037 params.push_back(d->nick);
2038 params.push_back(":"+text);
2039 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2044 if (std::string(user->server) == Srv->GetServerName())
2046 chanrec *c = (chanrec*)dest;
2047 std::deque<TreeServer*> list;
2048 GetListOfServersForChannel(c,list);
2049 unsigned int ucount = list.size();
2050 for (unsigned int i = 0; i < ucount; i++)
2052 TreeSocket* Sock = list[i]->GetSocket();
2054 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2060 virtual void OnBackgroundTimer(time_t curtime)
2062 AutoConnectServers(curtime);
2063 DoPingChecks(curtime);
2066 virtual void OnUserJoin(userrec* user, chanrec* channel)
2068 // Only do this for local users
2069 if (std::string(user->server) == Srv->GetServerName())
2071 std::deque<std::string> params;
2073 params.push_back(channel->name);
2076 // if the channel has a key, force the join by emulating the key.
2077 params.push_back(channel->key);
2079 if (channel->GetUserCounter() > 1)
2081 // not the first in the channel
2082 DoOneToMany(user->nick,"JOIN",params);
2086 // first in the channel, set up their permissions
2087 // and the channel TS with FJOIN.
2089 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2091 params.push_back(channel->name);
2092 params.push_back(ts);
2093 params.push_back("@"+std::string(user->nick));
2094 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2099 virtual void OnChangeHost(userrec* user, std::string newhost)
2101 // only occurs for local clients
2102 std::deque<std::string> params;
2103 params.push_back(newhost);
2104 DoOneToMany(user->nick,"FHOST",params);
2107 virtual void OnChangeName(userrec* user, std::string gecos)
2109 // only occurs for local clients
2110 std::deque<std::string> params;
2111 params.push_back(gecos);
2112 DoOneToMany(user->nick,"FNAME",params);
2115 virtual void OnUserPart(userrec* user, chanrec* channel)
2117 if (std::string(user->server) == Srv->GetServerName())
2119 std::deque<std::string> params;
2120 params.push_back(channel->name);
2121 DoOneToMany(user->nick,"PART",params);
2125 virtual void OnUserConnect(userrec* user)
2127 char agestr[MAXBUF];
2128 if (std::string(user->server) == Srv->GetServerName())
2130 std::deque<std::string> params;
2131 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2132 params.push_back(agestr);
2133 params.push_back(user->nick);
2134 params.push_back(user->host);
2135 params.push_back(user->dhost);
2136 params.push_back(user->ident);
2137 params.push_back("+"+std::string(user->modes));
2138 params.push_back(user->ip);
2139 params.push_back(":"+std::string(user->fullname));
2140 DoOneToMany(Srv->GetServerName(),"NICK",params);
2144 virtual void OnUserQuit(userrec* user, std::string reason)
2146 if (std::string(user->server) == Srv->GetServerName())
2148 std::deque<std::string> params;
2149 params.push_back(":"+reason);
2150 DoOneToMany(user->nick,"QUIT",params);
2154 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2156 if (std::string(user->server) == Srv->GetServerName())
2158 std::deque<std::string> params;
2159 params.push_back(user->nick);
2160 DoOneToMany(oldnick,"NICK",params);
2164 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2166 if (std::string(source->server) == Srv->GetServerName())
2168 std::deque<std::string> params;
2169 params.push_back(chan->name);
2170 params.push_back(user->nick);
2171 params.push_back(":"+reason);
2172 DoOneToMany(source->nick,"KICK",params);
2176 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2178 std::deque<std::string> params;
2179 params.push_back(dest->nick);
2180 params.push_back(":"+reason);
2181 DoOneToMany(source->nick,"KILL",params);
2184 virtual void OnRehash(std::string parameter)
2186 if (parameter != "")
2188 std::deque<std::string> params;
2189 params.push_back(parameter);
2190 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2192 if (Srv->MatchText(Srv->GetServerName(),parameter))
2194 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2195 Srv->RehashServer();
2198 ReadConfiguration(false);
2201 // note: the protocol does not allow direct umode +o except
2202 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2204 virtual void OnOper(userrec* user, std::string opertype)
2206 if (std::string(user->server) == Srv->GetServerName())
2208 std::deque<std::string> params;
2209 params.push_back(opertype);
2210 DoOneToMany(user->nick,"OPERTYPE",params);
2214 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2216 if (std::string(source->server) == Srv->GetServerName())
2220 char sduration[MAXBUF];
2221 snprintf(sduration,MAXBUF,"%ld",duration);
2222 std::deque<std::string> params;
2223 params.push_back(host);
2224 params.push_back(sduration);
2225 params.push_back(":"+reason);
2226 DoOneToMany(source->nick,linetype+"LINE",params);
2230 std::deque<std::string> params;
2231 params.push_back(host);
2232 DoOneToMany(source->nick,linetype+"LINE",params);
2237 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2239 OnLine(source,hostmask,true,'G',duration,reason);
2242 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2244 OnLine(source,ipmask,true,'Z',duration,reason);
2247 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2249 OnLine(source,nickmask,true,'Q',duration,reason);
2252 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2254 OnLine(source,hostmask,true,'E',duration,reason);
2257 virtual void OnDelGLine(userrec* source, std::string hostmask)
2259 OnLine(source,hostmask,false,'G',"","");
2262 virtual void OnDelZLine(userrec* source, std::string ipmask)
2264 OnLine(source,ipmask,false,'Z',"","");
2267 virtual void OnDelQLine(userrec* source, std::string nickmask)
2269 OnLine(source,nickmask,false,'Q',"","");
2272 virtual void OnDelELine(userrec* source, std::string hostmask)
2274 OnLine(source,hostmask,false,'E',"","");
2277 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2279 if (std::string(user->server) == Srv->GetServerName())
2281 if (target_type == TYPE_USER)
2283 userrec* u = (userrec*)dest;
2284 std::deque<std::string> params;
2285 params.push_back(u->nick);
2286 params.push_back(text);
2287 DoOneToMany(user->nick,"MODE",params);
2291 chanrec* c = (chanrec*)dest;
2292 std::deque<std::string> params;
2293 params.push_back(c->name);
2294 params.push_back(text);
2295 DoOneToMany(user->nick,"MODE",params);
2300 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2302 TreeSocket* s = (TreeSocket*)opaque;
2305 if (target_type == TYPE_USER)
2307 userrec* u = (userrec*)target;
2308 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2312 chanrec* c = (chanrec*)target;
2313 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2318 virtual ~ModuleSpanningTree()
2323 virtual Version GetVersion()
2325 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2330 class ModuleSpanningTreeFactory : public ModuleFactory
2333 ModuleSpanningTreeFactory()
2337 ~ModuleSpanningTreeFactory()
2341 virtual Module * CreateModule()
2343 TreeProtocolModule = new ModuleSpanningTree;
2344 return TreeProtocolModule;
2350 extern "C" void * init_module( void )
2352 return new ModuleSpanningTreeFactory;