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;
65 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
66 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
67 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
68 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
69 void ReadConfiguration(bool rebind);
75 std::vector<TreeServer*> Children;
76 std::string ServerName;
77 std::string ServerDesc;
78 std::string VersionString;
81 TreeSocket* Socket; // for directly connected servers this points at the socket object
93 UserCount = OperCount = 0;
94 VersionString = GetVersionString();
97 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
101 UserCount = OperCount = 0;
102 VersionString = GetVersionString();
106 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
109 UserCount = OperCount = 0;
110 this->SetNextPingTime(time(NULL) + 60);
113 // find the 'route' for this server (e.g. the one directly connected
114 // to the local server, which we can use to reach it)
116 if (Route != TreeRoot)
117 while (Route->GetParent() != TreeRoot)
118 Route = Route->GetParent();
121 TreeServer* GetRoute()
126 std::string GetName()
128 return this->ServerName;
131 std::string GetDesc()
133 return this->ServerDesc;
136 std::string GetVersion()
138 return this->VersionString;
141 void SetNextPingTime(time_t t)
144 LastPingWasGood = false;
147 time_t NextPingTime()
149 return this->NextPing;
152 bool AnsweredLastPing()
154 return LastPingWasGood;
159 LastPingWasGood = true;
164 return this->UserCount;
169 return this->OperCount;
172 TreeSocket* GetSocket()
177 TreeServer* GetParent()
182 void SetVersion(std::string Version)
184 VersionString = Version;
187 unsigned int ChildCount()
189 return Children.size();
192 TreeServer* GetChild(unsigned int n)
194 if (n < Children.size())
204 void AddChild(TreeServer* Child)
206 Children.push_back(Child);
209 bool DelChild(TreeServer* Child)
211 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
222 // removes child nodes of this node, and of that node, etc etc
225 bool stillchildren = true;
226 while (stillchildren)
228 stillchildren = false;
229 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
231 TreeServer* s = (TreeServer*)*a;
235 stillchildren = true;
249 std::string SendPass;
250 std::string RecvPass;
251 unsigned long AutoConnect;
252 time_t NextConnectTime;
255 /* $ModDesc: Povides a spanning tree server link protocol */
259 std::vector<Link> LinkBlocks;
261 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
263 if (Current->GetName() == ServerName)
264 return Current->GetRoute();
265 for (unsigned int q = 0; q < Current->ChildCount(); q++)
267 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
269 return found->GetRoute();
274 // Returns the locally connected server we must route a
275 // message through to reach server 'ServerName'. This
276 // only applies to one-to-one and not one-to-many routing.
277 TreeServer* BestRouteTo(std::string ServerName)
279 if (ServerName.c_str() == TreeRoot->GetName())
283 // first, find the server by recursively walking the tree
284 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
288 bool LookForServer(TreeServer* Current, std::string ServerName)
290 if (ServerName == Current->GetName())
292 for (unsigned int q = 0; q < Current->ChildCount(); q++)
294 if (LookForServer(Current->GetChild(q),ServerName))
302 void RFindServer(TreeServer* Current, std::string ServerName)
304 if ((ServerName == Current->GetName()) && (!Found))
311 for (unsigned int q = 0; q < Current->ChildCount(); q++)
314 RFindServer(Current->GetChild(q),ServerName);
320 void RFindServerMask(TreeServer* Current, std::string ServerName)
322 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
329 for (unsigned int q = 0; q < Current->ChildCount(); q++)
332 RFindServerMask(Current->GetChild(q),ServerName);
337 TreeServer* FindServer(std::string ServerName)
340 RFindServer(TreeRoot,ServerName);
344 TreeServer* FindServerMask(std::string ServerName)
347 RFindServerMask(TreeRoot,ServerName);
351 bool IsServer(std::string ServerName)
353 return LookForServer(TreeRoot,ServerName);
356 class TreeSocket : public InspSocket
359 std::string in_buffer;
360 ServerState LinkState;
361 std::string InboundServerName;
362 std::string InboundDescription;
364 int num_lost_servers;
366 bool LastPingWasGood;
370 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
371 : InspSocket(host, port, listening, maxtime)
374 this->LinkState = LISTENER;
377 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
378 : InspSocket(host, port, listening, maxtime)
381 this->LinkState = CONNECTING;
384 TreeSocket(int newfd, char* ip)
385 : InspSocket(newfd, ip)
387 this->LinkState = WAIT_AUTH_1;
390 virtual bool OnConnected()
392 if (this->LinkState == CONNECTING)
394 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
395 // we should send our details here.
396 // if the other side is satisfied, they send theirs.
397 // we do not need to change state here.
398 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
400 if (x->Name == this->myhost)
402 // found who we're supposed to be connecting to, send the neccessary gubbins.
403 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
411 virtual void OnError(InspSocketError e)
415 virtual int OnDisconnect()
420 // recursively send the server tree with distances as hops
421 void SendServers(TreeServer* Current, TreeServer* s, int hops)
424 for (unsigned int q = 0; q < Current->ChildCount(); q++)
426 TreeServer* recursive_server = Current->GetChild(q);
427 if (recursive_server != s)
429 // :source.server SERVER server.name hops :Description
430 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
431 this->WriteLine(command);
432 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
433 // down to next level
434 this->SendServers(recursive_server, s, hops+1);
439 void SquitServer(TreeServer* Current)
441 // recursively squit the servers attached to 'Current'
442 for (unsigned int q = 0; q < Current->ChildCount(); q++)
444 TreeServer* recursive_server = Current->GetChild(q);
445 this->SquitServer(recursive_server);
447 // Now we've whacked the kids, whack self
449 bool quittingpeople = true;
450 while (quittingpeople)
452 quittingpeople = false;
453 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
455 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
457 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
459 quittingpeople = true;
466 void Squit(TreeServer* Current,std::string reason)
470 std::deque<std::string> params;
471 params.push_back(Current->GetName());
472 params.push_back(":"+reason);
473 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
474 if (Current->GetParent() == TreeRoot)
476 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
480 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
482 num_lost_servers = 0;
484 SquitServer(Current);
486 Current->GetParent()->DelChild(Current);
488 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
492 log(DEFAULT,"Squit from unknown server");
496 bool ForceMode(std::string source, std::deque<std::string> params)
498 userrec* who = new userrec;
499 who->fd = FD_MAGIC_NUMBER;
500 if (params.size() < 2)
503 for (unsigned int q = 0; q < params.size(); q++)
505 modelist[q] = (char*)params[q].c_str();
507 Srv->SendMode(modelist,params.size(),who);
508 DoOneToAllButSender(source,"FMODE",params,source);
513 bool ForceTopic(std::string source, std::deque<std::string> params)
515 // FTOPIC %s %lu %s :%s
516 if (params.size() != 4)
518 std::string channel = params[0];
519 time_t ts = atoi(params[1].c_str());
520 std::string setby = params[2];
521 std::string topic = params[3];
523 chanrec* c = Srv->FindChannel(channel);
526 if ((ts >= c->topicset) || (!*c->topic))
528 std::string oldtopic = c->topic;
529 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
530 strlcpy(c->setby,setby.c_str(),NICKMAX);
532 // if the topic text is the same as the current topic,
533 // dont bother to send the TOPIC command out, just silently
534 // update the set time and set nick.
535 if (oldtopic != topic)
536 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
541 // all done, send it on its way
542 params[3] = ":" + params[3];
543 DoOneToAllButSender(source,"FTOPIC",params,source);
548 bool ForceJoin(std::string source, std::deque<std::string> params)
550 if (params.size() < 3)
554 char modestring[MAXBUF];
555 char* mode_users[127];
556 mode_users[0] = first;
557 mode_users[1] = modestring;
558 strcpy(mode_users[1],"+");
559 unsigned int modectr = 2;
562 std::string channel = params[0];
563 time_t TS = atoi(params[1].c_str());
566 chanrec* chan = Srv->FindChannel(channel);
571 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
573 // default is a high value, which if we dont have this
574 // channel will let the other side apply their modes.
575 time_t ourTS = time(NULL)+600;
576 chanrec* us = Srv->FindChannel(channel);
582 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
584 // do this first, so our mode reversals are correctly received by other servers
585 // if there is a TS collision.
586 DoOneToAllButSender(source,"FJOIN",params,source);
588 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
590 // process one channel at a time, applying modes.
591 char* usr = (char*)params[usernum].c_str();
592 char permissions = *usr;
597 mode_users[modectr++] = usr;
598 strlcat(modestring,"o",MAXBUF);
602 mode_users[modectr++] = usr;
603 strlcat(modestring,"h",MAXBUF);
607 mode_users[modectr++] = usr;
608 strlcat(modestring,"v",MAXBUF);
611 who = Srv->FindNick(usr);
614 Srv->JoinUserToChannel(who,channel,key);
615 if (modectr >= (MAXMODES-1))
617 // theres a mode for this user. push them onto the mode queue, and flush it
618 // if there are more than MAXMODES to go.
621 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
622 Srv->SendMode(mode_users,modectr,who);
626 log(DEBUG,"Their channel newer than ours, bouncing their modes");
628 std::deque<std::string> params;
629 // modes are now being UNSET...
630 *mode_users[1] = '-';
631 for (unsigned int x = 0; x < modectr; x++)
633 params.push_back(mode_users[x]);
635 // tell everyone to bounce the modes. bad modes, bad!
636 DoOneToMany(Srv->GetServerName(),"FMODE",params);
638 strcpy(mode_users[1],"+");
643 // there werent enough modes built up to flush it during FJOIN,
644 // or, there are a number left over. flush them out.
645 if ((modectr > 2) && (who))
649 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
650 Srv->SendMode(mode_users,modectr,who);
654 log(DEBUG,"Their channel newer than ours, bouncing their modes");
655 std::deque<std::string> params;
656 *mode_users[1] = '-';
657 for (unsigned int x = 0; x < modectr; x++)
659 params.push_back(mode_users[x]);
661 DoOneToMany(Srv->GetServerName(),"FMODE",params);
667 bool IntroduceClient(std::string source, std::deque<std::string> params)
669 if (params.size() < 8)
671 // NICK age nick host dhost ident +modes ip :gecos
673 std::string nick = params[1];
674 std::string host = params[2];
675 std::string dhost = params[3];
676 std::string ident = params[4];
677 time_t age = atoi(params[0].c_str());
678 std::string modes = params[5];
679 while (*(modes.c_str()) == '+')
681 char* m = (char*)modes.c_str();
685 std::string ip = params[6];
686 std::string gecos = params[7];
687 char* tempnick = (char*)nick.c_str();
688 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
690 user_hash::iterator iter;
691 iter = clientlist.find(tempnick);
692 if (iter != clientlist.end())
695 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);
696 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
700 clientlist[tempnick] = new userrec();
701 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
702 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
703 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
704 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
705 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
706 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
707 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
708 clientlist[tempnick]->registered = 7;
709 clientlist[tempnick]->signon = age;
710 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
711 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
712 for (int i = 0; i < MAXCHANS; i++)
714 clientlist[tempnick]->chans[i].channel = NULL;
715 clientlist[tempnick]->chans[i].uc_modes = 0;
717 params[7] = ":" + params[7];
718 DoOneToAllButSender(source,"NICK",params,source);
722 void SendFJoins(TreeServer* Current, chanrec* c)
725 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
726 std::vector<char*> *ulist = c->GetUsers();
727 for (unsigned int i = 0; i < ulist->size(); i++)
729 char* o = (*ulist)[i];
730 userrec* otheruser = (userrec*)o;
731 strlcat(list," ",MAXBUF);
732 strlcat(list,cmode(otheruser,c),MAXBUF);
733 strlcat(list,otheruser->nick,MAXBUF);
734 if (strlen(list)>(480-NICKMAX))
736 this->WriteLine(list);
737 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
740 if (list[strlen(list)-1] != ':')
742 this->WriteLine(list);
746 void SendChannelModes(TreeServer* Current)
749 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
751 SendFJoins(Current, c->second);
752 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
753 this->WriteLine(data);
754 if (*c->second->topic)
756 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);
757 this->WriteLine(data);
759 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
761 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
762 this->WriteLine(data);
764 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
768 // send all users and their channels
769 void SendUsers(TreeServer* Current)
772 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
774 if (u->second->registered == 7)
776 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);
777 this->WriteLine(data);
778 if (strchr(u->second->modes,'o'))
780 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
782 //char* chl = chlist(u->second,u->second);
785 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
787 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
792 void DoBurst(TreeServer* s)
794 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
795 this->WriteLine("BURST");
796 // send our version string
797 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
799 this->SendServers(TreeRoot,s,1);
800 // Send users and their channels
802 // Send everything else (channel modes etc)
803 this->SendChannelModes(s);
804 this->WriteLine("ENDBURST");
807 virtual bool OnDataReady()
809 char* data = this->Read();
812 this->in_buffer += data;
813 while (in_buffer.find("\n") != std::string::npos)
815 char* line = (char*)in_buffer.c_str();
816 std::string ret = "";
817 while ((*line != '\n') && (strlen(line)))
822 if ((*line == '\n') || (*line == '\r'))
825 if (!this->ProcessLine(ret))
831 return (data != NULL);
834 int WriteLine(std::string line)
836 return this->Write(line + "\r\n");
839 bool Error(std::deque<std::string> params)
841 if (params.size() < 1)
843 std::string Errmsg = params[0];
844 std::string SName = myhost;
845 if (InboundServerName != "")
847 SName = InboundServerName;
849 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
850 // we will return false to cause the socket to close.
854 bool OperType(std::string prefix, std::deque<std::string> params)
856 if (params.size() != 1)
858 std::string opertype = params[0];
859 userrec* u = Srv->FindNick(prefix);
862 strlcpy(u->oper,opertype.c_str(),NICKMAX);
863 if (!strchr(u->modes,'o'))
865 strcat(u->modes,"o");
867 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
872 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
874 if (params.size() < 1)
876 std::string servermask = params[0];
877 if (Srv->MatchText(Srv->GetServerName(),servermask))
879 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
881 ReadConfiguration(false);
883 DoOneToAllButSender(prefix,"REHASH",params,prefix);
887 bool RemoteKill(std::string prefix, std::deque<std::string> params)
889 if (params.size() != 2)
891 std::string nick = params[0];
892 std::string reason = params[1];
893 userrec* u = Srv->FindNick(prefix);
894 userrec* who = Srv->FindNick(nick);
897 std::string sourceserv = prefix;
900 sourceserv = u->server;
902 params[1] = ":" + params[1];
903 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
904 Srv->QuitUser(who,reason);
909 bool LocalPong(std::string prefix, std::deque<std::string> params)
911 if (params.size() < 1)
913 TreeServer* ServerSource = FindServer(prefix);
916 ServerSource->SetPingFlag();
921 bool ServerVersion(std::string prefix, std::deque<std::string> params)
923 if (params.size() < 1)
925 TreeServer* ServerSource = FindServer(prefix);
928 ServerSource->SetVersion(params[0]);
930 params[0] = ":" + params[0];
931 DoOneToAllButSender(prefix,"VERSION",params,prefix);
935 bool ChangeHost(std::string prefix, std::deque<std::string> params)
937 if (params.size() < 1)
939 userrec* u = Srv->FindNick(prefix);
942 Srv->ChangeHost(u,params[0]);
943 DoOneToAllButSender(prefix,"FHOST",params,u->server);
948 bool ChangeName(std::string prefix, std::deque<std::string> params)
950 if (params.size() < 1)
952 userrec* u = Srv->FindNick(prefix);
955 Srv->ChangeGECOS(u,params[0]);
956 params[0] = ":" + params[0];
957 DoOneToAllButSender(prefix,"FNAME",params,u->server);
962 bool LocalPing(std::string prefix, std::deque<std::string> params)
964 if (params.size() < 1)
966 std::string stufftobounce = params[0];
967 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
971 bool RemoteServer(std::string prefix, std::deque<std::string> params)
973 if (params.size() < 4)
975 std::string servername = params[0];
976 std::string password = params[1];
977 // hopcount is not used for a remote server, we calculate this ourselves
978 std::string description = params[3];
979 TreeServer* ParentOfThis = FindServer(prefix);
982 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
985 TreeServer* CheckDupe = FindServer(servername);
988 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
991 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
992 ParentOfThis->AddChild(Node);
993 params[3] = ":" + params[3];
994 DoOneToAllButSender(prefix,"SERVER",params,prefix);
995 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
999 bool Outbound_Reply_Server(std::deque<std::string> params)
1001 if (params.size() < 4)
1003 std::string servername = params[0];
1004 std::string password = params[1];
1005 int hops = atoi(params[2].c_str());
1008 this->WriteLine("ERROR :Server too far away for authentication");
1011 std::string description = params[3];
1012 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1014 if ((x->Name == servername) && (x->RecvPass == password))
1016 TreeServer* CheckDupe = FindServer(servername);
1019 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1022 // Begin the sync here. this kickstarts the
1023 // other side, waiting in WAIT_AUTH_2 state,
1024 // into starting their burst, as it shows
1025 // that we're happy.
1026 this->LinkState = CONNECTED;
1027 // we should add the details of this server now
1028 // to the servers tree, as a child of the root
1030 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1031 TreeRoot->AddChild(Node);
1032 params[3] = ":" + params[3];
1033 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1034 this->DoBurst(Node);
1038 this->WriteLine("ERROR :Invalid credentials");
1042 bool Inbound_Server(std::deque<std::string> params)
1044 if (params.size() < 4)
1046 std::string servername = params[0];
1047 std::string password = params[1];
1048 int hops = atoi(params[2].c_str());
1051 this->WriteLine("ERROR :Server too far away for authentication");
1054 std::string description = params[3];
1055 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1057 if ((x->Name == servername) && (x->RecvPass == password))
1059 TreeServer* CheckDupe = FindServer(servername);
1062 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1065 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1066 this->InboundServerName = servername;
1067 this->InboundDescription = description;
1068 // this is good. Send our details: Our server name and description and hopcount of 0,
1069 // along with the sendpass from this block.
1070 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1071 // move to the next state, we are now waiting for THEM.
1072 this->LinkState = WAIT_AUTH_2;
1076 this->WriteLine("ERROR :Invalid credentials");
1080 std::deque<std::string> Split(std::string line, bool stripcolon)
1082 std::deque<std::string> n;
1083 if (!strchr(line.c_str(),' '))
1088 std::stringstream s(line);
1089 std::string param = "";
1108 if ((param == ":") && (item > 0))
1131 bool ProcessLine(std::string line)
1133 char* l = (char*)line.c_str();
1134 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1135 l[strlen(l)-1] = '\0';
1139 Srv->Log(DEBUG,"IN: '"+line+"'");
1140 std::deque<std::string> params = this->Split(line,true);
1141 std::string command = "";
1142 std::string prefix = "";
1143 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1146 command = params[1];
1147 char* pref = (char*)prefix.c_str();
1155 command = params[0];
1159 switch (this->LinkState)
1164 // Waiting for SERVER command from remote server. Server initiating
1165 // the connection sends the first SERVER command, listening server
1166 // replies with theirs if its happy, then if the initiator is happy,
1167 // it starts to send its net sync, which starts the merge, otherwise
1168 // it sends an ERROR.
1169 if (command == "SERVER")
1171 return this->Inbound_Server(params);
1173 else if (command == "ERROR")
1175 return this->Error(params);
1179 // Waiting for start of other side's netmerge to say they liked our
1181 if (command == "SERVER")
1183 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1187 else if (command == "BURST")
1189 this->LinkState = CONNECTED;
1190 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1191 TreeRoot->AddChild(Node);
1193 params.push_back(InboundServerName);
1194 params.push_back("*");
1195 params.push_back("1");
1196 params.push_back(":"+InboundDescription);
1197 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1198 this->DoBurst(Node);
1200 else if (command == "ERROR")
1202 return this->Error(params);
1207 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1211 if (command == "SERVER")
1213 // another server we connected to, which was in WAIT_AUTH_1 state,
1214 // has just sent us their credentials. If we get this far, theyre
1215 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1216 // if we're happy with this, we should send our netburst which
1217 // kickstarts the merge.
1218 return this->Outbound_Reply_Server(params);
1220 else if (command == "ERROR")
1222 return this->Error(params);
1226 // This is the 'authenticated' state, when all passwords
1227 // have been exchanged and anything past this point is taken
1229 std::string target = "";
1230 if ((command == "NICK") && (params.size() > 1))
1232 return this->IntroduceClient(prefix,params);
1234 else if (command == "FJOIN")
1236 return this->ForceJoin(prefix,params);
1238 else if (command == "SERVER")
1240 return this->RemoteServer(prefix,params);
1242 else if (command == "ERROR")
1244 return this->Error(params);
1246 else if (command == "OPERTYPE")
1248 return this->OperType(prefix,params);
1250 else if (command == "FMODE")
1252 return this->ForceMode(prefix,params);
1254 else if (command == "KILL")
1256 return this->RemoteKill(prefix,params);
1258 else if (command == "FTOPIC")
1260 return this->ForceTopic(prefix,params);
1262 else if (command == "REHASH")
1264 return this->RemoteRehash(prefix,params);
1266 else if (command == "PING")
1268 return this->LocalPing(prefix,params);
1270 else if (command == "PONG")
1272 return this->LocalPong(prefix,params);
1274 else if (command == "VERSION")
1276 return this->ServerVersion(prefix,params);
1278 else if (command == "FHOST")
1280 return this->ChangeHost(prefix,params);
1282 else if (command == "FNAME")
1284 return this->ChangeName(prefix,params);
1286 else if (command == "SQUIT")
1288 if (params.size() == 2)
1290 this->Squit(FindServer(params[0]),params[1]);
1296 // not a special inter-server command.
1297 // Emulate the actual user doing the command,
1298 // this saves us having a huge ugly parser.
1299 userrec* who = Srv->FindNick(prefix);
1300 std::string sourceserv = this->myhost;
1301 if (this->InboundServerName != "")
1303 sourceserv = this->InboundServerName;
1308 target = who->server;
1309 char* strparams[127];
1310 for (unsigned int q = 0; q < params.size(); q++)
1312 strparams[q] = (char*)params[q].c_str();
1314 Srv->CallCommandHandler(command, strparams, params.size(), who);
1318 // its not a user. Its either a server, or somethings screwed up.
1319 if (IsServer(prefix))
1321 target = Srv->GetServerName();
1325 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1329 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1338 virtual std::string GetName()
1340 std::string sourceserv = this->myhost;
1341 if (this->InboundServerName != "")
1343 sourceserv = this->InboundServerName;
1348 virtual void OnTimeout()
1350 if (this->LinkState == CONNECTING)
1352 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1356 virtual void OnClose()
1358 // Connection closed.
1359 // If the connection is fully up (state CONNECTED)
1360 // then propogate a netsplit to all peers.
1361 std::string quitserver = this->myhost;
1362 if (this->InboundServerName != "")
1364 quitserver = this->InboundServerName;
1366 TreeServer* s = FindServer(quitserver);
1369 Squit(s,"Remote host closed the connection");
1373 virtual int OnIncomingConnection(int newsock, char* ip)
1375 TreeSocket* s = new TreeSocket(newsock, ip);
1381 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1383 for (unsigned int c = 0; c < list.size(); c++)
1385 if (list[c] == server)
1390 list.push_back(server);
1393 // returns a list of DIRECT servernames for a specific channel
1394 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1396 std::deque<TreeServer*> list;
1397 std::vector<char*> *ulist = c->GetUsers();
1398 for (unsigned int i = 0; i < ulist->size(); i++)
1400 char* o = (*ulist)[i];
1401 userrec* otheruser = (userrec*)o;
1402 if (std::string(otheruser->server) != Srv->GetServerName())
1404 TreeServer* best = BestRouteTo(otheruser->server);
1406 AddThisServer(best,list);
1412 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1414 TreeServer* omitroute = BestRouteTo(omit);
1415 if ((command == "NOTICE") || (command == "PRIVMSG"))
1417 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1419 if (*(params[0].c_str()) != '#')
1421 // special routing for private messages/notices
1422 userrec* d = Srv->FindNick(params[0]);
1425 std::deque<std::string> par;
1427 par.push_back(params[0]);
1428 par.push_back(":"+params[1]);
1429 DoOneToOne(prefix,command,par,d->server);
1435 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1436 chanrec* c = Srv->FindChannel(params[0]);
1439 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1440 log(DEBUG,"Got a list of %d servers",list.size());
1441 for (unsigned int i = 0; i < list.size(); i++)
1443 TreeSocket* Sock = list[i]->GetSocket();
1444 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1446 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1447 Sock->WriteLine(data);
1455 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1457 TreeServer* Route = TreeRoot->GetChild(x);
1458 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1460 TreeSocket* Sock = Route->GetSocket();
1461 Sock->WriteLine(data);
1467 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1469 TreeServer* omitroute = BestRouteTo(omit);
1470 std::string FullLine = ":" + prefix + " " + command;
1471 for (unsigned int x = 0; x < params.size(); x++)
1473 FullLine = FullLine + " " + params[x];
1475 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1477 TreeServer* Route = TreeRoot->GetChild(x);
1478 // Send the line IF:
1479 // The route has a socket (its a direct connection)
1480 // The route isnt the one to be omitted
1481 // The route isnt the path to the one to be omitted
1482 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1484 TreeSocket* Sock = Route->GetSocket();
1485 Sock->WriteLine(FullLine);
1491 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1493 std::string FullLine = ":" + prefix + " " + command;
1494 for (unsigned int x = 0; x < params.size(); x++)
1496 FullLine = FullLine + " " + params[x];
1498 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1500 TreeServer* Route = TreeRoot->GetChild(x);
1501 if (Route->GetSocket())
1503 TreeSocket* Sock = Route->GetSocket();
1504 Sock->WriteLine(FullLine);
1510 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1512 TreeServer* Route = BestRouteTo(target);
1515 std::string FullLine = ":" + prefix + " " + command;
1516 for (unsigned int x = 0; x < params.size(); x++)
1518 FullLine = FullLine + " " + params[x];
1520 if (Route->GetSocket())
1522 TreeSocket* Sock = Route->GetSocket();
1523 Sock->WriteLine(FullLine);
1533 std::vector<TreeSocket*> Bindings;
1535 void ReadConfiguration(bool rebind)
1539 for (int j =0; j < Conf->Enumerate("bind"); j++)
1541 std::string Type = Conf->ReadValue("bind","type",j);
1542 std::string IP = Conf->ReadValue("bind","address",j);
1543 long Port = Conf->ReadInteger("bind","port",j,true);
1544 if (Type == "servers")
1550 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1551 if (listener->GetState() == I_LISTENING)
1553 Srv->AddSocket(listener);
1554 Bindings.push_back(listener);
1558 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1566 for (int j =0; j < Conf->Enumerate("link"); j++)
1569 L.Name = Conf->ReadValue("link","name",j);
1570 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1571 L.Port = Conf->ReadInteger("link","port",j,true);
1572 L.SendPass = Conf->ReadValue("link","sendpass",j);
1573 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1574 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1575 L.NextConnectTime = time(NULL) + L.AutoConnect;
1576 LinkBlocks.push_back(L);
1577 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1582 class ModuleSpanningTree : public Module
1584 std::vector<TreeSocket*> Bindings;
1590 ModuleSpanningTree()
1593 Conf = new ConfigReader;
1596 // Create the root of the tree
1597 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1599 ReadConfiguration(true);
1602 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1604 std::string Parent = TreeRoot->GetName();
1605 if (Current->GetParent())
1607 Parent = Current->GetParent()->GetName();
1609 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1611 ShowLinks(Current->GetChild(q),user,hops+1);
1613 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1616 int CountLocalServs()
1618 return TreeRoot->ChildCount();
1621 void CountServsRecursive(TreeServer* Current)
1624 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1626 CountServsRecursive(Current->GetChild(q));
1633 CountServsRecursive(TreeRoot);
1637 void HandleLinks(char** parameters, int pcnt, userrec* user)
1639 ShowLinks(TreeRoot,user,0);
1640 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1644 void HandleLusers(char** parameters, int pcnt, userrec* user)
1646 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1647 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1648 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1649 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1650 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1654 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1656 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1660 for (int t = 0; t < depth; t++)
1662 matrix[line][t] = ' ';
1664 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1666 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1668 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1673 // Ok, prepare to be confused.
1674 // After much mulling over how to approach this, it struck me that
1675 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1676 // keeping track of a ton of ascii characters, and line by line
1677 // under recursion working out where to place them using multiplications
1678 // and divisons, we instead render the map onto a backplane of characters
1679 // (a character matrix), then draw the branches as a series of "L" shapes
1680 // from the nodes. This is not only friendlier on CPU it uses less stack.
1682 void HandleMap(char** parameters, int pcnt, userrec* user)
1684 // This array represents a virtual screen which we will
1685 // "scratch" draw to, as the console device of an irc
1686 // client does not provide for a proper terminal.
1687 char matrix[128][80];
1688 for (unsigned int t = 0; t < 128; t++)
1690 matrix[t][0] = '\0';
1693 // The only recursive bit is called here.
1694 ShowMap(TreeRoot,user,0,matrix);
1695 // Process each line one by one. The algorithm has a limit of
1696 // 128 servers (which is far more than a spanning tree should have
1697 // anyway, so we're ok). This limit can be raised simply by making
1698 // the character matrix deeper, 128 rows taking 10k of memory.
1699 for (int l = 1; l < line; l++)
1701 // scan across the line looking for the start of the
1702 // servername (the recursive part of the algorithm has placed
1703 // the servers at indented positions depending on what they
1705 int first_nonspace = 0;
1706 while (matrix[l][first_nonspace] == ' ')
1711 // Draw the `- (corner) section: this may be overwritten by
1712 // another L shape passing along the same vertical pane, becoming
1713 // a |- (branch) section instead.
1714 matrix[l][first_nonspace] = '-';
1715 matrix[l][first_nonspace-1] = '`';
1717 // Draw upwards until we hit the parent server, causing possibly
1718 // other corners (`-) to become branches (|-)
1719 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1721 matrix[l2][first_nonspace-1] = '|';
1725 // dump the whole lot to the user. This is the easy bit, honest.
1726 for (int t = 0; t < line; t++)
1728 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1730 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1734 int HandleSquit(char** parameters, int pcnt, userrec* user)
1736 TreeServer* s = FindServerMask(parameters[0]);
1739 TreeSocket* sock = s->GetSocket();
1742 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1743 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1748 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1753 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1758 void DoPingChecks(time_t curtime)
1760 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1762 TreeServer* serv = TreeRoot->GetChild(j);
1763 TreeSocket* sock = serv->GetSocket();
1766 if (curtime >= serv->NextPingTime())
1768 if (serv->AnsweredLastPing())
1770 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1771 serv->SetNextPingTime(curtime + 60);
1775 // they didnt answer, boot them
1776 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1777 sock->Squit(serv,"Ping timeout");
1786 void AutoConnectServers(time_t curtime)
1788 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1790 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1792 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1793 x->NextConnectTime = curtime + x->AutoConnect;
1794 TreeServer* CheckDupe = FindServer(x->Name);
1797 // an autoconnected server is not connected. Check if its time to connect it
1798 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1799 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1800 Srv->AddSocket(newsocket);
1806 int HandleVersion(char** parameters, int pcnt, userrec* user)
1808 // we've already checked if pcnt > 0, so this is safe
1809 TreeServer* found = FindServerMask(parameters[0]);
1812 std::string Version = found->GetVersion();
1813 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1817 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1822 int HandleConnect(char** parameters, int pcnt, userrec* user)
1824 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1826 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1828 TreeServer* CheckDupe = FindServer(x->Name);
1831 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);
1832 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1833 Srv->AddSocket(newsocket);
1838 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());
1843 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1847 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1849 if (command == "CONNECT")
1851 return this->HandleConnect(parameters,pcnt,user);
1853 else if (command == "SQUIT")
1855 return this->HandleSquit(parameters,pcnt,user);
1857 else if (command == "MAP")
1859 this->HandleMap(parameters,pcnt,user);
1862 else if (command == "LUSERS")
1864 this->HandleLusers(parameters,pcnt,user);
1867 else if (command == "LINKS")
1869 this->HandleLinks(parameters,pcnt,user);
1872 else if ((command == "VERSION") && (pcnt > 0))
1874 this->HandleVersion(parameters,pcnt,user);
1877 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1879 // this bit of code cleverly routes all module commands
1880 // to all remote severs *automatically* so that modules
1881 // can just handle commands locally, without having
1882 // to have any special provision in place for remote
1883 // commands and linking protocols.
1884 std::deque<std::string> params;
1886 for (int j = 0; j < pcnt; j++)
1888 if (strchr(parameters[j],' '))
1890 params.push_back(":" + std::string(parameters[j]));
1894 params.push_back(std::string(parameters[j]));
1897 DoOneToMany(user->nick,command,params);
1902 virtual void OnGetServerDescription(std::string servername,std::string &description)
1904 TreeServer* s = FindServer(servername);
1907 description = s->GetDesc();
1911 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1913 if (std::string(source->server) == Srv->GetServerName())
1915 std::deque<std::string> params;
1916 params.push_back(dest->nick);
1917 params.push_back(channel->name);
1918 DoOneToMany(source->nick,"INVITE",params);
1922 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1924 std::deque<std::string> params;
1925 params.push_back(chan->name);
1926 params.push_back(":"+topic);
1927 DoOneToMany(user->nick,"TOPIC",params);
1930 virtual void OnWallops(userrec* user, std::string text)
1932 if (std::string(user->server) == Srv->GetServerName())
1934 std::deque<std::string> params;
1935 params.push_back(":"+text);
1936 DoOneToMany(user->nick,"WALLOPS",params);
1940 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1942 if (target_type == TYPE_USER)
1944 userrec* d = (userrec*)dest;
1945 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1947 std::deque<std::string> params;
1949 params.push_back(d->nick);
1950 params.push_back(":"+text);
1951 DoOneToOne(user->nick,"NOTICE",params,d->server);
1956 if (std::string(user->server) == Srv->GetServerName())
1958 chanrec *c = (chanrec*)dest;
1959 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1960 for (unsigned int i = 0; i < list.size(); i++)
1962 TreeSocket* Sock = list[i]->GetSocket();
1964 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1970 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1972 if (target_type == TYPE_USER)
1974 // route private messages which are targetted at clients only to the server
1975 // which needs to receive them
1976 userrec* d = (userrec*)dest;
1977 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1979 std::deque<std::string> params;
1981 params.push_back(d->nick);
1982 params.push_back(":"+text);
1983 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1988 if (std::string(user->server) == Srv->GetServerName())
1990 chanrec *c = (chanrec*)dest;
1991 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1992 for (unsigned int i = 0; i < list.size(); i++)
1994 TreeSocket* Sock = list[i]->GetSocket();
1996 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2002 virtual void OnBackgroundTimer(time_t curtime)
2004 AutoConnectServers(curtime);
2005 DoPingChecks(curtime);
2008 virtual void OnUserJoin(userrec* user, chanrec* channel)
2010 // Only do this for local users
2011 if (std::string(user->server) == Srv->GetServerName())
2013 std::deque<std::string> params;
2015 params.push_back(channel->name);
2018 // if the channel has a key, force the join by emulating the key.
2019 params.push_back(channel->key);
2021 if (channel->GetUserCounter() > 1)
2023 // not the first in the channel
2024 DoOneToMany(user->nick,"JOIN",params);
2028 // first in the channel, set up their permissions
2029 // and the channel TS with FJOIN.
2031 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2033 params.push_back(channel->name);
2034 params.push_back(ts);
2035 params.push_back("@"+std::string(user->nick));
2036 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2041 virtual void OnChangeHost(userrec* user, std::string newhost)
2043 // only occurs for local clients
2044 std::deque<std::string> params;
2045 params.push_back(newhost);
2046 DoOneToMany(user->nick,"FHOST",params);
2049 virtual void OnChangeName(userrec* user, std::string gecos)
2051 // only occurs for local clients
2052 std::deque<std::string> params;
2053 params.push_back(gecos);
2054 DoOneToMany(user->nick,"FNAME",params);
2057 virtual void OnUserPart(userrec* user, chanrec* channel)
2059 if (std::string(user->server) == Srv->GetServerName())
2061 std::deque<std::string> params;
2063 params.push_back(channel->name);
2064 DoOneToMany(user->nick,"PART",params);
2068 virtual void OnUserConnect(userrec* user)
2070 char agestr[MAXBUF];
2071 if (std::string(user->server) == Srv->GetServerName())
2073 std::deque<std::string> params;
2074 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2076 params.push_back(agestr);
2077 params.push_back(user->nick);
2078 params.push_back(user->host);
2079 params.push_back(user->dhost);
2080 params.push_back(user->ident);
2081 params.push_back("+"+std::string(user->modes));
2082 params.push_back(user->ip);
2083 params.push_back(":"+std::string(user->fullname));
2084 DoOneToMany(Srv->GetServerName(),"NICK",params);
2088 virtual void OnUserQuit(userrec* user, std::string reason)
2090 if (std::string(user->server) == Srv->GetServerName())
2092 std::deque<std::string> params;
2093 params.push_back(":"+reason);
2094 DoOneToMany(user->nick,"QUIT",params);
2098 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2100 if (std::string(user->server) == Srv->GetServerName())
2102 std::deque<std::string> params;
2103 params.push_back(user->nick);
2104 DoOneToMany(oldnick,"NICK",params);
2108 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2110 if (std::string(source->server) == Srv->GetServerName())
2112 std::deque<std::string> params;
2113 params.push_back(chan->name);
2114 params.push_back(user->nick);
2115 params.push_back(":"+reason);
2116 DoOneToMany(source->nick,"KICK",params);
2120 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2122 std::deque<std::string> params;
2123 params.push_back(dest->nick);
2124 params.push_back(":"+reason);
2125 DoOneToMany(source->nick,"KILL",params);
2128 virtual void OnRehash(std::string parameter)
2130 if (parameter != "")
2132 std::deque<std::string> params;
2133 params.push_back(parameter);
2134 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2136 if (Srv->MatchText(Srv->GetServerName(),parameter))
2138 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2139 Srv->RehashServer();
2142 ReadConfiguration(false);
2145 // note: the protocol does not allow direct umode +o except
2146 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2148 virtual void OnOper(userrec* user, std::string opertype)
2150 if (std::string(user->server) == Srv->GetServerName())
2152 std::deque<std::string> params;
2153 params.push_back(opertype);
2154 DoOneToMany(user->nick,"OPERTYPE",params);
2158 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2160 if (std::string(user->server) == Srv->GetServerName())
2162 if (target_type == TYPE_USER)
2164 userrec* u = (userrec*)dest;
2165 std::deque<std::string> params;
2166 params.push_back(u->nick);
2167 params.push_back(text);
2168 DoOneToMany(user->nick,"MODE",params);
2172 chanrec* c = (chanrec*)dest;
2173 std::deque<std::string> params;
2174 params.push_back(c->name);
2175 params.push_back(text);
2176 DoOneToMany(user->nick,"MODE",params);
2181 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2183 TreeSocket* s = (TreeSocket*)opaque;
2186 if (target_type == TYPE_USER)
2188 userrec* u = (userrec*)target;
2189 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2193 chanrec* c = (chanrec*)target;
2194 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2199 virtual ~ModuleSpanningTree()
2204 virtual Version GetVersion()
2206 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2211 class ModuleSpanningTreeFactory : public ModuleFactory
2214 ModuleSpanningTreeFactory()
2218 ~ModuleSpanningTreeFactory()
2222 virtual Module * CreateModule()
2224 TreeProtocolModule = new ModuleSpanningTree;
2225 return TreeProtocolModule;
2231 extern "C" void * init_module( void )
2233 return new ModuleSpanningTreeFactory;