1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
23 #include "inspircd_config.h"
25 #include <ext/hash_map>
33 #include "helperfuncs.h"
35 #include "inspstring.h"
40 #define nspace __gnu_cxx
45 class ModuleSpanningTree;
46 static ModuleSpanningTree* TreeProtocolModule;
48 extern std::vector<Module*> modules;
49 extern std::vector<ircd_module*> factory;
52 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
54 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
55 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
57 extern user_hash clientlist;
58 extern chan_hash chanlist;
63 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
64 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
65 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
66 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
67 void ReadConfiguration(bool rebind);
73 std::vector<TreeServer*> Children;
74 std::string ServerName;
75 std::string ServerDesc;
76 std::string VersionString;
79 TreeSocket* Socket; // for directly connected servers this points at the socket object
91 UserCount = OperCount = 0;
92 VersionString = GetVersionString();
95 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
99 UserCount = OperCount = 0;
100 VersionString = GetVersionString();
104 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
107 UserCount = OperCount = 0;
108 this->SetNextPingTime(time(NULL) + 60);
111 // find the 'route' for this server (e.g. the one directly connected
112 // to the local server, which we can use to reach it)
114 if (Route != TreeRoot)
115 while (Route->GetParent() != TreeRoot)
116 Route = Route->GetParent();
119 TreeServer* GetRoute()
124 std::string GetName()
126 return this->ServerName;
129 std::string GetDesc()
131 return this->ServerDesc;
134 std::string GetVersion()
136 return this->VersionString;
139 void SetNextPingTime(time_t t)
142 LastPingWasGood = false;
145 time_t NextPingTime()
147 return this->NextPing;
150 bool AnsweredLastPing()
152 return LastPingWasGood;
157 LastPingWasGood = true;
162 return this->UserCount;
167 return this->OperCount;
170 TreeSocket* GetSocket()
175 TreeServer* GetParent()
180 void SetVersion(std::string Version)
182 VersionString = Version;
185 unsigned int ChildCount()
187 return Children.size();
190 TreeServer* GetChild(unsigned int n)
192 if (n < Children.size())
202 void AddChild(TreeServer* Child)
204 Children.push_back(Child);
207 bool DelChild(TreeServer* Child)
209 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
220 // removes child nodes of this node, and of that node, etc etc
223 bool stillchildren = true;
224 while (stillchildren)
226 stillchildren = false;
227 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
229 TreeServer* s = (TreeServer*)*a;
233 stillchildren = true;
247 std::string SendPass;
248 std::string RecvPass;
249 unsigned long AutoConnect;
250 time_t NextConnectTime;
253 /* $ModDesc: Povides a spanning tree server link protocol */
257 TreeServer *TreeRoot;
258 std::vector<Link> LinkBlocks;
260 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
262 if (Current->GetName() == ServerName)
263 return Current->GetRoute();
264 for (unsigned int q = 0; q < Current->ChildCount(); q++)
266 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
268 return found->GetRoute();
273 // Returns the locally connected server we must route a
274 // message through to reach server 'ServerName'. This
275 // only applies to one-to-one and not one-to-many routing.
276 TreeServer* BestRouteTo(std::string ServerName)
278 if (ServerName.c_str() == TreeRoot->GetName())
282 // first, find the server by recursively walking the tree
283 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
287 bool LookForServer(TreeServer* Current, std::string ServerName)
289 if (ServerName == Current->GetName())
291 for (unsigned int q = 0; q < Current->ChildCount(); q++)
293 if (LookForServer(Current->GetChild(q),ServerName))
301 void RFindServer(TreeServer* Current, std::string ServerName)
303 if ((ServerName == Current->GetName()) && (!Found))
310 for (unsigned int q = 0; q < Current->ChildCount(); q++)
313 RFindServer(Current->GetChild(q),ServerName);
319 void RFindServerMask(TreeServer* Current, std::string ServerName)
321 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
328 for (unsigned int q = 0; q < Current->ChildCount(); q++)
331 RFindServerMask(Current->GetChild(q),ServerName);
336 TreeServer* FindServer(std::string ServerName)
339 RFindServer(TreeRoot,ServerName);
343 TreeServer* FindServerMask(std::string ServerName)
346 RFindServerMask(TreeRoot,ServerName);
350 bool IsServer(std::string ServerName)
352 return LookForServer(TreeRoot,ServerName);
355 class TreeSocket : public InspSocket
358 std::string in_buffer;
359 ServerState LinkState;
360 std::string InboundServerName;
361 std::string InboundDescription;
363 int num_lost_servers;
365 bool LastPingWasGood;
369 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
370 : InspSocket(host, port, listening, maxtime)
373 this->LinkState = LISTENER;
376 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
377 : InspSocket(host, port, listening, maxtime)
380 this->LinkState = CONNECTING;
383 TreeSocket(int newfd, char* ip)
384 : InspSocket(newfd, ip)
386 this->LinkState = WAIT_AUTH_1;
389 virtual bool OnConnected()
391 if (this->LinkState == CONNECTING)
393 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
394 // we should send our details here.
395 // if the other side is satisfied, they send theirs.
396 // we do not need to change state here.
397 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
399 if (x->Name == this->myhost)
401 // found who we're supposed to be connecting to, send the neccessary gubbins.
402 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
410 virtual void OnError(InspSocketError e)
414 virtual int OnDisconnect()
419 // recursively send the server tree with distances as hops
420 void SendServers(TreeServer* Current, TreeServer* s, int hops)
423 for (unsigned int q = 0; q < Current->ChildCount(); q++)
425 TreeServer* recursive_server = Current->GetChild(q);
426 if (recursive_server != s)
428 // :source.server SERVER server.name hops :Description
429 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
430 this->WriteLine(command);
431 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
432 // down to next level
433 this->SendServers(recursive_server, s, hops+1);
438 void SquitServer(TreeServer* Current)
440 // recursively squit the servers attached to 'Current'
441 for (unsigned int q = 0; q < Current->ChildCount(); q++)
443 TreeServer* recursive_server = Current->GetChild(q);
444 this->SquitServer(recursive_server);
446 // Now we've whacked the kids, whack self
448 bool quittingpeople = true;
449 while (quittingpeople)
451 quittingpeople = false;
452 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
454 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
456 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
458 quittingpeople = true;
465 void Squit(TreeServer* Current,std::string reason)
469 std::deque<std::string> params;
470 params.push_back(Current->GetName());
471 params.push_back(":"+reason);
472 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
473 if (Current->GetParent() == TreeRoot)
475 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
479 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
481 num_lost_servers = 0;
483 SquitServer(Current);
485 Current->GetParent()->DelChild(Current);
487 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
491 log(DEFAULT,"Squit from unknown server");
495 bool ForceMode(std::string source, std::deque<std::string> params)
497 userrec* who = new userrec;
498 who->fd = FD_MAGIC_NUMBER;
499 if (params.size() < 2)
502 for (unsigned int q = 0; q < params.size(); q++)
504 modelist[q] = (char*)params[q].c_str();
506 Srv->SendMode(modelist,params.size(),who);
507 DoOneToAllButSender(source,"FMODE",params,source);
512 bool ForceTopic(std::string source, std::deque<std::string> params)
514 // FTOPIC %s %lu %s :%s
515 if (params.size() != 4)
517 std::string channel = params[0];
518 time_t ts = atoi(params[1].c_str());
519 std::string setby = params[2];
520 std::string topic = params[3];
522 chanrec* c = Srv->FindChannel(channel);
525 if ((ts >= c->topicset) || (!*c->topic))
527 std::string oldtopic = c->topic;
528 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
529 strlcpy(c->setby,setby.c_str(),NICKMAX);
531 // if the topic text is the same as the current topic,
532 // dont bother to send the TOPIC command out, just silently
533 // update the set time and set nick.
534 if (oldtopic != topic)
535 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
540 // all done, send it on its way
541 params[3] = ":" + params[3];
542 DoOneToAllButSender(source,"FTOPIC",params,source);
547 bool ForceJoin(std::string source, std::deque<std::string> params)
549 if (params.size() < 3)
553 char modestring[MAXBUF];
554 char* mode_users[127];
555 mode_users[0] = first;
556 mode_users[1] = modestring;
557 strcpy(mode_users[1],"+");
558 unsigned int modectr = 2;
561 std::string channel = params[0];
562 time_t TS = atoi(params[1].c_str());
565 chanrec* chan = Srv->FindChannel(channel);
570 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
572 // default is a high value, which if we dont have this
573 // channel will let the other side apply their modes.
574 time_t ourTS = time(NULL)+600;
575 chanrec* us = Srv->FindChannel(channel);
581 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
583 // do this first, so our mode reversals are correctly received by other servers
584 // if there is a TS collision.
585 DoOneToAllButSender(source,"FJOIN",params,source);
587 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
589 // process one channel at a time, applying modes.
590 char* usr = (char*)params[usernum].c_str();
591 char permissions = *usr;
596 mode_users[modectr++] = usr;
597 strlcat(modestring,"o",MAXBUF);
601 mode_users[modectr++] = usr;
602 strlcat(modestring,"h",MAXBUF);
606 mode_users[modectr++] = usr;
607 strlcat(modestring,"v",MAXBUF);
610 who = Srv->FindNick(usr);
613 Srv->JoinUserToChannel(who,channel,key);
614 if (modectr >= (MAXMODES-1))
616 // theres a mode for this user. push them onto the mode queue, and flush it
617 // if there are more than MAXMODES to go.
620 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
621 Srv->SendMode(mode_users,modectr,who);
625 log(DEBUG,"Their channel newer than ours, bouncing their modes");
627 std::deque<std::string> params;
628 // modes are now being UNSET...
629 *mode_users[1] = '-';
630 for (unsigned int x = 0; x < modectr; x++)
632 params.push_back(mode_users[x]);
634 // tell everyone to bounce the modes. bad modes, bad!
635 DoOneToMany(Srv->GetServerName(),"FMODE",params);
637 strcpy(mode_users[1],"+");
642 // there werent enough modes built up to flush it during FJOIN,
643 // or, there are a number left over. flush them out.
644 if ((modectr > 2) && (who))
648 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
649 Srv->SendMode(mode_users,modectr,who);
653 log(DEBUG,"Their channel newer than ours, bouncing their modes");
654 std::deque<std::string> params;
655 *mode_users[1] = '-';
656 for (unsigned int x = 0; x < modectr; x++)
658 params.push_back(mode_users[x]);
660 DoOneToMany(Srv->GetServerName(),"FMODE",params);
666 bool IntroduceClient(std::string source, std::deque<std::string> params)
668 if (params.size() < 8)
670 // NICK age nick host dhost ident +modes ip :gecos
672 std::string nick = params[1];
673 std::string host = params[2];
674 std::string dhost = params[3];
675 std::string ident = params[4];
676 time_t age = atoi(params[0].c_str());
677 std::string modes = params[5];
678 while (*(modes.c_str()) == '+')
680 char* m = (char*)modes.c_str();
684 std::string ip = params[6];
685 std::string gecos = params[7];
686 char* tempnick = (char*)nick.c_str();
687 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
689 user_hash::iterator iter;
690 iter = clientlist.find(tempnick);
691 if (iter != clientlist.end())
694 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);
695 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
699 clientlist[tempnick] = new userrec();
700 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
701 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
702 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
703 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
704 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
705 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
706 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
707 clientlist[tempnick]->registered = 7;
708 clientlist[tempnick]->signon = age;
709 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
710 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
711 for (int i = 0; i < MAXCHANS; i++)
713 clientlist[tempnick]->chans[i].channel = NULL;
714 clientlist[tempnick]->chans[i].uc_modes = 0;
716 params[7] = ":" + params[7];
717 DoOneToAllButSender(source,"NICK",params,source);
721 void SendFJoins(TreeServer* Current, chanrec* c)
724 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
725 std::vector<char*> *ulist = c->GetUsers();
726 for (unsigned int i = 0; i < ulist->size(); i++)
728 char* o = (*ulist)[i];
729 userrec* otheruser = (userrec*)o;
730 strlcat(list," ",MAXBUF);
731 strlcat(list,cmode(otheruser,c),MAXBUF);
732 strlcat(list,otheruser->nick,MAXBUF);
733 if (strlen(list)>(480-NICKMAX))
735 this->WriteLine(list);
736 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
739 if (list[strlen(list)-1] != ':')
741 this->WriteLine(list);
745 void SendChannelModes(TreeServer* Current)
748 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
750 SendFJoins(Current, c->second);
751 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
752 this->WriteLine(data);
753 if (*c->second->topic)
755 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);
756 this->WriteLine(data);
758 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
760 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
761 this->WriteLine(data);
763 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
767 // send all users and their channels
768 void SendUsers(TreeServer* Current)
771 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
773 if (u->second->registered == 7)
775 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);
776 this->WriteLine(data);
777 if (strchr(u->second->modes,'o'))
779 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
781 //char* chl = chlist(u->second,u->second);
784 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
786 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
791 void DoBurst(TreeServer* s)
793 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
794 this->WriteLine("BURST");
795 // send our version string
796 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
798 this->SendServers(TreeRoot,s,1);
799 // Send users and their channels
801 // Send everything else (channel modes etc)
802 this->SendChannelModes(s);
803 this->WriteLine("ENDBURST");
806 virtual bool OnDataReady()
808 char* data = this->Read();
811 this->in_buffer += data;
812 while (in_buffer.find("\n") != std::string::npos)
814 char* line = (char*)in_buffer.c_str();
815 std::string ret = "";
816 while ((*line != '\n') && (strlen(line)))
821 if ((*line == '\n') || (*line == '\r'))
824 if (!this->ProcessLine(ret))
830 return (data != NULL);
833 int WriteLine(std::string line)
835 return this->Write(line + "\r\n");
838 bool Error(std::deque<std::string> params)
840 if (params.size() < 1)
842 std::string Errmsg = params[0];
843 std::string SName = myhost;
844 if (InboundServerName != "")
846 SName = InboundServerName;
848 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
849 // we will return false to cause the socket to close.
853 bool OperType(std::string prefix, std::deque<std::string> params)
855 if (params.size() != 1)
857 std::string opertype = params[0];
858 userrec* u = Srv->FindNick(prefix);
861 strlcpy(u->oper,opertype.c_str(),NICKMAX);
862 if (!strchr(u->modes,'o'))
864 strcat(u->modes,"o");
866 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
871 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
873 if (params.size() < 1)
875 std::string servermask = params[0];
876 if (Srv->MatchText(Srv->GetServerName(),servermask))
878 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
880 ReadConfiguration(false);
882 DoOneToAllButSender(prefix,"REHASH",params,prefix);
886 bool RemoteKill(std::string prefix, std::deque<std::string> params)
888 if (params.size() != 2)
890 std::string nick = params[0];
891 std::string reason = params[1];
892 userrec* u = Srv->FindNick(prefix);
893 userrec* who = Srv->FindNick(nick);
896 std::string sourceserv = prefix;
899 sourceserv = u->server;
901 params[1] = ":" + params[1];
902 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
903 Srv->QuitUser(who,reason);
908 bool LocalPong(std::string prefix, std::deque<std::string> params)
910 if (params.size() < 1)
912 TreeServer* ServerSource = FindServer(prefix);
915 ServerSource->SetPingFlag();
920 bool ServerVersion(std::string prefix, std::deque<std::string> params)
922 if (params.size() < 1)
924 TreeServer* ServerSource = FindServer(prefix);
927 ServerSource->SetVersion(params[0]);
929 params[0] = ":" + params[0];
930 DoOneToAllButSender(prefix,"VERSION",params,prefix);
934 bool ChangeHost(std::string prefix, std::deque<std::string> params)
936 if (params.size() < 1)
938 userrec* u = Srv->FindNick(prefix);
941 Srv->ChangeHost(u,params[0]);
942 DoOneToAllButSender(prefix,"FHOST",params,u->server);
947 bool ChangeName(std::string prefix, std::deque<std::string> params)
949 if (params.size() < 1)
951 userrec* u = Srv->FindNick(prefix);
954 Srv->ChangeGECOS(u,params[0]);
955 params[0] = ":" + params[0];
956 DoOneToAllButSender(prefix,"FNAME",params,u->server);
961 bool LocalPing(std::string prefix, std::deque<std::string> params)
963 if (params.size() < 1)
965 std::string stufftobounce = params[0];
966 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
970 bool RemoteServer(std::string prefix, std::deque<std::string> params)
972 if (params.size() < 4)
974 std::string servername = params[0];
975 std::string password = params[1];
976 // hopcount is not used for a remote server, we calculate this ourselves
977 std::string description = params[3];
978 TreeServer* ParentOfThis = FindServer(prefix);
981 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
984 TreeServer* CheckDupe = FindServer(servername);
987 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
990 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
991 ParentOfThis->AddChild(Node);
992 params[3] = ":" + params[3];
993 DoOneToAllButSender(prefix,"SERVER",params,prefix);
994 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
998 bool Outbound_Reply_Server(std::deque<std::string> params)
1000 if (params.size() < 4)
1002 std::string servername = params[0];
1003 std::string password = params[1];
1004 int hops = atoi(params[2].c_str());
1007 this->WriteLine("ERROR :Server too far away for authentication");
1010 std::string description = params[3];
1011 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1013 if ((x->Name == servername) && (x->RecvPass == password))
1015 TreeServer* CheckDupe = FindServer(servername);
1018 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1021 // Begin the sync here. this kickstarts the
1022 // other side, waiting in WAIT_AUTH_2 state,
1023 // into starting their burst, as it shows
1024 // that we're happy.
1025 this->LinkState = CONNECTED;
1026 // we should add the details of this server now
1027 // to the servers tree, as a child of the root
1029 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1030 TreeRoot->AddChild(Node);
1031 params[3] = ":" + params[3];
1032 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1033 this->DoBurst(Node);
1037 this->WriteLine("ERROR :Invalid credentials");
1041 bool Inbound_Server(std::deque<std::string> params)
1043 if (params.size() < 4)
1045 std::string servername = params[0];
1046 std::string password = params[1];
1047 int hops = atoi(params[2].c_str());
1050 this->WriteLine("ERROR :Server too far away for authentication");
1053 std::string description = params[3];
1054 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1056 if ((x->Name == servername) && (x->RecvPass == password))
1058 TreeServer* CheckDupe = FindServer(servername);
1061 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1064 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1065 this->InboundServerName = servername;
1066 this->InboundDescription = description;
1067 // this is good. Send our details: Our server name and description and hopcount of 0,
1068 // along with the sendpass from this block.
1069 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1070 // move to the next state, we are now waiting for THEM.
1071 this->LinkState = WAIT_AUTH_2;
1075 this->WriteLine("ERROR :Invalid credentials");
1079 std::deque<std::string> Split(std::string line, bool stripcolon)
1081 std::deque<std::string> n;
1082 if (!strchr(line.c_str(),' '))
1087 std::stringstream s(line);
1088 std::string param = "";
1107 if ((param == ":") && (item > 0))
1130 bool ProcessLine(std::string line)
1132 char* l = (char*)line.c_str();
1133 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1134 l[strlen(l)-1] = '\0';
1138 Srv->Log(DEBUG,"IN: '"+line+"'");
1139 std::deque<std::string> params = this->Split(line,true);
1140 std::string command = "";
1141 std::string prefix = "";
1142 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1145 command = params[1];
1146 char* pref = (char*)prefix.c_str();
1154 command = params[0];
1158 switch (this->LinkState)
1163 // Waiting for SERVER command from remote server. Server initiating
1164 // the connection sends the first SERVER command, listening server
1165 // replies with theirs if its happy, then if the initiator is happy,
1166 // it starts to send its net sync, which starts the merge, otherwise
1167 // it sends an ERROR.
1168 if (command == "SERVER")
1170 return this->Inbound_Server(params);
1172 else if (command == "ERROR")
1174 return this->Error(params);
1178 // Waiting for start of other side's netmerge to say they liked our
1180 if (command == "SERVER")
1182 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1186 else if (command == "BURST")
1188 this->LinkState = CONNECTED;
1189 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1190 TreeRoot->AddChild(Node);
1192 params.push_back(InboundServerName);
1193 params.push_back("*");
1194 params.push_back("1");
1195 params.push_back(":"+InboundDescription);
1196 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1197 this->DoBurst(Node);
1199 else if (command == "ERROR")
1201 return this->Error(params);
1206 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1210 if (command == "SERVER")
1212 // another server we connected to, which was in WAIT_AUTH_1 state,
1213 // has just sent us their credentials. If we get this far, theyre
1214 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1215 // if we're happy with this, we should send our netburst which
1216 // kickstarts the merge.
1217 return this->Outbound_Reply_Server(params);
1219 else if (command == "ERROR")
1221 return this->Error(params);
1225 // This is the 'authenticated' state, when all passwords
1226 // have been exchanged and anything past this point is taken
1228 std::string target = "";
1229 if ((command == "NICK") && (params.size() > 1))
1231 return this->IntroduceClient(prefix,params);
1233 else if (command == "FJOIN")
1235 return this->ForceJoin(prefix,params);
1237 else if (command == "SERVER")
1239 return this->RemoteServer(prefix,params);
1241 else if (command == "ERROR")
1243 return this->Error(params);
1245 else if (command == "OPERTYPE")
1247 return this->OperType(prefix,params);
1249 else if (command == "FMODE")
1251 return this->ForceMode(prefix,params);
1253 else if (command == "KILL")
1255 return this->RemoteKill(prefix,params);
1257 else if (command == "FTOPIC")
1259 return this->ForceTopic(prefix,params);
1261 else if (command == "REHASH")
1263 return this->RemoteRehash(prefix,params);
1265 else if (command == "PING")
1267 return this->LocalPing(prefix,params);
1269 else if (command == "PONG")
1271 return this->LocalPong(prefix,params);
1273 else if (command == "VERSION")
1275 return this->ServerVersion(prefix,params);
1277 else if (command == "FHOST")
1279 return this->ChangeHost(prefix,params);
1281 else if (command == "FNAME")
1283 return this->ChangeName(prefix,params);
1285 else if (command == "SQUIT")
1287 if (params.size() == 2)
1289 this->Squit(FindServer(params[0]),params[1]);
1295 // not a special inter-server command.
1296 // Emulate the actual user doing the command,
1297 // this saves us having a huge ugly parser.
1298 userrec* who = Srv->FindNick(prefix);
1299 std::string sourceserv = this->myhost;
1300 if (this->InboundServerName != "")
1302 sourceserv = this->InboundServerName;
1307 target = who->server;
1308 char* strparams[127];
1309 for (unsigned int q = 0; q < params.size(); q++)
1311 strparams[q] = (char*)params[q].c_str();
1313 Srv->CallCommandHandler(command, strparams, params.size(), who);
1317 // its not a user. Its either a server, or somethings screwed up.
1318 if (IsServer(prefix))
1320 target = Srv->GetServerName();
1324 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1328 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1337 virtual std::string GetName()
1339 std::string sourceserv = this->myhost;
1340 if (this->InboundServerName != "")
1342 sourceserv = this->InboundServerName;
1347 virtual void OnTimeout()
1349 if (this->LinkState == CONNECTING)
1351 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1355 virtual void OnClose()
1357 // Connection closed.
1358 // If the connection is fully up (state CONNECTED)
1359 // then propogate a netsplit to all peers.
1360 std::string quitserver = this->myhost;
1361 if (this->InboundServerName != "")
1363 quitserver = this->InboundServerName;
1365 TreeServer* s = FindServer(quitserver);
1368 Squit(s,"Remote host closed the connection");
1372 virtual int OnIncomingConnection(int newsock, char* ip)
1374 TreeSocket* s = new TreeSocket(newsock, ip);
1380 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1382 for (unsigned int c = 0; c < list.size(); c++)
1384 if (list[c] == server)
1389 list.push_back(server);
1392 // returns a list of DIRECT servernames for a specific channel
1393 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1395 std::deque<TreeServer*> list;
1396 std::vector<char*> *ulist = c->GetUsers();
1397 for (unsigned int i = 0; i < ulist->size(); i++)
1399 char* o = (*ulist)[i];
1400 userrec* otheruser = (userrec*)o;
1401 if (std::string(otheruser->server) != Srv->GetServerName())
1403 TreeServer* best = BestRouteTo(otheruser->server);
1405 AddThisServer(best,list);
1411 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1413 TreeServer* omitroute = BestRouteTo(omit);
1414 if ((command == "NOTICE") || (command == "PRIVMSG"))
1416 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1418 if (*(params[0].c_str()) != '#')
1420 // special routing for private messages/notices
1421 userrec* d = Srv->FindNick(params[0]);
1424 std::deque<std::string> par;
1426 par.push_back(params[0]);
1427 par.push_back(":"+params[1]);
1428 DoOneToOne(prefix,command,par,d->server);
1434 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1435 chanrec* c = Srv->FindChannel(params[0]);
1438 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1439 log(DEBUG,"Got a list of %d servers",list.size());
1440 for (unsigned int i = 0; i < list.size(); i++)
1442 TreeSocket* Sock = list[i]->GetSocket();
1443 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1445 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1446 Sock->WriteLine(data);
1454 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1456 TreeServer* Route = TreeRoot->GetChild(x);
1457 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1459 TreeSocket* Sock = Route->GetSocket();
1460 Sock->WriteLine(data);
1466 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1468 TreeServer* omitroute = BestRouteTo(omit);
1469 std::string FullLine = ":" + prefix + " " + command;
1470 for (unsigned int x = 0; x < params.size(); x++)
1472 FullLine = FullLine + " " + params[x];
1474 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1476 TreeServer* Route = TreeRoot->GetChild(x);
1477 // Send the line IF:
1478 // The route has a socket (its a direct connection)
1479 // The route isnt the one to be omitted
1480 // The route isnt the path to the one to be omitted
1481 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1483 TreeSocket* Sock = Route->GetSocket();
1484 Sock->WriteLine(FullLine);
1490 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1492 std::string FullLine = ":" + prefix + " " + command;
1493 for (unsigned int x = 0; x < params.size(); x++)
1495 FullLine = FullLine + " " + params[x];
1497 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1499 TreeServer* Route = TreeRoot->GetChild(x);
1500 if (Route->GetSocket())
1502 TreeSocket* Sock = Route->GetSocket();
1503 Sock->WriteLine(FullLine);
1509 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1511 TreeServer* Route = BestRouteTo(target);
1514 std::string FullLine = ":" + prefix + " " + command;
1515 for (unsigned int x = 0; x < params.size(); x++)
1517 FullLine = FullLine + " " + params[x];
1519 if (Route->GetSocket())
1521 TreeSocket* Sock = Route->GetSocket();
1522 Sock->WriteLine(FullLine);
1532 std::vector<TreeSocket*> Bindings;
1534 void ReadConfiguration(bool rebind)
1538 for (int j =0; j < Conf->Enumerate("bind"); j++)
1540 std::string Type = Conf->ReadValue("bind","type",j);
1541 std::string IP = Conf->ReadValue("bind","address",j);
1542 long Port = Conf->ReadInteger("bind","port",j,true);
1543 if (Type == "servers")
1549 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1550 if (listener->GetState() == I_LISTENING)
1552 Srv->AddSocket(listener);
1553 Bindings.push_back(listener);
1557 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1565 for (int j =0; j < Conf->Enumerate("link"); j++)
1568 L.Name = Conf->ReadValue("link","name",j);
1569 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1570 L.Port = Conf->ReadInteger("link","port",j,true);
1571 L.SendPass = Conf->ReadValue("link","sendpass",j);
1572 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1573 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1574 L.NextConnectTime = time(NULL) + L.AutoConnect;
1575 LinkBlocks.push_back(L);
1576 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1581 class ModuleSpanningTree : public Module
1583 std::vector<TreeSocket*> Bindings;
1589 ModuleSpanningTree()
1592 Conf = new ConfigReader;
1595 // Create the root of the tree
1596 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1598 ReadConfiguration(true);
1601 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1603 std::string Parent = TreeRoot->GetName();
1604 if (Current->GetParent())
1606 Parent = Current->GetParent()->GetName();
1608 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1610 ShowLinks(Current->GetChild(q),user,hops+1);
1612 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1615 int CountLocalServs()
1617 return TreeRoot->ChildCount();
1620 void CountServsRecursive(TreeServer* Current)
1623 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1625 CountServsRecursive(Current->GetChild(q));
1632 CountServsRecursive(TreeRoot);
1636 void HandleLinks(char** parameters, int pcnt, userrec* user)
1638 ShowLinks(TreeRoot,user,0);
1639 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1643 void HandleLusers(char** parameters, int pcnt, userrec* user)
1645 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1646 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1647 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1648 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1649 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1653 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1655 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1659 for (int t = 0; t < depth; t++)
1661 matrix[line][t] = ' ';
1663 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1665 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1667 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1672 // Ok, prepare to be confused.
1673 // After much mulling over how to approach this, it struck me that
1674 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1675 // keeping track of a ton of ascii characters, and line by line
1676 // under recursion working out where to place them using multiplications
1677 // and divisons, we instead render the map onto a backplane of characters
1678 // (a character matrix), then draw the branches as a series of "L" shapes
1679 // from the nodes. This is not only friendlier on CPU it uses less stack.
1681 void HandleMap(char** parameters, int pcnt, userrec* user)
1683 // This array represents a virtual screen which we will
1684 // "scratch" draw to, as the console device of an irc
1685 // client does not provide for a proper terminal.
1686 char matrix[128][80];
1687 for (unsigned int t = 0; t < 128; t++)
1689 matrix[t][0] = '\0';
1692 // The only recursive bit is called here.
1693 ShowMap(TreeRoot,user,0,matrix);
1694 // Process each line one by one. The algorithm has a limit of
1695 // 128 servers (which is far more than a spanning tree should have
1696 // anyway, so we're ok). This limit can be raised simply by making
1697 // the character matrix deeper, 128 rows taking 10k of memory.
1698 for (int l = 1; l < line; l++)
1700 // scan across the line looking for the start of the
1701 // servername (the recursive part of the algorithm has placed
1702 // the servers at indented positions depending on what they
1704 int first_nonspace = 0;
1705 while (matrix[l][first_nonspace] == ' ')
1710 // Draw the `- (corner) section: this may be overwritten by
1711 // another L shape passing along the same vertical pane, becoming
1712 // a |- (branch) section instead.
1713 matrix[l][first_nonspace] = '-';
1714 matrix[l][first_nonspace-1] = '`';
1716 // Draw upwards until we hit the parent server, causing possibly
1717 // other corners (`-) to become branches (|-)
1718 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1720 matrix[l2][first_nonspace-1] = '|';
1724 // dump the whole lot to the user. This is the easy bit, honest.
1725 for (int t = 0; t < line; t++)
1727 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1729 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1733 int HandleSquit(char** parameters, int pcnt, userrec* user)
1735 TreeServer* s = FindServerMask(parameters[0]);
1738 TreeSocket* sock = s->GetSocket();
1741 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1742 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1747 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1752 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1757 void DoPingChecks(time_t curtime)
1759 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1761 TreeServer* serv = TreeRoot->GetChild(j);
1762 TreeSocket* sock = serv->GetSocket();
1765 if (curtime >= serv->NextPingTime())
1767 if (serv->AnsweredLastPing())
1769 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1770 serv->SetNextPingTime(curtime + 60);
1774 // they didnt answer, boot them
1775 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1776 sock->Squit(serv,"Ping timeout");
1785 void AutoConnectServers(time_t curtime)
1787 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1789 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1791 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1792 x->NextConnectTime = curtime + x->AutoConnect;
1793 TreeServer* CheckDupe = FindServer(x->Name);
1796 // an autoconnected server is not connected. Check if its time to connect it
1797 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1798 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1799 Srv->AddSocket(newsocket);
1805 int HandleVersion(char** parameters, int pcnt, userrec* user)
1807 // we've already checked if pcnt > 0, so this is safe
1808 TreeServer* found = FindServerMask(parameters[0]);
1811 std::string Version = found->GetVersion();
1812 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1816 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1821 int HandleConnect(char** parameters, int pcnt, userrec* user)
1823 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1825 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1827 TreeServer* CheckDupe = FindServer(x->Name);
1830 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);
1831 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1832 Srv->AddSocket(newsocket);
1837 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());
1842 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1846 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1848 if (command == "CONNECT")
1850 return this->HandleConnect(parameters,pcnt,user);
1852 else if (command == "SQUIT")
1854 return this->HandleSquit(parameters,pcnt,user);
1856 else if (command == "MAP")
1858 this->HandleMap(parameters,pcnt,user);
1861 else if (command == "LUSERS")
1863 this->HandleLusers(parameters,pcnt,user);
1866 else if (command == "LINKS")
1868 this->HandleLinks(parameters,pcnt,user);
1871 else if ((command == "VERSION") && (pcnt > 0))
1873 this->HandleVersion(parameters,pcnt,user);
1876 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1878 // this bit of code cleverly routes all module commands
1879 // to all remote severs *automatically* so that modules
1880 // can just handle commands locally, without having
1881 // to have any special provision in place for remote
1882 // commands and linking protocols.
1883 std::deque<std::string> params;
1885 for (int j = 0; j < pcnt; j++)
1887 if (strchr(parameters[j],' '))
1889 params.push_back(":" + std::string(parameters[j]));
1893 params.push_back(std::string(parameters[j]));
1896 DoOneToMany(user->nick,command,params);
1901 virtual void OnGetServerDescription(std::string servername,std::string &description)
1903 TreeServer* s = FindServer(servername);
1906 description = s->GetDesc();
1910 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1912 if (std::string(source->server) == Srv->GetServerName())
1914 std::deque<std::string> params;
1915 params.push_back(dest->nick);
1916 params.push_back(channel->name);
1917 DoOneToMany(source->nick,"INVITE",params);
1921 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1923 std::deque<std::string> params;
1924 params.push_back(chan->name);
1925 params.push_back(":"+topic);
1926 DoOneToMany(user->nick,"TOPIC",params);
1929 virtual void OnWallops(userrec* user, std::string text)
1931 if (std::string(user->server) == Srv->GetServerName())
1933 std::deque<std::string> params;
1934 params.push_back(":"+text);
1935 DoOneToMany(user->nick,"WALLOPS",params);
1939 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1941 if (target_type == TYPE_USER)
1943 userrec* d = (userrec*)dest;
1944 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1946 std::deque<std::string> params;
1948 params.push_back(d->nick);
1949 params.push_back(":"+text);
1950 DoOneToOne(user->nick,"NOTICE",params,d->server);
1955 if (std::string(user->server) == Srv->GetServerName())
1957 chanrec *c = (chanrec*)dest;
1958 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1959 for (unsigned int i = 0; i < list.size(); i++)
1961 TreeSocket* Sock = list[i]->GetSocket();
1963 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1969 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1971 if (target_type == TYPE_USER)
1973 // route private messages which are targetted at clients only to the server
1974 // which needs to receive them
1975 userrec* d = (userrec*)dest;
1976 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1978 std::deque<std::string> params;
1980 params.push_back(d->nick);
1981 params.push_back(":"+text);
1982 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1987 if (std::string(user->server) == Srv->GetServerName())
1989 chanrec *c = (chanrec*)dest;
1990 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1991 for (unsigned int i = 0; i < list.size(); i++)
1993 TreeSocket* Sock = list[i]->GetSocket();
1995 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2001 virtual void OnBackgroundTimer(time_t curtime)
2003 AutoConnectServers(curtime);
2004 DoPingChecks(curtime);
2007 virtual void OnUserJoin(userrec* user, chanrec* channel)
2009 // Only do this for local users
2010 if (std::string(user->server) == Srv->GetServerName())
2012 std::deque<std::string> params;
2014 params.push_back(channel->name);
2017 // if the channel has a key, force the join by emulating the key.
2018 params.push_back(channel->key);
2020 if (channel->GetUserCounter() > 1)
2022 // not the first in the channel
2023 DoOneToMany(user->nick,"JOIN",params);
2027 // first in the channel, set up their permissions
2028 // and the channel TS with FJOIN.
2030 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2032 params.push_back(channel->name);
2033 params.push_back(ts);
2034 params.push_back("@"+std::string(user->nick));
2035 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2040 virtual void OnChangeHost(userrec* user, std::string newhost)
2042 // only occurs for local clients
2043 std::deque<std::string> params;
2044 params.push_back(newhost);
2045 DoOneToMany(user->nick,"FHOST",params);
2048 virtual void OnChangeName(userrec* user, std::string gecos)
2050 // only occurs for local clients
2051 std::deque<std::string> params;
2052 params.push_back(gecos);
2053 DoOneToMany(user->nick,"FNAME",params);
2056 virtual void OnUserPart(userrec* user, chanrec* channel)
2058 if (std::string(user->server) == Srv->GetServerName())
2060 std::deque<std::string> params;
2062 params.push_back(channel->name);
2063 DoOneToMany(user->nick,"PART",params);
2067 virtual void OnUserConnect(userrec* user)
2069 char agestr[MAXBUF];
2070 if (std::string(user->server) == Srv->GetServerName())
2072 std::deque<std::string> params;
2073 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2075 params.push_back(agestr);
2076 params.push_back(user->nick);
2077 params.push_back(user->host);
2078 params.push_back(user->dhost);
2079 params.push_back(user->ident);
2080 params.push_back("+"+std::string(user->modes));
2081 params.push_back(user->ip);
2082 params.push_back(":"+std::string(user->fullname));
2083 DoOneToMany(Srv->GetServerName(),"NICK",params);
2087 virtual void OnUserQuit(userrec* user, std::string reason)
2089 if (std::string(user->server) == Srv->GetServerName())
2091 std::deque<std::string> params;
2092 params.push_back(":"+reason);
2093 DoOneToMany(user->nick,"QUIT",params);
2097 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2099 if (std::string(user->server) == Srv->GetServerName())
2101 std::deque<std::string> params;
2102 params.push_back(user->nick);
2103 DoOneToMany(oldnick,"NICK",params);
2107 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2109 if (std::string(source->server) == Srv->GetServerName())
2111 std::deque<std::string> params;
2112 params.push_back(chan->name);
2113 params.push_back(user->nick);
2114 params.push_back(":"+reason);
2115 DoOneToMany(source->nick,"KICK",params);
2119 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2121 std::deque<std::string> params;
2122 params.push_back(dest->nick);
2123 params.push_back(":"+reason);
2124 DoOneToMany(source->nick,"KILL",params);
2127 virtual void OnRehash(std::string parameter)
2129 if (parameter != "")
2131 std::deque<std::string> params;
2132 params.push_back(parameter);
2133 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2135 if (Srv->MatchText(Srv->GetServerName(),parameter))
2137 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2138 Srv->RehashServer();
2141 ReadConfiguration(false);
2144 // note: the protocol does not allow direct umode +o except
2145 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2147 virtual void OnOper(userrec* user, std::string opertype)
2149 if (std::string(user->server) == Srv->GetServerName())
2151 std::deque<std::string> params;
2152 params.push_back(opertype);
2153 DoOneToMany(user->nick,"OPERTYPE",params);
2157 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2159 if (std::string(user->server) == Srv->GetServerName())
2161 if (target_type == TYPE_USER)
2163 userrec* u = (userrec*)dest;
2164 std::deque<std::string> params;
2165 params.push_back(u->nick);
2166 params.push_back(text);
2167 DoOneToMany(user->nick,"MODE",params);
2171 chanrec* c = (chanrec*)dest;
2172 std::deque<std::string> params;
2173 params.push_back(c->name);
2174 params.push_back(text);
2175 DoOneToMany(user->nick,"MODE",params);
2180 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2182 TreeSocket* s = (TreeSocket*)opaque;
2185 if (target_type == TYPE_USER)
2187 userrec* u = (userrec*)target;
2188 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2192 chanrec* c = (chanrec*)target;
2193 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2198 virtual ~ModuleSpanningTree()
2203 virtual Version GetVersion()
2205 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2210 class ModuleSpanningTreeFactory : public ModuleFactory
2213 ModuleSpanningTreeFactory()
2217 ~ModuleSpanningTreeFactory()
2221 virtual Module * CreateModule()
2223 TreeProtocolModule = new ModuleSpanningTree;
2224 return TreeProtocolModule;
2230 extern "C" void * init_module( void )
2232 return new ModuleSpanningTreeFactory;