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 log(DEBUG,"*** CREATE NEW SERVER %s ABOVE IS %s",Name.c_str(),Above->GetName().c_str());
115 // find the 'route' for this server (e.g. the one directly connected
116 // to the local server, which we can use to reach it)
118 if (Route != TreeRoot)
120 log(DEBUG,"(1) Route is %s",Route->GetName().c_str());
121 while (Route->GetParent() != TreeRoot)
123 Route = Route->GetParent();
124 log(DEBUG,"(2) Route is %s",Route->GetName().c_str());
128 log(DEBUG," ROUTE FOR %s is %s",Name.c_str(),Route->GetName().c_str());
131 TreeServer* GetRoute()
136 std::string GetName()
138 return this->ServerName;
141 std::string GetDesc()
143 return this->ServerDesc;
146 std::string GetVersion()
148 return this->VersionString;
151 void SetNextPingTime(time_t t)
154 LastPingWasGood = false;
157 time_t NextPingTime()
159 return this->NextPing;
162 bool AnsweredLastPing()
164 return LastPingWasGood;
169 LastPingWasGood = true;
174 return this->UserCount;
179 return this->OperCount;
182 TreeSocket* GetSocket()
187 TreeServer* GetParent()
192 void SetVersion(std::string Version)
194 VersionString = Version;
197 unsigned int ChildCount()
199 return Children.size();
202 TreeServer* GetChild(unsigned int n)
204 if (n < Children.size())
214 void AddChild(TreeServer* Child)
216 Children.push_back(Child);
219 bool DelChild(TreeServer* Child)
221 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
232 // removes child nodes of this node, and of that node, etc etc
235 bool stillchildren = true;
236 while (stillchildren)
238 stillchildren = false;
239 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
241 TreeServer* s = (TreeServer*)*a;
245 stillchildren = true;
259 std::string SendPass;
260 std::string RecvPass;
261 unsigned long AutoConnect;
262 time_t NextConnectTime;
265 /* $ModDesc: Povides a spanning tree server link protocol */
269 std::vector<Link> LinkBlocks;
271 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
273 if (Current->GetName() == ServerName)
274 return Current->GetRoute();
275 for (unsigned int q = 0; q < Current->ChildCount(); q++)
277 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
279 return found->GetRoute();
284 // Returns the locally connected server we must route a
285 // message through to reach server 'ServerName'. This
286 // only applies to one-to-one and not one-to-many routing.
287 TreeServer* BestRouteTo(std::string ServerName)
289 if (ServerName.c_str() == TreeRoot->GetName())
293 // first, find the server by recursively walking the tree
294 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
298 bool LookForServer(TreeServer* Current, std::string ServerName)
300 if (ServerName == Current->GetName())
302 for (unsigned int q = 0; q < Current->ChildCount(); q++)
304 if (LookForServer(Current->GetChild(q),ServerName))
312 void RFindServer(TreeServer* Current, std::string ServerName)
314 if ((ServerName == Current->GetName()) && (!Found))
321 for (unsigned int q = 0; q < Current->ChildCount(); q++)
324 RFindServer(Current->GetChild(q),ServerName);
330 void RFindServerMask(TreeServer* Current, std::string ServerName)
332 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
339 for (unsigned int q = 0; q < Current->ChildCount(); q++)
342 RFindServerMask(Current->GetChild(q),ServerName);
347 TreeServer* FindServer(std::string ServerName)
350 RFindServer(TreeRoot,ServerName);
354 TreeServer* FindServerMask(std::string ServerName)
357 RFindServerMask(TreeRoot,ServerName);
361 bool IsServer(std::string ServerName)
363 return LookForServer(TreeRoot,ServerName);
366 class TreeSocket : public InspSocket
369 std::string in_buffer;
370 ServerState LinkState;
371 std::string InboundServerName;
372 std::string InboundDescription;
374 int num_lost_servers;
376 bool LastPingWasGood;
380 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
381 : InspSocket(host, port, listening, maxtime)
384 this->LinkState = LISTENER;
387 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
388 : InspSocket(host, port, listening, maxtime)
391 this->LinkState = CONNECTING;
394 TreeSocket(int newfd, char* ip)
395 : InspSocket(newfd, ip)
397 this->LinkState = WAIT_AUTH_1;
400 virtual bool OnConnected()
402 if (this->LinkState == CONNECTING)
404 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
405 // we should send our details here.
406 // if the other side is satisfied, they send theirs.
407 // we do not need to change state here.
408 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
410 if (x->Name == this->myhost)
412 // found who we're supposed to be connecting to, send the neccessary gubbins.
413 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
421 virtual void OnError(InspSocketError e)
425 virtual int OnDisconnect()
430 // recursively send the server tree with distances as hops
431 void SendServers(TreeServer* Current, TreeServer* s, int hops)
434 for (unsigned int q = 0; q < Current->ChildCount(); q++)
436 TreeServer* recursive_server = Current->GetChild(q);
437 if (recursive_server != s)
439 // :source.server SERVER server.name hops :Description
440 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
441 this->WriteLine(command);
442 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
443 // down to next level
444 this->SendServers(recursive_server, s, hops+1);
449 void SquitServer(TreeServer* Current)
451 // recursively squit the servers attached to 'Current'
452 for (unsigned int q = 0; q < Current->ChildCount(); q++)
454 TreeServer* recursive_server = Current->GetChild(q);
455 this->SquitServer(recursive_server);
457 // Now we've whacked the kids, whack self
459 bool quittingpeople = true;
460 while (quittingpeople)
462 quittingpeople = false;
463 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
465 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
467 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
469 quittingpeople = true;
476 void Squit(TreeServer* Current,std::string reason)
480 std::deque<std::string> params;
481 params.push_back(Current->GetName());
482 params.push_back(":"+reason);
483 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
484 if (Current->GetParent() == TreeRoot)
486 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
490 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
492 num_lost_servers = 0;
494 SquitServer(Current);
496 Current->GetParent()->DelChild(Current);
498 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
502 log(DEFAULT,"Squit from unknown server");
506 bool ForceMode(std::string source, std::deque<std::string> params)
508 userrec* who = new userrec;
509 who->fd = FD_MAGIC_NUMBER;
510 if (params.size() < 2)
513 for (unsigned int q = 0; q < params.size(); q++)
515 modelist[q] = (char*)params[q].c_str();
517 Srv->SendMode(modelist,params.size(),who);
518 DoOneToAllButSender(source,"FMODE",params,source);
523 bool ForceTopic(std::string source, std::deque<std::string> params)
525 // FTOPIC %s %lu %s :%s
526 if (params.size() != 4)
528 std::string channel = params[0];
529 time_t ts = atoi(params[1].c_str());
530 std::string setby = params[2];
531 std::string topic = params[3];
533 chanrec* c = Srv->FindChannel(channel);
536 if ((ts >= c->topicset) || (!*c->topic))
538 std::string oldtopic = c->topic;
539 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
540 strlcpy(c->setby,setby.c_str(),NICKMAX);
542 // if the topic text is the same as the current topic,
543 // dont bother to send the TOPIC command out, just silently
544 // update the set time and set nick.
545 if (oldtopic != topic)
546 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
551 // all done, send it on its way
552 params[3] = ":" + params[3];
553 DoOneToAllButSender(source,"FTOPIC",params,source);
558 bool ForceJoin(std::string source, std::deque<std::string> params)
560 if (params.size() < 3)
564 char modestring[MAXBUF];
565 char* mode_users[127];
566 mode_users[0] = first;
567 mode_users[1] = modestring;
568 strcpy(mode_users[1],"+");
569 unsigned int modectr = 2;
572 std::string channel = params[0];
573 time_t TS = atoi(params[1].c_str());
576 chanrec* chan = Srv->FindChannel(channel);
581 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
583 // default is a high value, which if we dont have this
584 // channel will let the other side apply their modes.
585 time_t ourTS = time(NULL)+600;
586 chanrec* us = Srv->FindChannel(channel);
592 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
594 // do this first, so our mode reversals are correctly received by other servers
595 // if there is a TS collision.
596 DoOneToAllButSender(source,"FJOIN",params,source);
598 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
600 // process one channel at a time, applying modes.
601 char* usr = (char*)params[usernum].c_str();
602 char permissions = *usr;
607 mode_users[modectr++] = usr;
608 strlcat(modestring,"o",MAXBUF);
612 mode_users[modectr++] = usr;
613 strlcat(modestring,"h",MAXBUF);
617 mode_users[modectr++] = usr;
618 strlcat(modestring,"v",MAXBUF);
621 who = Srv->FindNick(usr);
624 Srv->JoinUserToChannel(who,channel,key);
625 if (modectr >= (MAXMODES-1))
627 // theres a mode for this user. push them onto the mode queue, and flush it
628 // if there are more than MAXMODES to go.
631 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
632 Srv->SendMode(mode_users,modectr,who);
636 log(DEBUG,"Their channel newer than ours, bouncing their modes");
638 std::deque<std::string> params;
639 // modes are now being UNSET...
640 *mode_users[1] = '-';
641 for (unsigned int x = 0; x < modectr; x++)
643 params.push_back(mode_users[x]);
645 // tell everyone to bounce the modes. bad modes, bad!
646 DoOneToMany(Srv->GetServerName(),"FMODE",params);
648 strcpy(mode_users[1],"+");
653 // there werent enough modes built up to flush it during FJOIN,
654 // or, there are a number left over. flush them out.
655 if ((modectr > 2) && (who))
659 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
660 Srv->SendMode(mode_users,modectr,who);
664 log(DEBUG,"Their channel newer than ours, bouncing their modes");
665 std::deque<std::string> params;
666 *mode_users[1] = '-';
667 for (unsigned int x = 0; x < modectr; x++)
669 params.push_back(mode_users[x]);
671 DoOneToMany(Srv->GetServerName(),"FMODE",params);
677 bool IntroduceClient(std::string source, std::deque<std::string> params)
679 if (params.size() < 8)
681 // NICK age nick host dhost ident +modes ip :gecos
683 std::string nick = params[1];
684 std::string host = params[2];
685 std::string dhost = params[3];
686 std::string ident = params[4];
687 time_t age = atoi(params[0].c_str());
688 std::string modes = params[5];
689 while (*(modes.c_str()) == '+')
691 char* m = (char*)modes.c_str();
695 std::string ip = params[6];
696 std::string gecos = params[7];
697 char* tempnick = (char*)nick.c_str();
698 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
700 user_hash::iterator iter;
701 iter = clientlist.find(tempnick);
702 if (iter != clientlist.end())
705 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);
706 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
710 clientlist[tempnick] = new userrec();
711 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
712 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
713 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
714 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
715 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
716 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
717 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
718 clientlist[tempnick]->registered = 7;
719 clientlist[tempnick]->signon = age;
720 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
721 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
722 for (int i = 0; i < MAXCHANS; i++)
724 clientlist[tempnick]->chans[i].channel = NULL;
725 clientlist[tempnick]->chans[i].uc_modes = 0;
727 params[7] = ":" + params[7];
728 DoOneToAllButSender(source,"NICK",params,source);
732 void SendFJoins(TreeServer* Current, chanrec* c)
735 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
736 std::vector<char*> *ulist = c->GetUsers();
737 for (unsigned int i = 0; i < ulist->size(); i++)
739 char* o = (*ulist)[i];
740 userrec* otheruser = (userrec*)o;
741 strlcat(list," ",MAXBUF);
742 strlcat(list,cmode(otheruser,c),MAXBUF);
743 strlcat(list,otheruser->nick,MAXBUF);
744 if (strlen(list)>(480-NICKMAX))
746 this->WriteLine(list);
747 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
750 if (list[strlen(list)-1] != ':')
752 this->WriteLine(list);
756 void SendChannelModes(TreeServer* Current)
759 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
761 SendFJoins(Current, c->second);
762 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
763 this->WriteLine(data);
764 if (*c->second->topic)
766 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);
767 this->WriteLine(data);
769 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
771 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
772 this->WriteLine(data);
774 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
778 // send all users and their channels
779 void SendUsers(TreeServer* Current)
782 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
784 if (u->second->registered == 7)
786 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);
787 this->WriteLine(data);
788 if (strchr(u->second->modes,'o'))
790 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
792 //char* chl = chlist(u->second,u->second);
795 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
797 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
802 void DoBurst(TreeServer* s)
804 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
805 this->WriteLine("BURST");
806 // send our version string
807 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
809 this->SendServers(TreeRoot,s,1);
810 // Send users and their channels
812 // Send everything else (channel modes etc)
813 this->SendChannelModes(s);
814 this->WriteLine("ENDBURST");
817 virtual bool OnDataReady()
819 char* data = this->Read();
822 this->in_buffer += data;
823 while (in_buffer.find("\n") != std::string::npos)
825 char* line = (char*)in_buffer.c_str();
826 std::string ret = "";
827 while ((*line != '\n') && (strlen(line)))
832 if ((*line == '\n') || (*line == '\r'))
835 if (!this->ProcessLine(ret))
841 return (data != NULL);
844 int WriteLine(std::string line)
846 return this->Write(line + "\r\n");
849 bool Error(std::deque<std::string> params)
851 if (params.size() < 1)
853 std::string Errmsg = params[0];
854 std::string SName = myhost;
855 if (InboundServerName != "")
857 SName = InboundServerName;
859 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
860 // we will return false to cause the socket to close.
864 bool OperType(std::string prefix, std::deque<std::string> params)
866 if (params.size() != 1)
868 std::string opertype = params[0];
869 userrec* u = Srv->FindNick(prefix);
872 strlcpy(u->oper,opertype.c_str(),NICKMAX);
873 if (!strchr(u->modes,'o'))
875 strcat(u->modes,"o");
877 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
882 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
884 if (params.size() < 1)
886 std::string servermask = params[0];
887 if (Srv->MatchText(Srv->GetServerName(),servermask))
889 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
891 ReadConfiguration(false);
893 DoOneToAllButSender(prefix,"REHASH",params,prefix);
897 bool RemoteKill(std::string prefix, std::deque<std::string> params)
899 if (params.size() != 2)
901 std::string nick = params[0];
902 std::string reason = params[1];
903 userrec* u = Srv->FindNick(prefix);
904 userrec* who = Srv->FindNick(nick);
907 std::string sourceserv = prefix;
910 sourceserv = u->server;
912 params[1] = ":" + params[1];
913 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
914 Srv->QuitUser(who,reason);
919 bool LocalPong(std::string prefix, std::deque<std::string> params)
921 if (params.size() < 1)
923 TreeServer* ServerSource = FindServer(prefix);
926 ServerSource->SetPingFlag();
931 bool ServerVersion(std::string prefix, std::deque<std::string> params)
933 if (params.size() < 1)
935 TreeServer* ServerSource = FindServer(prefix);
938 ServerSource->SetVersion(params[0]);
940 params[0] = ":" + params[0];
941 DoOneToAllButSender(prefix,"VERSION",params,prefix);
945 bool ChangeHost(std::string prefix, std::deque<std::string> params)
947 if (params.size() < 1)
949 userrec* u = Srv->FindNick(prefix);
952 Srv->ChangeHost(u,params[0]);
953 DoOneToAllButSender(prefix,"FHOST",params,u->server);
958 bool ChangeName(std::string prefix, std::deque<std::string> params)
960 if (params.size() < 1)
962 userrec* u = Srv->FindNick(prefix);
965 Srv->ChangeGECOS(u,params[0]);
966 params[0] = ":" + params[0];
967 DoOneToAllButSender(prefix,"FNAME",params,u->server);
972 bool LocalPing(std::string prefix, std::deque<std::string> params)
974 if (params.size() < 1)
976 std::string stufftobounce = params[0];
977 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
981 bool RemoteServer(std::string prefix, std::deque<std::string> params)
983 if (params.size() < 4)
985 std::string servername = params[0];
986 std::string password = params[1];
987 // hopcount is not used for a remote server, we calculate this ourselves
988 std::string description = params[3];
989 TreeServer* ParentOfThis = FindServer(prefix);
992 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
995 TreeServer* CheckDupe = FindServer(servername);
998 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1001 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1002 ParentOfThis->AddChild(Node);
1003 params[3] = ":" + params[3];
1004 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1005 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1009 bool Outbound_Reply_Server(std::deque<std::string> params)
1011 if (params.size() < 4)
1013 std::string servername = params[0];
1014 std::string password = params[1];
1015 int hops = atoi(params[2].c_str());
1018 this->WriteLine("ERROR :Server too far away for authentication");
1021 std::string description = params[3];
1022 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1024 if ((x->Name == servername) && (x->RecvPass == password))
1026 TreeServer* CheckDupe = FindServer(servername);
1029 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1032 // Begin the sync here. this kickstarts the
1033 // other side, waiting in WAIT_AUTH_2 state,
1034 // into starting their burst, as it shows
1035 // that we're happy.
1036 this->LinkState = CONNECTED;
1037 // we should add the details of this server now
1038 // to the servers tree, as a child of the root
1040 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1041 TreeRoot->AddChild(Node);
1042 params[3] = ":" + params[3];
1043 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1044 this->DoBurst(Node);
1048 this->WriteLine("ERROR :Invalid credentials");
1052 bool Inbound_Server(std::deque<std::string> params)
1054 if (params.size() < 4)
1056 std::string servername = params[0];
1057 std::string password = params[1];
1058 int hops = atoi(params[2].c_str());
1061 this->WriteLine("ERROR :Server too far away for authentication");
1064 std::string description = params[3];
1065 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1067 if ((x->Name == servername) && (x->RecvPass == password))
1069 TreeServer* CheckDupe = FindServer(servername);
1072 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1075 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1076 this->InboundServerName = servername;
1077 this->InboundDescription = description;
1078 // this is good. Send our details: Our server name and description and hopcount of 0,
1079 // along with the sendpass from this block.
1080 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1081 // move to the next state, we are now waiting for THEM.
1082 this->LinkState = WAIT_AUTH_2;
1086 this->WriteLine("ERROR :Invalid credentials");
1090 std::deque<std::string> Split(std::string line, bool stripcolon)
1092 std::deque<std::string> n;
1093 if (!strchr(line.c_str(),' '))
1098 std::stringstream s(line);
1099 std::string param = "";
1118 if ((param == ":") && (item > 0))
1141 bool ProcessLine(std::string line)
1143 char* l = (char*)line.c_str();
1144 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1145 l[strlen(l)-1] = '\0';
1149 Srv->Log(DEBUG,"IN: '"+line+"'");
1150 std::deque<std::string> params = this->Split(line,true);
1151 std::string command = "";
1152 std::string prefix = "";
1153 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1156 command = params[1];
1157 char* pref = (char*)prefix.c_str();
1165 command = params[0];
1169 switch (this->LinkState)
1174 // Waiting for SERVER command from remote server. Server initiating
1175 // the connection sends the first SERVER command, listening server
1176 // replies with theirs if its happy, then if the initiator is happy,
1177 // it starts to send its net sync, which starts the merge, otherwise
1178 // it sends an ERROR.
1179 if (command == "SERVER")
1181 return this->Inbound_Server(params);
1183 else if (command == "ERROR")
1185 return this->Error(params);
1189 // Waiting for start of other side's netmerge to say they liked our
1191 if (command == "SERVER")
1193 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1197 else if (command == "BURST")
1199 this->LinkState = CONNECTED;
1200 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1201 TreeRoot->AddChild(Node);
1203 params.push_back(InboundServerName);
1204 params.push_back("*");
1205 params.push_back("1");
1206 params.push_back(":"+InboundDescription);
1207 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1208 this->DoBurst(Node);
1210 else if (command == "ERROR")
1212 return this->Error(params);
1217 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1221 if (command == "SERVER")
1223 // another server we connected to, which was in WAIT_AUTH_1 state,
1224 // has just sent us their credentials. If we get this far, theyre
1225 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1226 // if we're happy with this, we should send our netburst which
1227 // kickstarts the merge.
1228 return this->Outbound_Reply_Server(params);
1230 else if (command == "ERROR")
1232 return this->Error(params);
1236 // This is the 'authenticated' state, when all passwords
1237 // have been exchanged and anything past this point is taken
1239 std::string target = "";
1240 if ((command == "NICK") && (params.size() > 1))
1242 return this->IntroduceClient(prefix,params);
1244 else if (command == "FJOIN")
1246 return this->ForceJoin(prefix,params);
1248 else if (command == "SERVER")
1250 return this->RemoteServer(prefix,params);
1252 else if (command == "ERROR")
1254 return this->Error(params);
1256 else if (command == "OPERTYPE")
1258 return this->OperType(prefix,params);
1260 else if (command == "FMODE")
1262 return this->ForceMode(prefix,params);
1264 else if (command == "KILL")
1266 return this->RemoteKill(prefix,params);
1268 else if (command == "FTOPIC")
1270 return this->ForceTopic(prefix,params);
1272 else if (command == "REHASH")
1274 return this->RemoteRehash(prefix,params);
1276 else if (command == "PING")
1278 return this->LocalPing(prefix,params);
1280 else if (command == "PONG")
1282 return this->LocalPong(prefix,params);
1284 else if (command == "VERSION")
1286 return this->ServerVersion(prefix,params);
1288 else if (command == "FHOST")
1290 return this->ChangeHost(prefix,params);
1292 else if (command == "FNAME")
1294 return this->ChangeName(prefix,params);
1296 else if (command == "SQUIT")
1298 if (params.size() == 2)
1300 this->Squit(FindServer(params[0]),params[1]);
1306 // not a special inter-server command.
1307 // Emulate the actual user doing the command,
1308 // this saves us having a huge ugly parser.
1309 userrec* who = Srv->FindNick(prefix);
1310 std::string sourceserv = this->myhost;
1311 if (this->InboundServerName != "")
1313 sourceserv = this->InboundServerName;
1318 target = who->server;
1319 char* strparams[127];
1320 for (unsigned int q = 0; q < params.size(); q++)
1322 strparams[q] = (char*)params[q].c_str();
1324 Srv->CallCommandHandler(command, strparams, params.size(), who);
1328 // its not a user. Its either a server, or somethings screwed up.
1329 if (IsServer(prefix))
1331 target = Srv->GetServerName();
1335 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1339 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1348 virtual std::string GetName()
1350 std::string sourceserv = this->myhost;
1351 if (this->InboundServerName != "")
1353 sourceserv = this->InboundServerName;
1358 virtual void OnTimeout()
1360 if (this->LinkState == CONNECTING)
1362 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1366 virtual void OnClose()
1368 // Connection closed.
1369 // If the connection is fully up (state CONNECTED)
1370 // then propogate a netsplit to all peers.
1371 std::string quitserver = this->myhost;
1372 if (this->InboundServerName != "")
1374 quitserver = this->InboundServerName;
1376 TreeServer* s = FindServer(quitserver);
1379 Squit(s,"Remote host closed the connection");
1383 virtual int OnIncomingConnection(int newsock, char* ip)
1385 TreeSocket* s = new TreeSocket(newsock, ip);
1391 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1393 for (unsigned int c = 0; c < list.size(); c++)
1395 if (list[c] == server)
1400 list.push_back(server);
1403 // returns a list of DIRECT servernames for a specific channel
1404 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1406 std::deque<TreeServer*> list;
1407 std::vector<char*> *ulist = c->GetUsers();
1408 for (unsigned int i = 0; i < ulist->size(); i++)
1410 char* o = (*ulist)[i];
1411 userrec* otheruser = (userrec*)o;
1412 if (std::string(otheruser->server) != Srv->GetServerName())
1414 TreeServer* best = BestRouteTo(otheruser->server);
1416 AddThisServer(best,list);
1422 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1424 TreeServer* omitroute = BestRouteTo(omit);
1425 if ((command == "NOTICE") || (command == "PRIVMSG"))
1427 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1429 if (*(params[0].c_str()) != '#')
1431 // special routing for private messages/notices
1432 userrec* d = Srv->FindNick(params[0]);
1435 std::deque<std::string> par;
1437 par.push_back(params[0]);
1438 par.push_back(":"+params[1]);
1439 DoOneToOne(prefix,command,par,d->server);
1445 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1446 chanrec* c = Srv->FindChannel(params[0]);
1449 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1450 log(DEBUG,"Got a list of %d servers",list.size());
1451 for (unsigned int i = 0; i < list.size(); i++)
1453 TreeSocket* Sock = list[i]->GetSocket();
1454 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1456 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1457 Sock->WriteLine(data);
1465 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1467 TreeServer* Route = TreeRoot->GetChild(x);
1468 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1470 TreeSocket* Sock = Route->GetSocket();
1471 Sock->WriteLine(data);
1477 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1479 TreeServer* omitroute = BestRouteTo(omit);
1480 std::string FullLine = ":" + prefix + " " + command;
1481 for (unsigned int x = 0; x < params.size(); x++)
1483 FullLine = FullLine + " " + params[x];
1485 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1487 TreeServer* Route = TreeRoot->GetChild(x);
1488 // Send the line IF:
1489 // The route has a socket (its a direct connection)
1490 // The route isnt the one to be omitted
1491 // The route isnt the path to the one to be omitted
1492 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1494 TreeSocket* Sock = Route->GetSocket();
1495 Sock->WriteLine(FullLine);
1501 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1503 std::string FullLine = ":" + prefix + " " + command;
1504 for (unsigned int x = 0; x < params.size(); x++)
1506 FullLine = FullLine + " " + params[x];
1508 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1510 TreeServer* Route = TreeRoot->GetChild(x);
1511 if (Route->GetSocket())
1513 TreeSocket* Sock = Route->GetSocket();
1514 Sock->WriteLine(FullLine);
1520 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1522 TreeServer* Route = BestRouteTo(target);
1525 std::string FullLine = ":" + prefix + " " + command;
1526 for (unsigned int x = 0; x < params.size(); x++)
1528 FullLine = FullLine + " " + params[x];
1530 if (Route->GetSocket())
1532 TreeSocket* Sock = Route->GetSocket();
1533 Sock->WriteLine(FullLine);
1543 std::vector<TreeSocket*> Bindings;
1545 void ReadConfiguration(bool rebind)
1549 for (int j =0; j < Conf->Enumerate("bind"); j++)
1551 std::string Type = Conf->ReadValue("bind","type",j);
1552 std::string IP = Conf->ReadValue("bind","address",j);
1553 long Port = Conf->ReadInteger("bind","port",j,true);
1554 if (Type == "servers")
1560 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1561 if (listener->GetState() == I_LISTENING)
1563 Srv->AddSocket(listener);
1564 Bindings.push_back(listener);
1568 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1576 for (int j =0; j < Conf->Enumerate("link"); j++)
1579 L.Name = Conf->ReadValue("link","name",j);
1580 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1581 L.Port = Conf->ReadInteger("link","port",j,true);
1582 L.SendPass = Conf->ReadValue("link","sendpass",j);
1583 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1584 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1585 L.NextConnectTime = time(NULL) + L.AutoConnect;
1586 LinkBlocks.push_back(L);
1587 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1592 class ModuleSpanningTree : public Module
1594 std::vector<TreeSocket*> Bindings;
1600 ModuleSpanningTree()
1603 Conf = new ConfigReader;
1606 // Create the root of the tree
1607 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1609 ReadConfiguration(true);
1612 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1614 std::string Parent = TreeRoot->GetName();
1615 if (Current->GetParent())
1617 Parent = Current->GetParent()->GetName();
1619 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1621 ShowLinks(Current->GetChild(q),user,hops+1);
1623 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1626 int CountLocalServs()
1628 return TreeRoot->ChildCount();
1631 void CountServsRecursive(TreeServer* Current)
1634 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1636 CountServsRecursive(Current->GetChild(q));
1643 CountServsRecursive(TreeRoot);
1647 void HandleLinks(char** parameters, int pcnt, userrec* user)
1649 ShowLinks(TreeRoot,user,0);
1650 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1654 void HandleLusers(char** parameters, int pcnt, userrec* user)
1656 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1657 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1658 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1659 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1660 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1664 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1666 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1670 for (int t = 0; t < depth; t++)
1672 matrix[line][t] = ' ';
1674 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1676 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1678 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1683 // Ok, prepare to be confused.
1684 // After much mulling over how to approach this, it struck me that
1685 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1686 // keeping track of a ton of ascii characters, and line by line
1687 // under recursion working out where to place them using multiplications
1688 // and divisons, we instead render the map onto a backplane of characters
1689 // (a character matrix), then draw the branches as a series of "L" shapes
1690 // from the nodes. This is not only friendlier on CPU it uses less stack.
1692 void HandleMap(char** parameters, int pcnt, userrec* user)
1694 // This array represents a virtual screen which we will
1695 // "scratch" draw to, as the console device of an irc
1696 // client does not provide for a proper terminal.
1697 char matrix[128][80];
1698 for (unsigned int t = 0; t < 128; t++)
1700 matrix[t][0] = '\0';
1703 // The only recursive bit is called here.
1704 ShowMap(TreeRoot,user,0,matrix);
1705 // Process each line one by one. The algorithm has a limit of
1706 // 128 servers (which is far more than a spanning tree should have
1707 // anyway, so we're ok). This limit can be raised simply by making
1708 // the character matrix deeper, 128 rows taking 10k of memory.
1709 for (int l = 1; l < line; l++)
1711 // scan across the line looking for the start of the
1712 // servername (the recursive part of the algorithm has placed
1713 // the servers at indented positions depending on what they
1715 int first_nonspace = 0;
1716 while (matrix[l][first_nonspace] == ' ')
1721 // Draw the `- (corner) section: this may be overwritten by
1722 // another L shape passing along the same vertical pane, becoming
1723 // a |- (branch) section instead.
1724 matrix[l][first_nonspace] = '-';
1725 matrix[l][first_nonspace-1] = '`';
1727 // Draw upwards until we hit the parent server, causing possibly
1728 // other corners (`-) to become branches (|-)
1729 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1731 matrix[l2][first_nonspace-1] = '|';
1735 // dump the whole lot to the user. This is the easy bit, honest.
1736 for (int t = 0; t < line; t++)
1738 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1740 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1744 int HandleSquit(char** parameters, int pcnt, userrec* user)
1746 TreeServer* s = FindServerMask(parameters[0]);
1749 TreeSocket* sock = s->GetSocket();
1752 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1753 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1758 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1763 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1768 void DoPingChecks(time_t curtime)
1770 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1772 TreeServer* serv = TreeRoot->GetChild(j);
1773 TreeSocket* sock = serv->GetSocket();
1776 if (curtime >= serv->NextPingTime())
1778 if (serv->AnsweredLastPing())
1780 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1781 serv->SetNextPingTime(curtime + 60);
1785 // they didnt answer, boot them
1786 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1787 sock->Squit(serv,"Ping timeout");
1796 void AutoConnectServers(time_t curtime)
1798 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1800 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1802 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1803 x->NextConnectTime = curtime + x->AutoConnect;
1804 TreeServer* CheckDupe = FindServer(x->Name);
1807 // an autoconnected server is not connected. Check if its time to connect it
1808 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1809 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1810 Srv->AddSocket(newsocket);
1816 int HandleVersion(char** parameters, int pcnt, userrec* user)
1818 // we've already checked if pcnt > 0, so this is safe
1819 TreeServer* found = FindServerMask(parameters[0]);
1822 std::string Version = found->GetVersion();
1823 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1827 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1832 int HandleConnect(char** parameters, int pcnt, userrec* user)
1834 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1836 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1838 TreeServer* CheckDupe = FindServer(x->Name);
1841 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);
1842 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1843 Srv->AddSocket(newsocket);
1848 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());
1853 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1857 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1859 if (command == "CONNECT")
1861 return this->HandleConnect(parameters,pcnt,user);
1863 else if (command == "SQUIT")
1865 return this->HandleSquit(parameters,pcnt,user);
1867 else if (command == "MAP")
1869 this->HandleMap(parameters,pcnt,user);
1872 else if (command == "LUSERS")
1874 this->HandleLusers(parameters,pcnt,user);
1877 else if (command == "LINKS")
1879 this->HandleLinks(parameters,pcnt,user);
1882 else if ((command == "VERSION") && (pcnt > 0))
1884 this->HandleVersion(parameters,pcnt,user);
1887 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1889 // this bit of code cleverly routes all module commands
1890 // to all remote severs *automatically* so that modules
1891 // can just handle commands locally, without having
1892 // to have any special provision in place for remote
1893 // commands and linking protocols.
1894 std::deque<std::string> params;
1896 for (int j = 0; j < pcnt; j++)
1898 if (strchr(parameters[j],' '))
1900 params.push_back(":" + std::string(parameters[j]));
1904 params.push_back(std::string(parameters[j]));
1907 DoOneToMany(user->nick,command,params);
1912 virtual void OnGetServerDescription(std::string servername,std::string &description)
1914 TreeServer* s = FindServer(servername);
1917 description = s->GetDesc();
1921 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1923 if (std::string(source->server) == Srv->GetServerName())
1925 std::deque<std::string> params;
1926 params.push_back(dest->nick);
1927 params.push_back(channel->name);
1928 DoOneToMany(source->nick,"INVITE",params);
1932 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1934 std::deque<std::string> params;
1935 params.push_back(chan->name);
1936 params.push_back(":"+topic);
1937 DoOneToMany(user->nick,"TOPIC",params);
1940 virtual void OnWallops(userrec* user, std::string text)
1942 if (std::string(user->server) == Srv->GetServerName())
1944 std::deque<std::string> params;
1945 params.push_back(":"+text);
1946 DoOneToMany(user->nick,"WALLOPS",params);
1950 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1952 if (target_type == TYPE_USER)
1954 userrec* d = (userrec*)dest;
1955 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1957 std::deque<std::string> params;
1959 params.push_back(d->nick);
1960 params.push_back(":"+text);
1961 DoOneToOne(user->nick,"NOTICE",params,d->server);
1966 if (std::string(user->server) == Srv->GetServerName())
1968 chanrec *c = (chanrec*)dest;
1969 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1970 for (unsigned int i = 0; i < list.size(); i++)
1972 TreeSocket* Sock = list[i]->GetSocket();
1974 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1980 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1982 if (target_type == TYPE_USER)
1984 // route private messages which are targetted at clients only to the server
1985 // which needs to receive them
1986 userrec* d = (userrec*)dest;
1987 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1989 std::deque<std::string> params;
1991 params.push_back(d->nick);
1992 params.push_back(":"+text);
1993 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1998 if (std::string(user->server) == Srv->GetServerName())
2000 chanrec *c = (chanrec*)dest;
2001 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
2002 for (unsigned int i = 0; i < list.size(); i++)
2004 TreeSocket* Sock = list[i]->GetSocket();
2006 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2012 virtual void OnBackgroundTimer(time_t curtime)
2014 AutoConnectServers(curtime);
2015 DoPingChecks(curtime);
2018 virtual void OnUserJoin(userrec* user, chanrec* channel)
2020 // Only do this for local users
2021 if (std::string(user->server) == Srv->GetServerName())
2023 std::deque<std::string> params;
2025 params.push_back(channel->name);
2028 // if the channel has a key, force the join by emulating the key.
2029 params.push_back(channel->key);
2031 if (channel->GetUserCounter() > 1)
2033 // not the first in the channel
2034 DoOneToMany(user->nick,"JOIN",params);
2038 // first in the channel, set up their permissions
2039 // and the channel TS with FJOIN.
2041 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2043 params.push_back(channel->name);
2044 params.push_back(ts);
2045 params.push_back("@"+std::string(user->nick));
2046 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2051 virtual void OnChangeHost(userrec* user, std::string newhost)
2053 // only occurs for local clients
2054 std::deque<std::string> params;
2055 params.push_back(newhost);
2056 DoOneToMany(user->nick,"FHOST",params);
2059 virtual void OnChangeName(userrec* user, std::string gecos)
2061 // only occurs for local clients
2062 std::deque<std::string> params;
2063 params.push_back(gecos);
2064 DoOneToMany(user->nick,"FNAME",params);
2067 virtual void OnUserPart(userrec* user, chanrec* channel)
2069 if (std::string(user->server) == Srv->GetServerName())
2071 std::deque<std::string> params;
2073 params.push_back(channel->name);
2074 DoOneToMany(user->nick,"PART",params);
2078 virtual void OnUserConnect(userrec* user)
2080 char agestr[MAXBUF];
2081 if (std::string(user->server) == Srv->GetServerName())
2083 std::deque<std::string> params;
2084 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2086 params.push_back(agestr);
2087 params.push_back(user->nick);
2088 params.push_back(user->host);
2089 params.push_back(user->dhost);
2090 params.push_back(user->ident);
2091 params.push_back("+"+std::string(user->modes));
2092 params.push_back(user->ip);
2093 params.push_back(":"+std::string(user->fullname));
2094 DoOneToMany(Srv->GetServerName(),"NICK",params);
2098 virtual void OnUserQuit(userrec* user, std::string reason)
2100 if (std::string(user->server) == Srv->GetServerName())
2102 std::deque<std::string> params;
2103 params.push_back(":"+reason);
2104 DoOneToMany(user->nick,"QUIT",params);
2108 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2110 if (std::string(user->server) == Srv->GetServerName())
2112 std::deque<std::string> params;
2113 params.push_back(user->nick);
2114 DoOneToMany(oldnick,"NICK",params);
2118 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2120 if (std::string(source->server) == Srv->GetServerName())
2122 std::deque<std::string> params;
2123 params.push_back(chan->name);
2124 params.push_back(user->nick);
2125 params.push_back(":"+reason);
2126 DoOneToMany(source->nick,"KICK",params);
2130 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2132 std::deque<std::string> params;
2133 params.push_back(dest->nick);
2134 params.push_back(":"+reason);
2135 DoOneToMany(source->nick,"KILL",params);
2138 virtual void OnRehash(std::string parameter)
2140 if (parameter != "")
2142 std::deque<std::string> params;
2143 params.push_back(parameter);
2144 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2146 if (Srv->MatchText(Srv->GetServerName(),parameter))
2148 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2149 Srv->RehashServer();
2152 ReadConfiguration(false);
2155 // note: the protocol does not allow direct umode +o except
2156 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2158 virtual void OnOper(userrec* user, std::string opertype)
2160 if (std::string(user->server) == Srv->GetServerName())
2162 std::deque<std::string> params;
2163 params.push_back(opertype);
2164 DoOneToMany(user->nick,"OPERTYPE",params);
2168 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2170 if (std::string(user->server) == Srv->GetServerName())
2172 if (target_type == TYPE_USER)
2174 userrec* u = (userrec*)dest;
2175 std::deque<std::string> params;
2176 params.push_back(u->nick);
2177 params.push_back(text);
2178 DoOneToMany(user->nick,"MODE",params);
2182 chanrec* c = (chanrec*)dest;
2183 std::deque<std::string> params;
2184 params.push_back(c->name);
2185 params.push_back(text);
2186 DoOneToMany(user->nick,"MODE",params);
2191 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2193 TreeSocket* s = (TreeSocket*)opaque;
2196 if (target_type == TYPE_USER)
2198 userrec* u = (userrec*)target;
2199 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2203 chanrec* c = (chanrec*)target;
2204 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2209 virtual ~ModuleSpanningTree()
2214 virtual Version GetVersion()
2216 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2221 class ModuleSpanningTreeFactory : public ModuleFactory
2224 ModuleSpanningTreeFactory()
2228 ~ModuleSpanningTreeFactory()
2232 virtual Module * CreateModule()
2234 TreeProtocolModule = new ModuleSpanningTree;
2235 return TreeProtocolModule;
2241 extern "C" void * init_module( void )
2243 return new ModuleSpanningTreeFactory;