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 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
531 strlcpy(c->setby,setby.c_str(),NICKMAX);
533 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
538 // all done, send it on its way
539 params[3] = ":" + params[3];
540 DoOneToAllButSender(source,"FTOPIC",params,source);
545 bool ForceJoin(std::string source, std::deque<std::string> params)
547 if (params.size() < 3)
551 char modestring[MAXBUF];
552 char* mode_users[127];
553 mode_users[0] = first;
554 mode_users[1] = modestring;
555 strcpy(mode_users[1],"+");
556 unsigned int modectr = 2;
559 std::string channel = params[0];
560 time_t TS = atoi(params[1].c_str());
563 chanrec* chan = Srv->FindChannel(channel);
568 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
570 // default is a high value, which if we dont have this
571 // channel will let the other side apply their modes.
572 time_t ourTS = time(NULL)+600;
573 chanrec* us = Srv->FindChannel(channel);
579 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
581 // do this first, so our mode reversals are correctly received by other servers
582 // if there is a TS collision.
583 DoOneToAllButSender(source,"FJOIN",params,source);
585 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
587 // process one channel at a time, applying modes.
588 char* usr = (char*)params[usernum].c_str();
589 char permissions = *usr;
594 mode_users[modectr++] = usr;
595 strlcat(modestring,"o",MAXBUF);
599 mode_users[modectr++] = usr;
600 strlcat(modestring,"h",MAXBUF);
604 mode_users[modectr++] = usr;
605 strlcat(modestring,"v",MAXBUF);
608 who = Srv->FindNick(usr);
611 Srv->JoinUserToChannel(who,channel,key);
612 if (modectr >= (MAXMODES-1))
614 // theres a mode for this user. push them onto the mode queue, and flush it
615 // if there are more than MAXMODES to go.
618 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
619 Srv->SendMode(mode_users,modectr,who);
623 log(DEBUG,"Their channel newer than ours, bouncing their modes");
625 std::deque<std::string> params;
626 // modes are now being UNSET...
627 *mode_users[1] = '-';
628 for (unsigned int x = 0; x < modectr; x++)
630 params.push_back(mode_users[x]);
632 // tell everyone to bounce the modes. bad modes, bad!
633 DoOneToMany(Srv->GetServerName(),"FMODE",params);
635 strcpy(mode_users[1],"+");
640 // there werent enough modes built up to flush it during FJOIN,
641 // or, there are a number left over. flush them out.
642 if ((modectr > 2) && (who))
646 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
647 Srv->SendMode(mode_users,modectr,who);
651 log(DEBUG,"Their channel newer than ours, bouncing their modes");
652 std::deque<std::string> params;
653 *mode_users[1] = '-';
654 for (unsigned int x = 0; x < modectr; x++)
656 params.push_back(mode_users[x]);
658 DoOneToMany(Srv->GetServerName(),"FMODE",params);
664 bool IntroduceClient(std::string source, std::deque<std::string> params)
666 if (params.size() < 8)
668 // NICK age nick host dhost ident +modes ip :gecos
670 std::string nick = params[1];
671 std::string host = params[2];
672 std::string dhost = params[3];
673 std::string ident = params[4];
674 time_t age = atoi(params[0].c_str());
675 std::string modes = params[5];
676 while (*(modes.c_str()) == '+')
678 char* m = (char*)modes.c_str();
682 std::string ip = params[6];
683 std::string gecos = params[7];
684 char* tempnick = (char*)nick.c_str();
685 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
687 user_hash::iterator iter;
688 iter = clientlist.find(tempnick);
689 if (iter != clientlist.end())
692 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);
693 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
697 clientlist[tempnick] = new userrec();
698 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
699 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
700 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
701 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
702 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
703 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
704 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
705 clientlist[tempnick]->registered = 7;
706 clientlist[tempnick]->signon = age;
707 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
708 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
709 for (int i = 0; i < MAXCHANS; i++)
711 clientlist[tempnick]->chans[i].channel = NULL;
712 clientlist[tempnick]->chans[i].uc_modes = 0;
714 params[7] = ":" + params[7];
715 DoOneToAllButSender(source,"NICK",params,source);
719 void SendFJoins(TreeServer* Current, chanrec* c)
722 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
723 std::vector<char*> *ulist = c->GetUsers();
724 for (unsigned int i = 0; i < ulist->size(); i++)
726 char* o = (*ulist)[i];
727 userrec* otheruser = (userrec*)o;
728 strlcat(list," ",MAXBUF);
729 strlcat(list,cmode(otheruser,c),MAXBUF);
730 strlcat(list,otheruser->nick,MAXBUF);
731 if (strlen(list)>(480-NICKMAX))
733 this->WriteLine(list);
734 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
737 if (list[strlen(list)-1] != ':')
739 this->WriteLine(list);
743 void SendChannelModes(TreeServer* Current)
746 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
748 SendFJoins(Current, c->second);
749 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
750 this->WriteLine(data);
751 if (*c->second->topic)
753 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);
754 this->WriteLine(data);
756 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
758 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
759 this->WriteLine(data);
761 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
765 // send all users and their channels
766 void SendUsers(TreeServer* Current)
769 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
771 if (u->second->registered == 7)
773 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);
774 this->WriteLine(data);
775 if (strchr(u->second->modes,'o'))
777 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
779 //char* chl = chlist(u->second,u->second);
782 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
784 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
789 void DoBurst(TreeServer* s)
791 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
792 this->WriteLine("BURST");
793 // send our version string
794 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
796 this->SendServers(TreeRoot,s,1);
797 // Send users and their channels
799 // Send everything else (channel modes etc)
800 this->SendChannelModes(s);
801 this->WriteLine("ENDBURST");
804 virtual bool OnDataReady()
806 char* data = this->Read();
809 this->in_buffer += data;
810 while (in_buffer.find("\n") != std::string::npos)
812 char* line = (char*)in_buffer.c_str();
813 std::string ret = "";
814 while ((*line != '\n') && (strlen(line)))
819 if ((*line == '\n') || (*line == '\r'))
822 if (!this->ProcessLine(ret))
828 return (data != NULL);
831 int WriteLine(std::string line)
833 return this->Write(line + "\r\n");
836 bool Error(std::deque<std::string> params)
838 if (params.size() < 1)
840 std::string Errmsg = params[0];
841 std::string SName = myhost;
842 if (InboundServerName != "")
844 SName = InboundServerName;
846 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
847 // we will return false to cause the socket to close.
851 bool OperType(std::string prefix, std::deque<std::string> params)
853 if (params.size() != 1)
855 std::string opertype = params[0];
856 userrec* u = Srv->FindNick(prefix);
859 strlcpy(u->oper,opertype.c_str(),NICKMAX);
860 if (!strchr(u->modes,'o'))
862 strcat(u->modes,"o");
864 DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
869 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
871 if (params.size() < 1)
873 std::string servermask = params[0];
874 if (Srv->MatchText(Srv->GetServerName(),servermask))
876 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
878 ReadConfiguration(false);
880 DoOneToAllButSender(prefix,"REHASH",params,prefix);
884 bool RemoteKill(std::string prefix, std::deque<std::string> params)
886 if (params.size() != 2)
888 std::string nick = params[0];
889 std::string reason = params[1];
890 userrec* u = Srv->FindNick(prefix);
891 userrec* who = Srv->FindNick(nick);
894 std::string sourceserv = prefix;
897 sourceserv = u->server;
899 params[1] = ":" + params[1];
900 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
901 Srv->QuitUser(who,reason);
906 bool LocalPong(std::string prefix, std::deque<std::string> params)
908 if (params.size() < 1)
910 TreeServer* ServerSource = FindServer(prefix);
913 ServerSource->SetPingFlag();
918 bool ServerVersion(std::string prefix, std::deque<std::string> params)
920 if (params.size() < 1)
922 TreeServer* ServerSource = FindServer(prefix);
925 ServerSource->SetVersion(params[0]);
927 params[0] = ":" + params[0];
928 DoOneToAllButSender(prefix,"VERSION",params,prefix);
932 bool ChangeHost(std::string prefix, std::deque<std::string> params)
934 if (params.size() < 1)
936 userrec* u = Srv->FindNick(prefix);
939 Srv->ChangeHost(u,params[0]);
941 DoOneToAllButSender(prefix,"FHOST",params,prefix);
945 bool ChangeName(std::string prefix, std::deque<std::string> params)
947 if (params.size() < 1)
949 userrec* u = Srv->FindNick(prefix);
952 Srv->ChangeGECOS(u,params[0]);
954 params[0] = ":" + params[0];
955 DoOneToAllButSender(prefix,"FNAME",params,prefix);
959 bool LocalPing(std::string prefix, std::deque<std::string> params)
961 if (params.size() < 1)
963 std::string stufftobounce = params[0];
964 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
968 bool RemoteServer(std::string prefix, std::deque<std::string> params)
970 if (params.size() < 4)
972 std::string servername = params[0];
973 std::string password = params[1];
974 // hopcount is not used for a remote server, we calculate this ourselves
975 std::string description = params[3];
976 TreeServer* ParentOfThis = FindServer(prefix);
979 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
982 TreeServer* CheckDupe = FindServer(servername);
985 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
988 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
989 ParentOfThis->AddChild(Node);
990 params[3] = ":" + params[3];
991 DoOneToAllButSender(prefix,"SERVER",params,prefix);
992 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
996 bool Outbound_Reply_Server(std::deque<std::string> params)
998 if (params.size() < 4)
1000 std::string servername = params[0];
1001 std::string password = params[1];
1002 int hops = atoi(params[2].c_str());
1005 this->WriteLine("ERROR :Server too far away for authentication");
1008 std::string description = params[3];
1009 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1011 if ((x->Name == servername) && (x->RecvPass == password))
1013 TreeServer* CheckDupe = FindServer(servername);
1016 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1019 // Begin the sync here. this kickstarts the
1020 // other side, waiting in WAIT_AUTH_2 state,
1021 // into starting their burst, as it shows
1022 // that we're happy.
1023 this->LinkState = CONNECTED;
1024 // we should add the details of this server now
1025 // to the servers tree, as a child of the root
1027 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1028 TreeRoot->AddChild(Node);
1029 params[3] = ":" + params[3];
1030 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1031 this->DoBurst(Node);
1035 this->WriteLine("ERROR :Invalid credentials");
1039 bool Inbound_Server(std::deque<std::string> params)
1041 if (params.size() < 4)
1043 std::string servername = params[0];
1044 std::string password = params[1];
1045 int hops = atoi(params[2].c_str());
1048 this->WriteLine("ERROR :Server too far away for authentication");
1051 std::string description = params[3];
1052 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1054 if ((x->Name == servername) && (x->RecvPass == password))
1056 TreeServer* CheckDupe = FindServer(servername);
1059 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1062 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1063 this->InboundServerName = servername;
1064 this->InboundDescription = description;
1065 // this is good. Send our details: Our server name and description and hopcount of 0,
1066 // along with the sendpass from this block.
1067 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1068 // move to the next state, we are now waiting for THEM.
1069 this->LinkState = WAIT_AUTH_2;
1073 this->WriteLine("ERROR :Invalid credentials");
1077 std::deque<std::string> Split(std::string line, bool stripcolon)
1079 std::deque<std::string> n;
1080 if (!strchr(line.c_str(),' '))
1085 std::stringstream s(line);
1086 std::string param = "";
1105 if ((param == ":") && (item > 0))
1128 bool ProcessLine(std::string line)
1130 char* l = (char*)line.c_str();
1131 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1132 l[strlen(l)-1] = '\0';
1136 Srv->Log(DEBUG,"IN: '"+line+"'");
1137 std::deque<std::string> params = this->Split(line,true);
1138 std::string command = "";
1139 std::string prefix = "";
1140 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1143 command = params[1];
1144 char* pref = (char*)prefix.c_str();
1152 command = params[0];
1156 switch (this->LinkState)
1161 // Waiting for SERVER command from remote server. Server initiating
1162 // the connection sends the first SERVER command, listening server
1163 // replies with theirs if its happy, then if the initiator is happy,
1164 // it starts to send its net sync, which starts the merge, otherwise
1165 // it sends an ERROR.
1166 if (command == "SERVER")
1168 return this->Inbound_Server(params);
1170 else if (command == "ERROR")
1172 return this->Error(params);
1176 // Waiting for start of other side's netmerge to say they liked our
1178 if (command == "SERVER")
1180 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1184 else if (command == "BURST")
1186 this->LinkState = CONNECTED;
1187 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1188 TreeRoot->AddChild(Node);
1190 params.push_back(InboundServerName);
1191 params.push_back("*");
1192 params.push_back("1");
1193 params.push_back(":"+InboundDescription);
1194 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1195 this->DoBurst(Node);
1197 else if (command == "ERROR")
1199 return this->Error(params);
1204 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1208 if (command == "SERVER")
1210 // another server we connected to, which was in WAIT_AUTH_1 state,
1211 // has just sent us their credentials. If we get this far, theyre
1212 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1213 // if we're happy with this, we should send our netburst which
1214 // kickstarts the merge.
1215 return this->Outbound_Reply_Server(params);
1217 else if (command == "ERROR")
1219 return this->Error(params);
1223 // This is the 'authenticated' state, when all passwords
1224 // have been exchanged and anything past this point is taken
1226 std::string target = "";
1227 if ((command == "NICK") && (params.size() > 1))
1229 return this->IntroduceClient(prefix,params);
1231 else if (command == "FJOIN")
1233 return this->ForceJoin(prefix,params);
1235 else if (command == "SERVER")
1237 return this->RemoteServer(prefix,params);
1239 else if (command == "ERROR")
1241 return this->Error(params);
1243 else if (command == "OPERTYPE")
1245 return this->OperType(prefix,params);
1247 else if (command == "FMODE")
1249 return this->ForceMode(prefix,params);
1251 else if (command == "KILL")
1253 return this->RemoteKill(prefix,params);
1255 else if (command == "FTOPIC")
1257 return this->ForceTopic(prefix,params);
1259 else if (command == "REHASH")
1261 return this->RemoteRehash(prefix,params);
1263 else if (command == "PING")
1265 return this->LocalPing(prefix,params);
1267 else if (command == "PONG")
1269 return this->LocalPong(prefix,params);
1271 else if (command == "VERSION")
1273 return this->ServerVersion(prefix,params);
1275 else if (command == "FHOST")
1277 return this->ChangeHost(prefix,params);
1279 else if (command == "FNAME")
1281 return this->ChangeName(prefix,params);
1283 else if (command == "SQUIT")
1285 if (params.size() == 2)
1287 this->Squit(FindServer(params[0]),params[1]);
1293 // not a special inter-server command.
1294 // Emulate the actual user doing the command,
1295 // this saves us having a huge ugly parser.
1296 userrec* who = Srv->FindNick(prefix);
1297 std::string sourceserv = this->myhost;
1298 if (this->InboundServerName != "")
1300 sourceserv = this->InboundServerName;
1305 target = who->server;
1306 char* strparams[127];
1307 for (unsigned int q = 0; q < params.size(); q++)
1309 strparams[q] = (char*)params[q].c_str();
1311 Srv->CallCommandHandler(command, strparams, params.size(), who);
1315 // its not a user. Its either a server, or somethings screwed up.
1316 if (IsServer(prefix))
1318 target = Srv->GetServerName();
1322 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1326 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1335 virtual std::string GetName()
1337 std::string sourceserv = this->myhost;
1338 if (this->InboundServerName != "")
1340 sourceserv = this->InboundServerName;
1345 virtual void OnTimeout()
1347 if (this->LinkState == CONNECTING)
1349 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1353 virtual void OnClose()
1355 // Connection closed.
1356 // If the connection is fully up (state CONNECTED)
1357 // then propogate a netsplit to all peers.
1358 std::string quitserver = this->myhost;
1359 if (this->InboundServerName != "")
1361 quitserver = this->InboundServerName;
1363 TreeServer* s = FindServer(quitserver);
1366 Squit(s,"Remote host closed the connection");
1370 virtual int OnIncomingConnection(int newsock, char* ip)
1372 TreeSocket* s = new TreeSocket(newsock, ip);
1378 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1380 for (unsigned int c = 0; c < list.size(); c++)
1382 if (list[c] == server)
1387 list.push_back(server);
1390 // returns a list of DIRECT servernames for a specific channel
1391 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1393 std::deque<TreeServer*> list;
1394 std::vector<char*> *ulist = c->GetUsers();
1395 for (unsigned int i = 0; i < ulist->size(); i++)
1397 char* o = (*ulist)[i];
1398 userrec* otheruser = (userrec*)o;
1399 if (std::string(otheruser->server) != Srv->GetServerName())
1401 TreeServer* best = BestRouteTo(otheruser->server);
1403 AddThisServer(best,list);
1409 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1411 TreeServer* omitroute = BestRouteTo(omit);
1412 if ((command == "NOTICE") || (command == "PRIVMSG"))
1414 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1416 if (*(params[0].c_str()) != '#')
1418 // special routing for private messages/notices
1419 userrec* d = Srv->FindNick(params[0]);
1422 std::deque<std::string> par;
1424 par.push_back(params[0]);
1425 par.push_back(":"+params[1]);
1426 DoOneToOne(prefix,command,par,d->server);
1432 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1433 chanrec* c = Srv->FindChannel(params[0]);
1436 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1437 log(DEBUG,"Got a list of %d servers",list.size());
1438 for (unsigned int i = 0; i < list.size(); i++)
1440 TreeSocket* Sock = list[i]->GetSocket();
1441 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1443 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1444 Sock->WriteLine(data);
1452 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1454 TreeServer* Route = TreeRoot->GetChild(x);
1455 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1457 TreeSocket* Sock = Route->GetSocket();
1458 Sock->WriteLine(data);
1464 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1466 TreeServer* omitroute = BestRouteTo(omit);
1467 std::string FullLine = ":" + prefix + " " + command;
1468 for (unsigned int x = 0; x < params.size(); x++)
1470 FullLine = FullLine + " " + params[x];
1472 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1474 TreeServer* Route = TreeRoot->GetChild(x);
1475 // Send the line IF:
1476 // The route has a socket (its a direct connection)
1477 // The route isnt the one to be omitted
1478 // The route isnt the path to the one to be omitted
1479 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1481 TreeSocket* Sock = Route->GetSocket();
1482 Sock->WriteLine(FullLine);
1488 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1490 std::string FullLine = ":" + prefix + " " + command;
1491 for (unsigned int x = 0; x < params.size(); x++)
1493 FullLine = FullLine + " " + params[x];
1495 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1497 TreeServer* Route = TreeRoot->GetChild(x);
1498 if (Route->GetSocket())
1500 TreeSocket* Sock = Route->GetSocket();
1501 Sock->WriteLine(FullLine);
1507 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1509 TreeServer* Route = BestRouteTo(target);
1512 std::string FullLine = ":" + prefix + " " + command;
1513 for (unsigned int x = 0; x < params.size(); x++)
1515 FullLine = FullLine + " " + params[x];
1517 if (Route->GetSocket())
1519 TreeSocket* Sock = Route->GetSocket();
1520 Sock->WriteLine(FullLine);
1530 std::vector<TreeSocket*> Bindings;
1532 void ReadConfiguration(bool rebind)
1536 for (int j =0; j < Conf->Enumerate("bind"); j++)
1538 std::string Type = Conf->ReadValue("bind","type",j);
1539 std::string IP = Conf->ReadValue("bind","address",j);
1540 long Port = Conf->ReadInteger("bind","port",j,true);
1541 if (Type == "servers")
1547 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1548 if (listener->GetState() == I_LISTENING)
1550 Srv->AddSocket(listener);
1551 Bindings.push_back(listener);
1555 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1563 for (int j =0; j < Conf->Enumerate("link"); j++)
1566 L.Name = Conf->ReadValue("link","name",j);
1567 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1568 L.Port = Conf->ReadInteger("link","port",j,true);
1569 L.SendPass = Conf->ReadValue("link","sendpass",j);
1570 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1571 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1572 L.NextConnectTime = time(NULL) + L.AutoConnect;
1573 LinkBlocks.push_back(L);
1574 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1579 class ModuleSpanningTree : public Module
1581 std::vector<TreeSocket*> Bindings;
1587 ModuleSpanningTree()
1590 Conf = new ConfigReader;
1593 // Create the root of the tree
1594 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1596 ReadConfiguration(true);
1599 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1601 std::string Parent = TreeRoot->GetName();
1602 if (Current->GetParent())
1604 Parent = Current->GetParent()->GetName();
1606 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1608 ShowLinks(Current->GetChild(q),user,hops+1);
1610 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1613 int CountLocalServs()
1615 return TreeRoot->ChildCount();
1618 void CountServsRecursive(TreeServer* Current)
1621 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1623 CountServsRecursive(Current->GetChild(q));
1630 CountServsRecursive(TreeRoot);
1634 void HandleLinks(char** parameters, int pcnt, userrec* user)
1636 ShowLinks(TreeRoot,user,0);
1637 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1641 void HandleLusers(char** parameters, int pcnt, userrec* user)
1643 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1644 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1645 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1646 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1647 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1651 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1653 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1657 for (int t = 0; t < depth; t++)
1659 matrix[line][t] = ' ';
1661 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1663 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1665 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1670 // Ok, prepare to be confused.
1671 // After much mulling over how to approach this, it struck me that
1672 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1673 // keeping track of a ton of ascii characters, and line by line
1674 // under recursion working out where to place them using multiplications
1675 // and divisons, we instead render the map onto a backplane of characters
1676 // (a character matrix), then draw the branches as a series of "L" shapes
1677 // from the nodes. This is not only friendlier on CPU it uses less stack.
1679 void HandleMap(char** parameters, int pcnt, userrec* user)
1681 // This array represents a virtual screen which we will
1682 // "scratch" draw to, as the console device of an irc
1683 // client does not provide for a proper terminal.
1684 char matrix[128][80];
1685 for (unsigned int t = 0; t < 128; t++)
1687 matrix[t][0] = '\0';
1690 // The only recursive bit is called here.
1691 ShowMap(TreeRoot,user,0,matrix);
1692 // Process each line one by one. The algorithm has a limit of
1693 // 128 servers (which is far more than a spanning tree should have
1694 // anyway, so we're ok). This limit can be raised simply by making
1695 // the character matrix deeper, 128 rows taking 10k of memory.
1696 for (int l = 1; l < line; l++)
1698 // scan across the line looking for the start of the
1699 // servername (the recursive part of the algorithm has placed
1700 // the servers at indented positions depending on what they
1702 int first_nonspace = 0;
1703 while (matrix[l][first_nonspace] == ' ')
1708 // Draw the `- (corner) section: this may be overwritten by
1709 // another L shape passing along the same vertical pane, becoming
1710 // a |- (branch) section instead.
1711 matrix[l][first_nonspace] = '-';
1712 matrix[l][first_nonspace-1] = '`';
1714 // Draw upwards until we hit the parent server, causing possibly
1715 // other corners (`-) to become branches (|-)
1716 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1718 matrix[l2][first_nonspace-1] = '|';
1722 // dump the whole lot to the user. This is the easy bit, honest.
1723 for (int t = 0; t < line; t++)
1725 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1727 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1731 int HandleSquit(char** parameters, int pcnt, userrec* user)
1733 TreeServer* s = FindServerMask(parameters[0]);
1736 TreeSocket* sock = s->GetSocket();
1739 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1740 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1745 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1750 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1755 void DoPingChecks(time_t curtime)
1757 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1759 TreeServer* serv = TreeRoot->GetChild(j);
1760 TreeSocket* sock = serv->GetSocket();
1763 if (curtime >= serv->NextPingTime())
1765 if (serv->AnsweredLastPing())
1767 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1768 serv->SetNextPingTime(curtime + 60);
1772 // they didnt answer, boot them
1773 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1774 sock->Squit(serv,"Ping timeout");
1783 void AutoConnectServers(time_t curtime)
1785 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1787 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1789 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1790 x->NextConnectTime = curtime + x->AutoConnect;
1791 TreeServer* CheckDupe = FindServer(x->Name);
1794 // an autoconnected server is not connected. Check if its time to connect it
1795 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1796 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1797 Srv->AddSocket(newsocket);
1803 int HandleVersion(char** parameters, int pcnt, userrec* user)
1805 // we've already checked if pcnt > 0, so this is safe
1806 TreeServer* found = FindServerMask(parameters[0]);
1809 std::string Version = found->GetVersion();
1810 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1814 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1819 int HandleConnect(char** parameters, int pcnt, userrec* user)
1821 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1823 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1825 TreeServer* CheckDupe = FindServer(x->Name);
1828 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);
1829 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1830 Srv->AddSocket(newsocket);
1835 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());
1840 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1844 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1846 if (command == "CONNECT")
1848 return this->HandleConnect(parameters,pcnt,user);
1850 else if (command == "SQUIT")
1852 return this->HandleSquit(parameters,pcnt,user);
1854 else if (command == "MAP")
1856 this->HandleMap(parameters,pcnt,user);
1859 else if (command == "LUSERS")
1861 this->HandleLusers(parameters,pcnt,user);
1864 else if (command == "LINKS")
1866 this->HandleLinks(parameters,pcnt,user);
1869 else if ((command == "VERSION") && (pcnt > 0))
1871 this->HandleVersion(parameters,pcnt,user);
1874 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1876 // this bit of code cleverly routes all module commands
1877 // to all remote severs *automatically* so that modules
1878 // can just handle commands locally, without having
1879 // to have any special provision in place for remote
1880 // commands and linking protocols.
1881 std::deque<std::string> params;
1883 for (int j = 0; j < pcnt; j++)
1885 if (strchr(parameters[j],' '))
1887 params.push_back(":" + std::string(parameters[j]));
1891 params.push_back(std::string(parameters[j]));
1894 DoOneToMany(user->nick,command,params);
1899 virtual void OnGetServerDescription(std::string servername,std::string &description)
1901 TreeServer* s = FindServer(servername);
1904 description = s->GetDesc();
1908 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1910 if (std::string(source->server) == Srv->GetServerName())
1912 std::deque<std::string> params;
1913 params.push_back(dest->nick);
1914 params.push_back(channel->name);
1915 DoOneToMany(source->nick,"INVITE",params);
1919 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1921 std::deque<std::string> params;
1922 params.push_back(chan->name);
1923 params.push_back(":"+topic);
1924 DoOneToMany(user->nick,"TOPIC",params);
1927 virtual void OnWallops(userrec* user, std::string text)
1929 if (std::string(user->server) == Srv->GetServerName())
1931 std::deque<std::string> params;
1932 params.push_back(":"+text);
1933 DoOneToMany(user->nick,"WALLOPS",params);
1937 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1939 if (target_type == TYPE_USER)
1941 userrec* d = (userrec*)dest;
1942 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1944 std::deque<std::string> params;
1946 params.push_back(d->nick);
1947 params.push_back(":"+text);
1948 DoOneToOne(user->nick,"NOTICE",params,d->server);
1953 if (std::string(user->server) == Srv->GetServerName())
1955 chanrec *c = (chanrec*)dest;
1956 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1957 for (unsigned int i = 0; i < list.size(); i++)
1959 TreeSocket* Sock = list[i]->GetSocket();
1961 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1967 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1969 if (target_type == TYPE_USER)
1971 // route private messages which are targetted at clients only to the server
1972 // which needs to receive them
1973 userrec* d = (userrec*)dest;
1974 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1976 std::deque<std::string> params;
1978 params.push_back(d->nick);
1979 params.push_back(":"+text);
1980 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1985 if (std::string(user->server) == Srv->GetServerName())
1987 chanrec *c = (chanrec*)dest;
1988 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1989 for (unsigned int i = 0; i < list.size(); i++)
1991 TreeSocket* Sock = list[i]->GetSocket();
1993 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
1999 virtual void OnBackgroundTimer(time_t curtime)
2001 AutoConnectServers(curtime);
2002 DoPingChecks(curtime);
2005 virtual void OnUserJoin(userrec* user, chanrec* channel)
2007 // Only do this for local users
2008 if (std::string(user->server) == Srv->GetServerName())
2010 std::deque<std::string> params;
2012 params.push_back(channel->name);
2015 // if the channel has a key, force the join by emulating the key.
2016 params.push_back(channel->key);
2018 if (channel->GetUserCounter() > 1)
2020 // not the first in the channel
2021 DoOneToMany(user->nick,"JOIN",params);
2025 // first in the channel, set up their permissions
2026 // and the channel TS with FJOIN.
2028 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2030 params.push_back(channel->name);
2031 params.push_back(ts);
2032 params.push_back("@"+std::string(user->nick));
2033 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2038 virtual void OnChangeHost(userrec* user, std::string newhost)
2040 // only occurs for local clients
2041 std::deque<std::string> params;
2042 params.push_back(newhost);
2043 DoOneToMany(user->nick,"FHOST",params);
2046 virtual void OnChangeName(userrec* user, std::string gecos)
2048 // only occurs for local clients
2049 std::deque<std::string> params;
2050 params.push_back(gecos);
2051 DoOneToMany(user->nick,"FNAME",params);
2054 virtual void OnUserPart(userrec* user, chanrec* channel)
2056 if (std::string(user->server) == Srv->GetServerName())
2058 std::deque<std::string> params;
2060 params.push_back(channel->name);
2061 DoOneToMany(user->nick,"PART",params);
2065 virtual void OnUserConnect(userrec* user)
2067 char agestr[MAXBUF];
2068 if (std::string(user->server) == Srv->GetServerName())
2070 std::deque<std::string> params;
2071 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2073 params.push_back(agestr);
2074 params.push_back(user->nick);
2075 params.push_back(user->host);
2076 params.push_back(user->dhost);
2077 params.push_back(user->ident);
2078 params.push_back("+"+std::string(user->modes));
2079 params.push_back(user->ip);
2080 params.push_back(":"+std::string(user->fullname));
2081 DoOneToMany(Srv->GetServerName(),"NICK",params);
2085 virtual void OnUserQuit(userrec* user, std::string reason)
2087 if (std::string(user->server) == Srv->GetServerName())
2089 std::deque<std::string> params;
2090 params.push_back(":"+reason);
2091 DoOneToMany(user->nick,"QUIT",params);
2095 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2097 if (std::string(user->server) == Srv->GetServerName())
2099 std::deque<std::string> params;
2100 params.push_back(user->nick);
2101 DoOneToMany(oldnick,"NICK",params);
2105 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2107 if (std::string(source->server) == Srv->GetServerName())
2109 std::deque<std::string> params;
2110 params.push_back(chan->name);
2111 params.push_back(user->nick);
2112 params.push_back(":"+reason);
2113 DoOneToMany(source->nick,"KICK",params);
2117 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2119 std::deque<std::string> params;
2120 params.push_back(dest->nick);
2121 params.push_back(":"+reason);
2122 DoOneToMany(source->nick,"KILL",params);
2125 virtual void OnRehash(std::string parameter)
2127 if (parameter != "")
2129 std::deque<std::string> params;
2130 params.push_back(parameter);
2131 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2133 if (Srv->MatchText(Srv->GetServerName(),parameter))
2135 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2136 Srv->RehashServer();
2139 ReadConfiguration(false);
2142 // note: the protocol does not allow direct umode +o except
2143 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2145 virtual void OnOper(userrec* user, std::string opertype)
2147 if (std::string(user->server) == Srv->GetServerName())
2149 std::deque<std::string> params;
2150 params.push_back(opertype);
2151 DoOneToMany(user->nick,"OPERTYPE",params);
2155 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2157 if (std::string(user->server) == Srv->GetServerName())
2159 if (target_type == TYPE_USER)
2161 userrec* u = (userrec*)dest;
2162 std::deque<std::string> params;
2163 params.push_back(u->nick);
2164 params.push_back(text);
2165 DoOneToMany(user->nick,"MODE",params);
2169 chanrec* c = (chanrec*)dest;
2170 std::deque<std::string> params;
2171 params.push_back(c->name);
2172 params.push_back(text);
2173 DoOneToMany(user->nick,"MODE",params);
2178 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2180 TreeSocket* s = (TreeSocket*)opaque;
2183 if (target_type == TYPE_USER)
2185 userrec* u = (userrec*)target;
2186 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2190 chanrec* c = (chanrec*)target;
2191 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2196 virtual ~ModuleSpanningTree()
2201 virtual Version GetVersion()
2203 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2208 class ModuleSpanningTreeFactory : public ModuleFactory
2211 ModuleSpanningTreeFactory()
2215 ~ModuleSpanningTreeFactory()
2219 virtual Module * CreateModule()
2221 TreeProtocolModule = new ModuleSpanningTree;
2222 return TreeProtocolModule;
2228 extern "C" void * init_module( void )
2230 return new ModuleSpanningTreeFactory;