1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
23 #include "inspircd_config.h"
25 #include <ext/hash_map>
33 #include "helperfuncs.h"
35 #include "inspstring.h"
40 #define nspace __gnu_cxx
45 class ModuleSpanningTree;
46 static ModuleSpanningTree* TreeProtocolModule;
48 extern std::vector<Module*> modules;
49 extern std::vector<ircd_module*> factory;
52 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
54 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
55 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
57 extern user_hash clientlist;
58 extern chan_hash chanlist;
63 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
64 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
65 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
66 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
67 void ReadConfiguration(bool rebind);
72 std::vector<TreeServer*> Children;
73 std::string ServerName;
74 std::string ServerDesc;
75 std::string VersionString;
78 TreeSocket* Socket; // for directly connected servers this points at the socket object
90 UserCount = OperCount = 0;
91 VersionString = GetVersionString();
94 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
98 UserCount = OperCount = 0;
99 VersionString = GetVersionString();
102 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
105 UserCount = OperCount = 0;
106 this->SetNextPingTime(time(NULL) + 60);
110 std::string GetName()
112 return this->ServerName;
115 std::string GetDesc()
117 return this->ServerDesc;
120 std::string GetVersion()
122 return this->VersionString;
125 void SetNextPingTime(time_t t)
128 LastPingWasGood = false;
131 time_t NextPingTime()
133 return this->NextPing;
136 bool AnsweredLastPing()
138 return LastPingWasGood;
143 LastPingWasGood = true;
148 return this->UserCount;
153 return this->OperCount;
156 TreeSocket* GetSocket()
161 TreeServer* GetParent()
166 void SetVersion(std::string Version)
168 VersionString = Version;
171 unsigned int ChildCount()
173 return Children.size();
176 TreeServer* GetChild(unsigned int n)
178 if (n < Children.size())
188 void AddChild(TreeServer* Child)
190 Children.push_back(Child);
193 bool DelChild(TreeServer* Child)
195 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
206 // removes child nodes of this node, and of that node, etc etc
209 bool stillchildren = true;
210 while (stillchildren)
212 stillchildren = false;
213 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
215 TreeServer* s = (TreeServer*)*a;
219 stillchildren = true;
233 std::string SendPass;
234 std::string RecvPass;
235 unsigned long AutoConnect;
236 time_t NextConnectTime;
239 /* $ModDesc: Povides a spanning tree server link protocol */
243 TreeServer *TreeRoot;
244 std::vector<Link> LinkBlocks;
246 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
248 if (Current->GetName() == ServerName)
250 for (unsigned int q = 0; q < Current->ChildCount(); q++)
252 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
261 // Returns the locally connected server we must route a
262 // message through to reach server 'ServerName'. This
263 // only applies to one-to-one and not one-to-many routing.
264 TreeServer* BestRouteTo(std::string ServerName)
266 if (ServerName.c_str() == TreeRoot->GetName())
270 // first, find the server by recursively walking the tree
271 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
272 // did we find it? If not, they did something wrong, abort.
279 // The server exists, follow its parent nodes until
280 // the parent of the current is 'TreeRoot', we know
281 // then that this is a directly-connected server.
282 while ((Found) && (Found->GetParent() != TreeRoot))
284 Found = Found->GetParent();
290 bool LookForServer(TreeServer* Current, std::string ServerName)
292 if (ServerName == Current->GetName())
294 for (unsigned int q = 0; q < Current->ChildCount(); q++)
296 if (LookForServer(Current->GetChild(q),ServerName))
304 void RFindServer(TreeServer* Current, std::string ServerName)
306 if ((ServerName == Current->GetName()) && (!Found))
313 for (unsigned int q = 0; q < Current->ChildCount(); q++)
316 RFindServer(Current->GetChild(q),ServerName);
322 void RFindServerMask(TreeServer* Current, std::string ServerName)
324 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
331 for (unsigned int q = 0; q < Current->ChildCount(); q++)
334 RFindServerMask(Current->GetChild(q),ServerName);
339 TreeServer* FindServer(std::string ServerName)
342 RFindServer(TreeRoot,ServerName);
346 TreeServer* FindServerMask(std::string ServerName)
349 RFindServerMask(TreeRoot,ServerName);
353 bool IsServer(std::string ServerName)
355 return LookForServer(TreeRoot,ServerName);
358 class TreeSocket : public InspSocket
361 std::string in_buffer;
362 ServerState LinkState;
363 std::string InboundServerName;
364 std::string InboundDescription;
366 int num_lost_servers;
368 bool LastPingWasGood;
372 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
373 : InspSocket(host, port, listening, maxtime)
376 this->LinkState = LISTENER;
379 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
380 : InspSocket(host, port, listening, maxtime)
383 this->LinkState = CONNECTING;
386 TreeSocket(int newfd, char* ip)
387 : InspSocket(newfd, ip)
389 this->LinkState = WAIT_AUTH_1;
392 virtual bool OnConnected()
394 if (this->LinkState == CONNECTING)
396 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
397 // we should send our details here.
398 // if the other side is satisfied, they send theirs.
399 // we do not need to change state here.
400 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
402 if (x->Name == this->myhost)
404 // found who we're supposed to be connecting to, send the neccessary gubbins.
405 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
413 virtual void OnError(InspSocketError e)
417 virtual int OnDisconnect()
422 // recursively send the server tree with distances as hops
423 void SendServers(TreeServer* Current, TreeServer* s, int hops)
426 for (unsigned int q = 0; q < Current->ChildCount(); q++)
428 TreeServer* recursive_server = Current->GetChild(q);
429 if (recursive_server != s)
431 // :source.server SERVER server.name hops :Description
432 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
433 this->WriteLine(command);
434 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
435 // down to next level
436 this->SendServers(recursive_server, s, hops+1);
441 void SquitServer(TreeServer* Current)
443 // recursively squit the servers attached to 'Current'
444 for (unsigned int q = 0; q < Current->ChildCount(); q++)
446 TreeServer* recursive_server = Current->GetChild(q);
447 this->SquitServer(recursive_server);
449 // Now we've whacked the kids, whack self
451 bool quittingpeople = true;
452 while (quittingpeople)
454 quittingpeople = false;
455 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
457 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
459 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
461 quittingpeople = true;
468 void Squit(TreeServer* Current,std::string reason)
472 std::deque<std::string> params;
473 params.push_back(Current->GetName());
474 params.push_back(":"+reason);
475 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
476 if (Current->GetParent() == TreeRoot)
478 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
482 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
484 num_lost_servers = 0;
486 SquitServer(Current);
488 Current->GetParent()->DelChild(Current);
490 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
494 log(DEFAULT,"Squit from unknown server");
498 bool ForceMode(std::string source, std::deque<std::string> params)
500 userrec* who = new userrec;
501 who->fd = FD_MAGIC_NUMBER;
502 if (params.size() < 2)
505 for (unsigned int q = 0; q < params.size(); q++)
507 modelist[q] = (char*)params[q].c_str();
509 Srv->SendMode(modelist,params.size(),who);
510 DoOneToAllButSender(source,"FMODE",params,source);
515 bool ForceTopic(std::string source, std::deque<std::string> params)
517 // FTOPIC %s %lu %s :%s
518 if (params.size() != 4)
520 std::string channel = params[0];
521 time_t ts = atoi(params[1].c_str());
522 std::string setby = params[2];
523 std::string topic = params[3];
525 chanrec* c = Srv->FindChannel(channel);
528 if ((ts >= c->topicset) || (!*c->topic))
530 std::string oldtopic = c->topic;
531 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
532 strlcpy(c->setby,setby.c_str(),NICKMAX);
534 // if the topic text is the same as the current topic,
535 // dont bother to send the TOPIC command out, just silently
536 // update the set time and set nick.
537 if (oldtopic != topic)
538 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
543 // all done, send it on its way
544 params[3] = ":" + params[3];
545 DoOneToAllButSender(source,"FTOPIC",params,source);
550 bool ForceJoin(std::string source, std::deque<std::string> params)
552 if (params.size() < 3)
556 char modestring[MAXBUF];
557 char* mode_users[127];
558 mode_users[0] = first;
559 mode_users[1] = modestring;
560 strcpy(mode_users[1],"+");
561 unsigned int modectr = 2;
564 std::string channel = params[0];
565 time_t TS = atoi(params[1].c_str());
568 chanrec* chan = Srv->FindChannel(channel);
573 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
575 // default is a high value, which if we dont have this
576 // channel will let the other side apply their modes.
577 time_t ourTS = time(NULL)+600;
578 chanrec* us = Srv->FindChannel(channel);
584 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
586 // do this first, so our mode reversals are correctly received by other servers
587 // if there is a TS collision.
588 DoOneToAllButSender(source,"FJOIN",params,source);
590 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
592 // process one channel at a time, applying modes.
593 char* usr = (char*)params[usernum].c_str();
594 char permissions = *usr;
599 mode_users[modectr++] = usr;
600 strlcat(modestring,"o",MAXBUF);
604 mode_users[modectr++] = usr;
605 strlcat(modestring,"h",MAXBUF);
609 mode_users[modectr++] = usr;
610 strlcat(modestring,"v",MAXBUF);
613 who = Srv->FindNick(usr);
616 Srv->JoinUserToChannel(who,channel,key);
617 if (modectr >= (MAXMODES-1))
619 // theres a mode for this user. push them onto the mode queue, and flush it
620 // if there are more than MAXMODES to go.
623 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
624 Srv->SendMode(mode_users,modectr,who);
628 log(DEBUG,"Their channel newer than ours, bouncing their modes");
630 std::deque<std::string> params;
631 // modes are now being UNSET...
632 *mode_users[1] = '-';
633 for (unsigned int x = 0; x < modectr; x++)
635 params.push_back(mode_users[x]);
637 // tell everyone to bounce the modes. bad modes, bad!
638 DoOneToMany(Srv->GetServerName(),"FMODE",params);
640 strcpy(mode_users[1],"+");
645 // there werent enough modes built up to flush it during FJOIN,
646 // or, there are a number left over. flush them out.
647 if ((modectr > 2) && (who))
651 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
652 Srv->SendMode(mode_users,modectr,who);
656 log(DEBUG,"Their channel newer than ours, bouncing their modes");
657 std::deque<std::string> params;
658 *mode_users[1] = '-';
659 for (unsigned int x = 0; x < modectr; x++)
661 params.push_back(mode_users[x]);
663 DoOneToMany(Srv->GetServerName(),"FMODE",params);
669 bool IntroduceClient(std::string source, std::deque<std::string> params)
671 if (params.size() < 8)
673 // NICK age nick host dhost ident +modes ip :gecos
675 std::string nick = params[1];
676 std::string host = params[2];
677 std::string dhost = params[3];
678 std::string ident = params[4];
679 time_t age = atoi(params[0].c_str());
680 std::string modes = params[5];
681 while (*(modes.c_str()) == '+')
683 char* m = (char*)modes.c_str();
687 std::string ip = params[6];
688 std::string gecos = params[7];
689 char* tempnick = (char*)nick.c_str();
690 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
692 user_hash::iterator iter;
693 iter = clientlist.find(tempnick);
694 if (iter != clientlist.end())
697 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);
698 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
702 clientlist[tempnick] = new userrec();
703 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
704 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
705 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
706 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
707 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
708 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
709 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
710 clientlist[tempnick]->registered = 7;
711 clientlist[tempnick]->signon = age;
712 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
713 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
714 for (int i = 0; i < MAXCHANS; i++)
716 clientlist[tempnick]->chans[i].channel = NULL;
717 clientlist[tempnick]->chans[i].uc_modes = 0;
719 params[7] = ":" + params[7];
720 DoOneToAllButSender(source,"NICK",params,source);
724 void SendFJoins(TreeServer* Current, chanrec* c)
727 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
728 std::vector<char*> *ulist = c->GetUsers();
729 for (unsigned int i = 0; i < ulist->size(); i++)
731 char* o = (*ulist)[i];
732 userrec* otheruser = (userrec*)o;
733 strlcat(list," ",MAXBUF);
734 strlcat(list,cmode(otheruser,c),MAXBUF);
735 strlcat(list,otheruser->nick,MAXBUF);
736 if (strlen(list)>(480-NICKMAX))
738 this->WriteLine(list);
739 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
742 if (list[strlen(list)-1] != ':')
744 this->WriteLine(list);
748 void SendChannelModes(TreeServer* Current)
751 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
753 SendFJoins(Current, c->second);
754 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
755 this->WriteLine(data);
756 if (*c->second->topic)
758 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);
759 this->WriteLine(data);
761 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
763 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
764 this->WriteLine(data);
766 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
770 // send all users and their channels
771 void SendUsers(TreeServer* Current)
774 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
776 if (u->second->registered == 7)
778 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);
779 this->WriteLine(data);
780 if (strchr(u->second->modes,'o'))
782 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
784 //char* chl = chlist(u->second,u->second);
787 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
789 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
794 void DoBurst(TreeServer* s)
796 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
797 this->WriteLine("BURST");
798 // send our version string
799 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
801 this->SendServers(TreeRoot,s,1);
802 // Send users and their channels
804 // Send everything else (channel modes etc)
805 this->SendChannelModes(s);
806 this->WriteLine("ENDBURST");
809 virtual bool OnDataReady()
811 char* data = this->Read();
814 this->in_buffer += data;
815 while (in_buffer.find("\n") != std::string::npos)
817 char* line = (char*)in_buffer.c_str();
818 std::string ret = "";
819 while ((*line != '\n') && (strlen(line)))
824 if ((*line == '\n') || (*line == '\r'))
827 if (!this->ProcessLine(ret))
833 return (data != NULL);
836 int WriteLine(std::string line)
838 return this->Write(line + "\r\n");
841 bool Error(std::deque<std::string> params)
843 if (params.size() < 1)
845 std::string Errmsg = params[0];
846 std::string SName = myhost;
847 if (InboundServerName != "")
849 SName = InboundServerName;
851 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
852 // we will return false to cause the socket to close.
856 bool OperType(std::string prefix, std::deque<std::string> params)
858 if (params.size() != 1)
860 std::string opertype = params[0];
861 userrec* u = Srv->FindNick(prefix);
864 strlcpy(u->oper,opertype.c_str(),NICKMAX);
865 if (!strchr(u->modes,'o'))
867 strcat(u->modes,"o");
869 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
874 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
876 if (params.size() < 1)
878 std::string servermask = params[0];
879 if (Srv->MatchText(Srv->GetServerName(),servermask))
881 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
883 ReadConfiguration(false);
885 DoOneToAllButSender(prefix,"REHASH",params,prefix);
889 bool RemoteKill(std::string prefix, std::deque<std::string> params)
891 if (params.size() != 2)
893 std::string nick = params[0];
894 std::string reason = params[1];
895 userrec* u = Srv->FindNick(prefix);
896 userrec* who = Srv->FindNick(nick);
899 std::string sourceserv = prefix;
902 sourceserv = u->server;
904 params[1] = ":" + params[1];
905 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
906 Srv->QuitUser(who,reason);
911 bool LocalPong(std::string prefix, std::deque<std::string> params)
913 if (params.size() < 1)
915 TreeServer* ServerSource = FindServer(prefix);
918 ServerSource->SetPingFlag();
923 bool ServerVersion(std::string prefix, std::deque<std::string> params)
925 if (params.size() < 1)
927 TreeServer* ServerSource = FindServer(prefix);
930 ServerSource->SetVersion(params[0]);
932 params[0] = ":" + params[0];
933 DoOneToAllButSender(prefix,"VERSION",params,prefix);
937 bool ChangeHost(std::string prefix, std::deque<std::string> params)
939 if (params.size() < 1)
941 userrec* u = Srv->FindNick(prefix);
944 Srv->ChangeHost(u,params[0]);
945 DoOneToAllButSender(prefix,"FHOST",params,u->server);
950 bool ChangeName(std::string prefix, std::deque<std::string> params)
952 if (params.size() < 1)
954 userrec* u = Srv->FindNick(prefix);
957 Srv->ChangeGECOS(u,params[0]);
958 params[0] = ":" + params[0];
959 DoOneToAllButSender(prefix,"FNAME",params,u->server);
964 bool LocalPing(std::string prefix, std::deque<std::string> params)
966 if (params.size() < 1)
968 std::string stufftobounce = params[0];
969 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
973 bool RemoteServer(std::string prefix, std::deque<std::string> params)
975 if (params.size() < 4)
977 std::string servername = params[0];
978 std::string password = params[1];
979 // hopcount is not used for a remote server, we calculate this ourselves
980 std::string description = params[3];
981 TreeServer* ParentOfThis = FindServer(prefix);
984 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
987 TreeServer* CheckDupe = FindServer(servername);
990 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
993 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
994 ParentOfThis->AddChild(Node);
995 params[3] = ":" + params[3];
996 DoOneToAllButSender(prefix,"SERVER",params,prefix);
997 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1001 bool Outbound_Reply_Server(std::deque<std::string> params)
1003 if (params.size() < 4)
1005 std::string servername = params[0];
1006 std::string password = params[1];
1007 int hops = atoi(params[2].c_str());
1010 this->WriteLine("ERROR :Server too far away for authentication");
1013 std::string description = params[3];
1014 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1016 if ((x->Name == servername) && (x->RecvPass == password))
1018 TreeServer* CheckDupe = FindServer(servername);
1021 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1024 // Begin the sync here. this kickstarts the
1025 // other side, waiting in WAIT_AUTH_2 state,
1026 // into starting their burst, as it shows
1027 // that we're happy.
1028 this->LinkState = CONNECTED;
1029 // we should add the details of this server now
1030 // to the servers tree, as a child of the root
1032 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1033 TreeRoot->AddChild(Node);
1034 params[3] = ":" + params[3];
1035 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1036 this->DoBurst(Node);
1040 this->WriteLine("ERROR :Invalid credentials");
1044 bool Inbound_Server(std::deque<std::string> params)
1046 if (params.size() < 4)
1048 std::string servername = params[0];
1049 std::string password = params[1];
1050 int hops = atoi(params[2].c_str());
1053 this->WriteLine("ERROR :Server too far away for authentication");
1056 std::string description = params[3];
1057 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1059 if ((x->Name == servername) && (x->RecvPass == password))
1061 TreeServer* CheckDupe = FindServer(servername);
1064 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1067 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1068 this->InboundServerName = servername;
1069 this->InboundDescription = description;
1070 // this is good. Send our details: Our server name and description and hopcount of 0,
1071 // along with the sendpass from this block.
1072 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1073 // move to the next state, we are now waiting for THEM.
1074 this->LinkState = WAIT_AUTH_2;
1078 this->WriteLine("ERROR :Invalid credentials");
1082 std::deque<std::string> Split(std::string line, bool stripcolon)
1084 std::deque<std::string> n;
1085 if (!strchr(line.c_str(),' '))
1090 std::stringstream s(line);
1091 std::string param = "";
1110 if ((param == ":") && (item > 0))
1133 bool ProcessLine(std::string line)
1135 char* l = (char*)line.c_str();
1136 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1137 l[strlen(l)-1] = '\0';
1141 Srv->Log(DEBUG,"IN: '"+line+"'");
1142 std::deque<std::string> params = this->Split(line,true);
1143 std::string command = "";
1144 std::string prefix = "";
1145 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1148 command = params[1];
1149 char* pref = (char*)prefix.c_str();
1157 command = params[0];
1161 switch (this->LinkState)
1166 // Waiting for SERVER command from remote server. Server initiating
1167 // the connection sends the first SERVER command, listening server
1168 // replies with theirs if its happy, then if the initiator is happy,
1169 // it starts to send its net sync, which starts the merge, otherwise
1170 // it sends an ERROR.
1171 if (command == "SERVER")
1173 return this->Inbound_Server(params);
1175 else if (command == "ERROR")
1177 return this->Error(params);
1181 // Waiting for start of other side's netmerge to say they liked our
1183 if (command == "SERVER")
1185 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1189 else if (command == "BURST")
1191 this->LinkState = CONNECTED;
1192 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1193 TreeRoot->AddChild(Node);
1195 params.push_back(InboundServerName);
1196 params.push_back("*");
1197 params.push_back("1");
1198 params.push_back(":"+InboundDescription);
1199 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1200 this->DoBurst(Node);
1202 else if (command == "ERROR")
1204 return this->Error(params);
1209 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1213 if (command == "SERVER")
1215 // another server we connected to, which was in WAIT_AUTH_1 state,
1216 // has just sent us their credentials. If we get this far, theyre
1217 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1218 // if we're happy with this, we should send our netburst which
1219 // kickstarts the merge.
1220 return this->Outbound_Reply_Server(params);
1222 else if (command == "ERROR")
1224 return this->Error(params);
1228 // This is the 'authenticated' state, when all passwords
1229 // have been exchanged and anything past this point is taken
1231 std::string target = "";
1232 if ((command == "NICK") && (params.size() > 1))
1234 return this->IntroduceClient(prefix,params);
1236 else if (command == "FJOIN")
1238 return this->ForceJoin(prefix,params);
1240 else if (command == "SERVER")
1242 return this->RemoteServer(prefix,params);
1244 else if (command == "ERROR")
1246 return this->Error(params);
1248 else if (command == "OPERTYPE")
1250 return this->OperType(prefix,params);
1252 else if (command == "FMODE")
1254 return this->ForceMode(prefix,params);
1256 else if (command == "KILL")
1258 return this->RemoteKill(prefix,params);
1260 else if (command == "FTOPIC")
1262 return this->ForceTopic(prefix,params);
1264 else if (command == "REHASH")
1266 return this->RemoteRehash(prefix,params);
1268 else if (command == "PING")
1270 return this->LocalPing(prefix,params);
1272 else if (command == "PONG")
1274 return this->LocalPong(prefix,params);
1276 else if (command == "VERSION")
1278 return this->ServerVersion(prefix,params);
1280 else if (command == "FHOST")
1282 return this->ChangeHost(prefix,params);
1284 else if (command == "FNAME")
1286 return this->ChangeName(prefix,params);
1288 else if (command == "SQUIT")
1290 if (params.size() == 2)
1292 this->Squit(FindServer(params[0]),params[1]);
1298 // not a special inter-server command.
1299 // Emulate the actual user doing the command,
1300 // this saves us having a huge ugly parser.
1301 userrec* who = Srv->FindNick(prefix);
1302 std::string sourceserv = this->myhost;
1303 if (this->InboundServerName != "")
1305 sourceserv = this->InboundServerName;
1310 target = who->server;
1311 char* strparams[127];
1312 for (unsigned int q = 0; q < params.size(); q++)
1314 strparams[q] = (char*)params[q].c_str();
1316 Srv->CallCommandHandler(command, strparams, params.size(), who);
1320 // its not a user. Its either a server, or somethings screwed up.
1321 if (IsServer(prefix))
1323 target = Srv->GetServerName();
1327 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1331 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1340 virtual std::string GetName()
1342 std::string sourceserv = this->myhost;
1343 if (this->InboundServerName != "")
1345 sourceserv = this->InboundServerName;
1350 virtual void OnTimeout()
1352 if (this->LinkState == CONNECTING)
1354 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1358 virtual void OnClose()
1360 // Connection closed.
1361 // If the connection is fully up (state CONNECTED)
1362 // then propogate a netsplit to all peers.
1363 std::string quitserver = this->myhost;
1364 if (this->InboundServerName != "")
1366 quitserver = this->InboundServerName;
1368 TreeServer* s = FindServer(quitserver);
1371 Squit(s,"Remote host closed the connection");
1375 virtual int OnIncomingConnection(int newsock, char* ip)
1377 TreeSocket* s = new TreeSocket(newsock, ip);
1383 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1385 for (unsigned int c = 0; c < list.size(); c++)
1387 if (list[c] == server)
1392 list.push_back(server);
1395 // returns a list of DIRECT servernames for a specific channel
1396 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1398 std::deque<TreeServer*> list;
1399 std::vector<char*> *ulist = c->GetUsers();
1400 for (unsigned int i = 0; i < ulist->size(); i++)
1402 char* o = (*ulist)[i];
1403 userrec* otheruser = (userrec*)o;
1404 if (std::string(otheruser->server) != Srv->GetServerName())
1406 TreeServer* best = BestRouteTo(otheruser->server);
1408 AddThisServer(best,list);
1414 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1416 TreeServer* omitroute = BestRouteTo(omit);
1417 if ((command == "NOTICE") || (command == "PRIVMSG"))
1419 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1421 if (*(params[0].c_str()) != '#')
1423 // special routing for private messages/notices
1424 userrec* d = Srv->FindNick(params[0]);
1427 std::deque<std::string> par;
1429 par.push_back(params[0]);
1430 par.push_back(":"+params[1]);
1431 DoOneToOne(prefix,command,par,d->server);
1437 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1438 chanrec* c = Srv->FindChannel(params[0]);
1441 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1442 log(DEBUG,"Got a list of %d servers",list.size());
1443 for (unsigned int i = 0; i < list.size(); i++)
1445 TreeSocket* Sock = list[i]->GetSocket();
1446 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1448 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1449 Sock->WriteLine(data);
1457 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1459 TreeServer* Route = TreeRoot->GetChild(x);
1460 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1462 TreeSocket* Sock = Route->GetSocket();
1463 Sock->WriteLine(data);
1469 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1471 TreeServer* omitroute = BestRouteTo(omit);
1472 std::string FullLine = ":" + prefix + " " + command;
1473 for (unsigned int x = 0; x < params.size(); x++)
1475 FullLine = FullLine + " " + params[x];
1477 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1479 TreeServer* Route = TreeRoot->GetChild(x);
1480 // Send the line IF:
1481 // The route has a socket (its a direct connection)
1482 // The route isnt the one to be omitted
1483 // The route isnt the path to the one to be omitted
1484 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1486 TreeSocket* Sock = Route->GetSocket();
1487 Sock->WriteLine(FullLine);
1493 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1495 std::string FullLine = ":" + prefix + " " + command;
1496 for (unsigned int x = 0; x < params.size(); x++)
1498 FullLine = FullLine + " " + params[x];
1500 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1502 TreeServer* Route = TreeRoot->GetChild(x);
1503 if (Route->GetSocket())
1505 TreeSocket* Sock = Route->GetSocket();
1506 Sock->WriteLine(FullLine);
1512 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1514 TreeServer* Route = BestRouteTo(target);
1517 std::string FullLine = ":" + prefix + " " + command;
1518 for (unsigned int x = 0; x < params.size(); x++)
1520 FullLine = FullLine + " " + params[x];
1522 if (Route->GetSocket())
1524 TreeSocket* Sock = Route->GetSocket();
1525 Sock->WriteLine(FullLine);
1535 std::vector<TreeSocket*> Bindings;
1537 void ReadConfiguration(bool rebind)
1541 for (int j =0; j < Conf->Enumerate("bind"); j++)
1543 std::string Type = Conf->ReadValue("bind","type",j);
1544 std::string IP = Conf->ReadValue("bind","address",j);
1545 long Port = Conf->ReadInteger("bind","port",j,true);
1546 if (Type == "servers")
1552 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1553 if (listener->GetState() == I_LISTENING)
1555 Srv->AddSocket(listener);
1556 Bindings.push_back(listener);
1560 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1568 for (int j =0; j < Conf->Enumerate("link"); j++)
1571 L.Name = Conf->ReadValue("link","name",j);
1572 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1573 L.Port = Conf->ReadInteger("link","port",j,true);
1574 L.SendPass = Conf->ReadValue("link","sendpass",j);
1575 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1576 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1577 L.NextConnectTime = time(NULL) + L.AutoConnect;
1578 LinkBlocks.push_back(L);
1579 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1584 class ModuleSpanningTree : public Module
1586 std::vector<TreeSocket*> Bindings;
1592 ModuleSpanningTree()
1595 Conf = new ConfigReader;
1598 // Create the root of the tree
1599 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1601 ReadConfiguration(true);
1604 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1606 std::string Parent = TreeRoot->GetName();
1607 if (Current->GetParent())
1609 Parent = Current->GetParent()->GetName();
1611 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1613 ShowLinks(Current->GetChild(q),user,hops+1);
1615 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1618 int CountLocalServs()
1620 return TreeRoot->ChildCount();
1623 void CountServsRecursive(TreeServer* Current)
1626 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1628 CountServsRecursive(Current->GetChild(q));
1635 CountServsRecursive(TreeRoot);
1639 void HandleLinks(char** parameters, int pcnt, userrec* user)
1641 ShowLinks(TreeRoot,user,0);
1642 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1646 void HandleLusers(char** parameters, int pcnt, userrec* user)
1648 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1649 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1650 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1651 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1652 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1656 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1658 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1662 for (int t = 0; t < depth; t++)
1664 matrix[line][t] = ' ';
1666 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1668 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1670 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1675 // Ok, prepare to be confused.
1676 // After much mulling over how to approach this, it struck me that
1677 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1678 // keeping track of a ton of ascii characters, and line by line
1679 // under recursion working out where to place them using multiplications
1680 // and divisons, we instead render the map onto a backplane of characters
1681 // (a character matrix), then draw the branches as a series of "L" shapes
1682 // from the nodes. This is not only friendlier on CPU it uses less stack.
1684 void HandleMap(char** parameters, int pcnt, userrec* user)
1686 // This array represents a virtual screen which we will
1687 // "scratch" draw to, as the console device of an irc
1688 // client does not provide for a proper terminal.
1689 char matrix[128][80];
1690 for (unsigned int t = 0; t < 128; t++)
1692 matrix[t][0] = '\0';
1695 // The only recursive bit is called here.
1696 ShowMap(TreeRoot,user,0,matrix);
1697 // Process each line one by one. The algorithm has a limit of
1698 // 128 servers (which is far more than a spanning tree should have
1699 // anyway, so we're ok). This limit can be raised simply by making
1700 // the character matrix deeper, 128 rows taking 10k of memory.
1701 for (int l = 1; l < line; l++)
1703 // scan across the line looking for the start of the
1704 // servername (the recursive part of the algorithm has placed
1705 // the servers at indented positions depending on what they
1707 int first_nonspace = 0;
1708 while (matrix[l][first_nonspace] == ' ')
1713 // Draw the `- (corner) section: this may be overwritten by
1714 // another L shape passing along the same vertical pane, becoming
1715 // a |- (branch) section instead.
1716 matrix[l][first_nonspace] = '-';
1717 matrix[l][first_nonspace-1] = '`';
1719 // Draw upwards until we hit the parent server, causing possibly
1720 // other corners (`-) to become branches (|-)
1721 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1723 matrix[l2][first_nonspace-1] = '|';
1727 // dump the whole lot to the user. This is the easy bit, honest.
1728 for (int t = 0; t < line; t++)
1730 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1732 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1736 int HandleSquit(char** parameters, int pcnt, userrec* user)
1738 TreeServer* s = FindServerMask(parameters[0]);
1741 TreeSocket* sock = s->GetSocket();
1744 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1745 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1750 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1755 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1760 void DoPingChecks(time_t curtime)
1762 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1764 TreeServer* serv = TreeRoot->GetChild(j);
1765 TreeSocket* sock = serv->GetSocket();
1768 if (curtime >= serv->NextPingTime())
1770 if (serv->AnsweredLastPing())
1772 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1773 serv->SetNextPingTime(curtime + 60);
1777 // they didnt answer, boot them
1778 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1779 sock->Squit(serv,"Ping timeout");
1788 void AutoConnectServers(time_t curtime)
1790 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1792 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1794 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1795 x->NextConnectTime = curtime + x->AutoConnect;
1796 TreeServer* CheckDupe = FindServer(x->Name);
1799 // an autoconnected server is not connected. Check if its time to connect it
1800 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1801 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1802 Srv->AddSocket(newsocket);
1808 int HandleVersion(char** parameters, int pcnt, userrec* user)
1810 // we've already checked if pcnt > 0, so this is safe
1811 TreeServer* found = FindServerMask(parameters[0]);
1814 std::string Version = found->GetVersion();
1815 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1819 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1824 int HandleConnect(char** parameters, int pcnt, userrec* user)
1826 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1828 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1830 TreeServer* CheckDupe = FindServer(x->Name);
1833 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);
1834 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1835 Srv->AddSocket(newsocket);
1840 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());
1845 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1849 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1851 if (command == "CONNECT")
1853 return this->HandleConnect(parameters,pcnt,user);
1855 else if (command == "SQUIT")
1857 return this->HandleSquit(parameters,pcnt,user);
1859 else if (command == "MAP")
1861 this->HandleMap(parameters,pcnt,user);
1864 else if (command == "LUSERS")
1866 this->HandleLusers(parameters,pcnt,user);
1869 else if (command == "LINKS")
1871 this->HandleLinks(parameters,pcnt,user);
1874 else if ((command == "VERSION") && (pcnt > 0))
1876 this->HandleVersion(parameters,pcnt,user);
1879 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1881 // this bit of code cleverly routes all module commands
1882 // to all remote severs *automatically* so that modules
1883 // can just handle commands locally, without having
1884 // to have any special provision in place for remote
1885 // commands and linking protocols.
1886 std::deque<std::string> params;
1888 for (int j = 0; j < pcnt; j++)
1890 if (strchr(parameters[j],' '))
1892 params.push_back(":" + std::string(parameters[j]));
1896 params.push_back(std::string(parameters[j]));
1899 DoOneToMany(user->nick,command,params);
1904 virtual void OnGetServerDescription(std::string servername,std::string &description)
1906 TreeServer* s = FindServer(servername);
1909 description = s->GetDesc();
1913 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1915 if (std::string(source->server) == Srv->GetServerName())
1917 std::deque<std::string> params;
1918 params.push_back(dest->nick);
1919 params.push_back(channel->name);
1920 DoOneToMany(source->nick,"INVITE",params);
1924 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1926 std::deque<std::string> params;
1927 params.push_back(chan->name);
1928 params.push_back(":"+topic);
1929 DoOneToMany(user->nick,"TOPIC",params);
1932 virtual void OnWallops(userrec* user, std::string text)
1934 if (std::string(user->server) == Srv->GetServerName())
1936 std::deque<std::string> params;
1937 params.push_back(":"+text);
1938 DoOneToMany(user->nick,"WALLOPS",params);
1942 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1944 if (target_type == TYPE_USER)
1946 userrec* d = (userrec*)dest;
1947 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1949 std::deque<std::string> params;
1951 params.push_back(d->nick);
1952 params.push_back(":"+text);
1953 DoOneToOne(user->nick,"NOTICE",params,d->server);
1958 if (std::string(user->server) == Srv->GetServerName())
1960 chanrec *c = (chanrec*)dest;
1961 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1962 for (unsigned int i = 0; i < list.size(); i++)
1964 TreeSocket* Sock = list[i]->GetSocket();
1966 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1972 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1974 if (target_type == TYPE_USER)
1976 // route private messages which are targetted at clients only to the server
1977 // which needs to receive them
1978 userrec* d = (userrec*)dest;
1979 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1981 std::deque<std::string> params;
1983 params.push_back(d->nick);
1984 params.push_back(":"+text);
1985 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1990 if (std::string(user->server) == Srv->GetServerName())
1992 chanrec *c = (chanrec*)dest;
1993 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1994 for (unsigned int i = 0; i < list.size(); i++)
1996 TreeSocket* Sock = list[i]->GetSocket();
1998 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2004 virtual void OnBackgroundTimer(time_t curtime)
2006 AutoConnectServers(curtime);
2007 DoPingChecks(curtime);
2010 virtual void OnUserJoin(userrec* user, chanrec* channel)
2012 // Only do this for local users
2013 if (std::string(user->server) == Srv->GetServerName())
2015 std::deque<std::string> params;
2017 params.push_back(channel->name);
2020 // if the channel has a key, force the join by emulating the key.
2021 params.push_back(channel->key);
2023 if (channel->GetUserCounter() > 1)
2025 // not the first in the channel
2026 DoOneToMany(user->nick,"JOIN",params);
2030 // first in the channel, set up their permissions
2031 // and the channel TS with FJOIN.
2033 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2035 params.push_back(channel->name);
2036 params.push_back(ts);
2037 params.push_back("@"+std::string(user->nick));
2038 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2043 virtual void OnChangeHost(userrec* user, std::string newhost)
2045 // only occurs for local clients
2046 std::deque<std::string> params;
2047 params.push_back(newhost);
2048 DoOneToMany(user->nick,"FHOST",params);
2051 virtual void OnChangeName(userrec* user, std::string gecos)
2053 // only occurs for local clients
2054 std::deque<std::string> params;
2055 params.push_back(gecos);
2056 DoOneToMany(user->nick,"FNAME",params);
2059 virtual void OnUserPart(userrec* user, chanrec* channel)
2061 if (std::string(user->server) == Srv->GetServerName())
2063 std::deque<std::string> params;
2065 params.push_back(channel->name);
2066 DoOneToMany(user->nick,"PART",params);
2070 virtual void OnUserConnect(userrec* user)
2072 char agestr[MAXBUF];
2073 if (std::string(user->server) == Srv->GetServerName())
2075 std::deque<std::string> params;
2076 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2078 params.push_back(agestr);
2079 params.push_back(user->nick);
2080 params.push_back(user->host);
2081 params.push_back(user->dhost);
2082 params.push_back(user->ident);
2083 params.push_back("+"+std::string(user->modes));
2084 params.push_back(user->ip);
2085 params.push_back(":"+std::string(user->fullname));
2086 DoOneToMany(Srv->GetServerName(),"NICK",params);
2090 virtual void OnUserQuit(userrec* user, std::string reason)
2092 if (std::string(user->server) == Srv->GetServerName())
2094 std::deque<std::string> params;
2095 params.push_back(":"+reason);
2096 DoOneToMany(user->nick,"QUIT",params);
2100 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2102 if (std::string(user->server) == Srv->GetServerName())
2104 std::deque<std::string> params;
2105 params.push_back(user->nick);
2106 DoOneToMany(oldnick,"NICK",params);
2110 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2112 if (std::string(source->server) == Srv->GetServerName())
2114 std::deque<std::string> params;
2115 params.push_back(chan->name);
2116 params.push_back(user->nick);
2117 params.push_back(":"+reason);
2118 DoOneToMany(source->nick,"KICK",params);
2122 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2124 std::deque<std::string> params;
2125 params.push_back(dest->nick);
2126 params.push_back(":"+reason);
2127 DoOneToMany(source->nick,"KILL",params);
2130 virtual void OnRehash(std::string parameter)
2132 if (parameter != "")
2134 std::deque<std::string> params;
2135 params.push_back(parameter);
2136 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2138 if (Srv->MatchText(Srv->GetServerName(),parameter))
2140 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2141 Srv->RehashServer();
2144 ReadConfiguration(false);
2147 // note: the protocol does not allow direct umode +o except
2148 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2150 virtual void OnOper(userrec* user, std::string opertype)
2152 if (std::string(user->server) == Srv->GetServerName())
2154 std::deque<std::string> params;
2155 params.push_back(opertype);
2156 DoOneToMany(user->nick,"OPERTYPE",params);
2160 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2162 if (std::string(user->server) == Srv->GetServerName())
2164 if (target_type == TYPE_USER)
2166 userrec* u = (userrec*)dest;
2167 std::deque<std::string> params;
2168 params.push_back(u->nick);
2169 params.push_back(text);
2170 DoOneToMany(user->nick,"MODE",params);
2174 chanrec* c = (chanrec*)dest;
2175 std::deque<std::string> params;
2176 params.push_back(c->name);
2177 params.push_back(text);
2178 DoOneToMany(user->nick,"MODE",params);
2183 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2185 TreeSocket* s = (TreeSocket*)opaque;
2188 if (target_type == TYPE_USER)
2190 userrec* u = (userrec*)target;
2191 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2195 chanrec* c = (chanrec*)target;
2196 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2201 virtual ~ModuleSpanningTree()
2206 virtual Version GetVersion()
2208 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2213 class ModuleSpanningTreeFactory : public ModuleFactory
2216 ModuleSpanningTreeFactory()
2220 ~ModuleSpanningTreeFactory()
2224 virtual Module * CreateModule()
2226 TreeProtocolModule = new ModuleSpanningTree;
2227 return TreeProtocolModule;
2233 extern "C" void * init_module( void )
2235 return new ModuleSpanningTreeFactory;